Repository: douzhongqiang/EasyCanvas Branch: master Commit: 84aad331afad Files: 528 Total size: 2.3 MB Directory structure: gitextract_u8hxl36n/ ├── AudioVideoCore/ │ ├── AudioData.cpp │ ├── AudioData.h │ ├── AudioDecodec.cpp │ ├── AudioDecodec.h │ ├── AudioPlayer.cpp │ ├── AudioPlayer.h │ ├── AudioPlayerThread.cpp │ ├── AudioPlayerThread.h │ ├── AudioVideoCore.pro │ └── audiovideocore_global.h ├── CustomControls/ │ ├── CustomCombineControl/ │ │ ├── UICustomColorControl.cpp │ │ ├── UICustomColorControl.h │ │ ├── UICustomCombineControlBase.cpp │ │ ├── UICustomCombineControlBase.h │ │ ├── UICustomComboBoxControl.cpp │ │ ├── UICustomComboBoxControl.h │ │ ├── UICustomDateEditControl.cpp │ │ ├── UICustomDateEditControl.h │ │ ├── UICustomDoubleControl.cpp │ │ ├── UICustomDoubleControl.h │ │ ├── UICustomFontComboBoxControl.cpp │ │ ├── UICustomFontComboBoxControl.h │ │ ├── UICustomGroupControl.cpp │ │ ├── UICustomGroupControl.h │ │ ├── UICustomIntControl.cpp │ │ ├── UICustomIntControl.h │ │ ├── UICustomLineEditControl.cpp │ │ ├── UICustomLineEditControl.h │ │ ├── UICustomOrientationControl.cpp │ │ ├── UICustomOrientationControl.h │ │ ├── UICustomPostionControl.cpp │ │ ├── UICustomPostionControl.h │ │ ├── UICustomSwitchControl.cpp │ │ ├── UICustomSwitchControl.h │ │ ├── UICustomTextEditTagControl.cpp │ │ ├── UICustomTextEditTagControl.h │ │ ├── UICustomTimeEditControl.cpp │ │ └── UICustomTimeEditControl.h │ ├── CustomControls.pro │ ├── UICurtomLeftBarControl/ │ │ ├── UICustomLefTabsControl.h │ │ ├── UICustomLeftItemWidget.cpp │ │ ├── UICustomLeftItemWidget.h │ │ ├── UICustomLeftTabsControl.cpp │ │ ├── UICustomLeftWidget.cpp │ │ └── UICustomLeftWidget.h │ ├── UICustomColorControl/ │ │ ├── UICustomColorCircle.cpp │ │ ├── UICustomColorCircle.h │ │ ├── UICustomColorSlider.cpp │ │ ├── UICustomColorSlider.h │ │ ├── UICustomColorSliderItem.cpp │ │ ├── UICustomColorSliderItem.h │ │ ├── UICustomColorWidget.cpp │ │ ├── UICustomColorWidget.h │ │ ├── UICustomCustomColorOperator.cpp │ │ ├── UICustomCustomColorOperator.h │ │ ├── UICustonColorDialog.cpp │ │ └── UICustonColorDialog.h │ ├── UICustomSingleControl/ │ │ ├── UICustomCalendarWidget.cpp │ │ ├── UICustomCalendarWidget.h │ │ ├── UICustomColorViewWidget.cpp │ │ ├── UICustomColorViewWidget.h │ │ ├── UICustomComboBox.cpp │ │ ├── UICustomComboBox.h │ │ ├── UICustomDateEdit.cpp │ │ ├── UICustomDateEdit.h │ │ ├── UICustomDoubleSpinBox.cpp │ │ ├── UICustomDoubleSpinBox.h │ │ ├── UICustomImageViewer.cpp │ │ ├── UICustomImageViewer.h │ │ ├── UICustomIntSpinBox.cpp │ │ ├── UICustomIntSpinBox.h │ │ ├── UICustomLineEdit.cpp │ │ ├── UICustomLineEdit.h │ │ ├── UICustomPostionWidget.cpp │ │ ├── UICustomPostionWidget.h │ │ ├── UICustomSwitchWidget.cpp │ │ ├── UICustomSwitchWidget.h │ │ ├── UICustomTextEdit.cpp │ │ ├── UICustomTextEdit.h │ │ ├── UICustomTimeEdit.cpp │ │ └── UICustomTimeEdit.h │ └── customcontrols_global.h ├── CustomWidgets/ │ ├── CustomWidgets.pro │ ├── UICustomCore/ │ │ ├── CustomStyleConfig.cpp │ │ └── CustomStyleConfig.h │ ├── UICustomWidgtes/ │ │ ├── CustomDialog.cpp │ │ ├── CustomDialog.h │ │ ├── CustomMainWindow.cpp │ │ ├── CustomMainWindow.h │ │ ├── CustomTestWidget.cpp │ │ ├── CustomTestWidget.h │ │ ├── CustomWidget.cpp │ │ └── CustomWidget.h │ ├── customwidgets_global.h │ ├── qss/ │ │ └── light.css │ └── qss.qrc ├── EasyCanvas/ │ ├── EasyCanvas.pro │ ├── GlobalHotKey/ │ │ ├── GlobalHotKeyFilter.cpp │ │ ├── GlobalHotKeyFilter.h │ │ ├── GlobalHotKeyInfo.cpp │ │ ├── GlobalHotKeyInfo.h │ │ ├── GlobalHotKeyManager.cpp │ │ └── GlobalHotKeyManager.h │ ├── UICore/ │ │ ├── MainWindow.cpp │ │ ├── MainWindow.h │ │ ├── UIAboutMeDialog.cpp │ │ ├── UIAboutMeDialog.h │ │ ├── UIAttributWidget.cpp │ │ └── UIAttributWidget.h │ └── main.cpp ├── EasyCanvas.pro ├── EasyCanvasCore/ │ ├── EasyCanvasCore.pro │ ├── Scheme/ │ │ ├── CanvasSchemeManager.cpp │ │ ├── CanvasSchemeManager.h │ │ ├── SQLCore.cpp │ │ ├── SQLCore.h │ │ ├── SchemeDataInfo.h │ │ ├── UISchemeManagerDialog.cpp │ │ ├── UISchemeManagerDialog.h │ │ ├── UISchemeManagerWidget.cpp │ │ └── UISchemeManagerWidget.h │ ├── UICanvas/ │ │ ├── UICanvasAudioItem.cpp │ │ ├── UICanvasAudioItem.h │ │ ├── UICanvasEllipseItem.cpp │ │ ├── UICanvasEllipseItem.h │ │ ├── UICanvasImageItem.cpp │ │ ├── UICanvasImageItem.h │ │ ├── UICanvasItemBase.cpp │ │ ├── UICanvasItemBase.h │ │ ├── UICanvasItemManager.cpp │ │ ├── UICanvasItemManager.h │ │ ├── UICanvasOperators.cpp │ │ ├── UICanvasOperators.h │ │ ├── UICanvasPathItem.cpp │ │ ├── UICanvasPathItem.h │ │ ├── UICanvasRectItem.cpp │ │ ├── UICanvasRectItem.h │ │ ├── UICanvasScene.cpp │ │ ├── UICanvasScene.h │ │ ├── UICanvasTextItem.cpp │ │ ├── UICanvasTextItem.h │ │ ├── UICanvasView.cpp │ │ └── UICanvasView.h │ ├── UINodeTree/ │ │ ├── UINodeItem.cpp │ │ ├── UINodeItem.h │ │ ├── UINodeSortFilterProxyModel.cpp │ │ ├── UINodeSortFilterProxyModel.h │ │ ├── UINodeTreeDelegate.cpp │ │ ├── UINodeTreeDelegate.h │ │ ├── UINodeTreeView.cpp │ │ ├── UINodeTreeView.h │ │ ├── UINodeTreeViewModel.cpp │ │ ├── UINodeTreeViewModel.h │ │ ├── UINodeTreeWidget.cpp │ │ └── UINodeTreeWidget.h │ ├── UndoCmd/ │ │ ├── ItemAttributeChangedCmd.cpp │ │ ├── ItemAttributeChangedCmd.h │ │ ├── ItemChangeNameCmd.cpp │ │ ├── ItemChangeNameCmd.h │ │ ├── ItemCreateCmd.cpp │ │ ├── ItemCreateCmd.h │ │ ├── ItemDeleteCmd.cpp │ │ ├── ItemDeleteCmd.h │ │ ├── ItemPasteCmd.cpp │ │ ├── ItemPasteCmd.h │ │ ├── UndoCmdCore.cpp │ │ └── UndoCmdCore.h │ └── easycanvascore_global.h ├── EasyCanvas_zh_CH.ts ├── NDNodeAttribute/ │ ├── NDAttributeBase.cpp │ ├── NDAttributeBase.h │ ├── NDAttributeData.cpp │ ├── NDAttributeData.h │ ├── NDAttributeGroup.cpp │ ├── NDAttributeGroup.h │ ├── NDBoolAttribute.cpp │ ├── NDBoolAttribute.h │ ├── NDColorAttribute.cpp │ ├── NDColorAttribute.h │ ├── NDIntAttribute.cpp │ ├── NDIntAttribute.h │ ├── NDNodeAttribute.pro │ ├── NDNodeBase.cpp │ ├── NDNodeBase.h │ ├── NDNodeManager.cpp │ ├── NDNodeManager.h │ ├── NDPostionAttribute.cpp │ ├── NDPostionAttribute.h │ ├── NDRealAttribute.cpp │ ├── NDRealAttribute.h │ ├── NDStringAttribute.cpp │ ├── NDStringAttribute.h │ ├── NDTextNode.cpp │ ├── NDTextNode.h │ └── ndnodeattribute_global.h ├── NodeAttributeControl/ │ ├── NodeAttributeControl.pro │ ├── UIAttrBoolControl.cpp │ ├── UIAttrBoolControl.h │ ├── UIAttrColorControl.cpp │ ├── UIAttrColorControl.h │ ├── UIAttrFloatControl.cpp │ ├── UIAttrFloatControl.h │ ├── UIAttrIntControl.cpp │ ├── UIAttrIntControl.h │ ├── UIAttrTextControl.cpp │ ├── UIAttrTextControl.h │ ├── UINodeAttrControl.cpp │ ├── UINodeAttrControl.h │ └── nodeattributecontrol_global.h ├── PythonWrap/ │ ├── PythonWrap.pro │ ├── PythonWrapCore.cpp │ ├── PythonWrapCore.h │ ├── pythonwrap.cpp │ ├── pythonwrap.h │ └── pythonwrap_global.h ├── Utils/ │ ├── RALLBlockSignal.cpp │ ├── RALLBlockSignal.h │ ├── Utils.cpp │ ├── Utils.h │ ├── Utils.pro │ └── utils_global.h ├── bin/ │ ├── CustomColor.xml │ └── Script/ │ └── SetColorAlphaScript.py ├── readme.md └── thirdLibs/ ├── PythonQt/ │ ├── include/ │ │ ├── PythonQt.h │ │ ├── PythonQtBoolResult.h │ │ ├── PythonQtClassInfo.h │ │ ├── PythonQtClassWrapper.h │ │ ├── PythonQtConversion.h │ │ ├── PythonQtCppWrapperFactory.h │ │ ├── PythonQtDoc.h │ │ ├── PythonQtImportFileInterface.h │ │ ├── PythonQtImporter.h │ │ ├── PythonQtInstanceWrapper.h │ │ ├── PythonQtMethodInfo.h │ │ ├── PythonQtMisc.h │ │ ├── PythonQtObjectPtr.h │ │ ├── PythonQtProperty.h │ │ ├── PythonQtPythonInclude.h │ │ ├── PythonQtQFileImporter.h │ │ ├── PythonQtSignal.h │ │ ├── PythonQtSignalReceiver.h │ │ ├── PythonQtSlot.h │ │ ├── PythonQtSlotDecorator.h │ │ ├── PythonQtStdDecorators.h │ │ ├── PythonQtStdIn.h │ │ ├── PythonQtStdOut.h │ │ ├── PythonQtSystem.h │ │ ├── PythonQtThreadSupport.h │ │ ├── PythonQtUtils.h │ │ ├── PythonQtVariants.h │ │ ├── PythonQt_QtAll.h │ │ └── gui/ │ │ └── PythonQtScriptingConsole.h │ └── libs/ │ ├── debug/ │ │ ├── PythonQt-Qt5-Python38_d.lib │ │ └── PythonQt_QtAll-Qt5-Python38_d.lib │ └── release/ │ ├── PythonQt-Qt5-Python38.lib │ └── PythonQt_QtAll-Qt5-Python38.lib ├── ffmpeg/ │ ├── include/ │ │ ├── libavcodec/ │ │ │ ├── ac3_parser.h │ │ │ ├── adts_parser.h │ │ │ ├── avcodec.h │ │ │ ├── avdct.h │ │ │ ├── avfft.h │ │ │ ├── d3d11va.h │ │ │ ├── dirac.h │ │ │ ├── dv_profile.h │ │ │ ├── dxva2.h │ │ │ ├── jni.h │ │ │ ├── mediacodec.h │ │ │ ├── qsv.h │ │ │ ├── vaapi.h │ │ │ ├── vdpau.h │ │ │ ├── version.h │ │ │ ├── videotoolbox.h │ │ │ ├── vorbis_parser.h │ │ │ └── xvmc.h │ │ ├── libavdevice/ │ │ │ ├── avdevice.h │ │ │ └── version.h │ │ ├── libavfilter/ │ │ │ ├── avfilter.h │ │ │ ├── buffersink.h │ │ │ ├── buffersrc.h │ │ │ └── version.h │ │ ├── libavformat/ │ │ │ ├── avformat.h │ │ │ ├── avio.h │ │ │ └── version.h │ │ ├── libavutil/ │ │ │ ├── adler32.h │ │ │ ├── aes.h │ │ │ ├── aes_ctr.h │ │ │ ├── attributes.h │ │ │ ├── audio_fifo.h │ │ │ ├── avassert.h │ │ │ ├── avconfig.h │ │ │ ├── avstring.h │ │ │ ├── avutil.h │ │ │ ├── base64.h │ │ │ ├── blowfish.h │ │ │ ├── bprint.h │ │ │ ├── bswap.h │ │ │ ├── buffer.h │ │ │ ├── camellia.h │ │ │ ├── cast5.h │ │ │ ├── channel_layout.h │ │ │ ├── common.h │ │ │ ├── cpu.h │ │ │ ├── crc.h │ │ │ ├── des.h │ │ │ ├── dict.h │ │ │ ├── display.h │ │ │ ├── downmix_info.h │ │ │ ├── encryption_info.h │ │ │ ├── error.h │ │ │ ├── eval.h │ │ │ ├── ffversion.h │ │ │ ├── fifo.h │ │ │ ├── file.h │ │ │ ├── frame.h │ │ │ ├── hash.h │ │ │ ├── hdr_dynamic_metadata.h │ │ │ ├── hmac.h │ │ │ ├── hwcontext.h │ │ │ ├── hwcontext_cuda.h │ │ │ ├── hwcontext_d3d11va.h │ │ │ ├── hwcontext_drm.h │ │ │ ├── hwcontext_dxva2.h │ │ │ ├── hwcontext_mediacodec.h │ │ │ ├── hwcontext_qsv.h │ │ │ ├── hwcontext_vaapi.h │ │ │ ├── hwcontext_vdpau.h │ │ │ ├── hwcontext_videotoolbox.h │ │ │ ├── imgutils.h │ │ │ ├── intfloat.h │ │ │ ├── intreadwrite.h │ │ │ ├── lfg.h │ │ │ ├── log.h │ │ │ ├── lzo.h │ │ │ ├── macros.h │ │ │ ├── mastering_display_metadata.h │ │ │ ├── mathematics.h │ │ │ ├── md5.h │ │ │ ├── mem.h │ │ │ ├── motion_vector.h │ │ │ ├── murmur3.h │ │ │ ├── opt.h │ │ │ ├── parseutils.h │ │ │ ├── pixdesc.h │ │ │ ├── pixelutils.h │ │ │ ├── pixfmt.h │ │ │ ├── random_seed.h │ │ │ ├── rational.h │ │ │ ├── rc4.h │ │ │ ├── replaygain.h │ │ │ ├── ripemd.h │ │ │ ├── samplefmt.h │ │ │ ├── sha.h │ │ │ ├── sha512.h │ │ │ ├── spherical.h │ │ │ ├── stereo3d.h │ │ │ ├── tea.h │ │ │ ├── threadmessage.h │ │ │ ├── time.h │ │ │ ├── timecode.h │ │ │ ├── timestamp.h │ │ │ ├── tree.h │ │ │ ├── twofish.h │ │ │ ├── tx.h │ │ │ ├── version.h │ │ │ └── xtea.h │ │ ├── libpostproc/ │ │ │ ├── postprocess.h │ │ │ └── version.h │ │ ├── libswresample/ │ │ │ ├── swresample.h │ │ │ └── version.h │ │ └── libswscale/ │ │ ├── swscale.h │ │ └── version.h │ └── libs/ │ ├── avcodec-58.def │ ├── avcodec.lib │ ├── avdevice-58.def │ ├── avdevice.lib │ ├── avfilter-7.def │ ├── avfilter.lib │ ├── avformat-58.def │ ├── avformat.lib │ ├── avutil-56.def │ ├── avutil.lib │ ├── postproc-55.def │ ├── postproc.lib │ ├── swresample-3.def │ ├── swresample.lib │ ├── swscale-5.def │ └── swscale.lib └── python3_8/ ├── include/ │ ├── Python-ast.h │ ├── Python.h │ ├── abstract.h │ ├── asdl.h │ ├── ast.h │ ├── bitset.h │ ├── bltinmodule.h │ ├── boolobject.h │ ├── bytearrayobject.h │ ├── bytes_methods.h │ ├── bytesobject.h │ ├── cellobject.h │ ├── ceval.h │ ├── classobject.h │ ├── code.h │ ├── codecs.h │ ├── compile.h │ ├── complexobject.h │ ├── context.h │ ├── cpython/ │ │ ├── abstract.h │ │ ├── dictobject.h │ │ ├── fileobject.h │ │ ├── initconfig.h │ │ ├── interpreteridobject.h │ │ ├── object.h │ │ ├── objimpl.h │ │ ├── pyerrors.h │ │ ├── pylifecycle.h │ │ ├── pymem.h │ │ ├── pystate.h │ │ ├── sysmodule.h │ │ ├── traceback.h │ │ ├── tupleobject.h │ │ └── unicodeobject.h │ ├── datetime.h │ ├── descrobject.h │ ├── dictobject.h │ ├── dtoa.h │ ├── dynamic_annotations.h │ ├── enumobject.h │ ├── errcode.h │ ├── eval.h │ ├── fileobject.h │ ├── fileutils.h │ ├── floatobject.h │ ├── frameobject.h │ ├── funcobject.h │ ├── genobject.h │ ├── graminit.h │ ├── grammar.h │ ├── import.h │ ├── internal/ │ │ ├── pycore_accu.h │ │ ├── pycore_atomic.h │ │ ├── pycore_ceval.h │ │ ├── pycore_code.h │ │ ├── pycore_condvar.h │ │ ├── pycore_context.h │ │ ├── pycore_fileutils.h │ │ ├── pycore_getopt.h │ │ ├── pycore_gil.h │ │ ├── pycore_hamt.h │ │ ├── pycore_initconfig.h │ │ ├── pycore_object.h │ │ ├── pycore_pathconfig.h │ │ ├── pycore_pyerrors.h │ │ ├── pycore_pyhash.h │ │ ├── pycore_pylifecycle.h │ │ ├── pycore_pymem.h │ │ ├── pycore_pystate.h │ │ ├── pycore_traceback.h │ │ ├── pycore_tupleobject.h │ │ └── pycore_warnings.h │ ├── interpreteridobject.h │ ├── intrcheck.h │ ├── iterobject.h │ ├── listobject.h │ ├── longintrepr.h │ ├── longobject.h │ ├── marshal.h │ ├── memoryobject.h │ ├── methodobject.h │ ├── modsupport.h │ ├── moduleobject.h │ ├── namespaceobject.h │ ├── node.h │ ├── object.h │ ├── objimpl.h │ ├── odictobject.h │ ├── opcode.h │ ├── osdefs.h │ ├── osmodule.h │ ├── parsetok.h │ ├── patchlevel.h │ ├── picklebufobject.h │ ├── py_curses.h │ ├── pyarena.h │ ├── pycapsule.h │ ├── pyconfig.h │ ├── pyctype.h │ ├── pydebug.h │ ├── pydtrace.h │ ├── pyerrors.h │ ├── pyexpat.h │ ├── pyfpe.h │ ├── pyhash.h │ ├── pylifecycle.h │ ├── pymacconfig.h │ ├── pymacro.h │ ├── pymath.h │ ├── pymem.h │ ├── pyport.h │ ├── pystate.h │ ├── pystrcmp.h │ ├── pystrhex.h │ ├── pystrtod.h │ ├── pythonrun.h │ ├── pythread.h │ ├── pytime.h │ ├── rangeobject.h │ ├── setobject.h │ ├── sliceobject.h │ ├── structmember.h │ ├── structseq.h │ ├── symtable.h │ ├── sysmodule.h │ ├── token.h │ ├── traceback.h │ ├── tracemalloc.h │ ├── tupleobject.h │ ├── typeslots.h │ ├── ucnhash.h │ ├── unicodeobject.h │ ├── warnings.h │ └── weakrefobject.h └── libs/ ├── _tkinter.lib ├── _tkinter_d.lib ├── python3.lib ├── python38.lib ├── python38_d.lib └── python3_d.lib ================================================ FILE CONTENTS ================================================ ================================================ FILE: AudioVideoCore/AudioData.cpp ================================================ #include "AudioData.h" ================================================ FILE: AudioVideoCore/AudioData.h ================================================ #ifndef AUDIODATA_H #define AUDIODATA_H #include #include #include #include #include struct AudioData { QMutex m_audioPlayMutex; QWaitCondition m_audioPlayCondition; QWaitCondition m_audioDecodecCondition; std::atomic m_nStartIndex; std::atomic m_nEndIndex; std::atomic m_nTotalCanUsed; AudioData() :m_nStartIndex(0) ,m_nEndIndex(0) ,m_nTotalCanUsed(0){} ~AudioData(){} }; #endif ================================================ FILE: AudioVideoCore/AudioDecodec.cpp ================================================ #include "AudioDecodec.h" #include #include AudioDecodec::AudioDecodec(QObject* parent) :QThread(parent) ,m_isPlay(true) ,m_isDecodecFinsihed(true) { av_register_all(); m_pPlayThread = new AudioPlayerThread(m_audioData, this); QObject::connect(m_pPlayThread, &AudioPlayerThread::playFinished, this, &AudioDecodec::onPlayFinished); } AudioDecodec::~AudioDecodec() { this->stop(); m_isPlay = false; this->requestInterruption(); m_audioData.m_audioDecodecCondition.wakeAll(); this->wait(); closeFile(); delete m_pPlayThread; qDebug() << __FUNCTION__; } bool AudioDecodec::openAudioFile(const QString& filePath) { m_pAvFrame = av_frame_alloc(); // 打开文件 int result = avformat_open_input(&m_pFormatContent, filePath.toLocal8Bit().data(), nullptr, nullptr); if (result != 0) qDebug() << "Result is Not Zero!"; if (m_pFormatContent == nullptr) qDebug() << "FormtContent is Nullptr"; if (result || !m_pFormatContent) return false; // 查找流信息 result = avformat_find_stream_info(m_pFormatContent, nullptr); if (result < 0) return false; // 查找音频流 int streamCount = m_pFormatContent->nb_streams; for (int i=0; istreams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { m_nAudioStreamIndex = i; break; } } if (m_nAudioStreamIndex < 0) { avformat_close_input(&m_pFormatContent); return false; } // 获取总时长 m_nTotalTime = m_pFormatContent->duration * 1.0 / AV_TIME_BASE * 1000; // 查找解码器 m_pCodecContent = m_pFormatContent->streams[m_nAudioStreamIndex]->codec; AVCodec* codec = avcodec_find_decoder(m_pCodecContent->codec_id); if (codec == nullptr) { avformat_close_input(&m_pFormatContent); return false; } // 打开解码器 result = avcodec_open2(m_pCodecContent, codec, nullptr); if (result != 0) { avformat_close_input(&m_pFormatContent); return false; } // 设置采样率等信息 m_nSampleRate = m_pCodecContent->sample_rate; m_nSampleFormat = m_pCodecContent->sample_fmt; m_pCodecContent->channel_layout = av_get_default_channel_layout(m_pCodecContent->channels); m_nChannelSize = m_pCodecContent->channels; m_isDecodecFinsihed = false; return true; } void AudioDecodec::run(void) { while (!this->isInterruptionRequested()) { // 缓冲区满了,挂起线程 if (m_pPlayThread->isBufferFull() || !m_isPlay) { m_audioData.m_audioPlayMutex.lock(); m_audioData.m_audioDecodecCondition.wait(&m_audioData.m_audioPlayMutex); m_audioData.m_audioPlayMutex.unlock(); } AVPacket pkt; // 获取帧出错,可能是结束或者出错 int result = av_read_frame(m_pFormatContent, &pkt); if (result != 0) { // 释放包的内存 av_packet_unref(&pkt); m_isPlay = false; m_isDecodecFinsihed = true; continue; } // 只处理音频 if (pkt.stream_index != m_nAudioStreamIndex) continue; // 解码音频帧, 发送音频包 if (avcodec_send_packet(m_pCodecContent, &pkt)) continue; // 解码音频帧,接收音频解码帧 if (avcodec_receive_frame(m_pCodecContent, m_pAvFrame)) continue; int writedSize = 0; // 获取解码后的PCM数据 int size = m_pPlayThread->addAudioData((char*)m_pAvFrame->data[0], m_pAvFrame->linesize[0]); writedSize += size; while (writedSize < m_pAvFrame->linesize[0] && m_isPlay) { m_audioData.m_audioPlayMutex.lock(); m_audioData.m_audioDecodecCondition.wait(&m_audioData.m_audioPlayMutex); m_audioData.m_audioPlayMutex.unlock(); if (m_isPlay) { int size = m_pPlayThread->addAudioData((char*)m_pAvFrame->data[0] + writedSize, \ m_pAvFrame->linesize[0] - writedSize); writedSize += size; } } // 释放包的内存 av_packet_unref(&pkt); } } void AudioDecodec::play(void) { int sampleSize = 16; m_pPlayThread->setSampleInfo(m_nSampleRate, sampleSize, m_nChannelSize); // 播放 m_pPlayThread->startPlay(); // 解码 m_isPlay = true; if (!this->isRunning()) this->start(); m_audioData.m_audioDecodecCondition.wakeAll(); } void AudioDecodec::pause(void) { m_pPlayThread->pausePlay(); } void AudioDecodec::stop(void) { m_isPlay = false; m_audioData.m_audioDecodecCondition.wakeAll(); m_pPlayThread->stop(); if (m_nAudioStreamIndex >= 0) av_seek_frame(m_pFormatContent, m_nAudioStreamIndex, 0, AVSEEK_FLAG_BACKWARD); m_isDecodecFinsihed = false; } // 关闭文件 void AudioDecodec::closeFile(void) { av_frame_free(&m_pAvFrame); if (m_pFormatContent) avformat_close_input(&m_pFormatContent); } bool AudioDecodec::isDecodecFinished(void) { bool result = m_isDecodecFinsihed; return result; } // 获取音频信息 int AudioDecodec::getTotalTime(void) { return m_nTotalTime; } void AudioDecodec::getSampleInfos(int &sampleRate, int &sampleSize, int &channelCount) { sampleRate = m_nSampleRate; sampleSize = 16; channelCount = m_nChannelSize; } void AudioDecodec::onPlayFinished(void) { if (m_isDecodecFinsihed) emit playFinished(); } ================================================ FILE: AudioVideoCore/AudioDecodec.h ================================================ #ifndef AUDIODECODEC_H #define AUDIODECODEC_H extern "C" { #include #include #include } #include #include #include "AudioData.h" #include "AudioPlayerThread.h" #include "audiovideocore_global.h" class AUDIOVIDEOCORESHARED_EXPORT AudioDecodec : public QThread { Q_OBJECT public: AudioDecodec(QObject* parent = nullptr); ~AudioDecodec(); // 打开音频文件 bool openAudioFile(const QString& filePath); // 关闭文件 void closeFile(void); // 获取是否结束 bool isDecodecFinished(void); // 获取音频信息 int getTotalTime(void); void getSampleInfos(int &sampleRate, int &sampleSize, int &channelCount); // 开始解码并播放 void play(void); // 暂停 void pause(void); // 结束播放 void stop(void); void run(void) override; private: AVFormatContext* m_pFormatContent = nullptr; AVCodecContext* m_pCodecContent = nullptr; int m_nAudioStreamIndex = -1; qreal m_nTotalTime = 0.0; // ms int m_nSampleRate = 0; // 采样率 AVSampleFormat m_nSampleFormat; // 采样大小 int m_nChannelSize = 2; // 通道数 AVFrame *m_pAvFrame = nullptr; AudioPlayerThread* m_pPlayThread= nullptr; std::atomic m_isPlay; std::atomic m_isDecodecFinsihed; // 音频相关数据 AudioData m_audioData; friend AudioPlayerThread; signals: void playFinished(void); private slots: void onPlayFinished(void); }; #endif ================================================ FILE: AudioVideoCore/AudioPlayer.cpp ================================================ #include "AudioPlayer.h" AudioPlayer::AudioPlayer(QObject* parent) :QObject(parent) { m_pAudioPlayer = new AudioDecodec(this); QObject::connect(m_pAudioPlayer, &AudioDecodec::playFinished, this, &AudioPlayer::onPlayFinished); } AudioPlayer::~AudioPlayer() { } // 打开一个音频文件 bool AudioPlayer::openAudioFile(const QString& fileName) { return m_pAudioPlayer->openAudioFile(fileName); } // 关闭文件 void AudioPlayer::close(void) { m_pAudioPlayer->closeFile(); } // 获取音频信息 AudioPlayer::AudioInfo AudioPlayer::getInfo(void) { AudioInfo audioInfo; audioInfo.totalTime = m_pAudioPlayer->getTotalTime(); m_pAudioPlayer->getSampleInfos(audioInfo.sampleRate, audioInfo.sampleSize, audioInfo.channelSize); return audioInfo; } // 开始播放 void AudioPlayer::play(void) { m_pAudioPlayer->play(); m_playerStatus = t_playing; } // 暂停播放 void AudioPlayer::pause(void) { m_pAudioPlayer->pause(); m_playerStatus = t_pause; } // 结束 void AudioPlayer::stop(void) { m_pAudioPlayer->stop(); m_playerStatus = t_normal; } AudioPlayer::PlayStatus AudioPlayer::getCurrentPlayStatus(void) { return m_playerStatus; } void AudioPlayer::onPlayFinished(void) { this->stop(); emit playFinished(); } ================================================ FILE: AudioVideoCore/AudioPlayer.h ================================================ #ifndef AUDIOPLAYER_H #define AUDIOPLAYER_H #include #include "AudioDecodec.h" #include "audiovideocore_global.h" class AUDIOVIDEOCORESHARED_EXPORT AudioPlayer : public QObject { Q_OBJECT public: struct AudioInfo { int sampleRate; // 采样率 int sampleSize; // 采样大小 int channelSize; // 通道数 int totalTime; // 总时长ms }; enum PlayStatus { t_normal, t_playing, t_pause }; public: AudioPlayer(QObject* parent = nullptr); ~AudioPlayer(); // 打开一个音频文件 bool openAudioFile(const QString& fileName); // 关闭文件 void close(void); // 获取音频信息 AudioInfo getInfo(void); // 开始播放 void play(void); // 暂停播放 void pause(void); // 结束 void stop(void); // 获取当前播放状态 PlayStatus getCurrentPlayStatus(void); private: AudioDecodec* m_pAudioPlayer = nullptr; PlayStatus m_playerStatus = t_normal; private slots: void onPlayFinished(void); signals: void playFinished(void); }; #endif ================================================ FILE: AudioVideoCore/AudioPlayerThread.cpp ================================================ #include "AudioPlayerThread.h" #include "AudioData.h" #include #include AudioPlayerThread::AudioPlayerThread(AudioData& audioData, QObject* parent) :QThread(parent) ,m_isPlay(true) ,m_audioData(audioData) { initAudioBuffer(); } AudioPlayerThread::~AudioPlayerThread() { m_isPlay = false; this->requestInterruption(); m_audioData.m_audioPlayCondition.wakeAll(); this->wait(); stop(); delete[] m_pAudioBuffer; qDebug() << __FUNCTION__; } void AudioPlayerThread::initAudioBuffer(void) { m_pAudioBuffer = new char[m_nMaxBufferSize]; memset(m_pAudioBuffer, 0, m_nMaxBufferSize); } int AudioPlayerThread::addAudioData(const char* pAudioData, int length) { int canAddedSize = m_nMaxBufferSize - m_audioData.m_nTotalCanUsed; int destSize = qMin(canAddedSize, length); destSize = destSize / 4 * 4; if (destSize == 0) return destSize; int nTempEndIndex = m_audioData.m_nEndIndex; if (m_nMaxBufferSize - nTempEndIndex >= destSize) memcpy(m_pAudioBuffer + m_audioData.m_nEndIndex, pAudioData, destSize); else { int size = m_nMaxBufferSize - m_audioData.m_nEndIndex; memcpy(m_pAudioBuffer + m_audioData.m_nEndIndex, pAudioData, size); memcpy(m_pAudioBuffer + 0, pAudioData + size, destSize - size); } // 重新设置结束标志 m_audioData.m_nEndIndex += destSize; if (m_audioData.m_nEndIndex >= m_nMaxBufferSize) m_audioData.m_nEndIndex -= m_nMaxBufferSize; m_audioData.m_nTotalCanUsed += destSize; m_audioData.m_audioPlayCondition.wakeAll(); return destSize; } // 判断缓存区是否已经满了 bool AudioPlayerThread::isBufferFull(void) { if (m_audioData.m_nTotalCanUsed >= m_nMaxBufferSize) return true; return false; } void AudioPlayerThread::setSampleInfo(int sampleRate, int sampleSize, int channelCount) { m_format.setSampleRate(sampleRate); m_format.setSampleSize(sampleSize); m_format.setChannelCount(channelCount); m_format.setCodec("audio/pcm"); m_format.setByteOrder(QAudioFormat::LittleEndian); m_format.setSampleType(QAudioFormat::SignedInt); if (m_pAudioOutput) delete m_pAudioOutput; m_pAudioOutput = new QAudioOutput(m_format, this); m_pIODevice = m_pAudioOutput->start(); qDebug() << m_pAudioOutput->state(); if (m_pAudioOutput == nullptr) qDebug() << "AudioOutPut Is Nullptr"; if (m_pIODevice == nullptr) qDebug() << "m_pIODevice Is Nullptr" << m_pAudioOutput->error(); } // 开始播放 void AudioPlayerThread::startPlay(void) { if (!this->isRunning()) this->start(); m_audioData.m_nStartIndex = 0; m_audioData.m_nEndIndex = 0; m_audioData.m_nTotalCanUsed = 0; memset(m_pAudioBuffer, 0, m_nMaxBufferSize); m_isPlay = true; } void AudioPlayerThread::pausePlay(void) { m_isPlay = false; } void AudioPlayerThread::run(void) { while (!this->isInterruptionRequested()) { // 线程挂起,等待被唤醒 if (m_audioData.m_nTotalCanUsed <= 0 || !m_isPlay) { // 发送播放结束 if (m_audioData.m_nTotalCanUsed <= 0) emit playFinished(); m_audioData.m_audioPlayMutex.lock(); m_audioData.m_audioPlayCondition.wait(&m_audioData.m_audioPlayMutex); m_audioData.m_audioPlayMutex.unlock(); } // 数据比较少,立即播放 int nTotalCanUsed = m_audioData.m_nTotalCanUsed; if (m_pAudioOutput->bytesFree() >= nTotalCanUsed && m_isPlay) { if (nTotalCanUsed + m_audioData.m_nStartIndex <= m_nMaxBufferSize) { // 直接写入数据 m_pIODevice->write(m_pAudioBuffer + m_audioData.m_nStartIndex, nTotalCanUsed); } else { int size = m_nMaxBufferSize - m_audioData.m_nStartIndex; m_pIODevice->write(m_pAudioBuffer + m_audioData.m_nStartIndex, size); m_pIODevice->write(m_pAudioBuffer + 0, nTotalCanUsed - size); } // 设置起始位置 m_audioData.m_nStartIndex += nTotalCanUsed; if (m_audioData.m_nStartIndex >= m_nMaxBufferSize) m_audioData.m_nStartIndex -= m_nMaxBufferSize; m_audioData.m_nTotalCanUsed -= nTotalCanUsed; // 唤醒解码线程 m_audioData.m_audioDecodecCondition.wakeAll(); continue; } // 数据比较多,循环播放 int perWriteSize = m_pAudioOutput->periodSize(); if (m_pAudioOutput->bytesFree() >= perWriteSize && m_isPlay) { if (perWriteSize + m_audioData.m_nStartIndex <= m_nMaxBufferSize) { // 直接写入数据 m_pIODevice->write(m_pAudioBuffer + m_audioData.m_nStartIndex, perWriteSize); } else { int size = m_nMaxBufferSize - m_audioData.m_nStartIndex; m_pIODevice->write(m_pAudioBuffer + m_audioData.m_nStartIndex, size); m_pIODevice->write(m_pAudioBuffer + 0, perWriteSize - size); } m_audioData.m_nStartIndex += perWriteSize; if (m_audioData.m_nStartIndex >= m_nMaxBufferSize) m_audioData.m_nStartIndex -= m_nMaxBufferSize; m_audioData.m_nTotalCanUsed -= perWriteSize; // 唤醒解码线程 m_audioData.m_audioDecodecCondition.wakeAll(); } QThread::msleep(10); } } void AudioPlayerThread::stop(void) { m_isPlay = false; m_audioData.m_nStartIndex = 0; m_audioData.m_nEndIndex = 0; m_audioData.m_nTotalCanUsed = false; memset(m_pAudioBuffer, 0, m_nMaxBufferSize); } ================================================ FILE: AudioVideoCore/AudioPlayerThread.h ================================================ #ifndef AUDIOPLAYERTHREAD_H #define AUDIOPLAYERTHREAD_H #include #include #include #include #include #include #include #include class DecodecVideo; class AudioData; class AudioPlayDecice : QIODevice { Q_OBJECT public: }; class AudioPlayerThread : public QThread { Q_OBJECT public: AudioPlayerThread(AudioData& audioData, QObject* parent = nullptr); ~AudioPlayerThread() override; void run(void) override; // set sample infos void setSampleInfo(int sampleRate, int sampleSize, int channelCount); // 添加数据 int addAudioData(const char* pAudioData, int length); // 开始播放 void startPlay(void); // 暂停 void pausePlay(void); // 结束 void stop(void); // 判断缓存区是否已经满了 bool isBufferFull(void); private: QAudioFormat m_format; QAudioOutput* m_pAudioOutput = nullptr; QIODevice* m_pIODevice = nullptr; // 音频数据Buffer char* m_pAudioBuffer = nullptr; const int m_nMaxBufferSize = 1 * 1024 * 1024; // 1M的音频数据Buffer void initAudioBuffer(void); std::atomic m_isPlay; AudioData& m_audioData; signals: void playFinished(void); }; #endif ================================================ FILE: AudioVideoCore/AudioVideoCore.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-03-23T14:11:21 # #------------------------------------------------- QT += widgets multimedia TARGET = AudioVideoCore TEMPLATE = lib DEFINES += AUDIOVIDEOCORE_LIBRARY # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 DESTDIR += $$PWD/../bin MOC_DIR += $$PWD/../AudioVideoCore/temp OBJECTS_DIR += $$PWD/../AudioVideoCore/temp CONFIG += c++11 INCLUDEPATH += $$PWD/../thirdLibs/ffmpeg/include LIBS += -L$$PWD/../thirdLibs/ffmpeg/libs/ -lavcodec -lavformat -lavutil QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG SOURCES += \ AudioData.cpp \ AudioDecodec.cpp \ AudioPlayer.cpp \ AudioPlayerThread.cpp HEADERS += \ AudioData.h \ AudioDecodec.h \ AudioPlayer.h \ AudioPlayerThread.h \ audiovideocore_global.h unix { target.path = /usr/lib INSTALLS += target } ================================================ FILE: AudioVideoCore/audiovideocore_global.h ================================================ #ifndef AUDIOVIDEOCORE_GLOBAL_H #define AUDIOVIDEOCORE_GLOBAL_H #include #if defined(AUDIOVIDEOCORE_LIBRARY) # define AUDIOVIDEOCORESHARED_EXPORT Q_DECL_EXPORT #else # define AUDIOVIDEOCORESHARED_EXPORT Q_DECL_IMPORT #endif #endif // AUDIOVIDEOCORE_GLOBAL_H ================================================ FILE: CustomControls/CustomCombineControl/UICustomColorControl.cpp ================================================ #include "UICustomColorControl.h" #include "UICustomColorControl/UICustomColorWidget.h" #include "UICustomColorControl/UICustonColorDialog.h" UICustomColorControl::UICustomColorControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pColorViewWidget = new UICustomColorViewWidget; m_pMainLayout->addWidget(m_pColorViewWidget); // 添加Slider m_pSlider = new QSlider(Qt::Horizontal); m_pSlider->setMinimum(0); m_pSlider->setMaximum(255); m_pSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pMainLayout->addWidget(m_pSlider); QObject::connect(m_pSlider, &QSlider::valueChanged, this, &UICustomColorControl::onSliderValueChanged); QObject::connect(m_pSlider, &QSlider::sliderPressed, this, &UICustomColorControl::onSliderPressed); QObject::connect(m_pSlider, &QSlider::sliderMoved, this, &UICustomColorControl::onSliderMoved); QObject::connect(m_pSlider, &QSlider::sliderReleased, this, &UICustomColorControl::onSliderReleased); QObject::connect(m_pColorViewWidget, &UICustomColorViewWidget::mousePressed, \ this, &UICustomColorControl::onColorViewClicked); this->setWidth(400); this->setHeight(30); } UICustomColorControl::~UICustomColorControl() { } void UICustomColorControl::setCurrentColor(const QColor& color, bool cmd) { if (color == m_pColorViewWidget->getCurrentColor()) return; m_pColorViewWidget->setCurrentColor(color); int h,s,v; color.getHsv(&h, &s, &v); m_pSlider->blockSignals(true); m_pSlider->setValue(v); m_pSlider->blockSignals(false); // 发送颜色更改信号 emit colorChanged(color, cmd); } const QColor& UICustomColorControl::getCurrentColor(void) { return m_pColorViewWidget->getCurrentColor(); } void UICustomColorControl::onSliderMoved(void) { setColorByVValue(m_pSlider->value()); } void UICustomColorControl::setColorByVValue(int vValue, bool cmd) { QColor color = m_pColorViewWidget->getCurrentColor(); int h,s,v; color.getHsv(&h, &s, &v); color.setHsv(h, s, vValue); if (color != m_pColorViewWidget->getCurrentColor() || cmd) { m_pColorViewWidget->setCurrentColor(color); emit colorDragChanged(color, cmd); } } void UICustomColorControl::onSliderPressed(void) { m_tempColor = m_pColorViewWidget->getCurrentColor(); setColorByVValue(m_pSlider->value()); } void UICustomColorControl::onSliderReleased(void) { int value = m_pSlider->value(); setCurrentColor(m_tempColor); setColorByVValue(value, true); m_pSlider->blockSignals(true); m_pSlider->setValue(value); m_pSlider->blockSignals(false); } void UICustomColorControl::onSliderValueChanged(int value) { setColorByVValue(value); } void UICustomColorControl::onColorViewClicked(void) { UICustomColorDialog dialog; dialog.setCurrentColor(m_pColorViewWidget->getCurrentColor()); if (UICustomColorDialog::Accepted != dialog.exec()) return; QColor color = dialog.getCurrentColor(); this->setCurrentColor(color, true); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomColorControl.h ================================================ /** 基本组合控件-颜色控件: 作者:Douzhq 日期:2020-01-22 个人博客:不会飞的纸飞机 http://www.douzhq.cn */ #ifndef UICUSTOMCOLORCONTROL_H #define UICUSTOMCOLORCONTROL_H #include "UICustomCombineControlBase.h" #include "UICustomWidgtes/CustomWidget.h" #include "UICustomSingleControl/UICustomColorViewWidget.h" #include "customcontrols_global.h" #include class CUSTOMCONTROLSSHARED_EXPORT UICustomColorControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomColorControl(QWidget* parent = nullptr); ~UICustomColorControl(); // 设置/获取当前的颜色值 void setCurrentColor(const QColor& color, bool cmd = false); const QColor& getCurrentColor(void); private: // 预览控件 UICustomColorViewWidget* m_pColorViewWidget = nullptr; // 滑条 QSlider* m_pSlider = nullptr; QColor m_tempColor; // 设置颜色 void setColorByVValue(int vValue, bool cmd = false); private slots: void onSliderMoved(void); void onSliderPressed(void); void onSliderReleased(void); void onSliderValueChanged(int value); void onColorViewClicked(void); signals: // 颜色更改发送信号(滑杆松开后发送该信号、通过点击更改颜色) void colorChanged(const QColor& color, bool cmd = false); // 颜色更改信号(滑动滑杆就触发) void colorDragChanged(const QColor& color, bool cmd = false); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomCombineControlBase.cpp ================================================ #include "UICustomCombineControlBase.h" #include "UICustomCore/CustomStyleConfig.h" UICustomCombineControlBase::UICustomCombineControlBase(QWidget* parent) :CustomWidget(parent) { m_pMainLayout = new QHBoxLayout(this); m_pMainLayout->setSpacing(0); m_pMainLayout->setMargin(0); m_pTagLabel = new QLabel(); m_pMainLayout->addWidget(m_pTagLabel); m_pTagLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_pTagLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // 设置默认第0列宽度 setColumnWidth(0, 160); g_StyleConfig->setCurrentStyle(this, "DefaultWidget"); } UICustomCombineControlBase::~UICustomCombineControlBase() { } void UICustomCombineControlBase::setColumnWidth(int column, int width) { int count = m_pMainLayout->count(); int number = 0; for (int i=0; iitemAt(i)->widget(); if (pWidget == nullptr) continue; if (number == column) { pWidget->setFixedWidth(width); return; } number++; } } // 设置某一列显示/隐藏 void UICustomCombineControlBase::setColumnVisible(int column, bool visible) { int count = m_pMainLayout->count(); int number = 0; for (int i=0; iitemAt(i)->widget(); if (pWidget == nullptr) continue; if (number == column) { pWidget->setHidden(!visible); return; } number++; } } void UICustomCombineControlBase::setColumnExpingVisible(int column, bool isExping) { int count = m_pMainLayout->count(); int number = 0; for (int i=0; iitemAt(i)->widget(); if (pWidget == nullptr) continue; if (number == column) { if (isExping) pWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); else pWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); return; } number++; } } void UICustomCombineControlBase::setTagText(const QString& tagText) { m_pTagLabel->setText(tagText); } void UICustomCombineControlBase::setTextAlign(Qt::Alignment alignment) { m_pTagLabel->setAlignment(alignment); } // 设置宽度和高度 void UICustomCombineControlBase::setWidth(int width) { m_nWidth = width; this->setMinimumWidth(width); } void UICustomCombineControlBase::setHeight(int height) { m_nHeight = height; this->setMinimumHeight(height); } QSize UICustomCombineControlBase::sizeHint() const { QSize size(m_nWidth, m_nHeight); return size; } ================================================ FILE: CustomControls/CustomCombineControl/UICustomCombineControlBase.h ================================================ /** 基本组合控件基类: 作者:Douzhq 日期:2020-01-22 个人博客:不会飞的纸飞机 www.douzhq.cn */ #ifndef UICUSTOMCOMBINECONTROLBASE_H #define UICUSTOMCOMBINECONTROLBASE_H #include "UICustomWidgtes/CustomWidget.h" #include #include #include #include "customcontrols_global.h" class CUSTOMCONTROLSSHARED_EXPORT UICustomCombineControlBase : public CustomWidget { Q_OBJECT public: UICustomCombineControlBase(QWidget* parent = nullptr); ~UICustomCombineControlBase(); // 设置某一列的宽度 void setColumnWidth(int column, int width); // 设置某一列显示/隐藏 void setColumnVisible(int column, bool visible); // 设置某一列伸缩性 void setColumnExpingVisible(int column, bool isExping); // 设置文本内容 void setTagText(const QString& tagText); // 设置文本的对齐方式 void setTextAlign(Qt::Alignment alignment); // 设置宽度和高度 void setWidth(int width); void setHeight(int height); protected: QHBoxLayout *m_pMainLayout = nullptr; QLabel* m_pTagLabel = nullptr; QSize sizeHint() const override; private: int m_nWidth = 400; int m_nHeight = 30; }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomComboBoxControl.cpp ================================================ #include "UICustomComboBoxControl.h" UICustomComboBoxControl::UICustomComboBoxControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pCustomComboBox = new UICustomComboBox; m_pCustomComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pMainLayout->addWidget(m_pCustomComboBox); QObject::connect(m_pCustomComboBox, SIGNAL(currentIndexChanged(int)), \ this, SIGNAL(currentIndexChanged(int))); QObject::connect(m_pCustomComboBox, SIGNAL(currentIndexChanged(const QString &)), \ this, SIGNAL(currentTextChanged(const QString&))); } UICustomComboBoxControl::~UICustomComboBoxControl() { } // 添加元素 void UICustomComboBoxControl::addItem(const QString& item) { m_pCustomComboBox->addItem(item); } void UICustomComboBoxControl::addItem(const QString& name, const QVariant& data) { m_pCustomComboBox->addItem(name, data); } // 获取当前元素 QString UICustomComboBoxControl::getCurrentItem(void) { return m_pCustomComboBox->currentText(); } void UICustomComboBoxControl::setCurrentItem(const QString& text) { m_pCustomComboBox->setCurrentText(text); } void UICustomComboBoxControl::setCurrentIndex(int index) { m_pCustomComboBox->setCurrentIndex(index); } int UICustomComboBoxControl::getCurrentIndex(void) { return m_pCustomComboBox->currentIndex(); } QVariant UICustomComboBoxControl::getCurrentItemData(void) { return m_pCustomComboBox->currentData(); } int UICustomComboBoxControl::getItemCount(void) { return m_pCustomComboBox->count(); } void UICustomComboBoxControl::clearAllItems(void) { m_pCustomComboBox->clear(); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomComboBoxControl.h ================================================ #ifndef UICUSTOMCOMBOBOXCONTROL_H #define UICUSTOMCOMBOBOXCONTROL_H #include "UICustomCombineControlBase.h" #include "UICustomSingleControl/UICustomComboBox.h" #include "customcontrols_global.h" class CUSTOMCONTROLSSHARED_EXPORT UICustomComboBoxControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomComboBoxControl(QWidget* parent = nullptr); ~UICustomComboBoxControl(); // 添加元素 void addItem(const QString& item); void addItem(const QString& name, const QVariant& data); // 获取当前元素 void setCurrentItem(const QString& text); QString getCurrentItem(void); void setCurrentIndex(int index); int getCurrentIndex(void); // 获取当前数据 QVariant getCurrentItemData(void); // 获取当前个数 int getItemCount(void); // 清除所有元素 void clearAllItems(void); private: UICustomComboBox* m_pCustomComboBox = nullptr; signals: void currentTextChanged(const QString& str); void currentIndexChanged(int index); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomDateEditControl.cpp ================================================ #include "UICustomDateEditControl.h" UICustomDateEditControl::UICustomDateEditControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pDateEdit = new UICutomDateEdit; m_pDateEdit->setDisplayFormat("yyyy-MM-dd"); m_pMainLayout->addWidget(m_pDateEdit); } UICustomDateEditControl::~UICustomDateEditControl() { } void UICustomDateEditControl::setCurrentDate(const QDate& date) { m_pDateEdit->setDate(date); } QDate UICustomDateEditControl::getCurrentDate(void) { return m_pDateEdit->date(); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomDateEditControl.h ================================================ #ifndef UICUSTOMDATEEDITCONTROL_H #define UICUSTOMDATEEDITCONTROL_H #include "UICustomCombineControlBase.h" #include "UICustomSingleControl/UICustomDateEdit.h" #include "customcontrols_global.h" class CUSTOMCONTROLSSHARED_EXPORT UICustomDateEditControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomDateEditControl(QWidget* parent = nullptr); ~UICustomDateEditControl(); // 设置/获取日期 void setCurrentDate(const QDate& date); QDate getCurrentDate(void); private: UICutomDateEdit* m_pDateEdit = nullptr; }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomDoubleControl.cpp ================================================ #include "UICustomDoubleControl.h" #include "UICustomSingleControl/UICustomDoubleSpinBox.h" UICustomDoubleControl::UICustomDoubleControl(QWidget* parent) :UICustomCombineControlBase(parent) { // Double m_pDoubleSpinBox = new UICustomDoubleSpinBox; m_pMainLayout->addWidget(m_pDoubleSpinBox); m_pSlider = new QSlider(Qt::Horizontal); m_pSlider->setMinimum(0); m_pSlider->setMaximum(100); m_pMainLayout->addWidget(m_pSlider); setRangeValue(0, 1.0); m_pSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QObject::connect(m_pDoubleSpinBox, &UICustomDoubleSpinBox::editingFinished, \ this, &UICustomDoubleControl::onDoubleValueChanged); QObject::connect(m_pSlider, &QSlider::valueChanged, this, &UICustomDoubleControl::onSliderValueChanged); QObject::connect(m_pSlider, &QSlider::sliderPressed, this, &UICustomDoubleControl::onSliderPressed); QObject::connect(m_pSlider, &QSlider::sliderMoved, this, &UICustomDoubleControl::onSliderMoved); QObject::connect(m_pSlider, &QSlider::sliderReleased, this, &UICustomDoubleControl::onSliderReleased); this->setWidth(400); this->setHeight(30); } UICustomDoubleControl::~UICustomDoubleControl() { } void UICustomDoubleControl::setCurrentValue(qreal value) { if (value < m_qMinValue || value > m_qMaxValue) return; m_pDoubleSpinBox->setValue(value); int val = (value - m_qMinValue) * 1.0 / (m_qMaxValue - m_qMinValue) * 100; m_pSlider->blockSignals(true); m_pSlider->setValue(val); m_pSlider->blockSignals(false); } qreal UICustomDoubleControl::getCurrentValue(void) { return m_pDoubleSpinBox->value(); } void UICustomDoubleControl::setRangeValue(qreal minValue, qreal maxValue) { m_qMinValue = minValue; m_qMaxValue = maxValue; m_pDoubleSpinBox->setMinimum(m_qMinValue); m_pDoubleSpinBox->setMaximum(m_qMaxValue); } void UICustomDoubleControl::onSliderPressed(void) { m_beforeValue = m_pDoubleSpinBox->value(); qreal valus = getValuesBySlider(); m_pDoubleSpinBox->setValue(valus); emit valueChanged(valus); } void UICustomDoubleControl::onSliderMoved(void) { qreal valus = getValuesBySlider(); m_pDoubleSpinBox->setValue(valus); emit valueChanged(valus); } void UICustomDoubleControl::onSliderReleased(void) { qreal valus = getValuesBySlider(); m_pDoubleSpinBox->setValue(valus); emit valueChanged(m_beforeValue); emit valueChanged(valus, true); } void UICustomDoubleControl::onSliderValueChanged(int value) { qreal valus = getValuesBySlider(); m_pDoubleSpinBox->setValue(valus); emit valueChanged(valus); } qreal UICustomDoubleControl::getValuesBySlider(void) { int value = m_pSlider->value(); return m_qMinValue + (m_qMaxValue - m_qMinValue) * value * 1.0 / 100; } void UICustomDoubleControl::onDoubleValueChanged(void) { qreal value = m_pDoubleSpinBox->value(); int val = (value - m_qMinValue) * 1.0 / (m_qMaxValue - m_qMinValue) * 100; m_pSlider->blockSignals(true); m_pSlider->setValue(val); m_pSlider->blockSignals(false); emit valueChanged(value, true); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomDoubleControl.h ================================================ /** 基本组合控件-浮点值控件: 作者:Douzhq 日期:2020-01-22 个人博客:不会飞的纸飞机 www.douzhq.cn */ #ifndef UICUSTOMDOUBLECONTROL_H #define UICUSTOMDOUBLECONTROL_H #include "UICustomWidgtes/CustomWidget.h" #include "UICustomCombineControlBase.h" #include "customcontrols_global.h" #include #include #include class UICustomDoubleSpinBox; class CUSTOMCONTROLSSHARED_EXPORT UICustomDoubleControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomDoubleControl(QWidget* parent = nullptr); ~UICustomDoubleControl(); // 设置/获取当前值 void setCurrentValue(qreal value); qreal getCurrentValue(void); // 设置范围 void setRangeValue(qreal minValue, qreal maxValue); private: UICustomDoubleSpinBox* m_pDoubleSpinBox = nullptr; QSlider* m_pSlider = nullptr; qreal m_beforeValue = 0; qreal m_qMaxValue = 0; qreal m_qMinValue = 1; qreal getValuesBySlider(void); private slots: void onSliderPressed(void); void onSliderMoved(void); void onSliderReleased(void); void onSliderValueChanged(int value); void onDoubleValueChanged(void); signals: void valueChanged(qreal value, bool cmd = false); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomFontComboBoxControl.cpp ================================================ #include "UICustomFontComboBoxControl.h" #include UICustomFontComboBoxControl::UICustomFontComboBoxControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pComboBox = new QFontComboBox; m_pComboBox->setEditable(false); m_pComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pMainLayout->addWidget(m_pComboBox); this->setWidth(400); this->setHeight(30); } UICustomFontComboBoxControl::~UICustomFontComboBoxControl() { } ================================================ FILE: CustomControls/CustomCombineControl/UICustomFontComboBoxControl.h ================================================ #ifndef UICUSTOMFONTCOMBOBOXCONTROL_H #define UICUSTOMFONTCOMBOBOXCONTROL_H #include "UICustomCombineControlBase.h" #include "customwidgets_global.h" #include class QFontComboBox; class CUSTOMCONTROLSSHARED_EXPORT UICustomFontComboBoxControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomFontComboBoxControl(QWidget* parent = nullptr); ~UICustomFontComboBoxControl(); private: QFontComboBox* m_pComboBox = nullptr; }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomGroupControl.cpp ================================================ #include "UICustomGroupControl.h" #include "UICustomCore/CustomStyleConfig.h" #include #include #include UICustomGroupTitleItem::UICustomGroupTitleItem(QWidget* parent) :CustomWidget(parent) { g_StyleConfig->setCurrentStyle(this, "GroupTitle"); this->setMinimumHeight(30); } UICustomGroupTitleItem::~UICustomGroupTitleItem() { } void UICustomGroupTitleItem::mousePressEvent(QMouseEvent* event) { m_isExpanding = !m_isExpanding; this->update(); event->accept(); emit clickedTitle(m_isExpanding); } void UICustomGroupTitleItem::customPaint(QPainter* painter) { QTextOption o; o.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); QPen pen; pen.setColor(QColor(230, 230, 230)); painter->setPen(pen); int leftSpacing = 4; int drawMargin = 2; int expandWidth = 12; // 绘制展开 qreal topHeight = (this->rect().height() - expandWidth) / 2.0; QRectF spandRect(leftSpacing + drawMargin, topHeight, expandWidth, expandWidth); painter->drawRect(spandRect); QLineF line1(spandRect.x(), spandRect.center().y(), spandRect.right(), spandRect.center().y()); QLineF line2(spandRect.center().x(), spandRect.top(), spandRect.center().x(), spandRect.bottom()); painter->drawLine(line1); if (!m_isExpanding) painter->drawLine(line2); // 绘制Title qreal leftWidth = spandRect.x() + leftSpacing + drawMargin * 2 + expandWidth; QRectF rect(leftWidth, 0, this->width() - leftWidth, this->height()); painter->drawText(rect, m_cTitleName, o); } void UICustomGroupTitleItem::setTitleText(const QString& titleNameString) { m_cTitleName = titleNameString; this->update(); } QSize UICustomGroupTitleItem::sizeHint() const { QSize size(400, 30); return size; } // ----------------------------------------------------------------------------- // 组件内容 UICustomGroupContentItem::UICustomGroupContentItem(QWidget* parent) :CustomWidget(parent) { m_pLayout = new QVBoxLayout(this); m_pLayout->setMargin(2); m_pLayout->setSpacing(2); g_StyleConfig->setCurrentStyle(this, "GroupContent"); } UICustomGroupContentItem::~UICustomGroupContentItem() { } void UICustomGroupContentItem::addWidget(QWidget* widget) { m_pLayout->addWidget(widget); } void UICustomGroupContentItem::insertWidget(int index, QWidget* widget) { m_pLayout->insertWidget(index, widget); } QSize UICustomGroupContentItem::sizeHint() const { int count = m_pLayout->count(); // 高度 int height = 0; for (int i=0; iitemAt(i)->widget(); if (pWidget == nullptr) continue; height += pWidget->sizeHint().height(); } height += 4 + 2 * count; QSize size(400, height); return size; } // ----------------------------------------------------------------------------- UICustomGroupControl::UICustomGroupControl(QWidget* parent) :CustomWidget(parent) { m_pMainLayout = new QVBoxLayout(this); m_pMainLayout->setMargin(2); m_pMainLayout->setSpacing(0); m_pTitleItemWidget = new UICustomGroupTitleItem; m_pContentItemWidget = new UICustomGroupContentItem; m_pMainLayout->addWidget(m_pTitleItemWidget); m_pMainLayout->addWidget(m_pContentItemWidget); g_StyleConfig->setCurrentStyle(this, "GroupWidget"); QObject::connect(m_pTitleItemWidget, &UICustomGroupTitleItem::clickedTitle, \ this, &UICustomGroupControl::onClickedGroupTitleItem); } UICustomGroupControl::~UICustomGroupControl() { } void UICustomGroupControl::addContentWidget(QWidget* widget) { m_pContentItemWidget->addWidget(widget); } void UICustomGroupControl::insertContentWidget(int index, QWidget* widget) { m_pContentItemWidget->insertWidget(index, widget); } void UICustomGroupControl::setTitleText(const QString& string) { m_pTitleItemWidget->setTitleText(string); } void UICustomGroupControl::onClickedGroupTitleItem(bool isExpanded) { m_pContentItemWidget->setVisible(isExpanded); } QSize UICustomGroupControl::sizeHint() const { int height = 4; height += m_pTitleItemWidget->sizeHint().height(); if (m_pContentItemWidget->isVisible()) height += m_pContentItemWidget->sizeHint().height(); return QSize(400, height); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomGroupControl.h ================================================ #ifndef UICUSTOMGROUPCONTROL_H #define UICUSTOMGROUPCONTROL_H #include #include #include "UICustomWidgtes/CustomWidget.h" #include "customcontrols_global.h" class UICustomGroupTitleItem; class UICustomGroupContentItem; // 组控件 class CUSTOMCONTROLSSHARED_EXPORT UICustomGroupControl : public CustomWidget { Q_OBJECT public: UICustomGroupControl(QWidget* parent = nullptr); ~UICustomGroupControl(); // 添加内容 void addContentWidget(QWidget* widget); void insertContentWidget(int index, QWidget* widget); // 设置标题文本 void setTitleText(const QString& string); protected: virtual QSize sizeHint() const override; private: QVBoxLayout* m_pMainLayout = nullptr; UICustomGroupTitleItem* m_pTitleItemWidget = nullptr; UICustomGroupContentItem* m_pContentItemWidget = nullptr; private slots: void onClickedGroupTitleItem(bool isExpanded); }; // ----------------------------------------------------------------------------- // 标题 class UICustomGroupTitleItem : public CustomWidget { Q_OBJECT public: UICustomGroupTitleItem(QWidget* parent = nullptr); ~UICustomGroupTitleItem(); // 设置Title内容 void setTitleText(const QString& titleNameString); friend class UICustomGroupControl; protected: virtual void mousePressEvent(QMouseEvent* event) override; virtual void customPaint(QPainter* painter) override; virtual QSize sizeHint() const override; private: QString m_cTitleName; bool m_isExpanding = true; signals: void clickedTitle(bool isExpanded); }; // ----------------------------------------------------------------------------- // 组件内容 class UICustomGroupContentItem : public CustomWidget { Q_OBJECT public: UICustomGroupContentItem(QWidget* parent = nullptr); ~UICustomGroupContentItem(); void addWidget(QWidget* widget); void insertWidget(int index, QWidget* widget); friend class UICustomGroupControl; protected: virtual QSize sizeHint() const override; private: QVBoxLayout* m_pLayout = nullptr; }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomIntControl.cpp ================================================ #include "UICustomIntControl.h" #include "UICustomSingleControl/UICustomIntSpinBox.h" #include UICustomIntControl::UICustomIntControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pIntValue = new UICustomIntSpinBox; m_pMainLayout->addWidget(m_pIntValue); m_pSlider = new QSlider(Qt::Horizontal); m_pMainLayout->addWidget(m_pSlider); m_pSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setRangeValue(0, 100); m_pSlider->setMinimum(0); m_pSlider->setMaximum(100); QObject::connect(m_pIntValue, &UICustomIntSpinBox::editingFinished, \ this, &UICustomIntControl::onIntValueChanged); QObject::connect(m_pSlider, &QSlider::valueChanged, this, &UICustomIntControl::onSliderValueChanged); QObject::connect(m_pSlider, &QSlider::sliderPressed, this, &UICustomIntControl::onSliderPressed); QObject::connect(m_pSlider, &QSlider::sliderMoved, this, &UICustomIntControl::onSliderMoved); QObject::connect(m_pSlider, &QSlider::sliderReleased, this, &UICustomIntControl::onSliderReleased); this->setWidth(400); this->setHeight(30); } UICustomIntControl::~UICustomIntControl() { } void UICustomIntControl::setRangeValue(int minValue, int maxValue) { m_nMaxValue = maxValue; m_nMinValue = minValue; m_pIntValue->setMinimum(m_nMinValue); m_pIntValue->setMaximum(m_nMaxValue); } void UICustomIntControl::setCurrentValue(int value) { if (value < m_nMinValue || value > m_nMaxValue) return; m_pIntValue->setValue(value); int val = (value - m_nMinValue) * 1.0 / (m_nMaxValue - m_nMinValue) * 100; m_pSlider->blockSignals(true); m_pSlider->setValue(val); m_pSlider->blockSignals(false); } int UICustomIntControl::getCurrentValue(void) { return m_pIntValue->value(); } int UICustomIntControl::getValuesBySlider(void) { int value = m_pSlider->value(); return m_nMinValue + value * 1.0 / 100 * (m_nMaxValue - m_nMinValue); } void UICustomIntControl::onSliderPressed(void) { m_tempValue = m_pIntValue->value(); int value = getValuesBySlider(); m_pIntValue->setValue(value); emit valueChanged(value); } void UICustomIntControl::onSliderMoved(void) { int value = getValuesBySlider(); m_pIntValue->setValue(value); emit valueChanged(value); } void UICustomIntControl::onSliderReleased(void) { int value = getValuesBySlider(); m_pIntValue->setValue(value); emit valueChanged(m_tempValue); emit valueChanged(value, true); } void UICustomIntControl::onSliderValueChanged(int val) { int value = getValuesBySlider(); m_pIntValue->setValue(value); emit valueChanged(value); } void UICustomIntControl::onIntValueChanged(void) { int value = m_pIntValue->value(); m_pSlider->blockSignals(true); m_pSlider->setValue(value * 1.0 / (m_nMaxValue - m_nMinValue) * 100); m_pSlider->blockSignals(false); emit valueChanged(value, true); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomIntControl.h ================================================ /** 基本组合控件-整形值控件: 作者:Douzhq 日期:2020-01-22 个人博客:不会飞的纸飞机 www.douzhq.cn */ #ifndef UICUSTOMINTCONTROL_H #define UICUSTOMINTCONTROL_H #include "UICustomCombineControlBase.h" #include #include #include #include "customcontrols_global.h" class UICustomIntSpinBox; class CUSTOMCONTROLSSHARED_EXPORT UICustomIntControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomIntControl(QWidget* parent = nullptr); ~UICustomIntControl(); // 设置/获取当前的值 void setCurrentValue(int value); int getCurrentValue(void); // 设置范围 void setRangeValue(int minValue, int maxValue); private: UICustomIntSpinBox* m_pIntValue = nullptr; QSlider* m_pSlider = nullptr; int m_nMaxValue = 100; int m_nMinValue = 0; int m_tempValue = 0; int getValuesBySlider(void); private slots: void onSliderPressed(void); void onSliderMoved(void); void onSliderReleased(void); void onSliderValueChanged(int); void onIntValueChanged(void); signals: void valueChanged(int value, bool cmd = false); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomLineEditControl.cpp ================================================ #include "UICustomLineEditControl.h" UICustomLineEditControl::UICustomLineEditControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pLineEdit = new UICustomLineEdit; m_pMainLayout->addWidget(m_pLineEdit); m_pLineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pToolButton = new QToolButton; m_pMainLayout->addWidget(m_pToolButton); // 转发信后 QObject::connect(m_pLineEdit, &QLineEdit::textChanged, this, &UICustomLineEditControl::textChanged); QObject::connect(m_pLineEdit, &QLineEdit::editingFinished, this, &UICustomLineEditControl::editingFinished); QObject::connect(m_pToolButton, &QToolButton::clicked, this, &UICustomLineEditControl::clickedToolButton); this->setWidth(400); this->setHeight(30); } UICustomLineEditControl::~UICustomLineEditControl() { } // 设置按钮相关 void UICustomLineEditControl::setToolButtonVisible(bool isVisible) { m_pToolButton->setVisible(isVisible); } void UICustomLineEditControl::setToolButtonText(const QString& text) { m_pToolButton->setText(text); } void UICustomLineEditControl::setToolButtonIcon(const QIcon& icon) { m_pToolButton->setIcon(icon); } // 设置文本 void UICustomLineEditControl::setText(const QString& string) { m_pLineEdit->setText(string); } QString UICustomLineEditControl::getText(void) { return m_pLineEdit->text(); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomLineEditControl.h ================================================ #ifndef UICUSTOMLINEEDITCONTROL_H #define UICUSTOMLINEEDITCONTROL_H #include "UICustomCombineControlBase.h" #include "customcontrols_global.h" #include "UICustomSingleControl/UICustomLineEdit.h" #include #include #include class CUSTOMCONTROLSSHARED_EXPORT UICustomLineEditControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomLineEditControl(QWidget* parent = nullptr); ~UICustomLineEditControl(); // 设置按钮相关 void setToolButtonVisible(bool isVisible); void setToolButtonText(const QString& text); void setToolButtonIcon(const QIcon& icon); // 设置文本 void setText(const QString& string); QString getText(void); private: UICustomLineEdit* m_pLineEdit = nullptr; QToolButton* m_pToolButton = nullptr; signals: void clickedToolButton(void); void textChanged(const QString &text); void editingFinished(void); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomOrientationControl.cpp ================================================ #include "UICustomOrientationControl.h" #include "UICustomCore/CustomStyleConfig.h" #include #include #include UICustomOrientationItemWidget::UICustomOrientationItemWidget() { m_color = QColor(80, 80, 80); this->setFixedSize(30, 30); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } UICustomOrientationItemWidget::~UICustomOrientationItemWidget() { } void UICustomOrientationItemWidget::customPaint(QPainter* painter) { painter->setRenderHint(QPainter::Antialiasing); painter->fillRect(this->rect(), QBrush(m_color)); QPen nPen; nPen.setColor(QColor(230, 230, 230)); painter->setPen(nPen); if (m_isPressed) painter->drawEllipse(this->rect().adjusted(2, 2, -2, -2)); } void UICustomOrientationItemWidget::mousePressEvent(QMouseEvent* event) { m_isPressed = true; emit clickedItem(); event->accept(); } void UICustomOrientationItemWidget::setPressedStatus(bool status) { m_isPressed = status; m_color = QColor(60, 60, 60); this->update(); } QSize UICustomOrientationItemWidget::sizeHint() const { return CustomWidget::sizeHint(); QSize size(20, 20); return size; } // ----------------------------------------------------------------- UICustomOrientationWidget::UICustomOrientationWidget(QWidget* parent) :CustomWidget(parent) { QGridLayout* layout = new QGridLayout(this); layout->setSpacing(0); layout->setMargin(0); for (int i=0; i<9; ++i) { UICustomOrientationItemWidget* itemWidget = new UICustomOrientationItemWidget; m_items << itemWidget; layout->addWidget(itemWidget, i / 3, i % 3); if (i + 1 % 3 == 0) { QSpacerItem *spacerItem = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed); layout->addItem(spacerItem, i / 3, 3); } //itemWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QObject::connect(itemWidget, &UICustomOrientationItemWidget::clickedItem, \ this, &UICustomOrientationWidget::onClickedItem); } } UICustomOrientationWidget::~UICustomOrientationWidget() { } void UICustomOrientationWidget::onClickedItem(void) { UICustomOrientationItemWidget* pW = dynamic_cast(sender()); if (pW == nullptr) return; cleanAllItemsStatus(); pW->setPressedStatus(true); } void UICustomOrientationWidget::cleanAllItemsStatus(void) { for (auto iter = m_items.begin(); iter != m_items.end(); ++iter) (*iter)->setPressedStatus(false); } // ----------------------------------------------------------------- UICustomOrientationControl::UICustomOrientationControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pOrientationWidget = new UICustomOrientationWidget; m_pMainLayout->addWidget(m_pOrientationWidget); m_pOrientationWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //this->setFixedSize(200, 200); } UICustomOrientationControl::~UICustomOrientationControl() { } ================================================ FILE: CustomControls/CustomCombineControl/UICustomOrientationControl.h ================================================ #ifndef UICUSTOMORIENTATIONCONTROL_H #define UICUSTOMORIENTATIONCONTROL_H #include "UICustomWidgtes/CustomWidget.h" #include "UICustomCombineControlBase.h" #include "customcontrols_global.h" class UICustomOrientationItemWidget; class UICustomOrientationWidget; class CUSTOMCONTROLSSHARED_EXPORT UICustomOrientationControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomOrientationControl(QWidget* parent = nullptr); ~UICustomOrientationControl(); private: UICustomOrientationWidget* m_pOrientationWidget = nullptr; }; // ----------------------------------------------------------------- class UICustomOrientationItemWidget : public CustomWidget { Q_OBJECT public: UICustomOrientationItemWidget(); ~UICustomOrientationItemWidget(); void setPressedStatus(bool status); protected: virtual void customPaint(QPainter* painter) override; virtual void mousePressEvent(QMouseEvent* event) override; virtual QSize sizeHint() const override; private: bool m_isPressed = false; QColor m_color; signals: void clickedItem(void); }; // ----------------------------------------------------------------- class UICustomOrientationWidget : public CustomWidget { Q_OBJECT public: UICustomOrientationWidget(QWidget* parent = nullptr); ~UICustomOrientationWidget(); private: QList m_items; void cleanAllItemsStatus(void); private slots: void onClickedItem(void); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomPostionControl.cpp ================================================ #include "UICustomPostionControl.h" UICustomPostionControl::UICustomPostionControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pPostionWidget = new UICustomPostionWidget; m_pMainLayout->addWidget(m_pPostionWidget); this->setWidth(400); this->setHeight(150); QObject::connect(m_pPostionWidget, &UICustomPostionWidget::postionValueChanged, \ this, &UICustomPostionControl::postionValueChanged); } UICustomPostionControl::~UICustomPostionControl() { } // 设置当前映射的尺寸 void UICustomPostionControl::setCurrentMapSize(int width, int height) { m_nMapWidth = width; m_nMapHeight = height; } // 设置当前的位置 void UICustomPostionControl::setCurrentXPt(int xValue) { qreal val = xValue * 1.0 / m_nMapWidth * 100; m_pPostionWidget->setPostionXValue(val); } void UICustomPostionControl::setCurrentYPt(int yValue) { qreal val = yValue * 1.0 / m_nMapHeight * 100; m_pPostionWidget->setPostionYValue(val); } void UICustomPostionControl::setCurrentPostion(int xValue, int yValue) { qreal xVal = xValue * 1.0 / m_nMapWidth * 100; qreal yVal = yValue * 1.0 / m_nMapHeight * 100; m_pPostionWidget->setPostionValue(xVal, yVal); } // 获取当前位置 int UICustomPostionControl::getCurrentXPt(void) { qreal xVal = m_pPostionWidget->getPostionXValue(); return xVal / 100.0 * m_nMapWidth; } int UICustomPostionControl::getCurrentYPt(void) { qreal yVal = m_pPostionWidget->getPostionYValue(); return yVal / 100.0 * m_nMapHeight; } void UICustomPostionControl::getCurrentPostion(int& xValue, int& yValue) { qreal xVal, yVal; m_pPostionWidget->getPostionValue(xVal, yVal); xValue = xVal / 100.0 * m_nMapWidth; yValue = yVal / 100.0 * m_nMapHeight; } ================================================ FILE: CustomControls/CustomCombineControl/UICustomPostionControl.h ================================================ #ifndef UICUSTOMPOSTIONCONTROL_H #define UICUSTOMPOSTIONCONTROL_H #include "UICustomCombineControlBase.h" #include "UICustomSingleControl/UICustomPostionWidget.h" #include "customcontrols_global.h" #include class CUSTOMCONTROLSSHARED_EXPORT UICustomPostionControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomPostionControl(QWidget* parent = nullptr); ~UICustomPostionControl(); // 设置当前映射的尺寸 void setCurrentMapSize(int width, int height); // 设置当前的位置 void setCurrentXPt(int xValue); void setCurrentYPt(int yValue); void setCurrentPostion(int xValue, int yValue); // 获取当前位置 int getCurrentXPt(void); int getCurrentYPt(void); void getCurrentPostion(int& xValue, int& yValue); private: UICustomPostionWidget* m_pPostionWidget = nullptr; int m_nMapWidth = 100; int m_nMapHeight = 100; signals: void postionValueChanged(qreal xValue, qreal yValue); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomSwitchControl.cpp ================================================ #include "UICustomSwitchControl.h" UICustomSwitchControl::UICustomSwitchControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pSwitchWidget = new UICustomSwitchWidget; m_pMainLayout->addWidget(m_pSwitchWidget); m_pLabel = new QLabel; m_pMainLayout->addWidget(m_pLabel); m_pMainLayout->addStretch(); this->setWidth(400); this->setHeight(30); QObject::connect(m_pSwitchWidget, &UICustomSwitchWidget::valueChanged, \ this, &UICustomSwitchControl::valueChanged); } UICustomSwitchControl::~UICustomSwitchControl() { } // 设置/获取当前值 void UICustomSwitchControl::setCurrentValue(bool isOn, bool hasAnim) { m_pSwitchWidget->setSwitchStatus(isOn, hasAnim); } bool UICustomSwitchControl::getCurrentValue(void) { return m_pSwitchWidget->getSwitchStatus(); } void UICustomSwitchControl::setRightText(const QString& text) { m_pLabel->setText(text); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomSwitchControl.h ================================================ #ifndef UICUSTOMSWITCHCONTROL_H #define UICUSTOMSWITCHCONTROL_H #include "UICustomCombineControlBase.h" #include "UICustomSingleControl/UICustomSwitchWidget.h" #include "customcontrols_global.h" #include class CUSTOMCONTROLSSHARED_EXPORT UICustomSwitchControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomSwitchControl(QWidget* parent = nullptr); ~UICustomSwitchControl(); // 设置/获取当前值 void setCurrentValue(bool isOn, bool hasAnim = true); bool getCurrentValue(void); // 设置右侧文本 void setRightText(const QString& text); private: UICustomSwitchWidget* m_pSwitchWidget = nullptr; QLabel* m_pLabel = nullptr; signals: void valueChanged(bool isOn, bool cmd = false); }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomTextEditTagControl.cpp ================================================ #include "UICustomTextEditTagControl.h" #include UICustomTextEditTagControl::UICustomTextEditTagControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pTextEdit = new UICustomTextEdit; m_pTextEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); m_pMainLayout->addWidget(m_pTextEdit); } UICustomTextEditTagControl::~UICustomTextEditTagControl() { } QString UICustomTextEditTagControl::getCurrentText(void) { return m_pTextEdit->toPlainText(); } void UICustomTextEditTagControl::setCurrentText(const QString& text) { m_pTextEdit->clear(); m_pTextEdit->setPlainText(text); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomTextEditTagControl.h ================================================ #ifndef UICUSTOMTEXTEDITTAGCONTROL_H #define UICUSTOMTEXTEDITTAGCONTROL_H #include "UICustomSingleControl/UICustomTextEdit.h" #include "UICustomCombineControlBase.h" #include "customcontrols_global.h" #include class CUSTOMCONTROLSSHARED_EXPORT UICustomTextEditTagControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomTextEditTagControl(QWidget* parent = nullptr); ~UICustomTextEditTagControl(); // 获取当前文本 QString getCurrentText(void); void setCurrentText(const QString& text); private: UICustomTextEdit* m_pTextEdit = nullptr; }; #endif ================================================ FILE: CustomControls/CustomCombineControl/UICustomTimeEditControl.cpp ================================================ #include "UICustomTimeEditControl.h" UICustomTimeEditControl::UICustomTimeEditControl(QWidget* parent) :UICustomCombineControlBase(parent) { m_pTimeEdit = new UICustomTimeEdit; m_pTimeEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pMainLayout->addWidget(m_pTimeEdit); } UICustomTimeEditControl::~UICustomTimeEditControl() { } void UICustomTimeEditControl::setCurrentTime(const QTime& time) { m_pTimeEdit->setTime(time); } QTime UICustomTimeEditControl::getCurrentTime(void) { return m_pTimeEdit->time(); } ================================================ FILE: CustomControls/CustomCombineControl/UICustomTimeEditControl.h ================================================ #ifndef UICUSTOMTIMEEDITCONTROL_H #define UICUSTOMTIMEEDITCONTROL_H #include "UICustomCombineControlBase.h" #include "UICustomSingleControl/UICustomTimeEdit.h" #include "customcontrols_global.h" #include class CUSTOMCONTROLSSHARED_EXPORT UICustomTimeEditControl : public UICustomCombineControlBase { Q_OBJECT public: UICustomTimeEditControl(QWidget* parent = nullptr); ~UICustomTimeEditControl(); // 设置/获取当前时间 void setCurrentTime(const QTime& time); QTime getCurrentTime(void); private: UICustomTimeEdit* m_pTimeEdit = nullptr; }; #endif ================================================ FILE: CustomControls/CustomControls.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-01-13T22:28:08 # #------------------------------------------------- QT += widgets xml TARGET = CustomControls TEMPLATE = lib DEFINES += CUSTOMCONTROLS_LIBRARY # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS DESTDIR += $$PWD/../bin MOC_DIR += $$PWD/../CustomControls/temp OBJECTS_DIR += $$PWD/../CustomControls/temp CONFIG += c++11 LIBS += -L$$PWD/../bin -lCustomWidgets INCLUDEPATH += $$PWD/../CustomWidgets QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ CustomCombineControl/UICustomColorControl.cpp \ CustomCombineControl/UICustomCombineControlBase.cpp \ CustomCombineControl/UICustomComboBoxControl.cpp \ CustomCombineControl/UICustomDateEditControl.cpp \ CustomCombineControl/UICustomDoubleControl.cpp \ CustomCombineControl/UICustomFontComboBoxControl.cpp \ CustomCombineControl/UICustomGroupControl.cpp \ CustomCombineControl/UICustomIntControl.cpp \ CustomCombineControl/UICustomLineEditControl.cpp \ CustomCombineControl/UICustomOrientationControl.cpp \ CustomCombineControl/UICustomPostionControl.cpp \ CustomCombineControl/UICustomSwitchControl.cpp \ CustomCombineControl/UICustomTextEditTagControl.cpp \ CustomCombineControl/UICustomTimeEditControl.cpp \ UICurtomLeftBarControl/UICustomLeftItemWidget.cpp \ UICurtomLeftBarControl/UICustomLeftTabsControl.cpp \ UICurtomLeftBarControl/UICustomLeftWidget.cpp \ UICustomColorControl/UICustomColorCircle.cpp \ UICustomColorControl/UICustomColorSlider.cpp \ UICustomColorControl/UICustomColorSliderItem.cpp \ UICustomColorControl/UICustomColorWidget.cpp \ UICustomColorControl/UICustomCustomColorOperator.cpp \ UICustomColorControl/UICustonColorDialog.cpp \ UICustomSingleControl/UICustomCalendarWidget.cpp \ UICustomSingleControl/UICustomColorViewWidget.cpp \ UICustomSingleControl/UICustomComboBox.cpp \ UICustomSingleControl/UICustomDateEdit.cpp \ UICustomSingleControl/UICustomDoubleSpinBox.cpp \ UICustomSingleControl/UICustomImageViewer.cpp \ UICustomSingleControl/UICustomIntSpinBox.cpp \ UICustomSingleControl/UICustomLineEdit.cpp \ UICustomSingleControl/UICustomPostionWidget.cpp \ UICustomSingleControl/UICustomSwitchWidget.cpp \ UICustomSingleControl/UICustomTextEdit.cpp \ UICustomSingleControl/UICustomTimeEdit.cpp HEADERS += \ CustomCombineControl/UICustomColorControl.h \ CustomCombineControl/UICustomCombineControlBase.h \ CustomCombineControl/UICustomComboBoxControl.h \ CustomCombineControl/UICustomDateEditControl.h \ CustomCombineControl/UICustomDoubleControl.h \ CustomCombineControl/UICustomFontComboBoxControl.h \ CustomCombineControl/UICustomGroupControl.h \ CustomCombineControl/UICustomIntControl.h \ CustomCombineControl/UICustomLineEditControl.h \ CustomCombineControl/UICustomOrientationControl.h \ CustomCombineControl/UICustomPostionControl.h \ CustomCombineControl/UICustomSwitchControl.h \ CustomCombineControl/UICustomTextEditTagControl.h \ CustomCombineControl/UICustomTimeEditControl.h \ UICurtomLeftBarControl/UICustomLefTabsControl.h \ UICurtomLeftBarControl/UICustomLeftItemWidget.h \ UICurtomLeftBarControl/UICustomLeftWidget.h \ UICustomColorControl/UICustomColorCircle.h \ UICustomColorControl/UICustomColorSlider.h \ UICustomColorControl/UICustomColorSliderItem.h \ UICustomColorControl/UICustomColorWidget.h \ UICustomColorControl/UICustomCustomColorOperator.h \ UICustomColorControl/UICustonColorDialog.h \ UICustomSingleControl/UICustomCalendarWidget.h \ UICustomSingleControl/UICustomColorViewWidget.h \ UICustomSingleControl/UICustomComboBox.h \ UICustomSingleControl/UICustomDateEdit.h \ UICustomSingleControl/UICustomDoubleSpinBox.h \ UICustomSingleControl/UICustomImageViewer.h \ UICustomSingleControl/UICustomIntSpinBox.h \ UICustomSingleControl/UICustomLineEdit.h \ UICustomSingleControl/UICustomPostionWidget.h \ UICustomSingleControl/UICustomSwitchWidget.h \ UICustomSingleControl/UICustomTextEdit.h \ UICustomSingleControl/UICustomTimeEdit.h \ customcontrols_global.h unix { target.path = /usr/lib INSTALLS += target } ================================================ FILE: CustomControls/UICurtomLeftBarControl/UICustomLefTabsControl.h ================================================ #ifndef UICUSTOMLEFTTABSCONTROL_H #define UICUSTOMLEFTTABSCONTROL_H #include "UICustomWidgtes/CustomWidget.h" #include #include #include "customcontrols_global.h" class UICutomLeftWidget; class CUSTOMCONTROLSSHARED_EXPORT UICustomLeftTabsControl : public CustomWidget { Q_OBJECT public: UICustomLeftTabsControl(QWidget* parent = nullptr); ~UICustomLeftTabsControl(); // 添加元素 void addWidget(QWidget* widget, const QString& name, const QString& iconPath = ""); // 设置当前选中的Item void setCurrentSelectedItem(int index); private: QStackedWidget* m_pStackWidget = nullptr; UICutomLeftWidget* m_pLeftWidget = nullptr; private slots: void onClickedItem(int index); }; #endif ================================================ FILE: CustomControls/UICurtomLeftBarControl/UICustomLeftItemWidget.cpp ================================================ #include "UICustomLeftItemWidget.h" #include "UICustomCore/CustomStyleConfig.h" #include UICustomLeftItemWidget::UICustomLeftItemWidget(QWidget* parent) :CustomWidget(parent) { g_StyleConfig->setCurrentStyle(this, "LeftBarItem"); } UICustomLeftItemWidget::~UICustomLeftItemWidget() { } void UICustomLeftItemWidget::customPaint(QPainter* painter) { painter->save(); painter->setRenderHint(QPainter::Antialiasing); // 绘制选中矩形 if (m_isSelected) { painter->save(); painter->fillRect(QRect(0, 0, m_nLeftSeletedWidth, this->height()), \ QBrush(g_StyleConfig->getHighLightColor())); // 绘制三角形 QPolygon polygon; polygon << QPoint(this->width() - 4 * m_nArrowWidth, this->rect().center().y()) \ << QPoint(this->width(), this->rect().center().y() - 3 * m_nArrowWidth) \ << QPoint(this->width(), this->rect().center().y() + 3 * m_nArrowWidth); painter->setPen(Qt::NoPen); painter->setBrush(QColor(g_StyleConfig->getHighLightColor())); painter->drawPolygon(polygon); painter->restore(); } // 绘制图标 int nIconSize = this->height() - 2 * 2; if (!m_pixmap.isNull()) painter->drawPixmap(QRect(m_nLeftSeletedWidth + m_nInterval, 2, nIconSize, nIconSize), m_pixmap); // 绘制文字 int xPt = nIconSize + m_nLeftSeletedWidth + m_nInterval * 2; QRect textRect(xPt, 0, this->width() - xPt, this->height()); QTextOption o; o.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); painter->drawText(textRect, m_cString, o); painter->restore(); } void UICustomLeftItemWidget::mousePressEvent(QMouseEvent* event) { setSelected(true); this->update(); // 发送点击信号 emit clickedItem(); return CustomWidget::mousePressEvent(event); } QSize UICustomLeftItemWidget::sizeHint(void) const { return QSize(250, 50); } // 设置/获取是否被选中 void UICustomLeftItemWidget::setSelected(bool isSelected) { m_isSelected = isSelected; if (m_isSelected) g_StyleConfig->setCurrentStyle(this, "LeftBarItemSelected", true); else g_StyleConfig->setCurrentStyle(this, "LeftBarItem", true); this->update(); } bool UICustomLeftItemWidget::isSelected(void) { return m_isSelected; } // 设置/获取字符串 void UICustomLeftItemWidget::setText(const QString& name) { m_cString = name; this->update(); } QString UICustomLeftItemWidget::getText(void) { return m_cString; } void UICustomLeftItemWidget::setIcon(const QString& imageFile) { m_pixmap.load(imageFile); this->update(); } ================================================ FILE: CustomControls/UICurtomLeftBarControl/UICustomLeftItemWidget.h ================================================ #ifndef UICUSTOMLEFTITEMWIDGET_H #define UICUSTOMLEFTITEMWIDGET_H #include "UICustomWidgtes/CustomWidget.h" #include "customcontrols_global.h" #include class CUSTOMCONTROLSSHARED_EXPORT UICustomLeftItemWidget : public CustomWidget { Q_OBJECT public: UICustomLeftItemWidget(QWidget* parent = nullptr); ~UICustomLeftItemWidget(); // 设置/获取是否被选中 void setSelected(bool isSelected); bool isSelected(void); // 设置/获取字符串 void setText(const QString& name); QString getText(void); // 设置图标 void setIcon(const QString& imageFile); protected: void customPaint(QPainter* painter) override; void mousePressEvent(QMouseEvent* event) override; QSize sizeHint(void) const override; bool m_isSelected = false; QString m_cString; QPixmap m_pixmap; int m_nLeftSeletedWidth = 5; int m_nInterval = 2; int m_nArrowWidth = 4; signals: void clickedItem(void); }; #endif ================================================ FILE: CustomControls/UICurtomLeftBarControl/UICustomLeftTabsControl.cpp ================================================ #include "UICustomLefTabsControl.h" #include "UICustomLeftWidget.h" #include #include UICustomLeftTabsControl::UICustomLeftTabsControl(QWidget* parent) :CustomWidget(parent) { QHBoxLayout* mainLayout = new QHBoxLayout(this); mainLayout->setMargin(0); mainLayout->setSpacing(0); QSplitter* splitter = new QSplitter(Qt::Horizontal); mainLayout->addWidget(splitter); // 添加 左侧工具条 m_pLeftWidget = new UICutomLeftWidget; QObject::connect(m_pLeftWidget, &UICutomLeftWidget::clickedItem, \ this, &UICustomLeftTabsControl::onClickedItem); splitter->addWidget(m_pLeftWidget); // 添加右侧主要部分 m_pStackWidget = new QStackedWidget; splitter->addWidget(m_pStackWidget); // 设置 Handle Hover Attribute QSplitterHandle* handle = splitter->handle(1); if (handle != nullptr) handle->setAttribute(Qt::WA_Hover, true); } UICustomLeftTabsControl::~UICustomLeftTabsControl() { } void UICustomLeftTabsControl::addWidget(QWidget* widget, const QString& name, const QString& iconPath) { m_pLeftWidget->addItem(name, iconPath); m_pStackWidget->addWidget(widget); } void UICustomLeftTabsControl::setCurrentSelectedItem(int index) { m_pLeftWidget->setCurrentSelected(index); } void UICustomLeftTabsControl::onClickedItem(int index) { m_pStackWidget->setCurrentIndex(index); } ================================================ FILE: CustomControls/UICurtomLeftBarControl/UICustomLeftWidget.cpp ================================================ #include "UICustomLeftWidget.h" #include #include "UICustomLeftItemWidget.h" #include "UICustomCore/CustomStyleConfig.h" UICutomLeftWidget::UICutomLeftWidget(QWidget* parent) :CustomWidget(parent) { this->setMinimumWidth(250); this->setMaximumWidth(300); m_pMainLayout = new QVBoxLayout(this); m_pMainLayout->setMargin(4); m_pMainLayout->setSpacing(2); m_pMainLayout->addStretch(); g_StyleConfig->setCurrentStyle(this, "LeftBar"); } UICutomLeftWidget::~UICutomLeftWidget() { } void UICutomLeftWidget::addItem(const QString& name, const QString& iconPath) { UICustomLeftItemWidget* item = new UICustomLeftItemWidget; QObject::connect(item, &UICustomLeftItemWidget::clickedItem, this, &UICutomLeftWidget::onClickedItem); item->setText(name); if (!iconPath.isEmpty()) item->setIcon(iconPath); m_pMainLayout->insertWidget(m_items.count(), item); m_items << item; } void UICutomLeftWidget::cleanAllSelected(void) { foreach(auto item , m_items) item->setSelected(false); } void UICutomLeftWidget::onClickedItem(void) { UICustomLeftItemWidget* itemWidget = qobject_cast(sender()); if (itemWidget == nullptr) return; cleanAllSelected(); itemWidget->setSelected(true); // 查找点击的Item的索引 int index = 0; bool hasFinded = false; for (auto iter = m_items.begin(); iter != m_items.end(); ++iter) { if (itemWidget == *iter) { hasFinded = true; break; } index++; } // 发送点击信号 if (hasFinded) emit clickedItem(index); } void UICutomLeftWidget::setCurrentSelected(int index) { m_items[index]->setSelected(true); } ================================================ FILE: CustomControls/UICurtomLeftBarControl/UICustomLeftWidget.h ================================================ #ifndef UICUSTOMLEFTWIDGET_H #define UICUSTOMLEFTWIDGET_H #include "UICustomWidgtes/CustomWidget.h" #include class QVBoxLayout; class UICustomLeftItemWidget; class UICutomLeftWidget : public CustomWidget { Q_OBJECT public: UICutomLeftWidget(QWidget* parent = nullptr); ~UICutomLeftWidget(); // 添加元素 void addItem(const QString& name, const QString& iconPath = ""); // 清除所有选中 void cleanAllSelected(void); // 设置当前选中 void setCurrentSelected(int index); private: QVBoxLayout* m_pMainLayout = nullptr; QList m_items; private slots: void onClickedItem(void); signals: void clickedItem(int); }; #endif ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorCircle.cpp ================================================ #include "UICustomColorCircle.h" #include "UICustomCore/CustomStyleConfig.h" #include #include #include #include UICustomColorCircle::UICustomColorCircle(QWidget* parent) :CustomWidget(parent) { m_colorVec << QColor(255, 0, 0) << QColor(255, 255, 0) \ << QColor(0, 255, 0) << QColor(0, 255, 255) \ << QColor(0, 0, 255) << QColor(255, 0, 255); //this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } UICustomColorCircle::~UICustomColorCircle() { } void UICustomColorCircle::customPaint(QPainter* painter) { painter->setRenderHint(QPainter::Antialiasing); QConicalGradient conicalGradient(this->rect().center(), 0); qreal interval = 1.0 / m_colorVec.size(); // 设置渐变颜色 for (int i=0; isetBrush(conicalGradient); painter->setPen(QPen(Qt::NoPen)); int width = qMin(this->width(), this->height()) / 2 * 2; QRect centerRect(this->rect().center().x() - width / 2, \ this->rect().center().y() - width / 2, \ width, width); painter->drawEllipse(centerRect); // 绘制中间部分 centerRect.adjust(m_nCircleWidth, m_nCircleWidth, -m_nCircleWidth, -m_nCircleWidth); painter->setBrush(QColor(g_StyleConfig->getNormalBackgroundColor())); painter->drawEllipse(centerRect); // 绘制H选择圆圈 QPen nPen; nPen.setColor(QColor(0, 0, 0)); nPen.setWidth(2); painter->setPen(nPen); painter->setBrush(Qt::NoBrush); QVector2D vec(cos(m_nHValue / (180 / 3.1415926)), sin(m_nHValue / (180 / 3.1415926))); vec.normalize(); int length = centerRect.width() / 2 + m_nCircleWidth / 2; vec = vec * length; vec = QVector2D(this->rect().center().x() + vec.x(), this->rect().center().y() - vec.y()); painter->drawEllipse(QPoint(vec.x(), vec.y()), m_nCircleWidth / 5, m_nCircleWidth / 5); // 绘制中间矩形 int d = static_cast(sqrt(2) * centerRect.width() / 2); QRect rect(centerRect.center().x() - d / 2, centerRect.center().y() - d / 2, d, d); rect.adjust(2, 2, -2, -2); drawCenterRect(rect, painter); } void UICustomColorCircle::drawCenterRect(const QRect& rect, QPainter* painter) { painter->save(); QLinearGradient linearGradientH(rect.topLeft(), rect.topRight()); linearGradientH.setColorAt(0, QColor(255, 255, 255)); QColor color; color.setHsv(m_nHValue, 255, 255); linearGradientH.setColorAt(1, color); painter->fillRect(rect, linearGradientH); QLinearGradient linearGradientV(rect.topLeft(), rect.bottomLeft()); linearGradientV.setColorAt(0, QColor(0, 0, 0, 0)); linearGradientV.setColorAt(1, QColor(0, 0, 0, 255)); painter->fillRect(rect, linearGradientV); // 绘制选中的圈 int h, s, v; m_currentColor.getHsv(&h, &s, &v); qreal interValX = rect.width() * s * 1.0 / 255; qreal interValY = rect.height() * v * 1.0 / 255; QPoint centerPos(rect.bottomLeft().x() + interValX, rect.bottomLeft().y() - interValY); QPen nPen; nPen.setColor(QColor(0, 0, 0)); nPen.setWidth(2); painter->setPen(nPen); painter->setBrush(Qt::NoBrush); painter->drawEllipse(centerPos, m_nCircleWidth / 5, m_nCircleWidth / 5); painter->restore(); } qreal UICustomColorCircle::distance(QPoint p1, QPoint p2) { return sqrt((p1.x() - p2.x()) * (p1.x() - p2.x()) + (p1.y() - p2.y()) * (p1.y() - p2.y())); } int UICustomColorCircle::getHValue(QPoint pos) { QPoint centerPos = this->rect().center(); QVector2D vec = QVector2D(pos) - QVector2D(centerPos); vec.normalize(); float angle = acos(vec.x()); int value = static_cast(angle * (180 / 3.1415926)); if (pos.y() > centerPos.y()) value = 360 - value; return value; } void UICustomColorCircle::updateCurrentColor(QPoint pos) { int width = qMin(this->width(), this->height()) / 2 * 2; QRect centerRect(this->rect().center().x() - width / 2, \ this->rect().center().y() - width / 2, \ width, width); centerRect.adjust(m_nCircleWidth, m_nCircleWidth, -m_nCircleWidth, -m_nCircleWidth); int d = static_cast(sqrt(2) * centerRect.width() / 2); QRect rect(centerRect.center().x() - d / 2, centerRect.center().y() - d / 2, d, d); rect.adjust(2, 2, -2, -2); int sValue = qMin(static_cast((pos.x() - rect.x()) * 1.0 / rect.width() * 255), 255); int vValue = qMin(static_cast((rect.bottom() - pos.y()) * 1.0 / rect.height() * 255), 255); sValue = qMax(sValue, 0); vValue = qMax(vValue, 0); m_currentColor.setHsv(m_nHValue, sValue, vValue); } QColor UICustomColorCircle::getCurrentColor(void) { int h, s, v; m_currentColor.getHsv(&h, &s, &v); m_currentColor.setHsv(m_nHValue, s, v); return m_currentColor; } void UICustomColorCircle::setCurrentColor(const QColor& color) { m_currentColor = color; int h, s, v; m_currentColor.getHsv(&h, &s, &v); m_nHValue = h; this->update(); } void UICustomColorCircle::resizeEvent(QResizeEvent* event) { int width = qMin(this->size().width(), this->size().height()); m_nCircleWidth = static_cast(width / 8.0); return CustomWidget::resizeEvent(event); } void UICustomColorCircle::mousePressEvent(QMouseEvent* event) { m_selectMode = Normal; QPoint pos = event->pos(); int width = qMin(this->width(), this->height()) / 2 * 2; QRect centerRect(this->rect().center().x() - width / 2, \ this->rect().center().y() - width / 2, \ width, width); qreal distance1 = distance(this->rect().center(), pos); qreal distance2 = abs(centerRect.topLeft().x() - this->rect().center().x()); // 判断是否选中圆环 centerRect.adjust(m_nCircleWidth, m_nCircleWidth, -m_nCircleWidth, -m_nCircleWidth); qreal distance3 = abs(centerRect.topLeft().x() - this->rect().center().x()); if (distance1 > distance3 && distance1 < distance2) m_selectMode = Circle; // 判断是否选中中间矩形 int d = static_cast(sqrt(2) * centerRect.width() / 2); QRect rect(centerRect.center().x() - d / 2, centerRect.center().y() - d / 2, d, d); rect.adjust(2, 2, -2, -2); if (rect.contains(pos)) m_selectMode = Rect; if (m_selectMode == Circle) { m_nHValue = getHValue(pos); emit colorChanged(); this->update(); } else if (m_selectMode == Rect) { updateCurrentColor(pos); emit colorChanged(); this->update(); } return CustomWidget::mousePressEvent(event); } void UICustomColorCircle::mouseReleaseEvent(QMouseEvent* event) { QPoint pos = event->pos(); if (m_selectMode == Circle) { m_nHValue = getHValue(pos); emit colorChanged(); this->update(); } else if (m_selectMode == Rect) { updateCurrentColor(pos); emit colorChanged(); this->update(); } m_selectMode = Normal; return CustomWidget::mouseReleaseEvent(event); } void UICustomColorCircle::mouseMoveEvent(QMouseEvent* event) { QPoint pos = event->pos(); if (m_selectMode == Circle) { m_nHValue = getHValue(pos); emit colorChanged(); this->update(); } else if (m_selectMode == Rect) { updateCurrentColor(pos); emit colorChanged(); this->update(); } return CustomWidget::mouseMoveEvent(event); } QSize UICustomColorCircle::sizeHint() const { QSize size(250, 250); return size; } ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorCircle.h ================================================ #ifndef UICUSTOMCOLORRANGE_H #define UICUSTOMCOLORRANGE_H #include "UICustomWidgtes/CustomWidget.h" class UICustomColorCircle : public CustomWidget { Q_OBJECT public: UICustomColorCircle(QWidget* parent = nullptr); ~UICustomColorCircle(); enum SelectedMode { Normal, // 未选中状态 Circle, // 圆环选中状态 Rect // 矩形区域选中状态 }; // 设置/获取当前颜色 QColor getCurrentColor(void); void setCurrentColor(const QColor& color); protected: void customPaint(QPainter* painter) override; void resizeEvent(QResizeEvent* event) override; QSize sizeHint() const override; void mousePressEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; private: int m_nCircleWidth = 30; int m_nHValue = 0; QVector m_colorVec; SelectedMode m_selectMode = Normal; QColor m_currentColor; // 绘制中心矩形 void drawCenterRect(const QRect& rect, QPainter* painter); // 获取两点之间的距离 qreal distance(QPoint p1, QPoint p2); // 根据点的位置或者角度 int getHValue(QPoint pos); // 更新当前颜色值显示 void updateCurrentColor(QPoint pos); signals: void colorChanged(void); }; #endif ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorSlider.cpp ================================================ #include "UICustomColorSlider.h" UICustomColorSlider::UICustomColorSlider(QWidget *parent) :UICustomCombineControlBase(parent) { m_pColorSliderItem = new UICustomColorSliderItem; m_pValueSpixBox = new UICustomIntSpinBox; m_pMainLayout->addWidget(m_pValueSpixBox); m_pMainLayout->addWidget(m_pColorSliderItem); m_pColorSliderItem->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); this->setColumnWidth(0, 40); QObject::connect(m_pColorSliderItem, &UICustomColorSliderItem::changedValue, \ this, &UICustomColorSlider::onChangedValue); QObject::connect(m_pColorSliderItem, &UICustomColorSliderItem::changedValue, \ this, &UICustomColorSlider::valueChanged); QObject::connect(m_pValueSpixBox, &UICustomIntSpinBox::editingFinished, [&](void){ emit valueChanged(m_pValueSpixBox->value()); }); } UICustomColorSlider::~UICustomColorSlider() { } void UICustomColorSlider::setValueRange(int minValue, int maxValue) { m_pValueSpixBox->setMinimum(minValue); m_pValueSpixBox->setMaximum(maxValue); m_nMinValue = minValue; m_nMaxValue = maxValue; } // 设置开始颜色 void UICustomColorSlider::setStartColor(const QColor& startColor) { m_pColorSliderItem->setStartColor(startColor); } // 设置结束颜色 void UICustomColorSlider::setEndColor(const QColor& endColor) { m_pColorSliderItem->setEndColor(endColor); } void UICustomColorSlider::onChangedValue(int value) { int val = (m_nMaxValue - m_nMinValue) * value * 1.0 / 100; m_pValueSpixBox->setValue(val); } // 设置当前值 void UICustomColorSlider::setCurrentValue(int value) { if (value < m_nMinValue || value > m_nMaxValue) return; m_pValueSpixBox->setValue(value); int val = (value - m_nMinValue) * 1.0 / (m_nMaxValue - m_nMinValue) * 100; m_pColorSliderItem->setCurrentValue(val); } // 获取当前值 int UICustomColorSlider::getCurrentValue(void) { return m_pValueSpixBox->value(); } // 设置是否为H void UICustomColorSlider::setHVisible(bool isVisible) { m_pColorSliderItem->setHVisible(isVisible); } ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorSlider.h ================================================ #ifndef UICUSTOMCOLORSLIDER_H #define UICUSTOMCOLORSLIDER_H #include "UICustomWidgtes/CustomWidget.h" #include "UICustomColorSliderItem.h" #include "CustomCombineControl/UICustomCombineControlBase.h" #include "UICustomSingleControl/UICustomColorViewWidget.h" #include "UICustomSingleControl/UICustomIntSpinBox.h" class UICustomColorSlider : public UICustomCombineControlBase { Q_OBJECT public: UICustomColorSlider(QWidget *parent = nullptr); ~UICustomColorSlider(); // 设置 最小值、最大值 void setValueRange(int minValue, int maxValue); // 设置开始颜色 void setStartColor(const QColor& startColor); // 设置结束颜色 void setEndColor(const QColor& endColor); // 设置当前值 void setCurrentValue(int value); // 获取当前值 int getCurrentValue(void); // 设置是否为H void setHVisible(bool isVisible); private: UICustomColorSliderItem* m_pColorSliderItem = nullptr; UICustomIntSpinBox* m_pValueSpixBox = nullptr; int m_nMinValue = 0; int m_nMaxValue = 100; private slots: void onChangedValue(int value); signals: void valueChanged(int value); }; #endif ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorSliderItem.cpp ================================================ #include "UICustomColorSliderItem.h" #include #include UICustomColorSliderItem::UICustomColorSliderItem(QWidget* parent) :CustomWidget(parent) , m_cStartColor(255, 0, 0) , m_cEndColor(0, 255, 0) { m_colorVec << QColor(255, 0, 0) << QColor(255, 255, 0) \ << QColor(0, 255, 0) << QColor(0, 255, 255) \ << QColor(0, 0, 255) << QColor(255, 0, 255); } UICustomColorSliderItem::~UICustomColorSliderItem() { } void UICustomColorSliderItem::customPaint(QPainter* painter) { painter->save(); painter->setRenderHint(QPainter::Antialiasing); QRect rect = this->rect().adjusted(m_nMargin + m_nSliderWidth / 2 - m_nInterVal, m_nMargin, \ -(m_nMargin + m_nSliderWidth / 2 - m_nInterVal), \ -m_nMargin - m_nSliderHeight); // 绘制边框 painter->setPen(QPen(QColor(200, 200, 200))); painter->drawRoundedRect(rect, 4, 4); // 绘制渐变 rect = rect.adjusted(m_nInterVal, m_nInterVal, -m_nInterVal, -m_nInterVal); QLinearGradient linerGradient(rect.topLeft(), rect.topRight()); if (m_isHValueSlider) { for (int i=0; isetPen(Qt::NoPen); painter->setBrush(linerGradient); painter->drawRoundedRect(rect, 4, 4); // 绘制滑动三角形手柄 painter->setBrush(QColor(220, 220, 220)); qreal xPt = m_nCurrentValue * 1.0 / (m_nMaxValue - m_nMinValue) * rect.width() + rect.x(); QPoint currentPos(xPt, rect.bottom() + m_nInterVal + 1); QPolygon polygon; polygon << currentPos << QPoint(currentPos.x() - m_nSliderWidth / 2, currentPos.y() + m_nSliderHeight) \ << QPoint(currentPos.x() + m_nSliderWidth / 2, currentPos.y() + m_nSliderHeight); painter->drawPolygon(polygon); painter->restore(); } void UICustomColorSliderItem::mousePressEvent(QMouseEvent* event) { QRect rect = this->rect().adjusted(m_nMargin + m_nSliderWidth / 2 - m_nInterVal, m_nMargin, \ -(m_nMargin + m_nSliderWidth / 2 - m_nInterVal), \ -m_nMargin - m_nSliderHeight); rect = rect.adjusted(m_nInterVal, m_nInterVal, -m_nInterVal, -m_nInterVal); qreal xPt = m_nCurrentValue * 1.0 / (m_nMaxValue - m_nMinValue) * rect.width() + rect.x(); QPoint currentPos(xPt, rect.bottom() + m_nInterVal + 1); QPolygon polygon; polygon << currentPos << QPoint(currentPos.x() - m_nSliderWidth / 2, currentPos.y() + m_nSliderHeight) \ << QPoint(currentPos.x() + m_nSliderWidth / 2, currentPos.y() + m_nSliderHeight); // 判断是否选中 m_isSelected = false; QPoint pos = event->pos(); if (rect.contains(pos)) m_isSelected = true; else if (polygon.containsPoint(pos, Qt::OddEvenFill)) m_isSelected = true; if (m_isSelected) selectedPoint(pos); } void UICustomColorSliderItem::mouseMoveEvent(QMouseEvent* event) { QPoint pos = event->pos(); if (m_isSelected) selectedPoint(pos); } void UICustomColorSliderItem::mouseReleaseEvent(QMouseEvent* event) { QPoint pos = event->pos(); if (m_isSelected) selectedPoint(pos); m_isSelected = false; } QSize UICustomColorSliderItem::sizeHint() const { QSize size(200, 30); return size; } void UICustomColorSliderItem::selectedPoint(const QPoint& pos) { QRect rect = this->rect().adjusted(m_nMargin + m_nSliderWidth / 2 - m_nInterVal, m_nMargin, \ -(m_nMargin + m_nSliderWidth / 2 - m_nInterVal), \ -m_nMargin - m_nSliderHeight); rect = rect.adjusted(m_nInterVal, m_nInterVal, -m_nInterVal, -m_nInterVal); int value = (pos.x() - rect.x()) * 1.0 / rect.width() * (m_nMaxValue - m_nMinValue) + m_nMinValue; value = qMax(value, m_nMinValue); value = qMin(value, m_nMaxValue); m_nCurrentValue = value; // 发送信号 emit changedValue(m_nCurrentValue); this->update(); } // 设置开始颜色 void UICustomColorSliderItem::setStartColor(const QColor& startColor) { m_cStartColor = startColor; this->update(); } // 设置结束颜色 void UICustomColorSliderItem::setEndColor(const QColor& endColor) { m_cEndColor = endColor; this->update(); } // 设置当前选中的值 void UICustomColorSliderItem::setCurrentValue(int value) { m_nCurrentValue = value; this->update(); } // 获取当前选中值 int UICustomColorSliderItem::getCurrentValue(void) { return m_nCurrentValue; } void UICustomColorSliderItem::setHVisible(bool isVisible) { m_isHValueSlider = isVisible; } ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorSliderItem.h ================================================ #ifndef UICUSTOMCOLORSLIDERITEM_H #define UICUSTOMCOLORSLIDERITEM_H #include #include "UICustomWidgtes/CustomWidget.h" class QColor; class UICustomColorSliderItem : public CustomWidget { Q_OBJECT public: UICustomColorSliderItem(QWidget* parent = nullptr); ~UICustomColorSliderItem(); // 设置开始颜色 void setStartColor(const QColor& startColor); // 设置结束颜色 void setEndColor(const QColor& endColor); // 设置当前选中的值 void setCurrentValue(int value); // 获取当前选中值 int getCurrentValue(void); // 设置是否为H void setHVisible(bool isVisible); protected: void customPaint(QPainter* painter) override; void mousePressEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; QSize sizeHint() const override; private: int m_nMargin = 1; int m_nSliderWidth = 12; // 滑块宽度 int m_nSliderHeight = 10; // 滑块高度 int m_nInterVal = 4; int m_nCurrentValue = 0; // 当前选中数值 int m_nMinValue = 0; // 最小值 int m_nMaxValue = 100; // 最大值 QColor m_cStartColor; // 开始颜色 QColor m_cEndColor; // 结束颜色 QVector m_colorVec; bool m_isHValueSlider = false; bool m_isSelected = false; // 根据点更新显示 void selectedPoint(const QPoint& pos); signals: void changedValue(int value); }; #endif ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorWidget.cpp ================================================ #include "UICustomColorWidget.h" #include #include #include UICustomColorWidget::UICustomColorWidget(QWidget* parent) :CustomWidget(parent) ,m_currentColor(0, 0, 0) { // CustomColor m_pCustomColorOperator = new UICustomCustomColorOperator(this); m_pLayout = new QVBoxLayout(this); m_pLayout->setSpacing(0); QWidget* pW = new QWidget; pW->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pLayout->addWidget(pW); m_pColorCircle = new UICustomColorCircle; m_pColorCircle->setFixedSize(300, 300); m_pMainLayout = new QHBoxLayout(pW); m_pMainLayout->setMargin(0); initColorCircle(); initColorSliderWidget(); initColorButtonWidget(); QObject::connect(m_pColorCircle, &UICustomColorCircle::colorChanged, \ this, &UICustomColorWidget::onColorChanged); } UICustomColorWidget::~UICustomColorWidget() { } void UICustomColorWidget::initColorCircle(void) { QWidget* widget = new QWidget; m_pMainLayout->addWidget(widget); QVBoxLayout* layout = new QVBoxLayout(widget); layout->setMargin(2); layout->addWidget(m_pColorCircle); } void UICustomColorWidget::initColorSliderWidget(void) { QWidget* widget = new QWidget; widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_pMainLayout->addWidget(widget); QVBoxLayout* layout = new QVBoxLayout(widget); layout->setMargin(0); layout->setSpacing(2); initColorRGBSliderWidget(); initColorHSVSliderWidget(); layout->addWidget(m_pRGBGroup); layout->addWidget(m_pHSVGroup); layout->addStretch(); } void UICustomColorWidget::initColorHSVSliderWidget(void) { m_pHSVGroup = new QGroupBox("HSV"); QVBoxLayout *playout = new QVBoxLayout(m_pHSVGroup); m_pHSlider = new UICustomColorSlider; m_pHSlider->setTagText("H: "); m_pHSlider->setHVisible(true); m_pHSlider->setValueRange(0, 359); playout->addWidget(m_pHSlider); QObject::connect(m_pHSlider, &UICustomColorSlider::valueChanged, \ this, &UICustomColorWidget::onHSVSliderColorChanged); m_pSSlider = new UICustomColorSlider; m_pSSlider->setTagText("S: "); m_pSSlider->setValueRange(0, 255); playout->addWidget(m_pSSlider); QObject::connect(m_pSSlider, &UICustomColorSlider::valueChanged, \ this, &UICustomColorWidget::onHSVSliderColorChanged); m_pVSlider = new UICustomColorSlider; m_pVSlider->setTagText("V: "); m_pVSlider->setValueRange(0, 255); playout->addWidget(m_pVSlider); QObject::connect(m_pVSlider, &UICustomColorSlider::valueChanged, \ this, &UICustomColorWidget::onHSVSliderColorChanged); } void UICustomColorWidget::initColorButtonWidget(void) { QWidget* bottomWidget = new QWidget; bottomWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QHBoxLayout* mainLayout = new QHBoxLayout(bottomWidget); mainLayout->setMargin(0); // 添加自定义颜色 initColorCustomWidget(); mainLayout->addWidget(m_pCustomGroup); m_pColorView = new UICustomColorViewWidget; m_pColorView->setDragVisible(true); m_pColorView->setFixedSize(120, 120); mainLayout->addWidget(m_pColorView); QVBoxLayout *bottomLayout = new QVBoxLayout; bottomLayout->addStretch(); // 添加到自定义按钮 QPushButton* addButton = new QPushButton(tr("AddToCustom")); addButton->setFixedSize(120, 30); bottomLayout->addWidget(addButton); QObject::connect(addButton, &QPushButton::clicked, this, &UICustomColorWidget::onClickedAddCustomColor); // 确定按钮 QPushButton* okButton = new QPushButton(tr("OK")); okButton->setFixedSize(120, 30); bottomLayout->addWidget(okButton); QObject::connect(okButton, &QPushButton::clicked, this, &UICustomColorWidget::clickedOKButton); // 取消按钮 QPushButton* cannelButton = new QPushButton(tr("Cannel")); cannelButton->setFixedSize(120, 30); bottomLayout->addWidget(cannelButton); mainLayout->addLayout(bottomLayout); QObject::connect(cannelButton, &QPushButton::clicked, this, &UICustomColorWidget::clickedCannelButton); m_pLayout->addWidget(bottomWidget); } void UICustomColorWidget::initColorCustomWidget(void) { m_pCustomGroup = new QGroupBox(tr("Custom Color")); QGridLayout *layout = new QGridLayout(m_pCustomGroup); layout->setMargin(0); layout->setSpacing(0); for (int i=0; i<14; ++i) { UICustomColorViewWidget* colorView = new UICustomColorViewWidget; colorView->setAcceptDrops(true); colorView->setFixedSize(70, 30); layout->addWidget(colorView, i / (14 / 2), i % (14 / 2)); m_colorViewsList << colorView; // 点击时,设置颜色 QObject::connect(colorView, &UICustomColorViewWidget::mousePressed, \ this, &UICustomColorWidget::onClickedColorView); QObject::connect(colorView, &UICustomColorViewWidget::dropSignal, \ this, &UICustomColorWidget::onDropSignal); } // 保存到文件 loadCustomColor(); } // 点击自定义颜色 void UICustomColorWidget::onClickedColorView(void) { UICustomColorViewWidget* pColorView = dynamic_cast(sender()); if (pColorView == nullptr) return; // 清除选择 for (auto iter = m_colorViewsList.begin(); iter != m_colorViewsList.end(); ++iter) (*iter)->setSelected(false); // 设置选中 pColorView->setSelected(true); // 设置当前的颜色 QColor color = pColorView->getCurrentColor(); setCurrentColor(color); } void UICustomColorWidget::onClickedAddCustomColor(void) { // 设置选中的为当前颜色 for (auto iter = m_colorViewsList.begin(); iter != m_colorViewsList.end(); ++iter) { bool isSelected = (*iter)->getSelected(); if (isSelected) { (*iter)->setCurrentColor(m_currentColor); break; } } // 保存到文件 saveCustomColor(); } void UICustomColorWidget::onDropSignal(void) { // 保存到文件 saveCustomColor(); } void UICustomColorWidget::initColorRGBSliderWidget(void) { m_pRGBGroup = new QGroupBox("RGB"); QVBoxLayout *playout = new QVBoxLayout(m_pRGBGroup); m_pRedSlider = new UICustomColorSlider; m_pRedSlider->setTagText("R: "); playout->addWidget(m_pRedSlider); m_pRedSlider->setValueRange(0, 255); m_pRedSlider->setStartColor(QColor(0, m_currentColor.green(), m_currentColor.blue())); m_pRedSlider->setEndColor(QColor(255, m_currentColor.green(), m_currentColor.blue())); QObject::connect(m_pRedSlider, &UICustomColorSlider::valueChanged, \ this, &UICustomColorWidget::onSliderColorChanged); m_pGreenSlider = new UICustomColorSlider; m_pGreenSlider->setTagText("G: "); playout->addWidget(m_pGreenSlider); m_pGreenSlider->setValueRange(0, 255); m_pGreenSlider->setStartColor(QColor(m_currentColor.red(), 0, m_currentColor.blue())); m_pGreenSlider->setEndColor(QColor(m_currentColor.red(), 255, m_currentColor.blue())); QObject::connect(m_pGreenSlider, &UICustomColorSlider::valueChanged, \ this, &UICustomColorWidget::onSliderColorChanged); m_pBlueSlider = new UICustomColorSlider; m_pBlueSlider->setTagText("B: "); playout->addWidget(m_pBlueSlider); m_pBlueSlider->setValueRange(0, 255); m_pBlueSlider->setStartColor(QColor(m_currentColor.red(), m_currentColor.green(), 0)); m_pBlueSlider->setEndColor(QColor(m_currentColor.red(), m_currentColor.green(), 255)); QObject::connect(m_pBlueSlider, &UICustomColorSlider::valueChanged, \ this, &UICustomColorWidget::onSliderColorChanged); } void UICustomColorWidget::onColorChanged(void) { QColor color = m_pColorCircle->getCurrentColor(); m_pColorView->setCurrentColor(color); m_currentColor = color; // 更新Color颜色显示 updateForColorSlider(); updateForColorSliderValue(); } void UICustomColorWidget::onSliderColorChanged(void) { int rValue = m_pRedSlider->getCurrentValue(); int gValue = m_pGreenSlider->getCurrentValue(); int bValue = m_pBlueSlider->getCurrentValue(); QColor color(rValue, gValue, bValue); m_pColorCircle->setCurrentColor(color); m_pColorView->setCurrentColor(color); m_currentColor = color; // 更新Color颜色显示 updateForColorSlider(); updateForColorSliderValue(); } void UICustomColorWidget::onHSVSliderColorChanged(void) { int h = m_pHSlider->getCurrentValue(); int s = m_pSSlider->getCurrentValue(); int v = m_pVSlider->getCurrentValue(); QColor color; color.setHsv(h, s, v); m_pColorCircle->setCurrentColor(color); m_pColorView->setCurrentColor(color); m_currentColor = color; // 更新Color颜色显示 updateForColorSlider(); updateForColorSliderValue(); } void UICustomColorWidget::updateForColorSlider(void) { m_pRedSlider->setStartColor(QColor(0, m_currentColor.green(), m_currentColor.blue())); m_pRedSlider->setEndColor(QColor(255, m_currentColor.green(), m_currentColor.blue())); m_pGreenSlider->setStartColor(QColor(m_currentColor.red(), 0, m_currentColor.blue())); m_pGreenSlider->setEndColor(QColor(m_currentColor.red(), 255, m_currentColor.blue())); m_pBlueSlider->setStartColor(QColor(m_currentColor.red(), m_currentColor.green(), 0)); m_pBlueSlider->setEndColor(QColor(m_currentColor.red(), m_currentColor.green(), 255)); // s int h, s, v; m_currentColor.getHsv(&h, &s, &v); QColor startColor, endColor; startColor.setHsv(h, 0, v); endColor.setHsv(h, 255, v); m_pSSlider->setStartColor(startColor); m_pSSlider->setEndColor(endColor); // v startColor.setHsv(h, s, 0); endColor.setHsv(h, s, 255); m_pVSlider->setStartColor(startColor); m_pVSlider->setEndColor(endColor); } void UICustomColorWidget::updateForColorSliderValue(void) { m_pRedSlider->setCurrentValue(m_currentColor.red()); m_pGreenSlider->setCurrentValue(m_currentColor.green()); m_pBlueSlider->setCurrentValue(m_currentColor.blue()); int h, s, v; m_currentColor.getHsv(&h, &s, &v); m_pHSlider->setCurrentValue(h); m_pSSlider->setCurrentValue(s); m_pVSlider->setCurrentValue(v); } // 保存和加载 void UICustomColorWidget::saveCustomColor(void) { QList colors; for (auto iter = m_colorViewsList.begin(); iter != m_colorViewsList.end(); ++iter) { QColor color = (*iter)->getCurrentColor(); colors << color; } m_pCustomColorOperator->saveCustomColors(colors); } void UICustomColorWidget::loadCustomColor(void) { QList colors; m_pCustomColorOperator->loadCustonColors(colors); int count = 0; for (auto iter = colors.begin(); iter != colors.end(); ++iter) m_colorViewsList[count++]->setCurrentColor(*iter); } // 设置/获取当前的颜色 void UICustomColorWidget::setCurrentColor(const QColor& color) { m_currentColor = color; m_pColorCircle->setCurrentColor(color); m_pColorView->setCurrentColor(color); // 更新Color颜色显示 updateForColorSlider(); updateForColorSliderValue(); } QColor UICustomColorWidget::getCurrentColor(void) { return m_currentColor; } ================================================ FILE: CustomControls/UICustomColorControl/UICustomColorWidget.h ================================================ #ifndef UICUSTOMCOLORWIDGET_H #define UICUSTOMCOLORWIDGET_H #include "UICustomWidgtes/CustomWidget.h" #include "UICustomColorCircle.h" #include "UICustomColorSlider.h" #include "UICustomSingleControl/UICustomColorViewWidget.h" #include "UICustomCustomColorOperator.h" #include #include class QHBoxLayout; class UICustomColorWidget : public CustomWidget { Q_OBJECT public: UICustomColorWidget(QWidget* parent = nullptr); ~UICustomColorWidget(); // 设置/获取当前的颜色 void setCurrentColor(const QColor& color); QColor getCurrentColor(void); private: UICustomColorCircle* m_pColorCircle = nullptr; void initColorCircle(void); void initColorSliderWidget(void); void initColorRGBSliderWidget(void); void initColorHSVSliderWidget(void); void initColorButtonWidget(void); void initColorCustomWidget(void); QGroupBox* m_pRGBGroup = nullptr; QGroupBox* m_pHSVGroup = nullptr; QGroupBox* m_pCustomGroup = nullptr; UICustomColorSlider* m_pRedSlider = nullptr; UICustomColorSlider* m_pGreenSlider = nullptr; UICustomColorSlider* m_pBlueSlider = nullptr; UICustomColorSlider* m_pHSlider = nullptr; UICustomColorSlider* m_pSSlider = nullptr; UICustomColorSlider* m_pVSlider = nullptr; UICustomColorViewWidget* m_pColorView = nullptr; QVector m_colorViewsList; UICustomCustomColorOperator* m_pCustomColorOperator = nullptr; QColor m_currentColor; // 根据滑条,更新显示 void updateForColorSlider(void); void updateForColorSliderValue(void); // 保存和加载 void saveCustomColor(void); void loadCustomColor(void); private: QHBoxLayout* m_pMainLayout = nullptr; QVBoxLayout* m_pLayout = nullptr; private slots: void onColorChanged(void); void onSliderColorChanged(void); void onHSVSliderColorChanged(void); // 点击自定义颜色 void onClickedColorView(void); // 点击添加自定义颜色 void onClickedAddCustomColor(void); // 处理自定义颜色信号 void onDropSignal(void); signals: void clickedOKButton(void); void clickedCannelButton(void); }; #endif ================================================ FILE: CustomControls/UICustomColorControl/UICustomCustomColorOperator.cpp ================================================ #include "UICustomCustomColorOperator.h" #include #include #include #include const QString UICustomCustomColorOperator::m_cFileName = "./CustomColor.xml"; UICustomCustomColorOperator::UICustomCustomColorOperator(QObject* parent) :QObject(parent) { } UICustomCustomColorOperator::~UICustomCustomColorOperator() { } // 保存和加载颜色 void UICustomCustomColorOperator::saveCustomColors(const QList& colors) { QString curAppPath = qApp->applicationDirPath() + "/"; QFile file(curAppPath + m_cFileName); if (file.exists()) file.remove(); QDomDocument doc; //写入xml头部 QDomProcessingInstruction instruction; //添加处理命令 instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); doc.appendChild(instruction); // 添加颜色 QDomElement rootElement = doc.createElement("CustomColor"); doc.appendChild(rootElement); for (auto iter = colors.begin(); iter != colors.end(); ++iter) { QDomElement element = doc.createElement("Color"); element.setAttribute("red", iter->red()); element.setAttribute("green", iter->green()); element.setAttribute("blue", iter->blue()); rootElement.appendChild(element); } QFile xmlFile(curAppPath + m_cFileName); xmlFile.open(QFile::WriteOnly); QTextStream out_stream(&xmlFile); doc.save(out_stream, 4); xmlFile.close(); } void UICustomCustomColorOperator::loadCustonColors(QList& colors) { colors.clear(); // open file QString curAppPath = qApp->applicationDirPath() + "/"; QFile file(curAppPath + m_cFileName); if (!file.open(QFile::ReadOnly)) return; QDomDocument doc; if (!doc.setContent(&file)) { file.close(); return; } file.close(); // root element QDomElement root = doc.documentElement(); if (root.tagName() != "CustomColor") return; // nodeList QDomNodeList nodeList = root.childNodes(); for (int i = 0; i < nodeList.count(); ++i) { QDomElement element = nodeList.at(i).toElement(); QColor color; color.setRed(element.attribute("red").toInt()); color.setGreen(element.attribute("green").toInt()); color.setBlue(element.attribute("blue").toInt()); colors.append(color); } } ================================================ FILE: CustomControls/UICustomColorControl/UICustomCustomColorOperator.h ================================================ #ifndef UICUSTOMCUSTOMCOLOROPERATOR_H #define UICUSTOMCUSTOMCOLOROPERATOR_H #include #include #include #include class UICustomCustomColorOperator : public QObject { Q_OBJECT public: UICustomCustomColorOperator(QObject* parent = nullptr); ~UICustomCustomColorOperator(); // 保存和加载颜色 void saveCustomColors(const QList& colors); void loadCustonColors(QList& colors); private: static const QString m_cFileName; }; #endif ================================================ FILE: CustomControls/UICustomColorControl/UICustonColorDialog.cpp ================================================ #include "UICustonColorDialog.h" UICustomColorDialog::UICustomColorDialog(QWidget* parent) :CustomDialog(parent) { init(); QObject::connect(m_pColorWidget, &UICustomColorWidget::clickedOKButton, \ this, &UICustomColorDialog::accept); QObject::connect(m_pColorWidget, &UICustomColorWidget::clickedCannelButton, \ this, &UICustomColorDialog::reject); } UICustomColorDialog::~UICustomColorDialog() { } void UICustomColorDialog::init(void) { m_pColorWidget = new UICustomColorWidget; this->setContentWidget(m_pColorWidget); this->setWindowTitle(tr("Color Config")); } // 设置/获取颜色 void UICustomColorDialog::setCurrentColor(const QColor& color) { m_pColorWidget->setCurrentColor(color); } QColor UICustomColorDialog::getCurrentColor(void) { return m_pColorWidget->getCurrentColor(); } ================================================ FILE: CustomControls/UICustomColorControl/UICustonColorDialog.h ================================================ #ifndef UICUSTOMCONTROLDIALOG_H #define UICUSTOMCONTROLDIALOG_H #include "UICustomWidgtes/CustomDialog.h" #include "UICustomColorWidget.h" #include class UICustomColorDialog : public CustomDialog { Q_OBJECT public: UICustomColorDialog(QWidget* parent = nullptr); ~UICustomColorDialog(); // 设置/获取颜色 void setCurrentColor(const QColor& color); QColor getCurrentColor(void); private: UICustomColorWidget* m_pColorWidget = nullptr; void init(void); }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomCalendarWidget.cpp ================================================ #include "UICustomCalendarWidget.h" UICustomCalendarWidget::UICustomCalendarWidget(QWidget* parent) :QCalendarWidget(parent) { } UICustomCalendarWidget::~UICustomCalendarWidget() { } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomCalendarWidget.h ================================================ #ifndef UICUSTOMCALENDARWIDGET_H #define UICUSTOMCALENDARWIDGET_H #include class UICustomCalendarWidget : public QCalendarWidget { Q_OBJECT public: UICustomCalendarWidget(QWidget* parent = nullptr); ~UICustomCalendarWidget(); }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomColorViewWidget.cpp ================================================ #include "UICustomColorViewWidget.h" #include "UICustomCore/CustomStyleConfig.h" #include #include #include #include UICustomColorViewWidget::UICustomColorViewWidget(QWidget* parent) :CustomWidget(parent) , m_selectedColor(g_StyleConfig->getHighLightColor()) { g_StyleConfig->setCurrentStyle(this, "Transparent"); this->setAcceptDrops(false); } UICustomColorViewWidget::~UICustomColorViewWidget() { } void UICustomColorViewWidget::customPaint(QPainter* painter) { painter->save(); painter->setRenderHint(QPainter::Antialiasing); if (m_isSelected) { QPen pen; pen.setColor(m_selectedColor); pen.setWidth(2); painter->setPen(pen); } else painter->setPen(Qt::NoPen); painter->setBrush(QBrush(m_currentColor)); painter->drawRoundedRect(this->rect().adjusted(2, 2, -2, -2), 4, 4); painter->restore(); } QSize UICustomColorViewWidget::sizeHint() const { QSize size(80, 30); return size; } void UICustomColorViewWidget::mousePressEvent(QMouseEvent* event) { if (m_isDragVisible) { QDrag *drag = new QDrag(this); QMimeData *mineData = new QMimeData; mineData->setColorData(m_currentColor); drag->setMimeData(mineData); drag->exec(); } else { event->accept(); emit mousePressed(); } } void UICustomColorViewWidget::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasColor()) event->acceptProposedAction(); emit dragEnterSignals(); } void UICustomColorViewWidget::dragLeaveEvent(QDragLeaveEvent *event) { emit dragReleaseSignals(); } void UICustomColorViewWidget::dragMoveEvent(QDragMoveEvent *event) { } void UICustomColorViewWidget::dropEvent(QDropEvent *event) { if (!event->mimeData()->hasColor()) return; // 设置当前颜色 QColor color = qvariant_cast(event->mimeData()->colorData()); this->setCurrentColor(color); emit dropSignal(); } void UICustomColorViewWidget::setCurrentColor(const QColor& color) { m_currentColor = color; this->update(); } const QColor& UICustomColorViewWidget::getCurrentColor(void) { return m_currentColor; } void UICustomColorViewWidget::setDragVisible(bool isVisible) { m_isDragVisible = isVisible; } void UICustomColorViewWidget::setSelected(bool isSelected) { m_isSelected = isSelected; this->update(); } bool UICustomColorViewWidget::getSelected(void) { return m_isSelected; } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomColorViewWidget.h ================================================ #ifndef UICUSTOMCOLORVIEWWIDGET_H #define UICUSTOMCOLORVIEWWIDGET_H #include "UICustomWidgtes/CustomWidget.h" #include class UICustomColorViewWidget : public CustomWidget { Q_OBJECT public: UICustomColorViewWidget(QWidget* parent = nullptr); ~UICustomColorViewWidget(); // 设置/获取当前显示的颜色 void setCurrentColor(const QColor& color); const QColor& getCurrentColor(void); // 设置是否允许拖拽 void setDragVisible(bool isVisible); // 设置是否被选择 void setSelected(bool isSelected); bool getSelected(void); protected: virtual void customPaint(QPainter* painter) override; virtual QSize sizeHint() const override; virtual void mousePressEvent(QMouseEvent* event) override; virtual void dragEnterEvent(QDragEnterEvent *event) override; virtual void dragLeaveEvent(QDragLeaveEvent *event) override; virtual void dragMoveEvent(QDragMoveEvent *event) override; virtual void dropEvent(QDropEvent *event) override; private: QColor m_currentColor; QColor m_selectedColor; bool m_isDragVisible = false; bool m_isSelected = false; signals: void mousePressed(void); void dragEnterSignals(void); void dragReleaseSignals(void); void dropSignal(void); }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomComboBox.cpp ================================================ #include "UICustomComboBox.h" #include UICustomComboBox::UICustomComboBox(QWidget* parent) :QComboBox(parent) { this->setView(new QListView(this)); } UICustomComboBox::~UICustomComboBox() { } QSize UICustomComboBox::sizeHint(void) const { QSize size(80, 30); return size; } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomComboBox.h ================================================ #ifndef UICUSTOMCOMBOBOX_H #define UICUSTOMCOMBOBOX_H #include class UICustomComboBox : public QComboBox { Q_OBJECT public: UICustomComboBox(QWidget* parent = nullptr); ~UICustomComboBox() override; protected: QSize sizeHint(void) const override; }; #endif // UICUSTOMCOMBOBOX_H ================================================ FILE: CustomControls/UICustomSingleControl/UICustomDateEdit.cpp ================================================ #include "UICustomDateEdit.h" #include "UICustomCalendarWidget.h" UICutomDateEdit::UICutomDateEdit(QWidget* parent) :QDateEdit(parent) { this->setCalendarPopup(true); this->setCalendarWidget(new UICustomCalendarWidget); } UICutomDateEdit::~UICutomDateEdit() { } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomDateEdit.h ================================================ #ifndef UICUSTOMDATEEDIT_H #define UICUSTOMDATEEDIT_H #include class UICutomDateEdit : public QDateEdit { Q_OBJECT public: UICutomDateEdit(QWidget* parent = nullptr); ~UICutomDateEdit(); }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomDoubleSpinBox.cpp ================================================ #include "UICustomDoubleSpinBox.h" #include UICustomDoubleSpinBox::UICustomDoubleSpinBox(QWidget* parent) :QDoubleSpinBox(parent) { } UICustomDoubleSpinBox::~UICustomDoubleSpinBox() { } QSize UICustomDoubleSpinBox::sizeHint() const { QSize size(80, 30); return size; } void UICustomDoubleSpinBox::keyPressEvent(QKeyEvent* event) { QDoubleSpinBox::keyPressEvent(event); event->accept(); } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomDoubleSpinBox.h ================================================ #ifndef UICUSTOMDOUBLESPINBOX_H #define UICUSTOMDOUBLESPINBOX_H #include #include class UICustomDoubleSpinBox : public QDoubleSpinBox { Q_OBJECT public: UICustomDoubleSpinBox(QWidget* parent = nullptr); ~UICustomDoubleSpinBox(); protected: virtual QSize sizeHint() const override; void keyPressEvent(QKeyEvent* event) override; }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomImageViewer.cpp ================================================ #include "UICustomImageViewer.h" #include #include #include UICustomImageViewer::UICustomImageViewer(QWidget* parent) :QWidget(parent) { this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } UICustomImageViewer::~UICustomImageViewer() { } void UICustomImageViewer::loadImage(const QString& imagePath) { QImage image(imagePath); m_pixmap = QPixmap::fromImage(image); this->update(); } void UICustomImageViewer::loadImage(const QImage& image) { m_pixmap = QPixmap::fromImage(image); this->update(); } void UICustomImageViewer::paintEvent(QPaintEvent* event) { if (m_pixmap.isNull()) return; QPainter npainter(this); QPainter* painter = &npainter; QRect rect = this->rect().adjusted(m_nMargin, m_nMargin, -m_nMargin, -m_nMargin); painter->save(); // 平移 painter->translate(QPoint(rect.center().x() + m_nIntervalX, rect.center().y() + m_nIntervalY)); // 缩放 painter->scale(m_zoomRate, m_zoomRate); // 计算实际显示大小 int imageWidth = m_pixmap.width(); imageWidth = qMin(rect.width(), imageWidth); int imageHeight = imageWidth * 1.0 / (m_pixmap.width() * 1.0 / m_pixmap.height()); imageHeight = qMin(rect.height(), imageHeight); imageWidth = imageHeight * (m_pixmap.width() * 1.0 / m_pixmap.height()); QRect pixRect(-imageWidth / 2, -imageHeight / 2, imageWidth, imageHeight); painter->drawPixmap(pixRect, m_pixmap); painter->restore(); } void UICustomImageViewer::wheelEvent(QWheelEvent *event) { int value = event->delta(); if (value > 0) m_zoomRate += 0.2; else m_zoomRate -= 0.2; if (m_zoomRate < 0.5) m_zoomRate = 0.5; this->update(); } void UICustomImageViewer::mousePressEvent(QMouseEvent* event) { m_isMousePressed = true; m_tempPos = event->pos(); } void UICustomImageViewer::mouseMoveEvent(QMouseEvent* event) { if (!m_isMousePressed) return; this->setCursor(Qt::SizeAllCursor); QPoint pos = event->pos(); m_nIntervalX += pos.x() - m_tempPos.x(); m_nIntervalY += pos.y() - m_tempPos.y(); m_tempPos = pos; this->update(); } void UICustomImageViewer::mouseReleaseEvent(QMouseEvent* event) { m_isMousePressed = false; this->setCursor(Qt::ArrowCursor); } QSize UICustomImageViewer::sizeHint() const { QSize size(600, 600); return size; } // 缩放 void UICustomImageViewer::zoom(qreal value) { m_zoomRate = value; this->update(); } qreal UICustomImageViewer::getZoomValue(void) { return m_zoomRate; } // 复位 void UICustomImageViewer::rest(void) { m_zoomRate = 1.0; m_nIntervalX = 0; m_nIntervalY = 0; this->update(); } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomImageViewer.h ================================================ #ifndef UICUSTOMIMAGEVIEWER_H #define UICUSTOMIMAGEVIEWER_H #include #include "UICustomWidgtes/CustomWidget.h" #include "customcontrols_global.h" class CUSTOMCONTROLSSHARED_EXPORT UICustomImageViewer : public QWidget { Q_OBJECT public: UICustomImageViewer(QWidget* parent = nullptr); ~UICustomImageViewer(); // 加载图片 void loadImage(const QString& imagePath); void loadImage(const QImage& image); // 缩放 void zoom(qreal value); qreal getZoomValue(void); // 复位 void rest(void); protected: void paintEvent(QPaintEvent* event) override; void wheelEvent(QWheelEvent* event) override; void mousePressEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; QSize sizeHint() const override; private: QPixmap m_pixmap; int m_nMargin = 2; // 缩放系数 qreal m_zoomRate = 1.0; // 移动 int m_nIntervalX = 0; int m_nIntervalY = 0; bool m_isMousePressed = false; QPoint m_tempPos; }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomIntSpinBox.cpp ================================================ #include "UICustomIntSpinBox.h" #include UICustomIntSpinBox::UICustomIntSpinBox(QWidget* parent) :QSpinBox(parent) { } UICustomIntSpinBox::~UICustomIntSpinBox() { } QSize UICustomIntSpinBox::sizeHint() const { QSize size(80, 30); return size; } void UICustomIntSpinBox::keyPressEvent(QKeyEvent* event) { QSpinBox::keyPressEvent(event); event->accept(); } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomIntSpinBox.h ================================================ #ifndef UICUSTOMINTSPINBOX_H #define UICUSTOMINTSPINBOX_H #include #include #include "customcontrols_global.h" class CUSTOMCONTROLSSHARED_EXPORT UICustomIntSpinBox : public QSpinBox { Q_OBJECT public: UICustomIntSpinBox(QWidget* parent = nullptr); ~UICustomIntSpinBox(); protected: virtual QSize sizeHint() const override; void keyPressEvent(QKeyEvent* event) override; }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomLineEdit.cpp ================================================ #include "UICustomLineEdit.h" #include #include #include #include #include "UICustomCore/CustomStyleConfig.h" UICustomLineEdit::UICustomLineEdit(QWidget* parent) :QLineEdit(parent) { m_pButton = new UICustomCloseButton; m_pButton->setFixedSize(12, 12); QHBoxLayout* mainLayout = new QHBoxLayout(this); mainLayout->addStretch(); mainLayout->addWidget(m_pButton, 0, Qt::AlignRight | Qt::AlignVCenter); setCloseButtonEnable(false); // 关联信号和槽 QObject::connect(this, &UICustomLineEdit::textChanged, this, &UICustomLineEdit::onTextChanged); QObject::connect(m_pButton, &UICustomCloseButton::clicked, this, &UICustomLineEdit::onCloseButtonClicked); } UICustomLineEdit::~UICustomLineEdit() { } void UICustomLineEdit::keyPressEvent(QKeyEvent* event) { QLineEdit::keyPressEvent(event); event->accept(); } void UICustomLineEdit::setCloseButtonEnable(bool isEnabled) { m_isToolButtonEnable = isEnabled; if (!isEnabled) m_pButton->setVisible(false); } void UICustomLineEdit::onTextChanged(const QString& textChanged) { if (!m_isToolButtonEnable) { emit currentTextChanged(textChanged); return; } if (textChanged.isEmpty()) m_pButton->setVisible(false); else m_pButton->setVisible(true); emit currentTextChanged(textChanged); } void UICustomLineEdit::onCloseButtonClicked(void) { this->setText(""); } // ============================================================== UICustomCloseButton::UICustomCloseButton(QWidget* parent) :CustomWidget(parent) { this->setMouseTracking(true); g_StyleConfig->setCurrentStyle(this, "TransparentBgWidget"); } UICustomCloseButton::~UICustomCloseButton() { } void UICustomCloseButton::customPaint(QPainter* painter) { QColor penColor(200, 80, 80); if (m_isHoveredOn) penColor = QColor(200, 200, 200); // 设置画笔 QPen pen; pen.setWidth(2); pen.setColor(penColor); pen.setCapStyle(Qt::RoundCap); painter->setPen(pen); // 绘制关闭 QRect rect = this->rect(); rect.adjust(2, 2, -2, -2); painter->drawLine(rect.topLeft(), rect.bottomRight()); painter->drawLine(rect.topRight(), rect.bottomLeft()); } void UICustomCloseButton::mousePressEvent(QMouseEvent *event) { emit clicked(); CustomWidget::mousePressEvent(event); } void UICustomCloseButton::enterEvent(QEvent *event) { m_isHoveredOn = true; this->setCursor(Qt::PointingHandCursor); this->update(); CustomWidget::enterEvent(event); } void UICustomCloseButton::leaveEvent(QEvent *event) { m_isHoveredOn = false; this->setCursor(Qt::ArrowCursor); this->update(); CustomWidget::leaveEvent(event); } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomLineEdit.h ================================================ #ifndef UICUSTOMLINEEDIT_H #define UICUSTOMLINEEDIT_H #include #include #include "UICustomWidgtes/CustomWidget.h" #include "customcontrols_global.h" class UICustomCloseButton; class CUSTOMCONTROLSSHARED_EXPORT UICustomLineEdit : public QLineEdit { Q_OBJECT public: UICustomLineEdit(QWidget* parent = nullptr); ~UICustomLineEdit() override; // Close Button Visible void setCloseButtonEnable(bool isEnabled); protected: void keyPressEvent(QKeyEvent* event) override; private: UICustomCloseButton* m_pButton = nullptr; bool m_isToolButtonEnable = false; signals: void currentTextChanged(const QString& text); private slots: void onTextChanged(const QString& textChanged); void onCloseButtonClicked(void); }; // ============================================================== class UICustomCloseButton : public CustomWidget { Q_OBJECT public: UICustomCloseButton(QWidget* parent = nullptr); ~UICustomCloseButton(); protected: void customPaint(QPainter* painter) override; void mousePressEvent(QMouseEvent *event) override; void enterEvent(QEvent *event) override; void leaveEvent(QEvent *event) override; signals: void clicked(void); private: bool m_isHoveredOn = false; }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomPostionWidget.cpp ================================================ #include "UICustomPostionWidget.h" #include "UICustomCore/CustomStyleConfig.h" #include #include UICustomPostionWidget::UICustomPostionWidget(QWidget* parent) :CustomWidget(parent) { this->setMouseTracking(true); g_StyleConfig->setCurrentStyle(this, "Transparent"); } UICustomPostionWidget::~UICustomPostionWidget() { } void UICustomPostionWidget::customPaint(QPainter* painter) { QPoint pos = transToThisPostion(); painter->save(); painter->setPen(QPen(g_StyleConfig->getHighLightColor())); painter->setRenderHint(QPainter::Antialiasing); // 绘制矩形 QRect rect = this->rect().adjusted(m_nRadius, m_nRadius, -m_nRadius, -m_nRadius); painter->drawRect(rect); // 绘制位置 painter->setPen(QPen(QColor(230, 230, 230))); painter->drawEllipse(pos, m_nRadius, m_nRadius); painter->restore(); } QSize UICustomPostionWidget::sizeHint() const { QSize size(150, 150); return size; } void UICustomPostionWidget::mousePressEvent(QMouseEvent* event) { m_isPressed = true; QPoint pos = event->pos(); transToThisValue(pos); this->update(); } void UICustomPostionWidget::mouseMoveEvent(QMouseEvent* event) { if (!m_isPressed) return; QPoint pos = event->pos(); transToThisValue(pos); this->update(); } void UICustomPostionWidget::mouseReleaseEvent(QMouseEvent* event) { if (!m_isPressed) return; m_isPressed = false; QPoint pos = event->pos(); transToThisValue(pos); this->update(); } QPoint UICustomPostionWidget::transToThisPostion(void) { QRect rect = this->rect().adjusted(m_nRadius, m_nRadius, -m_nRadius, -m_nRadius); qreal xPt = m_xValue / 100.0 * rect.width() + rect.x(); qreal yPt = m_yValue / 100.0 * rect.height() + rect.y(); QPoint pos; pos.setX(xPt); pos.setY(yPt); return pos; } void UICustomPostionWidget::transToThisValue(QPoint pos) { QRect rect = this->rect().adjusted(m_nRadius, m_nRadius, -m_nRadius, -m_nRadius); if (!rect.contains(pos)) return; m_xValue = (pos.x() - rect.x()) * 1.0 / rect.width() * 100; m_yValue = (pos.y() - rect.y()) * 1.0 / rect.height() * 100; emit postionValueChanged(m_xValue, m_yValue); } void UICustomPostionWidget::setPostionValue(qreal xValue, qreal yValue) { m_xValue = xValue; m_yValue = yValue; this->update(); } void UICustomPostionWidget::setPostionXValue(qreal xValue) { m_xValue = xValue; this->update(); } void UICustomPostionWidget::setPostionYValue(qreal yValue) { m_yValue = yValue; this->update(); } void UICustomPostionWidget::getPostionValue(qreal& xValue, qreal &yValue) { xValue = m_xValue; yValue = m_yValue; } qreal UICustomPostionWidget::getPostionXValue(void) { return m_xValue; } qreal UICustomPostionWidget::getPostionYValue(void) { return m_yValue; } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomPostionWidget.h ================================================ #ifndef UICUSTOMPOSTIONWIDGET_H #define UICUSTOMPOSTIONWIDGET_H #include "UICustomWidgtes/CustomWidget.h" #include "customcontrols_global.h" #include class CUSTOMCONTROLSSHARED_EXPORT UICustomPostionWidget : public CustomWidget { Q_OBJECT public: UICustomPostionWidget(QWidget* parent = nullptr); ~UICustomPostionWidget(); // 设置位置 void setPostionValue(qreal xValue, qreal yValue); void setPostionXValue(qreal xValue); void setPostionYValue(qreal yValue); // 获取位置 void getPostionValue(qreal& xValue, qreal &yValue); qreal getPostionXValue(void); qreal getPostionYValue(void); protected: // Custom Paint Event void customPaint(QPainter* painter) override; QSize sizeHint() const override; void mousePressEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; private: bool m_isPressed = false; int m_nRadius = 4; qreal m_xValue = 0; // 百分比值 qreal m_yValue = 0; QPoint transToThisPostion(void); void transToThisValue(QPoint pos); signals: void postionValueChanged(qreal xValue, qreal yValue); }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomSwitchWidget.cpp ================================================ #include "UICustomSwitchWidget.h" #include "UICustomCore/CustomStyleConfig.h" #include UICustomSwitchWidget::UICustomSwitchWidget(QWidget* parent) :CustomWidget(parent) ,m_margin(1, 1, 1, 1) ,m_cBgColor(223, 105, 20) ,m_cSliderColor(243, 125, 40) , m_cOnBgColor(155, 78, 15) , m_cOnSliderColor(226, 105, 5) , m_cOffBgColor(138, 138, 138) , m_cOffSliderColor(160, 160, 160) { g_StyleConfig->setCurrentStyle(this, "Transparent"); this->setCursor(Qt::PointingHandCursor); setSwitchStatus(true, false); m_pTimer = new QTimer; m_pTimer->setInterval(20); QObject::connect(m_pTimer, &QTimer::timeout, this, &UICustomSwitchWidget::onTimeout); } UICustomSwitchWidget::~UICustomSwitchWidget() { } void UICustomSwitchWidget::setSwitchStatus(bool isOn, bool hasAnimation, bool cmd) { if (isOn) { m_cBgColor = m_cOnBgColor; m_cSliderColor = m_cOnSliderColor; } else { m_cBgColor = m_cOffBgColor; m_cSliderColor = m_cOffSliderColor; } if (m_isSwitchOn != isOn) { m_isSwitchOn = isOn; emit valueChanged(isOn, cmd); } // 开启动画 if (hasAnimation) m_pTimer->start(); this->update(); } bool UICustomSwitchWidget::getSwitchStatus(void) { return m_isSwitchOn; } void UICustomSwitchWidget::customPaint(QPainter* painter) { painter->save(); painter->setRenderHint(QPainter::Antialiasing); QRect rect = this->rect(); rect = rect.adjusted(m_margin.left(), m_margin.top(), -m_margin.right(), -m_margin.bottom()); // 绘制背景 painter->setPen(Qt::NoPen); painter->setBrush(QBrush(m_cBgColor)); painter->drawRoundedRect(rect, 4, 4); // 绘制滑块 painter->setBrush(QBrush(m_cSliderColor)); qreal interval = (rect.height() - m_nSliderHeight) / 2.0; QRect sliderRect(interval + m_nCurrentXPos, rect.y() + interval, m_nSliderWidth, m_nSliderHeight); painter->drawRoundedRect(sliderRect, 4, 4); painter->restore(); } QSize UICustomSwitchWidget::sizeHint() const { QSize size(80, 30); return size; } void UICustomSwitchWidget::mousePressEvent(QMouseEvent* event) { setSwitchStatus(!m_isSwitchOn, true, true); } void UICustomSwitchWidget::onTimeout(void) { QRect rect = this->rect(); rect = rect.adjusted(m_margin.left(), m_margin.top(), -m_margin.right(), -m_margin.bottom()); qreal interval = (rect.height() - m_nSliderHeight) / 2.0; int startPos = 0; int endXPos = rect.right() - interval - m_nSliderWidth; if (m_isSwitchOn) { // 向左移动 m_nCurrentXPos -= m_nAnimationInterval; if (m_nCurrentXPos <= startPos) { m_nCurrentXPos = 0; m_pTimer->stop(); } } else { // 向右移动 m_nCurrentXPos += m_nAnimationInterval; if (m_nCurrentXPos >= endXPos) { m_nCurrentXPos = endXPos; m_pTimer->stop(); } } this->update(); } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomSwitchWidget.h ================================================ #ifndef UICUSTOMSWITCHWIDGET_H #define UICUSTOMSWITCHWIDGET_H #include #include #include "UICustomWidgtes/CustomWidget.h" class UICustomSwitchWidget : public CustomWidget { Q_OBJECT public: UICustomSwitchWidget(QWidget* parent = nullptr); ~UICustomSwitchWidget(); void setSwitchStatus(bool isOn, bool hasAnimation = true, bool cmd = false); bool getSwitchStatus(void); protected: // Custom Paint Event virtual void customPaint(QPainter* painter) override; virtual QSize sizeHint() const override; virtual void mousePressEvent(QMouseEvent* event) override; private: bool m_isSwitchOn = false; QMargins m_margin; QColor m_cBgColor; // 背景色 QColor m_cSliderColor; // 滑块的颜色 int m_nCurrentXPos = 0; // 当前的X的位置 int m_nSliderWidth = 40; // 滑块大小 int m_nSliderHeight = 22; int m_nAnimationInterval = 5; QColor m_cOnBgColor; // 打开时背景色 QColor m_cOnSliderColor; // 打开时滑块颜色 QColor m_cOffBgColor; // 关闭时背景颜色 QColor m_cOffSliderColor; // 关闭时滑块颜色 QTimer* m_pTimer = nullptr; private slots: void onTimeout(void); signals: void valueChanged(bool isOn, bool cmd = false); }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomTextEdit.cpp ================================================ #include "UICustomTextEdit.h" #include #include UICustomTextEdit::UICustomTextEdit(QWidget* parent) :QTextEdit(parent) { } UICustomTextEdit::~UICustomTextEdit() { } void UICustomTextEdit::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key::Key_Enter) { emit pressedEnterKey(); event->accept(); return; } return QTextEdit::keyPressEvent(event); } QSize UICustomTextEdit::sizeHint(void) const { QSize size(80, 180); return size; } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomTextEdit.h ================================================ #ifndef UICUSTOMTEXTEDIT_H #define UICUSTOMTEXTEDIT_H #include #include #include "customcontrols_global.h" class CUSTOMCONTROLSSHARED_EXPORT UICustomTextEdit : public QTextEdit { Q_OBJECT public: UICustomTextEdit(QWidget* parent = nullptr); ~UICustomTextEdit() override; protected: void keyPressEvent(QKeyEvent *event) override; QSize sizeHint(void) const override; signals: void pressedEnterKey(void); // 按下小回车时,发送此信号 }; #endif ================================================ FILE: CustomControls/UICustomSingleControl/UICustomTimeEdit.cpp ================================================ #include "UICustomTimeEdit.h" UICustomTimeEdit::UICustomTimeEdit(QWidget* parent) :QTimeEdit(parent) { } UICustomTimeEdit::~UICustomTimeEdit() { } ================================================ FILE: CustomControls/UICustomSingleControl/UICustomTimeEdit.h ================================================ #ifndef UICUSTOMTIMEEDIT_H #define UICUSTOMTIMEEDIT_H #include #include class UICustomTimeEdit : public QTimeEdit { Q_OBJECT public: UICustomTimeEdit(QWidget* parent = nullptr); ~UICustomTimeEdit(); }; #endif ================================================ FILE: CustomControls/customcontrols_global.h ================================================ #ifndef CUSTOMCONTROLS_GLOBAL_H #define CUSTOMCONTROLS_GLOBAL_H #include #if defined(CUSTOMCONTROLS_LIBRARY) # define CUSTOMCONTROLSSHARED_EXPORT Q_DECL_EXPORT #else # define CUSTOMCONTROLSSHARED_EXPORT Q_DECL_IMPORT #endif #endif // CUSTOMCONTROLS_GLOBAL_H ================================================ FILE: CustomWidgets/CustomWidgets.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-01-04T20:25:00 # #------------------------------------------------- QT += widgets TARGET = CustomWidgets TEMPLATE = lib DEFINES += CUSTOMWIDGETS_LIBRARY DESTDIR += $$PWD/../bin MOC_DIR += $$PWD/../CustomWidgets/temp OBJECTS_DIR += $$PWD/../CustomWidgets/temp CONFIG += c++11 QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ UICustomCore/CustomStyleConfig.cpp \ UICustomWidgtes/CustomDialog.cpp \ UICustomWidgtes/CustomMainWindow.cpp \ UICustomWidgtes/CustomTestWidget.cpp \ UICustomWidgtes/CustomWidget.cpp HEADERS += \ UICustomCore/CustomStyleConfig.h \ UICustomWidgtes/CustomDialog.h \ UICustomWidgtes/CustomMainWindow.h \ UICustomWidgtes/CustomTestWidget.h \ UICustomWidgtes/CustomWidget.h \ customwidgets_global.h unix { target.path = /usr/lib INSTALLS += target } RESOURCES += \ qss.qrc ================================================ FILE: CustomWidgets/UICustomCore/CustomStyleConfig.cpp ================================================ #include "CustomStyleConfig.h" #include #include #include #include #include #include #include CustomStyleConfig::CustomStyleConfig() :m_cNormalBgColor(80, 80, 80) ,m_cNormalTextColor(255, 255, 255) ,m_cNormalHighLightColor(243, 125, 40) { QPalette pal; pal.setBrush(QPalette::Background, QBrush(m_cNormalBgColor)); pal.setBrush(QPalette::Foreground, QBrush(m_cNormalTextColor)); qApp->setPalette(pal); } CustomStyleConfig::~CustomStyleConfig() { } CustomStyleConfig* CustomStyleConfig::getInstance(void) { static CustomStyleConfig instance; return &instance; } void CustomStyleConfig::init(void) { qDebug() << __FUNCTION__; m_sCurrentPropertyName = "LightStyleProperty"; QString styleStringPath = ":/qss/light.css"; QFile nFile(styleStringPath); nFile.open(QFile::ReadOnly); QString styleSheetStr = nFile.readAll(); nFile.close(); qApp->setStyleSheet(styleSheetStr); // init font QFont font; font.setPointSizeF(10); //font.setPixelSize(24); qApp->setFont(font); } void CustomStyleConfig::setCurrentStyle(QWidget* widget, const QString& propertyValue, bool needPolish) { widget->setProperty(m_sCurrentPropertyName.toLocal8Bit().data(), propertyValue); if (needPolish) { qApp->style()->unpolish(widget); qApp->style()->polish(widget); } } void CustomStyleConfig::loadLanguage(const QString& qmFilePath) { QTranslator *translator = new QTranslator(this); bool result = translator->load(qmFilePath); if (result) qApp->installTranslator(translator); } const QColor& CustomStyleConfig::getNormalBackgroundColor(void) { return m_cNormalBgColor; } const QColor& CustomStyleConfig::getNormalTextColor(void) { return m_cNormalTextColor; } const QColor& CustomStyleConfig::getHighLightColor(void) { return m_cNormalHighLightColor; } ================================================ FILE: CustomWidgets/UICustomCore/CustomStyleConfig.h ================================================ #ifndef CUSTOMSTYLECONFIG_H #define CUSTOMSTYLECONFIG_H #include #include #include "customwidgets_global.h" #define g_StyleConfig CustomStyleConfig::getInstance() class CUSTOMWIDGETSSHARED_EXPORT CustomStyleConfig : public QObject { public: static CustomStyleConfig* getInstance(void); void init(void); void setCurrentStyle(QWidget* widget, const QString& propertyValue, bool needPolish = false); // 加载语言 void loadLanguage(const QString& qmFilePath); // 获取颜色 const QColor& getNormalBackgroundColor(void); const QColor& getNormalTextColor(void); const QColor& getHighLightColor(void); private: CustomStyleConfig(); ~CustomStyleConfig(); QString m_sCurrentPropertyName; QColor m_cNormalBgColor; QColor m_cNormalTextColor; QColor m_cNormalHighLightColor; }; #endif ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomDialog.cpp ================================================ #include "CustomDialog.h" #include #include #include #include #include #include #include #include #include #include "UICustomCore/CustomStyleConfig.h" #pragma comment(lib, "dwmapi.lib") #pragma comment(lib, "user32.lib") CustomDialogTitle::CustomDialogTitle() :m_buttonSize(20, 20) { // init Style g_StyleConfig->setCurrentStyle(this, "DefaultTitleBar"); this->setFixedHeight(m_nHeight); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); QHBoxLayout* mainLayout = new QHBoxLayout(this); mainLayout->setContentsMargins(20, 0, 20, 0); mainLayout->setSpacing(20); // Title m_pTitleText = new QLabel; m_pTitleText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mainLayout->addWidget(m_pTitleText); // minimize Button m_pMinimizeButton = new QPushButton; m_pMinimizeButton->setObjectName("minButton"); m_pMinimizeButton->setFixedSize(m_buttonSize); m_pMinimizeButton->setDefault(false); mainLayout->addWidget(m_pMinimizeButton); // maximize Button m_pMaximizeButton = new QPushButton; g_StyleConfig->setCurrentStyle(m_pMaximizeButton, "maxNormal"); m_pMaximizeButton->setObjectName("maxButton"); m_pMaximizeButton->setFixedSize(m_buttonSize); m_pMaximizeButton->setDefault(false); mainLayout->addWidget(m_pMaximizeButton); // close Button m_pCloseButton = new QPushButton; m_pCloseButton->setObjectName("closeButton"); m_pCloseButton->setFixedSize(m_buttonSize); m_pCloseButton->setDefault(false); mainLayout->addWidget(m_pCloseButton); } CustomDialogTitle::~CustomDialogTitle() { } void CustomDialogTitle::paintEvent(QPaintEvent *event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); return QWidget::paintEvent(event); } // ----------------------------------------------------------------------- const int CustomDialog::m_nBorderWidth = 10; CustomDialog::CustomDialog(QWidget *parent) : QDialog(parent) { Qt::WindowFlags windowFlags = this->windowFlags() | Qt::Window | Qt::FramelessWindowHint; windowFlags &= ~Qt::WindowSystemMenuHint; setWindowFlags(windowFlags); // init UI initUi(); } CustomDialog::~CustomDialog() { } void CustomDialog::setResizeable(bool resizeable) { bool visible = isVisible(); m_bResizeable = resizeable; if (m_bResizeable){ setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint); // setWindowFlag(Qt::WindowMaximizeButtonHint); //此行代码可以带回Aero效果,同时也带回了标题栏和边框,在nativeEvent()会再次去掉标题栏 // //this line will get titlebar/thick frame/Aero back, which is exactly what we want //we will get rid of titlebar and thick frame again in nativeEvent() later HWND hwnd = (HWND)this->winId(); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); ::SetWindowLong(hwnd, GWL_STYLE, style | WS_MAXIMIZEBOX | WS_THICKFRAME | WS_CAPTION); } else{ setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint); // setWindowFlag(Qt::WindowMaximizeButtonHint,false); HWND hwnd = (HWND)this->winId(); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); ::SetWindowLong(hwnd, GWL_STYLE, style & ~WS_MAXIMIZEBOX & ~WS_CAPTION); } //保留一个像素的边框宽度,否则系统不会绘制边框阴影 // //we better left 1 piexl width of border untouch, so OS can draw nice shadow around it const MARGINS shadow = { 1, 1, 1, 1 }; ::DwmExtendFrameIntoClientArea(HWND(winId()), &shadow); setVisible(visible); } void CustomDialog::setContentWidget(QWidget* contentWidget) { if (contentWidget == nullptr) return; contentWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_pMainLayout->addWidget(contentWidget); } void CustomDialog::setWindowTitle(const QString& str) { this->m_pTitleWidget->m_pTitleText->setText(str); QDialog::setWindowTitle(str); } void CustomDialog::setContentsMargins(const QMargins &margins) { QDialog::setContentsMargins(margins + m_frames); m_margins = margins; } void CustomDialog::setContentsMargins(int left, int top, int right, int bottom) { QDialog::setContentsMargins(left + m_frames.left(), \ top + m_frames.top(), \ right + m_frames.right(), \ bottom + m_frames.bottom()); m_margins.setLeft(left); m_margins.setTop(top); m_margins.setRight(right); m_margins.setBottom(bottom); } QMargins CustomDialog::contentsMargins() const { QMargins margins = QDialog::contentsMargins(); margins -= m_frames; return margins; } QRect CustomDialog::contentsRect() const { QRect rect = QDialog::contentsRect(); int width = rect.width(); int height = rect.height(); rect.setLeft(rect.left() - m_frames.left()); rect.setTop(rect.top() - m_frames.top()); rect.setWidth(width); rect.setHeight(height); return rect; } void CustomDialog::getContentsMargins(int *left, int *top, int *right, int *bottom) const { QDialog::getContentsMargins(left, top, right, bottom); if (!(left&&top&&right&&bottom)) return; if (isMaximized()) { *left -= m_frames.left(); *top -= m_frames.top(); *right -= m_frames.right(); *bottom -= m_frames.bottom(); } } void CustomDialog::showFullScreen() { if (isMaximized()) { QDialog::setContentsMargins(m_margins); m_frames = QMargins(); } QDialog::showFullScreen(); } void CustomDialog::initUi(void) { this->setContentsMargins(2, 2, 2, 2); QVBoxLayout* mainLayout = new QVBoxLayout(this); m_pTotlaLayout = mainLayout; mainLayout->setMargin(0); mainLayout->setSpacing(0); // title m_pTitleWidget = new CustomDialogTitle; m_pTitleWidget->m_pTitleText->setText("My Test Title"); mainLayout->addWidget(m_pTitleWidget); // content QWidget* pContentWidget = new QWidget; pContentWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); mainLayout->addWidget(pContentWidget); // Content Layout m_pMainLayout = new QVBoxLayout(pContentWidget); m_pMainLayout->setMargin(0); m_pMainLayout->setSpacing(0); QObject::connect(m_pTitleWidget->m_pMinimizeButton, &QPushButton::clicked, this, &CustomDialog::showMinimized); QObject::connect(m_pTitleWidget->m_pMaximizeButton, &QPushButton::clicked, this, &CustomDialog::onClickedMaximizeButton); QObject::connect(m_pTitleWidget->m_pCloseButton, &QPushButton::clicked, this, &CustomDialog::close); if (this->windowHandle()) QObject::connect(this->windowHandle(), &QWindow::windowStateChanged, this, &CustomDialog::onWindowStatusChanged); } void CustomDialog::onClickedMaximizeButton(void) { if (this->isMaximized()) this->showNormal(); else this->showMaximized(); } void CustomDialog::onWindowStatusChanged(Qt::WindowState windowStatus) { bool isMaxed = false; if (windowStatus == Qt::WindowMaximized) { isMaxed = true; //m_pTotlaLayout->setContentsMargins(10, 10, 1, 1); g_StyleConfig->setCurrentStyle(m_pTitleWidget->m_pMaximizeButton, "maxed", true); } else if (windowStatus == Qt::WindowNoState) { g_StyleConfig->setCurrentStyle(m_pTitleWidget->m_pMaximizeButton, "maxNormal", true); } } void CustomDialog::paintEvent(QPaintEvent* event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); QPen nPen; nPen.setWidth(2); nPen.setColor(QColor(0, 0, 0)); p.setPen(nPen); p.drawRect(this->rect()); return QDialog::paintEvent(event); } bool CustomDialog::nativeEvent(const QByteArray &eventType, void *message, long *result) { MSG *param = static_cast(message); switch (param->message) { case WM_NCCALCSIZE: { NCCALCSIZE_PARAMS& params = *reinterpret_cast(param->lParam); if (params.rgrc[0].top != 0) params.rgrc[0].top -= 1; //this kills the window frame and title bar we added with WS_THICKFRAME and WS_CAPTION *result = WVR_REDRAW; return true; } case WM_NCHITTEST: { const LONG border_width = m_nBorderWidth; RECT winrect; GetWindowRect(HWND(winId()), &winrect); long x = GET_X_LPARAM(param->lParam); long y = GET_Y_LPARAM(param->lParam); int nX = x - this->geometry().x(); int nY = y - this->geometry().y(); //support highdpi double dpr = this->devicePixelRatioF(); if (this->childAt(mapFromGlobal(QPoint(x/dpr,y/dpr))) == m_pTitleWidget->m_pTitleText) { *result = HTCAPTION; return true; } QRect nRect = this->rect().adjusted(m_nBorderWidth, m_nBorderWidth, -m_nBorderWidth, -m_nBorderWidth); bool needDispose = this->rect().contains(nX, nY) && !nRect.contains(nX, nY); if (!needDispose) return QDialog::nativeEvent(eventType, message, result); // dispose window frame if ((nX > 0) && (nX < m_nBorderWidth)) *result = HTLEFT; if ((nX > this->width() - m_nBorderWidth) && (nX < this->width())) *result = HTRIGHT; if ((nY > 0) && (nY < m_nBorderWidth)) *result = HTTOP; if ((nY > this->height() - m_nBorderWidth) && (nY < this->height())) *result = HTBOTTOM; if ((nX > 0) && (nX < m_nBorderWidth) && (nY > 0) && (nY < m_nBorderWidth)) *result = HTTOPLEFT; if ((nX > this->width() - m_nBorderWidth) && (nX < this->width()) && (nY > 0) && (nY < m_nBorderWidth)) *result = HTTOPRIGHT; if ((nX > 0) && (nX < m_nBorderWidth) && (nY > this->height() - m_nBorderWidth) && (nY < this->height())) *result = HTBOTTOMLEFT; if ((nX > this->width() - m_nBorderWidth) && (nX < this->width()) && (nY > this->height() - m_nBorderWidth) && (nY < this->height())) *result = HTBOTTOMRIGHT; return true; } case WM_GETMINMAXINFO: { if (::IsZoomed(param->hwnd)) { RECT frame = { 0, 0, 0, 0 }; AdjustWindowRectEx(&frame, WS_OVERLAPPEDWINDOW, FALSE, 0); //record frame area data #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) double dpr = this->devicePixelRatioF(); #else double dpr = 1.0; #endif m_frames.setLeft(abs(frame.left) / dpr + 0.5); m_frames.setTop(abs(frame.bottom) / dpr + 0.5); m_frames.setRight(abs(frame.right) / dpr + 0.5); m_frames.setBottom(abs(frame.bottom) / dpr + 0.5); QDialog::setContentsMargins(m_frames.left() + m_margins.left(), \ m_frames.top() + m_margins.top(), \ m_frames.right() + m_margins.right(), \ m_frames.bottom() + m_margins.bottom()); m_bJustMaximized = true; g_StyleConfig->setCurrentStyle(m_pTitleWidget->m_pMaximizeButton, "maxed", true); } else { if (m_bJustMaximized) { QDialog::setContentsMargins(m_margins); m_frames = QMargins(); m_bJustMaximized = false; g_StyleConfig->setCurrentStyle(m_pTitleWidget->m_pMaximizeButton, "maxNormal", true); } } return false; } } return QDialog::nativeEvent(eventType, message, result); } void CustomDialog::showEvent(QShowEvent* event) { if (!m_isShowed) { m_isShowed = true; setResizeable(m_bResizeable); } QDialog::showEvent(event); } ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomDialog.h ================================================ #pragma once #include #include #include #include #include "customwidgets_global.h" /** * Window Title */ class CustomDialog; class CustomDialogTitle : public QWidget { Q_OBJECT public: CustomDialogTitle(); ~CustomDialogTitle(); friend class CustomDialog; private: // controls QLabel *m_pTitleText = nullptr; QPushButton* m_pMinimizeButton = nullptr; QPushButton* m_pMaximizeButton = nullptr; QPushButton* m_pCloseButton = nullptr; private: int m_nHeight = 30; QSize m_buttonSize; protected: void paintEvent(QPaintEvent *event) override; }; /** * Windows Styles Dialog */ class QVBoxLayout; class CUSTOMWIDGETSSHARED_EXPORT CustomDialog : public QDialog { Q_OBJECT public: CustomDialog(QWidget *parent = Q_NULLPTR); ~CustomDialog(); //设置是否可以通过鼠标调整窗口大小 //if resizeable is set to false, then the window can not be resized by mouse //but still can be resized programtically void setResizeable(bool resizeable = true); bool isResizeable(){ return m_bResizeable; } // setContentWidget void setContentWidget(QWidget* contentWidget); // 设置标题 void setWindowTitle(const QString& str); public: void setContentsMargins(const QMargins &margins); void setContentsMargins(int left, int top, int right, int bottom); QMargins contentsMargins() const; QRect contentsRect() const; void getContentsMargins(int *left, int *top, int *right, int *bottom) const; public slots: void showFullScreen(); protected: QVBoxLayout *m_pMainLayout = nullptr; void paintEvent(QPaintEvent* event) override; bool nativeEvent(const QByteArray & eventType, void * message, long * result) override; void showEvent(QShowEvent* event) override; private: static const int m_nBorderWidth; // init ui(init titlebar) void initUi(void); CustomDialogTitle* m_pTitleWidget = nullptr; QVBoxLayout* m_pTotlaLayout = nullptr; QMargins m_margins; QMargins m_frames; bool m_bJustMaximized = false; bool m_bResizeable = true; bool m_isShowed = false; private slots: void onClickedMaximizeButton(void); void onWindowStatusChanged(Qt::WindowState windowStatus); }; ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomMainWindow.cpp ================================================ #include "CustomMainWindow.h" CustomMainWindow::CustomMainWindow(QWidget *parent) : QMainWindow(parent) { } CustomMainWindow::~CustomMainWindow() { } ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomMainWindow.h ================================================ #pragma once #include class CustomMainWindow : public QMainWindow { Q_OBJECT public: CustomMainWindow(QWidget *parent = Q_NULLPTR); ~CustomMainWindow(); }; ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomTestWidget.cpp ================================================ #include "CustomTestWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include CustomTestWidget::CustomTestWidget(QWidget* parent) :CustomWidget(parent) { QVBoxLayout* mainLayout = new QVBoxLayout(this); m_pMenuBar = new QMenuBar; mainLayout->addWidget(m_pMenuBar); m_pTabWidget = new QTabWidget; mainLayout->addWidget(m_pTabWidget); initMenuBar(); initCommonControls(); initTableControls(); initListControls(); } CustomTestWidget::~CustomTestWidget() { } void CustomTestWidget::initMenuBar(void) { QMenu *fileMenu = new QMenu(tr("File")); fileMenu->addAction(tr("Open File")); fileMenu->addAction(tr("Save File")); fileMenu->addAction(tr("Exit")); m_pMenuBar->addMenu(fileMenu); QMenu *EditMenu = new QMenu(tr("Edit")); EditMenu->addAction(tr("Redo")); EditMenu->addAction(tr("Undo")); EditMenu->addAction(tr("Copy")); EditMenu->addAction(tr("Cut")); EditMenu->addAction(tr("Paste")); m_pMenuBar->addMenu(EditMenu); QMenu *otherMenu = new QMenu(tr("Other")); otherMenu->addAction(tr("Theme")); otherMenu->addAction(tr("Language")); otherMenu->addSeparator(); otherMenu->addAction(tr("About")); m_pMenuBar->addMenu(otherMenu); } void CustomTestWidget::initCommonControls(void) { QWidget *commonWidget = new QWidget; m_pTabWidget->addTab(commonWidget, tr("Common Controls")); QVBoxLayout* layout = new QVBoxLayout(commonWidget); // row1 - QLabel QLineEdit QHBoxLayout* topLayout = new QHBoxLayout; QLabel* tagWidget = new QLabel(tr("Label:")); QLineEdit* lineEdit = new QLineEdit(tr("Test lineEdit")); topLayout->addWidget(tagWidget); topLayout->addWidget(lineEdit); layout->addLayout(topLayout); // row2 - QPushButton QHBoxLayout *secondLayout = new QHBoxLayout; for (int i = 1; i <= 4; ++i) { QString buttonName = "%1_Button"; buttonName = buttonName.arg(i); QPushButton* btn = new QPushButton; btn->setText(buttonName); //btn->setMinimumHeight(25); secondLayout->addWidget(btn); } layout->addLayout(secondLayout); // row3 - QComboBox QHBoxLayout *row3Layout = new QHBoxLayout; QComboBox* comboBox1 = new QComboBox; comboBox1->setView(new QListView(comboBox1)); comboBox1->addItem(tr("Test1")); comboBox1->addItem(tr("Test2")); comboBox1->addItem(tr("Test3")); comboBox1->addItem(tr("Test4")); row3Layout->addWidget(comboBox1); layout->addLayout(row3Layout); // row4 - QSlider and QProgressBar QHBoxLayout* row4Layout = new QHBoxLayout; QSlider *slider = new QSlider(Qt::Horizontal); slider->setMaximum(100); slider->setMinimum(0); slider->setValue(50); row4Layout->addWidget(slider); QProgressBar *progressBar = new QProgressBar; progressBar->setMinimum(0); progressBar->setMaximum(100); progressBar->setValue(50); QObject::connect(slider, &QSlider::valueChanged, progressBar, &QProgressBar::setValue); row4Layout->addWidget(progressBar); layout->addLayout(row4Layout); // row5 - checkbox and radiobutton // checkBox QGroupBox *checkBoxGroupBox = new QGroupBox; checkBoxGroupBox->setTitle(tr("CheckBox")); QHBoxLayout *checkBoxLayout = new QHBoxLayout(checkBoxGroupBox); QCheckBox* checkBox1 = new QCheckBox(tr("CheckBox1")); QCheckBox* checkBox2 = new QCheckBox(tr("CheckBox2")); checkBoxLayout->addWidget(checkBox1); checkBoxLayout->addWidget(checkBox2); // add Widgets QHBoxLayout *row5Layout = new QHBoxLayout; row5Layout->addWidget(checkBoxGroupBox); layout->addLayout(row5Layout); // radioButton QGroupBox *radioButtonGroupBox = new QGroupBox; radioButtonGroupBox->setTitle(tr("RadioButton")); QHBoxLayout *radioButtonLayout = new QHBoxLayout(radioButtonGroupBox); QRadioButton* radioButton1 = new QRadioButton(tr("RadioButton1")); QRadioButton* radioButton2 = new QRadioButton(tr("RadioButton2")); radioButtonLayout->addWidget(radioButton1); radioButtonLayout->addWidget(radioButton2); row5Layout->addWidget(radioButtonGroupBox); // row6 QHBoxLayout* row6Layout = new QHBoxLayout; QDoubleSpinBox* doubleSpinBox = new QDoubleSpinBox; QSpinBox* spinBox = new QSpinBox; QDateEdit *dateEdit = new QDateEdit; QTimeEdit* timeEdit = new QTimeEdit; row6Layout->addWidget(doubleSpinBox); row6Layout->addWidget(spinBox); row6Layout->addWidget(dateEdit); row6Layout->addWidget(timeEdit); layout->addLayout(row6Layout); // row7 - QTextEdit QHBoxLayout* row7Layout = new QHBoxLayout; QTextEdit* edit = new QTextEdit; row7Layout->addWidget(edit); layout->addLayout(row7Layout); } void CustomTestWidget::initTableControls(void) { QTableWidget* tableWidget = new QTableWidget; m_pTabWidget->addTab(tableWidget, tr("TableWidget")); tableWidget->setRowCount(100); tableWidget->setColumnCount(5); tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); QStringList heads; heads << tr("ID") << tr("Name") << tr("Sex") << tr("Age") << tr("Score"); tableWidget->setHorizontalHeaderLabels(heads); int ids[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; QString names[10] = { "douzhq", "xiaoming", "xiaohong", "xiaozhao", "xiaoli", \ "douzhq", "xiaoming", "xiaohong", "xiaozhao", "xiaoli" }; QString sex[10] = { "man", "man", "female", "man", "man", "female", "man", "man", "female", "man" }; int ages[10] = { 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; int Score[10] = { 100, 99, 98, 97, 96, 95, 94, 93, 92, 91 }; for (int i = 0; i < 100; ++i) { tableWidget->setItem(i, 0, new QTableWidgetItem(QString::number(ids[i % 10]))); tableWidget->setItem(i, 1, new QTableWidgetItem(names[i % 10])); tableWidget->setItem(i, 2, new QTableWidgetItem(sex[i % 10])); tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(ages[i % 10]))); tableWidget->setItem(i, 4, new QTableWidgetItem(QString::number(Score[i % 10]))); } } void CustomTestWidget::initListControls(void) { QWidget* w = new QWidget; w->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_pTabWidget->addTab(w, "ListWidget"); QHBoxLayout* layout = new QHBoxLayout(w); QListWidget* listWidget = new QListWidget; listWidget->addItem(new QListWidgetItem(tr("ListWidgetItem1"))); listWidget->addItem(new QListWidgetItem(tr("ListWidgetItem2"))); listWidget->addItem(new QListWidgetItem(tr("ListWidgetItem3"))); listWidget->addItem(new QListWidgetItem(tr("ListWidgetItem4"))); layout->addWidget(listWidget); QTreeWidget* treeWidget = new QTreeWidget; layout->addWidget(treeWidget); QTreeWidgetItem* topItem1 = new QTreeWidgetItem(); topItem1->setText(0, "topLevelItem1"); topItem1->addChild(new QTreeWidgetItem(QStringList("Top1_Child1"))); topItem1->addChild(new QTreeWidgetItem(QStringList("Top1_Child2"))); treeWidget->addTopLevelItem(topItem1); QTreeWidgetItem* topItem2 = new QTreeWidgetItem(); topItem2->setText(0, "topLevelItem2"); topItem2->addChild(new QTreeWidgetItem(QStringList("Top2_Child1"))); topItem2->addChild(new QTreeWidgetItem(QStringList("Top2_Child2"))); treeWidget->addTopLevelItem(topItem2); } ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomTestWidget.h ================================================ #ifndef CUSTOMT_TEST_WIDGET_H #define CUSTOMT_TEST_WIDGET_H #include #include "CustomWidget.h" class QTabWidget; class QMenuBar; class CustomTestWidget : public CustomWidget { Q_OBJECT public: CustomTestWidget(QWidget* parent = nullptr); ~CustomTestWidget(); private: QTabWidget* m_pTabWidget = nullptr; QMenuBar* m_pMenuBar = nullptr; void initMenuBar(void); void initCommonControls(void); void initTableControls(void); void initListControls(void); }; #endif ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomWidget.cpp ================================================ #include "CustomWidget.h" #include "UICustomCore/CustomStyleConfig.h" #include #include CustomWidget::CustomWidget(QWidget* parent) :QWidget(parent) { g_StyleConfig->setCurrentStyle(this, "DefaultWidget"); } CustomWidget::~CustomWidget() { } void CustomWidget::paintEvent(QPaintEvent* event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); customPaint(&p); return QWidget::paintEvent(event); } void CustomWidget::customPaint(QPainter* painter) { } ================================================ FILE: CustomWidgets/UICustomWidgtes/CustomWidget.h ================================================ #ifndef CUSTOMWIDGET_H #define CUSTOMWIDGET_H #include #include "customwidgets_global.h" class CUSTOMWIDGETSSHARED_EXPORT CustomWidget : public QWidget { Q_OBJECT public: CustomWidget(QWidget* parent = nullptr); ~CustomWidget(); protected: void paintEvent(QPaintEvent* event) final; // Custom Paint Event virtual void customPaint(QPainter* painter); }; #endif ================================================ FILE: CustomWidgets/customwidgets_global.h ================================================ #ifndef CUSTOMWIDGETS_GLOBAL_H #define CUSTOMWIDGETS_GLOBAL_H #include #if defined(CUSTOMWIDGETS_LIBRARY) # define CUSTOMWIDGETSSHARED_EXPORT Q_DECL_EXPORT #else # define CUSTOMWIDGETSSHARED_EXPORT Q_DECL_IMPORT #endif #endif // CUSTOMWIDGETS_GLOBAL_H ================================================ FILE: CustomWidgets/qss/light.css ================================================ /*标题*/ QWidget[LightStyleProperty='DefaultTitleBar'] { background-color: rgb(84, 126, 172); } /*通用的Widget*/ QWidget[LightStyleProperty='DefaultWidget'] { background-color: rgb(80, 80, 80); } /*有底线的Widget*/ QWidget[LightStyleProperty='BottomLineWidget'] { border-bottom: 1px solid rgb(200, 200, 200); } /*透明的Widget*/ QWidget[LightStyleProperty='TransparentBgWidget'] { background: transparent; } QMessageBox QWidget { color: rgb(0, 0, 0); } /*关闭按钮*/ QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton#closeButton { background: transparent; border:none; image: url(:/qss/images/close_normal.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:hover#closeButton { image: url(:/qss/images/close_hover.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:pressed#closeButton { image: url(:/qss/images/close_pressed.svg); } /*最小化按钮*/ QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton#minButton { background: transparent; border: none; image: url(:/qss/images/minimize_normal.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:hover#minButton { image: url(:/qss/images/minimize_hover.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:pressed#minButton { image: url(:/qss/images/minimize_pressed.svg); } /*最大化按钮*/ QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton#maxButton[LightStyleProperty='maxNormal'] { background: transparent; border: none; image: url(:/qss/images/maximized_normal.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:hover#maxButton[LightStyleProperty='maxNormal'] { image: url(:/qss/images/maximized_hover.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:pressed#maxButton[LightStyleProperty='maxNormal'] { image: url(:/qss/images/maximized_pressed.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton#maxButton[LightStyleProperty='maxed'] { background: transparent; border: none; image: url(:/qss/images/maximize_normal.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:hover#maxButton[LightStyleProperty='maxed'] { image: url(:/qss/images/maximize_hover.svg); } QWidget[LightStyleProperty='DefaultTitleBar'] QPushButton:pressed#maxButton[LightStyleProperty='maxed'] { image: url(:/qss/images/maximize_pressed.svg); } /*透明Widget*/ QWidget[LightStyleProperty='Transparent'] { background: transparent; } /*GroupTitle*/ /*************************************************************************************************************/ QWidget[LightStyleProperty='GroupTitle'] { background-color: rgb(90, 90, 90); color: rgb(230, 230, 230); } QWidget:hover[LightStyleProperty='GroupTitle'] { background-color: rgb(120, 120, 120); } /*GroupTitle*/ /*************************************************************************************************************/ QWidget[LightStyleProperty='GroupContent'] { background-color: rgb(60, 60, 60); } /*GroupWidget*/ /*************************************************************************************************************/ QWidget[LightStyleProperty='GroupWidget'] { background-color: rgb(80, 80, 80); border: 1px solid rgb(200, 200, 200); border-radius: 4px; } /*===========================================================================================================*/ /*ImageView*/ QWidget[LightStyleProperty='ImageView'] { background-color: rgb(60, 60, 60); border-radius: 4px; border: 1px solid rgb(200, 200, 200); } /*************************************************************************************************************/ /*DownLoadItemView*/ QWidget[LightStyleProperty='DownLoadItemView'] { background-color: rgb(70, 70, 70); border: 1px solid rgb(253, 135, 50); margin: 2px; padding: 2px; border-radius: 4px; } /*************************************************************************************************************/ /*LeftBarItem*/ QWidget[LightStyleProperty='LeftBarItem'] { background: rgb(80, 80, 80); color: rgb(230, 230, 230); border: 1px solid rgb(200, 200, 200); } QWidget[LightStyleProperty='LeftBarItemSelected'] { background: rgb(60, 60, 60); color: rgb(230, 230, 230); border: 1px solid rgb(200, 200, 200); } QWidget:hover[LightStyleProperty='LeftBarItem'] { background: rgb(100, 100, 100); color: rgb(255, 255, 255); } QWidget[LightStyleProperty='LeftBar'] { background: rgb(40, 40, 40); border: 1px solid rgb(200, 200, 200); border-radius: 4px; } QStackedWidget { background: rgb(40, 40, 40); border: 1px solid rgb(200, 200, 200); border-radius: 4px; padding: 4px; } /*************************************************************************************************************/ /*QSplitter*/ QSplitter::handle { background-color: rgb(40, 40, 40); margin: 0px 4px 0px 4px; } QSplitter::handle:horizontal { width: 5px; } QSplitter::handle:vertical { height: 5px; } QSplitter::handle:pressed { background-color: rgb(120, 120, 120); } QSplitter::handle:hover { background-color: rgb(200, 200, 200); } /*QLabel*/ QLabel { color: rgb(255, 255, 255); } QLabel[LightStyleProperty='LargeTitle'] { color: rgb(253, 135, 50); border: 0px solid red; border-bottom: 1px solid rgb(230, 230, 230); } /*QTabWidget*/ QTabWidget::pane { background-color: rgb(80, 80, 80); color: rgb(255, 255, 255); border: 1px solid rgb(140, 140, 140); } QTabWidget::tab-bar { background-color: rgb(80, 80, 80); color: rgb(255, 255, 255); } QTabBar::tab { background-color: rgb(100, 100, 100); color: rgb(255, 255, 255); border: 1px solid rgb(140, 140, 140); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom: none; padding: 4px; } QTabBar::tab:hover { background-color: rgb(80, 80, 80); } QTabBar::tab:selected { background-color: rgb(60, 60, 60); } QTabBar::tab:!selected { margin-top: 2px; } /*QLineEdit*/ QLineEdit, QTextEdit, QTimeEdit, QDateEdit, QDateTimeEdit, QDoubleSpinBox, QSpinBox { background-color: rgb(60, 60, 60); color: rgb(255, 255, 255); border: 1px solid rgb(100, 100, 100); border-radius: 4px; selection-background-color: rgb(130, 130, 130); min-height: 20px; padding: 2px; } QLineEdit:focus, QTextEdit:focus, QTimeEdit:focus, QDateEdit:focus, QDateTimeEdit:focus, QDoubleSpinBox:focus, QSpinBox:focus { border: 1px solid rgb(253, 135, 50); } /*QPushButton*/ QPushButton, QToolButton { border: 1px solid rgb(60, 60, 60); color: rgb(255, 255, 255); border-radius: 4px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 rgb(120, 120, 120), stop: 0.4 rgb(100, 100, 100), stop: 1.0 rgb(80, 80, 80)); min-height: 25px; padding: 2px 2px 2px 2px; } QPushButton:hover, QToolButton:hover { background-color: rgb(90, 90, 90); } QPushButton:pressed, QToolButton:pressed { background-color: rgb(60, 60, 60); border: 1px solid rgb(100, 100, 100); } QPushButton:disabled, QToolButton:disabled { background-color: rgb(80, 80, 80); } QPushButton[LightStyleProperty='LinkButton'] { background: transparent; color: rgb(243, 125, 40); border-width: 0px; } QPushButton:hover[LightStyleProperty='LinkButton'] { color: rgb(139, 240, 40); } /*QComboBox*/ QComboBox { background-color: rgb(90, 90, 90); border: 1px solid rgb(120, 120, 120); border-radius: 4px; min-height: 25px; color: rgb(255, 255, 255); } QComboBox:hover { background-color: rgb(100, 100, 100); } QComboBox::drop-down { background: transparent; border: none; } QComboBox::down-arrow { image: url(:/qss/images/comboBox_bottom.png); margin-right: 7px; width: 16px; height: 16px; } QComboBox QAbstractItemView { border: 1px solid rgb(120, 120, 120); background-color: rgb(80, 80, 80); outline: none; } QComboBox QAbstractItemView::item { height: 20; outline: none; background-color: rgb(60, 60, 60); color: rgb(255, 255, 255); } QComboBox QAbstractItemView::item:hover { background-color: rgb(253, 135, 50); color: rgb(255, 255, 255); } QComboBox QAbstractItemView::item:selected { background-color: rgb(253, 135, 50); } /*QMenuBar*/ QMenuBar { background-color: rgb(80, 80, 80); color: rgb(255, 255, 255); } QMenuBar::item { background-color: transparent; } QMenuBar::item:selected { background-color: rgb(60, 60, 60); } /*QMenu*/ QMenu { background-color: rgb(80, 80, 80); color: rgb(255, 255, 255); border: 1px solid rgb(120, 120, 120); } QMenu::item { padding: 2px 25px 2px 20px; border: 1px solid transparent; background-color: rgb(60, 60, 60); } QMenu::item:selected { background: rgb(253, 135, 50); } QMenu::item:hover { background: rgb(253, 135, 50); } QMenu::item:disabled { color: rgb(160, 160, 160); } QMenu::separator { height: 1px; background: rgb(120, 120, 120); } /*QSlider*/ QSlider::groove:horizontal { border: 1px solid rgb(120, 120, 120); height: 8px; background: rgb(60, 60, 60); margin: 0px 4px; border-radius: 4px; } QSlider::handle:horizontal { width:13px; margin-top:-3px; margin-bottom:-3px; border-radius:6px; background: rgb(243, 125, 40); /*border: 2px solid rgb(120, 120, 120);*/ background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.8 rgb(243, 125, 40),stop:0.9 rgb(140, 140, 140)); } QSlider::handle:horizontal:hover { background: rgb(253, 135, 50); background:qradialgradient(spread:pad,cx:0.5,cy:0.5,radius:0.5,fx:0.5,fy:0.5,stop:0.8 rgb(253, 135, 50),stop:0.9 rgb(140, 140, 140)); } QSlider::add-page:horizontal { } QSlider::sub-page:horizontal { height:8px; margin: 2px 2px 2px 7px; background: rgb(243, 125, 40); border-radius: 2px; } /*QProgressBar*/ QProgressBar { text-align: center; border: 1px solid rgb(120, 120, 120); border-radius: 4px; background-color: rgb(60, 60, 60); color: rgb(255, 255, 255); } QProgressBar::chunk { background-color: rgb(253, 135, 50); margin: 2px 2px 2px 2px; border-radius: 2px; } /*QGroupBox*/ QGroupBox { margin-top: 5px; background-color: rgb(80, 80, 80); border: 1px solid rgb(120, 120, 120); border-radius: 4px; padding: 4px; } QGroupBox::title { left:10px; position:relative; subcontrol-origin:margin; color: rgb(255, 255, 255); } /*QCheckBox*/ QGroupBox::indicator,QTreeWidget::indicator,QListWidget::indicator{ padding:0px -3px 0px 3px; } QCheckBox::indicator,QGroupBox::indicator,QTreeWidget::indicator,QListWidget::indicator{ width:13px; height:13px; } QCheckBox::indicator:unchecked,QGroupBox::indicator:unchecked,QTreeWidget::indicator:unchecked,QListWidget::indicator:unchecked{ image:url(:/qss/images/checkbox_unchecked.png); } QCheckBox::indicator:unchecked:disabled,QGroupBox::indicator:unchecked:disabled,QTreeWidget::indicator:unchecked:disabled,QListWidget::indicator:disabled{ image:url(:/qss/images/checkbox_unchecked_disable.png); } QCheckBox::indicator:checked,QGroupBox::indicator:checked,QTreeWidget::indicator:checked,QListWidget::indicator:checked{ image:url(:/qss/images/checkbox_checked.png); } QCheckBox::indicator:checked:disabled,QGroupBox::indicator:checked:disabled,QTreeWidget::indicator:checked:disabled,QListWidget::indicator:checked:disabled{ image:url(:/qss/images/checkbox_checked_disable.png); } QCheckBox::indicator:indeterminate,QGroupBox::indicator:indeterminate,QTreeWidget::indicator:indeterminate,QListWidget::indicator:indeterminate{ image:url(:/qss/images/checkbox_parcial.png); } QCheckBox::indicator:indeterminate:disabled,QGroupBox::indicator:indeterminate:disabled,QTreeWidget::indicator:indeterminate:disabled,QListWidget::indicator:indeterminate:disabled{ image:url(:/qss/images/checkbox_parcial_disable.png); } /*QRadioButton*/ QRadioButton::indicator{ width:15px; height:15px; } QRadioButton::indicator::unchecked{ image:url(:/qss/images/radiobutton_unchecked.png); } QRadioButton::indicator::unchecked:disabled{ image:url(:/qss/images/radiobutton_unchecked_disable.png); } QRadioButton::indicator::checked{ image:url(:/qss/images/radiobutton_checked.png); } QRadioButton::indicator::checked:disabled{ image:url(:/qss/images/radiobutton_checked_disable.png); } /*TableView、QListView、QTreeView*/ QTableView { background-color: rgb(80, 80, 80); color: rgb(255, 255, 255); gridline-color: rgb(120, 120, 120); outline: none; } QTreeView { show-decoration-selected: 1; background-color: rgb(80, 80, 80); color: rgb(255, 255, 255); outline: none; border-radius: 4px; } QListView, QListWidget { show-decoration-selected: 1; background-color: rgb(60, 60, 60); color: rgb(255, 255, 255); outline: none; border-radius: 4px; } QTreeView::item, QTableView::item { background: rgb(80, 80, 80); color: rgb(255, 255, 255); outline: none; } QListView::item, QListWidget::item { background: rgb(100, 100, 100); color: rgb(255, 255, 255); outline: none; border: 1px solid rgb(253, 135, 50); border-radius: 4px; } QTreeView::item:hover, QListView::item:hover, QListWidget::item:hover, QTableView::item:hover { background: rgba(253, 135, 50, 100); } QTreeView::item:selected, QListView::item:selected, QListWidget::item:selected, QTableView::item:selected { background: rgb(253, 135, 50); outline: none; } /*QHeaderView*/ QHeaderView, QTableCornerButton:section { background-color: rgb(80, 80, 80); } QHeaderView::section { background-color: rgb(40, 40, 40); color: rgb(230, 230, 230); padding: 4px; border: 1px solid rgb(100, 100, 100); } QHeaderView::section:checked { color: rgb(255, 255, 255); } /*QScrollBar*/ QScrollBar:vertical { border: 1px solid rgb(140, 140, 140); background: rgb(40, 40, 40); width: 12px; border-radius: 4px; } QScrollBar:horizontal { border: 1px solid rgb(140, 140, 140); background: rgb(40, 40, 40); height: 12px; border-radius: 4px; } QScrollBar::handle:vertical { min-height: 30px; background: rgb(100, 100, 100); border: none; border-radius: 4px; } QScrollBar::handle:horizontal { min-width: 30px; background: rgb(100, 100, 100); border: none; border-radius: 4px; } QScrollBar::handle:hover { background: rgb(160, 160, 160); } /* add-line, sub-line */ QScrollBar::add-line:vertical { border: none; height: 0px; subcontrol-position: bottom; subcontrol-origin: margin; } QScrollBar::sub-line:vertical { border: none; height: 0px; subcontrol-position: top; subcontrol-origin: margin; } QScrollBar::add-line:horizontal { border: none; width: 0px; subcontrol-position: right; subcontrol-origin: margin; } QScrollBar::sub-line:horizontal { border: none; width: 0px; subcontrol-position: left; subcontrol-origin: margin; } QScrollBar::add-page, QScrollBar::sub-page { background: transparent; } /*up-button and down-button*/ QTimeEdit::up-button,QDateEdit::up-button,QDateTimeEdit::up-button,QDoubleSpinBox::up-button,QSpinBox::up-button { image: url(:/qss/images/add_top.png); width: 10px; height: 10px; margin: 2px 2px 1px 0px; } QDoubleSpinBox::up-button,QSpinBox::up-button { width: 0px; } QTimeEdit::down-button,QDateEdit::down-button,QDateTimeEdit::down-button,QDoubleSpinBox::down-button,QSpinBox::down-button { image: url(:/qss/images/add_bottom.png); width: 10px; height: 10px; margin: 1px 2px 2px 0px; } QDoubleSpinBox::down-button,QSpinBox::down-button { width: 0px; } /*---------------------------------Tree Branch Abourt---------------------------------*/ QTreeView::branch { background: rgb(80, 80, 80); } QTreeView::branch:hover { background: rgba(235, 135, 50, 100); } QTreeView::branch:selected { background: rgb(235, 135, 50); } QTreeView::branch:has-siblings:!adjoins-item { border-image: url(:/qss/images/vline.png) 0; } QTreeView::branch:has-siblings:adjoins-item { border-image: url(:/qss/images/branch_more.png) 0; } QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: url(:/qss/images/branch_end.png) 0; } QTreeView::branch:has-children:!has-siblings:closed, QTreeView::branch:closed:has-children:has-siblings { border-image: none; image: url(:/qss/images/branch_closed.png); } QTreeView::branch:open:has-children:!has-siblings, QTreeView::branch:open:has-children:has-siblings { border-image: none; image: url(:/qss/images/branch_open.png); } ================================================ FILE: CustomWidgets/qss.qrc ================================================ qss/light.css qss/images/add_bottom.png qss/images/add_left.png qss/images/add_right.png qss/images/add_top.png qss/images/branch_open.png qss/images/calendar_nextmonth.png qss/images/calendar_prevmonth.png qss/images/checkbox_checked.png qss/images/checkbox_checked_disable.png qss/images/checkbox_parcial.png qss/images/checkbox_parcial_disable.png qss/images/checkbox_unchecked.png qss/images/checkbox_unchecked_disable.png qss/images/close_hover.svg qss/images/close_normal.svg qss/images/close_pressed.svg qss/images/comboBox_bottom.png qss/images/maximize_hover.svg qss/images/maximize_normal.svg qss/images/maximize_pressed.svg qss/images/maximized_hover.svg qss/images/maximized_normal.svg qss/images/maximized_pressed.svg qss/images/minimize_hover.svg qss/images/minimize_normal.svg qss/images/minimize_pressed.svg qss/images/radiobutton_checked.png qss/images/radiobutton_checked_disable.png qss/images/radiobutton_unchecked.png qss/images/radiobutton_unchecked_disable.png qss/images/branch_end.png qss/images/branch_more.png qss/images/stylesheet-branch-open.png qss/images/vline.png qss/images/branch_closed.png qss/images/branch_closed2.png ================================================ FILE: EasyCanvas/EasyCanvas.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-03-20T10:38:32 # #------------------------------------------------- QT += core gui multimedia greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = EasyCanvas TEMPLATE = app # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 CONFIG += c++11 RC_ICONS = EasyCanvas.ico MOC_DIR += $$PWD/../temp/EasyCanvas OBJECTS_DIR += $$PWD/../temp/EasyCanvas DESTDIR += $$PWD/../bin LIBS += -L$$PWD/../bin -lCustomWidgets LIBS += -L$$PWD/../bin -lCustomControls LIBS += -L$$PWD/../bin -lUtils LIBS += -L$$PWD/../bin -lNDNodeAttribute LIBS += -L$$PWD/../bin -lNodeAttributeControl LIBS += -L$$PWD/../bin -lAudioVideoCore LIBS += -L$$PWD/../bin -lPythonWrap LIBS += -L$$PWD/../bin -lEasyCanvasCore INCLUDEPATH += $$PWD/../CustomWidgets INCLUDEPATH += $$PWD/../CustomControls INCLUDEPATH += $$PWD/../NDNodeAttribute INCLUDEPATH += $$PWD/../NodeAttributeControl INCLUDEPATH += $$PWD/../Utils INCLUDEPATH += $$PWD/../AudioVideoCore INCLUDEPATH += $$PWD/../PythonWrap INCLUDEPATH += $$PWD/../EasyCanvasCore INCLUDEPATH += $$PWD/UICanvas INCLUDEPATH += $$PWD/UICore INCLUDEPATH += $$PWD/../thirdLibs/ffmpeg/include INCLUDEPATH += $$PWD/../thirdLibs/PythonQt_3_10/include INCLUDEPATH += $$PWD/../thirdLibs/python3_10/include CONFIG(debug, debug|release) { LIBS += -L$$PWD/../thirdLibs/PythonQt/libs/debug -lPythonQt_QtAll-Qt5-Python38_d -lPythonQt-Qt5-Python38_d LIBS += -L$$PWD/../thirdLibs/python3_8/libs -lpython3_d -lpython38_d } else { LIBS += -L$$PWD/../thirdLibs/PythonQt/libs/release -lPythonQt_QtAll-Qt5-Python38 -lPythonQt-Qt5-Python38 LIBS += -L$$PWD/../thirdLibs/python3_8/libs -lpython3 -lpython38 # python3.10 , VS2019 #LIBS += -L$$PWD/../thirdLibs/PythonQt_3_10/libs/release -lPythonQt_QtAll-Qt5-Python3.10 -lPythonQt-Qt5-Python3.10 #LIBS += -L$$PWD/../thirdLibs/python3_10/libs -lpython3 -lpython310 } SOURCES += \ GlobalHotKey/GlobalHotKeyFilter.cpp \ GlobalHotKey/GlobalHotKeyInfo.cpp \ GlobalHotKey/GlobalHotKeyManager.cpp \ UICore/MainWindow.cpp \ UICore/UIAboutMeDialog.cpp \ UICore/UIAttributWidget.cpp \ main.cpp HEADERS += \ GlobalHotKey/GlobalHotKeyFilter.h \ GlobalHotKey/GlobalHotKeyInfo.h \ GlobalHotKey/GlobalHotKeyManager.h \ UICore/MainWindow.h \ UICore/UIAboutMeDialog.h \ UICore/UIAttributWidget.h # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target ================================================ FILE: EasyCanvas/GlobalHotKey/GlobalHotKeyFilter.cpp ================================================ #include "GlobalHotKeyFilter.h" #include "GlobalHotKeyInfo.h" #include "GlobalHotKeyManager.h" #include #include GlobalHotKeyFilter::GlobalHotKeyFilter() { } GlobalHotKeyFilter::~GlobalHotKeyFilter() { } bool GlobalHotKeyFilter::nativeEventFilter(const QByteArray & eventType, void * message, long * result) { if (eventType != "windows_generic_MSG") return false; MSG *param = static_cast(message); switch (param->message) { case WM_HOTKEY: { m_photKeyManager->disposeHotKey(LOWORD(param->lParam), HIWORD(param->lParam)); break; } default: break; } return false; } ================================================ FILE: EasyCanvas/GlobalHotKey/GlobalHotKeyFilter.h ================================================ #ifndef GLOBALHOTKEYFILTER_ #define GLOBALHOTKEYFILTER_ #include #include class GlobalHotKeyManager; class GlobalHotKeyFilter : public QAbstractNativeEventFilter { public: explicit GlobalHotKeyFilter(); ~GlobalHotKeyFilter(); friend class GlobalHotKeyManager; protected: bool nativeEventFilter(const QByteArray & eventType, void * message, long * result) override; private: GlobalHotKeyManager* m_photKeyManager = nullptr; }; #endif ================================================ FILE: EasyCanvas/GlobalHotKey/GlobalHotKeyInfo.cpp ================================================ #include "GlobalHotKeyInfo.h" int GlobalHotKeyInfo::m_nTotalKey = 0; GlobalHotKeyInfo* GlobalHotKeyInfo::createInstance(Qt::KeyboardModifiers modifier, Qt::Key key) { GlobalHotKeyInfo* pInfo = new GlobalHotKeyInfo; pInfo->nKey = ++m_nTotalKey; pInfo->qtKey = key; pInfo->qtModifier = modifier; return pInfo; } GlobalHotKeyInfo::GlobalHotKeyInfo(QObject* parent) :QObject(parent) { } GlobalHotKeyInfo::~GlobalHotKeyInfo() { } void GlobalHotKeyInfo::sendActived(void) { emit actived(); } ================================================ FILE: EasyCanvas/GlobalHotKey/GlobalHotKeyInfo.h ================================================ #ifndef GLOBALHOTKEYINFO_H #define GLOBALHOTKEYINFO_H #include #include class GlobalHotKeyManager; class GlobalHotKeyInfo : public QObject { Q_OBJECT public: static GlobalHotKeyInfo* createInstance(Qt::KeyboardModifiers modifier, Qt::Key key); static int m_nTotalKey; // 发送激活信号 void sendActived(void); bool operator = (const GlobalHotKeyInfo& info) const{ return (nKey == info.nKey) || \ (modifier == info.modifier && key == info.key) || \ (qtModifier == info.qtModifier && qtKey == info.qtKey); } friend class GlobalHotKeyManager; inline int getId(void) const{ return nKey; } ~GlobalHotKeyInfo(); private: GlobalHotKeyInfo(QObject* parent = nullptr); quint32 key; quint32 modifier; Qt::KeyboardModifiers qtModifier; Qt::Key qtKey; int nKey = 0; signals: void actived(void); }; inline uint qHash(const GlobalHotKeyInfo& info, uint seed = 0) { return qHash(info.getId(), seed); } #endif ================================================ FILE: EasyCanvas/GlobalHotKey/GlobalHotKeyManager.cpp ================================================ #include "GlobalHotKeyManager.h" #include "GlobalHotKeyFilter.h" #include #include #include #pragma comment(lib, "user32.lib") GlobalHotKeyManager::GlobalHotKeyManager(QObject* parent) :QObject(parent) { GlobalHotKeyFilter* filer = new GlobalHotKeyFilter; filer->m_photKeyManager = this; qApp->installNativeEventFilter(filer); } GlobalHotKeyManager::~GlobalHotKeyManager() { for (auto iter = m_sets.begin(); iter != m_sets.end(); ++iter) unregisterHotKey(*iter, false); m_sets.clear(); } // 注册快捷键 void GlobalHotKeyManager::registerHotKey(const QSharedPointer& hotKeyInfo) { bool result = false; unsigned int modifier = getModifierValue(hotKeyInfo->qtModifier, result); if (!result) return; unsigned int key = getKeyValue(hotKeyInfo->qtKey, result); if (!result) return; hotKeyInfo->modifier = modifier; hotKeyInfo->key = key; m_sets.insert(hotKeyInfo); result = ::RegisterHotKey(nullptr, hotKeyInfo->nKey, modifier, key); if (!result) qDebug() << "Fail Register Hot Key"; } // 解除快捷键 void GlobalHotKeyManager::unregisterHotKey(const QSharedPointer& hotKeyInfo, bool needRemove) { if (m_sets.find(hotKeyInfo) == m_sets.end()) return; ::UnregisterHotKey(nullptr, hotKeyInfo->nKey); if (needRemove) m_sets.remove(hotKeyInfo); } bool GlobalHotKeyManager::disposeHotKey(unsigned int modifiers, unsigned int key) { QSharedPointer pInfo(new GlobalHotKeyInfo); pInfo->modifier = modifiers; pInfo->key = key; for (auto iter = m_sets.begin(); iter != m_sets.end(); ++iter) { if ((*iter)->key == key && (*iter)->modifier == modifiers) { (*iter)->sendActived(); return true; } } return false; } unsigned int GlobalHotKeyManager::getModifierValue(Qt::KeyboardModifiers value, bool& isOk) { unsigned int modife = 0; if (value & Qt::ControlModifier) modife |= MOD_CONTROL; if (value & Qt::AltModifier) modife |= MOD_ALT; if (value & Qt::ShiftModifier) modife |= MOD_SHIFT; if (modife) isOk = true; else { isOk = false; } return modife; } unsigned int GlobalHotKeyManager::getKeyValue(Qt::Key keycode, bool& isOk) { isOk = true; if(keycode <= 0xFFFF) {//Try to obtain the key from it's "character" const SHORT vKey = VkKeyScanW(keycode); if(vKey > -1) return LOBYTE(vKey); } //find key from switch/case --> Only finds a very small subset of keys switch (keycode) { case Qt::Key_Escape: return VK_ESCAPE; case Qt::Key_Tab: case Qt::Key_Backtab: return VK_TAB; case Qt::Key_Backspace: return VK_BACK; case Qt::Key_Return: case Qt::Key_Enter: return VK_RETURN; case Qt::Key_Insert: return VK_INSERT; case Qt::Key_Delete: return VK_DELETE; case Qt::Key_Pause: return VK_PAUSE; case Qt::Key_Print: return VK_PRINT; case Qt::Key_Clear: return VK_CLEAR; case Qt::Key_Home: return VK_HOME; case Qt::Key_End: return VK_END; case Qt::Key_Left: return VK_LEFT; case Qt::Key_Up: return VK_UP; case Qt::Key_Right: return VK_RIGHT; case Qt::Key_Down: return VK_DOWN; case Qt::Key_PageUp: return VK_PRIOR; case Qt::Key_PageDown: return VK_NEXT; case Qt::Key_CapsLock: return VK_CAPITAL; case Qt::Key_NumLock: return VK_NUMLOCK; case Qt::Key_ScrollLock: return VK_SCROLL; case Qt::Key_F1: return VK_F1; case Qt::Key_F2: return VK_F2; case Qt::Key_F3: return VK_F3; case Qt::Key_F4: return VK_F4; case Qt::Key_F5: return VK_F5; case Qt::Key_F6: return VK_F6; case Qt::Key_F7: return VK_F7; case Qt::Key_F8: return VK_F8; case Qt::Key_F9: return VK_F9; case Qt::Key_F10: return VK_F10; case Qt::Key_F11: return VK_F11; case Qt::Key_F12: return VK_F12; case Qt::Key_F13: return VK_F13; case Qt::Key_F14: return VK_F14; case Qt::Key_F15: return VK_F15; case Qt::Key_F16: return VK_F16; case Qt::Key_F17: return VK_F17; case Qt::Key_F18: return VK_F18; case Qt::Key_F19: return VK_F19; case Qt::Key_F20: return VK_F20; case Qt::Key_F21: return VK_F21; case Qt::Key_F22: return VK_F22; case Qt::Key_F23: return VK_F23; case Qt::Key_F24: return VK_F24; case Qt::Key_Menu: return VK_APPS; case Qt::Key_Help: return VK_HELP; case Qt::Key_MediaNext: return VK_MEDIA_NEXT_TRACK; case Qt::Key_MediaPrevious: return VK_MEDIA_PREV_TRACK; case Qt::Key_MediaPlay: return VK_MEDIA_PLAY_PAUSE; case Qt::Key_MediaStop: return VK_MEDIA_STOP; case Qt::Key_VolumeDown: return VK_VOLUME_DOWN; case Qt::Key_VolumeUp: return VK_VOLUME_UP; case Qt::Key_VolumeMute: return VK_VOLUME_MUTE; case Qt::Key_Mode_switch: return VK_MODECHANGE; case Qt::Key_Select: return VK_SELECT; case Qt::Key_Printer: return VK_PRINT; case Qt::Key_Execute: return VK_EXECUTE; case Qt::Key_Sleep: return VK_SLEEP; case Qt::Key_Period: return VK_DECIMAL; case Qt::Key_Play: return VK_PLAY; case Qt::Key_Cancel: return VK_CANCEL; case Qt::Key_Forward: return VK_BROWSER_FORWARD; case Qt::Key_Refresh: return VK_BROWSER_REFRESH; case Qt::Key_Stop: return VK_BROWSER_STOP; case Qt::Key_Search: return VK_BROWSER_SEARCH; case Qt::Key_Favorites: return VK_BROWSER_FAVORITES; case Qt::Key_HomePage: return VK_BROWSER_HOME; case Qt::Key_LaunchMail: return VK_LAUNCH_MAIL; case Qt::Key_LaunchMedia: return VK_LAUNCH_MEDIA_SELECT; case Qt::Key_Launch0: return VK_LAUNCH_APP1; case Qt::Key_Launch1: return VK_LAUNCH_APP2; case Qt::Key_Massyo: return VK_OEM_FJ_MASSHOU; case Qt::Key_Touroku: return VK_OEM_FJ_TOUROKU; default: if(keycode <= 0xFFFF) return (byte)keycode; else { isOk = false; return 0; } } } ================================================ FILE: EasyCanvas/GlobalHotKey/GlobalHotKeyManager.h ================================================ #ifndef GLOBALHOTKEYMANAGER_H #define GLOBALHOTKEYMANAGER_H #include #include #include #include "GlobalHotKeyInfo.h" class GlobalHotKeyManager : public QObject { public: explicit GlobalHotKeyManager(QObject* parent = nullptr); ~GlobalHotKeyManager(); // 注册快捷键 void registerHotKey(const QSharedPointer& hotKeyInfo); // 解除快捷键 void unregisterHotKey(const QSharedPointer& hotKeyInfo, bool needRemove = true); bool disposeHotKey(unsigned int modifiers, unsigned int key); private: QSet> m_sets; unsigned int getModifierValue(Qt::KeyboardModifiers value, bool& isOk); unsigned int getKeyValue(Qt::Key key, bool& isOk); }; #endif ================================================ FILE: EasyCanvas/UICore/MainWindow.cpp ================================================ #include "MainWindow.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "NDNodeBase.h" #include "UIAboutMeDialog.h" #include "PythonWrapCore.h" #include "UICanvas/UICanvasItemManager.h" #include "Scheme/CanvasSchemeManager.h" #include "Scheme/UISchemeManagerWidget.h" #include "Scheme/UISchemeManagerDialog.h" #include "UndoCmd/UndoCmdCore.h" #include "GlobalHotKey/GlobalHotKeyManager.h" #include "GlobalHotKey/GlobalHotKeyInfo.h" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { // 创建画布 m_pCanvasView = new UICanvasView; this->setCentralWidget(m_pCanvasView); g_PythonWrapCode->setSceneNode(m_pCanvasView->getCurrentSceneNode()); // 添加属性界面 m_pAttributeWidget = new UIAttributeWidget; m_pAttributeDockWidget = new QDockWidget(tr("Attribute")); m_pAttributeDockWidget->setWidget(m_pAttributeWidget); this->addDockWidget(Qt::RightDockWidgetArea, m_pAttributeDockWidget); // Undo View m_pUndoViewDockWidget = new QDockWidget(tr("UndoStack")); m_pUndoViewDockWidget->setFeatures(QDockWidget::AllDockWidgetFeatures); m_pUndoViewDockWidget->setFloating(true); m_pUndoView = g_currentCanvasManager->getCurrentUndoCmdCore()->createUndoView(); m_pUndoViewDockWidget->setWidget(m_pUndoView); this->addDockWidget(Qt::BottomDockWidgetArea, m_pUndoViewDockWidget); // 脚本编辑器 QWidget* pWidget = createScriptConsoleWidget(); m_pScriptConsoleDockWidget = new QDockWidget(tr("Script Console")); m_pScriptConsoleDockWidget->setFeatures(QDockWidget::AllDockWidgetFeatures); m_pScriptConsoleDockWidget->setFloating(true); this->addDockWidget(Qt::BottomDockWidgetArea, m_pScriptConsoleDockWidget); m_pScriptConsoleDockWidget->setWidget(pWidget); this->splitDockWidget(m_pScriptConsoleDockWidget, m_pUndoViewDockWidget, Qt::Horizontal); // 添加节点树 m_pNodeTreeWidget = new UINodeTreeWidget; m_pNodeTreeDockWidget = new QDockWidget(tr("NodeTree")); m_pNodeTreeDockWidget->setWidget(m_pNodeTreeWidget); this->addDockWidget(Qt::LeftDockWidgetArea, m_pNodeTreeDockWidget); QObject::connect(m_pCanvasView, &UICanvasView::itemSelectedChanged, \ this, &MainWindow::onSelectedItemChanged); initToolBar(); initMenuBar(); initStatusBar(); // 初始化属性面板 m_pAttributeWidget->setCurrentAttrNode(m_pCanvasView->getCurrentSelectedNode()); // 初始化标题 QString str("%1 - EasyCanvas"); this->setWindowTitle(str.arg("Empty")); } MainWindow::~MainWindow() { } QWidget* MainWindow::createScriptConsoleWidget(void) { m_pScriptConsole = g_PythonWrapCode->getScriptConsole(); QWidget* pScriptWidget = new QWidget; QVBoxLayout* mainLayout = new QVBoxLayout(pScriptWidget); mainLayout->setMargin(0); mainLayout->setSpacing(0); QMenuBar* pMenuBar = new QMenuBar; mainLayout->addWidget(pMenuBar); mainLayout->addWidget(m_pScriptConsole); // 添加菜单 QMenu* pFileMenu = new QMenu(tr("File")); pMenuBar->addMenu(pFileMenu); QAction* pFileAction = new QAction(tr("Open Script File")); QObject::connect(pFileAction, &QAction::triggered, this, &MainWindow::onClickedOpenScript); pFileMenu->addAction(pFileAction); QMenu* pHelpMenu = new QMenu(tr("Help")); pMenuBar->addMenu(pHelpMenu); QAction* pHelpAction = new QAction(tr("Script Help")); QObject::connect(pHelpAction, &QAction::triggered, this, &MainWindow::onClickedHelpScript); pHelpMenu->addAction(pHelpAction); return pScriptWidget; } void MainWindow::initGlobalHotKey(void) { GlobalHotKeyManager* manager = new GlobalHotKeyManager(this); // Ctrl + Z 撤销 GlobalHotKeyInfo* pInfoUndo = GlobalHotKeyInfo::createInstance(Qt::ControlModifier, Qt::Key_Z); manager->registerHotKey(QSharedPointer(pInfoUndo)); QObject::connect(pInfoUndo, &GlobalHotKeyInfo::actived, this, &MainWindow::onUndoCmd); // Ctrl + Y 重做 GlobalHotKeyInfo* pInfoRedo = GlobalHotKeyInfo::createInstance(Qt::ControlModifier, Qt::Key_Y); manager->registerHotKey(QSharedPointer(pInfoRedo)); QObject::connect(pInfoRedo, &GlobalHotKeyInfo::actived, this, &MainWindow::onRedoCmd); // Ctrl + N 新建空文档 GlobalHotKeyInfo* pInfoNewEmpty = GlobalHotKeyInfo::createInstance(Qt::ControlModifier, Qt::Key_N); manager->registerHotKey(QSharedPointer(pInfoNewEmpty)); QObject::connect(pInfoNewEmpty, &GlobalHotKeyInfo::actived, this, &MainWindow::onClickedNew); // Ctrl + O 打开 GlobalHotKeyInfo* pInfoOpenScheme = GlobalHotKeyInfo::createInstance(Qt::ControlModifier, Qt::Key_O); manager->registerHotKey(QSharedPointer(pInfoOpenScheme)); QObject::connect(pInfoOpenScheme, &GlobalHotKeyInfo::actived, this, &MainWindow::onClickedOpen); // Ctrl + S 保存 GlobalHotKeyInfo* pInfoSaveScheme = GlobalHotKeyInfo::createInstance(Qt::ControlModifier, Qt::Key_S); manager->registerHotKey(QSharedPointer(pInfoSaveScheme)); QObject::connect(pInfoSaveScheme, &GlobalHotKeyInfo::actived, this, &MainWindow::onClickedSava); } void MainWindow::onSelectedItemChanged(void) { NDNodeBase* node = m_pCanvasView->getCurrentSelectedNode(); m_pAttributeWidget->setCurrentAttrNode(node); } void MainWindow::initToolBar(void) { // 添加工具栏 m_pToolBar = new QToolBar; this->addToolBar(m_pToolBar); QString curAppPath = qApp->applicationDirPath() + "/"; QAction* pArrowDrawButton = new QAction(QIcon(curAppPath + "./images/arrowItem.png"), tr("Select")); pArrowDrawButton->setCheckable(true); pArrowDrawButton->setChecked(true); QObject::connect(pArrowDrawButton, &QAction::triggered, this, &MainWindow::onClickedArrowButton); m_pToolBar->addAction(pArrowDrawButton); QAction* pFreedowDrawButton = new QAction(QIcon(curAppPath + "./images/freeDrawItem.png"), tr("Pen Item")); pFreedowDrawButton->setCheckable(true); QObject::connect(pFreedowDrawButton, &QAction::triggered, this, &MainWindow::onClickedFreeDrawButton); m_pToolBar->addAction(pFreedowDrawButton); QAction* pImageButton = new QAction(QIcon(curAppPath + "./images/imageItem.png"), tr("Image Item")); QObject::connect(pImageButton, &QAction::triggered, this, &MainWindow::onClickedImageButton); m_pToolBar->addAction(pImageButton); QAction* pEllipseButton = new QAction(QIcon(curAppPath + "./images/ellipseItem.png"), tr("Ellipse Item")); QObject::connect(pEllipseButton, &QAction::triggered, this, &MainWindow::onClickedEllipseButton); m_pToolBar->addAction(pEllipseButton); QAction* pRectButton = new QAction(QIcon(curAppPath + "./images/rectItem.png"), tr("Rect Item")); QObject::connect(pRectButton, &QAction::triggered, this, &MainWindow::onClickedRectButton); m_pToolBar->addAction(pRectButton); QAction* pTextButton = new QAction(QIcon(curAppPath + "./images/textItem.png"), tr("Text Item")); QObject::connect(pTextButton, &QAction::triggered, this, &MainWindow::onClickedTextButton); m_pToolBar->addAction(pTextButton); QAction* pAudioButton = new QAction(QIcon(curAppPath + "./images/audioItem.png"), tr("Audio Item")); QObject::connect(pAudioButton, &QAction::triggered, this, &MainWindow::onClickedAudioButton); m_pToolBar->addAction(pAudioButton); } void MainWindow::initMenuBar(void) { QMenuBar* menuBar = new QMenuBar; this->setMenuBar(menuBar); // 添加文件菜单 QMenu* fileMenu = new QMenu(tr("File")); menuBar->addMenu(fileMenu); // 新建 QAction* newAction = new QAction(tr("New")); newAction->setShortcut(Qt::CTRL + Qt::Key_N); fileMenu->addAction(newAction); QObject::connect(newAction, &QAction::triggered, this, &MainWindow::onClickedNew); // 打开 QAction* openAction = new QAction(tr("Open")); openAction->setShortcut(Qt::CTRL + Qt::Key_O); fileMenu->addAction(openAction); QObject::connect(openAction, &QAction::triggered, this, &MainWindow::onClickedOpen); // 保存 QAction* saveAction = new QAction(tr("Save")); saveAction->setShortcut(Qt::CTRL + Qt::Key_S); fileMenu->addAction(saveAction); QObject::connect(saveAction, &QAction::triggered, this, &MainWindow::onClickedSava); // 另存为 QAction* saveAsAction = new QAction(tr("SaveAs")); fileMenu->addAction(saveAsAction); QObject::connect(saveAsAction, &QAction::triggered, this, &MainWindow::onClickedSaveAs); // 导出为图片 QAction* saveImageAction = new QAction(tr("Save To Image")); fileMenu->addAction(saveImageAction); QObject::connect(saveImageAction, &QAction::triggered, this, &MainWindow::onClickedSaveToImage); fileMenu->addSeparator(); // 打开脚本文件 QAction* pFileAction = new QAction(tr("Open Script File")); QObject::connect(pFileAction, &QAction::triggered, this, &MainWindow::onClickedOpenScript); fileMenu->addAction(pFileAction); // 添加编辑菜单 QMenu* editMenu = new QMenu(tr("Edit")); menuBar->addMenu(editMenu); // 脚本编辑器 QAction* pythonScriptAction = new QAction(tr("Script Editor")); editMenu->addAction(pythonScriptAction); QObject::connect(pythonScriptAction, &QAction::triggered, this, &MainWindow::onClickedScriptEdit); editMenu->addSeparator(); // 撤销 QAction* undoAction = g_currentCanvasManager->getCurrentUndoCmdCore()->createUndoAction(); undoAction->setShortcut(Qt::CTRL + Qt::Key_Z); editMenu->addAction(undoAction); // 重做 QAction* redoAction = g_currentCanvasManager->getCurrentUndoCmdCore()->createRedoAction(); redoAction->setShortcut(Qt::CTRL + Qt::Key_Y); editMenu->addAction(redoAction); // UndoView QAction* undoViewAction = new QAction(tr("Undo View")); QObject::connect(undoViewAction, &QAction::triggered, this, &MainWindow::onClickedUndoView); editMenu->addAction(undoViewAction); // 添加Item QMenu* canvasItem = new QMenu(tr("CanvasItem")); menuBar->addMenu(canvasItem); QString curAppPath = qApp->applicationDirPath() + "/"; QAction* pArrowDrawButton = new QAction(QIcon(curAppPath + "./images/arrowItem.png"), tr("Select")); QObject::connect(pArrowDrawButton, &QAction::triggered, this, &MainWindow::onClickedArrowButton); canvasItem->addAction(pArrowDrawButton); QAction* pFreedowDrawButton = new QAction(QIcon(curAppPath + "./images/freeDrawItem.png"), tr("Pen Item")); QObject::connect(pFreedowDrawButton, &QAction::triggered, this, &MainWindow::onClickedFreeDrawButton); canvasItem->addAction(pFreedowDrawButton); QAction* pImageButton = new QAction(QIcon(curAppPath + "./images/imageItem.png"), tr("Image Item")); QObject::connect(pImageButton, &QAction::triggered, this, &MainWindow::onClickedImageButton); canvasItem->addAction(pImageButton); QAction* pEllipseButton = new QAction(QIcon(curAppPath + "./images/ellipseItem.png"), tr("Ellipse Item")); QObject::connect(pEllipseButton, &QAction::triggered, this, &MainWindow::onClickedEllipseButton); canvasItem->addAction(pEllipseButton); QAction* pRectButton = new QAction(QIcon(curAppPath + "./images/rectItem.png"), tr("Rect Item")); QObject::connect(pRectButton, &QAction::triggered, this, &MainWindow::onClickedRectButton); canvasItem->addAction(pRectButton); QAction* pTextButton = new QAction(QIcon(curAppPath + "./images/textItem.png"), tr("Text Item")); QObject::connect(pTextButton, &QAction::triggered, this, &MainWindow::onClickedTextButton); canvasItem->addAction(pTextButton); QAction* pAudioButton = new QAction(QIcon(curAppPath + "./images/audioItem.png"), tr("Audio Item")); QObject::connect(pAudioButton, &QAction::triggered, this, &MainWindow::onClickedAudioButton); canvasItem->addAction(pAudioButton); // 添加帮助 QMenu* helpMenu = new QMenu(tr("Help")); menuBar->addMenu(helpMenu); // 关于我 QAction* pHelpAction = new QAction(tr("About Me")); QObject::connect(pHelpAction, &QAction::triggered, this, &MainWindow::onClickedAboutMe); helpMenu->addAction(pHelpAction); // 脚本命令 QAction* pScriptHelpAction = new QAction(tr("Script Help")); QObject::connect(pScriptHelpAction, &QAction::triggered, this, &MainWindow::onClickedHelpScript); helpMenu->addAction(pScriptHelpAction); } void MainWindow::initStatusBar(void) { QStatusBar* statusBar = new QStatusBar; this->setStatusBar(statusBar); statusBar->showMessage(tr("Ready")); } void MainWindow::onClickedImageButton(void) { m_pCanvasView->createImageItem(); } void MainWindow::onClickedArrowButton(void) { m_pCanvasView->setCurrentMode(UICanvasView::t_ArrowMode); } void MainWindow::onClickedFreeDrawButton(void) { m_pCanvasView->setCurrentMode(UICanvasView::t_FreeDrawMode); } void MainWindow::onClickedRectButton(void) { m_pCanvasView->createRectItem(); } void MainWindow::onClickedEllipseButton(void) { m_pCanvasView->createEllipseItem(); } void MainWindow::onClickedAudioButton(void) { m_pCanvasView->createAudioItem(); } void MainWindow::onClickedTextButton(void) { m_pCanvasView->createTextItem(); } void MainWindow::onClickedSaveToImage(void) { QString curAppPath = qApp->applicationDirPath() + "/"; QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), curAppPath + "./EasyCanvas.png", tr("Images (*.png *.jpg *.bmp)")); if (fileName.isEmpty()) return; m_pCanvasView->saveToImage(fileName); QMessageBox message; message.about(this, tr("Save Info"), tr("Save Successed!")); } void MainWindow::onClickedOpenScript(void) { QString curAppPath = qApp->applicationDirPath() + "/"; QString fileName = QFileDialog::getOpenFileName(this, tr("Open Script File"), curAppPath + "./", tr("Python (*.py)")); if (fileName.isEmpty()) return; g_PythonWrapCode->runScriptFiles(fileName); } void MainWindow::onClickedNew(void) { g_CanvasSchemeManager->setCurrentSchemeName(""); g_currentCanvasManager->cleanAll(); QString str("%1 - EasyCanvas"); this->setWindowTitle(str.arg("Empty")); } void MainWindow::onClickedOpen(void) { this->statusBar()->showMessage(tr("Opening...")); UISchemeManagerDialog pSchemeManagerWidget(this); pSchemeManagerWidget.exec(); this->statusBar()->showMessage(tr("Opened Successed")); // 设置标题 QString str("%1 - EasyCanvas"); this->setWindowTitle(str.arg(g_CanvasSchemeManager->getCurrentSchemeName())); } void MainWindow::onClickedSava(void) { if (g_CanvasSchemeManager->getCurrentSchemeName().isEmpty()) onClickedSaveAs(); else { this->statusBar()->showMessage(tr("Saving...")); g_CanvasSchemeManager->saveScheme(); this->statusBar()->showMessage(tr("Save Successed")); } // 设置标题 QString str("%1 - EasyCanvas"); this->setWindowTitle(str.arg(g_CanvasSchemeManager->getCurrentSchemeName())); } void MainWindow::onClickedSaveAs(void) { QString schemeName = QInputDialog::getText(this, tr("Please Input Scheme Name"), tr("Please Input Scheme Name")); if (schemeName.isEmpty()) return; g_CanvasSchemeManager->setCurrentSchemeName(schemeName); this->statusBar()->showMessage(tr("Saving...")); g_CanvasSchemeManager->saveScheme(); this->statusBar()->showMessage(tr("Save Successed")); // 设置标题 QString str("%1 - EasyCanvas"); this->setWindowTitle(str.arg(g_CanvasSchemeManager->getCurrentSchemeName())); } void MainWindow::onClickedAboutMe(void) { UIAboutMeDialog aboutMeDialog; aboutMeDialog.resize(900, 600); aboutMeDialog.exec(); } void MainWindow::onClickedHelpScript(void) { QDesktopServices::openUrl(QUrl("https://www.feijiblog.com/blog/qteasycanvasv2cmd")); } void MainWindow::onClickedScriptEdit(void) { m_pScriptConsoleDockWidget->show(); } // 撤销 void MainWindow::onUndoCmd(void) { g_currentCanvasManager->undo(); } // 重做 void MainWindow::onRedoCmd(void) { g_currentCanvasManager->redo(); } void MainWindow::onClickedUndoView(void) { m_pUndoViewDockWidget->show(); } ================================================ FILE: EasyCanvas/UICore/MainWindow.h ================================================ #ifndef WIDGET_H #define WIDGET_H #include #include #include #include "UICanvas/UICanvasView.h" #include "UIAttributWidget.h" #include "UINodeTree/UINodeTreeWidget.h" class PythonQtScriptingConsole; class QToolBar; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); // 注册全局热键 void initGlobalHotKey(void); private: UICanvasView* m_pCanvasView = nullptr; // 属性界面 UIAttributeWidget* m_pAttributeWidget = nullptr; QDockWidget* m_pAttributeDockWidget = nullptr; // 节点树 UINodeTreeWidget* m_pNodeTreeWidget = nullptr; QDockWidget* m_pNodeTreeDockWidget = nullptr; // Undo View QUndoView* m_pUndoView = nullptr; QDockWidget* m_pUndoViewDockWidget = nullptr; // 脚本编辑器 QWidget* m_pScriptConsole = nullptr; QDockWidget* m_pScriptConsoleDockWidget = nullptr; QToolBar* m_pToolBar = nullptr; void initToolBar(void); void initMenuBar(void); void initStatusBar(void); QWidget* createScriptConsoleWidget(void); private slots: void onClickedImageButton(void); void onClickedArrowButton(void); void onClickedFreeDrawButton(void); void onClickedRectButton(void); void onClickedEllipseButton(void); void onClickedAudioButton(void); void onClickedTextButton(void); void onSelectedItemChanged(void); // 文件相关 void onClickedNew(void); // 新建场景 void onClickedOpen(void); // 打开场景 void onClickedSava(void); // 保存场景 void onClickedSaveAs(void); // 另存为 void onClickedSaveToImage(void); // 保存为图片 void onClickedOpenScript(void); // 打开脚本文件 // 关于我 void onClickedAboutMe(void); void onClickedHelpScript(void); // 编辑菜单 // 脚本编辑器 void onClickedScriptEdit(void); // 撤销 void onUndoCmd(void); // 重做 void onRedoCmd(void); // 显示Undo View void onClickedUndoView(void); }; #endif // WIDGET_H ================================================ FILE: EasyCanvas/UICore/UIAboutMeDialog.cpp ================================================ #include "UIAboutMeDialog.h" #include UIAboutMeDialog::UIAboutMeDialog(QWidget* parent) :CustomDialog(parent) { m_pImageViewer = new UICustomImageViewer; QString curAppPath = qApp->applicationDirPath() + "/"; m_pImageViewer->loadImage(curAppPath + "./AboutMe.png"); this->setWindowTitle(tr("About Me")); this->setContentWidget(m_pImageViewer); } UIAboutMeDialog::~UIAboutMeDialog() { } ================================================ FILE: EasyCanvas/UICore/UIAboutMeDialog.h ================================================ #ifndef UIABOUITMEDIALOG_H #define UIABOUITMEDIALOG_H #include #include "UICustomWidgtes/CustomDialog.h" #include "UICustomSingleControl/UICustomImageViewer.h" class UIAboutMeDialog : public CustomDialog { Q_OBJECT public: UIAboutMeDialog(QWidget* parent = nullptr); ~UIAboutMeDialog(); private: UICustomImageViewer* m_pImageViewer = nullptr; }; #endif ================================================ FILE: EasyCanvas/UICore/UIAttributWidget.cpp ================================================ #include "UIAttributWidget.h" #include "NDNodeBase.h" #include "UINodeAttrControl.h" UIAttributeWidget::UIAttributeWidget(QWidget* parent) :QWidget(parent) { m_pMainLayout = new QVBoxLayout(this); this->setMinimumWidth(450); } UIAttributeWidget::~UIAttributeWidget() { } // 设置当前显示的节点 void UIAttributeWidget::setCurrentAttrNode(NDNodeBase* node) { if (m_pWidget) { m_pWidget->deleteLater(); m_pWidget = nullptr; } QWidget* widget = UINodeAttrControl::createNodeWidget(node); if (widget == nullptr) return; m_pWidget = widget; // 设置Widget m_pMainLayout->addWidget(widget); } ================================================ FILE: EasyCanvas/UICore/UIAttributWidget.h ================================================ #ifndef UIATTRIBUTEWIDGET_H #define UIATTRIBUTEWIDGET_H #include #include class NDNodeBase; class UIAttributeWidget : public QWidget { Q_OBJECT public: UIAttributeWidget(QWidget* parent = nullptr); ~UIAttributeWidget(); // 设置当前显示的节点 void setCurrentAttrNode(NDNodeBase* node); protected: QVBoxLayout* m_pMainLayout = nullptr; QWidget* m_pWidget = nullptr; }; #endif ================================================ FILE: EasyCanvas/main.cpp ================================================ #include #include #include #include #include #include #include "UICustomCore/CustomStyleConfig.h" #include "MainWindow.h" #include "PythonWrapCore.h" void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) { QString messageString = "%1: %2 (%3:%4, %5)\n"; QString typeString; switch (type) { case QtDebugMsg: typeString = "Debug"; break; case QtInfoMsg: typeString = "Info"; break; case QtWarningMsg: typeString = "Warning"; break; case QtCriticalMsg: typeString = "Critical"; break; case QtFatalMsg: typeString = "Fatal"; break; } messageString = messageString.arg(typeString).arg(msg).arg(context.file).arg(context.line).arg(context.function); QFile file(qApp->applicationDirPath() + QString("/") + "./log.txt"); file.open(QFile::Append); QTextStream stream(&file); stream << messageString; file.close(); } int main(int argc, char* argv[]) { //qInstallMessageHandler(myMessageOutput); QApplication a(argc, argv); qDebug() << "EasyCanvas Starting..."; // 初始化样式和翻译 g_StyleConfig->init(); QString curAppPath = qApp->applicationDirPath() + "/"; g_StyleConfig->loadLanguage(curAppPath + "./CustomNormalCode_zh_CH.qm"); qDebug() << "Init Pythoning"; // 初始化Python环境 g_PythonWrapCode->init(); qDebug() << "EasyCanvas Loading Widnows..."; MainWindow w; w.initGlobalHotKey(); w.showMaximized(); return a.exec(); } ================================================ FILE: EasyCanvas.pro ================================================ TEMPLATE = subdirs SUBDIRS += \ Utils \ CustomWidgets \ CustomControls \ NDNodeAttribute \ NodeAttributeControl \ AudioVideoCore \ EasyCanvasCore \ PythonWrap \ EasyCanvas CONFIG += ordered TRANSLATIONS = EasyCanvas_zh_CH.ts ================================================ FILE: EasyCanvasCore/EasyCanvasCore.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-08-03T18:18:55 # #------------------------------------------------- QT += widgets multimedia sql TARGET = EasyCanvasCore TEMPLATE = lib DEFINES += EASYCANVASCORE_LIBRARY # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS MOC_DIR += $$PWD/../EasyCanvasCore/temp OBJECTS_DIR += $$PWD/../EasyCanvasCore/temp DESTDIR += $$PWD/../bin LIBS += -L$$PWD/../bin -lCustomWidgets LIBS += -L$$PWD/../bin -lCustomControls LIBS += -L$$PWD/../bin -lUtils LIBS += -L$$PWD/../bin -lNDNodeAttribute LIBS += -L$$PWD/../bin -lNodeAttributeControl LIBS += -L$$PWD/../bin -lAudioVideoCore INCLUDEPATH += $$PWD/../CustomWidgets INCLUDEPATH += $$PWD/../CustomControls INCLUDEPATH += $$PWD/../NDNodeAttribute INCLUDEPATH += $$PWD/../NodeAttributeControl INCLUDEPATH += $$PWD/../Utils INCLUDEPATH += $$PWD/../AudioVideoCore INCLUDEPATH += $$PWD/../thirdLibs/ffmpeg/include QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ Scheme/CanvasSchemeManager.cpp \ Scheme/SQLCore.cpp \ Scheme/UISchemeManagerDialog.cpp \ Scheme/UISchemeManagerWidget.cpp \ UICanvas/UICanvasAudioItem.cpp \ UICanvas/UICanvasEllipseItem.cpp \ UICanvas/UICanvasImageItem.cpp \ UICanvas/UICanvasItemBase.cpp \ UICanvas/UICanvasItemManager.cpp \ UICanvas/UICanvasOperators.cpp \ UICanvas/UICanvasPathItem.cpp \ UICanvas/UICanvasRectItem.cpp \ UICanvas/UICanvasScene.cpp \ UICanvas/UICanvasTextItem.cpp \ UICanvas/UICanvasView.cpp \ UINodeTree/UINodeItem.cpp \ UINodeTree/UINodeSortFilterProxyModel.cpp \ UINodeTree/UINodeTreeDelegate.cpp \ UINodeTree/UINodeTreeView.cpp \ UINodeTree/UINodeTreeViewModel.cpp \ UINodeTree/UINodeTreeWidget.cpp \ UndoCmd/ItemAttributeChangedCmd.cpp \ UndoCmd/ItemChangeNameCmd.cpp \ UndoCmd/ItemCreateCmd.cpp \ UndoCmd/ItemDeleteCmd.cpp \ UndoCmd/ItemPasteCmd.cpp \ UndoCmd/UndoCmdCore.cpp HEADERS += \ Scheme/CanvasSchemeManager.h \ Scheme/SQLCore.h \ Scheme/SchemeDataInfo.h \ Scheme/UISchemeManagerDialog.h \ Scheme/UISchemeManagerWidget.h \ UICanvas/UICanvasAudioItem.h \ UICanvas/UICanvasEllipseItem.h \ UICanvas/UICanvasImageItem.h \ UICanvas/UICanvasItemBase.h \ UICanvas/UICanvasItemManager.h \ UICanvas/UICanvasOperators.h \ UICanvas/UICanvasPathItem.h \ UICanvas/UICanvasRectItem.h \ UICanvas/UICanvasScene.h \ UICanvas/UICanvasTextItem.h \ UICanvas/UICanvasView.h \ UINodeTree/UINodeItem.h \ UINodeTree/UINodeSortFilterProxyModel.h \ UINodeTree/UINodeTreeDelegate.h \ UINodeTree/UINodeTreeView.h \ UINodeTree/UINodeTreeViewModel.h \ UINodeTree/UINodeTreeWidget.h \ UndoCmd/ItemAttributeChangedCmd.h \ UndoCmd/ItemChangeNameCmd.h \ UndoCmd/ItemCreateCmd.h \ UndoCmd/ItemDeleteCmd.h \ UndoCmd/ItemPasteCmd.h \ UndoCmd/UndoCmdCore.h \ easycanvascore_global.h unix { target.path = /usr/lib INSTALLS += target } ================================================ FILE: EasyCanvasCore/Scheme/CanvasSchemeManager.cpp ================================================ #include "CanvasSchemeManager.h" #include "SQLCore.h" #include "UICanvas/UICanvasItemManager.h" #include "UICanvas/UICanvasView.h" #include CanvasSchemeManager* CanvasSchemeManager::getInstance(void) { static CanvasSchemeManager instance; return &instance; } CanvasSchemeManager::CanvasSchemeManager() { m_pSQLCore = new SQLCore(this); // 数据初始化 init(); } void CanvasSchemeManager::init(void) { // 创建方案管理表 m_pSQLCore->createSchemeManagerTable(); // 同步方案信息 syncSchemeInfoFromDB(); } CanvasSchemeManager::~CanvasSchemeManager() { } // 设置/获取当前的方案名称 void CanvasSchemeManager::setCurrentSchemeName(const QString& schemeName) { m_schemeName = schemeName; } QString CanvasSchemeManager::getCurrentSchemeName(void) { return m_schemeName; } void CanvasSchemeManager::saveScheme(void) { // 查找是否存在方案 SchemeDataInfo::SchemeInfo tempInfo; tempInfo.schemeName = m_schemeName; auto iter = std::find(m_schemeInfos.begin(), m_schemeInfos.end(), tempInfo); if (iter == m_schemeInfos.end()) { // 没找到, 添加方案 SchemeDataInfo::SchemeInfo info; info.schemeName = m_schemeName; info.createTime = QDateTime::currentDateTime(); info.editTime = QDateTime::currentDateTime(); // 获取图像信息 QImage image; g_currentCanvasManager->getCurrentCanvasView()->saveToImage(image); image = converToSamllImage(image); info.image = image; m_schemeInfos.insert(info); // 添加到数据库 m_pSQLCore->insertSchemeInfo(info); } else { // 更新方案 // 重新设置修改时间 SchemeDataInfo::SchemeInfo info = *iter; info.editTime = QDateTime::currentDateTime(); // 获取图像信息 QImage image; g_currentCanvasManager->getCurrentCanvasView()->saveToImage(image); image = converToSamllImage(image); info.image = image; m_schemeInfos.erase(iter); m_schemeInfos.insert(info); // qDebug() << info.editTime.toString("yyyy-MM-dd hh:mm:ss"); // qDebug() << m_schemeInfos.begin()->editTime.toString("yyyy-MM-dd hh:mm:ss"); // 更改数据库方案 m_pSQLCore->editSchemeInfo(info.schemeName, info); } // 创建方案数据元素表 m_pSQLCore->createSchemeTables(m_schemeName); m_pSQLCore->saveData(m_schemeName); } void CanvasSchemeManager::deleteScheme(const QString& schemeName) { SchemeDataInfo::SchemeInfo tempInfo; tempInfo.schemeName = schemeName; auto iter = std::find(m_schemeInfos.begin(), m_schemeInfos.end(), tempInfo); if (iter == m_schemeInfos.end()) return; // 删除方案 m_pSQLCore->deleteSchemeInfo(schemeName); m_schemeInfos.erase(iter); } void CanvasSchemeManager::openScheme(void) { m_pSQLCore->loadScheme(m_schemeName); } void CanvasSchemeManager::changedSchemeName(const QString& name, const QString& destName) { // 查找 SchemeDataInfo::SchemeInfo tempInfo; tempInfo.schemeName = name; auto iter = std::find(m_schemeInfos.begin(), m_schemeInfos.end(), tempInfo); if (iter == m_schemeInfos.end()) return; tempInfo = *iter; tempInfo.schemeName = destName; m_schemeInfos.erase(iter); m_schemeInfos.insert(tempInfo); m_pSQLCore->changedSchemeName(name, destName); } std::set CanvasSchemeManager::getSchemeInfoList(void) { return m_schemeInfos; } // 获取方案名 QString CanvasSchemeManager::getSchemeName(int index) { int count = 0; foreach(auto info, m_schemeInfos) { if (count == index) return info.schemeName; count++; } return ""; } SchemeDataInfo::SchemeInfo CanvasSchemeManager::getSchemeInfo(int index) { int count = 0; foreach(auto info, m_schemeInfos) { if (count == index) return info; count++; } return SchemeDataInfo::SchemeInfo(); } void CanvasSchemeManager::syncSchemeInfoFromDB(void) { m_pSQLCore->getSchemeInfoList(m_schemeInfos); } QImage CanvasSchemeManager::converToSamllImage(const QImage& image) { return image.scaled(m_nMaxWidth, m_nMaxHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation); } ================================================ FILE: EasyCanvasCore/Scheme/CanvasSchemeManager.h ================================================ #ifndef CANVASSCHEMEMANAGER_H #define CANVASSCHEMEMANAGER_H #include #include #include #include #include "easycanvascore_global.h" #include "SchemeDataInfo.h" #define g_CanvasSchemeManager CanvasSchemeManager::getInstance() class SQLCore; class EASYCANVASCORESHARED_EXPORT CanvasSchemeManager : public QObject { Q_OBJECT public: static CanvasSchemeManager* getInstance(void); // 设置/获取当前的方案名称 void setCurrentSchemeName(const QString& schemeName); QString getCurrentSchemeName(void); // 保存当前方案 void saveScheme(void); // 删除方案 void deleteScheme(const QString& schemeName); // 打开方案 void openScheme(void); // 修改方案名称 void changedSchemeName(const QString& name, const QString& destName); // 获取全部数据 std::set getSchemeInfoList(void); // 获取方案名 QString getSchemeName(int index); SchemeDataInfo::SchemeInfo getSchemeInfo(int index); private: CanvasSchemeManager(); ~CanvasSchemeManager(); private: // 初始化 void init(void); SQLCore* m_pSQLCore = nullptr; QString m_schemeName; // 方案管理数据信息 std::set m_schemeInfos; // 从数据库同步方案 void syncSchemeInfoFromDB(void); // 将图片转化为缩略图 QImage converToSamllImage(const QImage& image); int m_nMaxWidth = 300; int m_nMaxHeight = 300; }; #endif ================================================ FILE: EasyCanvasCore/Scheme/SQLCore.cpp ================================================ #include "SQLCore.h" #include #include #include #include #include #include #include #include "UICanvas/UICanvasItemManager.h" #include "UICanvas/UICanvasView.h" #include "NDNodeBase.h" #include "NDAttributeGroup.h" #include "NDAttributeBase.h" #include "UICanvas/UICanvasItemBase.h" SQLCore::SQLCore(QObject* parent) :QObject(parent) { init(); } SQLCore::~SQLCore() { } void SQLCore::init(void) { QString curAppPath = qApp->applicationDirPath() + "/"; QSqlDatabase sqlDatabelse = QSqlDatabase::addDatabase("QSQLITE"); sqlDatabelse.setDatabaseName(curAppPath + "./EasyCanvasScheme.db"); // 打开数据库 bool result = sqlDatabelse.open(); if (!result) qDebug() << "SQL Open Error!"; m_pSqlQuery = new QSqlQuery(sqlDatabelse); m_schemeTableName = "SchemeManager"; } // 创建方案表 void SQLCore::createSchemeTables(const QString& schemeName) { // 创建方案表 QString mainTable("CREATE TABLE IF NOT EXISTS %1 (" "id INT AUTO_INCREMENT PRIMARY KEY NOT NULL," "nodeName VARCHAR(255) NOT NULL," "nodeType INT NOT NULL," "nodeInfo TEXT NOT NULL)"); mainTable = mainTable.arg(schemeName); bool result = m_pSqlQuery->exec(mainTable); if (!result) { qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); return; } } // 创建方案管理表 void SQLCore::createSchemeManagerTable(void) { QString schemeManagerString("CREATE TABLE IF NOT EXISTS %1 (" "schemeName VARCHAR(200) PRIMARY KEY NOT NULL," "createTime DATATIME NOT NULL," "editTime DATATIME NOT NULL," "indexCount VARCHAR(60) NOT NULL," "imageWidth INT, " "imageHeight INT," "image MEDIUMBLOL)"); schemeManagerString = schemeManagerString.arg(m_schemeTableName); bool result = m_pSqlQuery->exec(schemeManagerString); if (!result) qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); } // 数据存储 void SQLCore::saveData(const QString& schemenName) { // 清除当前的存储 cleanData(schemenName); // 主表 QString insertString = "INSERT INTO %1 (id, nodeName, nodeType, nodeInfo)" "VALUES(:id, :nodeName, :nodeType, :nodeInfo)"; insertString = insertString.arg(schemenName); m_pSqlQuery->prepare(insertString); // 获取全部节点 QList nodes; NDNodeBase* pSceneNode = g_currentCanvasManager->getCurrentCanvasView()->getCurrentSceneNode(); nodes << pSceneNode; QStringList nodeNames = g_currentCanvasManager->getAllNodeNames(); foreach(const QString & nodeName, nodeNames) { NDNodeBase* pNode = g_currentCanvasManager->getNode(nodeName); nodes << pNode; } // 插入数据库 for (auto iter = nodes.begin(); iter != nodes.end(); ++iter) { NDNodeBase* pNode = *iter; int id = 0; QSharedPointer canvasItem = g_currentCanvasManager->getCanvasItem(pNode->getNodeName()); if (!canvasItem.isNull()) id = canvasItem->getCurrentIndex(); // Json转为字符串 QJsonDocument doc(g_currentCanvasManager->getNodeStoreJson(pNode)); QByteArray byteArray = doc.toJson(QJsonDocument::Compact); QString jsonString(byteArray); m_pSqlQuery->bindValue(":id", id); m_pSqlQuery->bindValue(":nodeName", pNode->getNodeName()); m_pSqlQuery->bindValue(":nodeType", pNode->getNodeType()); m_pSqlQuery->bindValue(":nodeInfo", jsonString); // 写入主表中 bool result = m_pSqlQuery->exec(); if (!result) { qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); } } } void SQLCore::cleanData(const QString& schemenName) { QString deleteString("DELETE FROM %1;"); // 删除主表 QString delString = deleteString.arg(schemenName); bool result = m_pSqlQuery->exec(delString); if (!result) qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); } void SQLCore::getSchemeInfoList(std::set& infos) { infos.clear(); QSqlQuery query(QString("SELECT schemeName, createTime, editTime, imageWidth, imageHeight, image FROM %1").arg(m_schemeTableName)); while (query.next()) { SchemeDataInfo::SchemeInfo info; info.schemeName = query.value("schemeName").toString(); info.createTime = query.value("createTime").toDateTime(); info.editTime = query.value("editTime").toDateTime(); // 设置图像 int width = query.value("imageWidth").toInt(); int height = query.value("imageHeight").toInt(); if (width > 0 && height > 0) { // 获取图像数据 QByteArray byteArray = query.value("image").toByteArray(); // 数据拷贝 unsigned char* pImageData = new unsigned char[width * height * 4]; memcpy(pImageData, byteArray.constData(), byteArray.size()); QImage image((uchar*)pImageData, width, height, QImage::Format_RGB32); info.image = image; } infos.insert(info); } } QString SQLCore::getCurrentIndexCountString(void) { QStringList strList; for (int i = (int)UICanvasItemManager::t_RectItem; i < (int)UICanvasItemManager::t_End; ++i) { UICanvasItemManager::CanvasItemType itemType = (UICanvasItemManager::CanvasItemType)i; int indexCount = g_currentCanvasManager->getNodeCounts(itemType); strList << QString::number(indexCount); } return strList.join(","); } // 插入方案数据 void SQLCore::insertSchemeInfo(const SchemeDataInfo::SchemeInfo& info) { QString insertString = QString("INSERT INTO %1 (schemeName, createTime, editTime, indexCount, imageWidth, imageHeight, image)" "VALUES(:schemeName, :createTime, :editTime, :indexCount, :imageWidth, :imageHeight, :image)").arg(m_schemeTableName); m_pSqlQuery->prepare(insertString); m_pSqlQuery->bindValue(":schemeName", info.schemeName); m_pSqlQuery->bindValue(":createTime", info.createTime); m_pSqlQuery->bindValue(":editTime", info.editTime); m_pSqlQuery->bindValue(":imageWidth", info.image.width()); m_pSqlQuery->bindValue(":imageHeight", info.image.height()); // 保存图片 QImage image = info.image; if (info.image.format() != QImage::Format_RGB32) image = info.image.convertToFormat(QImage::Format_RGB32); QByteArray imageArray; imageArray.append((const char*)image.constBits(), image.byteCount()); m_pSqlQuery->bindValue(":image", imageArray); // 保存索引列表 QString indexCountStr = getCurrentIndexCountString(); m_pSqlQuery->bindValue(":indexCount", indexCountStr); bool result = m_pSqlQuery->exec(); if (!result) { qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); } } // 编辑方案数据 void SQLCore::editSchemeInfo(const QString& schemeName, const SchemeDataInfo::SchemeInfo& info) { QString updateString("UPDATE %1 SET schemeName=:schemeName, " "createTime=:createTime, " "editTime=:editTime, " "indexCount=:indexCount, " "imageWidth=:imageWidth, " "imageHeight=:imageHeight, " "image=:image " "WHERE schemeName=\"%2\";"); updateString = updateString.arg(m_schemeTableName).arg(schemeName); m_pSqlQuery->prepare(updateString); m_pSqlQuery->bindValue(":schemeName", info.schemeName); m_pSqlQuery->bindValue(":createTime", info.createTime); m_pSqlQuery->bindValue(":editTime", info.editTime); m_pSqlQuery->bindValue(":indexCount", getCurrentIndexCountString()); m_pSqlQuery->bindValue(":imageWidth", info.image.width()); m_pSqlQuery->bindValue(":imageHeight", info.image.height()); // 保存图片 QImage image = info.image; if (info.image.format() != QImage::Format_RGB32) image = info.image.convertToFormat(QImage::Format_RGB32); QByteArray imageArray; imageArray.append((const char*)image.constBits(), image.byteCount()); m_pSqlQuery->bindValue(":image", imageArray); bool result = m_pSqlQuery->exec(); if (!result) qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); } // 删除方案数据 void SQLCore::deleteSchemeInfo(const QString& schemeName) { // 删除管理表中的记录 QString deleteString("DELETE FROM %1 WHERE schemeName=\"%2\""); deleteString = deleteString.arg(m_schemeTableName).arg(schemeName); bool result = m_pSqlQuery->exec(deleteString); if (!result) qDebug() << __FUNCTION__ << deleteString << "; " << m_pSqlQuery->lastError().text(); // 删除属性表 QString deleteAttrString("DROP TABLE %1;"); // 删除主表 QString delString = deleteAttrString.arg(schemeName); result = m_pSqlQuery->exec(delString); if (!result) qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); } void SQLCore::changedSchemeName(const QString& schemeName, const QString& destName) { // 修该方案表中的名字 QString updateSqlString = "UPDATE %1 SET schemeName=:schemeName WHERE schemeName = \"%2\""; updateSqlString = updateSqlString.arg(m_schemeTableName).arg(schemeName); m_pSqlQuery->prepare(updateSqlString); m_pSqlQuery->bindValue(":schemeName", destName); bool result = m_pSqlQuery->exec(); if (!result) qDebug() << m_pSqlQuery->lastError().text(); // 修改主表的名字 QString reNameString = "ALTER TABLE %1 RENAME TO %2"; reNameString = reNameString.arg(schemeName).arg(destName); result = m_pSqlQuery->exec(reNameString); if (!result) qDebug() << __FUNCTION__ << m_pSqlQuery->lastError().text(); } void SQLCore::loadScheme(const QString& schemeName) { // 获取数目 int nTotalCount = 0; QString countString = QString("SELECT COUNT(*) FROM %1;").arg(schemeName); QSqlQuery query(countString); while (query.next()) { nTotalCount = query.value(0).toInt(); } // 获取主表中所有节点 QString schemeMainString = QString("SELECT id, nodeName, nodeType, nodeInfo FROM %1 ORDER BY id;").arg(schemeName); QSqlQuery mainQuery(schemeMainString); int maxIndex = 0; while (mainQuery.next()) { // 获取节点名等信息 QString nodeName = mainQuery.value("nodeName").toString(); UICanvasItemManager::CanvasItemType nodeType = (UICanvasItemManager::CanvasItemType)mainQuery.value("nodeType").toInt(); int id = mainQuery.value("id").toInt(); QString nodeInfo = mainQuery.value("nodeInfo").toString(); NDNodeBase* pCurrentNode = nullptr; // 创建CanvasItem if (nodeType != UICanvasItemManager::t_CanvasItem) { auto canvasItem = g_currentCanvasManager->createCanvasItem(nodeType, nodeName); if (canvasItem == nullptr) continue; canvasItem->setCurrentIndex(id); pCurrentNode = canvasItem->getCurrentNode(); } else { pCurrentNode = g_currentCanvasManager->getCurrentCanvasView()->getCurrentSceneNode(); } // 设置属性信息 QJsonParseError jsonParseError; QJsonDocument doc = QJsonDocument::fromJson(nodeInfo.toUtf8(), &jsonParseError); if (jsonParseError.error != QJsonParseError::NoError) continue; g_currentCanvasManager->fillNodeJsonInfo(pCurrentNode, doc.object()); maxIndex = qMax(maxIndex, id); } g_currentCanvasManager->setCurrentMaxId(++maxIndex); } ================================================ FILE: EasyCanvasCore/Scheme/SQLCore.h ================================================ #ifndef SQLCORE_H #define SQLCORE_H #include #include #include #include "SchemeDataInfo.h" class QSqlQuery; class NDNodeBase; class SQLCore : public QObject { Q_OBJECT public: explicit SQLCore(QObject* parent = nullptr); ~SQLCore(); // 创建方案表 void createSchemeTables(const QString& schemeName); // 创建方案管理表 void createSchemeManagerTable(void); // 数据存储 void saveData(const QString& schemenName); // 清空存储方案 void cleanData(const QString& schemenName); // 查找 // 获取方案列表 void getSchemeInfoList(std::set& infos); // 插入方案数据 void insertSchemeInfo(const SchemeDataInfo::SchemeInfo& info); // 编辑方案数据 void editSchemeInfo(const QString& schemeName, const SchemeDataInfo::SchemeInfo& info); // 删除方案数据 void deleteSchemeInfo(const QString& schemeName); // 更改方案名称 void changedSchemeName(const QString& schemeName, const QString& destName); // 加载方案 void loadScheme(const QString& schemeName); private: void init(void); QSqlQuery *m_pSqlQuery = nullptr; QString m_baseAttrAppendString; QString m_schemeTableName; // 获取当前的索引计数,组合字符串 QString getCurrentIndexCountString(void); }; #endif ================================================ FILE: EasyCanvasCore/Scheme/SchemeDataInfo.h ================================================ #ifndef SCHEMEDATAINFO #define SCHEMEDATAINFO #include #include #include #include class SchemeDataInfo { public: struct SchemeInfo { QString schemeName; QDateTime createTime; QDateTime editTime; QImage image; bool operator == (const SchemeInfo& info) const { return schemeName == info.schemeName; } bool operator < (const SchemeInfo& info) const { return editTime < info.editTime; } }; }; //class SchemeDataInfoSort //{ //public: // bool operator () (const SchemeDataInfo::SchemeInfo& a, const SchemeDataInfo::SchemeInfo& b) const // { // if () // } //}; inline uint qHash(const SchemeDataInfo::SchemeInfo& schemeInfo, uint seed = 0) { return qHash(schemeInfo.schemeName, seed); } #endif ================================================ FILE: EasyCanvasCore/Scheme/UISchemeManagerDialog.cpp ================================================ #include "UISchemeManagerDialog.h" #include "UISchemeManagerWidget.h" #include "CanvasSchemeManager.h" #include "UICanvas/UICanvasItemManager.h" #include UISchemeManagerDialog::UISchemeManagerDialog(QWidget* parent) :CustomDialog(parent) { initUi(); // 同步数据 m_pSchemeWidget->syncFromData(); // 改变大小 this->resize(800, 600); this->setWindowTitle(tr("Open Scheme")); } UISchemeManagerDialog::~UISchemeManagerDialog() { } void UISchemeManagerDialog::initUi(void) { // 设置Widget QWidget* contentWidget = new QWidget; this->setContentWidget(contentWidget); QVBoxLayout* mainLayout = new QVBoxLayout(contentWidget); // 添加方案管理Widget m_pSchemeWidget = new UISchemeManagerWidget; mainLayout->addWidget(m_pSchemeWidget); // 添加按钮 QWidget* pButtonWidget = new QWidget; mainLayout->addWidget(pButtonWidget); QHBoxLayout* buttomLayout = new QHBoxLayout(pButtonWidget); buttomLayout->setMargin(0); buttomLayout->setSpacing(4); buttomLayout->addStretch(); // 添加删除按钮 QPushButton* pDeleteButton = new QPushButton(tr("Delete")); QObject::connect(pDeleteButton, &QPushButton::clicked, this, &UISchemeManagerDialog::onClickedDeleteButton); pDeleteButton->setFixedWidth(120); buttomLayout->addWidget(pDeleteButton); // 添加打开按钮 QPushButton* pOpenButton = new QPushButton(tr("Open")); QObject::connect(pOpenButton, &QPushButton::clicked, this, &UISchemeManagerDialog::onClickedOpenButton); pOpenButton->setFixedWidth(120); buttomLayout->addWidget(pOpenButton); } void UISchemeManagerDialog::onClickedDeleteButton(void) { // 获取当前选择的方案名称 QString schemeName = m_pSchemeWidget->getCurrentSelectedSchemeName(); if (schemeName.isEmpty()) return; // 从数据库中删除 g_CanvasSchemeManager->deleteScheme(schemeName); // 刷新数据显示 m_pSchemeWidget->syncFromData(); } void UISchemeManagerDialog::onClickedOpenButton(void) { // 获取当前选择的方案名称 QString schemeName = m_pSchemeWidget->getCurrentSelectedSchemeName(); if (schemeName.isEmpty()) return; this->close(); // 打开方案 g_currentCanvasManager->cleanAll(); g_CanvasSchemeManager->setCurrentSchemeName(schemeName); g_CanvasSchemeManager->openScheme(); } ================================================ FILE: EasyCanvasCore/Scheme/UISchemeManagerDialog.h ================================================ #ifndef UISCHEMEMANAGERDIALOG_H #define UISCHEMEMANAGERDIALOG_H #include "UICustomWidgtes/CustomDialog.h" #include "easycanvascore_global.h" #include class UISchemeManagerWidget; class EASYCANVASCORESHARED_EXPORT UISchemeManagerDialog : public CustomDialog { Q_OBJECT public: explicit UISchemeManagerDialog(QWidget* parent = nullptr); ~UISchemeManagerDialog(); private: void initUi(void); UISchemeManagerWidget* m_pSchemeWidget = nullptr; private slots: void onClickedDeleteButton(void); void onClickedOpenButton(void); }; #endif ================================================ FILE: EasyCanvasCore/Scheme/UISchemeManagerWidget.cpp ================================================ #include "UISchemeManagerWidget.h" #include "CanvasSchemeManager.h" #include "SchemeDataInfo.h" #include #include #include #include UISchemeManagerWidget::UISchemeManagerWidget(QWidget* parent) :QListView(parent) { // 设置Model m_pModel = new SchemeManagerModel(this); this->setModel(m_pModel); // 设置Delegate m_delegate = new SchemeManagerDelegate(this); this->setItemDelegate(m_delegate); this->setViewMode(QListView::IconMode); this->setResizeMode(QListView::Adjust); this->setSelectionMode(QListView::SingleSelection); this->setSpacing(4); } UISchemeManagerWidget::~UISchemeManagerWidget() { } void UISchemeManagerWidget::syncFromData(void) { // 更新显示 this->clearSelection(); this->doItemsLayout(); } QString UISchemeManagerWidget::getCurrentSelectedSchemeName(void) { QModelIndexList indexs = this->selectionModel()->selectedIndexes(); if (indexs.isEmpty()) return ""; return m_pModel->data(indexs.at(0), Qt::DisplayRole).toString(); } // ========================== Model =================================== SchemeManagerModel::SchemeManagerModel(QObject* parent) :QAbstractListModel(parent) { } SchemeManagerModel::~SchemeManagerModel() { } int SchemeManagerModel::rowCount(const QModelIndex &parent) const { const std::set& infos = g_CanvasSchemeManager->getSchemeInfoList(); return infos.size(); } QVariant SchemeManagerModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole) { int rowIndex = index.row(); const std::set& infos = g_CanvasSchemeManager->getSchemeInfoList(); if (infos.size() <= rowIndex) return QVariant(); // 获取名字 return g_CanvasSchemeManager->getSchemeName(rowIndex); } return QVariant(); } bool SchemeManagerModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) return false; int rowIndex = index.row(); QString schemeName = g_CanvasSchemeManager->getSchemeName(rowIndex); g_CanvasSchemeManager->changedSchemeName(schemeName, value.toString()); return true; } Qt::ItemFlags SchemeManagerModel::flags(const QModelIndex &index) const { if (!index.isValid()) return QAbstractListModel::flags(index); return QAbstractListModel::flags(index) | Qt::ItemIsEditable; } // ========================== Delegate =================================== SchemeManagerDelegate::SchemeManagerDelegate(QObject* parent) :QStyledItemDelegate(parent) { } SchemeManagerDelegate::~SchemeManagerDelegate() { } void SchemeManagerDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { // QString name = g_CanvasSchemeManager->getSchemeName(index.row()); // painter->drawText(option.) //painter->fillRect(option.rect, QBrush(QColor(255, 0, 0))); // 获取信息数据 SchemeDataInfo::SchemeInfo info = g_CanvasSchemeManager->getSchemeInfo(index.row()); painter->setRenderHint(QPainter::Antialiasing); // 绘制边框 painter->setPen(QColor(253, 135, 50)); if (option.state & QStyle::State_Selected) painter->setBrush(QBrush(QColor(253, 135, 50))); else if (option.state & QStyle::State_MouseOver) painter->setBrush(QBrush(QColor(253, 135, 50, 100))); else { painter->setBrush(QBrush(QColor(100, 100, 100))); } painter->drawRoundedRect(option.rect, 4, 4); // 绘制图标 int fontHeight = painter->fontMetrics().height() + 5; QRect iconRect = option.rect.adjusted(2, 3, -2, -fontHeight); if (!info.image.isNull()) { qreal rato = info.image.width() * 1.0 / info.image.height(); int height = qMin((int)(iconRect.width() / rato), iconRect.height()); int width = rato * height; QRect imageRect(iconRect.x() + (iconRect.width() - width) / 2, \ iconRect.y() + (iconRect.height() - height) / 2, \ width, height); painter->drawImage(imageRect, info.image); } // 绘制文本 QString schemeName = info.schemeName; painter->setPen(QColor(255, 255, 255)); QTextOption o; o.setAlignment(Qt::AlignBottom | Qt::AlignHCenter); QRect textRect = option.rect.adjusted(0, 0, 0, -2); painter->drawText(textRect, schemeName, o); } QWidget *SchemeManagerDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QLineEdit* lineEdit = new QLineEdit(parent); int rowIndex = index.row(); QString schemeName = g_CanvasSchemeManager->getSchemeName(rowIndex); lineEdit->setText(schemeName); return lineEdit; } void SchemeManagerDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit* pLineEdit = qobject_cast(editor); if (pLineEdit == nullptr) return; int rowIndex = index.row(); QString schemeName = g_CanvasSchemeManager->getSchemeName(rowIndex); pLineEdit->setText(schemeName); } void SchemeManagerDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (model == nullptr || !index.isValid()) return; QLineEdit* pLineEdit = qobject_cast(editor); if (pLineEdit == nullptr) return; QString name = pLineEdit->text(); if (name.isEmpty()) return; model->setData(index, name, Qt::EditRole); } QSize SchemeManagerDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(320, 180); } void SchemeManagerDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const { QRect nRect = option.rect; QFontMetrics fontMetrics(option.font); nRect.adjust(0, nRect.height() - fontMetrics.height(), 0, 2); editor->setGeometry(nRect); } ================================================ FILE: EasyCanvasCore/Scheme/UISchemeManagerWidget.h ================================================ #ifndef UISCHEMEMANAGERWIDGET_H #define UISCHEMEMANAGERWIDGET_H #include #include #include #include #include #include "easycanvascore_global.h" class SchemeManagerModel; class SchemeManagerDelegate; class EASYCANVASCORESHARED_EXPORT UISchemeManagerWidget : public QListView { Q_OBJECT public: explicit UISchemeManagerWidget(QWidget* parent = nullptr); ~UISchemeManagerWidget(); // 同步数据 void syncFromData(void); // 获取当前选择的方案 QString getCurrentSelectedSchemeName(void); private: SchemeManagerModel* m_pModel = nullptr; SchemeManagerDelegate* m_delegate = nullptr; }; // ========================== Model =================================== class SchemeManagerModel : public QAbstractListModel { Q_OBJECT public: explicit SchemeManagerModel(QObject* parent = nullptr); ~SchemeManagerModel() override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; Qt::ItemFlags flags(const QModelIndex &index) const override; }; // ========================== Delegate =================================== class SchemeManagerDelegate : public QStyledItemDelegate { Q_OBJECT public: explicit SchemeManagerDelegate(QObject* parent = nullptr); ~SchemeManagerDelegate() override; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasAudioItem.cpp ================================================ #include "UICanvasAudioItem.h" #include #include #include "Utils.h" #include "NDStringAttribute.h" #include "NDColorAttribute.h" #include "NDNodeBase.h" #include "AudioPlayer.h" #include #include #include #include "Utils.h" UICanvasAudioItem::UICanvasAudioItem(QGraphicsItem* parentItem) :UICanvasItemBase(parentItem) , m_cStartColor(150, 255, 200) , m_cEndColor(46, 216, 130) { setCurrentSize(QSize(300, 60)); initAttributes(); m_pAudioPlayer = new AudioPlayer(this); QObject::connect(m_pAudioPlayer, &AudioPlayer::playFinished, \ this, &UICanvasAudioItem::onAudioPlayFinished); } UICanvasAudioItem::~UICanvasAudioItem() { } void UICanvasAudioItem::setCurrentSize(const QSize& size) { m_size = size; this->setItemResizeable(true); this->setItemResizeRatio(true, m_size.width() * 1.0 / size.height()); this->updateAttribute(); } void UICanvasAudioItem::mousePressEvent(QGraphicsSceneMouseEvent* event) { QRectF rect = this->getCustomRect(); qreal interval = rect.height() / 4.0; QPointF centerPos(rect.topLeft().x() + interval * 2, rect.topLeft().y() + interval * 2); QPointF localPos = event->pos(); if (g_utilTool->getDistance(centerPos, localPos) < interval && m_isOpenSuccessed) { // 点击播放 if (m_pAudioPlayer->getCurrentPlayStatus() != AudioPlayer::t_playing) m_pAudioPlayer->play(); else m_pAudioPlayer->stop(); this->update(); } else { return UICanvasItemBase::mousePressEvent(event); } } void UICanvasAudioItem::customPaint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { painter->save(); QRectF rect = this->getCustomRect(); QLinearGradient lineGradient(rect.topLeft(), rect.topRight()); lineGradient.setColorAt(0, m_cStartColor); lineGradient.setColorAt(1.0, m_cEndColor); painter->setBrush(lineGradient); QPen pen; pen.setWidth(1); pen.setColor(QColor(200, 200, 200)); painter->setPen(pen); qreal radius = rect.height() / 2.0; painter->drawRoundedRect(rect, radius, radius); // 绘制中间的圆圈 painter->setPen(Qt::NoPen); painter->setBrush(QColor(255, 255, 255)); qreal interval = rect.height() / 4.0; QPointF centerPos(rect.topLeft().x() + interval * 2, rect.topLeft().y() + interval * 2); painter->drawEllipse(centerPos, interval, interval); // 绘制播放状态 if (!isPlaying()) { // 绘制播放的三角形 QPolygonF polyon; polyon << QPointF(centerPos.x() - interval / 2 * cos(PI / 3), centerPos.y() - interval / 2 * sin(PI / 3)); polyon << QPointF(centerPos.x() - interval / 2 * cos(PI / 3), centerPos.y() + interval / 2 * sin(PI / 3)); polyon << QPointF(centerPos.x() + interval / 2, centerPos.y()); painter->setBrush(m_cStartColor); painter->drawPolygon(polyon); } else { // 绘制正方形 qreal nWidth = interval * cos(PI / 6); QRectF palyRectF(centerPos.x() - nWidth / 2, centerPos.y() - nWidth / 2, nWidth, nWidth); painter->setBrush(m_cStartColor); painter->drawRect(palyRectF); } // 绘制时间 QFont font = painter->font(); font.setPixelSize(interval * 2); painter->setFont(font); pen.setColor(QColor(255, 255, 255)); painter->setPen(pen); QString timeString = "%1:%2\""; timeString = timeString.arg(m_nTotlaAudioTime / 1000 / 60, 2, 10, QChar('0'))\ .arg(m_nTotlaAudioTime / 1000 % 60, 2, 10, QChar('0')); int width = painter->fontMetrics().width(timeString); QRectF timeRectF(rect.right() - width - interval, rect.top() + interval, \ width, interval * 2); QTextOption o; painter->drawText(timeRectF, timeString); painter->restore(); } void UICanvasAudioItem::initAttributes(void) { QString otherAttrs = tr("Other Attribute"); m_pNode->addAttributeGroup(otherAttrs); // 音频文件路径 m_pFilePathAttribute = new NDStringAttribute; m_pFilePathAttribute->setValue("Test Value"); m_pFilePathAttribute->setDisplayName(tr("Audio File Path: ")); m_pFilePathAttribute->setName("path"); m_pFilePathAttribute->setShowButton(true); m_pFilePathAttribute->setButtonString(tr("Browse")); m_pFilePathAttribute->setButtonFunction(std::bind(&UICanvasAudioItem::showFileBroseDialo, this, \ std::placeholders::_1)); m_pNode->addAttribute(otherAttrs, m_pFilePathAttribute); // 颜色属性 // 开始颜色 m_pStartColorAttribute = new NDColorAttribute; m_pStartColorAttribute->setValue(m_cStartColor); m_pStartColorAttribute->setDisplayName(tr("Start Color: ")); m_pStartColorAttribute->setName("startColor"); m_pNode->addAttribute(otherAttrs, m_pStartColorAttribute); // 终止颜色 m_pEndColorAttribute = new NDColorAttribute; m_pEndColorAttribute->setValue(m_cEndColor); m_pEndColorAttribute->setDisplayName(tr("End Color: ")); m_pEndColorAttribute->setName("endColor"); m_pNode->addAttribute(otherAttrs, m_pEndColorAttribute); // 连接信号和槽函数 QObject::connect(m_pStartColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasAudioItem::onStartColorValueChanged); QObject::connect(m_pEndColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasAudioItem::onEndColorValueChanged); QObject::connect(m_pFilePathAttribute, &NDStringAttribute::valueChanged, this, &UICanvasAudioItem::onTextChanged); } bool UICanvasAudioItem::showFileBroseDialo(QString& str) { QString curAppPath = qApp->applicationDirPath() + "/"; QString fileName = QFileDialog::getOpenFileName(nullptr, tr("Open Audio File"), curAppPath + "./", \ tr("Audio Files (*.wav *.mp3)")); if (fileName.isEmpty()) return false; str = fileName; return true; } bool UICanvasAudioItem::isPlaying(void) { if (m_pAudioPlayer == nullptr || !m_isOpenSuccessed) return false; if (m_pAudioPlayer->getCurrentPlayStatus() == AudioPlayer::t_playing) return true; return false; } void UICanvasAudioItem::onStartColorValueChanged(const QVariant& color) { m_cStartColor = color.value(); this->update(); } void UICanvasAudioItem::onEndColorValueChanged(const QVariant& color) { m_cEndColor = color.value(); this->update(); } void UICanvasAudioItem::onTextChanged(const QVariant& fileName) { m_pAudioPlayer->stop(); m_pAudioPlayer->close(); m_isOpenSuccessed = m_pAudioPlayer->openAudioFile(fileName.toString()); if (!m_isOpenSuccessed) return; AudioPlayer::AudioInfo info = m_pAudioPlayer->getInfo(); m_nTotlaAudioTime = info.totalTime; } void UICanvasAudioItem::onAudioPlayFinished(void) { this->update(); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasAudioItem.h ================================================ #ifndef UICANVASAUDIOITEM_H #define UICANVASAUDIOITEM_H #include "UICanvasItemBase.h" #include class NDStringAttribute; class NDColorAttribute; class AudioPlayer; class UICanvasAudioItem : public UICanvasItemBase { Q_OBJECT public: UICanvasAudioItem(QGraphicsItem* parentItem = nullptr); ~UICanvasAudioItem(); void setCurrentSize(const QSize& size); protected: void mousePressEvent(QGraphicsSceneMouseEvent *event) override; void customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; private: QColor m_cStartColor; QColor m_cEndColor; int m_nTotlaAudioTime = 0; // ms NDStringAttribute* m_pFilePathAttribute = nullptr; // 文件路径 NDColorAttribute* m_pStartColorAttribute = nullptr; // 开始颜色 NDColorAttribute* m_pEndColorAttribute = nullptr; // 结束颜色 void initAttributes(void); // 设置音频文件 bool showFileBroseDialo(QString& str); AudioPlayer* m_pAudioPlayer = nullptr; bool m_isOpenSuccessed = false; // 判断当前是否在播放 bool isPlaying(void); private slots: void onStartColorValueChanged(const QVariant& color); void onEndColorValueChanged(const QVariant& color); void onTextChanged(const QVariant& fileName); void onAudioPlayFinished(void); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasEllipseItem.cpp ================================================ #include "UICanvasEllipseItem.h" #include "NDNodeBase.h" #include "NDBoolAttribute.h" #include "NDIntAttribute.h" #include "NDColorAttribute.h" #include UICanvasEllipseItem::UICanvasEllipseItem(QGraphicsItem* parentItem) :UICanvasItemBase(parentItem) { initAttribute(); } UICanvasEllipseItem::~UICanvasEllipseItem() { } void UICanvasEllipseItem::setSize(int width, int height) { m_size.setWidth(width); m_size.setHeight(height); this->prepareGeometryChange(); } void UICanvasEllipseItem::customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->save(); // 设置画笔 if (m_pBOutLineAttribute->getValue().toBool()) { QPen pen; pen.setWidth(m_pOutLineWidthAttribute->getValue().toInt()); pen.setColor(m_pOutLineColorAttribute->getValue().value()); painter->setPen(pen); } else { painter->setPen(Qt::NoPen); } // 设置画刷 if (m_pBFillAttribute->getValue().toBool()) { painter->setBrush(QBrush(m_pFillColorAttribute->getValue().value())); } else { painter->setBrush(Qt::NoBrush); } QRectF rect = this->getCustomRect(); painter->drawEllipse(rect); painter->restore(); } void UICanvasEllipseItem::initAttribute() { QString groupName = tr("Item Attribute"); m_pNode->addAttributeGroup(groupName); // 是否为圆形 m_pBRoundAttribute = new NDBoolAttribute; m_pBRoundAttribute->setValue(true); m_pBRoundAttribute->setDisplayName(tr("Is Rounded: ")); m_pBRoundAttribute->setName("bRounded"); m_pNode->addAttribute(groupName, m_pBRoundAttribute); // 添加是否填充属性 m_pBFillAttribute = new NDBoolAttribute; m_pBFillAttribute->setValue(false); m_pBFillAttribute->setDisplayName(tr("Is Fill Color: ")); m_pBFillAttribute->setName("bFillColor"); m_pNode->addAttribute(groupName, m_pBFillAttribute); // 添加填充颜色 m_pFillColorAttribute = new NDColorAttribute; m_pFillColorAttribute->setEnable(false); m_pFillColorAttribute->setValue(QColor(150, 150, 150)); m_pFillColorAttribute->setDisplayName(tr("Fill Color: ")); m_pFillColorAttribute->setName("fillColor"); m_pNode->addAttribute(groupName, m_pFillColorAttribute); // 添加是否显示轮廓线 m_pBOutLineAttribute = new NDBoolAttribute; m_pBOutLineAttribute->setValue(true); m_pBOutLineAttribute->setDisplayName(tr("Show OutLine: ")); m_pBOutLineAttribute->setName("bOutline"); m_pNode->addAttribute(groupName, m_pBOutLineAttribute); // 轮廓线宽度 m_pOutLineWidthAttribute = new NDIntAttribute; m_pOutLineWidthAttribute->setValue(1); m_pOutLineWidthAttribute->setValueRange(1, 20); m_pOutLineWidthAttribute->setDisplayName(tr("OutLine Width: ")); m_pOutLineWidthAttribute->setName("outlineWidth"); m_pNode->addAttribute(groupName, m_pOutLineWidthAttribute); // 轮廓线颜色 m_pOutLineColorAttribute = new NDColorAttribute; m_pOutLineColorAttribute->setValue(QColor(10, 10, 10)); m_pOutLineColorAttribute->setDisplayName(tr("OutLine Color: ")); m_pOutLineColorAttribute->setName("outlineColor"); m_pNode->addAttribute(groupName, m_pOutLineColorAttribute); // 连接信号和槽 QObject::connect(m_pBRoundAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasEllipseItem::onRoundValueChanged); QObject::connect(m_pBFillAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasEllipseItem::onValueChanged); QObject::connect(m_pFillColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasEllipseItem::onValueChanged); QObject::connect(m_pBOutLineAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasEllipseItem::onValueChanged); QObject::connect(m_pOutLineWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasEllipseItem::onValueChanged); QObject::connect(m_pOutLineColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasEllipseItem::onValueChanged); } void UICanvasEllipseItem::onValueChanged(void) { this->update(); } void UICanvasEllipseItem::onRoundValueChanged(const QVariant& value) { this->setItemResizeable(true); this->setItemResizeRatio(value.toBool(), 1.0); if (value.toBool()) { int width = m_size.width(); m_size.setHeight(width); this->prepareGeometryChange(); } } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasEllipseItem.h ================================================ #ifndef UICANVASELLIPSEITEM_H #define UICANVASELLIPSEITEM_H #include "UICanvasItemBase.h" #include class NDIntAttribute; class NDBoolAttribute; class NDColorAttribute; class UICanvasEllipseItem : public UICanvasItemBase { Q_OBJECT public: UICanvasEllipseItem(QGraphicsItem* parentItem = nullptr); ~UICanvasEllipseItem(); // 设置尺寸 void setSize(int width, int height); protected: void customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); private: // 属性相关 void initAttribute(); NDBoolAttribute* m_pBRoundAttribute = nullptr; // 是否为圆形 NDBoolAttribute* m_pBFillAttribute = nullptr; // 是否为填充颜色 NDColorAttribute* m_pFillColorAttribute = nullptr; // 填充的颜色 NDBoolAttribute* m_pBOutLineAttribute = nullptr; // 是否显示轮廓线 NDIntAttribute* m_pOutLineWidthAttribute = nullptr; // 轮廓线宽度 NDColorAttribute* m_pOutLineColorAttribute = nullptr; // 轮廓线颜色 private slots: void onValueChanged(void); void onRoundValueChanged(const QVariant& value); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasImageItem.cpp ================================================ #include "UICanvasImageItem.h" #include "NDStringAttribute.h" #include "NDNodeBase.h" #include #include #include #include UICanvasImageItem::UICanvasImageItem(QGraphicsItem* parentItem) :UICanvasItemBase(parentItem) { initAttribute(); QString curAppPath = qApp->applicationDirPath() + "/"; setImage(curAppPath + "./t3.jpg"); } UICanvasImageItem::~UICanvasImageItem() { } void UICanvasImageItem::customPaint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { painter->save(); QRectF customRect = this->getCustomRect(); QRect pixRect(customRect.x(), customRect.y(), customRect.width(), customRect.height()); painter->drawPixmap(pixRect, m_pixmap); painter->restore(); } void UICanvasImageItem::setImage(const QString& filePath) { QImage image(filePath); m_pixmap = QPixmap::fromImage(image); if (!m_pixmap.isNull()) { // 设置 size m_size.setWidth(m_pixmap.width()); m_size.setHeight(m_pixmap.height()); // 设置改变大小属性 this->setItemResizeable(true); this->setItemResizeRatio(true, m_size.width() * 1.0 / m_size.height()); // 设置属性 QObject::disconnect(m_pFilePathAttribute, &NDStringAttribute::valueChanged, this, &UICanvasImageItem::onAttributeValueChanged); m_pFilePathAttribute->setValue(filePath); QObject::connect(m_pFilePathAttribute, &NDStringAttribute::valueChanged, this, &UICanvasImageItem::onAttributeValueChanged); } this->update(); } void UICanvasImageItem::initAttribute(void) { // 添加属性组 QString attributeGroupName = tr("Image Attribute"); m_pNode->addAttributeGroup(attributeGroupName); // 创建属性 m_pFilePathAttribute = new NDStringAttribute; m_pFilePathAttribute->setDisplayName(tr("Image Path: ")); m_pFilePathAttribute->setName("imagePath"); m_pFilePathAttribute->setShowButton(true); m_pFilePathAttribute->setButtonString(tr("Browse")); m_pFilePathAttribute->setButtonFunction(std::bind(&UICanvasImageItem::showFileBrowseDialo, \ this, std::placeholders::_1)); m_pNode->addAttribute(attributeGroupName, m_pFilePathAttribute); // 连接信号和槽函数 QObject::connect(m_pFilePathAttribute, &NDStringAttribute::valueChanged, \ this, &UICanvasImageItem::onAttributeValueChanged); } bool UICanvasImageItem::showFileBrowseDialo(QString& str) { QString curAppPath = qApp->applicationDirPath() + "/"; QString fileName = QFileDialog::getOpenFileName(nullptr, tr("Open Image File"), curAppPath + "./", \ tr("Image Files (*.bmp *.png *.jpg)")); if (fileName.isEmpty()) return false; str = fileName; return true; } void UICanvasImageItem::onAttributeValueChanged(const QVariant& value) { this->setImage(value.toString()); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasImageItem.h ================================================ #ifndef UICANVASIMAGEITEM_H #define UICANVASIMAGEITEM_H #include "UICanvasItemBase.h" #include class NDStringAttribute; class UICanvasImageItem : public UICanvasItemBase { Q_OBJECT public: UICanvasImageItem(QGraphicsItem* parentItem = nullptr); ~UICanvasImageItem(); // 设置图像 void setImage(const QString& filePath); protected: // 自定义元素绘制 virtual void customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); private: QPixmap m_pixmap; // 初始化属性 void initAttribute(void); // 图片文件目录 NDStringAttribute* m_pFilePathAttribute = nullptr; // 设置函数 bool showFileBrowseDialo(QString& str); private slots: void onAttributeValueChanged(const QVariant& value); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasItemBase.cpp ================================================ #include "UICanvasItemBase.h" #include "Utils.h" #include #include #include #include #include #include #include #include #include #include #include #include "NDNodeBase.h" #include "NDAttributeBase.h" #include "NDRealAttribute.h" #include "NDIntAttribute.h" #include "RALLBlockSignal.h" #include "UICanvasItemManager.h" #include "UICanvasView.h" QImage UICanvasItemBase::m_closeIcon; QImage UICanvasItemBase::m_resizeIcon; QImage UICanvasItemBase::m_rotateIcon; UICanvasItemBase::UICanvasItemBase(QGraphicsItem* parentItem) :QGraphicsItem(parentItem) , m_cPenColor(255, 0, 0) , m_cBrushColor(200, 100, 100) { this->setFlag(QGraphicsItem::ItemIsSelectable, true); this->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); initIcon(); // 初始化基本属性 initNodeBase(); // 获取中心位置 m_size = QSize(100, 100); QPointF centerPos = g_currentCanvasManager->getCurrentCanvasView()->getCenterPos(); this->setPos(centerPos); } UICanvasItemBase::~UICanvasItemBase() { } void UICanvasItemBase::setItemResizeable(bool resizeable) { m_isResizeable = resizeable; } NDNodeBase* UICanvasItemBase::getCurrentNode(void) const { return m_pNode; } void UICanvasItemBase::setItemResizeRatio(bool resizeRation, qreal rationValue) { m_isRatioScale = resizeRation; m_ratioValue = rationValue; } QRectF UICanvasItemBase::boundingRect() const { QRectF rectF = getCustomRect(); if (!this->isSelected()) return rectF; rectF.adjust(-m_nInterval, -m_nInterval, m_nInterval, m_nInterval); rectF.adjust(-m_nEllipseWidth, -m_nEllipseWidth, m_nEllipseWidth, m_nEllipseWidth); return rectF; } void UICanvasItemBase::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { painter->setRenderHint(QPainter::Antialiasing, true); painter->setRenderHint(QPainter::SmoothPixmapTransform, true); painter->setRenderHint(QPainter::TextAntialiasing, true); // 自定义绘制 customPaint(painter, option, widget); if (!this->isSelected()) return; // 设置画笔 QPen pen; pen.setWidth(m_nPenWidth); pen.setColor(m_cPenColor); pen.setStyle(Qt::DashLine); painter->setPen(pen); QRectF itemRect = this->getCustomRect(); // 绘制轮廓线 QRectF outLintRect = itemRect.adjusted(-m_nInterval, -m_nInterval, m_nInterval, m_nInterval); painter->drawRect(outLintRect); painter->setPen(Qt::NoPen); painter->setBrush(m_cBrushColor); // 绘制控制点 painter->drawEllipse(outLintRect.topRight(), m_nEllipseWidth, m_nEllipseWidth); if (!m_closePixmap.isNull()) painter->drawPixmap(QRect(outLintRect.topRight().x() - m_nEllipseWidth / 2, \ outLintRect.topRight().y() - m_nEllipseWidth / 2, \ m_nEllipseWidth, m_nEllipseWidth), m_closePixmap); painter->drawEllipse(outLintRect.bottomLeft(), m_nEllipseWidth, m_nEllipseWidth); if (!m_rotatePixmap.isNull()) painter->drawPixmap(QRect(outLintRect.bottomLeft().x() - m_nEllipseWidth / 2, \ outLintRect.bottomLeft().y() - m_nEllipseWidth / 2, \ m_nEllipseWidth, m_nEllipseWidth), m_rotatePixmap); if (m_isResizeable) { painter->drawEllipse(outLintRect.bottomRight(), m_nEllipseWidth, m_nEllipseWidth); if (!m_resizePixmap.isNull()) painter->drawPixmap(QRect(outLintRect.bottomRight().x() - m_nEllipseWidth / 2, \ outLintRect.bottomRight().y() - m_nEllipseWidth / 2, \ m_nEllipseWidth, m_nEllipseWidth), m_resizePixmap); } } QPainterPath UICanvasItemBase::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; } void UICanvasItemBase::mousePressEvent(QGraphicsSceneMouseEvent* event) { QRectF itemRect = this->getCustomRect(); QRectF outLintRect = itemRect.adjusted(-m_nInterval, -m_nInterval, m_nInterval, m_nInterval); // 获取当前模式 QPointF pos = event->pos(); QPointF scenePos = event->scenePos(); if (itemRect.contains(pos)) m_itemOper = t_move; else if (g_utilTool->getDistance(pos, outLintRect.topRight()) <= m_nEllipseWidth) { g_currentCanvasManager->deleteCanvasItem(m_pNode); return; } else if (g_utilTool->getDistance(pos, outLintRect.bottomLeft()) <= m_nEllipseWidth) m_itemOper = t_rotate; else if (g_utilTool->getDistance(pos, outLintRect.bottomRight()) <= m_nEllipseWidth) m_itemOper = t_resize; // 保存当前的一些信息 m_pos = pos; m_pressedPos = scenePos; m_startPos = this->pos(); m_startRotate = m_rotate; m_startSize = m_size; return QGraphicsItem::mousePressEvent(event); } void UICanvasItemBase::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { // 获取场景坐标和本地坐标 QPointF scenePos = event->scenePos(); QPointF pos = event->pos(); if (m_itemOper == t_move) { // 处理移动 mouseMoveMoveOperator(scenePos, pos); } else if (m_itemOper == t_resize) { // 处理更改大小 mouseMoveResizeOperator(scenePos, pos); } else if (m_itemOper == t_rotate) { // 处理旋转 mouseMoveRotateOperator(scenePos, pos); } return QGraphicsItem::mouseMoveEvent(event); } void UICanvasItemBase::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { // 获取场景坐标和本地坐标 QPointF scenePos = event->scenePos(); QPointF pos = event->pos(); if (m_itemOper == t_move) { // 处理移动 mouseReleaseMoveOperator(scenePos, pos); } else if (m_itemOper == t_resize) { // 处理更改大小 mouseReleaseResizeOperator(scenePos, pos); } else if (m_itemOper == t_rotate) { // 处理旋转 mouseReleaseRotateOperator(scenePos, pos); } m_itemOper = t_none; return QGraphicsItem::mouseReleaseEvent(event); } QVariant UICanvasItemBase::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant& value) { if (change == QGraphicsItem::ItemSelectedChange) prepareGeometryChange(); else if (change == QGraphicsItem::ItemPositionHasChanged) { updateAttribute(); } return QGraphicsItem::itemChange(change, value); } void UICanvasItemBase::mouseMoveMoveOperator(const QPointF& scenePos, const QPointF& loacalPos) { qreal xInterval = scenePos.x() - m_pressedPos.x(); qreal yInterval = scenePos.y() - m_pressedPos.y(); this->setPos(m_startPos + QPointF(xInterval, yInterval)); this->update(); } void UICanvasItemBase::mouseMoveResizeOperator(const QPointF& scenePos, const QPointF& loacalPos) { if (!m_isResizeable) return; qreal ratio = m_ratioValue; qreal itemWidth = abs(loacalPos.x()) * 2 - m_nInterval - m_nEllipseWidth; qreal itemHeight = abs(loacalPos.y()) * 2 - m_nInterval - m_nEllipseWidth; if (m_isRatioScale) itemHeight = itemWidth * 1.0 / ratio; // 设置图片的最小大小为10 if (itemWidth < 10 || itemHeight < 10) return; m_size = QSize(itemWidth, itemHeight); m_pWidthAttribute->setValue(m_size.width()); m_pHeightAttribute->setValue(m_size.height()); this->update(); } void UICanvasItemBase::mouseMoveRotateOperator(const QPointF& scenePos, const QPointF& loacalPos) { // 获取并设置为单位向量 QVector2D startVec(m_pos.x() - 0, m_pos.y() - 0); startVec.normalize(); QVector2D endVec(loacalPos.x() - 0, loacalPos.y() - 0); endVec.normalize(); // 单位向量点乘,计算角度 qreal dotValue = QVector2D::dotProduct(startVec, endVec); if (dotValue > 1.0) dotValue = 1.0; else if (dotValue < -1.0) dotValue = -1.0; dotValue = qAcos(dotValue); if (isnan(dotValue)) dotValue = 0.0; // 获取角度 qreal angle = dotValue * 1.0 / (PI / 180); // 向量叉乘获取方向 QVector3D crossValue = QVector3D::crossProduct(QVector3D(startVec, 1.0), QVector3D(endVec, 1.0)); if (crossValue.z() < 0) angle = -angle; m_rotate += angle; // 设置角度在0~360之间 if (m_rotate >= 360) m_rotate -= 360; else if (m_rotate < 0) m_rotate += 360; // 设置变化矩阵 QTransform transform; transform.rotate(m_rotate); this->setTransform(transform); m_pRotateAttribute->setValue(m_rotate); this->update(); } void UICanvasItemBase::mouseReleaseMoveOperator(const QPointF& scenePos, const QPointF& loacalPos) { QList attributes; QVector values; QVector oldValues; attributes << m_pXPostionAttribute << m_pYPostionAttribute; oldValues << m_startPos.x() << m_startPos.y(); values << this->pos().x() << this->pos().y(); g_currentCanvasManager->changedAttributeValues(attributes, oldValues); g_currentCanvasManager->changedAttributeValues(attributes, values, true); } void UICanvasItemBase::mouseReleaseResizeOperator(const QPointF& scenePos, const QPointF& loacalPos) { QList attributes; QVector values; QVector oldValues; attributes << m_pWidthAttribute << m_pHeightAttribute; oldValues << m_startSize.width() << m_startSize.height(); values << m_size.width() << m_size.height(); g_currentCanvasManager->changedAttributeValues(attributes, oldValues); g_currentCanvasManager->changedAttributeValues(attributes, values, true); } void UICanvasItemBase::mouseReleaseRotateOperator(const QPointF& scenePos, const QPointF& loacalPos) { qreal tempRotate = m_rotate; m_pRotateAttribute->setValue(m_startRotate); m_pRotateAttribute->setValue(tempRotate, true); } void UICanvasItemBase::customPaint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { } QRectF UICanvasItemBase::getCustomRect(void) const { QPointF centerPos(0, 0); return QRectF(centerPos.x() - m_size.width() / 2, centerPos.y() - m_size.height() / 2, \ m_size.width(), m_size.height()); } void UICanvasItemBase::initIcon(void) { QString curAppPath = qApp->applicationDirPath() + "/"; if (m_closeIcon.isNull()) m_closeIcon.load(curAppPath + "./Images/close.png"); if (m_resizeIcon.isNull()) m_resizeIcon.load(curAppPath + "./Images/resize.png"); if (m_rotateIcon.isNull()) m_rotateIcon.load(curAppPath + "./Images/rotate.png"); m_closePixmap = QPixmap::fromImage(m_closeIcon); m_resizePixmap = QPixmap::fromImage(m_resizeIcon); m_rotatePixmap = QPixmap::fromImage(m_rotateIcon); } void UICanvasItemBase::initNodeBase(void) { // 创建节点 m_pNode = new NDNodeBase(this); // 添加属性组 QString attributeGroupString = tr("Base Attribute"); NDAttributeGroup* pGroup = m_pNode->addAttributeGroup("BaseAttr", attributeGroupString); // X坐标 m_pXPostionAttribute = new NDRealAttribute; m_pXPostionAttribute->setDisplayName(tr("X Postion: ")); m_pXPostionAttribute->setName("xPt"); m_pXPostionAttribute->setValueRange(0, 5000); m_pNode->addAttribute(pGroup, m_pXPostionAttribute); // Y坐标 m_pYPostionAttribute = new NDRealAttribute; m_pYPostionAttribute->setDisplayName(tr("Y Postion: ")); m_pYPostionAttribute->setName("yPt"); m_pYPostionAttribute->setValueRange(0, 5000); m_pNode->addAttribute(pGroup, m_pYPostionAttribute); // Z坐标 m_pZPostionAttribute = new NDRealAttribute; m_pZPostionAttribute->setDisplayName(tr("Z Postion: ")); m_pZPostionAttribute->setName("zPt"); m_pZPostionAttribute->setValueRange(0, 10); m_pNode->addAttribute(pGroup, m_pZPostionAttribute); // 宽度 m_pWidthAttribute = new NDIntAttribute; m_pWidthAttribute->setDisplayName(tr("width: ")); m_pWidthAttribute->setName("width"); m_pWidthAttribute->setValueRange(10, 5000); m_pNode->addAttribute(pGroup, m_pWidthAttribute); // 高度 m_pHeightAttribute = new NDIntAttribute; m_pHeightAttribute->setDisplayName(tr("height: ")); m_pHeightAttribute->setName("height"); m_pHeightAttribute->setValueRange(10, 5000); m_pNode->addAttribute(pGroup, m_pHeightAttribute); // 旋转 m_pRotateAttribute = new NDRealAttribute; m_pRotateAttribute->setDisplayName(tr("Rotate Angle: ")); m_pRotateAttribute->setName("rotate"); m_pRotateAttribute->setValueRange(0, 360); m_pRotateAttribute->setValue(0); m_pNode->addAttribute(pGroup, m_pRotateAttribute); // 连接信号和槽 QObject::connect(m_pXPostionAttribute, &NDRealAttribute::valueChanged, this, &UICanvasItemBase::onXPostionAttributeValueChanged); QObject::connect(m_pYPostionAttribute, &NDRealAttribute::valueChanged, this, &UICanvasItemBase::onYPostionAttributeValueChanged); QObject::connect(m_pZPostionAttribute, &NDRealAttribute::valueChanged, this, &UICanvasItemBase::onZPostionAttributeValueChanged); QObject::connect(m_pWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasItemBase::onWidthAttributeValueChanged); QObject::connect(m_pHeightAttribute, &NDIntAttribute::valueChanged, this, &UICanvasItemBase::onHeightAttributeValueChanged); QObject::connect(m_pRotateAttribute, &NDRealAttribute::valueChanged, this, &UICanvasItemBase::onRotateAttributeValueChanged); } void UICanvasItemBase::updateAttribute(void) { QPointF pos = this->pos(); m_pXPostionAttribute->setValue(pos.x()); m_pYPostionAttribute->setValue(pos.y()); m_pZPostionAttribute->setValue(this->zValue()); m_pWidthAttribute->setValue(m_size.width()); m_pHeightAttribute->setValue(m_size.height()); m_pRotateAttribute->setValue(m_rotate); } // 获取属性字符串 QJsonObject UICanvasItemBase::getStoreJson(int interval) { QJsonObject object; object.insert("name", m_pNode->getNodeName()); object.insert("type", m_pNode->getNodeType()); // 获取属性组 QList attrGroups; m_pNode->getAllAttributeGroups(attrGroups); QJsonObject attrObject; for (auto iter = attrGroups.begin(); iter != attrGroups.end(); ++iter) { // 获取属性列表 QList attrs; (*iter)->getAttributes(attrs); for (auto attrIter = attrs.begin(); attrIter != attrs.end(); ++attrIter) { QString attrName = (*attrIter)->getName(); QVariant value = (*attrIter)->getValue(); if (attrName == "xPt" || attrName == "yPt") value = value.toDouble() + interval; attrObject.insert(attrName, QJsonValue::fromVariant(value)); } } object.insert("attribute", attrObject); return object; } void UICanvasItemBase::fillJsonInfo(const QJsonObject& jsonObject) { QJsonObject object = jsonObject.value("attribute").toObject(); for (auto iter = object.begin(); iter != object.end(); ++iter) { QString attrName = iter.key(); QVariant value = iter.value().toVariant(); NDAttributeBase* pAttr = m_pNode->getAttribute(attrName); if (pAttr == nullptr) continue; pAttr->setValue(value); } } void UICanvasItemBase::setCurrentIndex(int index) { m_nIndex = index; } int UICanvasItemBase::getCurrentIndex(void) { return m_nIndex; } void UICanvasItemBase::onXPostionAttributeValueChanged(const QVariant& value) { QPointF pos = this->pos(); pos.setX(value.toDouble()); this->setPos(pos); } void UICanvasItemBase::onYPostionAttributeValueChanged(const QVariant& value) { QPointF pos = this->pos(); pos.setY(value.toDouble()); this->setPos(pos); } void UICanvasItemBase::onZPostionAttributeValueChanged(const QVariant& value) { this->setZValue(value.toDouble()); } void UICanvasItemBase::onWidthAttributeValueChanged(const QVariant& value) { if (!m_isResizeable) { RALLBlockSingal wdithBlockSingal(m_pWidthAttribute); m_pWidthAttribute->setValue(m_size.width()); return; } qreal ratio = m_ratioValue; qreal itemWidth = value.toInt(); qreal itemHeight = m_size.height(); if (m_isRatioScale) itemHeight = itemWidth * 1.0 / ratio; // 设置图片的最小大小为10 if (itemWidth < 10 || itemHeight < 10) { RALLBlockSingal wdithBlockSingal(m_pWidthAttribute); m_pWidthAttribute->setValue(m_size.width()); return; } m_size.setWidth(itemWidth); m_size.setHeight(itemHeight); QObject::disconnect(m_pHeightAttribute, &NDIntAttribute::valueChanged, this, &UICanvasItemBase::onHeightAttributeValueChanged); m_pHeightAttribute->setValue((int)itemHeight); QObject::connect(m_pHeightAttribute, &NDIntAttribute::valueChanged, this, &UICanvasItemBase::onHeightAttributeValueChanged); this->update(); this->prepareGeometryChange(); } void UICanvasItemBase::onHeightAttributeValueChanged(const QVariant& value) { if (!m_isResizeable) { RALLBlockSingal wdithBlockSingal(m_pHeightAttribute); m_pHeightAttribute->setValue(m_size.height()); return; } qreal ratio = m_ratioValue; qreal itemWidth = m_size.width(); qreal itemHeight = value.toInt(); if (m_isRatioScale) itemWidth = itemHeight * 1.0 * ratio; // 设置图片的最小大小为10 if (itemWidth < 10 || itemHeight < 10) { RALLBlockSingal wdithBlockSingal(m_pHeightAttribute); m_pHeightAttribute->setValue(m_size.height()); return; } m_size.setWidth(itemWidth); m_size.setHeight(itemHeight); QObject::disconnect(m_pWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasItemBase::onWidthAttributeValueChanged); m_pWidthAttribute->setValue((int)itemWidth); QObject::connect(m_pWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasItemBase::onWidthAttributeValueChanged); this->update(); this->prepareGeometryChange(); } void UICanvasItemBase::onRotateAttributeValueChanged(const QVariant& value) { m_rotate = value.toDouble(); QTransform transform; transform.rotate(m_rotate); this->setTransform(transform); this->update(); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasItemBase.h ================================================ #ifndef UICANVASITEMBASE_H #define UICANVASITEMBASE_H #include #include #include #include #include #include "easycanvascore_global.h" class NDNodeBase; class NDAttributeBase; class NDRealAttribute; class NDIntAttribute; class EASYCANVASCORESHARED_EXPORT UICanvasItemBase : public QObject, public QGraphicsItem { Q_OBJECT public: enum ItemOperator { t_none, t_move, t_resize, t_rotate }; UICanvasItemBase(QGraphicsItem* parentItem = nullptr); ~UICanvasItemBase() override; // 获取当前的节点 NDNodeBase* getCurrentNode(void) const; // 设置改变大小相关属性 void setItemResizeable(bool resizeable); void setItemResizeRatio(bool resizeRation, qreal rationValue); // 更新属性显示 virtual void updateAttribute(void); // 获取当前属性Json virtual QJsonObject getStoreJson(int interval = 0); virtual void fillJsonInfo(const QJsonObject& jsonObject); // 设置/获取当前索引 void setCurrentIndex(int index); int getCurrentIndex(void); private: // 初始化Icon void initIcon(void); static QImage m_closeIcon; static QImage m_resizeIcon; static QImage m_rotateIcon; QPixmap m_closePixmap; QPixmap m_resizePixmap; QPixmap m_rotatePixmap; // 设置是否能够更改尺寸 bool m_isResizeable = true; bool m_isRatioScale = true; qreal m_ratioValue = 1.0; int m_nIndex = 0; protected: QRectF boundingRect() const override; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) final; QPainterPath shape() const override; void mousePressEvent(QGraphicsSceneMouseEvent *event) override; void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) override; // 自定义元素绘制 virtual void customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); QSize m_size; ItemOperator m_itemOper = t_none; // 获取自定义绘制所需要的矩形 QRectF getCustomRect(void) const; // 属性 NDNodeBase* m_pNode = nullptr; protected: void initNodeBase(void); // 通用属性 NDRealAttribute* m_pXPostionAttribute = nullptr; NDRealAttribute* m_pYPostionAttribute = nullptr; NDRealAttribute* m_pZPostionAttribute = nullptr; // 宽度和高度属性 NDIntAttribute* m_pWidthAttribute = nullptr; NDIntAttribute* m_pHeightAttribute = nullptr; // 旋转属性 NDRealAttribute* m_pRotateAttribute = nullptr; private slots: void onXPostionAttributeValueChanged(const QVariant& value); void onYPostionAttributeValueChanged(const QVariant& value); void onZPostionAttributeValueChanged(const QVariant& value); void onWidthAttributeValueChanged(const QVariant& value); void onHeightAttributeValueChanged(const QVariant& value); void onRotateAttributeValueChanged(const QVariant& value); protected: // 处理Item上的类型 virtual void mouseMoveMoveOperator(const QPointF& scenePos, const QPointF& loacalPos); virtual void mouseMoveResizeOperator(const QPointF& scenePos, const QPointF& loacalPos); virtual void mouseMoveRotateOperator(const QPointF& scenePos, const QPointF& loacalPos); // 处理鼠标释放 virtual void mouseReleaseMoveOperator(const QPointF& scenePos, const QPointF& loacalPos); virtual void mouseReleaseResizeOperator(const QPointF& scenePos, const QPointF& loacalPos); virtual void mouseReleaseRotateOperator(const QPointF& scenePos, const QPointF& loacalPos); QPointF m_pos; // 本地所坐标点击的点 QPointF m_pressedPos; // 场景坐标点击的点 QPointF m_startPos; // Item再场景坐标的起始坐标 QTransform m_transform; // 变换矩阵 qreal m_startRotate = 0.0; // 起始旋转角度 qreal m_rotate = 0.0; // 当前旋转角度 QSize m_startSize; // 起始矩形 private: int m_nInterval = 20; int m_nEllipseWidth = 12; // 半径 // 画笔设置 QColor m_cPenColor; int m_nPenWidth = 1; // 画刷设置 QColor m_cBrushColor; }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasItemManager.cpp ================================================ #include "UICanvasItemManager.h" #include "UICanvasItemBase.h" #include "NDNodeBase.h" #include "UICanvasRectItem.h" #include "UICanvasEllipseItem.h" #include "UICanvasTextItem.h" #include "UICanvasAudioItem.h" #include "UICanvasPathItem.h" #include "UICanvasImageItem.h" #include "UICanvasView.h" #include "UndoCmd/UndoCmdCore.h" #include #include #include #include #include #include "NDNodeManager.h" QVector UICanvasItemManager::m_canvasList; int UICanvasItemManager::m_nCurrentIndex = -1; UICanvasItemManager::UICanvasItemManager(QObject* parent) :QObject(parent) { for (int var = (int)t_RectItem; var < (int)t_End; ++var) { m_countMap[(CanvasItemType)var].count = 0; m_countMap[(CanvasItemType)var].iconPixmap = getTypeIcon((CanvasItemType)var); } m_pUndoCmdCore = new UndoCmdCore(this); QObject::connect(g_nodeManager, &NDNodeManager::signalAttrValueChanged, \ this, &UICanvasItemManager::onAttributeValueChanged); } UICanvasItemManager::~UICanvasItemManager() { } QString UICanvasItemManager::getTypeName(CanvasItemType type) { switch (type) { case t_CanvasItem: return "CanvasNode"; case t_RectItem: return "RectNode"; case t_TextItem: return "TextNode"; case t_EllipseItem: return "EllipseNode"; case t_ImageItem: return "ImageNode"; case t_PathItem: return "PathNode"; case t_AudioItem: return "AudioNode"; default: return ""; } return ""; } UICanvasItemManager::CanvasItemType UICanvasItemManager::getTypeByName(const QString& name) { if (name == "CanvasNode") return t_CanvasItem; else if (name == "RectNode") return t_RectItem; else if (name == "TextNode") return t_TextItem; else if (name == "EllipseNode") return t_EllipseItem; else if (name == "ImageNode") return t_ImageItem; else if (name == "PathNode") return t_PathItem; else if (name == "AudioNode") return t_AudioItem; return t_None; } void UICanvasItemManager::setCurrentMaxId(int maxId) { m_nMaxIndex = maxId; } // 根节点(画布节点) QJsonObject UICanvasItemManager::getNodeStoreJson(NDNodeBase* pNode) { if (pNode == nullptr) return QJsonObject(); if (pNode == m_pCanvasView->getCurrentSceneNode()) { QJsonObject object; object.insert("name", pNode->getNodeName()); object.insert("type", pNode->getNodeType()); // 获取属性组 QList attrGroups; pNode->getAllAttributeGroups(attrGroups); QJsonObject attrObject; for (auto iter = attrGroups.begin(); iter != attrGroups.end(); ++iter) { // 获取属性列表 QList attrs; (*iter)->getAttributes(attrs); for (auto attrIter = attrs.begin(); attrIter != attrs.end(); ++attrIter) { QString attrName = (*attrIter)->getName(); QVariant value = (*attrIter)->getValue(); attrObject.insert(attrName, QJsonValue::fromVariant(value)); } } object.insert("attribute", attrObject); return object; } auto item = getCanvasItem(pNode->getNodeName()); return item->getStoreJson(); } void UICanvasItemManager::fillNodeJsonInfo(NDNodeBase* pNode, const QJsonObject& jsonObject) { if (pNode == nullptr) return; if (pNode == m_pCanvasView->getCurrentSceneNode()) { QJsonObject object = jsonObject.value("attribute").toObject(); for (auto iter = object.begin(); iter != object.end(); ++iter) { QString attrName = iter.key(); QVariant value = iter.value().toVariant(); NDAttributeBase* pAttr = pNode->getAttribute(attrName); if (pAttr == nullptr) continue; pAttr->setValue(value); } return; } auto item = getCanvasItem(pNode->getNodeName()); return item->fillJsonInfo(jsonObject); } // 获取类别的图标 QIcon UICanvasItemManager::getTypeIcon(CanvasItemType type) { QString curAppPath = qApp->applicationDirPath() + "/"; switch (type) { case t_RectItem: return QIcon(curAppPath + "./images/rectItem.png"); case t_TextItem: return QIcon(curAppPath + "./images/textItem.png"); case t_EllipseItem: return QIcon(curAppPath + "./images/ellipseItem.png"); case t_ImageItem: return QIcon(curAppPath + "./images/imageItem.png"); case t_PathItem: return QIcon(curAppPath + "./images/freeDrawItem.png"); case t_AudioItem: return QIcon(curAppPath + "./images/audioItem.png"); default: return QIcon(); } return QIcon(); } QSharedPointer UICanvasItemManager::createCanvasItem(CanvasItemType type, const QString& nodeName, bool isAdded) { m_pCanvasItemBase.reset(); switch (type) { case t_RectItem: { m_pCanvasItemBase = QSharedPointer(new UICanvasRectItem); break; } case t_TextItem: { m_pCanvasItemBase = QSharedPointer(new UICanvasTextItem); break; } case t_EllipseItem: { m_pCanvasItemBase = QSharedPointer(new UICanvasEllipseItem); break; } case t_ImageItem: { m_pCanvasItemBase = QSharedPointer(new UICanvasImageItem); break; } case t_PathItem: { m_pCanvasItemBase = QSharedPointer(new UICanvasPathItem); break; } case t_AudioItem: { m_pCanvasItemBase = QSharedPointer(new UICanvasAudioItem); break; } default: break; } if (m_pCanvasItemBase == nullptr || !isAdded) return m_pCanvasItemBase; // 设置位置和选中 m_pCanvasView->cleanAllSelected(); m_pCanvasItemBase->setSelected(true); m_pCanvasItemBase->setCurrentIndex(m_nMaxIndex++); // 获取属性名 QString tempNodeName = nodeName; if (tempNodeName.isEmpty() || m_nameHash.find(tempNodeName) != m_nameHash.end()) { // 自动生成节点名 do { tempNodeName = QString("%1_%2").arg(getTypeName(type)).arg(m_countMap[type].count++); } while (m_nameHash.find(tempNodeName) != m_nameHash.end()); } // 设置属性名和类型 NDNodeBase* pNode = m_pCanvasItemBase->getCurrentNode(); pNode->setNodeName(tempNodeName); pNode->setNodeType((int)type); m_pCanvasView->addToScene(m_pCanvasItemBase.data()); // 添加到哈希表中 m_nameHash.insert(tempNodeName, m_pCanvasItemBase); // 发送添加信号 emit addedNode(type, tempNodeName); return m_pCanvasItemBase; } void UICanvasItemManager::addCanvasItem(QSharedPointer pCanvasItem) { if (pCanvasItem == nullptr) return; CanvasItemType type = (CanvasItemType)pCanvasItem->getCurrentNode()->getNodeType(); // 获取属性名 QString tempNodeName = pCanvasItem->getCurrentNode()->getNodeName(); if (tempNodeName.isEmpty() || m_nameHash.find(tempNodeName) != m_nameHash.end()) { // 自动生成节点名 do { tempNodeName = QString("%1_%2").arg(getTypeName(type)).arg(m_countMap[type].count++); } while (m_nameHash.find(tempNodeName) != m_nameHash.end()); } // 设置属性名和类型 NDNodeBase* pNode = pCanvasItem->getCurrentNode(); pNode->setNodeName(tempNodeName); m_pCanvasView->addToScene(pCanvasItem.data()); // 添加到哈希表中 m_nameHash.insert(tempNodeName, pCanvasItem); // 发送添加信号 emit addedNode(pCanvasItem->getCurrentNode()->getNodeType(), tempNodeName); } QSharedPointer UICanvasItemManager::createCanvasItemByCmd(CanvasItemType type) { m_pUndoCmdCore->runCreateCmd((int)type); return m_pCanvasItemBase; } void UICanvasItemManager::deleteCanvasItemByCmd(const QStringList& nodeName) { m_pUndoCmdCore->runDeleteCmd(nodeName); } // 删除节点 void UICanvasItemManager::deleteCanvasItem(NDNodeBase* node) { if (node == nullptr) return; QString name = node->getNodeName(); deleteCanvasItem(name); } void UICanvasItemManager::deleteCanvasItem(const QString& nodeName) { auto iter = m_nameHash.find(nodeName); if (iter == m_nameHash.end()) return; // 刪除 auto canvasItem = iter.value(); int type = canvasItem->getCurrentNode()->getNodeType(); // 从场景中移除元素 m_pCanvasView->removeFromScene(canvasItem.data()); // 移除 m_nameHash.remove(nodeName); emit deletedNode(type, nodeName); } void UICanvasItemManager::deleteCanvasItems(const QStringList& nodeNames) { foreach(const QString & nodeName, nodeNames) { deleteCanvasItem(nodeName); } } void UICanvasItemManager::changedNodeNameCmd(const QString& srcName, const QString& destName) { m_pUndoCmdCore->runChangeNameCmd(srcName, destName); } bool UICanvasItemManager::isCanChangedName(const QString& srcName, const QString& destName) { // 已存在该节点 if (m_nameHash.find(destName) != m_nameHash.end()) { return false; } // 查找节点 auto iter = m_nameHash.find(srcName); if (iter == m_nameHash.end()) return false; return true; } bool UICanvasItemManager::changedNodeName(const QString& srcName, const QString& destName) { // 已存在该节点 if (m_nameHash.find(destName) != m_nameHash.end()) { qDebug() << "Node Name is Existed"; return false; } // 查找节点 auto iter = m_nameHash.find(srcName); if (iter == m_nameHash.end()) return false; // 设置节点名字 auto canvasItem = iter.value(); NDNodeBase* pNode = canvasItem->getCurrentNode(); pNode->setNodeName(destName); m_nameHash.remove(srcName); m_nameHash.insert(destName, canvasItem); // 发送名字更改信号 emit changeNodeName(pNode->getNodeType(), srcName, destName); return true; } QStringList UICanvasItemManager::getAllNodeNames(void) { return m_nameHash.keys(); } NDNodeBase* UICanvasItemManager::getNode(const QString& name) { const auto iter = m_nameHash.find(name); if (iter == m_nameHash.end()) return nullptr; return (*iter)->getCurrentNode(); } QSharedPointer UICanvasItemManager::getCanvasItem(const QString& name) { const auto iter = m_nameHash.find(name); if (iter == m_nameHash.end()) return nullptr; return *iter; } int UICanvasItemManager::getNodeCounts(void) { return (int)t_End - (int)t_None - 2; } int UICanvasItemManager::getNodeCounts(CanvasItemType type) { if (type == t_CanvasItem) return getNodeCounts(); return m_countMap[type].count; } QString UICanvasItemManager::getNodeTypeDisplayName(CanvasItemType type) { return getTypeName(type); } QIcon UICanvasItemManager::getNodeTypeDisplayIcon(CanvasItemType type) { auto iter = m_countMap.find(type); if (iter == m_countMap.end()) return QIcon(); return iter.value().iconPixmap; } UICanvasItemManager* UICanvasItemManager::getCurrentCanvasManager(void) { return m_canvasList[m_nCurrentIndex]; } void UICanvasItemManager::createCanvasManager(void) { UICanvasItemManager* manager = new UICanvasItemManager; m_canvasList.append(manager); } // 设置/获取当前选择 void UICanvasItemManager::setCurrentIndex(int index) { m_nCurrentIndex = index; } int UICanvasItemManager::getCurrentIndex(void) { return m_nCurrentIndex; } // 设置当前的Canvas void UICanvasItemManager::setCurrentCanvasView(UICanvasView* canvasView) { m_pCanvasView = canvasView; } UICanvasView* UICanvasItemManager::getCurrentCanvasView(void) { return m_pCanvasView; } void UICanvasItemManager::cleanAll(void) { // 重置根节点 m_pCanvasView->resetSceneNode(); m_cCopyString = ""; m_nMaxIndex = 1; // 删除所有节点 for (auto iter = m_nameHash.begin(); iter != m_nameHash.end(); ++iter) { UICanvasItemBase* pItem = iter.value().data(); m_pCanvasView->removeFromScene(pItem); NDNodeBase* pNode = pItem->getCurrentNode(); emit deletedNode(pNode->getNodeType(), pNode->getNodeName()); } //清空 Redo/Undo栈 m_pUndoCmdCore->cleanUndoStack(); m_nameHash.clear(); // 重新计数 for (auto iter = m_countMap.begin(); iter != m_countMap.end(); ++iter) iter->count = 0; m_pCanvasItemBase.reset(); } void UICanvasItemManager::changedAttributeValues(const QList& attributes, \ const QVector& values, bool isCmd) { if (isCmd) { m_pUndoCmdCore->runChangedAttrCmd(attributes, values, true); return; } int count = 0; for (auto iter = attributes.begin(); iter != attributes.end(); ++iter) { (*iter)->setValue(values[count++]); } } void UICanvasItemManager::setSelectedNodes(const QStringList& nodeNames) { m_pCanvasView->cleanAllSelected(); foreach(const QString & nodeName, nodeNames) { auto iter = m_nameHash.find(nodeName); if (iter == m_nameHash.end()) continue; (*iter)->setSelected(true); } } QStringList UICanvasItemManager::getSelectedNodes(void) { QStringList nodeNames; QList nodes = m_pCanvasView->getCurrentSelectedNodes(); for (auto iter = nodes.begin(); iter != nodes.end(); ++iter) nodeNames << (*iter)->getNodeName(); return nodeNames; } // 复制选中节点 void UICanvasItemManager::copySelectNodes(void) { QJsonArray jsonArray; QList selectItems = m_pCanvasView->getCurrentSelectedItems(); int count = 0; for (auto iter = selectItems.begin(); iter != selectItems.end(); ++iter) { jsonArray.insert(count++, (*iter)->getStoreJson(30)); } // Json转为字符串 QJsonDocument doc(jsonArray); QByteArray byteArray = doc.toJson(QJsonDocument::Compact); QString jsonString(byteArray); m_cCopyString = jsonString; } void UICanvasItemManager::pasteCmd(void) { m_pUndoCmdCore->runPasteCmd(); } QList> UICanvasItemManager::paste(void) { QList> itemList; QJsonParseError jsonParseError; QJsonDocument doc = QJsonDocument::fromJson(m_cCopyString.toUtf8(), &jsonParseError); if (jsonParseError.error != QJsonParseError::NoError) return itemList; QJsonArray array = doc.array(); for (auto iter = array.begin(); iter != array.end(); ++iter) { QJsonObject object = iter->toObject(); // 创建元素 CanvasItemType canvasType = (CanvasItemType)object.value("type").toInt(); QSharedPointer canvasItem = this->createCanvasItem(canvasType); // 设置元素属性 canvasItem->fillJsonInfo(object); itemList << canvasItem; } return itemList; } // 撤銷和重做相关 void UICanvasItemManager::redo(void) { m_pUndoCmdCore->redo(); } void UICanvasItemManager::undo(void) { m_pUndoCmdCore->undo(); } // 获取Redo/Undo核心类 UndoCmdCore* UICanvasItemManager::getCurrentUndoCmdCore(void) { return m_pUndoCmdCore; } void UICanvasItemManager::onAttributeValueChanged(NDAttributeBase* pAttribute, const QVariant& value, bool cmd) { if (!cmd) return; QList attributeList; attributeList << pAttribute; m_pUndoCmdCore->runChangedAttrCmd(attributeList, value); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasItemManager.h ================================================ #ifndef UICANVASITEMMANAGER_H #define UICANVASITEMMANAGER_H #include #include #include #include #include #include #include "easycanvascore_global.h" class NDNodeBase; class UICanvasItemBase; class UICanvasView; class UndoCmdCore; class NDAttributeBase; #define g_currentCanvasManager UICanvasItemManager::getCurrentCanvasManager() class EASYCANVASCORESHARED_EXPORT UICanvasItemManager : public QObject { Q_OBJECT public: enum CanvasItemType { t_None, t_CanvasItem, t_RectItem, t_TextItem, t_EllipseItem, t_ImageItem, t_PathItem, t_AudioItem, t_End }; struct TypeNodeInfo { quint64 count = 0; // 计数 QIcon iconPixmap; }; public: UICanvasItemManager(QObject* parent = nullptr); ~UICanvasItemManager(); // 创建节点 QSharedPointer createCanvasItemByCmd(CanvasItemType type); QSharedPointer createCanvasItem(CanvasItemType type, const QString& nodeName = "", bool isAdded = true); // 添加节点 void addCanvasItem(QSharedPointer pCanvasItem); // 删除节点 void deleteCanvasItemByCmd(const QStringList& nodeName); void deleteCanvasItem(NDNodeBase* node); void deleteCanvasItem(const QString& nodeName); void deleteCanvasItems(const QStringList& nodeNames); // 替换节点名称 bool isCanChangedName(const QString& srcName, const QString& destName); void changedNodeNameCmd(const QString& srcName, const QString& destName); bool changedNodeName(const QString& srcName, const QString& destName); // 获取所有节点名称 QStringList getAllNodeNames(void); // 查找节点 NDNodeBase* getNode(const QString& name); QSharedPointer getCanvasItem(const QString& name); // 清除所有 void cleanAll(void); // 设置当前的选择列表 void setSelectedNodes(const QStringList& nodeNames); QStringList getSelectedNodes(void); // 复制选中节点 void copySelectNodes(void); // 粘贴 void pasteCmd(void); QList> paste(void); // 批量修该节点属性 void changedAttributeValues(const QList& attributes, \ const QVector& values, bool isCmd = false); // 设置/获取当前的Canvas void setCurrentCanvasView(UICanvasView* canvasView); UICanvasView* getCurrentCanvasView(void); // 获取当前所有节点类型数目 int getNodeCounts(void); // 获取某种节点类别的数目(当前索引的计数) int getNodeCounts(CanvasItemType type); // 获取节点类别的名字 QString getNodeTypeDisplayName(CanvasItemType type); // 获取节点类别的图标 QIcon getNodeTypeDisplayIcon(CanvasItemType type); static UICanvasItemManager* getCurrentCanvasManager(void); // 创建CanvasManager static void createCanvasManager(void); // 设置/获取当前选择 static void setCurrentIndex(int index); static int getCurrentIndex(void); public: // 撤銷和重做相关 void redo(void); void undo(void); // 获取Redo/Undo核心类 UndoCmdCore* getCurrentUndoCmdCore(void); public: // 类型转化为字符串名字 QString getTypeName(CanvasItemType type); CanvasItemType getTypeByName(const QString& name); // 设置当前最大ID void setCurrentMaxId(int maxId); // 根节点(画布节点) QJsonObject getNodeStoreJson(NDNodeBase* pNode); void fillNodeJsonInfo(NDNodeBase* pNode, const QJsonObject& jsonObject); private: int m_nMaxIndex = 1; // 最大索引 QHash> m_nameHash; QMap m_countMap; // 获取类别的图标 QIcon getTypeIcon(CanvasItemType type); // 多个场景管理器 static QVector m_canvasList; static int m_nCurrentIndex; // 当前的CanvasView UICanvasView* m_pCanvasView = nullptr; // UodoCmdCore UndoCmdCore* m_pUndoCmdCore = nullptr; QSharedPointer m_pCanvasItemBase; // 节点复制相关 QString m_cCopyString; signals: void addedNode(int type, const QString& nodeName); void deletedNode(int type, const QString& nodeName); void changeNodeName(int type, const QString& srcName, const QString& destName); private slots: void onAttributeValueChanged(NDAttributeBase* pAttribute, const QVariant& value, bool cmd); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasOperators.cpp ================================================ #include "UICanvasOperators.h" #include "UICanvasView.h" #include "UICanvasPathItem.h" #include "UICanvas/UICanvasItemManager.h" #include "UICanvasItemBase.h" #include "NDNodeBase.h" #include "NDAttributeBase.h" #include "NDRealAttribute.h" #include UICanvasOperBase::UICanvasOperBase(UICanvasView* view) :m_pCanvasView(view) { } UICanvasOperBase::~UICanvasOperBase() { } bool UICanvasOperBase::disposePressEvent(QMouseEvent* event) { return false; } bool UICanvasOperBase::disposeMoveEvent(QMouseEvent* event) { return false; } bool UICanvasOperBase::disposeReleaseEvent(QMouseEvent* event) { m_pCanvasView->setCurrentOperator(new UICanvasDefaultOper(m_pCanvasView)); return false; } bool UICanvasOperBase::disposeKeyPressEvent(QKeyEvent* event) { return false; } // --------------------------------------------------------------------- // 默认操作器,操作器调度器 UICanvasDefaultOper::UICanvasDefaultOper(UICanvasView* view) :UICanvasOperBase(view) { } UICanvasDefaultOper::~UICanvasDefaultOper() { } bool UICanvasDefaultOper::disposePressEvent(QMouseEvent* event) { auto selectedItems = m_pCanvasView->scene()->selectedItems(); auto items = m_pCanvasView->items(event->pos()); UICanvasView::CanvasMode mode = m_pCanvasView->getCurrentMode(); if (mode == UICanvasView::t_FreeDrawMode) { UICanvasPenOper* penFreeDrawOper = new UICanvasPenOper(m_pCanvasView); m_pCanvasView->setCurrentOperator(penFreeDrawOper); return penFreeDrawOper->disposePressEvent(event); } if (selectedItems.size() > 1 && items.size() > 0) { // 查找选择的列表中,是够包含选中的 bool hasSelected = false; foreach (auto item, items) { if (item->isSelected()) { hasSelected = true; break; } } if (!hasSelected) return true; // 设置为多选移动操作器(选中的个数>1 且 当前鼠标下有Item时) UICanvasMoveSelectedItem* moveSelectOper = new UICanvasMoveSelectedItem(m_pCanvasView); m_pCanvasView->setCurrentOperator(moveSelectOper); return moveSelectOper->disposePressEvent(event); } else if (items.size() <= 0) { if (mode == UICanvasView::t_ArrowMode) { // 设置为矩形选择操作器(当前点击的为空白) UICanvasRectSelectOper* rectSelectOper = new UICanvasRectSelectOper(m_pCanvasView); m_pCanvasView->setCurrentOperator(rectSelectOper); return rectSelectOper->disposePressEvent(event); } else if (mode == UICanvasView::t_FreeDrawMode) { UICanvasPenOper* penFreeDrawOper = new UICanvasPenOper(m_pCanvasView); m_pCanvasView->setCurrentOperator(penFreeDrawOper); return penFreeDrawOper->disposePressEvent(event); } } return true; } bool UICanvasDefaultOper::disposeMoveEvent(QMouseEvent* event) { return false; } bool UICanvasDefaultOper::disposeReleaseEvent(QMouseEvent* event) { return false; } bool UICanvasDefaultOper::disposeKeyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Delete) { QStringList selectedNodeNames; // 删除选中的元素 auto selectedItems = m_pCanvasView->scene()->selectedItems(); for (auto item : selectedItems) { UICanvasItemBase* canvasItem = dynamic_cast(item); if (canvasItem == nullptr) continue; selectedNodeNames << canvasItem->getCurrentNode()->getNodeName(); } // 执行删除命令 if (selectedNodeNames.size() > 0) g_currentCanvasManager->deleteCanvasItemByCmd(selectedNodeNames); } else if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) { // 方向键 上和下 微调 auto selectedItems = m_pCanvasView->scene()->selectedItems(); QList m_attrList; QVector m_values; for (auto item : selectedItems) { UICanvasItemBase* canvasItem = dynamic_cast(item); if (canvasItem == nullptr) continue; NDAttributeBase* pAttr = canvasItem->getCurrentNode()->getAttribute("yPt"); NDRealAttribute* pYPtAttr = qobject_cast(pAttr); if (pYPtAttr == nullptr) continue; // 重新设置属性 qreal yPt = pYPtAttr->getValue().toDouble(); if (event->key() == Qt::Key_Up) yPt -= 2; else yPt += 2; m_attrList << pAttr; m_values << yPt; } g_currentCanvasManager->changedAttributeValues(m_attrList, m_values, true); } else if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) { // 方向键 左和右 微调 auto selectedItems = m_pCanvasView->scene()->selectedItems(); QList m_attrList; QVector m_values; for (auto item : selectedItems) { UICanvasItemBase* canvasItem = dynamic_cast(item); if (canvasItem == nullptr) continue; NDAttributeBase* pAttr = canvasItem->getCurrentNode()->getAttribute("xPt"); NDRealAttribute* pXPtAttr = qobject_cast(pAttr); if (pXPtAttr == nullptr) continue; // 重新设置属性 qreal xPt = pXPtAttr->getValue().toDouble(); if (event->key() == Qt::Key_Left) xPt -= 2; else xPt += 2; m_attrList << pAttr; m_values << xPt; } g_currentCanvasManager->changedAttributeValues(m_attrList, m_values, true); } else if ((event->modifiers() & Qt::ControlModifier) && event->key() == Qt::Key_C) { // 复制 g_currentCanvasManager->copySelectNodes(); } else if ((event->modifiers() & Qt::ControlModifier) && event->key() == Qt::Key_V) { // 粘贴 g_currentCanvasManager->pasteCmd(); } return false; } // --------------------------------------------------------------------- // 画笔操作器 UICanvasPenOper::UICanvasPenOper(UICanvasView* view) :UICanvasOperBase(view) { auto item = g_currentCanvasManager->createCanvasItemByCmd(UICanvasItemManager::t_PathItem); m_pPathItem = dynamic_cast(item.data()); m_pPathItem->setPos(0, 0); m_pPathItem->setSelected(false); } UICanvasPenOper::~UICanvasPenOper() { } bool UICanvasPenOper::disposePressEvent(QMouseEvent* event) { QPointF scenePos = m_pCanvasView->mapToScene(event->pos()); m_pPathItem->setStartPos(scenePos); return UICanvasOperBase::disposePressEvent(event); } bool UICanvasPenOper::disposeMoveEvent(QMouseEvent* event) { QPointF scenePos = m_pCanvasView->mapToScene(event->pos()); m_pPathItem->addPoint(scenePos); return UICanvasOperBase::disposeMoveEvent(event); } bool UICanvasPenOper::disposeReleaseEvent(QMouseEvent* event) { m_pPathItem->endDrawPos(); m_pCanvasView->cleanAllSelected(); m_pPathItem->setSelected(true); return UICanvasOperBase::disposeReleaseEvent(event); } // --------------------------------------------------------------------- // 矩形选择操作器 UICanvasRectSelectOper::UICanvasRectSelectOper(UICanvasView* view) :UICanvasOperBase(view) { } UICanvasRectSelectOper::~UICanvasRectSelectOper() { } bool UICanvasRectSelectOper::disposePressEvent(QMouseEvent* event) { // 设置为显示选中矩形 m_pCanvasView->setSelectedRectVisible(true); m_pCanvasView->setSelectedRect(QRect()); // 清除所有选中 auto items = m_pCanvasView->scene()->selectedItems(); foreach(auto item, items) item->setSelected(false); m_pressedViewPos = event->pos(); m_pressedScenePos = m_pCanvasView->mapToScene(event->pos()); return UICanvasOperBase::disposePressEvent(event); } bool UICanvasRectSelectOper::disposeMoveEvent(QMouseEvent* event) { QPoint endPos = event->pos(); m_pCanvasView->setSelectedRect(QRect(m_pressedViewPos, endPos)); return UICanvasOperBase::disposeMoveEvent(event); } bool UICanvasRectSelectOper::disposeReleaseEvent(QMouseEvent* event) { // 选中被选择的矩形 QPointF endPos = m_pCanvasView->mapToScene(event->pos()); qreal xStart = qMin(m_pressedScenePos.x(), endPos.x()); qreal xEnd = qMax(m_pressedScenePos.x(), endPos.x()); qreal yStart = qMin(m_pressedScenePos.y(), endPos.y()); qreal yEnd = qMax(m_pressedScenePos.y(), endPos.y()); //设置矩形值 QRectF rect(QPointF(xStart, yStart), QPointF(xEnd, yEnd)); QList items = m_pCanvasView->scene()->items(rect, Qt::IntersectsItemShape); foreach(auto item, items) item->setSelected(true); m_pCanvasView->setSelectedRectVisible(false); return UICanvasOperBase::disposeReleaseEvent(event); } // --------------------------------------------------------------------- // 多选移动操作器 UICanvasMoveSelectedItem::UICanvasMoveSelectedItem(UICanvasView* view) :UICanvasOperBase(view) { } UICanvasMoveSelectedItem::~UICanvasMoveSelectedItem() { } bool UICanvasMoveSelectedItem::disposePressEvent(QMouseEvent* event) { m_items = m_pCanvasView->scene()->selectedItems(); m_scenePos = m_pCanvasView->mapToScene(event->pos()); foreach (auto item, m_items) { UICanvasItemBase* pItem = qgraphicsitem_cast(item); NDAttributeBase* pXAttr = pItem->getCurrentNode()->getAttribute("xPt"); NDAttributeBase* pYAttr = pItem->getCurrentNode()->getAttribute("yPt"); m_xAttributes << pXAttr; m_yAttributes << pYAttr; m_xValues << pXAttr->getValue(); m_yValues << pYAttr->getValue(); } m_xOldValues = m_xValues; m_yOldValues = m_yValues; return UICanvasOperBase::disposePressEvent(event); } bool UICanvasMoveSelectedItem::disposeMoveEvent(QMouseEvent* event) { QPointF pos = m_pCanvasView->mapToScene(event->pos()); qreal xIntervalue = pos.x() - m_scenePos.x(); qreal yIntervalue = pos.y() - m_scenePos.y(); m_scenePos = pos; // 重新设置全部选中的坐标 int count = 0; foreach (auto item, m_items) { QPointF itemPos = item->pos(); itemPos.setX(itemPos.x() + xIntervalue); itemPos.setY(itemPos.y() + yIntervalue); item->setPos(itemPos); m_xValues[count] = itemPos.x(); m_yValues[count++] = itemPos.y(); } return UICanvasOperBase::disposeMoveEvent(event); } bool UICanvasMoveSelectedItem::disposeReleaseEvent(QMouseEvent* event) { g_currentCanvasManager->changedAttributeValues(m_xAttributes + m_yAttributes, \ m_xOldValues + m_yOldValues); g_currentCanvasManager->changedAttributeValues(m_xAttributes + m_yAttributes, \ m_xValues + m_yValues, true); return UICanvasOperBase::disposeReleaseEvent(event); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasOperators.h ================================================ #ifndef UICANVASOPERATORS_H #define UICANVASOPERATORS_H #include #include class UICanvasView; class QMouseEvent; class UICanvasPathItem; class NDAttributeBase; class UICanvasOperBase { public: UICanvasOperBase(UICanvasView* view); virtual ~UICanvasOperBase(); virtual bool disposePressEvent(QMouseEvent* event); virtual bool disposeMoveEvent(QMouseEvent* event); virtual bool disposeReleaseEvent(QMouseEvent* event); virtual bool disposeKeyPressEvent(QKeyEvent* event); protected: UICanvasView* m_pCanvasView = nullptr; }; // --------------------------------------------------------------------- // 默认操作器,操作器调度器 class UICanvasDefaultOper : public UICanvasOperBase { public: UICanvasDefaultOper(UICanvasView* view); ~UICanvasDefaultOper(); bool disposePressEvent(QMouseEvent* event) override; bool disposeMoveEvent(QMouseEvent* event) override; bool disposeReleaseEvent(QMouseEvent* event) override; bool disposeKeyPressEvent(QKeyEvent* event) override; }; // --------------------------------------------------------------------- // 画笔操作器(自由绘制) class UICanvasPenOper : public UICanvasOperBase { public: UICanvasPenOper(UICanvasView* view); ~UICanvasPenOper(); bool disposePressEvent(QMouseEvent* event) override; bool disposeMoveEvent(QMouseEvent* event) override; bool disposeReleaseEvent(QMouseEvent* event) override; private: UICanvasPathItem* m_pPathItem = nullptr; }; // --------------------------------------------------------------------- // 矩形选择操作器 class UICanvasRectSelectOper : public UICanvasOperBase { public: UICanvasRectSelectOper(UICanvasView* view); ~UICanvasRectSelectOper(); bool disposePressEvent(QMouseEvent* event) override; bool disposeMoveEvent(QMouseEvent* event) override; bool disposeReleaseEvent(QMouseEvent* event) override; private: QPoint m_pressedViewPos; QPointF m_pressedScenePos; }; // --------------------------------------------------------------------- // 多选移动操作器 class UICanvasMoveSelectedItem : public UICanvasOperBase { public: UICanvasMoveSelectedItem(UICanvasView* view); ~UICanvasMoveSelectedItem(); bool disposePressEvent(QMouseEvent* event) override; bool disposeMoveEvent(QMouseEvent* event) override; bool disposeReleaseEvent(QMouseEvent* event) override; private: QPointF m_scenePos; QList m_items; QList m_xAttributes; QList m_yAttributes; QVector m_xValues; QVector m_yValues; QVector m_xOldValues; QVector m_yOldValues; }; // --------------------------------------------------------------------- // 删除操作器 class UICanvasDeleteOperator : public UICanvasOperBase { public: }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasPathItem.cpp ================================================ #include "UICanvasPathItem.h" #include "NDIntAttribute.h" #include "NDColorAttribute.h" #include "NDNodeBase.h" #include UICanvasPathItem::UICanvasPathItem(QGraphicsItem* parentItem) :UICanvasItemBase(parentItem) { this->setItemResizeable(false); initAttribute(); } UICanvasPathItem::~UICanvasPathItem() { } void UICanvasPathItem::addPoint(const QPointF& scenePos) { QPointF localPos = this->mapFromScene(scenePos); m_painterPath.lineTo(localPos); m_points.append(localPos); this->update(); } void UICanvasPathItem::customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->save(); QPen pen; pen.setWidth(m_pOutLineWidthAttribute->getValue().toInt()); pen.setColor(m_pOutLineColorAttribute->getValue().value()); painter->setPen(pen); painter->drawPath(m_painterPath); painter->restore(); } void UICanvasPathItem::initAttribute(void) { QString groupName = tr("Item Attribute"); m_pNode->addAttributeGroup(groupName); // 轮廓线宽度 m_pOutLineWidthAttribute = new NDIntAttribute; m_pOutLineWidthAttribute->setValue(1); m_pOutLineWidthAttribute->setValueRange(1, 20); m_pOutLineWidthAttribute->setDisplayName(tr("OutLine Width: ")); m_pOutLineWidthAttribute->setName("outlineWidth"); m_pNode->addAttribute(groupName, m_pOutLineWidthAttribute); // 轮廓线颜色 m_pOutLineColorAttribute = new NDColorAttribute; m_pOutLineColorAttribute->setValue(QColor(10, 10, 10)); m_pOutLineColorAttribute->setDisplayName(tr("OutLine Color: ")); m_pOutLineColorAttribute->setName("outlineColor"); m_pNode->addAttribute(groupName, m_pOutLineColorAttribute); QObject::connect(m_pOutLineWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasPathItem::onValueChanged); QObject::connect(m_pOutLineColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasPathItem::onValueChanged); } void UICanvasPathItem::setStartPos(const QPointF& startScenePos) { QPointF localPos = this->mapFromScene(startScenePos); m_points.append(localPos); // 设置起始点 m_hasPoints = true; m_painterStartPos = localPos; m_painterPath.moveTo(localPos); // 设置矩形 QRectF boundRect = m_painterPath.boundingRect(); m_size = QSize(boundRect.width(), boundRect.height()); this->update(); } void UICanvasPathItem::endDrawPos(void) { // 设置矩形 QRectF boundRect = m_painterPath.boundingRect(); m_size = QSize(boundRect.width(), boundRect.height()); QPointF centerPos = boundRect.center(); this->setPos(centerPos); m_painterPath.translate(-centerPos.x(), -centerPos.y()); m_hadAddPointFinished = true; this->prepareGeometryChange(); this->update(); } // 获取当前属性Json QJsonObject UICanvasPathItem::getStoreJson(int interval) { QJsonObject jsonObject = UICanvasItemBase::getStoreJson(interval); QStringList pointStringList; for (auto iter = m_points.begin(); iter != m_points.end(); ++iter) { QString pointString("(%1,%2)"); pointString = pointString.arg(iter->x()).arg(iter->y()); pointStringList << pointString; } jsonObject.insert("PointData", pointStringList.join(";")); return jsonObject; } void UICanvasPathItem::fillJsonInfo(const QJsonObject& jsonObject) { QString pointString = jsonObject.value("PointData").toString(); QStringList pointValues = pointString.split(";"); int count = 0; for (auto iter = pointValues.begin(); iter != pointValues.end(); ++iter) { QString pointValue = iter->right(iter->length() - 1); pointValue = pointValue.left(pointValue.length() - 1); QStringList values = pointValue.split(","); QPointF pos(values[0].toDouble(), values[1].toDouble()); if (count == 0) { setStartPos(pos); count++; continue; } else { addPoint(pos); } } endDrawPos(); UICanvasItemBase::fillJsonInfo(jsonObject); } void UICanvasPathItem::onValueChanged(void) { this->update(); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasPathItem.h ================================================ #ifndef UICANVASPATHITEM_H #define UICANVASPATHITEM_H #include "UICanvasItemBase.h" #include #include class NDIntAttribute; class NDColorAttribute; class UICanvasPathItem : public UICanvasItemBase { Q_OBJECT public: UICanvasPathItem(QGraphicsItem* parentItem = nullptr); ~UICanvasPathItem(); // 添加点 void addPoint(const QPointF& scenePos); // 设置起始点 void setStartPos(const QPointF& startScenePos); // 结束设置 void endDrawPos(void); // 获取当前属性Json virtual QJsonObject getStoreJson(int interval = 0) override; virtual void fillJsonInfo(const QJsonObject& jsonObject) override; protected: void customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; //QPainterPath shape() const override; private: bool m_hasPoints = false; bool m_hadAddPointFinished = false; QPointF m_painterStartPos; QPainterPath m_painterPath; QVector m_points; // 初始化 void initAttribute(void); NDIntAttribute* m_pOutLineWidthAttribute = nullptr; // 轮廓线宽度 NDColorAttribute* m_pOutLineColorAttribute = nullptr; // 轮廓线颜色 private slots: void onValueChanged(void); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasRectItem.cpp ================================================ #include "UICanvasRectItem.h" #include "NDNodeBase.h" #include "NDBoolAttribute.h" #include "NDIntAttribute.h" #include "NDColorAttribute.h" #include UICanvasRectItem::UICanvasRectItem(QGraphicsItem* parentItem) :UICanvasItemBase (parentItem) { initAttribute(); } UICanvasRectItem::~UICanvasRectItem() { } void UICanvasRectItem::setSize(int width, int height) { m_size.setWidth(width); m_size.setHeight(height); this->prepareGeometryChange(); } void UICanvasRectItem::customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->save(); // 设置画笔 if (m_pBOutLineAttribute->getValue().toBool()) { QPen pen; pen.setWidth(m_pOutLineWidthAttribute->getValue().toInt()); pen.setColor(m_pOutLineColorAttribute->getValue().value()); painter->setPen(pen); } else { painter->setPen(Qt::NoPen); } // 设置画刷 if (m_pBFillAttribute->getValue().toBool()) { painter->setBrush(QBrush(m_pFillColorAttribute->getValue().value())); } else { painter->setBrush(Qt::NoBrush); } QRectF rect = this->getCustomRect(); painter->drawRect(rect); painter->restore(); } void UICanvasRectItem::initAttribute() { QString groupName = tr("Item Attribute"); m_pNode->addAttributeGroup(groupName); // 是否为圆形 m_pBRoundAttribute = new NDBoolAttribute; m_pBRoundAttribute->setValue(true); m_pBRoundAttribute->setDisplayName(tr("Is Rounded: ")); m_pBRoundAttribute->setName("bRounded"); m_pNode->addAttribute(groupName, m_pBRoundAttribute); // 添加是否填充属性 m_pBFillAttribute = new NDBoolAttribute; m_pBFillAttribute->setValue(false); m_pBFillAttribute->setDisplayName(tr("Is Fill Color: ")); m_pBFillAttribute->setName("bFillColor"); m_pNode->addAttribute(groupName, m_pBFillAttribute); // 添加填充颜色 m_pFillColorAttribute = new NDColorAttribute; m_pFillColorAttribute->setEnable(false); m_pFillColorAttribute->setValue(QColor(150, 150, 150)); m_pFillColorAttribute->setDisplayName(tr("Fill Color: ")); m_pFillColorAttribute->setName("fillColor"); m_pNode->addAttribute(groupName, m_pFillColorAttribute); // 添加是否显示轮廓线 m_pBOutLineAttribute = new NDBoolAttribute; m_pBOutLineAttribute->setValue(true); m_pBOutLineAttribute->setDisplayName(tr("Show OutLine: ")); m_pBOutLineAttribute->setName("bOutline"); m_pNode->addAttribute(groupName, m_pBOutLineAttribute); // 轮廓线宽度 m_pOutLineWidthAttribute = new NDIntAttribute; m_pOutLineWidthAttribute->setValue(1); m_pOutLineWidthAttribute->setValueRange(1, 20); m_pOutLineWidthAttribute->setDisplayName(tr("OutLine Width: ")); m_pOutLineWidthAttribute->setName("outlineWidth"); m_pNode->addAttribute(groupName, m_pOutLineWidthAttribute); // 轮廓线颜色 m_pOutLineColorAttribute = new NDColorAttribute; m_pOutLineColorAttribute->setValue(QColor(10, 10, 10)); m_pOutLineColorAttribute->setDisplayName(tr("OutLine Color: ")); m_pOutLineColorAttribute->setName("outlineColor"); m_pNode->addAttribute(groupName, m_pOutLineColorAttribute); // 连接信号和槽 QObject::connect(m_pBRoundAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasRectItem::onRoundValueChanged); QObject::connect(m_pBFillAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasRectItem::onValueChanged); QObject::connect(m_pFillColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasRectItem::onValueChanged); QObject::connect(m_pBOutLineAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasRectItem::onValueChanged); QObject::connect(m_pOutLineWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasRectItem::onValueChanged); QObject::connect(m_pOutLineColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasRectItem::onValueChanged); } void UICanvasRectItem::onValueChanged(void) { this->update(); } void UICanvasRectItem::onRoundValueChanged(const QVariant& value) { this->setItemResizeable(true); this->setItemResizeRatio(value.toBool(), 1.0); if (value.toBool()) { int width = m_size.width(); m_size.setHeight(width); this->prepareGeometryChange(); } } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasRectItem.h ================================================ #ifndef UICANVASRECTITEM_H #define UICANVASRECTITEM_H #include "UICanvasItemBase.h" class NDBoolAttribute; class NDColorAttribute; class UICanvasRectItem : public UICanvasItemBase { Q_OBJECT public: UICanvasRectItem(QGraphicsItem* parentItem = nullptr); ~UICanvasRectItem(); // 设置尺寸 void setSize(int width, int height); protected: void customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); private: // 属性相关 void initAttribute(); NDBoolAttribute* m_pBRoundAttribute = nullptr; // 是否为圆形 NDBoolAttribute* m_pBFillAttribute = nullptr; // 是否为填充颜色 NDColorAttribute* m_pFillColorAttribute = nullptr; // 填充的颜色 NDBoolAttribute* m_pBOutLineAttribute = nullptr; // 是否显示轮廓线 NDIntAttribute* m_pOutLineWidthAttribute = nullptr; // 轮廓线宽度 NDColorAttribute* m_pOutLineColorAttribute = nullptr; // 轮廓线颜色 private slots: void onValueChanged(void); void onRoundValueChanged(const QVariant& value); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasScene.cpp ================================================ #include "UICanvasScene.h" #include "NDNodeBase.h" #include "NDIntAttribute.h" #include "NDColorAttribute.h" #include "UICanvasItemManager.h" #include UICanvasScene::UICanvasScene(QObject* parent) :QGraphicsScene(parent) { initNodeInfo(); int width = m_pWidthAttribute->getValue().toInt(); int height = m_pHeightAttribute->getValue().toInt(); this->setSceneRect(QRectF(0, 0, width, height)); } UICanvasScene::~UICanvasScene() { } void UICanvasScene::drawBackground(QPainter *painter, const QRectF &rect) { painter->fillRect(rect, QColor(60, 60, 60)); QRectF sceneRect = this->sceneRect(); painter->fillRect(sceneRect, QBrush(m_pBackgroundColorAttribute->getValue().value())); return QGraphicsScene::drawBackground(painter, rect); } void UICanvasScene::drawForeground(QPainter *painter, const QRectF &rect) { return QGraphicsScene::drawForeground(painter, rect); } void UICanvasScene::initNodeInfo(void) { m_pNode = new NDNodeBase(this); QString groupString = tr("Canvas Attribute"); m_pNode->addAttributeGroup(groupString); m_pNode->setNodeName("canvas"); m_pNode->setNodeType((int)UICanvasItemManager::t_CanvasItem); // 宽度 m_pWidthAttribute = new NDIntAttribute; m_pWidthAttribute->setDisplayName(tr("width: ")); m_pWidthAttribute->setName("width"); m_pWidthAttribute->setValueRange(10, 5000); m_pWidthAttribute->setValue(800); m_pNode->addAttribute(groupString, m_pWidthAttribute); // 高度 m_pHeightAttribute = new NDIntAttribute; m_pHeightAttribute->setDisplayName(tr("height: ")); m_pHeightAttribute->setName("height"); m_pHeightAttribute->setValueRange(10, 5000); m_pHeightAttribute->setValue(500); m_pNode->addAttribute(groupString, m_pHeightAttribute); // 颜色 m_pBackgroundColorAttribute = new NDColorAttribute; m_pBackgroundColorAttribute->setValue(QColor(255, 255, 255)); m_pBackgroundColorAttribute->setDisplayName(tr("Canvas Color: ")); m_pBackgroundColorAttribute->setName("canvasColor"); m_pNode->addAttribute(groupString, m_pBackgroundColorAttribute); QObject::connect(m_pWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasScene::onWidthAttributeValueChanged); QObject::connect(m_pHeightAttribute, &NDIntAttribute::valueChanged, this, &UICanvasScene::onHeightAttributeValueChanged); QObject::connect(m_pBackgroundColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasScene::onColorAttributeValueChanged); } NDNodeBase* UICanvasScene::getCurrentNode(void) { return m_pNode; } void UICanvasScene::resetNodeInfo(void) { m_pWidthAttribute->setValue(800); m_pHeightAttribute->setValue(500); m_pBackgroundColorAttribute->setValue(QColor(255, 255, 255)); } void UICanvasScene::onWidthAttributeValueChanged(const QVariant& value) { QRectF rect = this->sceneRect(); rect.setWidth(value.toInt()); this->setSceneRect(rect); } void UICanvasScene::onHeightAttributeValueChanged(const QVariant& value) { QRectF rect = this->sceneRect(); rect.setHeight(value.toInt()); this->setSceneRect(rect); } void UICanvasScene::onColorAttributeValueChanged(const QVariant& color) { this->update(); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasScene.h ================================================ #ifndef UICANVASSCENE_H #define UICANVASSCENE_H #include class NDNodeBase; class NDIntAttribute; class NDColorAttribute; class UICanvasScene : public QGraphicsScene { Q_OBJECT public: UICanvasScene(QObject* parent = nullptr); ~UICanvasScene(); // 获取节点 NDNodeBase* getCurrentNode(void); // 初始化节点属性 void resetNodeInfo(void); protected: virtual void drawBackground(QPainter *painter, const QRectF &rect) override; virtual void drawForeground(QPainter *painter, const QRectF &rect) override; private: // 初始化属性 void initNodeInfo(void); // 属性 NDNodeBase* m_pNode = nullptr; // 宽度和高度属性 NDIntAttribute* m_pWidthAttribute = nullptr; NDIntAttribute* m_pHeightAttribute = nullptr; // 颜色属性 NDColorAttribute* m_pBackgroundColorAttribute = nullptr; private slots: void onWidthAttributeValueChanged(const QVariant& value); void onHeightAttributeValueChanged(const QVariant& value); void onColorAttributeValueChanged(const QVariant& value); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasTextItem.cpp ================================================ #include "UICanvasTextItem.h" #include "NDNodeBase.h" #include "NDBoolAttribute.h" #include "NDIntAttribute.h" #include "NDColorAttribute.h" #include "NDStringAttribute.h" #include #include UICanvasTextItem::UICanvasTextItem(QGraphicsItem* parentItem) :UICanvasItemBase(parentItem) { m_font = qApp->font(); m_font.setPixelSize(25); this->setItemResizeable(false); initAttribute(); setCurrentText("EasyCanvas"); } UICanvasTextItem::~UICanvasTextItem() { } void UICanvasTextItem::setCurrentText(const QString& text) { m_cText = text; QObject::disconnect(m_pTextValueAttribute, &NDStringAttribute::valueChanged, this, &UICanvasTextItem::onTextValueChanged); m_pTextValueAttribute->setValue(m_cText); QObject::connect(m_pTextValueAttribute, &NDStringAttribute::valueChanged, this, &UICanvasTextItem::onTextValueChanged); QFontMetrics fm(m_font); QRect rect = fm.boundingRect(m_cText); m_size = QSize(rect.width(), rect.height()); this->prepareGeometryChange(); this->update(); } void UICanvasTextItem::setCurrentFont(const QFont& font) { m_font = font; QFontMetrics fm(m_font); QRect rect = fm.boundingRect(m_cText); m_size = QSize(rect.width(), rect.height()); this->prepareGeometryChange(); this->update(); } void UICanvasTextItem::customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->save(); QRectF textRect = this->getCustomRect(); QPainterPath path; path.addText(textRect.bottomLeft(), m_font, m_cText); // 添加轮廓 QPen pen; pen.setWidth(m_pOutLineWidthAttribute->getValue().toInt()); pen.setColor(m_pOutLineColorAttribute->getValue().value()); if (m_pBOutLineAttribute->getValue().toBool()) painter->strokePath(path, pen); // 绘制 pen.setWidth(m_pPenSizeAttribute->getValue().toInt()); pen.setColor(m_pTtextColorAttribute->getValue().value()); painter->setPen(pen); if (!m_pBFillColorAttribute->getValue().toBool()) painter->setBrush(Qt::NoBrush); else painter->setBrush(m_pFillColorAttribute->getValue().value()); painter->drawPath(path); painter->restore(); } void UICanvasTextItem::initAttribute(void) { QString groupName = tr("Text Attribute"); m_pNode->addAttributeGroup(groupName); // 本文内容 m_pTextValueAttribute = new NDStringAttribute; m_pTextValueAttribute->setValue(m_cText); m_pTextValueAttribute->setDisplayName(tr("Text: ")); m_pTextValueAttribute->setName("text"); m_pTextValueAttribute->setShowButton(false); m_pNode->addAttribute(groupName, m_pTextValueAttribute); // 字体大小 m_pFontSizeAttribute = new NDIntAttribute; m_pFontSizeAttribute->setValue(m_font.pixelSize()); m_pFontSizeAttribute->setValueRange(1, 200); m_pFontSizeAttribute->setDisplayName(tr("Font Size: ")); m_pFontSizeAttribute->setName("fontSize"); m_pNode->addAttribute(groupName, m_pFontSizeAttribute); // 画笔大小 m_pPenSizeAttribute = new NDIntAttribute; m_pPenSizeAttribute->setValue(1); m_pPenSizeAttribute->setValueRange(1, 10); m_pPenSizeAttribute->setDisplayName(tr("Pen Size: ")); m_pPenSizeAttribute->setName("penSize"); m_pNode->addAttribute(groupName, m_pPenSizeAttribute); // 文字颜色 m_pTtextColorAttribute = new NDColorAttribute; m_pTtextColorAttribute->setValue(QColor(10, 10, 10)); m_pTtextColorAttribute->setDisplayName(tr("Text Color: ")); m_pTtextColorAttribute->setName("textColor"); m_pNode->addAttribute(groupName, m_pTtextColorAttribute); // 是否填充颜色 m_pBFillColorAttribute = new NDBoolAttribute; m_pBFillColorAttribute->setValue(true); m_pBFillColorAttribute->setDisplayName(tr("Is Fill Color: ")); m_pBFillColorAttribute->setName("bFillColorOutline"); m_pNode->addAttribute(groupName, m_pBFillColorAttribute); // 文字填充颜色 m_pFillColorAttribute = new NDColorAttribute; m_pFillColorAttribute->setValue(QColor(10, 10, 10)); m_pFillColorAttribute->setDisplayName(tr("Fill Color: ")); m_pFillColorAttribute->setName("fillColor"); m_pNode->addAttribute(groupName, m_pFillColorAttribute); QString outLineGroupName = tr("OutLine Attribute"); m_pNode->addAttributeGroup(outLineGroupName); // 是否显示轮廓线 m_pBOutLineAttribute = new NDBoolAttribute; m_pBOutLineAttribute->setValue(false); m_pBOutLineAttribute->setDisplayName(tr("Is Show Outline: ")); m_pBOutLineAttribute->setName("bShowOutline"); m_pNode->addAttribute(outLineGroupName, m_pBOutLineAttribute); // 添加填充颜色 m_pOutLineColorAttribute = new NDColorAttribute; m_pOutLineColorAttribute->setEnable(false); m_pOutLineColorAttribute->setValue(QColor(200, 200, 200)); m_pOutLineColorAttribute->setDisplayName(tr("Outline Color: ")); m_pOutLineColorAttribute->setName("outlineColor"); m_pNode->addAttribute(outLineGroupName, m_pOutLineColorAttribute); // 轮廓线宽度 m_pOutLineWidthAttribute = new NDIntAttribute; m_pOutLineWidthAttribute->setValue(1); m_pOutLineWidthAttribute->setValueRange(1, 20); m_pOutLineWidthAttribute->setDisplayName(tr("OutLine Width: ")); m_pOutLineWidthAttribute->setName("outlineWidth"); m_pNode->addAttribute(outLineGroupName, m_pOutLineWidthAttribute); // 连接信号和槽 QObject::connect(m_pBOutLineAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasTextItem::onValueChanged); QObject::connect(m_pOutLineWidthAttribute, &NDIntAttribute::valueChanged, this, &UICanvasTextItem::onValueChanged); QObject::connect(m_pOutLineColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasTextItem::onValueChanged); QObject::connect(m_pFontSizeAttribute, &NDIntAttribute::valueChanged, this, &UICanvasTextItem::onFontSizeValueChanged); QObject::connect(m_pPenSizeAttribute, &NDIntAttribute::valueChanged, this, &UICanvasTextItem::onValueChanged); QObject::connect(m_pTtextColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasTextItem::onValueChanged); QObject::connect(m_pTextValueAttribute, &NDStringAttribute::valueChanged, this, &UICanvasTextItem::onTextValueChanged); QObject::connect(m_pBFillColorAttribute, &NDBoolAttribute::valueChanged, this, &UICanvasTextItem::onValueChanged); QObject::connect(m_pFillColorAttribute, &NDColorAttribute::valueChanged, this, &UICanvasTextItem::onValueChanged); } void UICanvasTextItem::onValueChanged(void) { this->update(); } void UICanvasTextItem::onTextValueChanged(const QVariant& text) { setCurrentText(text.toString()); this->update(); } void UICanvasTextItem::onFontSizeValueChanged(const QVariant& fontSize) { m_font.setPixelSize(fontSize.toInt()); setCurrentFont(m_font); this->update(); } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasTextItem.h ================================================ #ifndef UICANVASTEXTITEM_H #define UICANVASTEXTITEM_H #include #include #include "UICanvasItemBase.h" #include "NDNodeManager.h" #include "NDNodeBase.h" class NDBoolAttribute; class NDIntAttribute; class NDColorAttribute; class NDStringAttribute; class UICanvasTextItem : public UICanvasItemBase { Q_OBJECT public: UICanvasTextItem(QGraphicsItem* parentItem = nullptr); ~UICanvasTextItem(); // 设置文本 void setCurrentText(const QString& text); // 设置字体 void setCurrentFont(const QFont& font); protected: // 自定义元素绘制 void customPaint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override; private: QString m_cText; QFont m_font; void initAttribute(void); NDBoolAttribute* m_pBOutLineAttribute = nullptr; // 是否显示轮廓线 NDIntAttribute* m_pOutLineWidthAttribute = nullptr; // 轮廓线宽度 NDColorAttribute* m_pOutLineColorAttribute = nullptr; // 轮廓线颜色 NDIntAttribute* m_pFontSizeAttribute = nullptr; // 字体大小 NDIntAttribute* m_pPenSizeAttribute = nullptr; // 画笔大小 NDColorAttribute* m_pTtextColorAttribute = nullptr; // 文字颜色 NDBoolAttribute* m_pBFillColorAttribute = nullptr; // 是否填充颜色 NDColorAttribute* m_pFillColorAttribute = nullptr; // 填充颜色 NDStringAttribute* m_pTextValueAttribute = nullptr; // 文本内容 private slots: void onValueChanged(void); void onTextValueChanged(const QVariant& text); void onFontSizeValueChanged(const QVariant& fontSize); }; #endif ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasView.cpp ================================================ #include "UICanvasView.h" #include "UICanvasImageItem.h" #include #include #include "UICanvasPathItem.h" #include "UICanvasOperators.h" #include "UICanvasTextItem.h" #include "UICanvasRectItem.h" #include "UICanvasEllipseItem.h" #include "UICanvasAudioItem.h" #include "UICanvasScene.h" #include "UICanvasItemManager.h" #include UICanvasView::UICanvasView(QWidget* parent) :QGraphicsView(parent) , m_pCurrentOper(nullptr) , m_cSelectedPenColor(200, 100, 100) , m_cSelectedBrushColor(0, 0, 200, 100) { // 初始化CanvasManager UICanvasItemManager::createCanvasManager(); UICanvasItemManager::setCurrentIndex(0); g_currentCanvasManager->setCurrentCanvasView(this); this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); m_pScene = new UICanvasScene; QObject::connect(m_pScene, &UICanvasScene::selectionChanged, \ this, &UICanvasView::itemSelectedChanged); this->setScene(m_pScene); //this->setSceneRect(0, 0, 5000, 5000); // 设置默认操作器 this->setCurrentOperator(new UICanvasDefaultOper(this)); m_penPixmap = QPixmap(); QString curAppPath = qApp->applicationDirPath() + "/"; m_penPixmap.load(curAppPath + "./images/freeDrawItem.png"); } UICanvasView::~UICanvasView() { } void UICanvasView::createImageItem(void) { g_currentCanvasManager->createCanvasItemByCmd(UICanvasItemManager::t_ImageItem); } void UICanvasView::createTextItem(void) { g_currentCanvasManager->createCanvasItemByCmd(UICanvasItemManager::t_TextItem); } void UICanvasView::createRectItem(void) { g_currentCanvasManager->createCanvasItemByCmd(UICanvasItemManager::t_RectItem); } void UICanvasView::createEllipseItem(void) { g_currentCanvasManager->createCanvasItemByCmd(UICanvasItemManager::t_EllipseItem); } void UICanvasView::createAudioItem(void) { g_currentCanvasManager->createCanvasItemByCmd(UICanvasItemManager::t_AudioItem); } // 设置选中矩形 void UICanvasView::setSelectedRectVisible(bool isVisible) { m_isSelectedRectVisible = isVisible; this->viewport()->update(); } // 设置选中矩形范围 void UICanvasView::setSelectedRect(const QRect& rect) { QPointF startPos = this->mapToScene(rect.topLeft()); QPointF endPos = this->mapToScene(rect.bottomRight()); m_selectedRect = QRect(QPoint(startPos.x(), startPos.y()), \ QPoint(endPos.x(), endPos.y())); this->viewport()->update(); } void UICanvasView::setCurrentOperator(UICanvasOperBase* canvasOper) { m_pCurrentOper.reset(canvasOper); } void UICanvasView::mousePressEvent(QMouseEvent* event) { bool result = m_pCurrentOper->disposePressEvent(event); if (result) QGraphicsView::mousePressEvent(event); } void UICanvasView::mouseMoveEvent(QMouseEvent* event) { m_pCurrentOper->disposeMoveEvent(event); return QGraphicsView::mouseMoveEvent(event); } void UICanvasView::mouseReleaseEvent(QMouseEvent* event) { m_pCurrentOper->disposeReleaseEvent(event); return QGraphicsView::mouseReleaseEvent(event); } void UICanvasView::keyPressEvent(QKeyEvent* event) { m_pCurrentOper->disposeKeyPressEvent(event); } void UICanvasView::drawBackground(QPainter* painter, const QRectF& rect) { return QGraphicsView::drawBackground(painter, rect); } void UICanvasView::drawForeground(QPainter* painter, const QRectF& rect) { if (!m_isSelectedRectVisible) return QGraphicsView::drawForeground(painter, rect); QPen pen; pen.setWidth(1); pen.setColor(m_cSelectedPenColor); pen.setStyle(Qt::DashLine); painter->setPen(pen); painter->setBrush(m_cSelectedBrushColor); painter->drawRect(m_selectedRect); return QGraphicsView::drawForeground(painter, rect); } // 设置/获取当前模式 void UICanvasView::setCurrentMode(CanvasMode mode) { m_mode = mode; if (m_mode == t_FreeDrawMode && !m_penPixmap.isNull()) { this->viewport()->setCursor(QCursor(m_penPixmap, 0, m_penPixmap.height())); } else { this->viewport()->setCursor(Qt::ArrowCursor); } } UICanvasView::CanvasMode UICanvasView::getCurrentMode(void) { return m_mode; } NDNodeBase* UICanvasView::getCurrentSelectedNode(void) { QList items = m_pScene->selectedItems(); if (items.size() == 1) { UICanvasItemBase* canvasItem = qgraphicsitem_cast(items[0]); if (canvasItem == nullptr) return nullptr; return canvasItem->getCurrentNode(); } return m_pScene->getCurrentNode(); } QList UICanvasView::getCurrentSelectedNodes(void) { QList nodes; QList items = m_pScene->selectedItems(); for (auto iter = items.begin(); iter != items.end(); ++iter) { UICanvasItemBase* canvasItem = qgraphicsitem_cast(*iter); if (canvasItem) nodes << canvasItem->getCurrentNode(); } return nodes; } QList UICanvasView::getCurrentSelectedItems(void) { QList selectedItems; QList items = m_pScene->selectedItems(); for (auto iter = items.begin(); iter != items.end(); ++iter) { UICanvasItemBase* canvasItem = qgraphicsitem_cast(*iter); if (canvasItem) selectedItems << canvasItem; } return selectedItems; } NDNodeBase* UICanvasView::getCurrentSceneNode(void) { return m_pScene->getCurrentNode(); } void UICanvasView::resetSceneNode(void) { m_pScene->resetNodeInfo(); } QPointF UICanvasView::getCenterPos(void) { QRectF rect = m_pScene->sceneRect(); return rect.center(); } void UICanvasView::saveToImage(const QString& imagePath) { int width = m_pScene->width(); int height = m_pScene->height(); QImage image(QSize(width, height), QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::TextAntialiasing, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); cleanAllSelected(); m_pScene->render(&painter); image.save(imagePath); } // 添加到场景中 void UICanvasView::addToScene(UICanvasItemBase* item) { m_pScene->addItem(item); } // 从场景中删除 void UICanvasView::removeFromScene(UICanvasItemBase* item) { m_pScene->removeItem(item); } void UICanvasView::saveToImage(QImage& saveImage) { int width = m_pScene->width(); int height = m_pScene->height(); QImage image(QSize(width, height), QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::TextAntialiasing, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); cleanAllSelected(); m_pScene->render(&painter); saveImage = image; } void UICanvasView::cleanAllSelected(void) { auto items = m_pScene->selectedItems(); foreach(auto item, items) { item->setSelected(false); } } ================================================ FILE: EasyCanvasCore/UICanvas/UICanvasView.h ================================================ #ifndef UICANVASVIEW_H #define UICANVASVIEW_H #include #include #include #include "easycanvascore_global.h" class UICanvasOperBase; class UICanvasPathItem; class NDNodeBase; class UICanvasScene; class UICanvasItemBase; class EASYCANVASCORESHARED_EXPORT UICanvasView : public QGraphicsView { Q_OBJECT public: enum CanvasMode { t_ArrowMode, // 选择编辑模式 t_FreeDrawMode, // 自由绘制模式 t_ImageMode, // 图片模式 }; public: UICanvasView(QWidget* parent = nullptr); ~UICanvasView(); // 设置操作器 void setCurrentOperator(UICanvasOperBase* canvasOper); // Create Items void createImageItem(void); void createTextItem(void); void createRectItem(void); void createEllipseItem(void); void createAudioItem(void); // 设置选中矩形 void setSelectedRectVisible(bool isVisible); // 设置选中矩形范围 void setSelectedRect(const QRect& rect); // 设置/获取当前模式 void setCurrentMode(CanvasMode mode); CanvasMode getCurrentMode(void); // 获取当前选中的Item的节点 NDNodeBase* getCurrentSelectedNode(void); QList getCurrentSelectedNodes(void); QList getCurrentSelectedItems(void); // 获取当前场景根节点 NDNodeBase* getCurrentSceneNode(void); // 重置场景根节点 void resetSceneNode(void); // 获取中心点坐标 QPointF getCenterPos(void); // 添加到场景中 void addToScene(UICanvasItemBase* item); // 从场景中删除 void removeFromScene(UICanvasItemBase* item); // 保存 void saveToImage(const QString& imagePath); void saveToImage(QImage& saveImage); // 清除所有选择 void cleanAllSelected(void); protected: void mousePressEvent(QMouseEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; void keyPressEvent(QKeyEvent* event) override; void drawBackground(QPainter * painter, const QRectF & rect) override; void drawForeground(QPainter * painter, const QRectF & rect) override; private: UICanvasScene* m_pScene = nullptr; UICanvasPathItem* m_pathItem = nullptr; QSharedPointer m_pCurrentOper; // 选中矩形相关 bool m_isSelectedRectVisible = false; QRect m_selectedRect; QColor m_cSelectedPenColor; QColor m_cSelectedBrushColor; CanvasMode m_mode = t_ArrowMode; QPixmap m_penPixmap; signals: void itemSelectedChanged(void); }; #endif ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeItem.cpp ================================================ #include "UINodeItem.h" UINodeItem::UINodeItem(UINodeItem* parentItem) :QObject(parentItem) { m_pParentItem = parentItem; } UINodeItem::~UINodeItem() { } // 添加子节点 void UINodeItem::appendChildNode(UINodeItem* nodeItem) { nodeItem->setParentNode(this); m_childItems.append(nodeItem); } void UINodeItem::removeChildNode(const QString& nodeName) { UINodeItem* pNodeItem = nullptr; for (auto iter = m_childItems.begin(); iter != m_childItems.end(); ++iter) { if ((*iter)->getName() == nodeName) { pNodeItem = *iter; pNodeItem->setParentNode(nullptr); m_childItems.erase(iter); break; } } // if (pNodeItem) // pNodeItem->deleteLater(); } UINodeItem* UINodeItem::getChildNode(int index) { if (m_childItems.count() <= index) return nullptr; return m_childItems[index]; } UINodeItem* UINodeItem::getChildNode(const QString& nodeName) { for (auto iter = m_childItems.begin(); iter != m_childItems.end(); ++iter) { if ((*iter)->getName() == nodeName) return *iter; } return nullptr; } // 设置/获取父节点 void UINodeItem::setParentNode(UINodeItem* node) { m_pParentItem = node; this->setParent(m_pParentItem); } UINodeItem* UINodeItem::getParentNode(void) { return m_pParentItem; } // 设置/获取节点名字 void UINodeItem::setName(const QString& name) { m_cDisplayName = name; } QString UINodeItem::getName(void) { return m_cDisplayName; } void UINodeItem::setCanvasNodeVisible(bool isNode) { m_isCanvasNode = isNode; } bool UINodeItem::isCanvasNode(void) { return m_isCanvasNode; } // 设置/获取节点类型 void UINodeItem::setNodeType(int type) { m_nNodeType = type; } int UINodeItem::getNodeType(void) { return m_nNodeType; } // 获取当前的索引 int UINodeItem::getCurrentIndex(void) { if (m_pParentItem == nullptr) return 0; int count = 0; for (auto iter = m_pParentItem->m_childItems.begin(); iter != m_pParentItem->m_childItems.end(); ++iter) { if (*iter == this) return count; count++; } return -1; } int UINodeItem::getCurrentIndex(UINodeItem* node) { int count = 0; for (auto iter = m_childItems.begin(); iter != m_childItems.end(); ++iter) { if (*iter == node) return count; count++; } return -1; } // 获取子元素的数量 int UINodeItem::getSubNodeCount(void) { return m_childItems.count(); } ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeItem.h ================================================ #ifndef UINODEITEM_H #define UINODEITEM_H #include #include #include class UINodeItem : public QObject { Q_OBJECT public: explicit UINodeItem(UINodeItem* parentItem = nullptr); ~UINodeItem(); // 添加子节点 void appendChildNode(UINodeItem* nodeItem); // 刪除子节点 void removeChildNode(const QString& nodeName); // 获取子节点 UINodeItem* getChildNode(int index); UINodeItem* getChildNode(const QString& nodeName); // 设置/获取父节点 void setParentNode(UINodeItem* node); UINodeItem* getParentNode(void); // 设置/获取节点名字 void setName(const QString& name); QString getName(void); // 设置/获取是否为画布的节点 void setCanvasNodeVisible(bool isNode); bool isCanvasNode(void); // 设置/获取节点类型 void setNodeType(int type); int getNodeType(void); // 获取当前的索引 int getCurrentIndex(void); int getCurrentIndex(UINodeItem* node); // 获取子元素的数量 int getSubNodeCount(void); private: QString m_cDisplayName; // 显示的名字 bool m_isCanvasNode = false; // 是否能更改名字 int m_nNodeType = 0; // 节点类型 QVector m_childItems; // 子节点列表 UINodeItem* m_pParentItem = nullptr; // 父节点 }; #endif ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeSortFilterProxyModel.cpp ================================================ #include "UINodeSortFilterProxyModel.h" #include "UINodeItem.h" UINodeSortFilterProxyModel::UINodeSortFilterProxyModel(QObject* parent) :QSortFilterProxyModel(parent) { this->setDynamicSortFilter(true); this->setRecursiveFilteringEnabled(true); } UINodeSortFilterProxyModel::~UINodeSortFilterProxyModel() { } bool UINodeSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex & source_parent) const { if (m_filterString.isEmpty()) return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); QModelIndex index = this->sourceModel()->index(source_row, 0, source_parent); if (!index.isValid()) return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); UINodeItem* pNodeItem = static_cast(index.internalPointer()); if (!pNodeItem || !pNodeItem->isCanvasNode()) return false; QString name = this->sourceModel()->data(index).toString(); if (name.indexOf(m_filterString, 0, Qt::CaseInsensitive) >= 0) return true; return false; } void UINodeSortFilterProxyModel::setFilterString(const QString& filterString) { m_filterString = filterString; this->setFilterFixedString(m_filterString); } ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeSortFilterProxyModel.h ================================================ #ifndef UINODESORTFILTERPROXYMODEL_H #define UINODESORTFILTERPROXYMODEL_H #include #include class UINodeSortFilterProxyModel : public QSortFilterProxyModel { Q_OBJECT public: explicit UINodeSortFilterProxyModel(QObject* parent = nullptr); ~UINodeSortFilterProxyModel(); void setFilterString(const QString& filterString); protected: bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const; private: QString m_filterString; }; #endif ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeDelegate.cpp ================================================ #include "UINodeTreeDelegate.h" #include "UINodeItem.h" #include "UINodeSortFilterProxyModel.h" #include UINodeTreeDelegate::UINodeTreeDelegate(QObject* parent) :QStyledItemDelegate(parent) { } UINodeTreeDelegate::~UINodeTreeDelegate() { } void UINodeTreeDelegate::setProxyModel(UINodeSortFilterProxyModel* model) { m_pModel = model; } QWidget *UINodeTreeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) return QStyledItemDelegate::createEditor(parent, option, index); QModelIndex srcIndex = m_pModel->mapToSource(index); UINodeItem* node = static_cast(srcIndex.internalPointer()); bool isCanChangedName = node->isCanvasNode(); if (!isCanChangedName) return QStyledItemDelegate::createEditor(parent, option, index); QLineEdit* pLineEdit = new QLineEdit(parent); pLineEdit->setText(node->getName()); return pLineEdit; } void UINodeTreeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit* pLineEdit = qobject_cast(editor); if (pLineEdit == nullptr) return; QModelIndex srcIndex = m_pModel->mapToSource(index); UINodeItem* node = static_cast(srcIndex.internalPointer()); pLineEdit->setText(node->getName()); } void UINodeTreeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { if (model == nullptr || !index.isValid()) return; QLineEdit* pLineEdit = qobject_cast(editor); if (pLineEdit == nullptr) return; QString name = pLineEdit->text(); if (name.isEmpty()) return; model->setData(index, name, Qt::EditRole); } QSize UINodeTreeDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) return QStyledItemDelegate::sizeHint(option, index); QSize size; size.setWidth(option.decorationSize.width()); size.setHeight(30); return size; } ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeDelegate.h ================================================ #ifndef UINODETREEDELEGATE_H #define UINODETREEDELEGATE_H #include class UINodeSortFilterProxyModel; class UINodeTreeDelegate : public QStyledItemDelegate { Q_OBJECT public: explicit UINodeTreeDelegate(QObject* parent = nullptr); ~UINodeTreeDelegate(); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; void setProxyModel(UINodeSortFilterProxyModel* model); private: UINodeSortFilterProxyModel* m_pModel = nullptr; }; #endif ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeView.cpp ================================================ #include "UINodeTreeView.h" #include "UINodeTreeViewModel.h" #include "UINodeTreeDelegate.h" #include "UICanvas/UICanvasItemManager.h" #include "UICanvas/UICanvasView.h" #include "NDNodeBase.h" #include #include #include "UINodeSortFilterProxyModel.h" UINodeTreeView::UINodeTreeView(QWidget* parent) :QTreeView(parent) { // 设置model m_pModel = new UINodeTreeViewModel(this); m_pModel->setCurrentTreeView(this); m_pSortFilterModel = new UINodeSortFilterProxyModel; m_pSortFilterModel->setSourceModel(m_pModel); this->setModel(m_pSortFilterModel); //this->setModel(m_pModel); // 设置Delegate m_pDelegate = new UINodeTreeDelegate(this); m_pDelegate->setProxyModel(m_pSortFilterModel); this->setItemDelegate(m_pDelegate); this->expandAll(); this->header()->setVisible(false); this->setSelectionMode(QTreeView::ExtendedSelection); // 初始化选择 UICanvasView* pCanvasView = g_currentCanvasManager->getCurrentCanvasView(); QObject::connect(pCanvasView, &UICanvasView::itemSelectedChanged, this, &UINodeTreeView::onItemSelectedChanged); QItemSelectionModel* pSelectonModel = this->selectionModel(); QObject::connect(pSelectonModel, &QItemSelectionModel::selectionChanged, this, &UINodeTreeView::onSelectionChanged); } UINodeTreeView::~UINodeTreeView() { } void UINodeTreeView::setFilterString(const QString& filterString) { m_pSortFilterModel->invalidate(); // m_pSortFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); // m_pSortFilterModel->setFilterRegExp(filterString); m_pSortFilterModel->setFilterString(filterString); this->expandAll(); } void UINodeTreeView::updateView(void) { m_pModel->refrush(); this->expandAll(); this->doItemsLayout(); } void UINodeTreeView::onItemSelectedChanged(void) { UICanvasView* pCanvasView = g_currentCanvasManager->getCurrentCanvasView(); // 清除全部选中 QItemSelectionModel* pSelectonModel = this->selectionModel(); QObject::disconnect(pSelectonModel, &QItemSelectionModel::selectionChanged, this, &UINodeTreeView::onSelectionChanged); pSelectonModel->clear(); // 获取被选中的节点 QList nodes = pCanvasView->getCurrentSelectedNodes(); foreach(NDNodeBase* pNode ,nodes) { // 获取节点的索引 QModelIndex index = m_pModel->getIndexByName(pNode->getNodeName()); if (!index.isValid()) continue; // 选中 pSelectonModel->select(m_pSortFilterModel->mapFromSource(index), QItemSelectionModel::Select); } QObject::connect(pSelectonModel, &QItemSelectionModel::selectionChanged, this, &UINodeTreeView::onSelectionChanged); } void UINodeTreeView::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { // 取消信号和槽函数的连接 UICanvasView* pCanvasView = g_currentCanvasManager->getCurrentCanvasView(); QObject::disconnect(pCanvasView, &UICanvasView::itemSelectedChanged, this, &UINodeTreeView::onItemSelectedChanged); QStringList nodeNames; QItemSelectionModel* pSelectonModel = this->selectionModel(); QModelIndexList indexs = pSelectonModel->selectedIndexes(); for (auto iter = indexs.begin(); iter != indexs.end(); ++iter) { nodeNames << iter->data().toString(); } g_currentCanvasManager->setSelectedNodes(nodeNames); // 重新连接 QObject::connect(pCanvasView, &UICanvasView::itemSelectedChanged, this, &UINodeTreeView::onItemSelectedChanged); } void UINodeTreeView::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Delete) { // 获取所有被选中的节点名字列表 QStringList nodeNames; QItemSelectionModel* pSelectonModel = this->selectionModel(); QModelIndexList indexs = pSelectonModel->selectedIndexes(); for (auto iter = indexs.begin(); iter != indexs.end(); ++iter) { nodeNames << iter->data().toString(); } // 删除节点 g_currentCanvasManager->deleteCanvasItems(nodeNames); } return QTreeView::keyPressEvent(event); } ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeView.h ================================================ #ifndef UINODETREEVIEW_H #define UINODETREEVIEW_H #include #include #include "easycanvascore_global.h" class UINodeTreeViewModel; class UINodeTreeDelegate; class UINodeSortFilterProxyModel; class EASYCANVASCORESHARED_EXPORT UINodeTreeView : public QTreeView { Q_OBJECT public: explicit UINodeTreeView(QWidget* parent = nullptr); ~UINodeTreeView(); void setFilterString(const QString& filterString); void updateView(void); private: UINodeTreeViewModel* m_pModel = nullptr; UINodeTreeDelegate* m_pDelegate = nullptr; UINodeSortFilterProxyModel* m_pSortFilterModel = nullptr; protected: void keyPressEvent(QKeyEvent *event) override; private slots: // 响应节点被选中 void onItemSelectedChanged(void); // 节点的选择发生改变 void onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected); }; #endif ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeViewModel.cpp ================================================ #include "UINodeTreeViewModel.h" #include "UINodeItem.h" #include "UICanvas/UICanvasItemManager.h" #include "UINodeTreeView.h" #include UINodeTreeViewModel::UINodeTreeViewModel(QObject* parent) :QAbstractItemModel(parent) { m_pCanvasItemData = g_currentCanvasManager; updateAllNodes(); QObject::connect(m_pCanvasItemData, &UICanvasItemManager::addedNode, this, &UINodeTreeViewModel::onAddedNodeItem); QObject::connect(m_pCanvasItemData, &UICanvasItemManager::deletedNode, this, &UINodeTreeViewModel::onDeleteNodeItem); QObject::connect(m_pCanvasItemData, &UICanvasItemManager::changeNodeName, this, &UINodeTreeViewModel::onChangeNodeItemName); } UINodeTreeViewModel::~UINodeTreeViewModel() { } QModelIndex UINodeTreeViewModel::index(int row, int column, const QModelIndex &parent) const { if (!this->hasIndex(row, column, parent)) return QModelIndex(); if (!parent.isValid()) { // 根节点 return createIndex(row, column, m_pRootNodeItem); } // 创建普通节点 UINodeItem* nodeItem = static_cast(parent.internalPointer()); if (nodeItem == nullptr) return QModelIndex(); // 获取当前的子节点 UINodeItem* childNode = nodeItem->getChildNode(row); if (childNode == nullptr) return QModelIndex(); // 创建节点 return createIndex(row, column, childNode); } QModelIndex UINodeTreeViewModel::parent(const QModelIndex &child) const { if (!child.isValid()) return QModelIndex(); // 获取父节点 UINodeItem* nodeItem = static_cast(child.internalPointer()); nodeItem = nodeItem->getParentNode(); if (nodeItem == nullptr) return QModelIndex(); // 获取父节点的索引 int row = nodeItem->getCurrentIndex(); return createIndex(row, 0, nodeItem); } int UINodeTreeViewModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { return 1; } UINodeItem* pNode = static_cast(parent.internalPointer()); return pNode->getSubNodeCount(); } int UINodeTreeViewModel::columnCount(const QModelIndex &parent) const { return 1; } QVariant UINodeTreeViewModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); UINodeItem* pNode = static_cast(index.internalPointer()); if (role == Qt::DisplayRole) { return pNode->getName(); } else if (role == Qt::DecorationRole) { if (pNode->isCanvasNode()) { return m_pCanvasItemData->getNodeTypeDisplayIcon( \ (UICanvasItemManager::CanvasItemType)pNode->getNodeType()); } } return QVariant(); } Qt::ItemFlags UINodeTreeViewModel::flags(const QModelIndex &index) const { UINodeItem* pNode = static_cast(index.internalPointer()); if (!pNode->isCanvasNode()) return QAbstractItemModel::flags(index) & ~Qt::ItemIsSelectable; return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } void UINodeTreeViewModel::updateAllNodes(void) { // 创建根节点 m_pRootNodeItem = new UINodeItem; m_pRootNodeItem->setParent(this); m_pRootNodeItem->setName(tr("CanvasNode")); int nodeTypeCount = m_pCanvasItemData->getNodeCounts(); for (int i=0; iappendChildNode(typeNode); // 获取类别的显示名字 QString typeName = m_pCanvasItemData->getNodeTypeDisplayName(\ (UICanvasItemManager::CanvasItemType)(i + (int)UICanvasItemManager::t_RectItem)); typeNode->setName(typeName); } } // 设置当前的TreeView void UINodeTreeViewModel::setCurrentTreeView(UINodeTreeView* pTreeView) { m_pTreeView = pTreeView; } QModelIndex UINodeTreeViewModel::getIndexByName(const QString nodeName) { if (m_pRootNodeItem == nullptr) return QModelIndex(); int count = m_pRootNodeItem->getSubNodeCount(); QModelIndex rootIndex = index(0, 0); for (int i=0; igetChildNode(i); QModelIndex typeIndex = index(i, 0, rootIndex); int subCount = typeNodes->getSubNodeCount(); // 查找目标节点 for (int j = 0; j < subCount; ++j) { UINodeItem* node = typeNodes->getChildNode(j); if (node && node->getName() == nodeName) { // 找到了 QModelIndex destIndex = index(j, 0, typeIndex); return destIndex; } } } return QModelIndex(); } void UINodeTreeViewModel::refrush(void) { this->beginResetModel(); this->endResetModel(); } bool UINodeTreeViewModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) return false; UINodeItem* pNode = static_cast(index.internalPointer()); QString nodeName = pNode->getName(); bool result = m_pCanvasItemData->isCanChangedName(nodeName, value.toString()); if (result) { m_pCanvasItemData->changedNodeNameCmd(nodeName, value.toString()); pNode->setName(value.toString()); return true; } else { qDebug() << "Has Finded Node " << nodeName; } return false; } void UINodeTreeViewModel::onAddedNodeItem(int nodeType, const QString& name) { UINodeItem* node = m_pRootNodeItem->getChildNode(nodeType - 2); if (node == nullptr) return; UINodeItem* childNode = new UINodeItem; childNode->setName(name); childNode->setCanvasNodeVisible(true); childNode->setNodeType(nodeType); node->appendChildNode(childNode); // 更新显示 m_pTreeView->updateView(); } void UINodeTreeViewModel::onDeleteNodeItem(int nodeType, const QString& name) { UINodeItem* node = m_pRootNodeItem->getChildNode(nodeType - 2); if (node == nullptr) return; // 删除节点 node->removeChildNode(name); // 更新显示 m_pTreeView->clearSelection(); m_pTreeView->updateView(); } void UINodeTreeViewModel::onChangeNodeItemName(int nodeType, const QString& srcName, const QString& destName) { UINodeItem* node = m_pRootNodeItem->getChildNode(nodeType - 2); if (node == nullptr) return; // 删除节点 UINodeItem* childNodeItem = node->getChildNode(srcName); if (childNodeItem == nullptr) return; childNodeItem->setName(destName); // 更新显示 //m_pTreeView->clearSelection(); m_pTreeView->doItemsLayout(); } ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeViewModel.h ================================================ #ifndef UINODETREEVIEWMODEL_H #define UINODETREEVIEWMODEL_H #include #include class UICanvasItemManager; class UINodeItem; class UINodeTreeView; class UINodeTreeViewModel : public QAbstractItemModel { Q_OBJECT public: explicit UINodeTreeViewModel(QObject* parent = nullptr); ~UINodeTreeViewModel() override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &child) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; // 更新数据节点 void updateAllNodes(void); // 设置当前的TreeView void setCurrentTreeView(UINodeTreeView* pTreeView); // 获取一个索引 QModelIndex getIndexByName(const QString nodeName); void refrush(void); private: UICanvasItemManager* m_pCanvasItemData = nullptr; UINodeItem* m_pRootNodeItem = nullptr; UINodeTreeView* m_pTreeView = nullptr; private slots: void onAddedNodeItem(int nodeType, const QString& name); void onDeleteNodeItem(int nodeType, const QString& name); void onChangeNodeItemName(int nodeType, const QString& srcName, const QString& destName); }; #endif ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeWidget.cpp ================================================ #include "UINodeTreeWidget.h" #include #include #include #include #include "UINodeTreeView.h" #include "UICustomCore/CustomStyleConfig.h" #include "UICustomSingleControl/UICustomLineEdit.h" UINodeTreeWidget::UINodeTreeWidget(QWidget* parent) :QWidget(parent) { QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->setSpacing(2); mainLayout->setMargin(2); // 顶部搜索 QWidget *pTopWidget = new QWidget; g_StyleConfig->setCurrentStyle(pTopWidget, "BottomLineWidget"); QHBoxLayout* pTopLayout = new QHBoxLayout(pTopWidget); pTopLayout->setMargin(2); pTopLayout->setSpacing(0); QLabel* pHeadLabel = new QLabel(tr("Search Node:")); pTopLayout->addWidget(pHeadLabel); // 搜索框 m_pLineEdit = new UICustomLineEdit; m_pLineEdit->setCloseButtonEnable(true); QObject::connect(m_pLineEdit, &UICustomLineEdit::currentTextChanged, this, &UINodeTreeWidget::onTextChanged); pTopLayout->addWidget(m_pLineEdit); mainLayout->addWidget(pTopWidget); // 添加节点树 m_pTreeView = new UINodeTreeView; mainLayout->addWidget(m_pTreeView); } UINodeTreeWidget::~UINodeTreeWidget() { } void UINodeTreeWidget::onTextChanged(const QString& text) { m_pTreeView->setFilterString(text); } ================================================ FILE: EasyCanvasCore/UINodeTree/UINodeTreeWidget.h ================================================ #ifndef UINODETREEWIDGET_H #define UINODETREEWIDGET_H #include #include "easycanvascore_global.h" class UINodeTreeView; class QLineEdit; class UICustomLineEdit; class EASYCANVASCORESHARED_EXPORT UINodeTreeWidget : public QWidget { Q_OBJECT public: explicit UINodeTreeWidget(QWidget* parent = nullptr); ~UINodeTreeWidget(); private: UICustomLineEdit* m_pLineEdit = nullptr; UINodeTreeView* m_pTreeView = nullptr; private slots: void onTextChanged(const QString& text); }; #endif ================================================ FILE: EasyCanvasCore/UndoCmd/ItemAttributeChangedCmd.cpp ================================================ #include "ItemAttributeChangedCmd.h" #include "NDAttributeBase.h" ItemAttributeChangedCmd::ItemAttributeChangedCmd(const QList& pAttributeList, \ const QVariant& value, bool canRun) :m_isCanRun(canRun) { QStringList attrNames; m_newValueList.push_back(value); for (auto iter = pAttributeList.begin(); iter != pAttributeList.end(); ++iter) { attrNames << (*iter)->getFullName(); m_pAttributeList.push_back(QPointer(*iter)); } QString nameString = "Changed Attribute [%1] To %2"; nameString = nameString.arg(attrNames.join(",")).arg(value.toString()); this->setText(nameString); } ItemAttributeChangedCmd::ItemAttributeChangedCmd(const QList& pAttributeList, const QVector& values, bool canRun) :m_newValueList(values) ,m_isCanRun(canRun) { QStringList attrNames; QStringList valueStrings; for (auto iter = pAttributeList.begin(); iter != pAttributeList.end(); ++iter) { attrNames << (*iter)->getFullName(); m_pAttributeList.push_back(QPointer(*iter)); } for (auto iter = values.begin(); iter != values.end(); ++iter) valueStrings << iter->toString(); QString nameString = "Changed Attribute [%1] To [%2]"; nameString = nameString.arg(attrNames.join(",")).arg(valueStrings.join(",")); this->setText(nameString); } ItemAttributeChangedCmd::~ItemAttributeChangedCmd() { } void ItemAttributeChangedCmd::undo() { int count = 0; for (auto iter = m_pAttributeList.begin(); iter != m_pAttributeList.end(); ++iter) { QVariant value = m_oldValueList[count++]; QPointer pointer = *iter; if (pointer.isNull()) continue; pointer->setValue(value); } } void ItemAttributeChangedCmd::redo() { int count = 0; bool isOldEmpty = m_oldValueList.isEmpty(); for (auto iter = m_pAttributeList.begin(); iter != m_pAttributeList.end(); ++iter) { QPointer pointer = *iter; if (pointer.isNull()) continue; if (m_isCanRun) pointer->setValue(m_newValueList[count++]); if (isOldEmpty) m_oldValueList << pointer->getLastValue(); } m_isCanRun = true; } ================================================ FILE: EasyCanvasCore/UndoCmd/ItemAttributeChangedCmd.h ================================================ #ifndef ITEMATTRIBUTECHANGEDCMD_H #define ITEMATTRIBUTECHANGEDCMD_H #include #include #include #include #include class NDAttributeBase; class ItemAttributeChangedCmd : public QUndoCommand { public: ItemAttributeChangedCmd(const QList& pAttributeList, const QVariant& value, bool canRun = false); ItemAttributeChangedCmd(const QList& pAttributeList, const QVector& values, bool canRun = false); ~ItemAttributeChangedCmd(); virtual void undo() override; virtual void redo() override; private: QList> m_pAttributeList; QVector m_oldValueList; QVector m_newValueList; bool m_isCanRun = false; }; #endif ================================================ FILE: EasyCanvasCore/UndoCmd/ItemChangeNameCmd.cpp ================================================ #include "ItemChangeNameCmd.h" #include "UICanvas/UICanvasItemBase.h" #include "NDNodeBase.h" #include "UICanvas/UICanvasItemManager.h" ItemChangeNameCmd::ItemChangeNameCmd(QSharedPointer pItem, const QString& destName) :m_pCanvasItem(pItem) ,m_destName(destName) { m_srcName = m_pCanvasItem->getCurrentNode()->getNodeName(); QString name = "Changed Node Name %1 To %2"; this->setText(name.arg(pItem->getCurrentNode()->getNodeName()).arg(destName)); } ItemChangeNameCmd::~ItemChangeNameCmd() { } void ItemChangeNameCmd::undo() { g_currentCanvasManager->changedNodeName(m_destName, m_srcName); } void ItemChangeNameCmd::redo() { g_currentCanvasManager->changedNodeName(m_srcName, m_destName); } ================================================ FILE: EasyCanvasCore/UndoCmd/ItemChangeNameCmd.h ================================================ #ifndef ITEMCNANGENAMECMD_H #define ITEMCNANGENAMECMD_H #include #include class UICanvasItemBase; class ItemChangeNameCmd : public QUndoCommand { public: explicit ItemChangeNameCmd(QSharedPointer pItem, const QString& destName); ~ItemChangeNameCmd(); void undo() override; void redo() override; private: QSharedPointer m_pCanvasItem; QString m_destName; QString m_srcName; }; #endif ================================================ FILE: EasyCanvasCore/UndoCmd/ItemCreateCmd.cpp ================================================ #include "ItemCreateCmd.h" #include "UICanvas/UICanvasItemManager.h" #include "UICanvas/UICanvasItemBase.h" ItemCreateCmd::ItemCreateCmd(int type) :m_nType(type) { m_itemCanvasItem.reset(); QString str("Create Node %1"); this->setText(str.arg(g_currentCanvasManager->getNodeTypeDisplayName((UICanvasItemManager::CanvasItemType)type))); } ItemCreateCmd::~ItemCreateCmd() { } void ItemCreateCmd::undo() { if (m_itemCanvasItem) { NDNodeBase* pNode = m_itemCanvasItem->getCurrentNode(); g_currentCanvasManager->deleteCanvasItem(pNode); } } void ItemCreateCmd::redo() { if (m_itemCanvasItem) { g_currentCanvasManager->addCanvasItem(m_itemCanvasItem); } else { UICanvasItemManager::CanvasItemType itemType = (UICanvasItemManager::CanvasItemType)m_nType; m_itemCanvasItem = g_currentCanvasManager->createCanvasItem(itemType); } } ================================================ FILE: EasyCanvasCore/UndoCmd/ItemCreateCmd.h ================================================ #ifndef ITEMCREATECMD_H #define ITEMCREATECMD_H #include #include class UICanvasItemBase; class ItemCreateCmd : public QUndoCommand { public: explicit ItemCreateCmd(int type); ~ItemCreateCmd(); void undo() override; void redo() override; private: int m_nType = 0; QSharedPointer m_itemCanvasItem; }; #endif ================================================ FILE: EasyCanvasCore/UndoCmd/ItemDeleteCmd.cpp ================================================ #include "ItemDeleteCmd.h" #include "UICanvas/UICanvasItemManager.h" #include "UICanvas/UICanvasItemBase.h" #include "NDNodeBase.h" ItemDeleteCmd::ItemDeleteCmd(QList> pItems) :m_pCanvasItems(pItems) { // 设置名字 QString deleteNodeString = "Delete Node [%1]"; QStringList strs; for (auto iter = pItems.begin(); iter != pItems.end(); ++iter) { strs << (*iter)->getCurrentNode()->getNodeName(); } this->setText(deleteNodeString.arg(strs.join(","))); } ItemDeleteCmd::~ItemDeleteCmd() { } void ItemDeleteCmd::undo(void) { foreach (auto canvasItem, m_pCanvasItems) { if (canvasItem.isNull()) continue; g_currentCanvasManager->addCanvasItem(canvasItem); } } void ItemDeleteCmd::redo(void) { QStringList nodeNames; foreach (auto canvasItem, m_pCanvasItems) { if (canvasItem.isNull()) continue; nodeNames << canvasItem->getCurrentNode()->getNodeName(); } g_currentCanvasManager->deleteCanvasItems(nodeNames); } ================================================ FILE: EasyCanvasCore/UndoCmd/ItemDeleteCmd.h ================================================ #ifndef ITEMDELETECMD_H #define ITEMDELETECMD_H #include #include class UICanvasItemBase; class ItemDeleteCmd : public QUndoCommand { public: explicit ItemDeleteCmd(QList> pItems); ~ItemDeleteCmd(); void undo(void) override; void redo(void) override; private: QList> m_pCanvasItems; }; #endif ================================================ FILE: EasyCanvasCore/UndoCmd/ItemPasteCmd.cpp ================================================ #include "ItemPasteCmd.h" #include "UICanvas/UICanvasItemManager.h" #include "UICanvas/UICanvasItemBase.h" ItemPasteCmd::ItemPasteCmd() { this->setText("Paste Cmd"); } ItemPasteCmd::~ItemPasteCmd() { } void ItemPasteCmd::undo(void) { for (auto iter = m_createdItems.begin(); iter != m_createdItems.end(); ++iter) { NDNodeBase* pNode = (*iter)->getCurrentNode(); g_currentCanvasManager->deleteCanvasItem(pNode); } } void ItemPasteCmd::redo(void) { if (m_createdItems.size() <= 0) m_createdItems = g_currentCanvasManager->paste(); else { for (auto iter = m_createdItems.begin(); iter != m_createdItems.end(); ++iter) { g_currentCanvasManager->addCanvasItem(*iter); } } } ================================================ FILE: EasyCanvasCore/UndoCmd/ItemPasteCmd.h ================================================ #ifndef ITEMPASTECMD_H #define ITEMPASTECMD_H #include #include class UICanvasItemBase; class ItemPasteCmd : public QUndoCommand { public: explicit ItemPasteCmd(); ~ItemPasteCmd(); void undo(void) override; void redo(void) override; private: QList> m_createdItems; }; #endif ================================================ FILE: EasyCanvasCore/UndoCmd/UndoCmdCore.cpp ================================================ #include "UndoCmdCore.h" #include "ItemCreateCmd.h" #include "ItemDeleteCmd.h" #include "ItemChangeNameCmd.h" #include "ItemPasteCmd.h" #include "ItemAttributeChangedCmd.h" #include "NDNodeBase.h" #include "UICanvas/UICanvasItemManager.h" UndoCmdCore::UndoCmdCore(QObject* parent) :QObject(parent) { m_pUndoStack = new QUndoStack(this); } UndoCmdCore::~UndoCmdCore() { } // 添加 创建节点命令 void UndoCmdCore::runCreateCmd(int type) { ItemCreateCmd* itemCreateCmd = new ItemCreateCmd(type); m_pUndoStack->push(itemCreateCmd); } // 添加 删除节点命令 void UndoCmdCore::runDeleteCmd(const QStringList& nodeNames) { // 获取节点元素列表 QList> canvasItems; foreach (const QString& nodeName, nodeNames) { auto canvasItem = g_currentCanvasManager->getCanvasItem(nodeName); canvasItems << canvasItem; } ItemDeleteCmd* itemDeleteCmd = new ItemDeleteCmd(canvasItems); m_pUndoStack->push(itemDeleteCmd); } // 添加 改变名字命令 void UndoCmdCore::runChangeNameCmd(const QString& nodeName, const QString& destNodeName) { auto canvasItem = g_currentCanvasManager->getCanvasItem(nodeName); ItemChangeNameCmd* changeNameCmd = new ItemChangeNameCmd(canvasItem, destNodeName); m_pUndoStack->push(changeNameCmd); } // 添加 改变属性命令 void UndoCmdCore::runChangedAttrCmd(const QString& attrFullName, const QVariant& value, bool isCanrun) { int index = attrFullName.indexOf("."); if (index < 0) return; QString nodeName = attrFullName.left(index); QString attrName = attrFullName.right(attrFullName.length() - index - 1); NDNodeBase* node = g_currentCanvasManager->getNode(nodeName); if (node == nullptr) return; NDAttributeBase* pAttribute = node->getAttribute(attrName); if (pAttribute == nullptr) return; QList attributeList; attributeList << pAttribute; ItemAttributeChangedCmd* changedAttr = new ItemAttributeChangedCmd(attributeList, value, isCanrun); m_pUndoStack->push(changedAttr); } void UndoCmdCore::runChangedAttrCmd(const QList& attrList, const QVariant& value, bool isCanrun) { ItemAttributeChangedCmd* changedAttr = new ItemAttributeChangedCmd(attrList, value, isCanrun); m_pUndoStack->push(changedAttr); } void UndoCmdCore::runChangedAttrCmd(const QList& attrList, \ const QVector& values, bool isCanrun) { ItemAttributeChangedCmd* changedAttr = new ItemAttributeChangedCmd(attrList, values, isCanrun); m_pUndoStack->push(changedAttr); } void UndoCmdCore::runPasteCmd(void) { ItemPasteCmd* pasteCmd = new ItemPasteCmd; m_pUndoStack->push(pasteCmd); } void UndoCmdCore::redo(void) { m_pUndoStack->redo(); } void UndoCmdCore::undo(void) { m_pUndoStack->undo(); } // 创建Redo/Undo Action QAction* UndoCmdCore::createRedoAction(void) { return m_pUndoStack->createRedoAction(this, tr("Redo")); } QAction* UndoCmdCore::createUndoAction(void) { return m_pUndoStack->createUndoAction(this, tr("Undo")); } QUndoView* UndoCmdCore::createUndoView(void) { QUndoView* pView = new QUndoView(m_pUndoStack); return pView; } bool UndoCmdCore::isUndoStackEmpty(void) { return m_pUndoStack->index() <= 0; } void UndoCmdCore::cleanUndoStack(void) { m_pUndoStack->clear(); } ================================================ FILE: EasyCanvasCore/UndoCmd/UndoCmdCore.h ================================================ #ifndef UNDOCMDCORE_H #define UNDOCMDCORE_H #include #include #include #include "easycanvascore_global.h" class NDAttributeBase; class EASYCANVASCORESHARED_EXPORT UndoCmdCore : public QObject { Q_OBJECT public: enum UndoCmdType { t_createCmd, t_deleteCmd, t_renameCmd, t_changedAttrCmd, t_pasteCmd }; public: UndoCmdCore(QObject* parent = nullptr); ~UndoCmdCore(); // 添加 创建节点命令 void runCreateCmd(int type); // 添加 删除节点命令 void runDeleteCmd(const QStringList& nodeNames); // 添加 改变名字命令 void runChangeNameCmd(const QString& nodeName, const QString& destNodeName); // 添加 改变属性命令 void runChangedAttrCmd(const QString& attrFullName, const QVariant& value, bool isCanrun = false); void runChangedAttrCmd(const QList& attrList, const QVariant& value, bool isCanrun = false); void runChangedAttrCmd(const QList& attrList, const QVector& values, bool isCanrun = false); // 粘贴命令 void runPasteCmd(void); void redo(void); void undo(void); // 创建Redo/Undo Action QAction* createRedoAction(void); QAction* createUndoAction(void); // 创建Redo/Undo View QUndoView* createUndoView(void); // Undo栈相关 bool isUndoStackEmpty(void); void cleanUndoStack(void); private: QUndoStack* m_pUndoStack = nullptr; }; #endif ================================================ FILE: EasyCanvasCore/easycanvascore_global.h ================================================ #ifndef EASYCANVASCORE_GLOBAL_H #define EASYCANVASCORE_GLOBAL_H #include #if defined(EASYCANVASCORE_LIBRARY) # define EASYCANVASCORESHARED_EXPORT Q_DECL_EXPORT #else # define EASYCANVASCORESHARED_EXPORT Q_DECL_IMPORT #endif #endif // EASYCANVASCORE_GLOBAL_H ================================================ FILE: EasyCanvas_zh_CH.ts ================================================ ColorControlWidgets ColorControl http://www.douzhq.cn 颜色对话框 http://www.douzhq.cn Test Color1: 测试颜色1: Test Color2: 测试颜色2: Test Color3: 测试颜色3: CustomTestWidget File 文件 Open File 打开文件 Save File 保存文件 Exit 退出 Edit 编辑 Redo 重做 Undo 取消 Copy 拷贝 Cut 剪切 Paste 粘贴 Other 其他 Theme 风格 Language 语言 About 关于 Common Controls Label: Test lineEdit Test1 Test2 Test3 Test4 CheckBox CheckBox1 CheckBox2 RadioButton RadioButton1 RadioButton2 TableWidget ID Name Sex Age Score ListWidgetItem1 ListWidgetItem2 ListWidgetItem3 ListWidgetItem4 HttpDownLoader Failed to get file size. 获取文件大小失败 Fail Recv File Data 接收文件数据失败 Recv Data Error, Error Code is 接受数据失败,错位码为 MainWindow MainPage 主页 Task Manager 任务管理 Action Manager 行动管理 Chart View 图表统计 Attribute 属性 UndoStack 撤销/重做栈 Script Console 脚本终端 NodeTree 节点树 Open Script File 打开Python脚本文件 Script Help 脚本命令帮助 Select 选择工具 Pen Item 画笔工具 Image Item 图片工具 Ellipse Item 圆形/椭圆工具 Rect Item 矩形工具 Text Item 文本工具 Audio Item 自定义音频工具 File 文件 Save As 另存为 CanvasItem 画布元素 Help 帮助 New 新建空白画布 Open 打开 Save 保存 SaveAs 另存为... Save To Image 保存为图片 Edit 编辑 Script Editor 脚本终端 Undo View 撤销/重做栈 About Me 关于我 Ready 就绪 Images (*.png *.jpg *.bmp) 图片(*.png *.jpg *.bmp) Save Info 保存信息 Save Successed! 保存成功 Python (*.py) Python(*.py) Opening... 加载中... Opened Successed 加载方案成功 Saving... 方案保存中... Save Successed 方案保存成功 Please Input Scheme Name 请输入方案名称 NDTextNode X Postion: X坐标 Y Postion: Y坐标 Text Content: 文本内容 Text Color: 文字颜色 QObject Http下载软件 作者:douzhq www.douzhq.cn Http下载软件 作者:不会飞的纸飞机 www.douzhq.cn OutlineText http://www.douzhq.cn 文字轮廓 http://www.douzhq.cn QtConcurrentTestWidget Calc 缩放 TaskViewItemWidget Close Time: %1 结束时间:%1 Edit 编辑 Delete 删除 Add Sub Task 添加子任务 Edit Task 编辑任务 UIAboutMeDialog About Me 关于我 UIActionItemWidget Edit 编辑 Delete 删除 Action Name: 行动名称: Task Name: 任务名称: Start Time: 开始时间: Plan Action 计划行动 Progressing Action 进行中... Finished Action 已完成 UIActionMainWindow Add Action 添加行动 UIAddAction Action Type: 行动类型 Action Name: 行动名称: Action Type: 行动类型: Plan Action 计划行动 Processing Action 进行中。。。 Finished Action 已完成 Task: 任务: Start Date: 开始日期: Start Time: 开始时间: Duration: 时长: Discript: 描述: OK 确定 Cannel 取消 UIAddTask Add Task 添加任务 Task Name: 任务名称: Task Color: 任务标记颜色: Parent Task: 父级任务: Close Date: 结束日期: Switch Duration: 是否开启时长: Duration(hour): 时长(小时): Descript: 描述: Edit Task 编辑任务 None UICanvasAudioItem Other Attribute 其他属性 Audio File Path: 音频文件路径: Browse 预览 Start Color: 开始颜色: End Color: 结束颜色: Open Audio File 选择音频文件 Audio Files (*.wav *.mp3) 音频文件(*.wav *.mp3) UICanvasEllipseItem Item Attribute 图元属性 Is Rounded: 是否为圆形: Is Fill Color: 是否填充颜色: Fill Color: 填充颜色: Show OutLine: 是否显示轮廓线: OutLine Width: 轮廓线的宽度: OutLine Color: 轮廓线的颜色: UICanvasImageItem Image Attribute 图片属性 Image Path: 图片路径: Browse 预览 Open Image File 打开图片文件 Image Files (*.bmp *.png *.jpg) 图片文件 (*.bmp *.png *.jpg) UICanvasItemBase Base Attribute 基本属性 X Postion: X坐标: Y Postion: Y坐标: Z Postion: Z坐标: width: 宽度: height: 高度: Rotate Angle: 旋转角度: UICanvasPathItem Item Attribute 图元属性 OutLine Width: 轮廓线宽度: OutLine Color: 轮廓线颜色: UICanvasRectItem Item Attribute 图元属性 Is Rounded: 是否为矩形: Is Fill Color: 是否填充颜色: Fill Color: 填充颜色: Show OutLine: 是否显示轮廓线: OutLine Width: 轮廓线宽度: OutLine Color: 轮廓线颜色: UICanvasScene Canvas Attribute 画布属性 width: 画布宽度: height: 画布高度: Canvas Color: 画布颜色: UICanvasTextItem Text Attribute 文本属性 Text: 文本: Font Size: 字体大小: Pen Size: 画笔大小: Text Color: 文字颜色: Is Fill Color: 是否填充颜色: Fill Color: 填充颜色: OutLine Attribute 轮廓线属性: Is Show Outline: 是否显示轮廓线: Outline Color: 轮廓线颜色: OutLine Width: 轮廓线宽度: UIConfigDialog Download Config 下载设置 Please InPut FileName: 请输入文件名称: Please Select FilePath: 请选择文件路径: Browse 预览 OK 确定 Cannel 取消 Select Dir: 选择目录: UICustomColorDialog Color Config 颜色配置 UICustomColorWidget AddToCustom 添加到自定义 OK 确定 Cannel 取消 Custom Color 自定义颜色 UIDownloadItemWidget Total Size is 总大小为 Download Finished, Total Size is 下载完成,总大小为 UIDownloadWidget DownLoad 已下载 Please Input Url: 请输入连接地址: UIImageView Load File 加载文件 Open Image Files 打开图片 Images (*.png *.xpm *.jpg *.bmp) Images (*.png *.xpm *.jpg *.bmp) UIMenuBar File 文件 Open Image 打开图片 Save 保存 Save To 保存到 Save Config 保存配置 Load Config 加载配置 Edit 编辑 Redo 重做 Undo 取消 Add Text Node 添加文本节点 UINodeTree Nodes 节点 UINodeTreeViewModel CanvasNode UINodeTreeWidget Search Node: 搜索节点: UIRightToolWidget Add 添加 Create 创建 Open Image 打开图片 Images (*.png *.xpm *.jpg *bmp) Images (*.png *.xpm *.jpg *bmp) Finished! 已完成 UISchemeManagerDialog Open Scheme 打开方案 Delete 删除 Open 打开 UITaskViewWidget Task List 任务列表 UIWaitPageWidget Developing, Please Wainging... 开发中,敬请期待。。。 UIWaterMarkToolWidget Text: 文本: Postion: 位置坐标: XInterVal: X偏移: YInterVal: Y偏移: Color Config 颜色配置 Text Color: 文字颜色: Outline Color: 轮廓线颜色: FontSize: 字体大小: Font Family: 字体: Outline Visible: 是否显示轮廓线: UndoCmdCore Redo 重做 Undo 撤销 ================================================ FILE: NDNodeAttribute/NDAttributeBase.cpp ================================================ #include "NDAttributeBase.h" #include "NDBoolAttribute.h" #include "NDRealAttribute.h" #include "NDColorAttribute.h" #include "NDIntAttribute.h" #include "NDStringAttribute.h" #include "NDNodeBase.h" #include "NDNodeManager.h" #include "Utils.h" #include NDAttributeBase::NDAttributeBase(NDNodeBase *parentNode) :QObject (parentNode) { QObject::connect(this, &NDAttributeBase::valueChanged, \ this, &NDAttributeBase::onValueChaned); } NDAttributeBase::~NDAttributeBase() { } // 设置名字 void NDAttributeBase::setName(const QString& name) { m_attributeName = name; if (m_displayName.isEmpty()) m_displayName = name; } QString NDAttributeBase::getName(void) { return m_attributeName; } // 设置显示名字 void NDAttributeBase::setDisplayName(const QString& name) { m_displayName = name; } QString NDAttributeBase::getDisplayName(void) { return m_displayName; } QString NDAttributeBase::getFullName(void) { if (m_pParentNode == nullptr) return ""; return m_pParentNode->getNodeName() + "." + m_attributeName; } // 设置/获取父节点 void NDAttributeBase::setParentGroup(NDAttributeGroup* group) { if (group == nullptr) return; this->setParent(group); m_pParentGroup = group; } NDAttributeGroup* NDAttributeBase::getParentGroup(void) { return m_pParentGroup; } // 设置/获取父节点 void NDAttributeBase::setParentNode(NDNodeBase* node) { m_pParentNode = node; } NDNodeBase* NDAttributeBase::getParentNode(void) { return m_pParentNode; } // 设置/获取使能 void NDAttributeBase::setEnable(bool isEnabled) { if (isEnabled != m_isEnabled) { m_isEnabled = isEnabled; emit enabledChanged(m_isEnabled); } } bool NDAttributeBase::isEnable(void) { return m_isEnabled; } NDAttributeBase* NDAttributeBase::createAttribute(const QString& name, AttributeType type, \ const QString& displayName) { NDAttributeBase* attribute = nullptr; switch (type) { case t_bool: { attribute = new NDBoolAttribute; break; } case t_int: { attribute = new NDIntAttribute; break; } case t_qreal: { attribute = new NDRealAttribute; break; } case t_string: { attribute = new NDStringAttribute; break; } case t_color: { attribute = new NDColorAttribute; break; } default: break; } if (attribute == nullptr) return nullptr; // 设置属性名称 attribute->setDisplayName(displayName); attribute->setName(name); return attribute; } QVariant NDAttributeBase::getLastValue(void) { return m_lastValue; } QString NDAttributeBase::getTypeName(void) { AttributeType type = this->Type(); switch (type) { case t_bool: return "Bool"; case t_int: return "Int"; case t_qreal: return "QReal"; case t_string: return "String"; case t_stringList: return "StringList"; case t_color: return "Color"; case t_postion2d: return "Postion2D"; } return ""; } // 设置/获取属性值 void NDAttributeBase::setValue(const QVariant& value, bool cmd) { // 处理第一次 if (m_isFirstSetValue) { m_lastValue = value; m_isFirstSetValue = false; } // 判断是否需要发送信号 bool needSendSignal = true; if (m_value == value) needSendSignal = false; QVariant tempValue = m_value; m_value = value; if (needSendSignal) { m_lastValue = tempValue; emit valueChanged(value, cmd); } } QVariant NDAttributeBase::getValue(void) { return m_value; } void NDAttributeBase::onValueChaned(const QVariant& value, bool cmd) { g_nodeManager->informAttributeValueChanged(this, value, cmd); } ================================================ FILE: NDNodeAttribute/NDAttributeBase.h ================================================ #ifndef NDATTRIBUTEBASE_H #define NDATTRIBUTEBASE_H #include #include #include "ndnodeattribute_global.h" class NDNodeBase; class NDAttributeGroup; class NDNODEATTRIBUTESHARED_EXPORT NDAttributeBase : public QObject { Q_OBJECT public: enum AttributeType { t_bool, // 布尔类型 t_int, // int 型 t_qreal, // 浮点型 t_string, // 字符串类型 t_stringList, // 字符串数组 t_color, // 颜色 t_postion2d // 2D坐标类型 }; public: NDAttributeBase(NDNodeBase *parentNode = nullptr); virtual ~NDAttributeBase(); virtual AttributeType Type(void) const = 0 ; static NDAttributeBase* createAttribute(const QString& name, AttributeType type, const QString& displayName = ""); // 获取上一次的属性值 QVariant getLastValue(void); // 类型名转字符串 QString getTypeName(void); // 设置/获取属性值 virtual void setValue(const QVariant& value, bool cmd = false); virtual QVariant getValue(void); // 设置名字 void setName(const QString& name); QString getName(void); // 设置显示名字 void setDisplayName(const QString& name); QString getDisplayName(void); // 获取全名 QString getFullName(void); // 设置/获取父节点组 void setParentGroup(NDAttributeGroup* group); NDAttributeGroup* getParentGroup(void); // 设置/获取父节点 void setParentNode(NDNodeBase* node); NDNodeBase* getParentNode(void); // 设置/获取使能 void setEnable(bool isEnabled); bool isEnable(void); protected: AttributeType m_attributeType; QString m_attributeName; QString m_displayName; bool m_isEnabled = true; QVariant m_lastValue; QVariant m_value; bool m_isFirstSetValue = true; NDAttributeGroup* m_pParentGroup = nullptr; NDNodeBase* m_pParentNode = nullptr; signals: void enabledChanged(bool enabled); void valueChanged(const QVariant& value, bool cmd = false); private slots: void onValueChaned(const QVariant& value, bool cmd); }; #endif ================================================ FILE: NDNodeAttribute/NDAttributeData.cpp ================================================ #include "NDAttributeData.h" NDAttributeData::NDAttributeData() { } NDAttributeData::~NDAttributeData() { } void NDAttributeData::setValue(bool value) { } void NDAttributeData::setValue(int value) { } void NDAttributeData::setValue(qreal value) { } void NDAttributeData::setValue(const QString& value) { } void NDAttributeData::setValue(const QStringList& value) { } void NDAttributeData::setValue(const QColor& value) { } void NDAttributeData::setValue(const QPoint& value) { } void NDAttributeData::getValue(bool& value) { } void NDAttributeData::getValue(int& value) { } void NDAttributeData::getValue(qreal& value) { } void NDAttributeData::getValue(QString& value) { } void NDAttributeData::getValue(QStringList& value) { } void NDAttributeData::getValue(QColor& value) { } void NDAttributeData::getValue(QPoint& value) { } ================================================ FILE: NDNodeAttribute/NDAttributeData.h ================================================ #ifndef NDATTRIBUTEDATA_H #define NDATTRIBUTEDATA_H #include #include #include #include #include #include "NDAttributeBase.h" class NDAttributeData { public: NDAttributeData(); virtual ~NDAttributeData(); // 设置值 void setValue(bool value); void setValue(int value); void setValue(qreal value); void setValue(const QString& value); void setValue(const QStringList& value); void setValue(const QColor& value); void setValue(const QPoint& value); // 获取值 void getValue(bool& value); void getValue(int& value); void getValue(qreal& value); void getValue(QString& value); void getValue(QStringList& value); void getValue(QColor& value); void getValue(QPoint& value); private: void* m_pData = nullptr; }; #endif ================================================ FILE: NDNodeAttribute/NDAttributeGroup.cpp ================================================ #include "NDAttributeGroup.h" #include "NDAttributeBase.h" #include "NDNodeBase.h" NDAttributeGroup::NDAttributeGroup(QObject* parent) :QObject(parent) { } NDAttributeGroup::~NDAttributeGroup() { } // 添加删除属性 void NDAttributeGroup::addAttribute(NDAttributeBase* attribute) { if (attribute == nullptr) return; m_attributes.push_back(attribute); attribute->setParentGroup(this); } // 删除属性 void NDAttributeGroup::deleteAttribute(NDAttributeBase* attribute) { for (auto iter = m_attributes.begin(); iter != m_attributes.end(); ++iter) { if (*iter == attribute) { m_attributes.erase(iter); attribute->deleteLater(); break; } } } void NDAttributeGroup::getAttributes(QList& attributes) { attributes = m_attributes; } NDAttributeBase* NDAttributeGroup::getAttribute(const QString& name) { foreach (auto item, m_attributes) if (item->getName() == name) return item; return nullptr; } // 设置父节点 void NDAttributeGroup::setParentNode(NDNodeBase* node) { m_pParentNode = node; this->setParent(node); } NDNodeBase* NDAttributeGroup::getParentNode(void) { return m_pParentNode; } // 设置/获取属性组的名称 void NDAttributeGroup::setName(const QString& name) { m_groupName = name; } QString NDAttributeGroup::getName(void) { return m_groupName; } void NDAttributeGroup::setDisplayName(const QString& name) { m_displayName = name; } QString NDAttributeGroup::getDisplayName(void) { return m_displayName; } ================================================ FILE: NDNodeAttribute/NDAttributeGroup.h ================================================ #ifndef NDATTRIBUTEGROUP_H #define NDATTRIBUTEGROUP_H #include #include "ndnodeattribute_global.h" class NDAttributeBase; class NDNodeBase; class NDNODEATTRIBUTESHARED_EXPORT NDAttributeGroup : public QObject { Q_OBJECT public: NDAttributeGroup(QObject* parent = nullptr); ~NDAttributeGroup(); // 添加删除属性 void addAttribute(NDAttributeBase* attribute); // 删除属性 void deleteAttribute(NDAttributeBase* attribute); // 获取全部属性 void getAttributes(QList& attributes); NDAttributeBase* getAttribute(const QString& name); // 设置父节点 void setParentNode(NDNodeBase* node); NDNodeBase* getParentNode(void); // 设置/获取属性组的名称 void setName(const QString& name); QString getName(void); // 设置/获取属性组的显示名称 void setDisplayName(const QString& name); QString getDisplayName(void); private: NDNodeBase* m_pParentNode = nullptr; QList m_attributes; QString m_groupName; QString m_displayName; }; #endif ================================================ FILE: NDNodeAttribute/NDBoolAttribute.cpp ================================================ #include "NDBoolAttribute.h" #include "NDNodeManager.h" NDBoolAttribute::NDBoolAttribute(NDNodeBase *parentNode) :NDAttributeBase(parentNode) { m_value = true; } NDBoolAttribute::~NDBoolAttribute() { } ================================================ FILE: NDNodeAttribute/NDBoolAttribute.h ================================================ #ifndef NDBOOLATTRIBTE_H #define NDBOOLATTRIBTE_H #include "NDAttributeBase.h" #include "ndnodeattribute_global.h" class NDNODEATTRIBUTESHARED_EXPORT NDBoolAttribute : public NDAttributeBase { Q_OBJECT public: NDBoolAttribute(NDNodeBase *parentNode = nullptr); ~NDBoolAttribute(); AttributeType Type(void) const override{ return t_bool; } }; #endif ================================================ FILE: NDNodeAttribute/NDColorAttribute.cpp ================================================ #include "NDColorAttribute.h" #include "NDNodeManager.h" #include NDColorAttribute::NDColorAttribute(NDNodeBase *parentNode) :NDAttributeBase(parentNode) { m_value.setValue(QColor()); } NDColorAttribute::~NDColorAttribute() { } ================================================ FILE: NDNodeAttribute/NDColorAttribute.h ================================================ #ifndef NDCOLORATTRIBUTE_H #define NDCOLORATTRIBUTE_H #include "NDAttributeBase.h" #include "ndnodeattribute_global.h" #include class NDNODEATTRIBUTESHARED_EXPORT NDColorAttribute : public NDAttributeBase { Q_OBJECT public: NDColorAttribute(NDNodeBase *parentNode = nullptr); ~NDColorAttribute(); AttributeType Type(void) const override{ return t_color; } }; #endif ================================================ FILE: NDNodeAttribute/NDIntAttribute.cpp ================================================ #include "NDIntAttribute.h" #include "NDNodeManager.h" NDIntAttribute::NDIntAttribute(NDNodeBase* parentNode) :NDAttributeBase(parentNode) { m_value = 0; } NDIntAttribute::~NDIntAttribute() { } // 设置/获取 取值范围 void NDIntAttribute::setValueRange(int minValue, int maxValue) { m_nMinValue = minValue; m_nMaxValue = maxValue; } void NDIntAttribute::getValueRange(int& minValue, int& maxValue) { minValue = m_nMinValue; maxValue = m_nMaxValue; } ================================================ FILE: NDNodeAttribute/NDIntAttribute.h ================================================ #ifndef NDINTATTRIBUTE_H #define NDINTATTRIBUTE_H #include "NDAttributeBase.h" #include "ndnodeattribute_global.h" class NDNODEATTRIBUTESHARED_EXPORT NDIntAttribute : public NDAttributeBase { Q_OBJECT public: NDIntAttribute(NDNodeBase* parentNode = nullptr); ~NDIntAttribute(); AttributeType Type(void) const{ return t_int; } // 设置/获取 取值范围 void setValueRange(int minValue, int maxValue); void getValueRange(int& minValue, int& maxValue); private: int m_nMinValue = 0; int m_nMaxValue = 100; }; #endif ================================================ FILE: NDNodeAttribute/NDNodeAttribute.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-01-27T11:54:33 # #------------------------------------------------- QT += widgets TARGET = NDNodeAttribute TEMPLATE = lib DEFINES += NDNODEATTRIBUTE_LIBRARY DESTDIR += $$PWD/../bin MOC_DIR += $$PWD/../NDNodeAttribute/temp OBJECTS_DIR += $$PWD/../NDNodeAttribute/temp CONFIG += c++11 LIBS += -L$$PWD/../bin -lUtils INCLUDEPATH += $$PWD/../Utils # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ NDAttributeBase.cpp \ NDAttributeData.cpp \ NDAttributeGroup.cpp \ NDBoolAttribute.cpp \ NDColorAttribute.cpp \ NDIntAttribute.cpp \ NDNodeBase.cpp \ NDNodeManager.cpp \ NDPostionAttribute.cpp \ NDRealAttribute.cpp \ NDStringAttribute.cpp \ NDTextNode.cpp HEADERS += \ NDAttributeBase.h \ NDAttributeData.h \ NDAttributeGroup.h \ NDBoolAttribute.h \ NDColorAttribute.h \ NDIntAttribute.h \ NDNodeBase.h \ NDNodeManager.h \ NDPostionAttribute.h \ NDRealAttribute.h \ NDStringAttribute.h \ NDTextNode.h \ ndnodeattribute_global.h unix { target.path = /usr/lib INSTALLS += target } ================================================ FILE: NDNodeAttribute/NDNodeBase.cpp ================================================ #include "NDNodeBase.h" NDNodeBase::NDNodeBase(NodeType type, QObject* parent) :QObject(parent) ,m_nodeType(type) { } NDNodeBase::NDNodeBase(QObject* parent) :QObject (parent) { } NDNodeBase::~NDNodeBase() { } // 设置/获取节点类型 void NDNodeBase::setNodeType(int type) { m_nodeType = type; } int NDNodeBase::getNodeType(void) { return m_nodeType; } // 添加属性 bool NDNodeBase::addAttribute(NDAttributeGroup* group, NDAttributeBase* attribute) { if (group == nullptr || attribute == nullptr) return false; group->addAttribute(attribute); attribute->setParentNode(this); return true; } bool NDNodeBase::addAttribute(const QString& groupName, NDAttributeBase* attribute) { if (attribute == nullptr) return false; NDAttributeGroup* attributeGroup = nullptr; foreach(auto item, m_groupList) { if (groupName == item->getName()) { attributeGroup = item; break; } } if (attributeGroup == nullptr) return false; return addAttribute(attributeGroup, attribute); } bool NDNodeBase::addAttribute(const QString& groupName, const QString& name, NDAttributeBase::AttributeType type) { NDAttributeBase* attribute = NDAttributeBase::createAttribute(name, type); addAttribute(groupName, attribute); return true; } // 删除属性 bool NDNodeBase::deleteAttribute(NDAttributeBase* attribute) { auto group = attribute->getParentGroup(); if (group == nullptr) return false; group->deleteAttribute(attribute); return true; } bool NDNodeBase::deleteAttribute(const QString& name) { foreach (auto item, m_groupList) { if (NDAttributeBase* attribute = item->getAttribute(name)) { deleteAttribute(attribute); return true; } } return false; } // 查找属性 NDAttributeBase* NDNodeBase::getAttribute(const QString& attrName) { foreach (auto item, m_groupList) { if (NDAttributeBase* attribute = item->getAttribute(attrName)) { return attribute; } } return nullptr; } // 设置节点名字 void NDNodeBase::setNodeName(const QString& nodeName) { m_name = nodeName; } QString NDNodeBase::getNodeName(void) { return m_name; } void NDNodeBase::getAllAttributeGroups(QList& groups) { groups = m_groupList; } void NDNodeBase::addAttributeGroup(NDAttributeGroup* group) { if (group == nullptr) return; group->setParentNode(this); m_groupList.append(group); } NDAttributeGroup* NDNodeBase::addAttributeGroup(const QString& name) { NDAttributeGroup* group = new NDAttributeGroup; group->setName(name); group->setDisplayName(name); addAttributeGroup(group); return group; } NDAttributeGroup* NDNodeBase::addAttributeGroup(const QString& name, const QString& displayName) { NDAttributeGroup* group = new NDAttributeGroup; group->setName(name); group->setDisplayName(displayName); addAttributeGroup(group); return group; } // 删除属性组 void NDNodeBase::deleteAttributeGroup(NDAttributeGroup* group) { for (auto iter = m_groupList.begin(); iter != m_groupList.end(); ++iter) { if (*iter == group) { m_groupList.erase(iter); group->deleteLater(); break; } } } void NDNodeBase::deleteAttributeGroup(const QString& name) { for (auto iter = m_groupList.begin(); iter != m_groupList.end(); ++iter) { if ((*iter)->getName() == name) { m_groupList.erase(iter); (*iter)->deleteLater(); break; } } } ================================================ FILE: NDNodeAttribute/NDNodeBase.h ================================================ #ifndef NDNODEBASE_H #define NDNODEBASE_H #include #include "NDAttributeBase.h" #include "NDAttributeGroup.h" #include "ndnodeattribute_global.h" class NDNODEATTRIBUTESHARED_EXPORT NDNodeBase : public QObject { Q_OBJECT public: enum NodeType { t_textNode, t_RectNode, t_Elleipse, t_Arrow, t_FreeDraw, t_User, // 自定义节点类型 t_End }; public: NDNodeBase(QObject* parent = nullptr); NDNodeBase(NodeType type, QObject* parent = nullptr); ~NDNodeBase(); // 设置/获取节点类型 void setNodeType(int type); virtual int getNodeType(void); // 设置节点名字 void setNodeName(const QString& nodeName); QString getNodeName(void); // 获取属性组 void getAllAttributeGroups(QList& groups); // 添加属性组 void addAttributeGroup(NDAttributeGroup* group); NDAttributeGroup* addAttributeGroup(const QString& name); NDAttributeGroup* addAttributeGroup(const QString& name, const QString& displayName); // 删除属性组 void deleteAttributeGroup(NDAttributeGroup* group); void deleteAttributeGroup(const QString& name); // 添加属性 bool addAttribute(NDAttributeGroup* group, NDAttributeBase* attribute); bool addAttribute(const QString& groupName, NDAttributeBase* attribute); bool addAttribute(const QString& groupName, const QString& name, NDAttributeBase::AttributeType type); // 删除属性 bool deleteAttribute(NDAttributeBase* attribute); bool deleteAttribute(const QString& name); // 查找属性 NDAttributeBase* getAttribute(const QString& attrName); private: QList m_groupList; int m_nodeType; QString m_name; // 节点名字 }; #endif ================================================ FILE: NDNodeAttribute/NDNodeManager.cpp ================================================ #include "NDNodeManager.h" #include "NDTextNode.h" NDNodeManager::NDNodeManager(QObject* parent) :QObject(parent) { } NDNodeManager::~NDNodeManager() { } NDNodeManager* NDNodeManager::getInstance(void) { static NDNodeManager instance; return &instance; } void NDNodeManager::informAttributeValueChanged(NDAttributeBase* pAttribute, const QVariant& value, bool cmd) { emit signalAttrValueChanged(pAttribute, value, cmd); } ================================================ FILE: NDNodeAttribute/NDNodeManager.h ================================================ #ifndef NDNODEMANAGER_H #define NDNODEMANAGER_H #include #include #include #include "NDNodeBase.h" #include "ndnodeattribute_global.h" #define g_nodeManager NDNodeManager::getInstance() class NDNODEATTRIBUTESHARED_EXPORT NDNodeManager : public QObject { Q_OBJECT public: NDNodeManager(QObject* parent = nullptr) ; ~NDNodeManager(); static NDNodeManager* getInstance(void); // 信号通知 void informAttributeValueChanged(NDAttributeBase* pAttribute, const QVariant& value, bool cmd = false); signals: void signalAttrValueChanged(NDAttributeBase* pAttribute, const QVariant& value, bool cmd = false); }; #endif ================================================ FILE: NDNodeAttribute/NDPostionAttribute.cpp ================================================ #include "NDPostionAttribute.h" NDPostionAttribute::NDPostionAttribute(NDNodeBase *parentNode) :NDAttributeBase(parentNode) { } NDPostionAttribute::~NDPostionAttribute() { } // 设置/获取 当前值 void NDPostionAttribute::setCurrentValue(const QPoint& value) { bool needSendSignal = true; if (m_value == value) needSendSignal = false; m_value = value; // 发送信号 if (needSendSignal) emit valueChanged(value); } QPoint NDPostionAttribute::getCurrentValue(void) { return m_value; } ================================================ FILE: NDNodeAttribute/NDPostionAttribute.h ================================================ #ifndef NDPOSTIONATTRIBUTE_H #define NDPOSTIONATTRIBUTE_H #include "NDAttributeBase.h" #include class NDPostionAttribute : public NDAttributeBase { Q_OBJECT public: NDPostionAttribute(NDNodeBase *parentNode = nullptr); ~NDPostionAttribute(); AttributeType Type(void) const override{ return t_postion2d; } // 设置/获取 当前值 void setCurrentValue(const QPoint& value); QPoint getCurrentValue(void); private: QPoint m_value; signals: void valueChanged(const QPoint& value); }; #endif ================================================ FILE: NDNodeAttribute/NDRealAttribute.cpp ================================================ #include "NDRealAttribute.h" #include "Utils.h" #include "NDNodeManager.h" NDRealAttribute::NDRealAttribute(NDNodeBase* parentNode) :NDAttributeBase(parentNode) { m_value = 0; } NDRealAttribute::~NDRealAttribute() { } // 设置/获取 取值范围 void NDRealAttribute::setValueRange(qreal minValue, qreal maxValue) { m_qMinValue = minValue; m_qMaxValue = maxValue; } void NDRealAttribute::getValueRange(qreal& minValue, qreal& maxValue) { minValue = m_qMinValue; maxValue = m_qMaxValue; } ================================================ FILE: NDNodeAttribute/NDRealAttribute.h ================================================ #ifndef NDREALATTRIBUTE_H #define NDREALATTRIBUTE_H #include "NDAttributeBase.h" #include "ndnodeattribute_global.h" class NDNodeBase; class NDNODEATTRIBUTESHARED_EXPORT NDRealAttribute : public NDAttributeBase { Q_OBJECT public: NDRealAttribute(NDNodeBase* parentNode = nullptr); ~NDRealAttribute(); AttributeType Type(void) const override{ return t_qreal; } // 设置/获取 取值范围 void setValueRange(qreal minValue, qreal maxValue); void getValueRange(qreal& minValue, qreal& maxValue); private: qreal m_qMinValue = 0; qreal m_qMaxValue = 100; }; #endif ================================================ FILE: NDNodeAttribute/NDStringAttribute.cpp ================================================ #include "NDStringAttribute.h" #include "NDNodeManager.h" NDStringAttribute::NDStringAttribute(NDNodeBase* parentNode) :NDAttributeBase(parentNode) { m_value = ""; } NDStringAttribute::~NDStringAttribute() { } // 设置/获取是否显示按钮 void NDStringAttribute::setShowButton(bool isShow) { m_isShowButton = isShow; } bool NDStringAttribute::isShowButton(void) { return m_isShowButton; } // 设置/获取按钮名字 void NDStringAttribute::setButtonString(const QString& buttonName) { m_buttonString = buttonName; } QString NDStringAttribute::getButtonString(void) { return m_buttonString; } // 设置按钮的功能 void NDStringAttribute::setButtonFunction(std::function func) { m_buttonFunc = func; } std::function NDStringAttribute::getButtonFunction(void) { return m_buttonFunc; } ================================================ FILE: NDNodeAttribute/NDStringAttribute.h ================================================ #ifndef NDSTRINGATTRIBUTE_H #define NDSTRINGATTRIBUTE_H #include "NDAttributeBase.h" #include "ndnodeattribute_global.h" #include class NDNODEATTRIBUTESHARED_EXPORT NDStringAttribute : public NDAttributeBase { Q_OBJECT public: NDStringAttribute(NDNodeBase* parentNode = nullptr); ~NDStringAttribute(); AttributeType Type(void) const override{ return t_string; } // 设置/获取是否显示按钮 void setShowButton(bool isShow); bool isShowButton(void); // 设置/获取按钮名字 void setButtonString(const QString& buttonName); QString getButtonString(void); // 设置按钮的功能 void setButtonFunction(std::function func); std::function getButtonFunction(void); private: bool m_isShowButton = false; QString m_buttonString = ""; std::function m_buttonFunc; }; #endif ================================================ FILE: NDNodeAttribute/NDTextNode.cpp ================================================ #include "NDTextNode.h" #include "NDBoolAttribute.h" #include "NDRealAttribute.h" #include "NDColorAttribute.h" #include "NDIntAttribute.h" #include "NDStringAttribute.h" NDTextNode::NDTextNode(QObject* parent) :NDNodeBase(t_textNode, parent) { initAttribute(); } NDTextNode::~NDTextNode() { } void NDTextNode::initAttribute(void) { // 文本位置信息 m_pPostionXAttr = new NDRealAttribute(this); m_pPostionXAttr->setName("XPostion"); m_pPostionXAttr->setDisplayName(tr("X Postion: ")); //this->addAttribute(m_pPostionXAttr); m_pPostionYAttr = new NDRealAttribute(this); m_pPostionYAttr->setName("YPostion"); m_pPostionYAttr->setDisplayName(tr("Y Postion: ")); //this->addAttribute(m_pPostionYAttr); // 文本内容 m_pTextAttr = new NDStringAttribute(this); m_pTextAttr->setName("text"); m_pTextAttr->setDisplayName(tr("Text Content: ")); //this->addAttribute(m_pTextAttr); // 文本颜色 m_pTextColorAttr = new NDColorAttribute(this); m_pTextColorAttr->setName("textColor"); m_pTextColorAttr->setDisplayName(tr("Text Color: ")); //this->addAttribute(m_pTextColorAttr); // NDStringAttribute* m_pTextAttr = nullptr; // NDColorAttribute* m_pTextColorAttr = nullptr; // NDIntAttribute* m_pFontSizeAttr = nullptr; // NDStringAttribute* m_pFontFamilyAttr = nullptr; // // 轮廓线相关 // NDBoolAttribute* m_pOutlineSwitchAttr = nullptr; // NDIntAttribute* m_pOutlineWidthAttr = nullptr; // NDColorAttribute* m_pOutlineColorAttr = nullptr; } NDRealAttribute* NDTextNode::getXPostionAttr(void) { return m_pPostionXAttr; } NDRealAttribute* NDTextNode::getYPostionAttr(void) { return m_pPostionYAttr; } NDStringAttribute* NDTextNode::getTextAttr(void) { return m_pTextAttr; } NDColorAttribute* NDTextNode::getTextColorAttr(void) { return m_pTextColorAttr; } ================================================ FILE: NDNodeAttribute/NDTextNode.h ================================================ #ifndef NDTEXTNODE_H #define NDTEXTNODE_H #include "NDNodeBase.h" #include "NDAttributeBase.h" #include class NDStringAttribute; class NDIntAttribute; class NDRealAttribute; class NDPostionAttribute; class NDBoolAttribute; class NDColorAttribute; class NDTextNode : public NDNodeBase { public: NDTextNode(QObject* parent = nullptr); ~NDTextNode(); // 获取属性 NDRealAttribute* getXPostionAttr(void); NDRealAttribute* getYPostionAttr(void); NDStringAttribute* getTextAttr(void); NDColorAttribute* getTextColorAttr(void); private: void initAttribute(void); NDRealAttribute* m_pPostionXAttr = nullptr; NDRealAttribute* m_pPostionYAttr = nullptr; NDStringAttribute* m_pTextAttr = nullptr; NDColorAttribute* m_pTextColorAttr = nullptr; NDIntAttribute* m_pFontSizeAttr = nullptr; NDStringAttribute* m_pFontFamilyAttr = nullptr; // 轮廓线相关 NDBoolAttribute* m_pOutlineSwitchAttr = nullptr; NDIntAttribute* m_pOutlineWidthAttr = nullptr; NDColorAttribute* m_pOutlineColorAttr = nullptr; }; #endif ================================================ FILE: NDNodeAttribute/ndnodeattribute_global.h ================================================ #ifndef NDNODEATTRIBUTE_GLOBAL_H #define NDNODEATTRIBUTE_GLOBAL_H #include #if defined(NDNODEATTRIBUTE_LIBRARY) # define NDNODEATTRIBUTESHARED_EXPORT Q_DECL_EXPORT #else # define NDNODEATTRIBUTESHARED_EXPORT Q_DECL_IMPORT #endif #endif // NDNODEATTRIBUTE_GLOBAL_H ================================================ FILE: NodeAttributeControl/NodeAttributeControl.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-01-27T13:54:45 # #------------------------------------------------- QT += widgets TARGET = NodeAttributeControl TEMPLATE = lib DEFINES += NODEATTRIBUTECONTROL_LIBRARY # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS DESTDIR += $$PWD/../bin MOC_DIR += $$PWD/../NodeAttributeControl/temp OBJECTS_DIR += $$PWD/../NodeAttributeControl/temp CONFIG += c++11 LIBS += -L$$PWD/../bin -lCustomWidgets LIBS += -L$$PWD/../bin -lCustomControls LIBS += -L$$PWD/../bin -lNDNodeAttribute INCLUDEPATH += $$PWD/../CustomWidgets INCLUDEPATH += $$PWD/../CustomControls INCLUDEPATH += $$PWD/../NDNodeAttribute QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ UIAttrBoolControl.cpp \ UIAttrColorControl.cpp \ UIAttrFloatControl.cpp \ UIAttrIntControl.cpp \ UIAttrTextControl.cpp \ UINodeAttrControl.cpp HEADERS += \ UIAttrBoolControl.h \ UIAttrColorControl.h \ UIAttrFloatControl.h \ UIAttrIntControl.h \ UIAttrTextControl.h \ UINodeAttrControl.h \ nodeattributecontrol_global.h unix { target.path = /usr/lib INSTALLS += target } ================================================ FILE: NodeAttributeControl/UIAttrBoolControl.cpp ================================================ #include "UIAttrBoolControl.h" UIAttrBoolControl::UIAttrBoolControl(NDAttributeBase* attribute, QWidget* parent) :UICustomSwitchControl(parent) { setAttribute(attribute); } UIAttrBoolControl::~UIAttrBoolControl() { } void UIAttrBoolControl::setAttribute(NDAttributeBase* attribute) { if (attribute == nullptr || attribute->Type() != NDAttributeBase::t_bool) return; m_attribute = qobject_cast(attribute); this->setCurrentValue(m_attribute->getValue().toBool()); this->setTagText(m_attribute->getDisplayName()); QObject::connect(m_attribute, &NDBoolAttribute::valueChanged, this, &UIAttrBoolControl::onAttrValueChanged); QObject::connect(this, &UIAttrBoolControl::valueChanged, this, &UIAttrBoolControl::onControlValueChanged); } void UIAttrBoolControl::onAttrValueChanged(const QVariant& value) { this->setCurrentValue(value.toBool(), false); } void UIAttrBoolControl::onControlValueChanged(bool value, bool cmd) { QObject::disconnect(m_attribute, &NDBoolAttribute::valueChanged, this, &UIAttrBoolControl::onAttrValueChanged); m_attribute->setValue(value, cmd); QObject::connect(m_attribute, &NDBoolAttribute::valueChanged, this, &UIAttrBoolControl::onAttrValueChanged); } ================================================ FILE: NodeAttributeControl/UIAttrBoolControl.h ================================================ #ifndef UIATTRBOOLCONTROL_H #define UIATTRBOOLCONTROL_H #include "CustomCombineControl/UICustomSwitchControl.h" #include "NDAttributeBase.h" #include "NDBoolAttribute.h" #include "nodeattributecontrol_global.h" class NODEATTRIBUTECONTROLSHARED_EXPORT UIAttrBoolControl : public UICustomSwitchControl { Q_OBJECT public: UIAttrBoolControl(NDAttributeBase* attribute = nullptr, QWidget* parent = nullptr); ~UIAttrBoolControl(); // 设置属性 void setAttribute(NDAttributeBase* attribute); private: NDBoolAttribute* m_attribute = nullptr; private slots: void onAttrValueChanged(const QVariant& value); void onControlValueChanged(bool value, bool cmd = false); }; #endif ================================================ FILE: NodeAttributeControl/UIAttrColorControl.cpp ================================================ #include "UIAttrColorControl.h" UIAttrColorControl::UIAttrColorControl(NDAttributeBase* attribute, QWidget* parent) :UICustomColorControl(parent) { setAttribute(attribute); } UIAttrColorControl::~UIAttrColorControl() { } void UIAttrColorControl::setAttribute(NDAttributeBase* attribute) { if (attribute == nullptr || attribute->Type() != NDAttributeBase::t_color) return; m_attribute = qobject_cast(attribute); this->setCurrentColor(m_attribute->getValue().value()); this->setTagText(m_attribute->getDisplayName()); // 连接信号和槽 QObject::connect(this, &UIAttrColorControl::colorChanged, this, &UIAttrColorControl::onControlValuedChanged); QObject::connect(this, &UIAttrColorControl::colorDragChanged, this, &UIAttrColorControl::onControlValuedChanged); QObject::connect(m_attribute, &NDColorAttribute::valueChanged, this, &UIAttrColorControl::onColorValueChanged); } void UIAttrColorControl::onColorValueChanged(const QVariant& value) { this->setCurrentColor(value.value()); } void UIAttrColorControl::onControlValuedChanged(const QColor& color, bool cmd) { if (m_attribute == nullptr) return; this->blockSignals(true); m_attribute->setValue(color, cmd); this->blockSignals(false); } ================================================ FILE: NodeAttributeControl/UIAttrColorControl.h ================================================ #ifndef UIATTRCOLORCONTROL_H #define UIATTRCOLORCONTROL_H #include "CustomCombineControl/UICustomColorControl.h" #include "NDAttributeBase.h" #include "NDColorAttribute.h" class UIAttrColorControl : public UICustomColorControl { Q_OBJECT public: UIAttrColorControl(NDAttributeBase* attribute = nullptr, QWidget* parent = nullptr); ~UIAttrColorControl(); // 设置属性 void setAttribute(NDAttributeBase* attribute); private: NDColorAttribute* m_attribute = nullptr; private slots: // 属性值发生改变同步控件 void onColorValueChanged(const QVariant& value); // 控件值发生改变同步属性 void onControlValuedChanged(const QColor& color, bool cmd = false); }; #endif ================================================ FILE: NodeAttributeControl/UIAttrFloatControl.cpp ================================================ #include "UIAttrFloatControl.h" #include UIAttrFloatControl::UIAttrFloatControl(NDAttributeBase* attribute, QWidget* parent) :UICustomDoubleControl(parent) { setAttribute(attribute); if (m_attribute == nullptr) return; QObject::connect(m_attribute, &NDRealAttribute::valueChanged, this, &UIAttrFloatControl::onValueChanged); QObject::connect(this, &UIAttrFloatControl::valueChanged, this, &UIAttrFloatControl::onControlValueChanged); } UIAttrFloatControl::~UIAttrFloatControl() { } void UIAttrFloatControl::setAttribute(NDAttributeBase* attribute) { if (attribute == nullptr || attribute->Type() != NDAttributeBase::t_qreal) return; m_attribute = qobject_cast(attribute); if (m_attribute == nullptr) return; // 设置范围 qreal startValue, endValue; m_attribute->getValueRange(startValue, endValue); this->setRangeValue(startValue, endValue); // 设置值 this->setCurrentValue(m_attribute->getValue().toDouble()); this->setTagText(m_attribute->getDisplayName()); } void UIAttrFloatControl::onValueChanged(const QVariant& value) { this->setCurrentValue(value.toDouble()); } void UIAttrFloatControl::onControlValueChanged(qreal value, bool cmd) { QObject::disconnect(m_attribute, &NDRealAttribute::valueChanged, this, &UIAttrFloatControl::onValueChanged); m_attribute->setValue(value, cmd); QObject::connect(m_attribute, &NDRealAttribute::valueChanged, this, &UIAttrFloatControl::onValueChanged); } ================================================ FILE: NodeAttributeControl/UIAttrFloatControl.h ================================================ #ifndef UIATTRFLOATCONTROL_H #define UIATTRFLOATCONTROL_H #include "CustomCombineControl/UICustomDoubleControl.h" #include "NDNodeBase.h" #include "NDRealAttribute.h" class UIAttrFloatControl : public UICustomDoubleControl { Q_OBJECT public: UIAttrFloatControl(NDAttributeBase* attribute = nullptr, QWidget* parent = nullptr); ~UIAttrFloatControl(); // 设置属性 void setAttribute(NDAttributeBase* attribute); private: NDRealAttribute* m_attribute = nullptr; private slots: void onValueChanged(const QVariant& value); void onControlValueChanged(qreal value, bool cmd = false); }; #endif ================================================ FILE: NodeAttributeControl/UIAttrIntControl.cpp ================================================ #include "UIAttrIntControl.h" UIAttrIntControl::UIAttrIntControl(NDAttributeBase* attribute, QWidget* parent) :UICustomIntControl(parent) { setAttribute(attribute); if (m_attribute == nullptr) return; QObject::connect(m_attribute, &NDIntAttribute::valueChanged, this, &UIAttrIntControl::onAttrValueChanged); QObject::connect(this, &UIAttrIntControl::valueChanged, this, &UIAttrIntControl::onControlValueChanged); } UIAttrIntControl::~UIAttrIntControl() { } // 设置属性 void UIAttrIntControl::setAttribute(NDAttributeBase* attribute) { if (attribute == nullptr || attribute->Type() != NDAttributeBase::t_int) return; m_attribute = qobject_cast(attribute); if (m_attribute == nullptr) return; // 设置范围 int min = 0, max = 0; m_attribute->getValueRange(min, max); this->setRangeValue(min, max); // 设置值 this->setCurrentValue(m_attribute->getValue().toInt()); this->setTagText(m_attribute->getDisplayName()); } void UIAttrIntControl::onAttrValueChanged(const QVariant& value) { this->setCurrentValue(value.toInt()); } void UIAttrIntControl::onControlValueChanged(int value, bool cmd) { QObject::disconnect(m_attribute, &NDIntAttribute::valueChanged, this, &UIAttrIntControl::onAttrValueChanged); m_attribute->setValue(value, cmd); QObject::connect(m_attribute, &NDIntAttribute::valueChanged, this, &UIAttrIntControl::onAttrValueChanged); } ================================================ FILE: NodeAttributeControl/UIAttrIntControl.h ================================================ #ifndef UIATTRINTCONTROL_H #define UIATTRINTCONTROL_H #include "CustomCombineControl/UICustomIntControl.h" #include "NDNodeBase.h" #include "NDIntAttribute.h" class UIAttrIntControl : public UICustomIntControl { Q_OBJECT public: UIAttrIntControl(NDAttributeBase* attribute = nullptr, QWidget* parent = nullptr); ~UIAttrIntControl(); // 设置属性 void setAttribute(NDAttributeBase* attribute); private: NDIntAttribute* m_attribute = nullptr; private slots: void onAttrValueChanged(const QVariant& value); void onControlValueChanged(int value, bool cmd = false); }; #endif ================================================ FILE: NodeAttributeControl/UIAttrTextControl.cpp ================================================ #include "UIAttrTextControl.h" UIAttrTextControl::UIAttrTextControl(NDAttributeBase* attribute, QWidget* parent) :UICustomLineEditControl(parent) { m_tempString = "EasyCanvas"; setAttribute(attribute); if (m_attribute == nullptr) return; // 根据属性类型,设置控件的按钮 this->setToolButtonVisible(m_attribute->isShowButton()); this->setToolButtonText(m_attribute->getButtonString()); QObject::connect(this, &UIAttrTextControl::clickedToolButton, this, &UIAttrTextControl::onClickedToolButton); } UIAttrTextControl::~UIAttrTextControl() { } void UIAttrTextControl::setAttribute(NDAttributeBase* attribute) { if (attribute == nullptr || attribute->Type() != NDAttributeBase::t_string) return; m_attribute = qobject_cast(attribute); if (m_attribute == nullptr) return; this->setText(m_attribute->getValue().toString()); this->setTagText(m_attribute->getDisplayName()); QObject::connect(m_attribute, &NDStringAttribute::valueChanged, this, &UIAttrTextControl::onTextAttrValueChanged); QObject::connect(this, &UIAttrTextControl::textChanged, this, &UIAttrTextControl::onControlTextChanged); QObject::connect(this, &UIAttrTextControl::editingFinished, this, &UIAttrTextControl::onControlEditFinished); } void UIAttrTextControl::onTextAttrValueChanged(const QVariant& value) { this->blockSignals(true); this->setText(value.toString()); this->blockSignals(false); } void UIAttrTextControl::onControlTextChanged(const QString& value) { QObject::disconnect(m_attribute, &NDStringAttribute::valueChanged, this, &UIAttrTextControl::onTextAttrValueChanged); m_attribute->setValue(value); QObject::connect(m_attribute, &NDStringAttribute::valueChanged, this, &UIAttrTextControl::onTextAttrValueChanged); } void UIAttrTextControl::onControlEditFinished(void) { QString text = this->getText(); if (m_tempString == text) return; QObject::disconnect(m_attribute, &NDStringAttribute::valueChanged, this, &UIAttrTextControl::onTextAttrValueChanged); m_attribute->setValue(m_tempString); m_tempString = text; m_attribute->setValue(text, true); QObject::connect(m_attribute, &NDStringAttribute::valueChanged, this, &UIAttrTextControl::onTextAttrValueChanged); } void UIAttrTextControl::onClickedToolButton(void) { auto func = m_attribute->getButtonFunction(); if (func) { QString str = ""; bool result = func(str); if (result) m_attribute->setValue(str, true); } } ================================================ FILE: NodeAttributeControl/UIAttrTextControl.h ================================================ #ifndef UIATTRTEXTCONTROL_H #define UIATTRTEXTCONTROL_H #include "CustomCombineControl/UICustomLineEditControl.h" #include "NDStringAttribute.h" #include class UIAttrTextControl : public UICustomLineEditControl { Q_OBJECT public: UIAttrTextControl(NDAttributeBase* attribute = nullptr, QWidget* parent = nullptr); ~UIAttrTextControl(); // 设置属性 void setAttribute(NDAttributeBase* attribute); private: NDStringAttribute* m_attribute = nullptr; QString m_tempString; private slots: void onTextAttrValueChanged(const QVariant& value); void onControlTextChanged(const QString& value); void onControlEditFinished(void); void onClickedToolButton(void); }; #endif ================================================ FILE: NodeAttributeControl/UINodeAttrControl.cpp ================================================ #include "UINodeAttrControl.h" #include "UIAttrColorControl.h" #include "UIAttrTextControl.h" #include "UIAttrFloatControl.h" #include "UIAttrIntControl.h" #include "UIAttrBoolControl.h" #include "NDAttributeBase.h" #include "NDAttributeGroup.h" #include "CustomCombineControl/UICustomGroupControl.h" #include UINodeAttrControl::UINodeAttrControl(QObject* parent) :QObject(parent) { } UINodeAttrControl::~UINodeAttrControl() { } QWidget* UINodeAttrControl::createNodeWidget(NDNodeBase* node) { if (node == nullptr) return nullptr; // 获取所有的属性组 QList attributeGroupList; node->getAllAttributeGroups(attributeGroupList); if (attributeGroupList.count() <= 0) return nullptr; QWidget* pWidget = new QWidget; QVBoxLayout* mainLayout = new QVBoxLayout(pWidget); mainLayout->setMargin(0); mainLayout->setSpacing(8); // 添加属性组 foreach(auto group, attributeGroupList) { QWidget* groupControl = createAttributeGroupControl(group); mainLayout->addWidget(groupControl, 0, Qt::AlignTop); } mainLayout->addStretch(); return pWidget; } QWidget* UINodeAttrControl::createAttributeControl(NDAttributeBase* attribute) { if (attribute == nullptr) return nullptr; NDAttributeBase::AttributeType attrType = attribute->Type(); switch (attrType) { case NDAttributeBase::t_color: { return new UIAttrColorControl(attribute); } case NDAttributeBase::t_string: { return new UIAttrTextControl(attribute); } case NDAttributeBase::t_qreal: { return new UIAttrFloatControl(attribute); } case NDAttributeBase::t_int: { return new UIAttrIntControl(attribute); } case NDAttributeBase::t_bool: { return new UIAttrBoolControl(attribute); } default: break; } return nullptr; } QWidget* UINodeAttrControl::createAttributeGroupControl(NDAttributeGroup* group) { if (group == nullptr) return nullptr; // 添加group control UICustomGroupControl* groupControl = new UICustomGroupControl; groupControl->setTitleText(group->getDisplayName()); // 添加属性控件 QList attributes; group->getAttributes(attributes); foreach(auto attribute, attributes) { QWidget* pWidget = createAttributeControl(attribute); if (pWidget == nullptr) continue; groupControl->addContentWidget(pWidget); } return groupControl; } ================================================ FILE: NodeAttributeControl/UINodeAttrControl.h ================================================ #ifndef UINODEATTRCONTROL_H #define UINODEATTRCONTROL_H #include "NDNodeManager.h" #include "NDNodeBase.h" #include "nodeattributecontrol_global.h" #include #include class NDAttributeBase; class NDAttributeGroup; class NODEATTRIBUTECONTROLSHARED_EXPORT UINodeAttrControl : public QObject { Q_OBJECT public: UINodeAttrControl(QObject* parent = nullptr); ~UINodeAttrControl(); // 根据节点创建Widget static QWidget* createNodeWidget(NDNodeBase* node); private: // 创建属性控件 static QWidget* createAttributeControl(NDAttributeBase* attribute); // 创建属性组Widget static QWidget* createAttributeGroupControl(NDAttributeGroup* group); }; #endif ================================================ FILE: NodeAttributeControl/nodeattributecontrol_global.h ================================================ #ifndef NODEATTRIBUTECONTROL_GLOBAL_H #define NODEATTRIBUTECONTROL_GLOBAL_H #include #if defined(NODEATTRIBUTECONTROL_LIBRARY) # define NODEATTRIBUTECONTROLSHARED_EXPORT Q_DECL_EXPORT #else # define NODEATTRIBUTECONTROLSHARED_EXPORT Q_DECL_IMPORT #endif #endif // NODEATTRIBUTECONTROL_GLOBAL_H ================================================ FILE: PythonWrap/PythonWrap.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-07-13T22:27:57 # #------------------------------------------------- QT += gui widgets TARGET = PythonWrap TEMPLATE = lib DEFINES += PYTHONWRAP_LIBRARY # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS DESTDIR += $$PWD/../bin MOC_DIR += $$PWD/../PythonWrap/temp OBJECTS_DIR += $$PWD/../PythonWrap/temp # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 LIBS += -L$$PWD/../bin -lNDNodeAttribute LIBS += -L$$PWD/../bin -lEasyCanvasCore INCLUDEPATH += $$PWD/../NDNodeAttribute INCLUDEPATH += $$PWD/../EasyCanvasCore INCLUDEPATH += $$PWD/../thirdLibs/PythonQt_3_10/include INCLUDEPATH += $$PWD/../thirdLibs/python3_10/include CONFIG(debug, debug|release) { LIBS += -L$$PWD/../thirdLibs/PythonQt/libs/debug -lPythonQt_QtAll-Qt5-Python38_d -lPythonQt-Qt5-Python38_d LIBS += -L$$PWD/../thirdLibs/python3_8/libs -lpython3_d -lpython38_d } else { LIBS += -L$$PWD/../thirdLibs/PythonQt/libs/release -lPythonQt_QtAll-Qt5-Python38 -lPythonQt-Qt5-Python38 LIBS += -L$$PWD/../thirdLibs/python3_8/libs -lpython3 -lpython38 # python3.10 , VS2019 #LIBS += -L$$PWD/../thirdLibs/PythonQt_3_10/libs/release -lPythonQt_QtAll-Qt5-Python3.10 -lPythonQt-Qt5-Python3.10 #LIBS += -L$$PWD/../thirdLibs/python3_10/libs -lpython3 -lpython310 } QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG SOURCES += \ PythonWrapCore.cpp \ pythonwrap.cpp HEADERS += \ PythonWrapCore.h \ pythonwrap.h \ pythonwrap_global.h unix { target.path = /usr/lib INSTALLS += target } ================================================ FILE: PythonWrap/PythonWrapCore.cpp ================================================ #include "PythonWrapCore.h" #include "NDNodeBase.h" #include "NDAttributeGroup.h" #include "NDAttributeBase.h" #include "NDBoolAttribute.h" #include "NDColorAttribute.h" #include "NDIntAttribute.h" #include "NDRealAttribute.h" #include "NDPostionAttribute.h" #include "NDRealAttribute.h" #include "NDStringAttribute.h" #include "gui/PythonQtScriptingConsole.h" #include "UICanvas/UICanvasItemManager.h" #include "UICanvas/UICanvasItemBase.h" #include #include #include #include PythonWrapCore::PythonWrapCore(QObject* parent) :QObject(parent) { } PythonWrapCore::~PythonWrapCore() { } PythonWrapCore* PythonWrapCore::getInstace(void) { static PythonWrapCore instance; return &instance; } void PythonWrapCore::init(void) { qDebug() << "PythonWrap Init"; // init PythonQt and Python PythonQt::init(); PythonQt_QtAll::init(); m_mainObject = PythonQt::self()->getMainModule(); if (!m_mainObject.isNull()) m_mainObject.addObject("easyCanvas", g_PythonWrapCode); qDebug() << "PythonWrap End"; } // 改变属性值 void PythonWrapCore::setAttribute(const QString& attributeName, const QVariant& var) { // 获取节点名称 int index = attributeName.indexOf("."); if (index < 0) { writeConsoleOutPut("Attribute Error"); return; } QString nodeName = attributeName.left(index); QString attrName = attributeName.right(attributeName.length() - index - 1); // 处理场景节点 if (m_pSceneNode->getNodeName() == nodeName) { // 获取属性指针 NDAttributeBase* pAttr = getAttributeByName(m_pSceneNode, attrName); if (pAttr == nullptr) { writeConsoleOutPut("Attribute Error"); return; } // 设置值 setAttributeValue(pAttr, var); return; } // 处理普通元素节点 NDNodeBase* pNode = g_currentCanvasManager->getNode(nodeName); if (pNode == nullptr) { writeConsoleOutPut(QString("Not Has This Node ") + nodeName); return; } // 获取属性 NDAttributeBase* pAttr = getAttributeByName(pNode, attrName); if (pAttr == nullptr) { writeConsoleOutPut(QString("Not Has This Attribute ") + attrName); return; } setAttributeValue(pAttr, var); } QString PythonWrapCore::createNode(const QString& typeName) { UICanvasItemManager::CanvasItemType type = g_currentCanvasManager->getTypeByName(typeName); if (type == UICanvasItemManager::t_None || type == UICanvasItemManager::t_CanvasItem) { writeConsoleOutPut("Can't Create This Type Node!"); return ""; } QSharedPointer node = g_currentCanvasManager->createCanvasItemByCmd(type); if (node.isNull()) { writeConsoleOutPut("Create Node Error!"); return ""; } return node->getCurrentNode()->getNodeName(); } void PythonWrapCore::deleteNode(const QString& nodeName) { if (g_currentCanvasManager->getNode(nodeName) == nullptr) { writeConsoleOutPut(QString("Not Has This Node ") + nodeName); return; } QStringList strs; strs << nodeName; g_currentCanvasManager->deleteCanvasItemByCmd(strs); } void PythonWrapCore::changeNodeName(const QString& srcName, const QString& destName) { if (!g_currentCanvasManager->isCanChangedName(srcName, destName)) { writeConsoleOutPut("Can't Changed Node Name!"); return; } g_currentCanvasManager->changedNodeNameCmd(srcName, destName); } QStringList PythonWrapCore::getAllNodes(void) { return g_currentCanvasManager->getAllNodeNames(); } QStringList PythonWrapCore::getSelectedNodes(void) { return g_currentCanvasManager->getSelectedNodes(); } QString PythonWrapCore::getNodeType(const QString& nodeName) { NDNodeBase* pNode = g_currentCanvasManager->getNode(nodeName); if (pNode == nullptr) { writeConsoleOutPut("Can't Finde This Node!"); return ""; } return g_currentCanvasManager->getTypeName((UICanvasItemManager::CanvasItemType)pNode->getNodeType()); } QStringList PythonWrapCore::getAttributeNames(const QString& nodeName) { QStringList strs; NDNodeBase* pNode = g_currentCanvasManager->getNode(nodeName); if (pNode == nullptr) { writeConsoleOutPut("Can't Finde This Node!"); return strs; } QList groups; pNode->getAllAttributeGroups(groups); for (auto iter = groups.begin(); iter != groups.end(); ++iter) { QList attrs; (*iter)->getAttributes(attrs); for (auto nIter = attrs.begin(); nIter != attrs.end(); ++nIter) { strs << (*nIter)->getName(); } } return strs; } Q_INVOKABLE QVariant PythonWrapCore::getValue(const QString& attributeName) { // 获取节点名称 int index = attributeName.indexOf("."); if (index < 0) { writeConsoleOutPut("Attribute Error"); return ""; } QString nodeName = attributeName.left(index); QString attrName = attributeName.right(attributeName.length() - index - 1); // 处理场景节点 if (m_pSceneNode->getNodeName() == nodeName) { // 获取属性指针 NDAttributeBase* pAttr = getAttributeByName(m_pSceneNode, attrName); if (pAttr == nullptr) { writeConsoleOutPut("Attribute Error"); return ""; } // 设置值 return pAttr->getValue(); } // 处理普通元素节点 NDNodeBase* pNode = g_currentCanvasManager->getNode(nodeName); if (pNode == nullptr) { writeConsoleOutPut(QString("Not Has This Node ") + nodeName); return ""; } // 获取属性 NDAttributeBase* pAttr = getAttributeByName(pNode, attrName); if (pAttr == nullptr) { writeConsoleOutPut(QString("Not Has This Attribute ") + attrName); return ""; } return pAttr->getValue(); } QString PythonWrapCore::getAttributeType(const QString& attributeName) { // 获取节点名称 int index = attributeName.indexOf("."); if (index < 0) { writeConsoleOutPut("Attribute Error"); return ""; } QString nodeName = attributeName.left(index); QString attrName = attributeName.right(attributeName.length() - index - 1); // 处理场景节点 if (m_pSceneNode->getNodeName() == nodeName) { // 获取属性指针 NDAttributeBase* pAttr = getAttributeByName(m_pSceneNode, attrName); if (pAttr == nullptr) { writeConsoleOutPut("Attribute Error"); return ""; } // 设置值 return pAttr->getTypeName(); } // 处理普通元素节点 NDNodeBase* pNode = g_currentCanvasManager->getNode(nodeName); if (pNode == nullptr) { writeConsoleOutPut(QString("Not Has This Node ") + nodeName); return ""; } // 获取属性 NDAttributeBase* pAttr = getAttributeByName(pNode, attrName); if (pAttr == nullptr) { writeConsoleOutPut(QString("Not Has This Attribute ") + attrName); return ""; } return pAttr->getTypeName(); } void PythonWrapCore::setSceneNode(NDNodeBase* sceneNode) { m_pSceneNode = sceneNode; } QWidget* PythonWrapCore::getScriptConsole(void) { if (m_pScriptConsole == nullptr) { m_pScriptConsole = new PythonQtScriptingConsole(nullptr, m_mainObject); m_pScriptConsole->resize(800, 600); } return m_pScriptConsole; } void PythonWrapCore::writeConsoleOutPut(const QString& message) { m_pScriptConsole->stdOut(message); } void PythonWrapCore::runScriptFiles(const QString& fileName) { if (!QFile::exists(fileName)) { writeConsoleOutPut("The Script File is not Existed!"); return; } QFile file(fileName); file.open(QFile::ReadOnly); QString pyFile = file.readAll(); file.close(); m_mainObject.evalScript(pyFile); } NDAttributeBase* PythonWrapCore::getAttributeByName(NDNodeBase* node, const QString& attrName) { if (node == nullptr) return nullptr; // 获取属性组 QList attrGroups; node->getAllAttributeGroups(attrGroups); for (auto iter = attrGroups.begin(); iter != attrGroups.end(); ++iter) { NDAttributeBase* pAttr = (*iter)->getAttribute(attrName); if (pAttr != nullptr) return pAttr; } return nullptr; } void PythonWrapCore::setAttributeValue(NDAttributeBase* pAttr, const QVariant& var) { if (pAttr == nullptr) return; pAttr->setValue(var, true); } ================================================ FILE: PythonWrap/PythonWrapCore.h ================================================ #ifndef PYTHONWRAPCORE_H #define PYTHONWRAPCORE_H #include #include #include "pythonwrap_global.h" #include "PythonQt.h" #include "PythonQt_QtAll.h" #define g_PythonWrapCode PythonWrapCore::getInstace() class NDNodeBase; class NDAttributeBase; class PythonQtScriptingConsole; class PYTHONWRAPSHARED_EXPORT PythonWrapCore : public QObject { Q_OBJECT public: static PythonWrapCore* getInstace(void); // 初始化 void init(void); // 设置场景的节点 void setSceneNode(NDNodeBase* sceneNode); // 显示脚本控制台 QWidget* getScriptConsole(void); // 添加控制台输出 void writeConsoleOutPut(const QString& message); // 执行文件 void runScriptFiles(const QString& fileName); public: // 下面是主要针对python的接口 // 改变属性值 Q_INVOKABLE void setAttribute(const QString& attributeName, const QVariant& var); // 添加和删除节点 Q_INVOKABLE QString createNode(const QString& typeName); Q_INVOKABLE void deleteNode(const QString& nodeName); // 修改节点的名字 Q_INVOKABLE void changeNodeName(const QString& srcName, const QString& destName); // 获取节点名等 Q_INVOKABLE QStringList getAllNodes(void); // 获取选择的节点名 Q_INVOKABLE QStringList getSelectedNodes(void); // 获取节点类型 Q_INVOKABLE QString getNodeType(const QString& nodeName); // 获取属性列表 Q_INVOKABLE QStringList getAttributeNames(const QString& nodeName); // 获取属性值 Q_INVOKABLE QVariant getValue(const QString& attributeName); // 获取属性的类型 Q_INVOKABLE QString getAttributeType(const QString& attributeName); private: PythonWrapCore(QObject* parent = nullptr); ~PythonWrapCore(); NDNodeBase* m_pSceneNode = nullptr; // 获取属性指针 NDAttributeBase* getAttributeByName(NDNodeBase* node, const QString& attrName); // 为属性赋值 void setAttributeValue(NDAttributeBase* pAttr, const QVariant& var); private: PythonQtObjectPtr m_mainObject; PythonQtScriptingConsole* m_pScriptConsole = nullptr; }; #endif ================================================ FILE: PythonWrap/pythonwrap.cpp ================================================ #include "pythonwrap.h" PythonWrap::PythonWrap() { } ================================================ FILE: PythonWrap/pythonwrap.h ================================================ #ifndef PYTHONWRAP_H #define PYTHONWRAP_H #include "pythonwrap_global.h" class PYTHONWRAPSHARED_EXPORT PythonWrap { public: PythonWrap(); }; #endif // PYTHONWRAP_H ================================================ FILE: PythonWrap/pythonwrap_global.h ================================================ #ifndef PYTHONWRAP_GLOBAL_H #define PYTHONWRAP_GLOBAL_H #include #if defined(PYTHONWRAP_LIBRARY) # define PYTHONWRAPSHARED_EXPORT Q_DECL_EXPORT #else # define PYTHONWRAPSHARED_EXPORT Q_DECL_IMPORT #endif #endif // PYTHONWRAP_GLOBAL_H ================================================ FILE: Utils/RALLBlockSignal.cpp ================================================ #include "RALLBlockSignal.h" RALLBlockSingal::RALLBlockSingal(QObject* object) :m_pObject(object) { object->blockSignals(true); } RALLBlockSingal::~RALLBlockSingal() { m_pObject->blockSignals(false); } ================================================ FILE: Utils/RALLBlockSignal.h ================================================ #ifndef RALLBLOCKSIGNAL_H #define RALLBLOCKSIGNAL_H #include #include "utils_global.h" class UTILSSHARED_EXPORT RALLBlockSingal { public: RALLBlockSingal(QObject* object); virtual ~RALLBlockSingal(); private: QObject* m_pObject = nullptr; }; #endif ================================================ FILE: Utils/Utils.cpp ================================================ #include "Utils.h" Utils::Utils() { } Utils::~Utils() { } Utils* Utils::getInstance(void) { static Utils instance; return &instance; } // 获取两个点的距离 qreal Utils::getDistance(const QPointF& p1, const QPointF& p2) { qreal distance = sqrt((p1.x() - p2.x()) * (p1.x() - p2.x()) + \ (p1.y() - p2.y()) * (p1.y() - p2.y())); return distance; } // 比较两个浮点数是否相等 bool Utils::isEqual(qreal number1, qreal number2) { if (abs(number1 - number2) <= FLOAT_INTER_VALUE) return true; return false; } ================================================ FILE: Utils/Utils.h ================================================ #ifndef UTILS_H #define UTILS_H #include "utils_global.h" #include #define g_utilTool Utils::getInstance() #define FLOAT_INTER_VALUE 0.0000001 #define PI 3.14159265358979 class UTILSSHARED_EXPORT Utils { public: static Utils* getInstance(void); // 获取两个点的距离 qreal getDistance(const QPointF& p1, const QPointF& p2); // 比较两个浮点数是否相等 bool isEqual(qreal number1, qreal number2); private: Utils(); virtual ~Utils(); }; #endif // UTILS_H ================================================ FILE: Utils/Utils.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2020-02-17T15:32:51 # #------------------------------------------------- QT -= gui TARGET = Utils TEMPLATE = lib DEFINES += UTILS_LIBRARY DESTDIR += $$PWD/../bin MOC_DIR += $$PWD/../Utils/temp OBJECTS_DIR += $$PWD/../Utils/temp CONFIG += c++11 # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS QMAKE_CXXFLAGS_RELEASE += /Zi QMAKE_CXXFLAGS_RELEASE += /Od QMAKE_LFLAGS_RELEASE += /DEBUG # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ RALLBlockSignal.cpp \ Utils.cpp HEADERS += \ RALLBlockSignal.h \ Utils.h \ utils_global.h unix { target.path = /usr/lib INSTALLS += target } ================================================ FILE: Utils/utils_global.h ================================================ #ifndef UTILS_GLOBAL_H #define UTILS_GLOBAL_H #include #if defined(UTILS_LIBRARY) # define UTILSSHARED_EXPORT Q_DECL_EXPORT #else # define UTILSSHARED_EXPORT Q_DECL_IMPORT #endif #endif // UTILS_GLOBAL_H ================================================ FILE: bin/CustomColor.xml ================================================ ================================================ FILE: bin/Script/SetColorAlphaScript.py ================================================ from PythonQt import QtCore, QtGui print('Show Set Color Script') # 创建一个窗口 mainWidget = QtGui.QWidget() mainWidget.setWindowTitle("Color Alpha Set"); mainLayout = QtGui.QVBoxLayout(mainWidget); # 创建ComboBox topWidget = QtGui.QWidget() mainLayout.addWidget(topWidget) topLayout = QtGui.QHBoxLayout(topWidget) topLabel = QtGui.QLabel("Attribute Name: ") topLayout.addWidget(topLabel) global attrComboBox attrComboBox = QtGui.QComboBox() attrComboBox.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed) topLayout.addWidget(attrComboBox) # 创建Slider bottomWidget = QtGui.QWidget() mainLayout.addWidget(bottomWidget) bottomLayout = QtGui.QHBoxLayout(bottomWidget) global bottomLabel bottomLabel = QtGui.QLabel("Alpha(100%): ") bottomLayout.addWidget(bottomLabel) global alphaSlider alphaSlider = QtGui.QSlider(QtCore.Qt.Horizontal) alphaSlider.setMinimum(0) alphaSlider.setMaximum(255) bottomLayout.addWidget(alphaSlider) # 按钮 buttonWidget = QtGui.QWidget() mainLayout.addWidget(buttonWidget) buttonLayout = QtGui.QHBoxLayout(buttonWidget) pLoadButton = QtGui.QPushButton("Load") pLoadButton.setFixedWidth(100) pOKButton = QtGui.QPushButton("OK") pOKButton.setFixedWidth(100) buttonLayout.addStretch() buttonLayout.addWidget(pLoadButton) buttonLayout.addWidget(pOKButton) def onClickedLoadButton(): nodeNames = easyCanvas.getSelectedNodes() attributeNames = easyCanvas.getAttributeNames(nodeNames[0]) global attrComboBox attrComboBox.clear() for attrName in attributeNames: fullAttrName = nodeNames[0] + '.' + attrName attrTypeMame = easyCanvas.getAttributeType(fullAttrName) if attrTypeMame == 'Color': attrComboBox.addItem(fullAttrName) def onMClickedOKButton(): global attrComboBox attrName = attrComboBox.currentText color = easyCanvas.getValue(attrName) global alphaSlider alpha = alphaSlider.value color.setAlpha(alpha) easyCanvas.setAttribute(attrName, color) def onSliderChanged(value): text = "Alpha(" + str(value) + ")" bottomLabel.setText(text) def onComboBoxIndexChanged(str): global attrComboBox attrName = attrComboBox.currentText color = easyCanvas.getValue(attrName) global alphaSlider alphaSlider.setValue(color.alpha()) # 连接信号和槽函数 pLoadButton.connect('clicked()', onClickedLoadButton) pOKButton.connect('clicked()', onMClickedOKButton) alphaSlider.connect('valueChanged(int)', onSliderChanged) attrComboBox.connect('currentIndexChanged(QString)', onComboBoxIndexChanged) mainWidget.resize(480, 180); mainWidget.show() ================================================ FILE: readme.md ================================================ 基于Qt QGraphicsView的简单作图软件
- 开发环境使用VS2015和Qt5.13,64位。 - 如果您使用VS的其他版本编译需要自行编译PythonQt 软件绿色版(旧版本)下载地址: 链接:https://pan.baidu.com/s/1r2zKmt4ID_7p0V8Fm7e7cQ 提取码:m6n1 视频演示地址:https://www.bilibili.com/video/BV18K411L7Ca/ **新版本 V2.0下载地址:** 链接:https://pan.baidu.com/s/1vEJ1T2txrGtSjlBNHip-tg 提取码:94ds **注意:** 1. 这里使用的是64位的FFmpeg库,如果编译的时候报错,请编译成64位的版本或者自行替换成32位的FFMpeg库。 2. **由于DLL库文件太大,会导致Github仓库克隆失败,可以使用如下链接下载DLL库** 链接:https://pan.baidu.com/s/1B9hN8fEKvBQN7X-HqBlLZw 提取码:ubuq 3. **如果Git仓库克隆失败,可以使用如下链接获取源码,后可直接更新代码。** 链接:https://pan.baidu.com/s/1qn-L1Vc3cFSUdf8Rx5YLiA 提取码:0rsf 4. 源码中未提供Python库环境,如果运行失败可以安装Python3.8。或者将绿色版的 **Lib** 目录拷贝到生成的程序的可执行文件所在目录。**(PythonQt::Init())** 程序闪退,可按此步骤解决。 如果使用VS2019+Qt5.15.1 可以直接下载这个版本 链接:https://pan.baidu.com/s/1B22HTJKUe_f3Qmv_P1Bgbg 提取码:uys6 基本数据组织类图如下: ![类图](./EasyCanves类图.jpg) # 1. 基本功能 1. 画布设置,可以修改画布的尺寸、颜色信息 2. 添加图元 - 画笔绘制 - 矩形 - 椭圆/圆 - 图片 - 自定义音频元素 - 文字 所有的元素可以自由改变尺寸、位置、旋转以及自己的其他属性信息。 3. 方案管理 - 新建空画布 - 保存方案 - 加载方案 - 保存为文件 4. Python命令 更多命令详见: [http://www.feijiblog.com/blog/qteasycanvasv2cmd](http://www.feijiblog.com/blog/qteasycanvasv2cmd) 5. 节点树同步显示节点信息 6. 撤销/重做功能 # 2. 模块介绍 - **AudioVideoCore** 音频解码和播放 - **Utils** 公共工具 - **CustomWidgets** 自定义基础Widget - **CustomControls** 自定义基本控件 - **NDNodeAttribute** 节点和属性定义 - **NodeAttributeControl** 属性控件 - **thirdLibs** 第三方库 - **EasyCanvas** Main App # 3. 关于我 作者: 不会飞的纸飞机 个人博客主页: http://www.feijiblog.com CSDN主页: https://blog.csdn.net/douzhq ================================================ FILE: thirdLibs/PythonQt/include/PythonQt.h ================================================ #ifndef _PYTHONQT_H #define _PYTHONQT_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQt.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtUtils.h" #include "PythonQtSystem.h" #include "PythonQtInstanceWrapper.h" #include "PythonQtClassWrapper.h" #include "PythonQtSlot.h" #include "PythonQtObjectPtr.h" #include "PythonQtStdIn.h" #include "PythonQtThreadSupport.h" #include #include #include #include #include #include #include #include class PythonQtClassInfo; class PythonQtPrivate; class PythonQtMethodInfo; class PythonQtSignalReceiver; class PythonQtImportFileInterface; class PythonQtCppWrapperFactory; class PythonQtForeignWrapperFactory; class PythonQtQFileImporter; typedef void PythonQtVoidPtrCB(void* object); typedef void PythonQtQObjectWrappedCB(QObject* object); typedef void PythonQtQObjectNoLongerWrappedCB(QObject* object); typedef void* PythonQtPolymorphicHandlerCB(const void *ptr, const char **class_name); typedef QString PythonQtQObjectMissingAttributeCB(QObject* object, const QString& attribute); typedef void PythonQtShellSetInstanceWrapperCB(void* object, PythonQtInstanceWrapper* wrapper); template void PythonQtSetInstanceWrapperOnShell(void* object, PythonQtInstanceWrapper* wrapper) { (reinterpret_cast(object))->_wrapper = wrapper; } //! Helper template that allows to pass the ownership of a C++ instance between C++ and Python //! (it is used as a slot return type or parameter type so that it can be detected by the PythonQt //! slot calling code). template class PythonQtPassOwnershipToCPP { public: //! Allow conversion from T to PythonQtPassOwnershipToCPP PythonQtPassOwnershipToCPP(const T& t):_t(t) {} //! Allow conversion from PythonQtPassOwnershipToCPP to T operator T() const { return _t; } //! Stored value. This is important so that it has the same memory layout //! as a pointer if T is a pointer type (which is the typical use case for this class). T _t; }; //! Helper template that allows to pass the ownership of a C++ instance between C++ and Python //! (it is used as a slot return type or parameter type so that it can be detected by the PythonQt //! slot calling code). template class PythonQtPassOwnershipToPython { public: //! Allow conversion from T to PythonQtPassOwnershipToPython PythonQtPassOwnershipToPython(const T& t):_t(t) {} //! Allow conversion from PythonQtPassOwnershipToPython to T operator T() const { return _t; } //! Stored value. This is important so that it has the same memory layout //! as a pointer if T is a pointer type (which is the typical use case for this class). T _t; }; //! Helper template that allows to pass the ownership of a C++ instance between C++ and Python //! (it is used as a slot return type or parameter type so that it can be detected by the PythonQt //! slot calling code). template class PythonQtNewOwnerOfThis { public: //! Allow conversion from T to PythonQtNewOwnerOfThis PythonQtNewOwnerOfThis(const T& t):_t(t) {} //! Allow conversion from PythonQtNewOwnerOfThis to T operator T() const { return _t; } //! Stored value. This is important so that it has the same memory layout //! as a pointer if T is a pointer type (which is the typical use case for this class). T _t; }; //! returns the offset that needs to be added to upcast an object of type T1 to T2 template int PythonQtUpcastingOffset() { return ((reinterpret_cast(static_cast(reinterpret_cast(0x100)))) - (reinterpret_cast(reinterpret_cast(0x100)))); } //! callback to create a QObject lazily typedef QObject* PythonQtQObjectCreatorFunctionCB(); //! helper template to create a derived QObject class template QObject* PythonQtCreateObject() { return new T(); }; //! Helper define to convert from QString to Python C-API #ifdef PY3K #define QStringToPythonConstCharPointer(arg) ((arg).toUtf8().constData()) #define QStringToPythonCharPointer(arg) ((arg).toUtf8().data()) #define QStringToPythonEncoding(arg) ((arg).toUtf8()) #else #define QStringToPythonConstCharPointer(arg) ((arg).toLatin1().constData()) #define QStringToPythonCharPointer(arg) ((arg).toLatin1().data()) #define QStringToPythonEncoding(arg) ((arg).toLatin1()) #endif //! The main interface to the Python Qt binding, realized as a singleton /*! Use PythonQt::init() to initialize the singleton and PythonQt::self() to access it. While there can be only one PythonQt instance, you can have any number of Python context to do scripting in. One possibility is to use createModuleFromFile(), createModuleFromScript() or createUniqueModule() to get a context that is separated from the other contexts. Alternatively you can use Python dicts as contexts for script evaluation, but you will need to populate the dict with the __builtins__ instance to have all Pythons available when running code in the scope of a dict. */ class PYTHONQT_EXPORT PythonQt : public QObject { Q_OBJECT public: //! flags that can be passed to PythonQt::init() enum InitFlags { RedirectStdOut = 1, //!<< sets if the std out/err is redirected to pythonStdOut() and pythonStdErr() signals IgnoreSiteModule = 2, //!<< sets if Python should ignore the site module ExternalHelp = 4, //!<< sets if help() calls on PythonQt modules are forwarded to the pythonHelpRequest() signal PythonAlreadyInitialized = 8 //!<< sets that PythonQt should not can PyInitialize, since it is already done }; //! flags that tell PythonQt which operators to expect on the registered type enum TypeSlots { Type_Add = 1, Type_Subtract = 1 << 1, Type_Multiply = 1 << 2, Type_Divide = 1 << 3, Type_Mod = 1 << 4, Type_And = 1 << 5, Type_Or = 1 << 6, Type_Xor = 1 << 7, Type_LShift = 1 << 8, Type_RShift = 1 << 9, Type_InplaceAdd = 1 << 10, Type_InplaceSubtract = 1 << 11, Type_InplaceMultiply = 1 << 12, Type_InplaceDivide = 1 << 13, Type_InplaceMod = 1 << 14, Type_InplaceAnd = 1 << 15, Type_InplaceOr = 1 << 16, Type_InplaceXor = 1 << 17, Type_InplaceLShift = 1 << 18, Type_InplaceRShift = 1 << 19, Type_Length = 1 << 20, Type_MappingSetItem = 1 << 21, Type_MappingGetItem = 1 << 22, Type_Invert = 1 << 29, Type_RichCompare = 1 << 30, Type_NonZero = 1 << 31, }; //! enum for profiling callback enum ProfilingCallbackState { Enter = 1, Leave = 2 }; //! callback for profiling. className and methodName are only passed when state == Enter, otherwise //! they are NULL. typedef void ProfilingCB(ProfilingCallbackState state, const char* className, const char* methodName, PyObject* args); //--------------------------------------------------------------------------- //! \name Singleton Initialization //@{ //! initialize the python qt binding (flags are a or combination of PythonQt::InitFlags), if \c pythonQtModuleName is given //! it defines the name of the python module that PythonQt will add, otherwise "PythonQt" is used. //! This can be used to e.g. pass in PySide or PyQt4 to make it more compatible. static void init(int flags = IgnoreSiteModule | RedirectStdOut, const QByteArray& pythonQtModuleName = QByteArray()); //! cleanup of the singleton static void cleanup(); //! get the singleton instance static PythonQt* self(); //@} //! defines the object types for introspection enum ObjectType { Class, Function, Variable, Module, Anything, CallOverloads }; //--------------------------------------------------------------------------- //! \name Standard input handling //@{ //! Overwrite default handling of stdin using a custom callback. It internally backup //! the original 'sys.stdin' into 'sys.pythonqt_original_stdin' void setRedirectStdInCallback(PythonQtInputChangedCB* callback, void * callbackData = 0); //! Enable or disable stdin custom callback. It resets 'sys.stdin' using either 'sys.pythonqt_stdin' //! or 'sys.pythonqt_original_stdin' void setRedirectStdInCallbackEnabled(bool enabled); //@} //--------------------------------------------------------------------------- //! \name Modules //@{ //! get the __main__ module of python PythonQtObjectPtr getMainModule(); //! import the given module and return a reference to it (useful to import e.g. "sys" and call something on it) //! If a module is already imported, this returns the already imported module. PythonQtObjectPtr importModule(const QString& name); //! creates the new module \c name and evaluates the given file in the context of that module //! If the \c script is empty, the module contains no initial code. You can use evalScript/evalCode to add code //! to a module later on. //! The user needs to make sure that the \c name is unique in the python module dictionary. PythonQtObjectPtr createModuleFromFile(const QString& name, const QString& filename); //! creates the new module \c name and evaluates the given script in the context of that module. //! If the \c script is empty, the module contains no initial code. You can use evalScript/evalCode to add code //! to a module later on. //! The user needs to make sure that the \c name is unique in the python module dictionary. PythonQtObjectPtr createModuleFromScript(const QString& name, const QString& script = QString()); //! create a uniquely named module, you can use evalFile or evalScript to populate the module with //! script code PythonQtObjectPtr createUniqueModule(); //@} //--------------------------------------------------------------------------- //! \name Importing/Paths //@{ //! overwrite the python sys path (call this directly after PythonQt::init() if you want to change the std python sys path) void overwriteSysPath(const QStringList& paths); //! prepend a path to sys.path to allow importing from it void addSysPath(const QString& path); //! sets the __path__ list of a module to the given list (important for local imports) void setModuleImportPath(PyObject* module, const QStringList& paths); //@} //--------------------------------------------------------------------------- //! \name Registering Classes //@{ //! registers a QObject derived class to PythonQt (this is implicitly called by addObject as well) /* Since Qt4 does not offer a way to detect if a given classname is derived from QObject and thus has a QMetaObject, you MUST register all your QObject derived classes here when you want them to be detected in signal and slot calls */ void registerClass(const QMetaObject* metaobject, const char* package = NULL, PythonQtQObjectCreatorFunctionCB* wrapperCreator = NULL, PythonQtShellSetInstanceWrapperCB* shell = NULL); //! add a wrapper object for the given QMetaType typeName, also does an addClassDecorators() to add constructors for variants //! (ownership of wrapper is passed to PythonQt) /*! Make sure that you have done a qRegisterMetaType first, if typeName is a user type! This will add a wrapper object that is used to make calls to the given classname \c typeName. All slots that take a pointer to typeName as the first argument will be callable from Python on a variant object that contains such a type. */ void registerCPPClass(const char* typeName, const char* parentTypeName = NULL, const char* package = NULL, PythonQtQObjectCreatorFunctionCB* wrapperCreator = NULL, PythonQtShellSetInstanceWrapperCB* shell = NULL); //! as an alternative to registerClass, you can tell PythonQt the names of QObject derived classes //! and it will register the classes when it first sees a pointer to such a derived class void registerQObjectClassNames(const QStringList& names); //! add a parent class relation to the \c given typeName, the upcastingOffset is needed for multiple inheritance //! and can be calculated using PythonQtUpcastingOffset(), which also verifies that //! type is really derived from parentType. //! Returns false if the typeName was not yet registered. bool addParentClass(const char* typeName, const char* parentTypeName, int upcastingOffset=0); //! add a handler for polymorphic downcasting void addPolymorphicHandler(const char* typeName, PythonQtPolymorphicHandlerCB* cb); //@} //--------------------------------------------------------------------------- //! \name Script Parsing and Evaluation //@{ //! parses the given file (using PythonQt's own import mechanism) and returns the python code object, this can then be used to call evalCode() PythonQtObjectPtr parseFile(const QString& filename); //! Parses the given file and returns the python code object, this can then be used to call evalCode() //! It uses Python's importlib machinery to load the file's code and supports source and sourceless loading //! and generation of cache files. //! This method is PY3K only! PythonQtObjectPtr parseFileWithPythonLoaders(const QString& filename); //! evaluates the given code and returns the result value (use Py_Compile etc. to create pycode from string) //! If pycode is NULL, a python error is printed. QVariant evalCode(PyObject* object, PyObject* pycode); //! evaluates the given script code and returns the result value QVariant evalScript(PyObject* object, const QString& script, int start = Py_file_input); //! evaluates the given script code in context of given globals and locals and returns the result value QVariant evalScript(const QString& script, PyObject* globals, PyObject* locals, int start); //! evaluates the given script code from file void evalFile(PyObject* object, const QString& filename); //@} //--------------------------------------------------------------------------- //! \name Signal Handlers //@{ //! add a signal handler to the given \c signal of \c obj and connect it to a callable \c objectname in module bool addSignalHandler(QObject* obj, const char* signal, PyObject* module, const QString& objectname); //! remove a signal handler from the given \c signal of \c obj bool removeSignalHandler(QObject* obj, const char* signal, PyObject* module, const QString& objectname); //! add a signal handler to the given \c signal of \c obj and connect it to a callable \c receiver bool addSignalHandler(QObject* obj, const char* signal, PyObject* receiver); //! remove a signal handler from the given \c signal of \c obj bool removeSignalHandler(QObject* obj, const char* signal, PyObject* receiver); //! globally removes all signal handlers (connections between QObjects and Python). void removeSignalHandlers(); //@} //--------------------------------------------------------------------------- //! \name Variable access //@{ //! add the given \c qObject to the python \c object as a variable with \c name (it can be removed via clearVariable) void addObject(PyObject* object, const QString& name, QObject* qObject); //! add the given variable to the object void addVariable(PyObject* object, const QString& name, const QVariant& v); //! remove the given variable void removeVariable(PyObject* module, const QString& name); //! get the variable with the \c name of the \c object, returns an invalid QVariant on error QVariant getVariable(PyObject* object, const QString& name); //! get the variable with the \c name of the \c object as QVariant of type PythonQtObjectPtr, returns an invalid QVariant on error QVariant getNativeVariable(PyObject* object, const QString& name); //! read vars etc. in scope of an \c object, optional looking inside of an object \c objectname QStringList introspection(PyObject* object, const QString& objectname, ObjectType type); //! read vars etc. in scope of the given \c object QStringList introspectObject(PyObject* object, ObjectType type); //! read vars etc. in scope of the type object called \c typename. First the typename //! of the form module.type is split into module and type. Then the module is looked up //! in sys.modules. If the module or type is not found there, then the type is looked up in //! the __builtin__ module. QStringList introspectType(const QString& typeName, ObjectType type); //! returns the found callable object or NULL //! @return new reference PythonQtObjectPtr lookupCallable(PyObject* object, const QString& name); //! returns the return type of the method of a wrapped c++ object referenced by \c objectname QString getReturnTypeOfWrappedMethod(PyObject* module, const QString& objectname); //! returns the return type of the method \c methodName of a wrapped c++ type referenced by \c typeName QString getReturnTypeOfWrappedMethod(const QString& typeName, const QString& methodName); //@} //--------------------------------------------------------------------------- //! \name Calling Python Objects //@{ //! call the given python \c callable in the scope of object, returns the result converted to a QVariant QVariant call(PyObject* object, const QString& callable, const QVariantList& args = QVariantList(), const QVariantMap& kwargs = QVariantMap()); //! call the given python object, returns the result converted to a QVariant QVariant call(PyObject* callable, const QVariantList& args = QVariantList(), const QVariantMap& kwargs = QVariantMap()); //! call the given python object, returns the result as new PyObject PyObject* callAndReturnPyObject(PyObject* callable, const QVariantList& args = QVariantList(), const QVariantMap& kwargs = QVariantMap()); //@} //--------------------------------------------------------------------------- //! \name Decorations, Constructors, Wrappers... //@{ //! add an object whose slots will be used as decorator slots for //! other QObjects or CPP classes. The slots need to follow the //! convention that the first argument is a pointer to the wrapped object. //! (ownership is passed to PythonQt) /*! Example: A slot with the signature \code bool doSomething(QWidget* w, int a) \endcode will extend QWidget instances (and derived classes) with a "bool doSomething(int a)" slot that will be called with the concrete instance as first argument. So in Python you can now e.g. call \code someWidget.doSomething(12) \endcode without QWidget really having this method. This allows to easily make normal methods of Qt classes callable by forwarding them with such decorator slots or to make CPP classes (which are not derived from QObject) callable from Python. */ void addInstanceDecorators(QObject* o); //! add an object whose slots will be used as decorator slots for //! class objects (ownership is passed to PythonQt) /*! The slots need to follow the following convention: - SomeClass* new_SomeClass(...) - QVariant new_SomeClass(...) - void delete_SomeClass(SomeClass*) - ... static_SomeClass_someName(...) This will add: - a constructor - a constructor which generates a QVariant - a destructor (only useful for CPP objects) - a static decorator slot which will be available on the MetaObject (visible in PythonQt module) */ void addClassDecorators(QObject* o); //! this will add the object both as class and instance decorator (ownership is passed to PythonQt) void addDecorators(QObject* o); //! add the given factory to PythonQt (ownership stays with caller) void addWrapperFactory(PythonQtCppWrapperFactory* factory); //! add the given factory to PythonQt (ownership stays with caller) void addWrapperFactory(PythonQtForeignWrapperFactory* factory); //! remove the wrapper factory void removeWrapperFactory(PythonQtCppWrapperFactory* factory); //! remove the wrapper factory void removeWrapperFactory(PythonQtForeignWrapperFactory* factory); //@} //--------------------------------------------------------------------------- //! \name Custom Importer //@{ //! replace the internal import implementation and use the supplied interface to load files (both py and pyc files) //! (this method should be called directly after initialization of init() and before calling overwriteSysPath(). //! On the first call to this method, it will install a generic PythonQt importer in Pythons "path_hooks". //! This is not reversible, so even setting setImporter(NULL) afterwards will //! keep the custom PythonQt importer with a QFile default import interface. //! Subsequent python import calls will make use of the passed importInterface //! which forwards all import calls to the given \c importInterface. //! Passing NULL will install a default QFile importer. //! (\c importInterface ownership stays with caller) void setImporter(PythonQtImportFileInterface* importInterface); //! this installs the default QFile importer (which effectively does a setImporter(NULL)) //! (without calling setImporter or installDefaultImporter at least once, the default python import //! mechanism is in place) //! the default importer allows to import files from anywhere QFile can read from, //! including the Qt resource system using ":". Keep in mind that you need to extend //! "sys.path" with ":" to be able to import from the Qt resources. void installDefaultImporter() { setImporter(NULL); } //! set paths that the importer should ignore void setImporterIgnorePaths(const QStringList& paths); //! get paths that the importer should ignore const QStringList& getImporterIgnorePaths(); //! get access to the file importer (if set) static PythonQtImportFileInterface* importInterface(); //@} //--------------------------------------------------------------------------- //! \name Other Stuff //@{ //! get access to internal data (should not be used on the public API, but is used by some C functions) static PythonQtPrivate* priv() { return _self->_p; } //! clear all NotFound entries on all class infos, to ensure that //! newly loaded wrappers can add methods even when the object was wrapped by PythonQt before the wrapper was loaded void clearNotFoundCachedMembers(); //! handle a python error, call this when a python function fails. If no error occurred, it returns false. //! The error is currently just output to the python stderr, future version might implement better trace printing bool handleError(bool printStack = true); //! return \a true if \a handleError() has been called and an error occurred. bool hadError()const; //! reset error flag. After calling this, hadError() will return false. //! \sa hadError() void clearError(); //! if set to true, the systemExitExceptionRaised signal will be emitted if exception SystemExit is caught //! \sa handleError() void setSystemExitExceptionHandlerEnabled(bool value); //! return \a true if SystemExit exception is handled by PythonQt //! \sa setSystemExitExceptionHandlerEnabled() bool systemExitExceptionHandlerEnabled() const; //! set a callback that is called when a QObject with parent == NULL is wrapped by PythonQt void setQObjectWrappedCallback(PythonQtQObjectWrappedCB* cb); //! set a callback that is called when a QObject with parent == NULL is no longer wrapped by PythonQt void setQObjectNoLongerWrappedCallback(PythonQtQObjectNoLongerWrappedCB* cb); //! call the callback if it is set static void qObjectNoLongerWrappedCB(QObject* o); //! set a callback that is called when a QObject does not have a specific attribute. void setQObjectMissingAttributeCallback(PythonQtQObjectMissingAttributeCB* cb); //! call the callback if it is set static QString qObjectMissingAttributeCallback(QObject* o, const QString& attribute); //! called by internal help methods PyObject* helpCalled(PythonQtClassInfo* info); //! returns the found object or NULL //! @return new reference PythonQtObjectPtr lookupObject(PyObject* module, const QString& name); //! sets a callback that is called before and after function calls for profiling void setProfilingCallback(ProfilingCB* cb); //! Enable GIL and thread state handling (turned off by default). //! If you want to use Python threading, you have to call this //! with true early in your main thread, before you launch //! any threads in Python. It can be called before or after //! PythonQt::init(). static void setEnableThreadSupport(bool flag); //@} Q_SIGNALS: //! emitted when python outputs something to stdout (and redirection is turned on) void pythonStdOut(const QString& str); //! emitted when python outputs something to stderr (and redirection is turned on) void pythonStdErr(const QString& str); //! emitted when help() is called on a PythonQt object and \c ExternalHelp is enabled void pythonHelpRequest(const QByteArray& cppClassName); //! emitted when both custom SystemExit exception handler is enabled and a SystemExit //! exception is raised. //! \sa setSystemExitExceptionHandlerEnabled(bool) void systemExitExceptionRaised(int exitCode); private: void initPythonQtModule(bool redirectStdOut, const QByteArray& pythonQtModuleName); QString getReturnTypeOfWrappedMethodHelper(const PythonQtObjectPtr& variableObject, const QString& methodName, const QString& context); PyObject* getObjectByType(const QString& typeName); //! callback for stdout redirection, emits pythonStdOut signal static void stdOutRedirectCB(const QString& str); //! callback for stderr redirection, emits pythonStdErr signal static void stdErrRedirectCB(const QString& str); //! get (and create if not available) the signal receiver of that QObject, signal receiver is made child of the passed \c obj PythonQtSignalReceiver* getSignalReceiver(QObject* obj); PythonQt(int flags, const QByteArray& pythonQtModuleName); ~PythonQt(); static PythonQt* _self; static int _uniqueModuleCount; PythonQtPrivate* _p; }; class PythonQtDebugAPI; //! internal PythonQt details class PYTHONQT_EXPORT PythonQtPrivate : public QObject { Q_OBJECT public: PythonQtPrivate(); ~PythonQtPrivate(); enum DecoratorTypes { StaticDecorator = 1, ConstructorDecorator = 2, DestructorDecorator = 4, InstanceDecorator = 8, AllDecorators = 0xffff }; //! get the suffixes that are used for shared libraries const QStringList& sharedLibrarySuffixes() { return _sharedLibrarySuffixes; } //! returns if the id is the id for PythonQtObjectPtr bool isPythonQtObjectPtrMetaId(int id) { return _PythonQtObjectPtr_metaId == id; } //! returns if the id is the id for PythonQtSafeObjectPtr bool isPythonQtSafeObjectPtrMetaId(int id) { return _PythonQtSafeObjectPtr_metaId == id; } //! returns if the id is either PythonQtObjectPtr or PythonQtSafeObjectPtr bool isPythonQtAnyObjectPtrMetaId(int id) { return _PythonQtObjectPtr_metaId == id || _PythonQtSafeObjectPtr_metaId == id; } //! add the wrapper pointer (for reuse if the same obj appears while wrapper still exists) void addWrapperPointer(void* obj, PythonQtInstanceWrapper* wrapper); //! remove the wrapper ptr again void removeWrapperPointer(void* obj); //! called by destructor of shells to allow invalidation of the Python wrapper void shellClassDeleted(void* shellClass); //! try to unwrap the given object to a C++ pointer using the foreign wrapper factories void* unwrapForeignWrapper(const QByteArray& classname, PyObject* obj); //! add parent class relation bool addParentClass(const char* typeName, const char* parentTypeName, int upcastingOffset); //! add a handler for polymorphic downcasting void addPolymorphicHandler(const char* typeName, PythonQtPolymorphicHandlerCB* cb); //! lookup existing classinfo and return new if not yet present PythonQtClassInfo* lookupClassInfoAndCreateIfNotPresent(const char* typeName); //! called when a signal emitting QObject is destroyed to remove the signal handler from the hash map void removeSignalEmitter(QObject* obj); //! wrap the given QObject into a Python object (or return existing wrapper!) PyObject* wrapQObject(QObject* obj); //! wrap the given ptr into a Python object (or return existing wrapper!) if there is a known QObject of that name or a known wrapper in the factory. //! If passOwnership == true, the ownership is passed to PythonQt, so the object will be deleted by PythonQt when the Python wrapper //! goes away. PyObject* wrapPtr(void* ptr, const QByteArray& name, bool passOwnership = false); //! create a read-only buffer object from the given memory static PyObject* wrapMemoryAsBuffer(const void* data, Py_ssize_t size); //! create a read-write buffer object from the given memory static PyObject* wrapMemoryAsBuffer(void* data, Py_ssize_t size); //! registers a QObject derived class to PythonQt (this is implicitly called by addObject as well) /* Since Qt4 does not offer a way to detect if a given classname is derived from QObject and thus has a QMetaObject, you MUST register all your QObject derived classes here when you want them to be detected in signal and slot calls */ void registerClass(const QMetaObject* metaobject, const char* package = NULL, PythonQtQObjectCreatorFunctionCB* wrapperCreator = NULL, PythonQtShellSetInstanceWrapperCB* shell = NULL, PyObject* module = NULL, int typeSlots = 0); //! add a wrapper object for the given QMetaType typeName, also does an addClassDecorators() to add constructors for variants //! (ownership of wrapper is passed to PythonQt) /*! Make sure that you have done a qRegisterMetaType first, if typeName is a user type! This will add a wrapper object that is used to make calls to the given classname \c typeName. All slots that take a pointer to typeName as the first argument will be callable from Python on a variant object that contains such a type. */ void registerCPPClass(const char* typeName, const char* parentTypeName = NULL, const char* package = NULL, PythonQtQObjectCreatorFunctionCB* wrapperCreator = NULL, PythonQtShellSetInstanceWrapperCB* shell = NULL, PyObject* module = NULL, int typeSlots = 0); //! as an alternative to registerClass, you can tell PythonQt the names of QObject derived classes //! and it will register the classes when it first sees a pointer to such a derived class void registerQObjectClassNames(const QStringList& names); //! add a decorator object void addDecorators(QObject* o, int decoTypes); //! helper method that creates a PythonQtClassWrapper object (returns a new reference) PythonQtClassWrapper* createNewPythonQtClassWrapper(PythonQtClassInfo* info, PyObject* module, const QByteArray& pythonClassName); //! create a new instance of the given enum type with given value (returns a new reference) static PyObject* createEnumValueInstance(PyObject* enumType, unsigned int enumValue); //! helper that creates a new int derived class that represents the enum of the given name (returns a new reference) static PyObject* createNewPythonQtEnumWrapper(const char* enumName, PyObject* parentObject); //! helper method that creates a PythonQtInstanceWrapper object and registers it in the object map PythonQtInstanceWrapper* createNewPythonQtInstanceWrapper(QObject* obj, PythonQtClassInfo* info, void* wrappedPtr = NULL); //! get the class info for a meta object (if available) PythonQtClassInfo* getClassInfo(const QMetaObject* meta); //! get the class info for a meta object (if available) PythonQtClassInfo* getClassInfo(const QByteArray& className); //! register a class name that causes lazy loading of the moduleToImport when //! PythonQt encounters the type void registerLazyClass(const QByteArray& name, const QByteArray& moduleToImport); //! creates the new module from the given pycode PythonQtObjectPtr createModule(const QString& name, PyObject* pycode); //! get the current class info (for the next PythonQtClassWrapper that is created) and reset it to NULL again PythonQtClassInfo* currentClassInfoForClassWrapperCreation(); //! the dummy tuple (which is empty and may be used to detected that a wrapper is called from internal wrapper creation static PyObject* dummyTuple(); //! called by virtual overloads when a python return value can not be converted to the required Qt type void handleVirtualOverloadReturnError(const char* signature, const PythonQtMethodInfo* methodInfo, PyObject* result); //! get access to the PythonQt module PythonQtObjectPtr pythonQtModule() const { return _pythonQtModule; } //! returns the profiling callback, which may be NULL PythonQt::ProfilingCB* profilingCB() const { return _profilingCB; } //! determines the signature of the given callable object (similar as pydoc) QString getSignature(PyObject* object); //! returns true if the object is a method descriptor (same as inspect.ismethoddescriptor() in inspect.py) bool isMethodDescriptor(PyObject* object) const; //! get the dynamic meta object for the given wrapper. It will contain the signals/slots that have been added in Python const QMetaObject* getDynamicMetaObject(PythonQtInstanceWrapper* wrapper, const QMetaObject* prototypeMetaObject); //! recursively creates the dynamic meta object chain down to the Qt class wrapper. const QMetaObject* setupDynamicMetaObjectChain(PythonQtClassWrapper* type, const QMetaObject* prototypeMetaObject); //! builds and returns the dynamic meta object for the given type, derived from prototypeMetaObject. const QMetaObject* buildDynamicMetaObject(PythonQtClassWrapper* type, const QMetaObject* prototypeMetaObject); //! redirected from shell classes, tries to call the given meta call on the Python wrapper. int handleMetaCall(QObject* object, PythonQtInstanceWrapper* wrapper, QMetaObject::Call call, int id, void** args); //! calls the given method on Python function with same name. void callMethodInPython(QMetaMethod &method, PythonQtInstanceWrapper* wrapper, void** args); private: //! Setup the shared library suffixes by getting them from the "imp" module. void setupSharedLibrarySuffixes(); //! create a new pythonqt class wrapper and place it in the pythonqt module void createPythonQtClassWrapper(PythonQtClassInfo* info, const char* package, PyObject* module = NULL); //! get/create new package module (the returned object is a borrowed reference) PyObject* packageByName(const char* name); //! get the wrapper for a given pointer (and remove a wrapper of an already destroyed qobject) PythonQtInstanceWrapper* findWrapperAndRemoveUnused(void* obj); //! stores pointer to PyObject mapping of wrapped QObjects AND C++ objects QHash _wrappedObjects; //! stores the meta info of known Qt classes QHash _knownClassInfos; //! names of qobject derived classes that can be casted to qobject savely QHash _knownQObjectClassNames; //! lazy classes that cause PythonQt to trigger an import if they are encountered. QHash _knownLazyClasses; //! stores signal receivers for QObjects QHash _signalReceivers; //! the PythonQt python module PythonQtObjectPtr _pythonQtModule; //! the name of the PythonQt python module QByteArray _pythonQtModuleName; //! the importer interface (if set) PythonQtImportFileInterface* _importInterface; //! the default importer PythonQtQFileImporter* _defaultImporter; PythonQtQObjectNoLongerWrappedCB* _noLongerWrappedCB; PythonQtQObjectWrappedCB* _wrappedCB; PythonQtQObjectMissingAttributeCB* _qObjectMissingAttribCB; QStringList _importIgnorePaths; QStringList _sharedLibrarySuffixes; PythonQtObjectPtr _pySourceFileLoader; PythonQtObjectPtr _pySourcelessFileLoader; //! the cpp object wrapper factories QList _cppWrapperFactories; QList _foreignWrapperFactories; QHash _packages; PythonQtClassInfo* _currentClassInfoForClassWrapperCreation; PythonQt::ProfilingCB* _profilingCB; PythonQtDebugAPI* _debugAPI; int _initFlags; int _PythonQtObjectPtr_metaId; int _PythonQtSafeObjectPtr_metaId; bool _hadError; bool _systemExitExceptionHandlerEnabled; friend class PythonQt; }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtBoolResult.h ================================================ #ifndef _PYTHONQTBOOLRESULT_H #define _PYTHONQTBOOLRESULT_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtBoolResultt.h // \author Florian Link // \date 2014-09 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include "structmember.h" extern PYTHONQT_EXPORT PyTypeObject PythonQtBoolResult_Type; #define PythonQtBoolResult_Check(op) (Py_TYPE(op) == &PythonQtBoolResult_Type) //! defines a python object that stores a single bool typedef struct { PyObject_HEAD bool _value; } PythonQtBoolResultObject; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtClassInfo.h ================================================ #ifndef _PYTHONQTCLASSINFO_H #define _PYTHONQTCLASSINFO_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ #include "PythonQtPythonInclude.h" #include "PythonQt.h" #include #include #include #include #include class PythonQtSlotInfo; class PythonQtClassInfo; struct PythonQtDynamicClassInfo { PythonQtDynamicClassInfo() { _dynamicMetaObject = NULL; _classInfo = NULL; } ~PythonQtDynamicClassInfo(); const QMetaObject* _dynamicMetaObject; PythonQtClassInfo* _classInfo; }; struct PythonQtMemberInfo { enum Type { Invalid, Slot, Signal, EnumValue, EnumWrapper, Property, NestedClass, NotFound }; PythonQtMemberInfo():_type(Invalid),_slot(NULL),_pythonType(NULL),_enumValue(0) { } PythonQtMemberInfo(PythonQtSlotInfo* info); PythonQtMemberInfo(const PythonQtObjectPtr& enumValue); PythonQtMemberInfo(const QMetaProperty& prop); Type _type; // TODO: this could be a union... PythonQtSlotInfo* _slot; PyObject* _pythonType; PythonQtObjectPtr _enumValue; QMetaProperty _property; }; //! a class that stores all required information about a Qt object (and an optional associated C++ class name) /*! for fast lookup of slots when calling the object from Python */ class PYTHONQT_EXPORT PythonQtClassInfo { public: PythonQtClassInfo(); ~PythonQtClassInfo(); //! store information about parent classes struct ParentClassInfo { ParentClassInfo(PythonQtClassInfo* parent, int upcastingOffset=0):_parent(parent),_upcastingOffset(upcastingOffset) {}; PythonQtClassInfo* _parent; int _upcastingOffset; }; //! setup as a QObject, taking the meta object as meta information about the QObject void setupQObject(const QMetaObject* meta); //! setup as a CPP (non-QObject), taking the classname void setupCPPObject(const QByteArray& classname); //! set the type capabilities void setTypeSlots(int typeSlots) { _typeSlots = typeSlots; } //! get the type capabilities int typeSlots() const { return _typeSlots; } //! get the Python method definition for a given slot name (without return type and signature) PythonQtMemberInfo member(const char* member); //! get access to the constructor slot (which may be overloaded if there are multiple constructors) PythonQtSlotInfo* constructors(); //! get access to the destructor slot PythonQtSlotInfo* destructor(); //! add a constructor, ownership is passed to classinfo void addConstructor(PythonQtSlotInfo* info); //! set a destructor, ownership is passed to classinfo void setDestructor(PythonQtSlotInfo* info); //! add a decorator slot, ownership is passed to classinfo void addDecoratorSlot(PythonQtSlotInfo* info); //! add a nested class, so that it can be shown as outer class member void addNestedClass(PythonQtClassInfo* info); //! get the classname (either of the QObject or of the wrapped CPP object) const QByteArray& className() const; //! get the unscoped classname (without ParentClass::) for nested classes QByteArray unscopedClassName() const; //! returns if the QObject bool isQObject() { return _isQObject; } //! returns if the class is a CPP wrapper bool isCPPWrapper() { return !_isQObject; } //! get the meta object const QMetaObject* metaObject() { return _meta; } //! set the meta object, this will reset the caching void setMetaObject(const QMetaObject* meta); //! returns if this class inherits from the given classname bool inherits(const char* classname); //! returns if this class inherits from the given classinfo bool inherits(PythonQtClassInfo* info); //! casts the given \c ptr to an object of type \c classname, returns the new pointer //! which might be different to \c ptr due to C++ multiple inheritance //! (if the cast is not possible or if ptr is NULL, NULL is returned) void* castTo(void* ptr, const char* classname); //! get help string for the metaobject QString help(); //! get list of all properties (on QObjects only, otherwise the list is empty) QStringList propertyList(); //! get list of all members (excluding properties, which can be listed with propertyList()) QStringList memberList(); //! get the meta type id of this class (only valid for isCPPWrapper() == true) int metaTypeId() { return _metaTypeId; } //! set an additional decorator provider that offers additional decorator slots for this class void setDecoratorProvider(PythonQtQObjectCreatorFunctionCB* cb); //! get the decorator qobject instance QObject* decorator(); //! add the parent class info of a CPP object void addParentClass(const ParentClassInfo& info) { _parentClasses.append(info); } //! set the associated PythonQtClassWrapper (which handles instance creation of this type) void setPythonQtClassWrapper(PyObject* obj) { _pythonQtClassWrapper = obj; } //! get the associated PythonQtClassWrapper (which handles instance creation of this type) PyObject* pythonQtClassWrapper() { return _pythonQtClassWrapper; } //! set the shell set instance wrapper cb void setShellSetInstanceWrapperCB(PythonQtShellSetInstanceWrapperCB* cb) { _shellSetInstanceWrapperCB = cb; } //! get the shell set instance wrapper cb PythonQtShellSetInstanceWrapperCB* shellSetInstanceWrapperCB() { return _shellSetInstanceWrapperCB; } //! add a handler for polymorphic downcasting void addPolymorphicHandler(PythonQtPolymorphicHandlerCB* cb) { _polymorphicHandlers.append(cb); } //! cast the pointer down in the class hierarchy if a polymorphic handler allows to do that void* castDownIfPossible(void* ptr, PythonQtClassInfo** resultClassInfo); //! returns if the localScope has an enum of that type name or if the enum contains a :: scope, if that class contails the enum static PyObject* findEnumWrapper(const QByteArray& name, PythonQtClassInfo* localScope, bool* isLocalEnum = NULL); //! clear all members that where cached as "NotFound" void clearNotFoundCachedMembers(); //! get nested classes const QList& nestedClasses() { return _nestedClasses; } //! Create a copy of the given C++ object (which is known to be of a derived class), wrapped by Python and owned by PythonQt. //! This will downcast if possible and return a copy of the down casted object. //! This either requires a copy constructor on the class or it needs to be registered //! as a meta type. PyObject* copyObject(void* cppObject); //! Get the copy constructor for this class PythonQtSlotInfo* getCopyConstructor(); //! Sets reference counting callbacks for this class and all its subclasses void setReferenceCounting(PythonQtVoidPtrCB* refCB, PythonQtVoidPtrCB* unrefCB); //! Returns the ref counting CB, if there is any PythonQtVoidPtrCB* referenceCountingRefCB(); //! Returns the unref counting CB, if there is any PythonQtVoidPtrCB* referenceCountingUnrefCB(); //! Returns the Python type object for a given property. //! (the returned object does not get an extra reference count) PyObject* getPythonTypeForProperty(const QString& name); //! Returns the class info for given property, if available. PythonQtClassInfo* getClassInfoForProperty( const QString& name ); //! Returns if the class supports rich compare. This tests for //! __eq__, __ne__, __lt__, __le__, __gt__, __ge__ slots and if //! any of the slots is present it returns true and modifies the //! _typeSlots with Type_RichCompare. The result is cached internally. bool supportsRichCompare(); private: void updateRefCountingCBs(); void createEnumWrappers(const QObject* decoratorProvider); void createEnumWrappers(const QMetaObject* meta); PyObject* findEnumWrapper(const char* name); //! clear all cached members void clearCachedMembers(); void* recursiveCastDownIfPossible(void* ptr, const char** resultClassName); PythonQtSlotInfo* findDecoratorSlotsFromDecoratorProvider(const char* memberName, PythonQtSlotInfo* inputInfo, bool &found, QHash& memberCache, int upcastingOffset); void listDecoratorSlotsFromDecoratorProvider(QStringList& list, bool metaOnly); PythonQtSlotInfo* recursiveFindDecoratorSlotsFromDecoratorProvider(const char* memberName, PythonQtSlotInfo* inputInfo, bool &found, QHash& memberCache, int upcastingOffset); void recursiveCollectClassInfos(QList& classInfoObjects); void recursiveCollectDecoratorObjects(QList& decoratorObjects); bool lookForPropertyAndCache(const char* memberName); bool lookForMethodAndCache(const char* memberName); bool lookForEnumAndCache(const QMetaObject* m, const char* memberName); PythonQtSlotInfo* findDecoratorSlots(const char* memberName, PythonQtSlotInfo* tail, bool &found, QHash& memberCache, int upcastingOffset); int findCharOffset(const char* sigStart, char someChar); QHash _cachedMembers; PythonQtSlotInfo* _constructors; PythonQtSlotInfo* _destructor; PythonQtVoidPtrCB* _refCallback; PythonQtVoidPtrCB* _unrefCallback; QList _decoratorSlots; QList _enumWrappers; const QMetaObject* _meta; QByteArray _wrappedClassName; QList _parentClasses; QList _polymorphicHandlers; QList _nestedClasses; QObject* _decoratorProvider; PythonQtQObjectCreatorFunctionCB* _decoratorProviderCB; PyObject* _pythonQtClassWrapper; PythonQtShellSetInstanceWrapperCB* _shellSetInstanceWrapperCB; int _metaTypeId; int _typeSlots; bool _isQObject; bool _enumsCreated; bool _richCompareDetectionDone; bool _searchPolymorphicHandlerOnParent; bool _searchRefCountCB; }; //--------------------------------------------------------------- #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtClassWrapper.h ================================================ #ifndef _PYTHONQTCLASSWRAPPER_H #define _PYTHONQTCLASSWRAPPER_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtClassWrapper.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include "structmember.h" #include "methodobject.h" #include "compile.h" #include "eval.h" #include class PythonQtClassInfo; //! the type of the PythonQt class wrapper objects extern PYTHONQT_EXPORT PyTypeObject PythonQtClassWrapper_Type; struct PythonQtDynamicClassInfo; //--------------------------------------------------------------- //! a Python wrapper object for PythonQt wrapped classes //! which inherits from the Python type object to allow //! deriving of wrapped CPP classes from Python. typedef struct { PyHeapTypeObject _base; //! the additional class information that PythonQt stores for the CPP class PythonQtClassInfo* _classInfo; //! get the class info PythonQtClassInfo* classInfo() { return _classInfo; } PythonQtDynamicClassInfo* _dynamicClassInfo; } PythonQtClassWrapper; //--------------------------------------------------------------- #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtConversion.h ================================================ #ifndef _PYTHONQTCONVERSION_H #define _PYTHONQTCONVERSION_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtConversion.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQt.h" #include "PythonQtMisc.h" #include "PythonQtClassInfo.h" #include "PythonQtMethodInfo.h" #include #include typedef PyObject* PythonQtConvertMetaTypeToPythonCB(const void* inObject, int metaTypeId); typedef bool PythonQtConvertPythonToMetaTypeCB(PyObject* inObject, void* outObject, int metaTypeId, bool strict); typedef QVariant PythonQtConvertPythonSequenceToQVariantListCB(PyObject* inObject); #define PythonQtRegisterListTemplateConverter(type, innertype) \ { int typeId = qRegisterMetaType >(#type"<"#innertype">"); \ PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonListToListOfValueType, innertype>); \ PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertListOfValueTypeToPythonList, innertype>); \ } #define PythonQtRegisterListTemplateConverterForKnownClass(type, innertype) \ { int typeId = qRegisterMetaType >(#type"<"#innertype">"); \ PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonListToListOfKnownClass, innertype>); \ PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertListOfKnownClassToPythonList, innertype>); \ } #define PythonQtRegisterQPairConverter(type1, type2) \ { int typeId = qRegisterMetaType >("QPair<"#type1","#type2">"); \ PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonToPair); \ PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertPairToPython); \ } #define PythonQtRegisterIntegerMapConverter(type, innertype) \ { int typeId = qRegisterMetaType >(#type""); \ PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonToIntegerMap, innertype>); \ PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertIntegerMapToPython, innertype>); \ } #define PythonQtRegisterListTemplateQPairConverter(listtype, type1, type2) \ { \ qRegisterMetaType >("QPair<"#type1","#type2">"); \ int typeId = qRegisterMetaType > >(#listtype">"); \ PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonListToListOfPair >, type1, type2>); \ PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertListOfPairToPythonList >, type1, type2>); \ } #define PythonQtRegisterToolClassesTemplateConverter(innertype) \ PythonQtRegisterListTemplateConverter(QList, innertype); \ PythonQtRegisterListTemplateConverter(QVector, innertype); \ PythonQtRegisterListTemplateConverter(std::vector, innertype); #define PythonQtRegisterToolClassesTemplateConverterForKnownClass(innertype) \ PythonQtRegisterListTemplateConverterForKnownClass(QList, innertype); \ PythonQtRegisterListTemplateConverterForKnownClass(QVector, innertype); \ PythonQtRegisterListTemplateConverterForKnownClass(std::vector, innertype); //! a static class that offers methods for type conversion class PYTHONQT_EXPORT PythonQtConv { public: //! get a ref counted True or False Python object static PyObject* GetPyBool(bool val); //! converts the Qt parameter given in \c data, interpreting it as a \c info parameter, into a Python object, static PyObject* ConvertQtValueToPython(const PythonQtMethodInfo::ParameterInfo& info, const void* data); //! convert python object to Qt (according to the given parameter) and if the conversion should be strict (classInfo is currently not used anymore) static void* ConvertPythonToQt(const PythonQtMethodInfo::ParameterInfo& info, PyObject* obj, bool strict, PythonQtClassInfo* classInfo, void* alreadyAllocatedCPPObject, PythonQtArgumentFrame* frame = NULL); //! creates a data storage for the passed parameter type and returns a void pointer to be set as arg[0] of qt_metacall static void* CreateQtReturnValue(const PythonQtMethodInfo::ParameterInfo& info, PythonQtArgumentFrame* frame); //! converts QString to Python string (unicode!) static PyObject* QStringToPyObject(const QString& str); //! converts QStringList to Python tuple static PyObject* QStringListToPyObject(const QStringList& list); //! converts QStringList to Python list static PyObject* QStringListToPyList(const QStringList& list); //! get string representation of py object static QString PyObjGetRepresentation(PyObject* val); //! get string value from py object static QString PyObjGetString(PyObject* val) { bool ok; QString s = PyObjGetString(val, false, ok); return s; } //! get string value from py object static QString PyObjGetString(PyObject* val, bool strict, bool &ok); //! get bytes from py object static QByteArray PyObjGetBytes(PyObject* val, bool strict, bool &ok); //! get int from py object static int PyObjGetInt(PyObject* val, bool strict, bool &ok); //! get int64 from py object static qint64 PyObjGetLongLong(PyObject* val, bool strict, bool &ok); //! get int64 from py object static quint64 PyObjGetULongLong(PyObject* val, bool strict, bool &ok); //! get double from py object static double PyObjGetDouble(PyObject* val, bool strict, bool &ok); //! get bool from py object static bool PyObjGetBool(PyObject* val, bool strict, bool &ok); //! create a string list from python sequence static QStringList PyObjToStringList(PyObject* val, bool strict, bool& ok); //! convert python object to qvariant, if type is given it will try to create a qvariant of that type, otherwise //! it will guess from the python type static QVariant PyObjToQVariant(PyObject* val, int type = -1); //! convert QVariant from PyObject static PyObject* QVariantToPyObject(const QVariant& v); static PyObject* QVariantHashToPyObject(const QVariantHash& m); static PyObject* QVariantMapToPyObject(const QVariantMap& m); static PyObject* QVariantListToPyObject(const QVariantList& l); //! get human readable string from CPP object (when the metatype is known) static QString CPPObjectToString(int type, const void* data); //! register a converter callback from python to cpp for given metatype static void registerPythonToMetaTypeConverter(int metaTypeId, PythonQtConvertPythonToMetaTypeCB* cb) { _pythonToMetaTypeConverters.insert(metaTypeId, cb); } //! register a converter callback from cpp to python for given metatype static void registerMetaTypeToPythonConverter(int metaTypeId, PythonQtConvertMetaTypeToPythonCB* cb) { _metaTypeToPythonConverters.insert(metaTypeId, cb); } //! set a callback that is called when a Python sequence should be converted to a QVariantList //! to allow special conversion. static void setPythonSequenceToQVariantListCallback(PythonQtConvertPythonSequenceToQVariantListCB* cb) { _pythonSequenceToQVariantListCB = cb; } //! converts the Qt parameter given in \c data, interpreting it as a \c type registered qvariant/meta type, into a Python object, static PyObject* convertQtValueToPythonInternal(int type, const void* data); //! creates a copy of given object, using the QMetaType static PyObject* createCopyFromMetaType( int type, const void* object ); //! cast wrapper to given className if possible static void* castWrapperTo(PythonQtInstanceWrapper* wrapper, const QByteArray& className, bool& ok); static bool convertToPythonQtObjectPtr(PyObject* obj, void* /* PythonQtObjectPtr* */ outPtr, int /*metaTypeId*/, bool /*strict*/); static PyObject* convertFromPythonQtObjectPtr(const void* /* PythonQtObjectPtr* */ inObject, int /*metaTypeId*/); static bool convertToPythonQtSafeObjectPtr(PyObject* obj, void* /* PythonQtObjectPtr* */ outPtr, int /*metaTypeId*/, bool /*strict*/); static PyObject* convertFromPythonQtSafeObjectPtr(const void* /* PythonQtObjectPtr* */ inObject, int /*metaTypeId*/); static bool convertToQListOfPythonQtObjectPtr(PyObject* obj, void* /* QList* */ outList, int /*metaTypeId*/, bool /*strict*/); static PyObject* convertFromQListOfPythonQtObjectPtr(const void* /* QList* */ inObject, int /*metaTypeId*/); static PyObject* convertFromStringRef(const void* inObject, int /*metaTypeId*/); //! Returns the name of the equivalent CPP type (for signals and slots) static QByteArray getCPPTypeName(PyObject* type); //! Returns if the given object is a string (or unicode string) static bool isStringType(PyTypeObject* type); protected: static QHash _metaTypeToPythonConverters; static QHash _pythonToMetaTypeConverters; static PythonQtConvertPythonSequenceToQVariantListCB* _pythonSequenceToQVariantListCB; //! handle automatic conversion of some special types (QColor, QBrush, ...) static void* handlePythonToQtAutoConversion(int typeId, PyObject* obj, void* alreadyAllocatedCPPObject, PythonQtArgumentFrame* frame); //! converts the list of pointers of given type to Python static PyObject* ConvertQListOfPointerTypeToPythonList(QList* list, const PythonQtMethodInfo::ParameterInfo& info); //! tries to convert the python object to a QList of pointers to \c type objects, returns true on success static bool ConvertPythonListToQListOfPointerType(PyObject* obj, QList* list, const PythonQtMethodInfo::ParameterInfo& info, bool strict); //! helper template method for conversion from Python to QVariantMap/Hash template static void pythonToMapVariant(PyObject* val, QVariant& result); //! helper template function for QVariantMapToPyObject/QVariantHashToPyObject template static PyObject* mapToPython (const Map& m); }; template PyObject* PythonQtConvertListOfValueTypeToPythonList(const void* /*QList* */ inList, int metaTypeId) { ListType* list = (ListType*)inList; static const int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId))); if (innerType == QVariant::Invalid) { std::cerr << "PythonQtConvertListOfValueTypeToPythonList: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } PyObject* result = PyTuple_New(list->size()); int i = 0; Q_FOREACH (const T& value, *list) { PyTuple_SET_ITEM(result, i, PythonQtConv::convertQtValueToPythonInternal(innerType, &value)); i++; } return result; } template bool PythonQtConvertPythonListToListOfValueType(PyObject* obj, void* /*QList* */ outList, int metaTypeId, bool /*strict*/) { ListType* list = (ListType*)outList; static const int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId))); if (innerType == QVariant::Invalid) { std::cerr << "PythonQtConvertPythonListToListOfValueType: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } bool result = false; if (PySequence_Check(obj)) { int count = PySequence_Size(obj); if (count >= 0) { result = true; PyObject* value; for (int i = 0;ipush_back(qvariant_cast(v)); } else { result = false; break; } } } } return result; } //-------------------------------------------------------------------------------------------------------------------- template PyObject* PythonQtConvertListOfKnownClassToPythonList(const void* /*QList* */ inList, int metaTypeId) { ListType* list = (ListType*)inList; static PythonQtClassInfo* innerType = PythonQt::priv()->getClassInfo(PythonQtMethodInfo::getInnerListTypeName(QByteArray(QMetaType::typeName(metaTypeId)))); if (innerType == NULL) { std::cerr << "PythonQtConvertListOfKnownClassToPythonList: unknown inner type " << innerType->className().constData() << std::endl; } PyObject* result = PyTuple_New(list->size()); int i = 0; Q_FOREACH(const T& value, *list) { T* newObject = new T(value); PythonQtInstanceWrapper* wrap = (PythonQtInstanceWrapper*)PythonQt::priv()->wrapPtr(newObject, innerType->className()); wrap->_ownedByPythonQt = true; PyTuple_SET_ITEM(result, i, (PyObject*)wrap); i++; } return result; } template bool PythonQtConvertPythonListToListOfKnownClass(PyObject* obj, void* /*QList* */ outList, int metaTypeId, bool /*strict*/) { ListType* list = (ListType*)outList; static PythonQtClassInfo* innerType = PythonQt::priv()->getClassInfo(PythonQtMethodInfo::getInnerListTypeName(QByteArray(QMetaType::typeName(metaTypeId)))); if (innerType == NULL) { std::cerr << "PythonQtConvertListOfKnownClassToPythonList: unknown inner type " << innerType->className().constData() << std::endl; } bool result = false; if (PySequence_Check(obj)) { int count = PySequence_Size(obj); if (count >= 0) { result = true; PyObject* value; for (int i = 0; i < count; i++) { value = PySequence_GetItem(obj, i); if (PyObject_TypeCheck(value, &PythonQtInstanceWrapper_Type)) { PythonQtInstanceWrapper* wrap = (PythonQtInstanceWrapper*)value; bool ok; T* object = (T*)PythonQtConv::castWrapperTo(wrap, innerType->className(), ok); Py_XDECREF(value); if (ok) { list->push_back(*object); } else { result = false; break; } } else { Py_XDECREF(value); result = false; break; } } } } return result; } //-------------------------------------------------------------------------------------------------------------------- template PyObject* PythonQtConvertPairToPython(const void* /*QPair* */ inPair, int metaTypeId) { QPair* pair = (QPair*)inPair; static int innerType1 = -1; static int innerType2 = -1; if (innerType1==-1) { QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId))); QList names = innerTypes.split(','); innerType1 = QMetaType::type(names.at(0).trimmed()); innerType2 = QMetaType::type(names.at(1).trimmed()); } if (innerType1 == QVariant::Invalid || innerType2 == QVariant::Invalid) { std::cerr << "PythonQtConvertPairToPython: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } PyObject* result = PyTuple_New(2); PyTuple_SET_ITEM(result, 0, PythonQtConv::convertQtValueToPythonInternal(innerType1, &pair->first)); PyTuple_SET_ITEM(result, 1, PythonQtConv::convertQtValueToPythonInternal(innerType2, &pair->second)); return result; } template bool PythonQtConvertPythonToPair(PyObject* obj, void* /*QPair* */ outPair, int metaTypeId, bool /*strict*/) { QPair* pair = (QPair*)outPair; static int innerType1 = -1; static int innerType2 = -1; if (innerType1 == -1) { QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId))); QList names = innerTypes.split(','); innerType1 = QMetaType::type(names.at(0).trimmed()); innerType2 = QMetaType::type(names.at(1).trimmed()); } if (innerType1 == QVariant::Invalid || innerType2 == QVariant::Invalid) { std::cerr << "PythonQtConvertPythonToPair: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } bool result = false; if (PySequence_Check(obj)) { int count = PySequence_Size(obj); if (count == 2) { result = true; PyObject* value; value = PySequence_GetItem(obj, 0); // this is quite some overhead, but it avoids having another large switch... QVariant v = PythonQtConv::PyObjToQVariant(value, innerType1); Py_XDECREF(value); if (v.isValid()) { pair->first = qvariant_cast(v); } else { return false; } value = PySequence_GetItem(obj, 1); // this is quite some overhead, but it avoids having another large switch... v = PythonQtConv::PyObjToQVariant(value, innerType2); Py_XDECREF(value); if (v.isValid()) { pair->second = qvariant_cast(v); } else { return false; } } } return result; } //-------------------------------------------------------------------------------------------------------------------- template PyObject* PythonQtConvertListOfPairToPythonList(const void* /*QList >* */ inList, int metaTypeId) { ListType* list = (ListType*)inList; static int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId))); if (innerType == QVariant::Invalid) { std::cerr << "PythonQtConvertListOfPairToPythonList: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } PyObject* result = PyTuple_New(list->size()); int i = 0; typedef const QPair Pair; Q_FOREACH(Pair& value, *list) { PyObject* object = PythonQtConvertPairToPython(&value, innerType); PyTuple_SET_ITEM(result, i, object); i++; } return result; } template bool PythonQtConvertPythonListToListOfPair(PyObject* obj, void* /*QList >* */ outList, int metaTypeId, bool /*strict*/) { ListType* list = (ListType*)outList; static int innerType = PythonQtMethodInfo::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId))); if (innerType == QVariant::Invalid) { std::cerr << "PythonQtConvertPythonListToListOfPair: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } bool result = false; if (PySequence_Check(obj)) { int count = PySequence_Size(obj); if (count >= 0) { result = true; PyObject* value; for (int i = 0; i < count; i++) { QPair pair; value = PySequence_GetItem(obj, i); if (PythonQtConvertPythonToPair(value, &pair, innerType, false)) { Py_XDECREF(value); list->push_back(pair); } else { Py_XDECREF(value); result = false; break; } } } } return result; } //-------------------------------------------------------------------------------------------------------------------- template PyObject* PythonQtConvertIntegerMapToPython(const void* /*QMap* */ inMap, int metaTypeId) { MapType* map = (MapType*)inMap; static int innerType = -1; if (innerType == -1) { QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId))); QList names = innerTypes.split(','); innerType = QMetaType::type(names.at(1).trimmed()); } if (innerType == QVariant::Invalid) { std::cerr << "PythonQtConvertIntegerMapToPython: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } PyObject* result = PyDict_New(); typename MapType::const_iterator t = map->constBegin(); PyObject* key; PyObject* val; for (; t != map->constEnd(); t++) { key = PyInt_FromLong(t.key()); val = PythonQtConv::convertQtValueToPythonInternal(innerType, &t.value()); PyDict_SetItem(result, key, val); Py_DECREF(key); Py_DECREF(val); } return result; } template bool PythonQtConvertPythonToIntegerMap(PyObject* val, void* /*QMap* */ outMap, int metaTypeId, bool /*strict*/) { MapType* map = (MapType*)outMap; static int innerType = -1; if (innerType == -1) { QByteArray innerTypes = PythonQtMethodInfo::getInnerTemplateTypeName(QByteArray(QMetaType::typeName(metaTypeId))); QList names = innerTypes.split(','); innerType = QMetaType::type(names.at(1).trimmed()); } if (innerType == QVariant::Invalid) { std::cerr << "PythonQtConvertPythonToIntegerMap: unknown inner type " << QMetaType::typeName(metaTypeId) << std::endl; } bool result = false; if (PyMapping_Check(val)) { result = true; PyObject* items = PyMapping_Items(val); if (items) { int count = PyList_Size(items); PyObject* value; PyObject* key; PyObject* tuple; for (int i = 0; i < count; i++) { tuple = PyList_GetItem(items, i); key = PyTuple_GetItem(tuple, 0); value = PyTuple_GetItem(tuple, 1); bool ok; int intKey = PythonQtConv::PyObjGetInt(key, false, ok); // this is quite some overhead, but it avoids having another large switch... QVariant v = PythonQtConv::PyObjToQVariant(value, innerType); if (v.isValid() && ok) { map->insert(intKey, qvariant_cast(v)); } else { result = false; break; } } Py_DECREF(items); } } return result; } #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtCppWrapperFactory.h ================================================ #ifndef _PYTHONQTCPPWRAPPERFACTORY_H #define _PYTHONQTCPPWRAPPERFACTORY_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtCppWrapperFactory.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-06 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include #include //! Factory interface for C++ classes that can be wrapped by QObject objects /*! To create your own factory, derive PythonQtCppWrapperFactory and implement the create() method. A factory can be added to PythonQt by PythonQt::addCppWrapperFactory(). */ class PYTHONQT_EXPORT PythonQtCppWrapperFactory { public: PythonQtCppWrapperFactory() {}; virtual ~PythonQtCppWrapperFactory() {}; //! create a wrapper for the given object virtual QObject* create(const QByteArray& classname, void *ptr) = 0; }; //! Factory interface for C++ classes that can be mapped directly from/to //! Python with other means than PythonQt/QObjects. class PYTHONQT_EXPORT PythonQtForeignWrapperFactory { public: PythonQtForeignWrapperFactory() {}; virtual ~PythonQtForeignWrapperFactory() {}; //! create a Python object (with new reference count), wrapping the given \p ptr as class of type \p classname //! Return NULL (and not Py_None) if the object could not be wrapped. virtual PyObject* wrap(const QByteArray& classname, void *ptr) = 0; //! unwrap the given object to a C++ object of type \p classname if possible //! Return NULL otherwise. virtual void* unwrap(const QByteArray& classname, PyObject* object) = 0; }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtDoc.h ================================================ #ifndef _PYTHONQTDOC_H #define _PYTHONQTDOC_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtDoc.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-10 */ //---------------------------------------------------------------------------------- /*! \if USE_GLOBAL_DOXYGEN_DOC \page PythonQtPage PythonQt Overview \else \mainpage notitle \endif \image html PythonQt.jpg \section Introduction \b PythonQt is a dynamic Python binding for the Qt framework. It offers an easy way to embed the Python scripting language into your C++ Qt applications. The focus of PythonQt is on embedding Python into an existing C++ application, not on writing the whole application completely in Python. If you are looking for a simple way to embed Python objects into your C++/Qt Application and to script parts of your application via Python, PythonQt is the way to go! PythonQt is a stable library that was developed to make the Image Processing and Visualization platform MeVisLab scriptable from Python. - \ref Features - \ref Download - \ref License - \ref Developer - \ref Building - \ref Examples \page Features Features \section Builtin Built-in Features The following are the built-in features of the PythonQt library: - Access all \b slots, \b properties, children and registered enums of any QObject derived class from Python - Connecting Qt Signals to Python functions (both from within Python and from C++) - Easy wrapping of Python objects from C++ with smart, reference-counting PythonQtObjectPtr. - Convenient conversions to/from QVariant for PythonQtObjectPtr. - Wrapping of C++ objects (which are not derived from QObject) via PythonQtCppWrapperFactory - Extending C++ and QObject derived classes with additional slots, static methods and constructors (see Decorators) - StdOut/Err redirection to Qt signals instead of cout - Interface for creating your own \c import replacement, so that Python scripts can be e.g. signed/verified before they are executed (PythonQtImportFileInterface) - Mapping of plain-old-datatypes and ALL QVariant types to and from Python - Support for wrapping of user QVariant types which are registerd via QMetaType - Support for Qt namespace (with all enumerators) - All PythonQt wrapped objects support the dir() statement, so that you can see easily which attributes a QObject, CPP object or QVariant has - No preprocessing/wrapping tool needs to be started, PythonQt can script any QObject without prior knowledge about it (except for the MetaObject information from the \b moc) - Multiple inheritance for C++ objects (e.g. a QWidget is derived from QObject and QPaintDevice, PythonQt will automatically cast a QWidget to a QPaintDevice when needed) - Polymorphic downcasting (if e.g. PythonQt sees a QEvent, it can downcast it depending on the type(), so the Python e.g. sees a QPaintEvent instead of a plain QEvent) - Deriving C++ objects from Python and overwriting virtual method with a Python implementation (requires usage of wrapper generator or manual work!) - Extensible handler for Python/C++ conversion of complex types, e.g. mapping of QVector to/from a Python array - Setting of dynamic QObject properties via setProperty(), dynamic properties can be accessed for reading and writing like normal Python attributes (but creating a new property needs to be done with setProperty(), to distinguish from normal Python attributes) - Support for QtCore.Signal, QtCore.Slot and QtCore.Property, including the creation of a dynamic QMetaObject. \section FeaturesQtAll Features with wrapper generator PythonQt offers the additional PythonQt_QtAll library which wraps the complete Qt API, including all C++ classes and all non-slots on QObject derived classes. This offers the following features: - Complete Qt API wrapped and accessible - The following modules are available as submodules of the PythonQt module: - QtCore - QtGui - QtNetwork - QtOpenGL - QtSql - QtSvg - QtWebKit - QtXml - QtXmlPatterns - QtMultimedia - QtQml - QtQuick - Any Qt class that has virtual methods can be easily derived from Python and the virtual methods can be reimplemented in Python - Polymorphic downcasting on QEvent, QGraphicsItem, QStyleOption, ... - Multiple inheritance support (e.g., QGraphicsTextItem is a QObject and a QGraphicsItem, PythonQt will handle this well) - QtQuick support is experimental and currently it is not possible to register new qml components from Python \section Supported Supported Versions PythonQt supports: - Python 2 (>= Python 2.6) - Python 3 (>= Python 3.3) - Qt 4.x (Qt 4.7 and Qt 4.8 recommended) - Qt 5.x (Tested with Qt 5.0, 5.3, 5.4 and 5.6) The last working Qt4 version is available at svn branches/Qt4LastWorkingVersion or you can download the PythonQt 3.0 release. The current svn trunk no longer supports Qt4, since we started to make use of some Qt5-only features. \section Comparison Comparison with PySide - PythonQt is not as pythonic as PySide in many details (e.g. buffer protocol, pickling, translation support, ...) and it is mainly thought for embedding and intercommunication between Qt/Cpp and Python - PythonQt offers properties as Python attributes, while PySide offers them as setter/getter methods (e.g. QWidget.width is a property in PythonQt and a method in PySide) - PythonQt currently does not support instanceof checks for Qt classes, except for the exact match and derived Python classes - QObject.emit to emit Qt signals from Python is not yet implemented but PythonQt allows to just emit a signal by calling it like a normal slot - Ownership handling of objects is not as complete as in PySide and PySide, especially in situations where the ownership is not clearly passed to C++ on the C++ API. - QStrings are always converted to unicode Python objects, QByteArray always stays a QByteArray and can be converted using QByteArray.data() - Qt methods that take an extra "bool* ok" parameter can be called passing PythonQt.BoolResult as parameter. In PySide, a tuple is returned instead. \page Download Download PythonQt is hosted on GitHub. You can download the source code or alternatively you can get the latest version from the git repository. \note We do not offer prebuilt binaries, since there are so many possible combinations of platforms (Windows/Linux/MacOs), architectures (32/64 bit) and Qt / Python versions. \page License License PythonQt is distributed under the LGPL 2.1 license. It can be used in commercial applications when following the LGPL 2.1 obligations. The build system of PythonQt makes use of a modified version of the LGPL'ed QtScript generator, located in the "generator" directory. See https://code.qt.io/cgit/qt-labs/qtscriptgenerator.git for details on the original project. Thanks a lot to the QtJambi guys and the QtScript Generator project for the C++ parser and Qt typesystem files! The PythonQt wrappers generated by the generator located in the "generated_cpp" directory are free to be used without any licensing restrictions. The generated wrappers are pre-generated and checked-in for 5.0, 5.3, 5.4 and 5.6, so you only need to build and run the generator when you want to build additional wrappers or you want to upgrade/downgrade to another Qt version. You may use the generator to generate C++ bindings for your own C++ classes (e.g., to make them inheritable in Python), but this is currently not documented and involves creating your own typesystem files. \page Developer Developer \section Interface Interface The main interface to PythonQt is the PythonQt singleton. PythonQt needs to be initialized via PythonQt::init() once. Afterwards you communicate with the singleton via PythonQt::self(). PythonQt offers a complete Qt binding, which needs to be enabled via PythonQt_QtAll::init(). \section Datatype Datatype Mapping The following table shows the mapping between Python and Qt objects:
Qt/C++Python
boolbool
doublefloat
floatfloat
char/uchar,int/uint,short,ushort,QCharinteger
longinteger
ulong,longlong,ulonglonglong
QStringunicode string
QByteArrayQByteArray wrapper
char*str
QStringListtuple of unicode strings
QVariantListtuple of objects
QVariantMapdict of objects
QVariantdepends on type, see below
QSize, QRect and all other standard Qt QVariantsvariant wrapper that supports complete API of the respective Qt classes
OwnRegisteredMetaTypeC++ wrapper, optionally with additional information/wrapping provided by registerCPPClass()
QListconverts to a list of CPP wrappers
QVectorconverts to a list of CPP wrappers
EnumTypeEnum wrapper derived from python integer
QObject (and derived classes)QObject wrapper
C++ objectCPP wrapper, either wrapped via PythonQtCppWrapperFactory or just decorated with decorators
PyObjectPyObject
PyObject is passed as direct pointer, which allows to pass/return any Python object directly to/from a Qt slot that uses PyObject* as its argument/return value. QVariants are mapped recursively as given above, e.g. a dictionary can contain lists of dictionaries of doubles. All Qt QVariant types are implemented, PythonQt supports the complete Qt API for these object. \section QObject QObject Wrapping All classes derived from QObject are automatically wrapped with a python wrapper class when they become visible to the Python interpreter. This can happen via - the PythonQt::addObject() method - when a Qt \b slot returns a QObject derived object to python - when a Qt \b signal contains a QObject and is connected to a python function It is important that you call PythonQt::registerClass() for any QObject derived class that may become visible to Python, except when you add it via PythonQt::addObject(). This will register the complete parent hierachy of the registered class, so that when you register e.g. a QPushButton, QWidget will be registered as well (and all intermediate parents). From Python, you can talk to the returned QObjects in a natural way by calling their slots and receiving the return values. You can also read/write all properties of the objects as if they where normal python properties. In addition to this, the wrapped objects support - className() - returns a string that reprents the classname of the QObject - help() - shows all properties, slots, enums, decorator slots and constructors of the object, in a printable form - delete() - deletes the object (use with care, especially if you passed the ownership to C++) - connect(signal, function) - connect the signal of the given object to a python function - connect(signal, qobject, slot) - connect the signal of the given object to a slot of another QObject - disconnect(signal, function) - disconnect the signal of the given object from a python function - disconnect(signal, qobject, slot) - disconnect the signal of the given object from a slot of another QObject - children() - returns the children of the object - setParent(QObject) - set the parent - QObject* parent() - get the parent The below example shows how to connect signals in Python: \code # define a signal handler function def someFunction(flag): print flag # button1 is a QPushButton that has been added to Python via addObject() # connect the clicked signal to a python function: button1.connect("clicked(bool)", someFunction) \endcode \section CPP CPP Wrapping You can create dedicated wrapper QObjects for any C++ class. This is done by deriving from PythonQtCppWrapperFactory and adding your factory via addWrapperFactory(). Whenever PythonQt encounters a CPP pointer (e.g. on a slot or signal) and it does not known it as a QObject derived class, it will create a generic CPP wrapper. So even unknown C++ objects can be passed through Python. If the wrapper factory supports the CPP class, a QObject wrapper will be created for each instance that enters Python. An alternative to a complete wrapper via the wrapper factory are decorators, see \ref Decorators \section MetaObject Meta Object/Class access For each known C++ class, PythonQt provides a Python class. These classes are visible inside of the "PythonQt" python module or in subpackages if a package is given when the class is registered. A Meta class supports: - access to all declared enum values - constructors - static methods - unbound non-static methods - help() and className() From within Python, you can import the module "PythonQt" to access these classes and the Qt namespace. \code from PythonQt import QtCore # namespace access: print QtCore.Qt.AlignLeft # constructors a = QtCore.QSize(12,13) b = QtCore.QFont() # static method QtCore.QDate.currentDate() # enum value QtCore.QFont.UltraCondensed \endcode \section Decorators Decorator slots PythonQt introduces a new generic approach to extend any wrapped QObject or CPP object with - constructors - destructors (for CPP objects) - additional slots - static slots (callable on both the Meta object and the instances) The idea behind decorators is that we wanted to make it as easy as possible to extend wrapped objects. Since we already have an implementation for invoking any Qt Slot from Python, it looked promising to use this approach for the extension of wrapped objects as well. This avoids that the PythonQt user needs to care about how Python arguments are mapped from/to Qt when he wants to create static methods, constructors and additional member functions. The basic idea about decorators is to create a QObject derived class that implements slots which take one of the above roles (e.g. constructor, destructor etc.) via a naming convention. These slots are then assigned to other classes via the naming convention. - SomeClassName* new_SomeClassName(...) - defines a constructor for "SomeClassName" that returns a new object of type SomeClassName (where SomeClassName can be any CPP class, not just QObject classes) - void delete_SomeClassName(SomeClassName* o) - defines a destructor, which should delete the passed in object o - anything static_SomeClassName_someMethodName(...) - defines a static method that is callable on instances and the meta class - anything someMethodName(SomeClassName* o, ...) - defines a slot that will be available on SomeClassName instances (and derived instances). When such a slot is called the first argument is the pointer to the instance and the rest of the arguments can be used to make a call on the instance. The below example shows all kinds of decorators in action: \code // an example CPP object class YourCPPObject { public: YourCPPObject(int arg1, float arg2) { a = arg1; b = arg2; } float doSomething(int arg1) { return arg1*a*b; }; private: int a; float b; }; // an example decorator class ExampleDecorator : public QObject { Q_OBJECT public slots: // add a constructor to QSize that takes a QPoint QSize* new_QSize(const QPoint& p) { return new QSize(p.x(), p.y()); } // add a constructor for QPushButton that takes a text and a parent widget QPushButton* new_QPushButton(const QString& text, QWidget* parent=NULL) { return new QPushButton(text, parent); } // add a constructor for a CPP object YourCPPObject* new_YourCPPObject(int arg1, float arg2) { return new YourCPPObject(arg1, arg2); } // add a destructor for a CPP object void delete_YourCPPObject(YourCPPObject* obj) { delete obj; } // add a static method to QWidget QWidget* static_QWidget_mouseGrabber() { return QWidget::mouseGrabber(); } // add an additional slot to QWidget (make move() callable, which is not declared as a slot in QWidget) void move(QWidget* w, const QPoint& p) { w->move(p); } // add an additional slot to QWidget, overloading the above move method void move(QWidget* w, int x, int y) { w->move(x,y); } // add a method to your own CPP object int doSomething(YourCPPObject* obj, int arg1) { return obj->doSomething(arg1); } }; ... PythonQt::self()->addDecorators(new ExampleDecorator()); PythonQt::self()->registerCPPClass("YourCPPObject"); \endcode After you have registered an instance of the above ExampleDecorator, you can do the following from Python (all these calls are mapped to the above decorator slots): \code from PythonQt import QtCore, QtGui, YourCPPObject # call our new constructor of QSize size = QtCore.QSize(QPoint(1,2)); # call our new QPushButton constructor button = QtGui.QPushButton("sometext"); # call the move slot (overload1) button.move(QPoint(0,0)) # call the move slot (overload2) button.move(0,0) # call the static method grabber = QtGui.QWidget.mouseWrapper(); # create a CPP object via constructor yourCpp = YourCPPObject(1,11.5) # call the wrapped method on CPP object print yourCpp.doSomething(1); # destructor will be called: yourCpp = None \endcode \section Ownership Ownership management In PythonQt, each wrapped C++ object is either owned by Python or C++. When an object is created via a Python constructor, it is owned by Python by default. When an object is returned from a C++ API (e.g. a slot), it is owned by C++ by default. Since the Qt API contains various APIs that pass the ownership from/to other C++ objects, PythonQt needs to keep track of such API calls. This is archieved by annotating arguments and return values in wrapper slots with magic templates: - PythonQtPassOwnershipToCPP - PythonQtPassOwnershipToPython - PythonQtNewOwnerOfThis These annotation templates work for since C++ pointer types. In addition to that, they work for QList, to pass the ownership for each object in the list. Examples: \code public slots: //! Pass ownership of return value to Python PythonQtPassOwnershipToPython createNewItemOwnedByPython(); //! Pass ownership of item to C++ void addItemToCPP(PythonQtPassOwnershipToPython item); //! Pass ownership of items to C++ (Note that the QList can't be a reference nor a pointer). void addItemToCPP(PythonQtPassOwnershipToPython > items); //! Pass ownership of wrapped object to C++ if parent is != NULL void addItemParent(QGraphicsItem* wrappedObject, PythonQtNewOwnerOfThis parent); \endcode \page Building Building PythonQt requires at least Qt 4.6.1 (for earlier Qt versions, you will need to run the pythonqt_generator, Qt 4.3 is the absolute minimum) and Python 2.6.x/2.7.x or Python 3.3 (or higher). To compile PythonQt, you will need a python developer installation which includes Python's header files and the python2x.[lib | dll | so | dynlib]. The recommended way to build PythonQt is to use the QMake-based *.pro file. The build scripts a currently set to use Python 2.6. You may need to tweak the \b build/python.prf file to set the correct Python includes and libs on your system. \subsection Windows On Windows, the (non-source) Python Windows installer can be used. Make sure that you use the same compiler as the one that your Python distribution is built with. If you want to use another compiler, you will need to build Python yourself, using your compiler. To build PythonQt, you need to set the environment variable \b PYTHON_PATH to point to the root dir of the python installation and \b PYTHON_LIB to point to the directory where the python lib file is located. When using the prebuild Python installer, this will be: \code > set PYTHON_PATH = c:\Python26 > set PYTHON_LIB = c:\Python26\libs \endcode When using the python sources, this will be something like: \code > set PYTHON_PATH = c:\yourDir\Python-2.6.1\ > set PYTHON_LIB = c:\yourDir\Python-2.6.1\PCbuild8\Win32 \endcode To build all, do the following (after setting the above variables): \code > cd PythonQtRoot > vcvars32 > qmake > nmake \endcode This should build everything. If Python can not be linked or include files can not be found, you probably need to tweak \b build/python.prf The tests and examples are located in PythonQt/lib. When using a Python distribution, the debug build typically does not work because the pythonxx_d.lib/.dll are not provided. You can tweak linking of the debug build to the release Python version, but this typically requires patching pyconfig.h and removing Py_DEBUG and linker pragmas (google for it!). \subsection Linux On Linux, you need to install a Python-dev package. If Python can not be linked or include files can not be found, you probably need to tweak \b build/python.prf To build PythonQt, just do a: \code > cd PythonQtRoot > qmake > make all \endcode The tests and examples are located in PythonQt/lib. You should add PythonQt/lib to your LD_LIBRARY_PATH so that the runtime linker can find the *.so files. \subsection MacOsX On Mac, Python is installed as a Framework, so you should not need to install it. To build PythonQt, just do a: \code > cd PythonQtRoot > qmake > make all \endcode \section Tests There is a unit test that tests most features of PythonQt, see the \b tests subdirectory for details. \page Examples Examples Examples are available in the \b examples directory. The PyScriptingConsole implements a simple interactive scripting console that shows how to script a simple application. The PyLauncher application can be used to run arbitrary PythonQt scripts given on the commandline. The following shows a simple example on how to integrate PythonQt into your Qt application: \code #include "PythonQt.h" #include ... int main( int argc, char **argv ) { QApplication qapp(argc, argv); // init PythonQt and Python itself PythonQt::init(); // get a smart pointer to the __main__ module of the Python interpreter PythonQtObjectPtr context = PythonQt::self()->getMainModule(); // add a QObject as variable of name "example" to the namespace of the __main__ module PyExampleObject example; context.addObject("example", &example); // do something context.evalScript("print example"); context.evalScript("def multiply(a,b):\n return a*b;\n"); QVariantList args; args << 42 << 47; QVariant result = context.call("multiply", args); ... \endcode */ ================================================ FILE: thirdLibs/PythonQt/include/PythonQtImportFileInterface.h ================================================ #ifndef _PYTHONQTIMPORTFILEINTERFACE_H #define _PYTHONQTIMPORTFILEINTERFACE_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtImportFileInterface.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include #include #include //! Defines an abstract interface to file access for the Python import statement. //! see PythonQt::setImporter() class PythonQtImportFileInterface { public: // get rid of warnings virtual ~PythonQtImportFileInterface() {} //! read the given file as byte array, without doing any linefeed translations virtual QByteArray readFileAsBytes(const QString& filename) = 0; //! read a source file, expects a readable Python text file with translated line feeds. //! If the file can not be load OR it can not be verified, ok is set to false virtual QByteArray readSourceFile(const QString& filename, bool& ok) = 0; //! returns if the file exists virtual bool exists(const QString& filename) = 0; //! returns true if the given file is an egg archive (e.g. zip). If the egg is a directory //! then false is returned. virtual bool isEggArchive(const QString& filename) = 0; //! get the last modified data of a file virtual QDateTime lastModifiedDate(const QString& filename) = 0; //! indicates that *.py files which are newer than their corresponding *.pyc files //! are ignored virtual bool ignoreUpdatedPythonSourceFiles() { return false; } //! called by PythonQt after successful import to allow //! recording of imports virtual void importedModule(const QString& /*module*/) {}; }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtImporter.h ================================================ #ifndef _PYTHONQTIMPORTER_ #define _PYTHONQTIMPORTER_ /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtImporter.h // \author Florian Link // \author Last changed by $Author: stk $ // \date 2004-06 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "structmember.h" #include "osdefs.h" #include "marshal.h" #include "compile.h" #include #include #include //! defines a python object that stores a Qt slot info typedef struct _PythonQtImporter { PyObject_HEAD QString* _path; } PythonQtImporter; //! implements importing of python files into PythonQt /*! also compiles/marshalls/unmarshalls py/pyc files and handles time stamps correctly */ class PythonQtImport { public: enum ModuleType { MI_NOT_FOUND, MI_MODULE, MI_PACKAGE, MI_SHAREDLIBRARY }; struct ModuleInfo { ModuleInfo() { type = MI_NOT_FOUND; } QString fullPath; //!< the full path to the found file QString moduleName; //!< the module name without the package prefix ModuleType type; }; //! initialize static void init(); //! writes the python code to disk, marshalling and writing the time stamp static void writeCompiledModule(PyCodeObject *co, const QString& filename, long mtime, long sourceSize); /*! Given the contents of a .py[co] file in a buffer, unmarshal the data and return the code object. Return None if it the magic word doesn't match (we do this instead of raising an exception as we fall back to .py if available and we don't want to mask other errors). Returns a new reference. */ static PyObject *unmarshalCode(const QString& path, const QByteArray& data, time_t mtime); //! Given a string buffer containing Python source code, compile it //! return and return a code object as a new reference. static PyObject *compileSource(const QString& path, const QByteArray& data); //! Return the code object for the module named by 'fullname' from the //! Zip archive as a new reference. static PyObject *getCodeFromData(const QString& path, int isbytecode = 0, int ispackage = 0, time_t mtime = 0); //! Get the code object associated with the module specified by //! 'fullname'. In Python3, modpath will always be the path to the *.py file and cachemodpath the path //! to the *.pyc file (if it exists). static PyObject * getModuleCode(PythonQtImporter *self, const char* fullname, QString& modpath, QString& cachemodpath); //! gets the compiled code for the given *.py file if there is a valid pyc file, otherwise compiles the file and writes the pyc static PyObject* getCodeFromPyc(const QString& file); //! Return if module exists and is a package or a module static ModuleInfo getModuleInfo(PythonQtImporter* self, const QString& fullname); //! get the last name of a dot chain (first.second.last) static QString getSubName(const QString& str); //! Given a buffer, return the long that is represented by the first //! 4 bytes, encoded as little endian. This partially reimplements //! marshal.c:r_long() static long getLong(unsigned char *buf); //! get time stamp of file static time_t getMTimeOfSource(const QString& path); //! replace extension of file static QString replaceExtension(const QString& str, const QString& ext); //! Returns the filename of the cache file for the given source file, e.g. test.pyc for test.py. static QString getCacheFilename(const QString& sourceFile, bool isOptimizedFilename); //! Returns the filename of the source file for the given cache file, e.g. test.py for test.pyc. static QString getSourceFilename(const QString& cacheFile); }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtInstanceWrapper.h ================================================ #ifndef _PYTHONQTINSTANCEWRAPPER_H #define _PYTHONQTINSTANCEWRAPPER_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtInstanceWrapper.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include "PythonQtClassWrapper.h" #include #include "structmember.h" #include "methodobject.h" #include "compile.h" #include "eval.h" class PythonQtClassInfo; class QObject; extern PYTHONQT_EXPORT PyTypeObject PythonQtInstanceWrapper_Type; //--------------------------------------------------------------- //! a Python wrapper object for Qt objects and C++ objects (that are themselves wrapped by wrapper QObjects) typedef struct PythonQtInstanceWrapperStruct { PyObject_HEAD //! the class information, this is set even if the _obj or _wrappedPtr is NULL to support typed NULL pointers inline PythonQtClassInfo* classInfo() { return ((PythonQtClassWrapper*)Py_TYPE(this))->_classInfo; } inline PythonQtDynamicClassInfo* dynamicClassInfo() { return ((PythonQtClassWrapper*)Py_TYPE(this))->_dynamicClassInfo; } //! set the QObject pointer void setQObject(QObject* object) { _obj = object; _objPointerCopy = object; } //! Passes the ownership of the wrapped object to C++ void passOwnershipToCPP() { // we pass the ownership to C++ _ownedByPythonQt = false; // handle shell instance if (_isShellInstance) { if (!_shellInstanceRefCountsWrapper) { // ref count the wrapper, so that the Python part of the shell instance can not go // away until the C++ object gets deleted... Py_INCREF((PyObject*)this); _shellInstanceRefCountsWrapper = true; } } } //! Passes the ownership to Python void passOwnershipToPython() { _ownedByPythonQt = true; // if the shell instance was owned by C++ and the ownership goes to Python, // we need to remove the extra ref count that kept the Python part alive from the C++ side. if (_shellInstanceRefCountsWrapper) { Py_DECREF((PyObject*)this); _shellInstanceRefCountsWrapper = false; } } //! pointer to the wrapped Qt object or if _wrappedPtr is set, the Qt object that wraps the C++ Ptr QPointer _obj; //! a copy of the _obj pointer, which is required because the wrapper needs to //! deregister itself via the _obj pointer, even when the QPointer object was destroyed void* _objPointerCopy; //! optional C++ object Ptr that is wrapped by the above _obj void* _wrappedPtr; // TODO xxx: put booleans into int that holds flags //! flag that stores if the object is owned by pythonQt bool _ownedByPythonQt; //! stores that the owned object should be destroyed using QMetaType::destroy() bool _useQMetaTypeDestroy; //! stores if the object is a shell instance bool _isShellInstance; //! stores if the shell instance (C++) owns the wrapper with its ref count bool _shellInstanceRefCountsWrapper; } PythonQtInstanceWrapper; int PythonQtInstanceWrapper_init(PythonQtInstanceWrapper * self, PyObject * args, PyObject * kwds); PyObject *PythonQtInstanceWrapper_delete(PythonQtInstanceWrapper * self); #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtMethodInfo.h ================================================ #ifndef _PYTHONQTMETHODINFO_H #define _PYTHONQTMETHODINFO_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtMethodInfo.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include #include #include #include class PythonQtClassInfo; struct _object; typedef struct _object PyObject; //! stores information about a specific signal/slot/method class PYTHONQT_EXPORT PythonQtMethodInfo { public: enum ParameterType { Unknown = -1, Variant = -2 }; //! stores various informations about a parameter/type name struct ParameterInfo { QByteArray name; QByteArray innerName; // if the type is a template, this stores the inner name PyObject* enumWrapper; // if it is an enum, a pointer to the enum wrapper int typeId; // a mixture from QMetaType and ParameterType char pointerCount; // the number of pointer indirections char innerNamePointerCount; // the number of pointer indirections in the inner name bool isConst; bool isReference; bool isQList; bool passOwnershipToCPP; bool passOwnershipToPython; bool newOwnerOfThis; }; PythonQtMethodInfo() { _shouldAllowThreads = true; }; ~PythonQtMethodInfo() {}; PythonQtMethodInfo(const QMetaMethod& meta, PythonQtClassInfo* classInfo); PythonQtMethodInfo(const QByteArray& typeName, const QList& args); PythonQtMethodInfo(const PythonQtMethodInfo& other) { _parameters = other._parameters; _shouldAllowThreads = other._shouldAllowThreads; } //! returns the method info of the signature, uses a cache internally to speed up //! multiple requests for the same method, classInfo is passed to allow local enum resolution (if NULL is passed, no local enums are recognized) static const PythonQtMethodInfo* getCachedMethodInfo(const QMetaMethod& method, PythonQtClassInfo* classInfo); //! get the cached method info using the passed in list of return value and arguments, return value needs to be passed as first arg static const PythonQtMethodInfo* getCachedMethodInfoFromArgumentList(int numArgs, const char** args); //! cleanup the cache static void cleanupCachedMethodInfos(); //! returns the number of parameters including the return value int parameterCount() const { return _parameters.size(); }; //! returns the id for the given type (using an internal dictionary) static int nameToType(const char* name); //! get the parameter infos const QList& parameters() const { return _parameters; } //! add an alias for a typename, e.g. QObjectList and QList. static void addParameterTypeAlias(const QByteArray& alias, const QByteArray& name); //! fill the parameter info for the given type name static void fillParameterInfo(ParameterInfo& type, const QByteArray& name, PythonQtClassInfo* classInfo = NULL); //! returns a parameter info for the given metatype (and creates and caches one if it is not yet present) static const ParameterInfo& getParameterInfoForMetaType(int type); //! returns the inner type id of a simple template of the form SomeObject static int getInnerTemplateMetaType(const QByteArray& typeName); //! returns the inner type name of a simple template of the form SomeObject static QByteArray getInnerTemplateTypeName(const QByteArray& typeName); //! returns the inner type name of a simple template or the typename without appended "List". static QByteArray getInnerListTypeName(const QByteArray& typeName); //! returns if the GIL should be released when calling this method. //! This is the default, but it will return false if any of the //! parameters is a PythonQtObjectPtr or PyObject*. bool shouldAllowThreads() const { return _shouldAllowThreads; } protected: void setupAllowThreads(); static QHash _parameterTypeDict; static QHash _parameterNameAliases; //! stores the cached signatures of methods to speedup mapping from Qt to Python types static QHash _cachedSignatures; static QHash _cachedParameterInfos; QList _parameters; bool _shouldAllowThreads; }; //! stores information about a slot, including a next pointer to overloaded slots class PYTHONQT_EXPORT PythonQtSlotInfo : public PythonQtMethodInfo { public: enum Type { MemberSlot, InstanceDecorator, ClassDecorator }; PythonQtSlotInfo(const PythonQtSlotInfo& info):PythonQtMethodInfo() { _meta = info._meta; _parameters = info._parameters; _shouldAllowThreads = info._shouldAllowThreads; _slotIndex = info._slotIndex; _next = NULL; _decorator = info._decorator; _type = info._type; _upcastingOffset = 0; } PythonQtSlotInfo(PythonQtClassInfo* classInfo, const QMetaMethod& meta, int slotIndex, QObject* decorator = NULL, Type type = MemberSlot ):PythonQtMethodInfo() { const PythonQtMethodInfo* info = getCachedMethodInfo(meta, classInfo); _meta = meta; _parameters = info->parameters(); _shouldAllowThreads = info->shouldAllowThreads(); _slotIndex = slotIndex; _next = NULL; _decorator = decorator; _type = type; _upcastingOffset = 0; } public: //! get the parameter infos for the arguments, without return type and instance decorator. QList arguments() const; void deleteOverloadsAndThis(); const QMetaMethod* metaMethod() const { return &_meta; } void setUpcastingOffset(int upcastingOffset) { _upcastingOffset = upcastingOffset; } int upcastingOffset() const { return _upcastingOffset; } //! get the index of the slot (needed for qt_metacall) int slotIndex() const { return _slotIndex; } //! get next overloaded slot (which has the same name) PythonQtSlotInfo* nextInfo() const { return _next; } //! set the next overloaded slot void setNextInfo(PythonQtSlotInfo* next) { _next = next; } //! returns if the slot is a decorator slot bool isInstanceDecorator() const { return _decorator!=NULL && _type == InstanceDecorator; } //! returns if the slot is a constructor slot bool isClassDecorator() const { return _decorator!=NULL && _type == ClassDecorator; } QObject* decorator() const { return _decorator; } //! get the full signature including return type QString fullSignature(bool skipReturnValue = false, int optionalArgsIndex = -1) const; //! get the Qt signature of the slot QByteArray signature() const; //! get the short slot name QByteArray slotName(bool removeDecorators = false) const; //! gets a list of all overload signatures. Signatures //! which only differ because of default values are joined using "[]" to //! indicate the optional arguments. QStringList overloads(bool skipReturnValue = false) const; //! Returns the class name that originally implements this method, //! regardless where the wrapper is located/implemented. QByteArray getImplementingClassName() const; //! Invoke the given slot on obj, save/restore thread state if needed. static void invokeQtMethod(QObject* obj, PythonQtSlotInfo* slot, void** argList); //! Sets if calling slots should release the GIL to allow other Python threads while being inside of C++ static void setGlobalShouldAllowThreads(bool flag); //! Returns if calling slots should release the GIL to allow Python threads while being inside of C++ static bool getGlobalShouldAllowThreads(); private: int _slotIndex; PythonQtSlotInfo* _next; QObject* _decorator; Type _type; QMetaMethod _meta; int _upcastingOffset; static bool _globalShouldAllowThreads; }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtMisc.h ================================================ #ifndef _PYTHONQTMISC_H #define _PYTHONQTMISC_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtMisc.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include #include #define PYTHONQT_MAX_ARGS 32 #define PythonQtArgumentFrame_ADD_VALUE(store, type, value, ptr) \ { type* item = (type*)store->nextPODPtr(); \ *item = value; \ ptr = (void*)item; \ } #define PythonQtArgumentFrame_ADD_VALUE_IF_NEEDED(alreadyAllocatedPtr,store, type, value, ptr) \ { \ type* item = (type*)(alreadyAllocatedPtr?alreadyAllocatedPtr:store->nextPODPtr()); \ *item = value; \ ptr = (void*)item; \ } #define PythonQtArgumentFrame_ADD_VARIANT_VALUE(store, value, ptr) \ { QVariant* item = store->nextVariantPtr(); \ *item = value; \ ptr = (void*)item; \ } #define PythonQtArgumentFrame_ADD_VARIANT_VALUE_IF_NEEDED(alreadyAllocatedPtr,store, value, ptr) \ { \ QVariant* item = (QVariant*)(alreadyAllocatedPtr?alreadyAllocatedPtr:store->nextVariantPtr()); \ *item = value; \ ptr = (void*)item; \ } //! Stores C++ arguments for a qt_metacall (which are created when converting data from Python to C++) class PythonQtArgumentFrame { public: //! Create a new (empty) frame (which is typically reused from a freelist) static PythonQtArgumentFrame* newFrame(); //! Frees the frame (resetting it and putting it back to the freelist) static void deleteFrame(PythonQtArgumentFrame* frame); //! Frees all PythonQtArgumentFrame frames that are stored. static void cleanupFreeList(); //! Resets the pod and variant argument lists to empty lists. void reset(); //! Get next pointer to a variant QVariant* nextVariantPtr(); //! Get next pointer to a POD. quint64* nextPODPtr(); private: PythonQtArgumentFrame(); ~PythonQtArgumentFrame(); std::vector _podArgs; std::vector _variantArgs; PythonQtArgumentFrame* _freeListNext; static PythonQtArgumentFrame* _freeListHead; }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtObjectPtr.h ================================================ #ifndef _PYTHONQTOBJECTPTR_H #define _PYTHONQTOBJECTPTR_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtObjectPtr.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include "PythonQtThreadSupport.h" #include #include #include class PythonQtSafeObjectPtr; //! a smart pointer that stores a PyObject pointer and that handles reference counting automatically class PYTHONQT_EXPORT PythonQtObjectPtr { public: PythonQtObjectPtr():_object(NULL) {} PythonQtObjectPtr(const PythonQtObjectPtr &p) :_object(NULL) { setObject(p.object()); } //! rvalue copy constructor, does not need any incref/decref. PythonQtObjectPtr(PythonQtObjectPtr &&p) :_object(p.takeObject()) { } //! rvalue copy constructor, does not need any incref/decref. PythonQtObjectPtr(PythonQtSafeObjectPtr &&p); //! If the given variant holds a PythonQtObjectPtr, extract the value from it and hold onto the reference. This results in an increment of the reference count. PythonQtObjectPtr(const QVariant& variant):_object(NULL) { fromVariant(variant); } PythonQtObjectPtr(PyObject* o); ~PythonQtObjectPtr(); //! If the given variant holds a PythonQtObjectPtr, extract the value from it and hold onto the reference. This results in an increment of the reference count. bool fromVariant(const QVariant& variant); //! Returns a PythonQtSafeObjectPtr as a QVariant. It does not return a PythonQtObjectPtr, because that would be unsafe regarding the GIL. QVariant toVariant(); //! Returns a PythonQtObjectPtr as a QVariant. Only use this when you know that the variant is only used locally and not stored outside of the current GIL scope. QVariant toLocalVariant(); PythonQtObjectPtr &operator=(const PythonQtObjectPtr &p) { setObject(p.object()); return *this; } //! rvalue assignment operator that steals the reference from p PythonQtObjectPtr &operator=(PythonQtObjectPtr &&p) { if (_object) { setObject(NULL); } _object = p.takeObject(); return *this; } //! rvalue assignment operator that steals the reference from p PythonQtObjectPtr &operator=(PythonQtSafeObjectPtr &&p); PythonQtObjectPtr &operator=(PyObject* o) { setObject(o); return *this; } PythonQtObjectPtr &operator=(const QVariant& variant) { fromVariant(variant); return *this; } bool operator==( const PythonQtObjectPtr &p ) const { return object() == p.object(); } bool operator!= ( const PythonQtObjectPtr& p ) const { return !( *this == p ); } bool operator==( PyObject* p ) const { return object() == p; } bool operator!= ( PyObject* p ) const { return object() != p; } bool isNull() const { return !object(); } PyObject* operator->() const { return object(); } PyObject& operator*() const { return *( object() ); } operator PyObject*() const { return object(); } //! sets the object and passes the ownership (stealing the reference, in Python slang) void setNewRef(PyObject* o); PyObject* object() const { return _object; } //! evaluates the given script code in the context of this object and returns the result value QVariant evalScript(const QString& script, int start = Py_file_input); //! evaluates the given code and returns the result value (use Py_Compile etc. to create pycode from string) //! If pycode is NULL, a python error is printed. QVariant evalCode(PyObject* pycode); //! evaluates the given code in the context void evalFile(const QString& filename); //! add the given \c object to the \c module as a variable with \c name (it can be removed via clearVariable) void addObject(const QString& name, QObject* object); //! add the given variable to the module void addVariable(const QString& name, const QVariant& v); //! remove the given variable void removeVariable(const QString& name); //! get the variable with the \c name of the \c module, returns an invalid QVariant on error QVariant getVariable(const QString& name); //! call the given python object (in the scope of the current object), returns the result converted to a QVariant QVariant call(const QString& callable, const QVariantList& args = QVariantList(), const QVariantMap& kwargs = QVariantMap()); //! call the contained python object directly, returns the result converted to a QVariant QVariant call(const QVariantList& args = QVariantList(), const QVariantMap& kwargs = QVariantMap()); //! takes the object from the pointer, leaving the pointer empty. //! the caller has to take care about the decref of the taken object! PyObject* takeObject() { PyObject* o = _object; _object = NULL; return o; } protected: void setObject(PyObject* o); private: PyObject* _object; }; //! a smart pointer that stores a PyObject pointer and that handles reference counting automatically class PYTHONQT_EXPORT PythonQtSafeObjectPtr { public: PythonQtSafeObjectPtr() :_object(NULL) {} PythonQtSafeObjectPtr(const PythonQtSafeObjectPtr &p) :_object(NULL) { setObject(p.object()); } PythonQtSafeObjectPtr(const PythonQtObjectPtr &p) :_object(NULL) { setObject(p.object()); } //! rvalue copy constructor, does not need any incref/decref. PythonQtSafeObjectPtr(PythonQtSafeObjectPtr &&p) :_object(p._object) { p._object = NULL; } //! rvalue copy constructor, does not need any incref/decref. PythonQtSafeObjectPtr(PythonQtObjectPtr &&p) :_object(p.takeObject()) { } PythonQtSafeObjectPtr(PyObject* o); ~PythonQtSafeObjectPtr(); PythonQtSafeObjectPtr &operator=(const PythonQtSafeObjectPtr &p) { setObject(p.object()); return *this; } PythonQtSafeObjectPtr &operator=(const PythonQtObjectPtr &p) { setObjectUnsafe(p.object()); return *this; } //! rvalue assignment operator that steals the reference from p PythonQtSafeObjectPtr &operator=(PythonQtSafeObjectPtr &&p) { if (_object) { setObject(NULL); } _object = p._object; p._object = NULL; return *this; } //! rvalue assignment operator that steals the reference from p PythonQtSafeObjectPtr &operator=(PythonQtObjectPtr &&p) { if (_object) { setObjectUnsafe(NULL); } _object = p.takeObject(); return *this; } PythonQtSafeObjectPtr &operator=(PyObject* o) { setObject(o); return *this; } bool operator==(const PythonQtSafeObjectPtr &p) const { return object() == p.object(); } bool operator!= (const PythonQtSafeObjectPtr& p) const { return !(*this == p); } bool operator==(PyObject* p) const { return object() == p; } bool operator!= (PyObject* p) const { return object() != p; } bool isNull() const { return !object(); } PyObject* operator->() const { return object(); } PyObject& operator*() const { return *(object()); } operator PyObject*() const { return object(); } PyObject* object() const { return _object; } //! takes the object from the pointer, leaving the pointer empty. //! the caller has to take care about the decref of the taken object! PyObject* takeObject() { PyObject* o = _object; _object = NULL; return o; } protected: void setObject(PyObject* o); void setObjectUnsafe(PyObject* o); private: PyObject* _object; }; // We don't want QVariant to take PythonQtObjectPtr via QVariant::fromValue, because it is unsafe when using multi-threading/GIL // A QVariant can still be obtained with PythonQtObjectPtr::toLocalVariant(). //Q_DECLARE_METATYPE(PythonQtObjectPtr) // register PythonQtSafeObjectPtr to the meta type system Q_DECLARE_METATYPE(PythonQtSafeObjectPtr) #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtProperty.h ================================================ #pragma once /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include #include #include extern PYTHONQT_EXPORT PyTypeObject PythonQtProperty_Type; #define PythonQtProperty_Check(op) (Py_TYPE(op) == &PythonQtProperty_Type) struct PythonQtPropertyData { PythonQtPropertyData() { fget = NULL; fset = NULL; fdel = NULL; freset = NULL; notify = NULL; doc = NULL; designable = true; scriptable = true; stored = true; user = false; constant = false; final = false; } //! Call the fset method in Python, bound to the wrapper object. //! Returns true if successful bool callSetter(PyObject* wrapper, PyObject* newValue); //! Call the fget method in Python, bound to the wrapper object. //! Returns the return value of the call (with a new ref). PyObject* callGetter(PyObject* wrapper); //! Call the freset method in Python, bound to the wrapper object. bool callReset(PyObject* wrapper); QByteArray cppType; PyObject* fget; PyObject* fset; PyObject* fdel; PyObject* freset; PyObject* notify; PyObject* doc; bool designable; bool scriptable; bool stored; bool user; bool constant; bool final; }; typedef struct { PyObject_HEAD PythonQtPropertyData* data; } PythonQtProperty; ================================================ FILE: thirdLibs/PythonQt/include/PythonQtPythonInclude.h ================================================ /* * * Copyright (C) 2011 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ #ifndef __PythonQtPythonInclude_h #define __PythonQtPythonInclude_h // Undefine macros that Python.h defines to avoid redefinition warning. #undef _POSIX_C_SOURCE #undef _POSIX_THREADS #undef _XOPEN_SOURCE // Undefine Qt keywords that conflict with Python headers #ifdef slots #undef slots #define PYTHONQT_RESTORE_KEYWORDS #endif // If PYTHONQT_USE_RELEASE_PYTHON_FALLBACK is enabled, try to link // release Python DLL if it is available by undefining _DEBUG while // including Python.h #if defined(PYTHONQT_USE_RELEASE_PYTHON_FALLBACK) && defined(_DEBUG) #undef _DEBUG #if defined(_MSC_VER) && _MSC_VER >= 1400 #define _CRT_NOFORCE_MANIFEST 1 #define _STL_NOFORCE_MANIFEST 1 #endif #include #define _DEBUG #else #include #endif // By including Python.h on Linux truncate could have been defined (in unistd.h) // which would lead to compiler errors. Therefore: #ifdef truncate # undef truncate #endif // get Qt keywords back #ifdef PYTHONQT_RESTORE_KEYWORDS #define slots Q_SLOTS #undef PYTHONQT_RESTORE_KEYWORDS #endif #if PY_MAJOR_VERSION >= 3 #define PY3K // Helper defines to facilitate porting #define PyString_FromString PyUnicode_FromString #define PyString_AS_STRING PyUnicode_AsUTF8 #define PyString_AsString PyUnicode_AsUTF8 #define PyString_FromFormat PyUnicode_FromFormat #define PyString_Check PyUnicode_Check #define PyInt_Type PyLong_Type #define PyInt_FromLong PyLong_FromLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_Check PyLong_Check #define PyInt_AsLong PyLong_AsLong #else // Defines to use Python 3 names in Python 2 code #define PyBytes_Type PyString_Type #define PyBytes_Check PyString_Check #define PyBytes_AS_STRING PyString_AS_STRING #define PyBytes_AsString PyString_AsString #define PyBytes_GET_SIZE PyString_GET_SIZE #define PyBytes_FromStringAndSize PyString_FromStringAndSize #endif #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtQFileImporter.h ================================================ #ifndef _PYTHONQTQFILEIMPORTER_H #define _PYTHONQTQFILEIMPORTER_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtQFileImporter.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2009-03 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include //! default importer implementation using QFile to load python code class PythonQtQFileImporter : public PythonQtImportFileInterface { public: PythonQtQFileImporter(); ~PythonQtQFileImporter(); QByteArray readFileAsBytes (const QString &filename); QByteArray readSourceFile (const QString &filename, bool &ok); bool exists (const QString &filename); bool isEggArchive(const QString& filename); QDateTime lastModifiedDate (const QString &filename); }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtSignal.h ================================================ #ifndef _PythonQtSignal_H #define _PythonQtSignal_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtSignal.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include "structmember.h" class PythonQtSlotInfo; extern PYTHONQT_EXPORT PyTypeObject PythonQtSignalFunction_Type; #define PythonQtSignalFunction_Check(op) (Py_TYPE(op) == &PythonQtSignalFunction_Type) PyObject* PythonQtSignalFunction_New(PythonQtSlotInfo *, PyObject *, PyObject *); struct PythonQtDynamicSignalInfo { QByteArray name; QList signatures; }; //! defines a python object that stores a Qt signal info typedef struct { PyObject_HEAD PythonQtSlotInfo *m_ml; /* Description of the C function to call */ PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */ PyObject *m_module; /* The __module__ attribute, can be anything */ PythonQtDynamicSignalInfo* _dynamicInfo; } PythonQtSignalFunctionObject; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtSignalReceiver.h ================================================ #ifndef _PYTHONQTSIGNALRECEIVER_H #define _PYTHONQTSIGNALRECEIVER_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtSignalReceiver.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include "PythonQtObjectPtr.h" class PythonQtMethodInfo; class PythonQtClassInfo; //! stores information about a signal target /*! copy construction and assignment works fine with the C++ standard behavior and are thus not implemented */ class PYTHONQT_EXPORT PythonQtSignalTarget { public: PythonQtSignalTarget() { _signalId = -1; _methodInfo = NULL; _slotId = -1; } PythonQtSignalTarget(int signalId,const PythonQtMethodInfo* methodInfo, int slotId, PyObject* callable) { _signalId = signalId; _slotId = slotId; _methodInfo = methodInfo; _callable = callable; }; ~PythonQtSignalTarget() { }; //! get the id of the original signal int signalId() const { return _signalId; } //! get the id that was assigned to this simulated slot int slotId() const { return _slotId; } //! get the signals parameter info const PythonQtMethodInfo* methodInfo() const { return _methodInfo; } //! call the python callable with the given arguments (as defined in methodInfo) void call(void **arguments) const; //! check if it is the same signal target bool isSame(int signalId, PyObject* callable) const; //! call the given callable with arguments described by PythonQtMethodInfo, returns a new reference as result value (or NULL) static PyObject* call(PyObject* callable, const PythonQtMethodInfo* methodInfo, void **arguments, bool skipFirstArgumentOfMethodInfo = false); private: int _signalId; int _slotId; const PythonQtMethodInfo* _methodInfo; PythonQtObjectPtr _callable; }; //! base class for signal receivers /*! */ class PythonQtSignalReceiverBase : public QObject { Q_OBJECT public: PythonQtSignalReceiverBase(QObject* obj):QObject(obj) {}; }; //! receives all signals for one QObject /*! we derive from our base but do not declare the QObject macro because we want to reimplement qt_metacall only. */ class PythonQtSignalReceiver : public PythonQtSignalReceiverBase { public: PythonQtSignalReceiver(QObject* obj); ~PythonQtSignalReceiver(); //! add a signal handler bool addSignalHandler(const char* signal, PyObject* callable); //! remove a signal handler for given callable (or all callables on that signal if callable is NULL) bool removeSignalHandler(const char* signal, PyObject* callable = NULL); //! we implement this method to simulate a number of slots that match the ids in _targets virtual int qt_metacall(QMetaObject::Call c, int id, void **arguments); private: //! get the index of the signal int getSignalIndex(const char* signal); QObject* _obj; PythonQtClassInfo* _objClassInfo; int _slotCount; int _destroyedSignalCount; // linear list may get slow on multiple targets, but I think typically we have many objects and just a few signals QList _targets; static int _destroyedSignal1Id; static int _destroyedSignal2Id; }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtSlot.h ================================================ #ifndef _PYTHONQTSLOT_H #define _PYTHONQTSLOT_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtSlot.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include "structmember.h" class PythonQtSlotInfo; enum PythonQtPassThisOwnershipType { IgnoreOwnership, PassOwnershipToCPP, PassOwnershipToPython }; extern PYTHONQT_EXPORT PyTypeObject PythonQtSlotFunction_Type; #define PythonQtSlotFunction_Check(op) (Py_TYPE(op) == &PythonQtSlotFunction_Type) PythonQtSlotInfo* PythonQtSlotFunction_GetSlotInfo(PyObject *); PyObject* PythonQtSlotFunction_GetSelf(PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PythonQtSlotFunction_GET_SELF(func) \ (((PythonQtSlotFunctionObject *)func) -> m_self) PyObject* PythonQtSlotFunction_Call(PyObject *, PyObject *, PyObject *); PyObject *PythonQtSlotFunction_CallImpl(PythonQtClassInfo* classInfo, QObject* objectToCall, PythonQtSlotInfo* info, PyObject *args, PyObject *kw, void* firstArg=NULL, void** directReturnValuePointer=NULL, PythonQtPassThisOwnershipType* passThisOwnershipToCPP = NULL); PyObject* PythonQtSlotFunction_New(PythonQtSlotInfo *, PyObject *, PyObject *); PyObject *PythonQtMemberFunction_Call(PythonQtSlotInfo* info, PyObject* m_self, PyObject *args, PyObject *kw); PyObject *PythonQtMemberFunction_parameterTypes(PythonQtSlotInfo* theInfo); PyObject *PythonQtMemberFunction_parameterNames(PythonQtSlotInfo* theInfo); PyObject *PythonQtMemberFunction_typeName(PythonQtSlotInfo* theInfo); //! defines a python object that stores a Qt slot info typedef struct { PyObject_HEAD PythonQtSlotInfo *m_ml; /* Description of the C function to call */ PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */ PyObject *m_module; /* The __module__ attribute, can be anything */ } PythonQtSlotFunctionObject; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtSlotDecorator.h ================================================ #pragma once /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include #include #include extern PYTHONQT_EXPORT PyTypeObject PythonQtSlotDecorator_Type; #define PythonQtSlotDecorator_Check(op) (Py_TYPE(op) == &PythonQtSlotDecorator_Type) typedef struct { PyObject_HEAD QByteArray* args; QByteArray* returnType; } PythonQtSlotDecorator; ================================================ FILE: thirdLibs/PythonQt/include/PythonQtStdDecorators.h ================================================ #ifndef _PYTHONQTSTDDECORATORS_H #define _PYTHONQTSTDDECORATORS_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtStdDecorators.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2007-04 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQt.h" #include #include #include #include #include #include #include #include #include #include #include #include class PYTHONQT_EXPORT PythonQtStdDecorators : public QObject { Q_OBJECT public Q_SLOTS: bool connect(QObject* sender, const QByteArray& signal, PyObject* callable); bool connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot, Qt::ConnectionType type = Qt::AutoConnection); bool connect(QObject* receiver, QObject* sender, const QByteArray& signal, const QByteArray& slot, Qt::ConnectionType type = Qt::AutoConnection) { return connect(sender, signal, receiver, slot, type); } bool static_QObject_connect(QObject* sender, const QByteArray& signal, PyObject* callable) { return connect(sender, signal, callable); } bool static_QObject_connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot, Qt::ConnectionType type = Qt::AutoConnection) { return connect(sender, signal, receiver, slot, type); } bool disconnect(QObject* sender, const QByteArray& signal, PyObject* callable = NULL); bool disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot); bool static_QObject_disconnect(QObject* sender, const QByteArray& signal, PyObject* callable = NULL) { return disconnect(sender, signal, callable); } bool static_QObject_disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot) { return disconnect(sender, signal, receiver, slot); } const QMetaObject* metaObject( QObject* obj ); QObject* parent(QObject* o); void setParent(QObject* o, PythonQtNewOwnerOfThis parent); const QObjectList* children(QObject* o); QObject* findChild(QObject* parent, PyObject* type, const QString& name = QString()); QList findChildren(QObject* parent, PyObject* type, const QString& name= QString()); QList findChildren(QObject* parent, PyObject* type, const QRegExp& regExp); bool setProperty(QObject* o, const char* name, const QVariant& value); QVariant property(QObject* o, const char* name); double static_Qt_qAbs(double a) { return qAbs(a); } double static_Qt_qBound(double a,double b,double c) { return qBound(a,b,c); } void static_Qt_qDebug(const QByteArray& msg) { qDebug("%s", msg.constData()); } // TODO: multi arg qDebug... void static_Qt_qWarning(const QByteArray& msg) { qWarning("%s", msg.constData()); } // TODO: multi arg qWarning... void static_Qt_qCritical(const QByteArray& msg) { qCritical("%s", msg.constData()); } // TODO: multi arg qCritical... void static_Qt_qFatal(const QByteArray& msg) { qFatal("%s", msg.constData()); } // TODO: multi arg qFatal... bool static_Qt_qFuzzyCompare(double a, double b) { return qFuzzyCompare(a, b); } double static_Qt_qMax(double a, double b) { return qMax(a, b); } double static_Qt_qMin(double a, double b) { return qMin(a, b); } int static_Qt_qRound(double a) { return qRound(a); } qint64 static_Qt_qRound64(double a) { return qRound64(a); } const char* static_Qt_qVersion() { return qVersion(); } int static_Qt_qrand() { return qrand(); } void static_Qt_qsrand(uint a) { qsrand(a); } QString tr(QObject* obj, const QString& text, const QString& ambig = QString(), int n = -1); QString static_Qt_SIGNAL(const QString& s) { return QString("2") + s; } QString static_Qt_SLOT(const QString& s) { return QString("1") + s; } void static_QTimer_singleShot(int msec, PyObject* callable); private: QObject* findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name); int findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList& list); int findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList& list); }; class PythonQtSingleShotTimer : public QTimer { Q_OBJECT public: PythonQtSingleShotTimer(int msec, const PythonQtObjectPtr& callable); public Q_SLOTS : void slotTimeout(); private: PythonQtObjectPtr _callable; }; class PythonQtWrapper_QMetaObject : public QObject { Q_OBJECT public Q_SLOTS: // Python 3: PythonQt shadows className, so we need an extra getClassName method... const char *getClassName(QMetaObject* obj) const { return obj->className(); } const QMetaObject *superClass(QMetaObject* obj) const { return obj->superClass(); } int methodOffset(QMetaObject* obj) const { return obj->methodOffset(); } int enumeratorOffset(QMetaObject* obj) const { return obj->enumeratorOffset(); } int propertyOffset(QMetaObject* obj) const { return obj->propertyOffset(); } int classInfoOffset(QMetaObject* obj) const { return obj->classInfoOffset(); } int constructorCount(QMetaObject* obj) const { return obj->constructorCount(); } int methodCount(QMetaObject* obj) const { return obj->methodCount(); } int enumeratorCount(QMetaObject* obj) const { return obj->enumeratorCount(); } int propertyCount(QMetaObject* obj) const { return obj->propertyCount(); } int classInfoCount(QMetaObject* obj) const { return obj->classInfoCount(); } int indexOfConstructor(QMetaObject* obj, const char *constructor) const { return obj->indexOfConstructor(constructor); } int indexOfMethod(QMetaObject* obj, const char *method) const { return obj->indexOfMethod(method); } int indexOfSignal(QMetaObject* obj, const char *signal) const { return obj->indexOfSignal(signal); } int indexOfSlot(QMetaObject* obj, const char *slot) const { return obj->indexOfSlot(slot); } int indexOfEnumerator(QMetaObject* obj, const char *name) const { return obj->indexOfEnumerator(name); } int indexOfProperty(QMetaObject* obj, const char *name) const { return obj->indexOfProperty(name); } int indexOfClassInfo(QMetaObject* obj, const char *name) const { return obj->indexOfClassInfo(name); } QMetaMethod constructor(QMetaObject* obj, int index) const { return obj->constructor(index); } QMetaMethod method(QMetaObject* obj, int index) const { return obj->method(index); } QMetaEnum enumerator(QMetaObject* obj, int index) const { return obj->enumerator(index); } QMetaProperty property(QMetaObject* obj, int index) const { return obj->property(index); } QMetaClassInfo classInfo(QMetaObject* obj, int index) const { return obj->classInfo(index); } QMetaProperty userProperty(QMetaObject* obj) const { return obj->userProperty(); } bool static_QMetaObject_checkConnectArgs(const char *signal, const char *method) { return QMetaObject::checkConnectArgs(signal, method); } QByteArray static_QMetaObject_normalizedSignature(const char *method) { return QMetaObject::normalizedSignature(method); } QByteArray static_QMetaObject_normalizedType(const char *type) { return QMetaObject::normalizedType(type); } }; //! Some helper methods that allow testing of the ownership class PYTHONQT_EXPORT PythonQtDebugAPI : public QObject { Q_OBJECT public: PythonQtDebugAPI(QObject* parent):QObject(parent) {}; public slots: //! Returns if the C++ object is owned by PythonQt and will be deleted when the reference goes away. bool isOwnedByPython(PyObject* object); //! Returns if the C++ object is an instance of a Python class that derives a C++ class. bool isDerivedShellInstance(PyObject* object); //! Returns if the shell instance has an extra ref count from the C++ side. bool hasExtraShellRefCount(PyObject* object); //! Pass the ownership of the given object to CPP (so that it will not be deleted by Python if the reference goes away) bool passOwnershipToCPP(PyObject* object); //! Pass the ownership of the given object to Python (so that the C++ object will be deleted when the Python reference goes away) bool passOwnershipToPython(PyObject* object); //! Returns if the given object is a PythonQt instance wrapper (or derived class) bool isPythonQtInstanceWrapper(PyObject* object); //! Returns if the given object is a PythonQt class wrapper (or derived class) bool isPythonQtClassWrapper(PyObject* object); }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtStdIn.h ================================================ #ifndef _PYTHONQTSTDIN_H #define _PYTHONQTSTDIN_H /* * * Copyright (C) 2011 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtStdIn.h // \author Jean-Christophe Fillion-Robin // \author Last changed by $Author: jcfr $ // \date 2011 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "structmember.h" #include //! declares the type of the stdout redirection class extern PyTypeObject PythonQtStdInRedirectType; //! declares the callback that is called from the write() function typedef QString PythonQtInputChangedCB(void* callData); //! declares the stdin redirection class typedef struct { PyObject_HEAD PythonQtInputChangedCB* _cb; void * _callData; } PythonQtStdInRedirect; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtStdOut.h ================================================ #ifndef _PYTHONQTSTDOUT_H #define _PYTHONQTSTDOUT_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtStdOut.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "structmember.h" #include //! declares the type of the stdout redirection class extern PyTypeObject PythonQtStdOutRedirectType; //! declares the callback that is called from the write() function typedef void PythonQtOutputChangedCB(const QString& str); //! declares the stdout redirection class typedef struct { PyObject_HEAD PythonQtOutputChangedCB* _cb; int softspace; bool closed; } PythonQtStdOutRedirect; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtSystem.h ================================================ #ifndef _PYTHONQTSYSTEM_ #define _PYTHONQTSYSTEM_ /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtSystem.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-05 */ //---------------------------------------------------------------------------------- #ifdef WIN32 #ifdef PYTHONQT_EXPORTS #define PYTHONQT_EXPORT __declspec(dllexport) #else #define PYTHONQT_EXPORT __declspec(dllimport) #endif #else #define PYTHONQT_EXPORT #endif #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtThreadSupport.h ================================================ #pragma once /* * * Copyright (C) 2018 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtThreadSupport.h // \author Florian Link // \date 2018-08 */ //---------------------------------------------------------------------------------- #include #include #define PYTHONQT_FULL_THREAD_SUPPORT #ifdef PYTHONQT_FULL_THREAD_SUPPORT #define PYTHONQT_GIL_SUPPORT #define PYTHONQT_ALLOW_THREADS_SUPPORT #endif #ifdef PYTHONQT_GIL_SUPPORT #define PYTHONQT_GIL_SCOPE PythonQtGILScope internal_pythonqt_gilscope; //! Ensures/releases the Python GIL //! An instance of this class can be used to //! allow access to the Python API from C++ code. class PYTHONQT_EXPORT PythonQtGILScope { public: PythonQtGILScope(); ~PythonQtGILScope(); void release(); //! This allows to globally enable/disable the GIL scopes. //! Make sure to only call this early in the PythonQt setup, or //! when you are holding the GIL. static void setGILScopeEnabled(bool flag); //! Check if GIL scopes are enabled. static bool isGILScopeEnabled(); private: PyGILState_STATE _state; bool _ensured; static bool _enableGILScope; }; #else #define PYTHONQT_GIL_SCOPE //! Empty dummy implementation. class PythonQtGILScope { public: PythonQtGILScope() {} void release() {} }; #endif #ifdef PYTHONQT_ALLOW_THREADS_SUPPORT #define PYTHONQT_ALLOW_THREADS_SCOPE PythonQtThreadStateSaver internal_pythonqt_savethread; //! This class wraps the Python save/restore thread state API. //! It can be used to allow other Python threads to run when entering C++ code //! from Python code. class PythonQtThreadStateSaver { public: PythonQtThreadStateSaver() { save(); } ~PythonQtThreadStateSaver() { restore(); } void save() { _state = PyEval_SaveThread(); } void restore() { if (_state) { PyEval_RestoreThread(_state); _state = NULL; } } private: PyThreadState* _state; }; #else #define PYTHONQT_ALLOW_THREADS_SCOPE //! Empty dummy implementation. class PythonQtThreadStateSaver { public: PythonQtThreadStateSaver() {}; void save() {} void restore() {} }; #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtUtils.h ================================================ #ifndef _PYTHONQTUTILS_H #define _PYTHONQTUTILS_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtUtils.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2014-09 */ //---------------------------------------------------------------------------------- #include "PythonQtPythonInclude.h" #include "PythonQtSystem.h" #include #include namespace PythonQtUtils { inline QByteArray signature(const QMetaMethod& method) { #if( QT_VERSION >= QT_VERSION_CHECK(5,0,0) ) return method.methodSignature(); #else return QByteArray(method.signature()); #endif } inline QByteArray methodName(const QMetaMethod& method) { #if( QT_VERSION >= QT_VERSION_CHECK(5,0,0) ) return method.name(); #else QByteArray sig(method.signature()); int idx = sig.indexOf('('); sig = sig.left(idx); return sig; #endif } inline QByteArray typeName(const QMetaMethod& method) { #if( QT_VERSION >= QT_VERSION_CHECK(5,0,0) ) QByteArray result = method.typeName(); if (result == "void") { return QByteArray(); } else { return result; } #else return method.typeName(); #endif } //! Returns of the python object is a class type inline bool isPythonClassType(PyObject* obj) { #ifdef PY3K return PyType_Check(obj); #else // support old-style classes and new style classes return (obj->ob_type == &PyClass_Type || obj->ob_type == &PyType_Type); #endif } } #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQtVariants.h ================================================ #ifndef _PYTHONQTVARIANTS_ #define _PYTHONQTVARIANTS_ /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtVariants.h // \author Florian Link // \author Last changed by $Author: stk $ // \date 2006-08 */ //---------------------------------------------------------------------------------- #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #endif ================================================ FILE: thirdLibs/PythonQt/include/PythonQt_QtAll.h ================================================ #ifndef _PYTHONQT_QTALL_H #define _PYTHONQT_QTALL_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ #ifdef WIN32 #ifdef PYTHONQT_QTALL_EXPORTS #define PYTHONQT_QTALL_EXPORT __declspec(dllexport) #else #define PYTHONQT_QTALL_EXPORT __declspec(dllimport) #endif #else #define PYTHONQT_QTALL_EXPORT #endif namespace PythonQt_QtAll { //! initialize the Qt binding PYTHONQT_QTALL_EXPORT void init(); }; #endif ================================================ FILE: thirdLibs/PythonQt/include/gui/PythonQtScriptingConsole.h ================================================ #ifndef _PythonQtScriptingConsole_H #define _PythonQtScriptingConsole_H /* * * Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved. * * This library 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: MeVis Medical Solutions AG, Universitaetsallee 29, * 28359 Bremen, Germany or: * * http://www.mevis.de * */ //---------------------------------------------------------------------------------- /*! // \file PythonQtScriptingConsole.h // \author Florian Link // \author Last changed by $Author: florian $ // \date 2006-10 */ //---------------------------------------------------------------------------------- #include "PythonQt.h" #include #include class QCompleter; //------------------------------------------------------------------------------- //! A simple console for python scripting class PYTHONQT_EXPORT PythonQtScriptingConsole : public QTextEdit { Q_OBJECT public: PythonQtScriptingConsole(QWidget* parent, const PythonQtObjectPtr& context, Qt::WindowFlags i = 0); ~PythonQtScriptingConsole(); public Q_SLOTS: //! execute current line void executeLine(bool storeOnly); //! derived key press event void keyPressEvent (QKeyEvent * e); //! output from console void consoleMessage(const QString & message); //! get history QStringList history() { return _history; } //! set history void setHistory(const QStringList& h) { _history = h; _historyPosition = 0; } //! clear the console void clear(); //! overridden to control which characters a user may delete virtual void cut(); //! output redirection void stdOut(const QString& s); //! output redirection void stdErr(const QString& s); void insertCompletion(const QString&); //! Appends a newline and command prompt at the end of the document. void appendCommandPrompt(bool storeOnly = false); public: //! returns true if python cerr had an error bool hadError() { return _hadError; } //! returns true if python cerr had an error void clearError() { _hadError = false; } protected: //! handle the pressing of tab void handleTabCompletion(); //! Returns the position of the command prompt int commandPromptPosition(); //! Returns if deletion is allowed at the current cursor //! (with and without selected text) bool verifySelectionBeforeDeletion(); //! Sets the current font void setCurrentFont(const QColor& color = QColor(0,0,0), bool bold = false); //! change the history according to _historyPos void changeHistory(); //! flush output that was not yet printed void flushStdOut(); private: void executeCode(const QString& code); PythonQtObjectPtr _context; QStringList _history; int _historyPosition; QString _clickedAnchor; QString _storageKey; QString _commandPrompt; QString _currentMultiLineCode; QString _stdOut; QString _stdErr; QTextCharFormat _defaultTextCharacterFormat; QCompleter* _completer; bool _hadError; }; #endif ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/ac3_parser.h ================================================ /* * AC-3 parser prototypes * Copyright (c) 2003 Fabrice Bellard * Copyright (c) 2003 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_AC3_PARSER_H #define AVCODEC_AC3_PARSER_H #include #include /** * Extract the bitstream ID and the frame size from AC-3 data. */ int av_ac3_parse_header(const uint8_t *buf, size_t size, uint8_t *bitstream_id, uint16_t *frame_size); #endif /* AVCODEC_AC3_PARSER_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/adts_parser.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_ADTS_PARSER_H #define AVCODEC_ADTS_PARSER_H #include #include #define AV_AAC_ADTS_HEADER_SIZE 7 /** * Extract the number of samples and frames from AAC data. * @param[in] buf pointer to AAC data buffer * @param[out] samples Pointer to where number of samples is written * @param[out] frames Pointer to where number of frames is written * @return Returns 0 on success, error code on failure. */ int av_adts_header_parse(const uint8_t *buf, uint32_t *samples, uint8_t *frames); #endif /* AVCODEC_ADTS_PARSER_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/avcodec.h ================================================ /* * copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_AVCODEC_H #define AVCODEC_AVCODEC_H /** * @file * @ingroup libavc * Libavcodec external API header */ #include #include "libavutil/samplefmt.h" #include "libavutil/attributes.h" #include "libavutil/avutil.h" #include "libavutil/buffer.h" #include "libavutil/cpu.h" #include "libavutil/channel_layout.h" #include "libavutil/dict.h" #include "libavutil/frame.h" #include "libavutil/hwcontext.h" #include "libavutil/log.h" #include "libavutil/pixfmt.h" #include "libavutil/rational.h" #include "version.h" /** * @defgroup libavc libavcodec * Encoding/Decoding Library * * @{ * * @defgroup lavc_decoding Decoding * @{ * @} * * @defgroup lavc_encoding Encoding * @{ * @} * * @defgroup lavc_codec Codecs * @{ * @defgroup lavc_codec_native Native Codecs * @{ * @} * @defgroup lavc_codec_wrappers External library wrappers * @{ * @} * @defgroup lavc_codec_hwaccel Hardware Accelerators bridge * @{ * @} * @} * @defgroup lavc_internal Internal * @{ * @} * @} */ /** * @ingroup libavc * @defgroup lavc_encdec send/receive encoding and decoding API overview * @{ * * The avcodec_send_packet()/avcodec_receive_frame()/avcodec_send_frame()/ * avcodec_receive_packet() functions provide an encode/decode API, which * decouples input and output. * * The API is very similar for encoding/decoding and audio/video, and works as * follows: * - Set up and open the AVCodecContext as usual. * - Send valid input: * - For decoding, call avcodec_send_packet() to give the decoder raw * compressed data in an AVPacket. * - For encoding, call avcodec_send_frame() to give the encoder an AVFrame * containing uncompressed audio or video. * In both cases, it is recommended that AVPackets and AVFrames are * refcounted, or libavcodec might have to copy the input data. (libavformat * always returns refcounted AVPackets, and av_frame_get_buffer() allocates * refcounted AVFrames.) * - Receive output in a loop. Periodically call one of the avcodec_receive_*() * functions and process their output: * - For decoding, call avcodec_receive_frame(). On success, it will return * an AVFrame containing uncompressed audio or video data. * - For encoding, call avcodec_receive_packet(). On success, it will return * an AVPacket with a compressed frame. * Repeat this call until it returns AVERROR(EAGAIN) or an error. The * AVERROR(EAGAIN) return value means that new input data is required to * return new output. In this case, continue with sending input. For each * input frame/packet, the codec will typically return 1 output frame/packet, * but it can also be 0 or more than 1. * * At the beginning of decoding or encoding, the codec might accept multiple * input frames/packets without returning a frame, until its internal buffers * are filled. This situation is handled transparently if you follow the steps * outlined above. * * In theory, sending input can result in EAGAIN - this should happen only if * not all output was received. You can use this to structure alternative decode * or encode loops other than the one suggested above. For example, you could * try sending new input on each iteration, and try to receive output if that * returns EAGAIN. * * End of stream situations. These require "flushing" (aka draining) the codec, * as the codec might buffer multiple frames or packets internally for * performance or out of necessity (consider B-frames). * This is handled as follows: * - Instead of valid input, send NULL to the avcodec_send_packet() (decoding) * or avcodec_send_frame() (encoding) functions. This will enter draining * mode. * - Call avcodec_receive_frame() (decoding) or avcodec_receive_packet() * (encoding) in a loop until AVERROR_EOF is returned. The functions will * not return AVERROR(EAGAIN), unless you forgot to enter draining mode. * - Before decoding can be resumed again, the codec has to be reset with * avcodec_flush_buffers(). * * Using the API as outlined above is highly recommended. But it is also * possible to call functions outside of this rigid schema. For example, you can * call avcodec_send_packet() repeatedly without calling * avcodec_receive_frame(). In this case, avcodec_send_packet() will succeed * until the codec's internal buffer has been filled up (which is typically of * size 1 per output frame, after initial input), and then reject input with * AVERROR(EAGAIN). Once it starts rejecting input, you have no choice but to * read at least some output. * * Not all codecs will follow a rigid and predictable dataflow; the only * guarantee is that an AVERROR(EAGAIN) return value on a send/receive call on * one end implies that a receive/send call on the other end will succeed, or * at least will not fail with AVERROR(EAGAIN). In general, no codec will * permit unlimited buffering of input or output. * * This API replaces the following legacy functions: * - avcodec_decode_video2() and avcodec_decode_audio4(): * Use avcodec_send_packet() to feed input to the decoder, then use * avcodec_receive_frame() to receive decoded frames after each packet. * Unlike with the old video decoding API, multiple frames might result from * a packet. For audio, splitting the input packet into frames by partially * decoding packets becomes transparent to the API user. You never need to * feed an AVPacket to the API twice (unless it is rejected with AVERROR(EAGAIN) - then * no data was read from the packet). * Additionally, sending a flush/draining packet is required only once. * - avcodec_encode_video2()/avcodec_encode_audio2(): * Use avcodec_send_frame() to feed input to the encoder, then use * avcodec_receive_packet() to receive encoded packets. * Providing user-allocated buffers for avcodec_receive_packet() is not * possible. * - The new API does not handle subtitles yet. * * Mixing new and old function calls on the same AVCodecContext is not allowed, * and will result in undefined behavior. * * Some codecs might require using the new API; using the old API will return * an error when calling it. All codecs support the new API. * * A codec is not allowed to return AVERROR(EAGAIN) for both sending and receiving. This * would be an invalid state, which could put the codec user into an endless * loop. The API has no concept of time either: it cannot happen that trying to * do avcodec_send_packet() results in AVERROR(EAGAIN), but a repeated call 1 second * later accepts the packet (with no other receive/flush API calls involved). * The API is a strict state machine, and the passage of time is not supposed * to influence it. Some timing-dependent behavior might still be deemed * acceptable in certain cases. But it must never result in both send/receive * returning EAGAIN at the same time at any point. It must also absolutely be * avoided that the current state is "unstable" and can "flip-flop" between * the send/receive APIs allowing progress. For example, it's not allowed that * the codec randomly decides that it actually wants to consume a packet now * instead of returning a frame, after it just returned AVERROR(EAGAIN) on an * avcodec_send_packet() call. * @} */ /** * @defgroup lavc_core Core functions/structures. * @ingroup libavc * * Basic definitions, functions for querying libavcodec capabilities, * allocating core structures, etc. * @{ */ /** * Identify the syntax and semantics of the bitstream. * The principle is roughly: * Two decoders with the same ID can decode the same streams. * Two encoders with the same ID can encode compatible streams. * There may be slight deviations from the principle due to implementation * details. * * If you add a codec ID to this list, add it so that * 1. no value of an existing codec ID changes (that would break ABI), * 2. it is as close as possible to similar codecs * * After adding new codec IDs, do not forget to add an entry to the codec * descriptor list and bump libavcodec minor version. */ enum AVCodecID { AV_CODEC_ID_NONE, /* video codecs */ AV_CODEC_ID_MPEG1VIDEO, AV_CODEC_ID_MPEG2VIDEO, ///< preferred ID for MPEG-1/2 video decoding AV_CODEC_ID_H261, AV_CODEC_ID_H263, AV_CODEC_ID_RV10, AV_CODEC_ID_RV20, AV_CODEC_ID_MJPEG, AV_CODEC_ID_MJPEGB, AV_CODEC_ID_LJPEG, AV_CODEC_ID_SP5X, AV_CODEC_ID_JPEGLS, AV_CODEC_ID_MPEG4, AV_CODEC_ID_RAWVIDEO, AV_CODEC_ID_MSMPEG4V1, AV_CODEC_ID_MSMPEG4V2, AV_CODEC_ID_MSMPEG4V3, AV_CODEC_ID_WMV1, AV_CODEC_ID_WMV2, AV_CODEC_ID_H263P, AV_CODEC_ID_H263I, AV_CODEC_ID_FLV1, AV_CODEC_ID_SVQ1, AV_CODEC_ID_SVQ3, AV_CODEC_ID_DVVIDEO, AV_CODEC_ID_HUFFYUV, AV_CODEC_ID_CYUV, AV_CODEC_ID_H264, AV_CODEC_ID_INDEO3, AV_CODEC_ID_VP3, AV_CODEC_ID_THEORA, AV_CODEC_ID_ASV1, AV_CODEC_ID_ASV2, AV_CODEC_ID_FFV1, AV_CODEC_ID_4XM, AV_CODEC_ID_VCR1, AV_CODEC_ID_CLJR, AV_CODEC_ID_MDEC, AV_CODEC_ID_ROQ, AV_CODEC_ID_INTERPLAY_VIDEO, AV_CODEC_ID_XAN_WC3, AV_CODEC_ID_XAN_WC4, AV_CODEC_ID_RPZA, AV_CODEC_ID_CINEPAK, AV_CODEC_ID_WS_VQA, AV_CODEC_ID_MSRLE, AV_CODEC_ID_MSVIDEO1, AV_CODEC_ID_IDCIN, AV_CODEC_ID_8BPS, AV_CODEC_ID_SMC, AV_CODEC_ID_FLIC, AV_CODEC_ID_TRUEMOTION1, AV_CODEC_ID_VMDVIDEO, AV_CODEC_ID_MSZH, AV_CODEC_ID_ZLIB, AV_CODEC_ID_QTRLE, AV_CODEC_ID_TSCC, AV_CODEC_ID_ULTI, AV_CODEC_ID_QDRAW, AV_CODEC_ID_VIXL, AV_CODEC_ID_QPEG, AV_CODEC_ID_PNG, AV_CODEC_ID_PPM, AV_CODEC_ID_PBM, AV_CODEC_ID_PGM, AV_CODEC_ID_PGMYUV, AV_CODEC_ID_PAM, AV_CODEC_ID_FFVHUFF, AV_CODEC_ID_RV30, AV_CODEC_ID_RV40, AV_CODEC_ID_VC1, AV_CODEC_ID_WMV3, AV_CODEC_ID_LOCO, AV_CODEC_ID_WNV1, AV_CODEC_ID_AASC, AV_CODEC_ID_INDEO2, AV_CODEC_ID_FRAPS, AV_CODEC_ID_TRUEMOTION2, AV_CODEC_ID_BMP, AV_CODEC_ID_CSCD, AV_CODEC_ID_MMVIDEO, AV_CODEC_ID_ZMBV, AV_CODEC_ID_AVS, AV_CODEC_ID_SMACKVIDEO, AV_CODEC_ID_NUV, AV_CODEC_ID_KMVC, AV_CODEC_ID_FLASHSV, AV_CODEC_ID_CAVS, AV_CODEC_ID_JPEG2000, AV_CODEC_ID_VMNC, AV_CODEC_ID_VP5, AV_CODEC_ID_VP6, AV_CODEC_ID_VP6F, AV_CODEC_ID_TARGA, AV_CODEC_ID_DSICINVIDEO, AV_CODEC_ID_TIERTEXSEQVIDEO, AV_CODEC_ID_TIFF, AV_CODEC_ID_GIF, AV_CODEC_ID_DXA, AV_CODEC_ID_DNXHD, AV_CODEC_ID_THP, AV_CODEC_ID_SGI, AV_CODEC_ID_C93, AV_CODEC_ID_BETHSOFTVID, AV_CODEC_ID_PTX, AV_CODEC_ID_TXD, AV_CODEC_ID_VP6A, AV_CODEC_ID_AMV, AV_CODEC_ID_VB, AV_CODEC_ID_PCX, AV_CODEC_ID_SUNRAST, AV_CODEC_ID_INDEO4, AV_CODEC_ID_INDEO5, AV_CODEC_ID_MIMIC, AV_CODEC_ID_RL2, AV_CODEC_ID_ESCAPE124, AV_CODEC_ID_DIRAC, AV_CODEC_ID_BFI, AV_CODEC_ID_CMV, AV_CODEC_ID_MOTIONPIXELS, AV_CODEC_ID_TGV, AV_CODEC_ID_TGQ, AV_CODEC_ID_TQI, AV_CODEC_ID_AURA, AV_CODEC_ID_AURA2, AV_CODEC_ID_V210X, AV_CODEC_ID_TMV, AV_CODEC_ID_V210, AV_CODEC_ID_DPX, AV_CODEC_ID_MAD, AV_CODEC_ID_FRWU, AV_CODEC_ID_FLASHSV2, AV_CODEC_ID_CDGRAPHICS, AV_CODEC_ID_R210, AV_CODEC_ID_ANM, AV_CODEC_ID_BINKVIDEO, AV_CODEC_ID_IFF_ILBM, #define AV_CODEC_ID_IFF_BYTERUN1 AV_CODEC_ID_IFF_ILBM AV_CODEC_ID_KGV1, AV_CODEC_ID_YOP, AV_CODEC_ID_VP8, AV_CODEC_ID_PICTOR, AV_CODEC_ID_ANSI, AV_CODEC_ID_A64_MULTI, AV_CODEC_ID_A64_MULTI5, AV_CODEC_ID_R10K, AV_CODEC_ID_MXPEG, AV_CODEC_ID_LAGARITH, AV_CODEC_ID_PRORES, AV_CODEC_ID_JV, AV_CODEC_ID_DFA, AV_CODEC_ID_WMV3IMAGE, AV_CODEC_ID_VC1IMAGE, AV_CODEC_ID_UTVIDEO, AV_CODEC_ID_BMV_VIDEO, AV_CODEC_ID_VBLE, AV_CODEC_ID_DXTORY, AV_CODEC_ID_V410, AV_CODEC_ID_XWD, AV_CODEC_ID_CDXL, AV_CODEC_ID_XBM, AV_CODEC_ID_ZEROCODEC, AV_CODEC_ID_MSS1, AV_CODEC_ID_MSA1, AV_CODEC_ID_TSCC2, AV_CODEC_ID_MTS2, AV_CODEC_ID_CLLC, AV_CODEC_ID_MSS2, AV_CODEC_ID_VP9, AV_CODEC_ID_AIC, AV_CODEC_ID_ESCAPE130, AV_CODEC_ID_G2M, AV_CODEC_ID_WEBP, AV_CODEC_ID_HNM4_VIDEO, AV_CODEC_ID_HEVC, #define AV_CODEC_ID_H265 AV_CODEC_ID_HEVC AV_CODEC_ID_FIC, AV_CODEC_ID_ALIAS_PIX, AV_CODEC_ID_BRENDER_PIX, AV_CODEC_ID_PAF_VIDEO, AV_CODEC_ID_EXR, AV_CODEC_ID_VP7, AV_CODEC_ID_SANM, AV_CODEC_ID_SGIRLE, AV_CODEC_ID_MVC1, AV_CODEC_ID_MVC2, AV_CODEC_ID_HQX, AV_CODEC_ID_TDSC, AV_CODEC_ID_HQ_HQA, AV_CODEC_ID_HAP, AV_CODEC_ID_DDS, AV_CODEC_ID_DXV, AV_CODEC_ID_SCREENPRESSO, AV_CODEC_ID_RSCC, AV_CODEC_ID_AVS2, AV_CODEC_ID_Y41P = 0x8000, AV_CODEC_ID_AVRP, AV_CODEC_ID_012V, AV_CODEC_ID_AVUI, AV_CODEC_ID_AYUV, AV_CODEC_ID_TARGA_Y216, AV_CODEC_ID_V308, AV_CODEC_ID_V408, AV_CODEC_ID_YUV4, AV_CODEC_ID_AVRN, AV_CODEC_ID_CPIA, AV_CODEC_ID_XFACE, AV_CODEC_ID_SNOW, AV_CODEC_ID_SMVJPEG, AV_CODEC_ID_APNG, AV_CODEC_ID_DAALA, AV_CODEC_ID_CFHD, AV_CODEC_ID_TRUEMOTION2RT, AV_CODEC_ID_M101, AV_CODEC_ID_MAGICYUV, AV_CODEC_ID_SHEERVIDEO, AV_CODEC_ID_YLC, AV_CODEC_ID_PSD, AV_CODEC_ID_PIXLET, AV_CODEC_ID_SPEEDHQ, AV_CODEC_ID_FMVC, AV_CODEC_ID_SCPR, AV_CODEC_ID_CLEARVIDEO, AV_CODEC_ID_XPM, AV_CODEC_ID_AV1, AV_CODEC_ID_BITPACKED, AV_CODEC_ID_MSCC, AV_CODEC_ID_SRGC, AV_CODEC_ID_SVG, AV_CODEC_ID_GDV, AV_CODEC_ID_FITS, AV_CODEC_ID_IMM4, AV_CODEC_ID_PROSUMER, AV_CODEC_ID_MWSC, AV_CODEC_ID_WCMV, AV_CODEC_ID_RASC, AV_CODEC_ID_HYMT, AV_CODEC_ID_ARBC, AV_CODEC_ID_AGM, AV_CODEC_ID_LSCR, AV_CODEC_ID_VP4, /* various PCM "codecs" */ AV_CODEC_ID_FIRST_AUDIO = 0x10000, ///< A dummy id pointing at the start of audio codecs AV_CODEC_ID_PCM_S16LE = 0x10000, AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_U16LE, AV_CODEC_ID_PCM_U16BE, AV_CODEC_ID_PCM_S8, AV_CODEC_ID_PCM_U8, AV_CODEC_ID_PCM_MULAW, AV_CODEC_ID_PCM_ALAW, AV_CODEC_ID_PCM_S32LE, AV_CODEC_ID_PCM_S32BE, AV_CODEC_ID_PCM_U32LE, AV_CODEC_ID_PCM_U32BE, AV_CODEC_ID_PCM_S24LE, AV_CODEC_ID_PCM_S24BE, AV_CODEC_ID_PCM_U24LE, AV_CODEC_ID_PCM_U24BE, AV_CODEC_ID_PCM_S24DAUD, AV_CODEC_ID_PCM_ZORK, AV_CODEC_ID_PCM_S16LE_PLANAR, AV_CODEC_ID_PCM_DVD, AV_CODEC_ID_PCM_F32BE, AV_CODEC_ID_PCM_F32LE, AV_CODEC_ID_PCM_F64BE, AV_CODEC_ID_PCM_F64LE, AV_CODEC_ID_PCM_BLURAY, AV_CODEC_ID_PCM_LXF, AV_CODEC_ID_S302M, AV_CODEC_ID_PCM_S8_PLANAR, AV_CODEC_ID_PCM_S24LE_PLANAR, AV_CODEC_ID_PCM_S32LE_PLANAR, AV_CODEC_ID_PCM_S16BE_PLANAR, AV_CODEC_ID_PCM_S64LE = 0x10800, AV_CODEC_ID_PCM_S64BE, AV_CODEC_ID_PCM_F16LE, AV_CODEC_ID_PCM_F24LE, AV_CODEC_ID_PCM_VIDC, /* various ADPCM codecs */ AV_CODEC_ID_ADPCM_IMA_QT = 0x11000, AV_CODEC_ID_ADPCM_IMA_WAV, AV_CODEC_ID_ADPCM_IMA_DK3, AV_CODEC_ID_ADPCM_IMA_DK4, AV_CODEC_ID_ADPCM_IMA_WS, AV_CODEC_ID_ADPCM_IMA_SMJPEG, AV_CODEC_ID_ADPCM_MS, AV_CODEC_ID_ADPCM_4XM, AV_CODEC_ID_ADPCM_XA, AV_CODEC_ID_ADPCM_ADX, AV_CODEC_ID_ADPCM_EA, AV_CODEC_ID_ADPCM_G726, AV_CODEC_ID_ADPCM_CT, AV_CODEC_ID_ADPCM_SWF, AV_CODEC_ID_ADPCM_YAMAHA, AV_CODEC_ID_ADPCM_SBPRO_4, AV_CODEC_ID_ADPCM_SBPRO_3, AV_CODEC_ID_ADPCM_SBPRO_2, AV_CODEC_ID_ADPCM_THP, AV_CODEC_ID_ADPCM_IMA_AMV, AV_CODEC_ID_ADPCM_EA_R1, AV_CODEC_ID_ADPCM_EA_R3, AV_CODEC_ID_ADPCM_EA_R2, AV_CODEC_ID_ADPCM_IMA_EA_SEAD, AV_CODEC_ID_ADPCM_IMA_EA_EACS, AV_CODEC_ID_ADPCM_EA_XAS, AV_CODEC_ID_ADPCM_EA_MAXIS_XA, AV_CODEC_ID_ADPCM_IMA_ISS, AV_CODEC_ID_ADPCM_G722, AV_CODEC_ID_ADPCM_IMA_APC, AV_CODEC_ID_ADPCM_VIMA, AV_CODEC_ID_ADPCM_AFC = 0x11800, AV_CODEC_ID_ADPCM_IMA_OKI, AV_CODEC_ID_ADPCM_DTK, AV_CODEC_ID_ADPCM_IMA_RAD, AV_CODEC_ID_ADPCM_G726LE, AV_CODEC_ID_ADPCM_THP_LE, AV_CODEC_ID_ADPCM_PSX, AV_CODEC_ID_ADPCM_AICA, AV_CODEC_ID_ADPCM_IMA_DAT4, AV_CODEC_ID_ADPCM_MTAF, AV_CODEC_ID_ADPCM_AGM, /* AMR */ AV_CODEC_ID_AMR_NB = 0x12000, AV_CODEC_ID_AMR_WB, /* RealAudio codecs*/ AV_CODEC_ID_RA_144 = 0x13000, AV_CODEC_ID_RA_288, /* various DPCM codecs */ AV_CODEC_ID_ROQ_DPCM = 0x14000, AV_CODEC_ID_INTERPLAY_DPCM, AV_CODEC_ID_XAN_DPCM, AV_CODEC_ID_SOL_DPCM, AV_CODEC_ID_SDX2_DPCM = 0x14800, AV_CODEC_ID_GREMLIN_DPCM, /* audio codecs */ AV_CODEC_ID_MP2 = 0x15000, AV_CODEC_ID_MP3, ///< preferred ID for decoding MPEG audio layer 1, 2 or 3 AV_CODEC_ID_AAC, AV_CODEC_ID_AC3, AV_CODEC_ID_DTS, AV_CODEC_ID_VORBIS, AV_CODEC_ID_DVAUDIO, AV_CODEC_ID_WMAV1, AV_CODEC_ID_WMAV2, AV_CODEC_ID_MACE3, AV_CODEC_ID_MACE6, AV_CODEC_ID_VMDAUDIO, AV_CODEC_ID_FLAC, AV_CODEC_ID_MP3ADU, AV_CODEC_ID_MP3ON4, AV_CODEC_ID_SHORTEN, AV_CODEC_ID_ALAC, AV_CODEC_ID_WESTWOOD_SND1, AV_CODEC_ID_GSM, ///< as in Berlin toast format AV_CODEC_ID_QDM2, AV_CODEC_ID_COOK, AV_CODEC_ID_TRUESPEECH, AV_CODEC_ID_TTA, AV_CODEC_ID_SMACKAUDIO, AV_CODEC_ID_QCELP, AV_CODEC_ID_WAVPACK, AV_CODEC_ID_DSICINAUDIO, AV_CODEC_ID_IMC, AV_CODEC_ID_MUSEPACK7, AV_CODEC_ID_MLP, AV_CODEC_ID_GSM_MS, /* as found in WAV */ AV_CODEC_ID_ATRAC3, AV_CODEC_ID_APE, AV_CODEC_ID_NELLYMOSER, AV_CODEC_ID_MUSEPACK8, AV_CODEC_ID_SPEEX, AV_CODEC_ID_WMAVOICE, AV_CODEC_ID_WMAPRO, AV_CODEC_ID_WMALOSSLESS, AV_CODEC_ID_ATRAC3P, AV_CODEC_ID_EAC3, AV_CODEC_ID_SIPR, AV_CODEC_ID_MP1, AV_CODEC_ID_TWINVQ, AV_CODEC_ID_TRUEHD, AV_CODEC_ID_MP4ALS, AV_CODEC_ID_ATRAC1, AV_CODEC_ID_BINKAUDIO_RDFT, AV_CODEC_ID_BINKAUDIO_DCT, AV_CODEC_ID_AAC_LATM, AV_CODEC_ID_QDMC, AV_CODEC_ID_CELT, AV_CODEC_ID_G723_1, AV_CODEC_ID_G729, AV_CODEC_ID_8SVX_EXP, AV_CODEC_ID_8SVX_FIB, AV_CODEC_ID_BMV_AUDIO, AV_CODEC_ID_RALF, AV_CODEC_ID_IAC, AV_CODEC_ID_ILBC, AV_CODEC_ID_OPUS, AV_CODEC_ID_COMFORT_NOISE, AV_CODEC_ID_TAK, AV_CODEC_ID_METASOUND, AV_CODEC_ID_PAF_AUDIO, AV_CODEC_ID_ON2AVC, AV_CODEC_ID_DSS_SP, AV_CODEC_ID_CODEC2, AV_CODEC_ID_FFWAVESYNTH = 0x15800, AV_CODEC_ID_SONIC, AV_CODEC_ID_SONIC_LS, AV_CODEC_ID_EVRC, AV_CODEC_ID_SMV, AV_CODEC_ID_DSD_LSBF, AV_CODEC_ID_DSD_MSBF, AV_CODEC_ID_DSD_LSBF_PLANAR, AV_CODEC_ID_DSD_MSBF_PLANAR, AV_CODEC_ID_4GV, AV_CODEC_ID_INTERPLAY_ACM, AV_CODEC_ID_XMA1, AV_CODEC_ID_XMA2, AV_CODEC_ID_DST, AV_CODEC_ID_ATRAC3AL, AV_CODEC_ID_ATRAC3PAL, AV_CODEC_ID_DOLBY_E, AV_CODEC_ID_APTX, AV_CODEC_ID_APTX_HD, AV_CODEC_ID_SBC, AV_CODEC_ID_ATRAC9, AV_CODEC_ID_HCOM, /* subtitle codecs */ AV_CODEC_ID_FIRST_SUBTITLE = 0x17000, ///< A dummy ID pointing at the start of subtitle codecs. AV_CODEC_ID_DVD_SUBTITLE = 0x17000, AV_CODEC_ID_DVB_SUBTITLE, AV_CODEC_ID_TEXT, ///< raw UTF-8 text AV_CODEC_ID_XSUB, AV_CODEC_ID_SSA, AV_CODEC_ID_MOV_TEXT, AV_CODEC_ID_HDMV_PGS_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT, AV_CODEC_ID_SRT, AV_CODEC_ID_MICRODVD = 0x17800, AV_CODEC_ID_EIA_608, AV_CODEC_ID_JACOSUB, AV_CODEC_ID_SAMI, AV_CODEC_ID_REALTEXT, AV_CODEC_ID_STL, AV_CODEC_ID_SUBVIEWER1, AV_CODEC_ID_SUBVIEWER, AV_CODEC_ID_SUBRIP, AV_CODEC_ID_WEBVTT, AV_CODEC_ID_MPL2, AV_CODEC_ID_VPLAYER, AV_CODEC_ID_PJS, AV_CODEC_ID_ASS, AV_CODEC_ID_HDMV_TEXT_SUBTITLE, AV_CODEC_ID_TTML, AV_CODEC_ID_ARIB_CAPTION, /* other specific kind of codecs (generally used for attachments) */ AV_CODEC_ID_FIRST_UNKNOWN = 0x18000, ///< A dummy ID pointing at the start of various fake codecs. AV_CODEC_ID_TTF = 0x18000, AV_CODEC_ID_SCTE_35, ///< Contain timestamp estimated through PCR of program stream. AV_CODEC_ID_BINTEXT = 0x18800, AV_CODEC_ID_XBIN, AV_CODEC_ID_IDF, AV_CODEC_ID_OTF, AV_CODEC_ID_SMPTE_KLV, AV_CODEC_ID_DVD_NAV, AV_CODEC_ID_TIMED_ID3, AV_CODEC_ID_BIN_DATA, AV_CODEC_ID_PROBE = 0x19000, ///< codec_id is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it AV_CODEC_ID_MPEG2TS = 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS * stream (only used by libavformat) */ AV_CODEC_ID_MPEG4SYSTEMS = 0x20001, /**< _FAKE_ codec to indicate a MPEG-4 Systems * stream (only used by libavformat) */ AV_CODEC_ID_FFMETADATA = 0x21000, ///< Dummy codec for streams containing only metadata information. AV_CODEC_ID_WRAPPED_AVFRAME = 0x21001, ///< Passthrough codec, AVFrames wrapped in AVPacket }; /** * This struct describes the properties of a single codec described by an * AVCodecID. * @see avcodec_descriptor_get() */ typedef struct AVCodecDescriptor { enum AVCodecID id; enum AVMediaType type; /** * Name of the codec described by this descriptor. It is non-empty and * unique for each codec descriptor. It should contain alphanumeric * characters and '_' only. */ const char *name; /** * A more descriptive name for this codec. May be NULL. */ const char *long_name; /** * Codec properties, a combination of AV_CODEC_PROP_* flags. */ int props; /** * MIME type(s) associated with the codec. * May be NULL; if not, a NULL-terminated array of MIME types. * The first item is always non-NULL and is the preferred MIME type. */ const char *const *mime_types; /** * If non-NULL, an array of profiles recognized for this codec. * Terminated with FF_PROFILE_UNKNOWN. */ const struct AVProfile *profiles; } AVCodecDescriptor; /** * Codec uses only intra compression. * Video and audio codecs only. */ #define AV_CODEC_PROP_INTRA_ONLY (1 << 0) /** * Codec supports lossy compression. Audio and video codecs only. * @note a codec may support both lossy and lossless * compression modes */ #define AV_CODEC_PROP_LOSSY (1 << 1) /** * Codec supports lossless compression. Audio and video codecs only. */ #define AV_CODEC_PROP_LOSSLESS (1 << 2) /** * Codec supports frame reordering. That is, the coded order (the order in which * the encoded packets are output by the encoders / stored / input to the * decoders) may be different from the presentation order of the corresponding * frames. * * For codecs that do not have this property set, PTS and DTS should always be * equal. */ #define AV_CODEC_PROP_REORDER (1 << 3) /** * Subtitle codec is bitmap based * Decoded AVSubtitle data can be read from the AVSubtitleRect->pict field. */ #define AV_CODEC_PROP_BITMAP_SUB (1 << 16) /** * Subtitle codec is text based. * Decoded AVSubtitle data can be read from the AVSubtitleRect->ass field. */ #define AV_CODEC_PROP_TEXT_SUB (1 << 17) /** * @ingroup lavc_decoding * Required number of additionally allocated bytes at the end of the input bitstream for decoding. * This is mainly needed because some optimized bitstream readers read * 32 or 64 bit at once and could read over the end.
* Note: If the first 23 bits of the additional bytes are not 0, then damaged * MPEG bitstreams could cause overread and segfault. */ #define AV_INPUT_BUFFER_PADDING_SIZE 64 /** * @ingroup lavc_encoding * minimum encoding buffer size * Used to avoid some checks during header writing. */ #define AV_INPUT_BUFFER_MIN_SIZE 16384 /** * @ingroup lavc_decoding */ enum AVDiscard{ /* We leave some space between them for extensions (drop some * keyframes for intra-only or drop just some bidir frames). */ AVDISCARD_NONE =-16, ///< discard nothing AVDISCARD_DEFAULT = 0, ///< discard useless packets like 0 size packets in avi AVDISCARD_NONREF = 8, ///< discard all non reference AVDISCARD_BIDIR = 16, ///< discard all bidirectional frames AVDISCARD_NONINTRA= 24, ///< discard all non intra frames AVDISCARD_NONKEY = 32, ///< discard all frames except keyframes AVDISCARD_ALL = 48, ///< discard all }; enum AVAudioServiceType { AV_AUDIO_SERVICE_TYPE_MAIN = 0, AV_AUDIO_SERVICE_TYPE_EFFECTS = 1, AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED = 2, AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED = 3, AV_AUDIO_SERVICE_TYPE_DIALOGUE = 4, AV_AUDIO_SERVICE_TYPE_COMMENTARY = 5, AV_AUDIO_SERVICE_TYPE_EMERGENCY = 6, AV_AUDIO_SERVICE_TYPE_VOICE_OVER = 7, AV_AUDIO_SERVICE_TYPE_KARAOKE = 8, AV_AUDIO_SERVICE_TYPE_NB , ///< Not part of ABI }; /** * @ingroup lavc_encoding */ typedef struct RcOverride{ int start_frame; int end_frame; int qscale; // If this is 0 then quality_factor will be used instead. float quality_factor; } RcOverride; /* encoding support These flags can be passed in AVCodecContext.flags before initialization. Note: Not everything is supported yet. */ /** * Allow decoders to produce frames with data planes that are not aligned * to CPU requirements (e.g. due to cropping). */ #define AV_CODEC_FLAG_UNALIGNED (1 << 0) /** * Use fixed qscale. */ #define AV_CODEC_FLAG_QSCALE (1 << 1) /** * 4 MV per MB allowed / advanced prediction for H.263. */ #define AV_CODEC_FLAG_4MV (1 << 2) /** * Output even those frames that might be corrupted. */ #define AV_CODEC_FLAG_OUTPUT_CORRUPT (1 << 3) /** * Use qpel MC. */ #define AV_CODEC_FLAG_QPEL (1 << 4) /** * Don't output frames whose parameters differ from first * decoded frame in stream. */ #define AV_CODEC_FLAG_DROPCHANGED (1 << 5) /** * Use internal 2pass ratecontrol in first pass mode. */ #define AV_CODEC_FLAG_PASS1 (1 << 9) /** * Use internal 2pass ratecontrol in second pass mode. */ #define AV_CODEC_FLAG_PASS2 (1 << 10) /** * loop filter. */ #define AV_CODEC_FLAG_LOOP_FILTER (1 << 11) /** * Only decode/encode grayscale. */ #define AV_CODEC_FLAG_GRAY (1 << 13) /** * error[?] variables will be set during encoding. */ #define AV_CODEC_FLAG_PSNR (1 << 15) /** * Input bitstream might be truncated at a random location * instead of only at frame boundaries. */ #define AV_CODEC_FLAG_TRUNCATED (1 << 16) /** * Use interlaced DCT. */ #define AV_CODEC_FLAG_INTERLACED_DCT (1 << 18) /** * Force low delay. */ #define AV_CODEC_FLAG_LOW_DELAY (1 << 19) /** * Place global headers in extradata instead of every keyframe. */ #define AV_CODEC_FLAG_GLOBAL_HEADER (1 << 22) /** * Use only bitexact stuff (except (I)DCT). */ #define AV_CODEC_FLAG_BITEXACT (1 << 23) /* Fx : Flag for H.263+ extra options */ /** * H.263 advanced intra coding / MPEG-4 AC prediction */ #define AV_CODEC_FLAG_AC_PRED (1 << 24) /** * interlaced motion estimation */ #define AV_CODEC_FLAG_INTERLACED_ME (1 << 29) #define AV_CODEC_FLAG_CLOSED_GOP (1U << 31) /** * Allow non spec compliant speedup tricks. */ #define AV_CODEC_FLAG2_FAST (1 << 0) /** * Skip bitstream encoding. */ #define AV_CODEC_FLAG2_NO_OUTPUT (1 << 2) /** * Place global headers at every keyframe instead of in extradata. */ #define AV_CODEC_FLAG2_LOCAL_HEADER (1 << 3) /** * timecode is in drop frame format. DEPRECATED!!!! */ #define AV_CODEC_FLAG2_DROP_FRAME_TIMECODE (1 << 13) /** * Input bitstream might be truncated at a packet boundaries * instead of only at frame boundaries. */ #define AV_CODEC_FLAG2_CHUNKS (1 << 15) /** * Discard cropping information from SPS. */ #define AV_CODEC_FLAG2_IGNORE_CROP (1 << 16) /** * Show all frames before the first keyframe */ #define AV_CODEC_FLAG2_SHOW_ALL (1 << 22) /** * Export motion vectors through frame side data */ #define AV_CODEC_FLAG2_EXPORT_MVS (1 << 28) /** * Do not skip samples and export skip information as frame side data */ #define AV_CODEC_FLAG2_SKIP_MANUAL (1 << 29) /** * Do not reset ASS ReadOrder field on flush (subtitles decoding) */ #define AV_CODEC_FLAG2_RO_FLUSH_NOOP (1 << 30) /* Unsupported options : * Syntax Arithmetic coding (SAC) * Reference Picture Selection * Independent Segment Decoding */ /* /Fx */ /* codec capabilities */ /** * Decoder can use draw_horiz_band callback. */ #define AV_CODEC_CAP_DRAW_HORIZ_BAND (1 << 0) /** * Codec uses get_buffer() for allocating buffers and supports custom allocators. * If not set, it might not use get_buffer() at all or use operations that * assume the buffer was allocated by avcodec_default_get_buffer. */ #define AV_CODEC_CAP_DR1 (1 << 1) #define AV_CODEC_CAP_TRUNCATED (1 << 3) /** * Encoder or decoder requires flushing with NULL input at the end in order to * give the complete and correct output. * * NOTE: If this flag is not set, the codec is guaranteed to never be fed with * with NULL data. The user can still send NULL data to the public encode * or decode function, but libavcodec will not pass it along to the codec * unless this flag is set. * * Decoders: * The decoder has a non-zero delay and needs to be fed with avpkt->data=NULL, * avpkt->size=0 at the end to get the delayed data until the decoder no longer * returns frames. * * Encoders: * The encoder needs to be fed with NULL data at the end of encoding until the * encoder no longer returns data. * * NOTE: For encoders implementing the AVCodec.encode2() function, setting this * flag also means that the encoder must set the pts and duration for * each output packet. If this flag is not set, the pts and duration will * be determined by libavcodec from the input frame. */ #define AV_CODEC_CAP_DELAY (1 << 5) /** * Codec can be fed a final frame with a smaller size. * This can be used to prevent truncation of the last audio samples. */ #define AV_CODEC_CAP_SMALL_LAST_FRAME (1 << 6) /** * Codec can output multiple frames per AVPacket * Normally demuxers return one frame at a time, demuxers which do not do * are connected to a parser to split what they return into proper frames. * This flag is reserved to the very rare category of codecs which have a * bitstream that cannot be split into frames without timeconsuming * operations like full decoding. Demuxers carrying such bitstreams thus * may return multiple frames in a packet. This has many disadvantages like * prohibiting stream copy in many cases thus it should only be considered * as a last resort. */ #define AV_CODEC_CAP_SUBFRAMES (1 << 8) /** * Codec is experimental and is thus avoided in favor of non experimental * encoders */ #define AV_CODEC_CAP_EXPERIMENTAL (1 << 9) /** * Codec should fill in channel configuration and samplerate instead of container */ #define AV_CODEC_CAP_CHANNEL_CONF (1 << 10) /** * Codec supports frame-level multithreading. */ #define AV_CODEC_CAP_FRAME_THREADS (1 << 12) /** * Codec supports slice-based (or partition-based) multithreading. */ #define AV_CODEC_CAP_SLICE_THREADS (1 << 13) /** * Codec supports changed parameters at any point. */ #define AV_CODEC_CAP_PARAM_CHANGE (1 << 14) /** * Codec supports avctx->thread_count == 0 (auto). */ #define AV_CODEC_CAP_AUTO_THREADS (1 << 15) /** * Audio encoder supports receiving a different number of samples in each call. */ #define AV_CODEC_CAP_VARIABLE_FRAME_SIZE (1 << 16) /** * Decoder is not a preferred choice for probing. * This indicates that the decoder is not a good choice for probing. * It could for example be an expensive to spin up hardware decoder, * or it could simply not provide a lot of useful information about * the stream. * A decoder marked with this flag should only be used as last resort * choice for probing. */ #define AV_CODEC_CAP_AVOID_PROBING (1 << 17) /** * Codec is intra only. */ #define AV_CODEC_CAP_INTRA_ONLY 0x40000000 /** * Codec is lossless. */ #define AV_CODEC_CAP_LOSSLESS 0x80000000 /** * Codec is backed by a hardware implementation. Typically used to * identify a non-hwaccel hardware decoder. For information about hwaccels, use * avcodec_get_hw_config() instead. */ #define AV_CODEC_CAP_HARDWARE (1 << 18) /** * Codec is potentially backed by a hardware implementation, but not * necessarily. This is used instead of AV_CODEC_CAP_HARDWARE, if the * implementation provides some sort of internal fallback. */ #define AV_CODEC_CAP_HYBRID (1 << 19) /** * This codec takes the reordered_opaque field from input AVFrames * and returns it in the corresponding field in AVCodecContext after * encoding. */ #define AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE (1 << 20) /** * Pan Scan area. * This specifies the area which should be displayed. * Note there may be multiple such areas for one frame. */ typedef struct AVPanScan { /** * id * - encoding: Set by user. * - decoding: Set by libavcodec. */ int id; /** * width and height in 1/16 pel * - encoding: Set by user. * - decoding: Set by libavcodec. */ int width; int height; /** * position of the top left corner in 1/16 pel for up to 3 fields/frames * - encoding: Set by user. * - decoding: Set by libavcodec. */ int16_t position[3][2]; } AVPanScan; /** * This structure describes the bitrate properties of an encoded bitstream. It * roughly corresponds to a subset the VBV parameters for MPEG-2 or HRD * parameters for H.264/HEVC. */ typedef struct AVCPBProperties { /** * Maximum bitrate of the stream, in bits per second. * Zero if unknown or unspecified. */ #if FF_API_UNSANITIZED_BITRATES int max_bitrate; #else int64_t max_bitrate; #endif /** * Minimum bitrate of the stream, in bits per second. * Zero if unknown or unspecified. */ #if FF_API_UNSANITIZED_BITRATES int min_bitrate; #else int64_t min_bitrate; #endif /** * Average bitrate of the stream, in bits per second. * Zero if unknown or unspecified. */ #if FF_API_UNSANITIZED_BITRATES int avg_bitrate; #else int64_t avg_bitrate; #endif /** * The size of the buffer to which the ratecontrol is applied, in bits. * Zero if unknown or unspecified. */ int buffer_size; /** * The delay between the time the packet this structure is associated with * is received and the time when it should be decoded, in periods of a 27MHz * clock. * * UINT64_MAX when unknown or unspecified. */ uint64_t vbv_delay; } AVCPBProperties; /** * The decoder will keep a reference to the frame and may reuse it later. */ #define AV_GET_BUFFER_FLAG_REF (1 << 0) /** * @defgroup lavc_packet AVPacket * * Types and functions for working with AVPacket. * @{ */ enum AVPacketSideDataType { /** * An AV_PKT_DATA_PALETTE side data packet contains exactly AVPALETTE_SIZE * bytes worth of palette. This side data signals that a new palette is * present. */ AV_PKT_DATA_PALETTE, /** * The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format * that the extradata buffer was changed and the receiving side should * act upon it appropriately. The new extradata is embedded in the side * data buffer and should be immediately used for processing the current * frame or packet. */ AV_PKT_DATA_NEW_EXTRADATA, /** * An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows: * @code * u32le param_flags * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) * s32le channel_count * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) * u64le channel_layout * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) * s32le sample_rate * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) * s32le width * s32le height * @endcode */ AV_PKT_DATA_PARAM_CHANGE, /** * An AV_PKT_DATA_H263_MB_INFO side data packet contains a number of * structures with info about macroblocks relevant to splitting the * packet into smaller packets on macroblock edges (e.g. as for RFC 2190). * That is, it does not necessarily contain info about all macroblocks, * as long as the distance between macroblocks in the info is smaller * than the target payload size. * Each MB info structure is 12 bytes, and is laid out as follows: * @code * u32le bit offset from the start of the packet * u8 current quantizer at the start of the macroblock * u8 GOB number * u16le macroblock address within the GOB * u8 horizontal MV predictor * u8 vertical MV predictor * u8 horizontal MV predictor for block number 3 * u8 vertical MV predictor for block number 3 * @endcode */ AV_PKT_DATA_H263_MB_INFO, /** * This side data should be associated with an audio stream and contains * ReplayGain information in form of the AVReplayGain struct. */ AV_PKT_DATA_REPLAYGAIN, /** * This side data contains a 3x3 transformation matrix describing an affine * transformation that needs to be applied to the decoded video frames for * correct presentation. * * See libavutil/display.h for a detailed description of the data. */ AV_PKT_DATA_DISPLAYMATRIX, /** * This side data should be associated with a video stream and contains * Stereoscopic 3D information in form of the AVStereo3D struct. */ AV_PKT_DATA_STEREO3D, /** * This side data should be associated with an audio stream and corresponds * to enum AVAudioServiceType. */ AV_PKT_DATA_AUDIO_SERVICE_TYPE, /** * This side data contains quality related information from the encoder. * @code * u32le quality factor of the compressed frame. Allowed range is between 1 (good) and FF_LAMBDA_MAX (bad). * u8 picture type * u8 error count * u16 reserved * u64le[error count] sum of squared differences between encoder in and output * @endcode */ AV_PKT_DATA_QUALITY_STATS, /** * This side data contains an integer value representing the stream index * of a "fallback" track. A fallback track indicates an alternate * track to use when the current track can not be decoded for some reason. * e.g. no decoder available for codec. */ AV_PKT_DATA_FALLBACK_TRACK, /** * This side data corresponds to the AVCPBProperties struct. */ AV_PKT_DATA_CPB_PROPERTIES, /** * Recommmends skipping the specified number of samples * @code * u32le number of samples to skip from start of this packet * u32le number of samples to skip from end of this packet * u8 reason for start skip * u8 reason for end skip (0=padding silence, 1=convergence) * @endcode */ AV_PKT_DATA_SKIP_SAMPLES, /** * An AV_PKT_DATA_JP_DUALMONO side data packet indicates that * the packet may contain "dual mono" audio specific to Japanese DTV * and if it is true, recommends only the selected channel to be used. * @code * u8 selected channels (0=mail/left, 1=sub/right, 2=both) * @endcode */ AV_PKT_DATA_JP_DUALMONO, /** * A list of zero terminated key/value strings. There is no end marker for * the list, so it is required to rely on the side data size to stop. */ AV_PKT_DATA_STRINGS_METADATA, /** * Subtitle event position * @code * u32le x1 * u32le y1 * u32le x2 * u32le y2 * @endcode */ AV_PKT_DATA_SUBTITLE_POSITION, /** * Data found in BlockAdditional element of matroska container. There is * no end marker for the data, so it is required to rely on the side data * size to recognize the end. 8 byte id (as found in BlockAddId) followed * by data. */ AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL, /** * The optional first identifier line of a WebVTT cue. */ AV_PKT_DATA_WEBVTT_IDENTIFIER, /** * The optional settings (rendering instructions) that immediately * follow the timestamp specifier of a WebVTT cue. */ AV_PKT_DATA_WEBVTT_SETTINGS, /** * A list of zero terminated key/value strings. There is no end marker for * the list, so it is required to rely on the side data size to stop. This * side data includes updated metadata which appeared in the stream. */ AV_PKT_DATA_METADATA_UPDATE, /** * MPEGTS stream ID as uint8_t, this is required to pass the stream ID * information from the demuxer to the corresponding muxer. */ AV_PKT_DATA_MPEGTS_STREAM_ID, /** * Mastering display metadata (based on SMPTE-2086:2014). This metadata * should be associated with a video stream and contains data in the form * of the AVMasteringDisplayMetadata struct. */ AV_PKT_DATA_MASTERING_DISPLAY_METADATA, /** * This side data should be associated with a video stream and corresponds * to the AVSphericalMapping structure. */ AV_PKT_DATA_SPHERICAL, /** * Content light level (based on CTA-861.3). This metadata should be * associated with a video stream and contains data in the form of the * AVContentLightMetadata struct. */ AV_PKT_DATA_CONTENT_LIGHT_LEVEL, /** * ATSC A53 Part 4 Closed Captions. This metadata should be associated with * a video stream. A53 CC bitstream is stored as uint8_t in AVPacketSideData.data. * The number of bytes of CC data is AVPacketSideData.size. */ AV_PKT_DATA_A53_CC, /** * This side data is encryption initialization data. * The format is not part of ABI, use av_encryption_init_info_* methods to * access. */ AV_PKT_DATA_ENCRYPTION_INIT_INFO, /** * This side data contains encryption info for how to decrypt the packet. * The format is not part of ABI, use av_encryption_info_* methods to access. */ AV_PKT_DATA_ENCRYPTION_INFO, /** * Active Format Description data consisting of a single byte as specified * in ETSI TS 101 154 using AVActiveFormatDescription enum. */ AV_PKT_DATA_AFD, /** * The number of side data types. * This is not part of the public API/ABI in the sense that it may * change when new side data types are added. * This must stay the last enum value. * If its value becomes huge, some code using it * needs to be updated as it assumes it to be smaller than other limits. */ AV_PKT_DATA_NB }; #define AV_PKT_DATA_QUALITY_FACTOR AV_PKT_DATA_QUALITY_STATS //DEPRECATED typedef struct AVPacketSideData { uint8_t *data; int size; enum AVPacketSideDataType type; } AVPacketSideData; /** * This structure stores compressed data. It is typically exported by demuxers * and then passed as input to decoders, or received as output from encoders and * then passed to muxers. * * For video, it should typically contain one compressed frame. For audio it may * contain several compressed frames. Encoders are allowed to output empty * packets, with no compressed data, containing only side data * (e.g. to update some stream parameters at the end of encoding). * * AVPacket is one of the few structs in FFmpeg, whose size is a part of public * ABI. Thus it may be allocated on stack and no new fields can be added to it * without libavcodec and libavformat major bump. * * The semantics of data ownership depends on the buf field. * If it is set, the packet data is dynamically allocated and is * valid indefinitely until a call to av_packet_unref() reduces the * reference count to 0. * * If the buf field is not set av_packet_ref() would make a copy instead * of increasing the reference count. * * The side data is always allocated with av_malloc(), copied by * av_packet_ref() and freed by av_packet_unref(). * * @see av_packet_ref * @see av_packet_unref */ typedef struct AVPacket { /** * A reference to the reference-counted buffer where the packet data is * stored. * May be NULL, then the packet data is not reference-counted. */ AVBufferRef *buf; /** * Presentation timestamp in AVStream->time_base units; the time at which * the decompressed packet will be presented to the user. * Can be AV_NOPTS_VALUE if it is not stored in the file. * pts MUST be larger or equal to dts as presentation cannot happen before * decompression, unless one wants to view hex dumps. Some formats misuse * the terms dts and pts/cts to mean something different. Such timestamps * must be converted to true pts/dts before they are stored in AVPacket. */ int64_t pts; /** * Decompression timestamp in AVStream->time_base units; the time at which * the packet is decompressed. * Can be AV_NOPTS_VALUE if it is not stored in the file. */ int64_t dts; uint8_t *data; int size; int stream_index; /** * A combination of AV_PKT_FLAG values */ int flags; /** * Additional packet data that can be provided by the container. * Packet can contain several types of side information. */ AVPacketSideData *side_data; int side_data_elems; /** * Duration of this packet in AVStream->time_base units, 0 if unknown. * Equals next_pts - this_pts in presentation order. */ int64_t duration; int64_t pos; ///< byte position in stream, -1 if unknown #if FF_API_CONVERGENCE_DURATION /** * @deprecated Same as the duration field, but as int64_t. This was required * for Matroska subtitles, whose duration values could overflow when the * duration field was still an int. */ attribute_deprecated int64_t convergence_duration; #endif } AVPacket; #define AV_PKT_FLAG_KEY 0x0001 ///< The packet contains a keyframe #define AV_PKT_FLAG_CORRUPT 0x0002 ///< The packet content is corrupted /** * Flag is used to discard packets which are required to maintain valid * decoder state but are not required for output and should be dropped * after decoding. **/ #define AV_PKT_FLAG_DISCARD 0x0004 /** * The packet comes from a trusted source. * * Otherwise-unsafe constructs such as arbitrary pointers to data * outside the packet may be followed. */ #define AV_PKT_FLAG_TRUSTED 0x0008 /** * Flag is used to indicate packets that contain frames that can * be discarded by the decoder. I.e. Non-reference frames. */ #define AV_PKT_FLAG_DISPOSABLE 0x0010 enum AVSideDataParamChangeFlags { AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT = 0x0001, AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT = 0x0002, AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE = 0x0004, AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS = 0x0008, }; /** * @} */ struct AVCodecInternal; enum AVFieldOrder { AV_FIELD_UNKNOWN, AV_FIELD_PROGRESSIVE, AV_FIELD_TT, //< Top coded_first, top displayed first AV_FIELD_BB, //< Bottom coded first, bottom displayed first AV_FIELD_TB, //< Top coded first, bottom displayed first AV_FIELD_BT, //< Bottom coded first, top displayed first }; /** * main external API structure. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * You can use AVOptions (av_opt* / av_set/get*()) to access these fields from user * applications. * The name string for AVOptions options matches the associated command line * parameter name and can be found in libavcodec/options_table.h * The AVOption/command line parameter names differ in some cases from the C * structure field names for historic reasons or brevity. * sizeof(AVCodecContext) must not be used outside libav*. */ typedef struct AVCodecContext { /** * information on struct for av_log * - set by avcodec_alloc_context3 */ const AVClass *av_class; int log_level_offset; enum AVMediaType codec_type; /* see AVMEDIA_TYPE_xxx */ const struct AVCodec *codec; enum AVCodecID codec_id; /* see AV_CODEC_ID_xxx */ /** * fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A'). * This is used to work around some encoder bugs. * A demuxer should set this to what is stored in the field used to identify the codec. * If there are multiple such fields in a container then the demuxer should choose the one * which maximizes the information about the used codec. * If the codec tag field in a container is larger than 32 bits then the demuxer should * remap the longer ID to 32 bits with a table or other structure. Alternatively a new * extra_codec_tag + size could be added but for this a clear advantage must be demonstrated * first. * - encoding: Set by user, if not then the default based on codec_id will be used. * - decoding: Set by user, will be converted to uppercase by libavcodec during init. */ unsigned int codec_tag; void *priv_data; /** * Private context used for internal data. * * Unlike priv_data, this is not codec-specific. It is used in general * libavcodec functions. */ struct AVCodecInternal *internal; /** * Private data of the user, can be used to carry app specific stuff. * - encoding: Set by user. * - decoding: Set by user. */ void *opaque; /** * the average bitrate * - encoding: Set by user; unused for constant quantizer encoding. * - decoding: Set by user, may be overwritten by libavcodec * if this info is available in the stream */ int64_t bit_rate; /** * number of bits the bitstream is allowed to diverge from the reference. * the reference can be CBR (for CBR pass1) or VBR (for pass2) * - encoding: Set by user; unused for constant quantizer encoding. * - decoding: unused */ int bit_rate_tolerance; /** * Global quality for codecs which cannot change it per frame. * This should be proportional to MPEG-1/2/4 qscale. * - encoding: Set by user. * - decoding: unused */ int global_quality; /** * - encoding: Set by user. * - decoding: unused */ int compression_level; #define FF_COMPRESSION_DEFAULT -1 /** * AV_CODEC_FLAG_*. * - encoding: Set by user. * - decoding: Set by user. */ int flags; /** * AV_CODEC_FLAG2_* * - encoding: Set by user. * - decoding: Set by user. */ int flags2; /** * some codecs need / can use extradata like Huffman tables. * MJPEG: Huffman tables * rv10: additional flags * MPEG-4: global headers (they can be in the bitstream or here) * The allocated memory should be AV_INPUT_BUFFER_PADDING_SIZE bytes larger * than extradata_size to avoid problems if it is read with the bitstream reader. * The bytewise contents of extradata must not depend on the architecture or CPU endianness. * Must be allocated with the av_malloc() family of functions. * - encoding: Set/allocated/freed by libavcodec. * - decoding: Set/allocated/freed by user. */ uint8_t *extradata; int extradata_size; /** * This is the fundamental unit of time (in seconds) in terms * of which frame timestamps are represented. For fixed-fps content, * timebase should be 1/framerate and timestamp increments should be * identically 1. * This often, but not always is the inverse of the frame rate or field rate * for video. 1/time_base is not the average frame rate if the frame rate is not * constant. * * Like containers, elementary streams also can store timestamps, 1/time_base * is the unit in which these timestamps are specified. * As example of such codec time base see ISO/IEC 14496-2:2001(E) * vop_time_increment_resolution and fixed_vop_rate * (fixed_vop_rate == 0 implies that it is different from the framerate) * * - encoding: MUST be set by user. * - decoding: the use of this field for decoding is deprecated. * Use framerate instead. */ AVRational time_base; /** * For some codecs, the time base is closer to the field rate than the frame rate. * Most notably, H.264 and MPEG-2 specify time_base as half of frame duration * if no telecine is used ... * * Set to time_base ticks per frame. Default 1, e.g., H.264/MPEG-2 set it to 2. */ int ticks_per_frame; /** * Codec delay. * * Encoding: Number of frames delay there will be from the encoder input to * the decoder output. (we assume the decoder matches the spec) * Decoding: Number of frames delay in addition to what a standard decoder * as specified in the spec would produce. * * Video: * Number of frames the decoded output will be delayed relative to the * encoded input. * * Audio: * For encoding, this field is unused (see initial_padding). * * For decoding, this is the number of samples the decoder needs to * output before the decoder's output is valid. When seeking, you should * start decoding this many samples prior to your desired seek point. * * - encoding: Set by libavcodec. * - decoding: Set by libavcodec. */ int delay; /* video only */ /** * picture width / height. * * @note Those fields may not match the values of the last * AVFrame output by avcodec_decode_video2 due frame * reordering. * * - encoding: MUST be set by user. * - decoding: May be set by the user before opening the decoder if known e.g. * from the container. Some decoders will require the dimensions * to be set by the caller. During decoding, the decoder may * overwrite those values as required while parsing the data. */ int width, height; /** * Bitstream width / height, may be different from width/height e.g. when * the decoded frame is cropped before being output or lowres is enabled. * * @note Those field may not match the value of the last * AVFrame output by avcodec_receive_frame() due frame * reordering. * * - encoding: unused * - decoding: May be set by the user before opening the decoder if known * e.g. from the container. During decoding, the decoder may * overwrite those values as required while parsing the data. */ int coded_width, coded_height; /** * the number of pictures in a group of pictures, or 0 for intra_only * - encoding: Set by user. * - decoding: unused */ int gop_size; /** * Pixel format, see AV_PIX_FMT_xxx. * May be set by the demuxer if known from headers. * May be overridden by the decoder if it knows better. * * @note This field may not match the value of the last * AVFrame output by avcodec_receive_frame() due frame * reordering. * * - encoding: Set by user. * - decoding: Set by user if known, overridden by libavcodec while * parsing the data. */ enum AVPixelFormat pix_fmt; /** * If non NULL, 'draw_horiz_band' is called by the libavcodec * decoder to draw a horizontal band. It improves cache usage. Not * all codecs can do that. You must check the codec capabilities * beforehand. * When multithreading is used, it may be called from multiple threads * at the same time; threads might draw different parts of the same AVFrame, * or multiple AVFrames, and there is no guarantee that slices will be drawn * in order. * The function is also used by hardware acceleration APIs. * It is called at least once during frame decoding to pass * the data needed for hardware render. * In that mode instead of pixel data, AVFrame points to * a structure specific to the acceleration API. The application * reads the structure and can change some fields to indicate progress * or mark state. * - encoding: unused * - decoding: Set by user. * @param height the height of the slice * @param y the y position of the slice * @param type 1->top field, 2->bottom field, 3->frame * @param offset offset into the AVFrame.data from which the slice should be read */ void (*draw_horiz_band)(struct AVCodecContext *s, const AVFrame *src, int offset[AV_NUM_DATA_POINTERS], int y, int type, int height); /** * callback to negotiate the pixelFormat * @param fmt is the list of formats which are supported by the codec, * it is terminated by -1 as 0 is a valid format, the formats are ordered by quality. * The first is always the native one. * @note The callback may be called again immediately if initialization for * the selected (hardware-accelerated) pixel format failed. * @warning Behavior is undefined if the callback returns a value not * in the fmt list of formats. * @return the chosen format * - encoding: unused * - decoding: Set by user, if not set the native format will be chosen. */ enum AVPixelFormat (*get_format)(struct AVCodecContext *s, const enum AVPixelFormat * fmt); /** * maximum number of B-frames between non-B-frames * Note: The output will be delayed by max_b_frames+1 relative to the input. * - encoding: Set by user. * - decoding: unused */ int max_b_frames; /** * qscale factor between IP and B-frames * If > 0 then the last P-frame quantizer will be used (q= lastp_q*factor+offset). * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset). * - encoding: Set by user. * - decoding: unused */ float b_quant_factor; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int b_frame_strategy; #endif /** * qscale offset between IP and B-frames * - encoding: Set by user. * - decoding: unused */ float b_quant_offset; /** * Size of the frame reordering buffer in the decoder. * For MPEG-2 it is 1 IPB or 0 low delay IP. * - encoding: Set by libavcodec. * - decoding: Set by libavcodec. */ int has_b_frames; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int mpeg_quant; #endif /** * qscale factor between P- and I-frames * If > 0 then the last P-frame quantizer will be used (q = lastp_q * factor + offset). * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset). * - encoding: Set by user. * - decoding: unused */ float i_quant_factor; /** * qscale offset between P and I-frames * - encoding: Set by user. * - decoding: unused */ float i_quant_offset; /** * luminance masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float lumi_masking; /** * temporary complexity masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float temporal_cplx_masking; /** * spatial complexity masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float spatial_cplx_masking; /** * p block masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float p_masking; /** * darkness masking (0-> disabled) * - encoding: Set by user. * - decoding: unused */ float dark_masking; /** * slice count * - encoding: Set by libavcodec. * - decoding: Set by user (or 0). */ int slice_count; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int prediction_method; #define FF_PRED_LEFT 0 #define FF_PRED_PLANE 1 #define FF_PRED_MEDIAN 2 #endif /** * slice offsets in the frame in bytes * - encoding: Set/allocated by libavcodec. * - decoding: Set/allocated by user (or NULL). */ int *slice_offset; /** * sample aspect ratio (0 if unknown) * That is the width of a pixel divided by the height of the pixel. * Numerator and denominator must be relatively prime and smaller than 256 for some video standards. * - encoding: Set by user. * - decoding: Set by libavcodec. */ AVRational sample_aspect_ratio; /** * motion estimation comparison function * - encoding: Set by user. * - decoding: unused */ int me_cmp; /** * subpixel motion estimation comparison function * - encoding: Set by user. * - decoding: unused */ int me_sub_cmp; /** * macroblock comparison function (not supported yet) * - encoding: Set by user. * - decoding: unused */ int mb_cmp; /** * interlaced DCT comparison function * - encoding: Set by user. * - decoding: unused */ int ildct_cmp; #define FF_CMP_SAD 0 #define FF_CMP_SSE 1 #define FF_CMP_SATD 2 #define FF_CMP_DCT 3 #define FF_CMP_PSNR 4 #define FF_CMP_BIT 5 #define FF_CMP_RD 6 #define FF_CMP_ZERO 7 #define FF_CMP_VSAD 8 #define FF_CMP_VSSE 9 #define FF_CMP_NSSE 10 #define FF_CMP_W53 11 #define FF_CMP_W97 12 #define FF_CMP_DCTMAX 13 #define FF_CMP_DCT264 14 #define FF_CMP_MEDIAN_SAD 15 #define FF_CMP_CHROMA 256 /** * ME diamond size & shape * - encoding: Set by user. * - decoding: unused */ int dia_size; /** * amount of previous MV predictors (2a+1 x 2a+1 square) * - encoding: Set by user. * - decoding: unused */ int last_predictor_count; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int pre_me; #endif /** * motion estimation prepass comparison function * - encoding: Set by user. * - decoding: unused */ int me_pre_cmp; /** * ME prepass diamond size & shape * - encoding: Set by user. * - decoding: unused */ int pre_dia_size; /** * subpel ME quality * - encoding: Set by user. * - decoding: unused */ int me_subpel_quality; /** * maximum motion estimation search range in subpel units * If 0 then no limit. * * - encoding: Set by user. * - decoding: unused */ int me_range; /** * slice flags * - encoding: unused * - decoding: Set by user. */ int slice_flags; #define SLICE_FLAG_CODED_ORDER 0x0001 ///< draw_horiz_band() is called in coded order instead of display #define SLICE_FLAG_ALLOW_FIELD 0x0002 ///< allow draw_horiz_band() with field slices (MPEG-2 field pics) #define SLICE_FLAG_ALLOW_PLANE 0x0004 ///< allow draw_horiz_band() with 1 component at a time (SVQ1) /** * macroblock decision mode * - encoding: Set by user. * - decoding: unused */ int mb_decision; #define FF_MB_DECISION_SIMPLE 0 ///< uses mb_cmp #define FF_MB_DECISION_BITS 1 ///< chooses the one which needs the fewest bits #define FF_MB_DECISION_RD 2 ///< rate distortion /** * custom intra quantization matrix * Must be allocated with the av_malloc() family of functions, and will be freed in * avcodec_free_context(). * - encoding: Set/allocated by user, freed by libavcodec. Can be NULL. * - decoding: Set/allocated/freed by libavcodec. */ uint16_t *intra_matrix; /** * custom inter quantization matrix * Must be allocated with the av_malloc() family of functions, and will be freed in * avcodec_free_context(). * - encoding: Set/allocated by user, freed by libavcodec. Can be NULL. * - decoding: Set/allocated/freed by libavcodec. */ uint16_t *inter_matrix; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int scenechange_threshold; /** @deprecated use encoder private options instead */ attribute_deprecated int noise_reduction; #endif /** * precision of the intra DC coefficient - 8 * - encoding: Set by user. * - decoding: Set by libavcodec */ int intra_dc_precision; /** * Number of macroblock rows at the top which are skipped. * - encoding: unused * - decoding: Set by user. */ int skip_top; /** * Number of macroblock rows at the bottom which are skipped. * - encoding: unused * - decoding: Set by user. */ int skip_bottom; /** * minimum MB Lagrange multiplier * - encoding: Set by user. * - decoding: unused */ int mb_lmin; /** * maximum MB Lagrange multiplier * - encoding: Set by user. * - decoding: unused */ int mb_lmax; #if FF_API_PRIVATE_OPT /** * @deprecated use encoder private options instead */ attribute_deprecated int me_penalty_compensation; #endif /** * - encoding: Set by user. * - decoding: unused */ int bidir_refine; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int brd_scale; #endif /** * minimum GOP size * - encoding: Set by user. * - decoding: unused */ int keyint_min; /** * number of reference frames * - encoding: Set by user. * - decoding: Set by lavc. */ int refs; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int chromaoffset; #endif /** * Note: Value depends upon the compare function used for fullpel ME. * - encoding: Set by user. * - decoding: unused */ int mv0_threshold; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int b_sensitivity; #endif /** * Chromaticity coordinates of the source primaries. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorPrimaries color_primaries; /** * Color Transfer Characteristic. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorTransferCharacteristic color_trc; /** * YUV colorspace type. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorSpace colorspace; /** * MPEG vs JPEG YUV range. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorRange color_range; /** * This defines the location of chroma samples. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVChromaLocation chroma_sample_location; /** * Number of slices. * Indicates number of picture subdivisions. Used for parallelized * decoding. * - encoding: Set by user * - decoding: unused */ int slices; /** Field order * - encoding: set by libavcodec * - decoding: Set by user. */ enum AVFieldOrder field_order; /* audio only */ int sample_rate; ///< samples per second int channels; ///< number of audio channels /** * audio sample format * - encoding: Set by user. * - decoding: Set by libavcodec. */ enum AVSampleFormat sample_fmt; ///< sample format /* The following data should not be initialized. */ /** * Number of samples per channel in an audio frame. * * - encoding: set by libavcodec in avcodec_open2(). Each submitted frame * except the last must contain exactly frame_size samples per channel. * May be 0 when the codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE set, then the * frame size is not restricted. * - decoding: may be set by some decoders to indicate constant frame size */ int frame_size; /** * Frame counter, set by libavcodec. * * - decoding: total number of frames returned from the decoder so far. * - encoding: total number of frames passed to the encoder so far. * * @note the counter is not incremented if encoding/decoding resulted in * an error. */ int frame_number; /** * number of bytes per packet if constant and known or 0 * Used by some WAV based audio codecs. */ int block_align; /** * Audio cutoff bandwidth (0 means "automatic") * - encoding: Set by user. * - decoding: unused */ int cutoff; /** * Audio channel layout. * - encoding: set by user. * - decoding: set by user, may be overwritten by libavcodec. */ uint64_t channel_layout; /** * Request decoder to use this channel layout if it can (0 for default) * - encoding: unused * - decoding: Set by user. */ uint64_t request_channel_layout; /** * Type of service that the audio stream conveys. * - encoding: Set by user. * - decoding: Set by libavcodec. */ enum AVAudioServiceType audio_service_type; /** * desired sample format * - encoding: Not used. * - decoding: Set by user. * Decoder will decode to this format if it can. */ enum AVSampleFormat request_sample_fmt; /** * This callback is called at the beginning of each frame to get data * buffer(s) for it. There may be one contiguous buffer for all the data or * there may be a buffer per each data plane or anything in between. What * this means is, you may set however many entries in buf[] you feel necessary. * Each buffer must be reference-counted using the AVBuffer API (see description * of buf[] below). * * The following fields will be set in the frame before this callback is * called: * - format * - width, height (video only) * - sample_rate, channel_layout, nb_samples (audio only) * Their values may differ from the corresponding values in * AVCodecContext. This callback must use the frame values, not the codec * context values, to calculate the required buffer size. * * This callback must fill the following fields in the frame: * - data[] * - linesize[] * - extended_data: * * if the data is planar audio with more than 8 channels, then this * callback must allocate and fill extended_data to contain all pointers * to all data planes. data[] must hold as many pointers as it can. * extended_data must be allocated with av_malloc() and will be freed in * av_frame_unref(). * * otherwise extended_data must point to data * - buf[] must contain one or more pointers to AVBufferRef structures. Each of * the frame's data and extended_data pointers must be contained in these. That * is, one AVBufferRef for each allocated chunk of memory, not necessarily one * AVBufferRef per data[] entry. See: av_buffer_create(), av_buffer_alloc(), * and av_buffer_ref(). * - extended_buf and nb_extended_buf must be allocated with av_malloc() by * this callback and filled with the extra buffers if there are more * buffers than buf[] can hold. extended_buf will be freed in * av_frame_unref(). * * If AV_CODEC_CAP_DR1 is not set then get_buffer2() must call * avcodec_default_get_buffer2() instead of providing buffers allocated by * some other means. * * Each data plane must be aligned to the maximum required by the target * CPU. * * @see avcodec_default_get_buffer2() * * Video: * * If AV_GET_BUFFER_FLAG_REF is set in flags then the frame may be reused * (read and/or written to if it is writable) later by libavcodec. * * avcodec_align_dimensions2() should be used to find the required width and * height, as they normally need to be rounded up to the next multiple of 16. * * Some decoders do not support linesizes changing between frames. * * If frame multithreading is used and thread_safe_callbacks is set, * this callback may be called from a different thread, but not from more * than one at once. Does not need to be reentrant. * * @see avcodec_align_dimensions2() * * Audio: * * Decoders request a buffer of a particular size by setting * AVFrame.nb_samples prior to calling get_buffer2(). The decoder may, * however, utilize only part of the buffer by setting AVFrame.nb_samples * to a smaller value in the output frame. * * As a convenience, av_samples_get_buffer_size() and * av_samples_fill_arrays() in libavutil may be used by custom get_buffer2() * functions to find the required data size and to fill data pointers and * linesize. In AVFrame.linesize, only linesize[0] may be set for audio * since all planes must be the same size. * * @see av_samples_get_buffer_size(), av_samples_fill_arrays() * * - encoding: unused * - decoding: Set by libavcodec, user can override. */ int (*get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags); /** * If non-zero, the decoded audio and video frames returned from * avcodec_decode_video2() and avcodec_decode_audio4() are reference-counted * and are valid indefinitely. The caller must free them with * av_frame_unref() when they are not needed anymore. * Otherwise, the decoded frames must not be freed by the caller and are * only valid until the next decode call. * * This is always automatically enabled if avcodec_receive_frame() is used. * * - encoding: unused * - decoding: set by the caller before avcodec_open2(). */ attribute_deprecated int refcounted_frames; /* - encoding parameters */ float qcompress; ///< amount of qscale change between easy & hard scenes (0.0-1.0) float qblur; ///< amount of qscale smoothing over time (0.0-1.0) /** * minimum quantizer * - encoding: Set by user. * - decoding: unused */ int qmin; /** * maximum quantizer * - encoding: Set by user. * - decoding: unused */ int qmax; /** * maximum quantizer difference between frames * - encoding: Set by user. * - decoding: unused */ int max_qdiff; /** * decoder bitstream buffer size * - encoding: Set by user. * - decoding: unused */ int rc_buffer_size; /** * ratecontrol override, see RcOverride * - encoding: Allocated/set/freed by user. * - decoding: unused */ int rc_override_count; RcOverride *rc_override; /** * maximum bitrate * - encoding: Set by user. * - decoding: Set by user, may be overwritten by libavcodec. */ int64_t rc_max_rate; /** * minimum bitrate * - encoding: Set by user. * - decoding: unused */ int64_t rc_min_rate; /** * Ratecontrol attempt to use, at maximum, of what can be used without an underflow. * - encoding: Set by user. * - decoding: unused. */ float rc_max_available_vbv_use; /** * Ratecontrol attempt to use, at least, times the amount needed to prevent a vbv overflow. * - encoding: Set by user. * - decoding: unused. */ float rc_min_vbv_overflow_use; /** * Number of bits which should be loaded into the rc buffer before decoding starts. * - encoding: Set by user. * - decoding: unused */ int rc_initial_buffer_occupancy; #if FF_API_CODER_TYPE #define FF_CODER_TYPE_VLC 0 #define FF_CODER_TYPE_AC 1 #define FF_CODER_TYPE_RAW 2 #define FF_CODER_TYPE_RLE 3 /** * @deprecated use encoder private options instead */ attribute_deprecated int coder_type; #endif /* FF_API_CODER_TYPE */ #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int context_model; #endif #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int frame_skip_threshold; /** @deprecated use encoder private options instead */ attribute_deprecated int frame_skip_factor; /** @deprecated use encoder private options instead */ attribute_deprecated int frame_skip_exp; /** @deprecated use encoder private options instead */ attribute_deprecated int frame_skip_cmp; #endif /* FF_API_PRIVATE_OPT */ /** * trellis RD quantization * - encoding: Set by user. * - decoding: unused */ int trellis; #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int min_prediction_order; /** @deprecated use encoder private options instead */ attribute_deprecated int max_prediction_order; /** @deprecated use encoder private options instead */ attribute_deprecated int64_t timecode_frame_start; #endif #if FF_API_RTP_CALLBACK /** * @deprecated unused */ /* The RTP callback: This function is called */ /* every time the encoder has a packet to send. */ /* It depends on the encoder if the data starts */ /* with a Start Code (it should). H.263 does. */ /* mb_nb contains the number of macroblocks */ /* encoded in the RTP payload. */ attribute_deprecated void (*rtp_callback)(struct AVCodecContext *avctx, void *data, int size, int mb_nb); #endif #if FF_API_PRIVATE_OPT /** @deprecated use encoder private options instead */ attribute_deprecated int rtp_payload_size; /* The size of the RTP payload: the coder will */ /* do its best to deliver a chunk with size */ /* below rtp_payload_size, the chunk will start */ /* with a start code on some codecs like H.263. */ /* This doesn't take account of any particular */ /* headers inside the transmitted RTP payload. */ #endif #if FF_API_STAT_BITS /* statistics, used for 2-pass encoding */ attribute_deprecated int mv_bits; attribute_deprecated int header_bits; attribute_deprecated int i_tex_bits; attribute_deprecated int p_tex_bits; attribute_deprecated int i_count; attribute_deprecated int p_count; attribute_deprecated int skip_count; attribute_deprecated int misc_bits; /** @deprecated this field is unused */ attribute_deprecated int frame_bits; #endif /** * pass1 encoding statistics output buffer * - encoding: Set by libavcodec. * - decoding: unused */ char *stats_out; /** * pass2 encoding statistics input buffer * Concatenated stuff from stats_out of pass1 should be placed here. * - encoding: Allocated/set/freed by user. * - decoding: unused */ char *stats_in; /** * Work around bugs in encoders which sometimes cannot be detected automatically. * - encoding: Set by user * - decoding: Set by user */ int workaround_bugs; #define FF_BUG_AUTODETECT 1 ///< autodetection #define FF_BUG_XVID_ILACE 4 #define FF_BUG_UMP4 8 #define FF_BUG_NO_PADDING 16 #define FF_BUG_AMV 32 #define FF_BUG_QPEL_CHROMA 64 #define FF_BUG_STD_QPEL 128 #define FF_BUG_QPEL_CHROMA2 256 #define FF_BUG_DIRECT_BLOCKSIZE 512 #define FF_BUG_EDGE 1024 #define FF_BUG_HPEL_CHROMA 2048 #define FF_BUG_DC_CLIP 4096 #define FF_BUG_MS 8192 ///< Work around various bugs in Microsoft's broken decoders. #define FF_BUG_TRUNCATED 16384 #define FF_BUG_IEDGE 32768 /** * strictly follow the standard (MPEG-4, ...). * - encoding: Set by user. * - decoding: Set by user. * Setting this to STRICT or higher means the encoder and decoder will * generally do stupid things, whereas setting it to unofficial or lower * will mean the encoder might produce output that is not supported by all * spec-compliant decoders. Decoders don't differentiate between normal, * unofficial and experimental (that is, they always try to decode things * when they can) unless they are explicitly asked to behave stupidly * (=strictly conform to the specs) */ int strict_std_compliance; #define FF_COMPLIANCE_VERY_STRICT 2 ///< Strictly conform to an older more strict version of the spec or reference software. #define FF_COMPLIANCE_STRICT 1 ///< Strictly conform to all the things in the spec no matter what consequences. #define FF_COMPLIANCE_NORMAL 0 #define FF_COMPLIANCE_UNOFFICIAL -1 ///< Allow unofficial extensions #define FF_COMPLIANCE_EXPERIMENTAL -2 ///< Allow nonstandardized experimental things. /** * error concealment flags * - encoding: unused * - decoding: Set by user. */ int error_concealment; #define FF_EC_GUESS_MVS 1 #define FF_EC_DEBLOCK 2 #define FF_EC_FAVOR_INTER 256 /** * debug * - encoding: Set by user. * - decoding: Set by user. */ int debug; #define FF_DEBUG_PICT_INFO 1 #define FF_DEBUG_RC 2 #define FF_DEBUG_BITSTREAM 4 #define FF_DEBUG_MB_TYPE 8 #define FF_DEBUG_QP 16 #if FF_API_DEBUG_MV /** * @deprecated this option does nothing */ #define FF_DEBUG_MV 32 #endif #define FF_DEBUG_DCT_COEFF 0x00000040 #define FF_DEBUG_SKIP 0x00000080 #define FF_DEBUG_STARTCODE 0x00000100 #define FF_DEBUG_ER 0x00000400 #define FF_DEBUG_MMCO 0x00000800 #define FF_DEBUG_BUGS 0x00001000 #if FF_API_DEBUG_MV #define FF_DEBUG_VIS_QP 0x00002000 #define FF_DEBUG_VIS_MB_TYPE 0x00004000 #endif #define FF_DEBUG_BUFFERS 0x00008000 #define FF_DEBUG_THREADS 0x00010000 #define FF_DEBUG_GREEN_MD 0x00800000 #define FF_DEBUG_NOMC 0x01000000 #if FF_API_DEBUG_MV /** * debug * - encoding: Set by user. * - decoding: Set by user. */ int debug_mv; #define FF_DEBUG_VIS_MV_P_FOR 0x00000001 // visualize forward predicted MVs of P-frames #define FF_DEBUG_VIS_MV_B_FOR 0x00000002 // visualize forward predicted MVs of B-frames #define FF_DEBUG_VIS_MV_B_BACK 0x00000004 // visualize backward predicted MVs of B-frames #endif /** * Error recognition; may misdetect some more or less valid parts as errors. * - encoding: unused * - decoding: Set by user. */ int err_recognition; /** * Verify checksums embedded in the bitstream (could be of either encoded or * decoded data, depending on the codec) and print an error message on mismatch. * If AV_EF_EXPLODE is also set, a mismatching checksum will result in the * decoder returning an error. */ #define AV_EF_CRCCHECK (1<<0) #define AV_EF_BITSTREAM (1<<1) ///< detect bitstream specification deviations #define AV_EF_BUFFER (1<<2) ///< detect improper bitstream length #define AV_EF_EXPLODE (1<<3) ///< abort decoding on minor error detection #define AV_EF_IGNORE_ERR (1<<15) ///< ignore errors and continue #define AV_EF_CAREFUL (1<<16) ///< consider things that violate the spec, are fast to calculate and have not been seen in the wild as errors #define AV_EF_COMPLIANT (1<<17) ///< consider all spec non compliances as errors #define AV_EF_AGGRESSIVE (1<<18) ///< consider things that a sane encoder should not do as an error /** * opaque 64-bit number (generally a PTS) that will be reordered and * output in AVFrame.reordered_opaque * - encoding: Set by libavcodec to the reordered_opaque of the input * frame corresponding to the last returned packet. Only * supported by encoders with the * AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE capability. * - decoding: Set by user. */ int64_t reordered_opaque; /** * Hardware accelerator in use * - encoding: unused. * - decoding: Set by libavcodec */ const struct AVHWAccel *hwaccel; /** * Hardware accelerator context. * For some hardware accelerators, a global context needs to be * provided by the user. In that case, this holds display-dependent * data FFmpeg cannot instantiate itself. Please refer to the * FFmpeg HW accelerator documentation to know how to fill this * is. e.g. for VA API, this is a struct vaapi_context. * - encoding: unused * - decoding: Set by user */ void *hwaccel_context; /** * error * - encoding: Set by libavcodec if flags & AV_CODEC_FLAG_PSNR. * - decoding: unused */ uint64_t error[AV_NUM_DATA_POINTERS]; /** * DCT algorithm, see FF_DCT_* below * - encoding: Set by user. * - decoding: unused */ int dct_algo; #define FF_DCT_AUTO 0 #define FF_DCT_FASTINT 1 #define FF_DCT_INT 2 #define FF_DCT_MMX 3 #define FF_DCT_ALTIVEC 5 #define FF_DCT_FAAN 6 /** * IDCT algorithm, see FF_IDCT_* below. * - encoding: Set by user. * - decoding: Set by user. */ int idct_algo; #define FF_IDCT_AUTO 0 #define FF_IDCT_INT 1 #define FF_IDCT_SIMPLE 2 #define FF_IDCT_SIMPLEMMX 3 #define FF_IDCT_ARM 7 #define FF_IDCT_ALTIVEC 8 #define FF_IDCT_SIMPLEARM 10 #define FF_IDCT_XVID 14 #define FF_IDCT_SIMPLEARMV5TE 16 #define FF_IDCT_SIMPLEARMV6 17 #define FF_IDCT_FAAN 20 #define FF_IDCT_SIMPLENEON 22 #define FF_IDCT_NONE 24 /* Used by XvMC to extract IDCT coefficients with FF_IDCT_PERM_NONE */ #define FF_IDCT_SIMPLEAUTO 128 /** * bits per sample/pixel from the demuxer (needed for huffyuv). * - encoding: Set by libavcodec. * - decoding: Set by user. */ int bits_per_coded_sample; /** * Bits per sample/pixel of internal libavcodec pixel/sample format. * - encoding: set by user. * - decoding: set by libavcodec. */ int bits_per_raw_sample; #if FF_API_LOWRES /** * low resolution decoding, 1-> 1/2 size, 2->1/4 size * - encoding: unused * - decoding: Set by user. */ int lowres; #endif #if FF_API_CODED_FRAME /** * the picture in the bitstream * - encoding: Set by libavcodec. * - decoding: unused * * @deprecated use the quality factor packet side data instead */ attribute_deprecated AVFrame *coded_frame; #endif /** * thread count * is used to decide how many independent tasks should be passed to execute() * - encoding: Set by user. * - decoding: Set by user. */ int thread_count; /** * Which multithreading methods to use. * Use of FF_THREAD_FRAME will increase decoding delay by one frame per thread, * so clients which cannot provide future frames should not use it. * * - encoding: Set by user, otherwise the default is used. * - decoding: Set by user, otherwise the default is used. */ int thread_type; #define FF_THREAD_FRAME 1 ///< Decode more than one frame at once #define FF_THREAD_SLICE 2 ///< Decode more than one part of a single frame at once /** * Which multithreading methods are in use by the codec. * - encoding: Set by libavcodec. * - decoding: Set by libavcodec. */ int active_thread_type; /** * Set by the client if its custom get_buffer() callback can be called * synchronously from another thread, which allows faster multithreaded decoding. * draw_horiz_band() will be called from other threads regardless of this setting. * Ignored if the default get_buffer() is used. * - encoding: Set by user. * - decoding: Set by user. */ int thread_safe_callbacks; /** * The codec may call this to execute several independent things. * It will return only after finishing all tasks. * The user may replace this with some multithreaded implementation, * the default implementation will execute the parts serially. * @param count the number of things to execute * - encoding: Set by libavcodec, user can override. * - decoding: Set by libavcodec, user can override. */ int (*execute)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg), void *arg2, int *ret, int count, int size); /** * The codec may call this to execute several independent things. * It will return only after finishing all tasks. * The user may replace this with some multithreaded implementation, * the default implementation will execute the parts serially. * Also see avcodec_thread_init and e.g. the --enable-pthread configure option. * @param c context passed also to func * @param count the number of things to execute * @param arg2 argument passed unchanged to func * @param ret return values of executed functions, must have space for "count" values. May be NULL. * @param func function that will be called count times, with jobnr from 0 to count-1. * threadnr will be in the range 0 to c->thread_count-1 < MAX_THREADS and so that no * two instances of func executing at the same time will have the same threadnr. * @return always 0 currently, but code should handle a future improvement where when any call to func * returns < 0 no further calls to func may be done and < 0 is returned. * - encoding: Set by libavcodec, user can override. * - decoding: Set by libavcodec, user can override. */ int (*execute2)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg, int jobnr, int threadnr), void *arg2, int *ret, int count); /** * noise vs. sse weight for the nsse comparison function * - encoding: Set by user. * - decoding: unused */ int nsse_weight; /** * profile * - encoding: Set by user. * - decoding: Set by libavcodec. */ int profile; #define FF_PROFILE_UNKNOWN -99 #define FF_PROFILE_RESERVED -100 #define FF_PROFILE_AAC_MAIN 0 #define FF_PROFILE_AAC_LOW 1 #define FF_PROFILE_AAC_SSR 2 #define FF_PROFILE_AAC_LTP 3 #define FF_PROFILE_AAC_HE 4 #define FF_PROFILE_AAC_HE_V2 28 #define FF_PROFILE_AAC_LD 22 #define FF_PROFILE_AAC_ELD 38 #define FF_PROFILE_MPEG2_AAC_LOW 128 #define FF_PROFILE_MPEG2_AAC_HE 131 #define FF_PROFILE_DNXHD 0 #define FF_PROFILE_DNXHR_LB 1 #define FF_PROFILE_DNXHR_SQ 2 #define FF_PROFILE_DNXHR_HQ 3 #define FF_PROFILE_DNXHR_HQX 4 #define FF_PROFILE_DNXHR_444 5 #define FF_PROFILE_DTS 20 #define FF_PROFILE_DTS_ES 30 #define FF_PROFILE_DTS_96_24 40 #define FF_PROFILE_DTS_HD_HRA 50 #define FF_PROFILE_DTS_HD_MA 60 #define FF_PROFILE_DTS_EXPRESS 70 #define FF_PROFILE_MPEG2_422 0 #define FF_PROFILE_MPEG2_HIGH 1 #define FF_PROFILE_MPEG2_SS 2 #define FF_PROFILE_MPEG2_SNR_SCALABLE 3 #define FF_PROFILE_MPEG2_MAIN 4 #define FF_PROFILE_MPEG2_SIMPLE 5 #define FF_PROFILE_H264_CONSTRAINED (1<<9) // 8+1; constraint_set1_flag #define FF_PROFILE_H264_INTRA (1<<11) // 8+3; constraint_set3_flag #define FF_PROFILE_H264_BASELINE 66 #define FF_PROFILE_H264_CONSTRAINED_BASELINE (66|FF_PROFILE_H264_CONSTRAINED) #define FF_PROFILE_H264_MAIN 77 #define FF_PROFILE_H264_EXTENDED 88 #define FF_PROFILE_H264_HIGH 100 #define FF_PROFILE_H264_HIGH_10 110 #define FF_PROFILE_H264_HIGH_10_INTRA (110|FF_PROFILE_H264_INTRA) #define FF_PROFILE_H264_MULTIVIEW_HIGH 118 #define FF_PROFILE_H264_HIGH_422 122 #define FF_PROFILE_H264_HIGH_422_INTRA (122|FF_PROFILE_H264_INTRA) #define FF_PROFILE_H264_STEREO_HIGH 128 #define FF_PROFILE_H264_HIGH_444 144 #define FF_PROFILE_H264_HIGH_444_PREDICTIVE 244 #define FF_PROFILE_H264_HIGH_444_INTRA (244|FF_PROFILE_H264_INTRA) #define FF_PROFILE_H264_CAVLC_444 44 #define FF_PROFILE_VC1_SIMPLE 0 #define FF_PROFILE_VC1_MAIN 1 #define FF_PROFILE_VC1_COMPLEX 2 #define FF_PROFILE_VC1_ADVANCED 3 #define FF_PROFILE_MPEG4_SIMPLE 0 #define FF_PROFILE_MPEG4_SIMPLE_SCALABLE 1 #define FF_PROFILE_MPEG4_CORE 2 #define FF_PROFILE_MPEG4_MAIN 3 #define FF_PROFILE_MPEG4_N_BIT 4 #define FF_PROFILE_MPEG4_SCALABLE_TEXTURE 5 #define FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION 6 #define FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE 7 #define FF_PROFILE_MPEG4_HYBRID 8 #define FF_PROFILE_MPEG4_ADVANCED_REAL_TIME 9 #define FF_PROFILE_MPEG4_CORE_SCALABLE 10 #define FF_PROFILE_MPEG4_ADVANCED_CODING 11 #define FF_PROFILE_MPEG4_ADVANCED_CORE 12 #define FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE 13 #define FF_PROFILE_MPEG4_SIMPLE_STUDIO 14 #define FF_PROFILE_MPEG4_ADVANCED_SIMPLE 15 #define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0 1 #define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1 2 #define FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION 32768 #define FF_PROFILE_JPEG2000_DCINEMA_2K 3 #define FF_PROFILE_JPEG2000_DCINEMA_4K 4 #define FF_PROFILE_VP9_0 0 #define FF_PROFILE_VP9_1 1 #define FF_PROFILE_VP9_2 2 #define FF_PROFILE_VP9_3 3 #define FF_PROFILE_HEVC_MAIN 1 #define FF_PROFILE_HEVC_MAIN_10 2 #define FF_PROFILE_HEVC_MAIN_STILL_PICTURE 3 #define FF_PROFILE_HEVC_REXT 4 #define FF_PROFILE_AV1_MAIN 0 #define FF_PROFILE_AV1_HIGH 1 #define FF_PROFILE_AV1_PROFESSIONAL 2 #define FF_PROFILE_MJPEG_HUFFMAN_BASELINE_DCT 0xc0 #define FF_PROFILE_MJPEG_HUFFMAN_EXTENDED_SEQUENTIAL_DCT 0xc1 #define FF_PROFILE_MJPEG_HUFFMAN_PROGRESSIVE_DCT 0xc2 #define FF_PROFILE_MJPEG_HUFFMAN_LOSSLESS 0xc3 #define FF_PROFILE_MJPEG_JPEG_LS 0xf7 #define FF_PROFILE_SBC_MSBC 1 #define FF_PROFILE_PRORES_PROXY 0 #define FF_PROFILE_PRORES_LT 1 #define FF_PROFILE_PRORES_STANDARD 2 #define FF_PROFILE_PRORES_HQ 3 #define FF_PROFILE_PRORES_4444 4 #define FF_PROFILE_PRORES_XQ 5 #define FF_PROFILE_ARIB_PROFILE_A 0 #define FF_PROFILE_ARIB_PROFILE_C 1 /** * level * - encoding: Set by user. * - decoding: Set by libavcodec. */ int level; #define FF_LEVEL_UNKNOWN -99 /** * Skip loop filtering for selected frames. * - encoding: unused * - decoding: Set by user. */ enum AVDiscard skip_loop_filter; /** * Skip IDCT/dequantization for selected frames. * - encoding: unused * - decoding: Set by user. */ enum AVDiscard skip_idct; /** * Skip decoding for selected frames. * - encoding: unused * - decoding: Set by user. */ enum AVDiscard skip_frame; /** * Header containing style information for text subtitles. * For SUBTITLE_ASS subtitle type, it should contain the whole ASS * [Script Info] and [V4+ Styles] section, plus the [Events] line and * the Format line following. It shouldn't include any Dialogue line. * - encoding: Set/allocated/freed by user (before avcodec_open2()) * - decoding: Set/allocated/freed by libavcodec (by avcodec_open2()) */ uint8_t *subtitle_header; int subtitle_header_size; #if FF_API_VBV_DELAY /** * VBV delay coded in the last frame (in periods of a 27 MHz clock). * Used for compliant TS muxing. * - encoding: Set by libavcodec. * - decoding: unused. * @deprecated this value is now exported as a part of * AV_PKT_DATA_CPB_PROPERTIES packet side data */ attribute_deprecated uint64_t vbv_delay; #endif #if FF_API_SIDEDATA_ONLY_PKT /** * Encoding only and set by default. Allow encoders to output packets * that do not contain any encoded data, only side data. * * Some encoders need to output such packets, e.g. to update some stream * parameters at the end of encoding. * * @deprecated this field disables the default behaviour and * it is kept only for compatibility. */ attribute_deprecated int side_data_only_packets; #endif /** * Audio only. The number of "priming" samples (padding) inserted by the * encoder at the beginning of the audio. I.e. this number of leading * decoded samples must be discarded by the caller to get the original audio * without leading padding. * * - decoding: unused * - encoding: Set by libavcodec. The timestamps on the output packets are * adjusted by the encoder so that they always refer to the * first sample of the data actually contained in the packet, * including any added padding. E.g. if the timebase is * 1/samplerate and the timestamp of the first input sample is * 0, the timestamp of the first output packet will be * -initial_padding. */ int initial_padding; /** * - decoding: For codecs that store a framerate value in the compressed * bitstream, the decoder may export it here. { 0, 1} when * unknown. * - encoding: May be used to signal the framerate of CFR content to an * encoder. */ AVRational framerate; /** * Nominal unaccelerated pixel format, see AV_PIX_FMT_xxx. * - encoding: unused. * - decoding: Set by libavcodec before calling get_format() */ enum AVPixelFormat sw_pix_fmt; /** * Timebase in which pkt_dts/pts and AVPacket.dts/pts are. * - encoding unused. * - decoding set by user. */ AVRational pkt_timebase; /** * AVCodecDescriptor * - encoding: unused. * - decoding: set by libavcodec. */ const AVCodecDescriptor *codec_descriptor; #if !FF_API_LOWRES /** * low resolution decoding, 1-> 1/2 size, 2->1/4 size * - encoding: unused * - decoding: Set by user. */ int lowres; #endif /** * Current statistics for PTS correction. * - decoding: maintained and used by libavcodec, not intended to be used by user apps * - encoding: unused */ int64_t pts_correction_num_faulty_pts; /// Number of incorrect PTS values so far int64_t pts_correction_num_faulty_dts; /// Number of incorrect DTS values so far int64_t pts_correction_last_pts; /// PTS of the last frame int64_t pts_correction_last_dts; /// DTS of the last frame /** * Character encoding of the input subtitles file. * - decoding: set by user * - encoding: unused */ char *sub_charenc; /** * Subtitles character encoding mode. Formats or codecs might be adjusting * this setting (if they are doing the conversion themselves for instance). * - decoding: set by libavcodec * - encoding: unused */ int sub_charenc_mode; #define FF_SUB_CHARENC_MODE_DO_NOTHING -1 ///< do nothing (demuxer outputs a stream supposed to be already in UTF-8, or the codec is bitmap for instance) #define FF_SUB_CHARENC_MODE_AUTOMATIC 0 ///< libavcodec will select the mode itself #define FF_SUB_CHARENC_MODE_PRE_DECODER 1 ///< the AVPacket data needs to be recoded to UTF-8 before being fed to the decoder, requires iconv #define FF_SUB_CHARENC_MODE_IGNORE 2 ///< neither convert the subtitles, nor check them for valid UTF-8 /** * Skip processing alpha if supported by codec. * Note that if the format uses pre-multiplied alpha (common with VP6, * and recommended due to better video quality/compression) * the image will look as if alpha-blended onto a black background. * However for formats that do not use pre-multiplied alpha * there might be serious artefacts (though e.g. libswscale currently * assumes pre-multiplied alpha anyway). * * - decoding: set by user * - encoding: unused */ int skip_alpha; /** * Number of samples to skip after a discontinuity * - decoding: unused * - encoding: set by libavcodec */ int seek_preroll; #if !FF_API_DEBUG_MV /** * debug motion vectors * - encoding: Set by user. * - decoding: Set by user. */ int debug_mv; #define FF_DEBUG_VIS_MV_P_FOR 0x00000001 //visualize forward predicted MVs of P frames #define FF_DEBUG_VIS_MV_B_FOR 0x00000002 //visualize forward predicted MVs of B frames #define FF_DEBUG_VIS_MV_B_BACK 0x00000004 //visualize backward predicted MVs of B frames #endif /** * custom intra quantization matrix * - encoding: Set by user, can be NULL. * - decoding: unused. */ uint16_t *chroma_intra_matrix; /** * dump format separator. * can be ", " or "\n " or anything else * - encoding: Set by user. * - decoding: Set by user. */ uint8_t *dump_separator; /** * ',' separated list of allowed decoders. * If NULL then all are allowed * - encoding: unused * - decoding: set by user */ char *codec_whitelist; /** * Properties of the stream that gets decoded * - encoding: unused * - decoding: set by libavcodec */ unsigned properties; #define FF_CODEC_PROPERTY_LOSSLESS 0x00000001 #define FF_CODEC_PROPERTY_CLOSED_CAPTIONS 0x00000002 /** * Additional data associated with the entire coded stream. * * - decoding: unused * - encoding: may be set by libavcodec after avcodec_open2(). */ AVPacketSideData *coded_side_data; int nb_coded_side_data; /** * A reference to the AVHWFramesContext describing the input (for encoding) * or output (decoding) frames. The reference is set by the caller and * afterwards owned (and freed) by libavcodec - it should never be read by * the caller after being set. * * - decoding: This field should be set by the caller from the get_format() * callback. The previous reference (if any) will always be * unreffed by libavcodec before the get_format() call. * * If the default get_buffer2() is used with a hwaccel pixel * format, then this AVHWFramesContext will be used for * allocating the frame buffers. * * - encoding: For hardware encoders configured to use a hwaccel pixel * format, this field should be set by the caller to a reference * to the AVHWFramesContext describing input frames. * AVHWFramesContext.format must be equal to * AVCodecContext.pix_fmt. * * This field should be set before avcodec_open2() is called. */ AVBufferRef *hw_frames_ctx; /** * Control the form of AVSubtitle.rects[N]->ass * - decoding: set by user * - encoding: unused */ int sub_text_format; #define FF_SUB_TEXT_FMT_ASS 0 #if FF_API_ASS_TIMING #define FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS 1 #endif /** * Audio only. The amount of padding (in samples) appended by the encoder to * the end of the audio. I.e. this number of decoded samples must be * discarded by the caller from the end of the stream to get the original * audio without any trailing padding. * * - decoding: unused * - encoding: unused */ int trailing_padding; /** * The number of pixels per image to maximally accept. * * - decoding: set by user * - encoding: set by user */ int64_t max_pixels; /** * A reference to the AVHWDeviceContext describing the device which will * be used by a hardware encoder/decoder. The reference is set by the * caller and afterwards owned (and freed) by libavcodec. * * This should be used if either the codec device does not require * hardware frames or any that are used are to be allocated internally by * libavcodec. If the user wishes to supply any of the frames used as * encoder input or decoder output then hw_frames_ctx should be used * instead. When hw_frames_ctx is set in get_format() for a decoder, this * field will be ignored while decoding the associated stream segment, but * may again be used on a following one after another get_format() call. * * For both encoders and decoders this field should be set before * avcodec_open2() is called and must not be written to thereafter. * * Note that some decoders may require this field to be set initially in * order to support hw_frames_ctx at all - in that case, all frames * contexts used must be created on the same device. */ AVBufferRef *hw_device_ctx; /** * Bit set of AV_HWACCEL_FLAG_* flags, which affect hardware accelerated * decoding (if active). * - encoding: unused * - decoding: Set by user (either before avcodec_open2(), or in the * AVCodecContext.get_format callback) */ int hwaccel_flags; /** * Video decoding only. Certain video codecs support cropping, meaning that * only a sub-rectangle of the decoded frame is intended for display. This * option controls how cropping is handled by libavcodec. * * When set to 1 (the default), libavcodec will apply cropping internally. * I.e. it will modify the output frame width/height fields and offset the * data pointers (only by as much as possible while preserving alignment, or * by the full amount if the AV_CODEC_FLAG_UNALIGNED flag is set) so that * the frames output by the decoder refer only to the cropped area. The * crop_* fields of the output frames will be zero. * * When set to 0, the width/height fields of the output frames will be set * to the coded dimensions and the crop_* fields will describe the cropping * rectangle. Applying the cropping is left to the caller. * * @warning When hardware acceleration with opaque output frames is used, * libavcodec is unable to apply cropping from the top/left border. * * @note when this option is set to zero, the width/height fields of the * AVCodecContext and output AVFrames have different meanings. The codec * context fields store display dimensions (with the coded dimensions in * coded_width/height), while the frame fields store the coded dimensions * (with the display dimensions being determined by the crop_* fields). */ int apply_cropping; /* * Video decoding only. Sets the number of extra hardware frames which * the decoder will allocate for use by the caller. This must be set * before avcodec_open2() is called. * * Some hardware decoders require all frames that they will use for * output to be defined in advance before decoding starts. For such * decoders, the hardware frame pool must therefore be of a fixed size. * The extra frames set here are on top of any number that the decoder * needs internally in order to operate normally (for example, frames * used as reference pictures). */ int extra_hw_frames; /** * The percentage of damaged samples to discard a frame. * * - decoding: set by user * - encoding: unused */ int discard_damaged_percentage; } AVCodecContext; #if FF_API_CODEC_GET_SET /** * Accessors for some AVCodecContext fields. These used to be provided for ABI * compatibility, and do not need to be used anymore. */ attribute_deprecated AVRational av_codec_get_pkt_timebase (const AVCodecContext *avctx); attribute_deprecated void av_codec_set_pkt_timebase (AVCodecContext *avctx, AVRational val); attribute_deprecated const AVCodecDescriptor *av_codec_get_codec_descriptor(const AVCodecContext *avctx); attribute_deprecated void av_codec_set_codec_descriptor(AVCodecContext *avctx, const AVCodecDescriptor *desc); attribute_deprecated unsigned av_codec_get_codec_properties(const AVCodecContext *avctx); #if FF_API_LOWRES attribute_deprecated int av_codec_get_lowres(const AVCodecContext *avctx); attribute_deprecated void av_codec_set_lowres(AVCodecContext *avctx, int val); #endif attribute_deprecated int av_codec_get_seek_preroll(const AVCodecContext *avctx); attribute_deprecated void av_codec_set_seek_preroll(AVCodecContext *avctx, int val); attribute_deprecated uint16_t *av_codec_get_chroma_intra_matrix(const AVCodecContext *avctx); attribute_deprecated void av_codec_set_chroma_intra_matrix(AVCodecContext *avctx, uint16_t *val); #endif /** * AVProfile. */ typedef struct AVProfile { int profile; const char *name; ///< short name for the profile } AVProfile; enum { /** * The codec supports this format via the hw_device_ctx interface. * * When selecting this format, AVCodecContext.hw_device_ctx should * have been set to a device of the specified type before calling * avcodec_open2(). */ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX = 0x01, /** * The codec supports this format via the hw_frames_ctx interface. * * When selecting this format for a decoder, * AVCodecContext.hw_frames_ctx should be set to a suitable frames * context inside the get_format() callback. The frames context * must have been created on a device of the specified type. */ AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX = 0x02, /** * The codec supports this format by some internal method. * * This format can be selected without any additional configuration - * no device or frames context is required. */ AV_CODEC_HW_CONFIG_METHOD_INTERNAL = 0x04, /** * The codec supports this format by some ad-hoc method. * * Additional settings and/or function calls are required. See the * codec-specific documentation for details. (Methods requiring * this sort of configuration are deprecated and others should be * used in preference.) */ AV_CODEC_HW_CONFIG_METHOD_AD_HOC = 0x08, }; typedef struct AVCodecHWConfig { /** * A hardware pixel format which the codec can use. */ enum AVPixelFormat pix_fmt; /** * Bit set of AV_CODEC_HW_CONFIG_METHOD_* flags, describing the possible * setup methods which can be used with this configuration. */ int methods; /** * The device type associated with the configuration. * * Must be set for AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX and * AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX, otherwise unused. */ enum AVHWDeviceType device_type; } AVCodecHWConfig; typedef struct AVCodecDefault AVCodecDefault; struct AVSubtitle; /** * AVCodec. */ typedef struct AVCodec { /** * Name of the codec implementation. * The name is globally unique among encoders and among decoders (but an * encoder and a decoder can share the same name). * This is the primary way to find a codec from the user perspective. */ const char *name; /** * Descriptive name for the codec, meant to be more human readable than name. * You should use the NULL_IF_CONFIG_SMALL() macro to define it. */ const char *long_name; enum AVMediaType type; enum AVCodecID id; /** * Codec capabilities. * see AV_CODEC_CAP_* */ int capabilities; const AVRational *supported_framerates; ///< array of supported framerates, or NULL if any, array is terminated by {0,0} const enum AVPixelFormat *pix_fmts; ///< array of supported pixel formats, or NULL if unknown, array is terminated by -1 const int *supported_samplerates; ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0 const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1 const uint64_t *channel_layouts; ///< array of support channel layouts, or NULL if unknown. array is terminated by 0 uint8_t max_lowres; ///< maximum value for lowres supported by the decoder const AVClass *priv_class; ///< AVClass for the private context const AVProfile *profiles; ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN} /** * Group name of the codec implementation. * This is a short symbolic name of the wrapper backing this codec. A * wrapper uses some kind of external implementation for the codec, such * as an external library, or a codec implementation provided by the OS or * the hardware. * If this field is NULL, this is a builtin, libavcodec native codec. * If non-NULL, this will be the suffix in AVCodec.name in most cases * (usually AVCodec.name will be of the form "_"). */ const char *wrapper_name; /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavcodec and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ int priv_data_size; struct AVCodec *next; /** * @name Frame-level threading support functions * @{ */ /** * If defined, called on thread contexts when they are created. * If the codec allocates writable tables in init(), re-allocate them here. * priv_data will be set to a copy of the original. */ int (*init_thread_copy)(AVCodecContext *); /** * Copy necessary context variables from a previous thread context to the current one. * If not defined, the next thread will start automatically; otherwise, the codec * must call ff_thread_finish_setup(). * * dst and src will (rarely) point to the same context, in which case memcpy should be skipped. */ int (*update_thread_context)(AVCodecContext *dst, const AVCodecContext *src); /** @} */ /** * Private codec-specific defaults. */ const AVCodecDefault *defaults; /** * Initialize codec static data, called from avcodec_register(). * * This is not intended for time consuming operations as it is * run for every codec regardless of that codec being used. */ void (*init_static_data)(struct AVCodec *codec); int (*init)(AVCodecContext *); int (*encode_sub)(AVCodecContext *, uint8_t *buf, int buf_size, const struct AVSubtitle *sub); /** * Encode data to an AVPacket. * * @param avctx codec context * @param avpkt output AVPacket (may contain a user-provided buffer) * @param[in] frame AVFrame containing the raw data to be encoded * @param[out] got_packet_ptr encoder sets to 0 or 1 to indicate that a * non-empty packet was returned in avpkt. * @return 0 on success, negative error code on failure */ int (*encode2)(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr); int (*decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt); int (*close)(AVCodecContext *); /** * Encode API with decoupled packet/frame dataflow. The API is the * same as the avcodec_ prefixed APIs (avcodec_send_frame() etc.), except * that: * - never called if the codec is closed or the wrong type, * - if AV_CODEC_CAP_DELAY is not set, drain frames are never sent, * - only one drain frame is ever passed down, */ int (*send_frame)(AVCodecContext *avctx, const AVFrame *frame); int (*receive_packet)(AVCodecContext *avctx, AVPacket *avpkt); /** * Decode API with decoupled packet/frame dataflow. This function is called * to get one output frame. It should call ff_decode_get_packet() to obtain * input data. */ int (*receive_frame)(AVCodecContext *avctx, AVFrame *frame); /** * Flush buffers. * Will be called when seeking */ void (*flush)(AVCodecContext *); /** * Internal codec capabilities. * See FF_CODEC_CAP_* in internal.h */ int caps_internal; /** * Decoding only, a comma-separated list of bitstream filters to apply to * packets before decoding. */ const char *bsfs; /** * Array of pointers to hardware configurations supported by the codec, * or NULL if no hardware supported. The array is terminated by a NULL * pointer. * * The user can only access this field via avcodec_get_hw_config(). */ const struct AVCodecHWConfigInternal **hw_configs; } AVCodec; #if FF_API_CODEC_GET_SET attribute_deprecated int av_codec_get_max_lowres(const AVCodec *codec); #endif struct MpegEncContext; /** * Retrieve supported hardware configurations for a codec. * * Values of index from zero to some maximum return the indexed configuration * descriptor; all other values return NULL. If the codec does not support * any hardware configurations then it will always return NULL. */ const AVCodecHWConfig *avcodec_get_hw_config(const AVCodec *codec, int index); /** * @defgroup lavc_hwaccel AVHWAccel * * @note Nothing in this structure should be accessed by the user. At some * point in future it will not be externally visible at all. * * @{ */ typedef struct AVHWAccel { /** * Name of the hardware accelerated codec. * The name is globally unique among encoders and among decoders (but an * encoder and a decoder can share the same name). */ const char *name; /** * Type of codec implemented by the hardware accelerator. * * See AVMEDIA_TYPE_xxx */ enum AVMediaType type; /** * Codec implemented by the hardware accelerator. * * See AV_CODEC_ID_xxx */ enum AVCodecID id; /** * Supported pixel format. * * Only hardware accelerated formats are supported here. */ enum AVPixelFormat pix_fmt; /** * Hardware accelerated codec capabilities. * see AV_HWACCEL_CODEC_CAP_* */ int capabilities; /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavcodec and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * Allocate a custom buffer */ int (*alloc_frame)(AVCodecContext *avctx, AVFrame *frame); /** * Called at the beginning of each frame or field picture. * * Meaningful frame information (codec specific) is guaranteed to * be parsed at this point. This function is mandatory. * * Note that buf can be NULL along with buf_size set to 0. * Otherwise, this means the whole frame is available at this point. * * @param avctx the codec context * @param buf the frame data buffer base * @param buf_size the size of the frame in bytes * @return zero if successful, a negative value otherwise */ int (*start_frame)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size); /** * Callback for parameter data (SPS/PPS/VPS etc). * * Useful for hardware decoders which keep persistent state about the * video parameters, and need to receive any changes to update that state. * * @param avctx the codec context * @param type the nal unit type * @param buf the nal unit data buffer * @param buf_size the size of the nal unit in bytes * @return zero if successful, a negative value otherwise */ int (*decode_params)(AVCodecContext *avctx, int type, const uint8_t *buf, uint32_t buf_size); /** * Callback for each slice. * * Meaningful slice information (codec specific) is guaranteed to * be parsed at this point. This function is mandatory. * The only exception is XvMC, that works on MB level. * * @param avctx the codec context * @param buf the slice data buffer base * @param buf_size the size of the slice in bytes * @return zero if successful, a negative value otherwise */ int (*decode_slice)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size); /** * Called at the end of each frame or field picture. * * The whole picture is parsed at this point and can now be sent * to the hardware accelerator. This function is mandatory. * * @param avctx the codec context * @return zero if successful, a negative value otherwise */ int (*end_frame)(AVCodecContext *avctx); /** * Size of per-frame hardware accelerator private data. * * Private data is allocated with av_mallocz() before * AVCodecContext.get_buffer() and deallocated after * AVCodecContext.release_buffer(). */ int frame_priv_data_size; /** * Called for every Macroblock in a slice. * * XvMC uses it to replace the ff_mpv_reconstruct_mb(). * Instead of decoding to raw picture, MB parameters are * stored in an array provided by the video driver. * * @param s the mpeg context */ void (*decode_mb)(struct MpegEncContext *s); /** * Initialize the hwaccel private data. * * This will be called from ff_get_format(), after hwaccel and * hwaccel_context are set and the hwaccel private data in AVCodecInternal * is allocated. */ int (*init)(AVCodecContext *avctx); /** * Uninitialize the hwaccel private data. * * This will be called from get_format() or avcodec_close(), after hwaccel * and hwaccel_context are already uninitialized. */ int (*uninit)(AVCodecContext *avctx); /** * Size of the private data to allocate in * AVCodecInternal.hwaccel_priv_data. */ int priv_data_size; /** * Internal hwaccel capabilities. */ int caps_internal; /** * Fill the given hw_frames context with current codec parameters. Called * from get_format. Refer to avcodec_get_hw_frames_parameters() for * details. * * This CAN be called before AVHWAccel.init is called, and you must assume * that avctx->hwaccel_priv_data is invalid. */ int (*frame_params)(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx); } AVHWAccel; /** * HWAccel is experimental and is thus avoided in favor of non experimental * codecs */ #define AV_HWACCEL_CODEC_CAP_EXPERIMENTAL 0x0200 /** * Hardware acceleration should be used for decoding even if the codec level * used is unknown or higher than the maximum supported level reported by the * hardware driver. * * It's generally a good idea to pass this flag unless you have a specific * reason not to, as hardware tends to under-report supported levels. */ #define AV_HWACCEL_FLAG_IGNORE_LEVEL (1 << 0) /** * Hardware acceleration can output YUV pixel formats with a different chroma * sampling than 4:2:0 and/or other than 8 bits per component. */ #define AV_HWACCEL_FLAG_ALLOW_HIGH_DEPTH (1 << 1) /** * Hardware acceleration should still be attempted for decoding when the * codec profile does not match the reported capabilities of the hardware. * * For example, this can be used to try to decode baseline profile H.264 * streams in hardware - it will often succeed, because many streams marked * as baseline profile actually conform to constrained baseline profile. * * @warning If the stream is actually not supported then the behaviour is * undefined, and may include returning entirely incorrect output * while indicating success. */ #define AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH (1 << 2) /** * @} */ #if FF_API_AVPICTURE /** * @defgroup lavc_picture AVPicture * * Functions for working with AVPicture * @{ */ /** * Picture data structure. * * Up to four components can be stored into it, the last component is * alpha. * @deprecated use AVFrame or imgutils functions instead */ typedef struct AVPicture { attribute_deprecated uint8_t *data[AV_NUM_DATA_POINTERS]; ///< pointers to the image data planes attribute_deprecated int linesize[AV_NUM_DATA_POINTERS]; ///< number of bytes per line } AVPicture; /** * @} */ #endif enum AVSubtitleType { SUBTITLE_NONE, SUBTITLE_BITMAP, ///< A bitmap, pict will be set /** * Plain text, the text field must be set by the decoder and is * authoritative. ass and pict fields may contain approximations. */ SUBTITLE_TEXT, /** * Formatted text, the ass field must be set by the decoder and is * authoritative. pict and text fields may contain approximations. */ SUBTITLE_ASS, }; #define AV_SUBTITLE_FLAG_FORCED 0x00000001 typedef struct AVSubtitleRect { int x; ///< top left corner of pict, undefined when pict is not set int y; ///< top left corner of pict, undefined when pict is not set int w; ///< width of pict, undefined when pict is not set int h; ///< height of pict, undefined when pict is not set int nb_colors; ///< number of colors in pict, undefined when pict is not set #if FF_API_AVPICTURE /** * @deprecated unused */ attribute_deprecated AVPicture pict; #endif /** * data+linesize for the bitmap of this subtitle. * Can be set for text/ass as well once they are rendered. */ uint8_t *data[4]; int linesize[4]; enum AVSubtitleType type; char *text; ///< 0 terminated plain UTF-8 text /** * 0 terminated ASS/SSA compatible event line. * The presentation of this is unaffected by the other values in this * struct. */ char *ass; int flags; } AVSubtitleRect; typedef struct AVSubtitle { uint16_t format; /* 0 = graphics */ uint32_t start_display_time; /* relative to packet pts, in ms */ uint32_t end_display_time; /* relative to packet pts, in ms */ unsigned num_rects; AVSubtitleRect **rects; int64_t pts; ///< Same as packet pts, in AV_TIME_BASE } AVSubtitle; /** * This struct describes the properties of an encoded stream. * * sizeof(AVCodecParameters) is not a part of the public ABI, this struct must * be allocated with avcodec_parameters_alloc() and freed with * avcodec_parameters_free(). */ typedef struct AVCodecParameters { /** * General type of the encoded data. */ enum AVMediaType codec_type; /** * Specific type of the encoded data (the codec used). */ enum AVCodecID codec_id; /** * Additional information about the codec (corresponds to the AVI FOURCC). */ uint32_t codec_tag; /** * Extra binary data needed for initializing the decoder, codec-dependent. * * Must be allocated with av_malloc() and will be freed by * avcodec_parameters_free(). The allocated size of extradata must be at * least extradata_size + AV_INPUT_BUFFER_PADDING_SIZE, with the padding * bytes zeroed. */ uint8_t *extradata; /** * Size of the extradata content in bytes. */ int extradata_size; /** * - video: the pixel format, the value corresponds to enum AVPixelFormat. * - audio: the sample format, the value corresponds to enum AVSampleFormat. */ int format; /** * The average bitrate of the encoded data (in bits per second). */ int64_t bit_rate; /** * The number of bits per sample in the codedwords. * * This is basically the bitrate per sample. It is mandatory for a bunch of * formats to actually decode them. It's the number of bits for one sample in * the actual coded bitstream. * * This could be for example 4 for ADPCM * For PCM formats this matches bits_per_raw_sample * Can be 0 */ int bits_per_coded_sample; /** * This is the number of valid bits in each output sample. If the * sample format has more bits, the least significant bits are additional * padding bits, which are always 0. Use right shifts to reduce the sample * to its actual size. For example, audio formats with 24 bit samples will * have bits_per_raw_sample set to 24, and format set to AV_SAMPLE_FMT_S32. * To get the original sample use "(int32_t)sample >> 8"." * * For ADPCM this might be 12 or 16 or similar * Can be 0 */ int bits_per_raw_sample; /** * Codec-specific bitstream restrictions that the stream conforms to. */ int profile; int level; /** * Video only. The dimensions of the video frame in pixels. */ int width; int height; /** * Video only. The aspect ratio (width / height) which a single pixel * should have when displayed. * * When the aspect ratio is unknown / undefined, the numerator should be * set to 0 (the denominator may have any value). */ AVRational sample_aspect_ratio; /** * Video only. The order of the fields in interlaced video. */ enum AVFieldOrder field_order; /** * Video only. Additional colorspace characteristics. */ enum AVColorRange color_range; enum AVColorPrimaries color_primaries; enum AVColorTransferCharacteristic color_trc; enum AVColorSpace color_space; enum AVChromaLocation chroma_location; /** * Video only. Number of delayed frames. */ int video_delay; /** * Audio only. The channel layout bitmask. May be 0 if the channel layout is * unknown or unspecified, otherwise the number of bits set must be equal to * the channels field. */ uint64_t channel_layout; /** * Audio only. The number of audio channels. */ int channels; /** * Audio only. The number of audio samples per second. */ int sample_rate; /** * Audio only. The number of bytes per coded audio frame, required by some * formats. * * Corresponds to nBlockAlign in WAVEFORMATEX. */ int block_align; /** * Audio only. Audio frame size, if known. Required by some formats to be static. */ int frame_size; /** * Audio only. The amount of padding (in samples) inserted by the encoder at * the beginning of the audio. I.e. this number of leading decoded samples * must be discarded by the caller to get the original audio without leading * padding. */ int initial_padding; /** * Audio only. The amount of padding (in samples) appended by the encoder to * the end of the audio. I.e. this number of decoded samples must be * discarded by the caller from the end of the stream to get the original * audio without any trailing padding. */ int trailing_padding; /** * Audio only. Number of samples to skip after a discontinuity. */ int seek_preroll; } AVCodecParameters; /** * Iterate over all registered codecs. * * @param opaque a pointer where libavcodec will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered codec or NULL when the iteration is * finished */ const AVCodec *av_codec_iterate(void **opaque); #if FF_API_NEXT /** * If c is NULL, returns the first registered codec, * if c is non-NULL, returns the next registered codec after c, * or NULL if c is the last one. */ attribute_deprecated AVCodec *av_codec_next(const AVCodec *c); #endif /** * Return the LIBAVCODEC_VERSION_INT constant. */ unsigned avcodec_version(void); /** * Return the libavcodec build-time configuration. */ const char *avcodec_configuration(void); /** * Return the libavcodec license. */ const char *avcodec_license(void); #if FF_API_NEXT /** * Register the codec codec and initialize libavcodec. * * @warning either this function or avcodec_register_all() must be called * before any other libavcodec functions. * * @see avcodec_register_all() */ attribute_deprecated void avcodec_register(AVCodec *codec); /** * Register all the codecs, parsers and bitstream filters which were enabled at * configuration time. If you do not call this function you can select exactly * which formats you want to support, by using the individual registration * functions. * * @see avcodec_register * @see av_register_codec_parser * @see av_register_bitstream_filter */ attribute_deprecated void avcodec_register_all(void); #endif /** * Allocate an AVCodecContext and set its fields to default values. The * resulting struct should be freed with avcodec_free_context(). * * @param codec if non-NULL, allocate private data and initialize defaults * for the given codec. It is illegal to then call avcodec_open2() * with a different codec. * If NULL, then the codec-specific defaults won't be initialized, * which may result in suboptimal default settings (this is * important mainly for encoders, e.g. libx264). * * @return An AVCodecContext filled with default values or NULL on failure. */ AVCodecContext *avcodec_alloc_context3(const AVCodec *codec); /** * Free the codec context and everything associated with it and write NULL to * the provided pointer. */ void avcodec_free_context(AVCodecContext **avctx); #if FF_API_GET_CONTEXT_DEFAULTS /** * @deprecated This function should not be used, as closing and opening a codec * context multiple time is not supported. A new codec context should be * allocated for each new use. */ int avcodec_get_context_defaults3(AVCodecContext *s, const AVCodec *codec); #endif /** * Get the AVClass for AVCodecContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avcodec_get_class(void); #if FF_API_COPY_CONTEXT /** * Get the AVClass for AVFrame. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avcodec_get_frame_class(void); /** * Get the AVClass for AVSubtitleRect. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avcodec_get_subtitle_rect_class(void); /** * Copy the settings of the source AVCodecContext into the destination * AVCodecContext. The resulting destination codec context will be * unopened, i.e. you are required to call avcodec_open2() before you * can use this AVCodecContext to decode/encode video/audio data. * * @param dest target codec context, should be initialized with * avcodec_alloc_context3(NULL), but otherwise uninitialized * @param src source codec context * @return AVERROR() on error (e.g. memory allocation error), 0 on success * * @deprecated The semantics of this function are ill-defined and it should not * be used. If you need to transfer the stream parameters from one codec context * to another, use an intermediate AVCodecParameters instance and the * avcodec_parameters_from_context() / avcodec_parameters_to_context() * functions. */ attribute_deprecated int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src); #endif /** * Allocate a new AVCodecParameters and set its fields to default values * (unknown/invalid/0). The returned struct must be freed with * avcodec_parameters_free(). */ AVCodecParameters *avcodec_parameters_alloc(void); /** * Free an AVCodecParameters instance and everything associated with it and * write NULL to the supplied pointer. */ void avcodec_parameters_free(AVCodecParameters **par); /** * Copy the contents of src to dst. Any allocated fields in dst are freed and * replaced with newly allocated duplicates of the corresponding fields in src. * * @return >= 0 on success, a negative AVERROR code on failure. */ int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src); /** * Fill the parameters struct based on the values from the supplied codec * context. Any allocated fields in par are freed and replaced with duplicates * of the corresponding fields in codec. * * @return >= 0 on success, a negative AVERROR code on failure */ int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec); /** * Fill the codec context based on the values from the supplied codec * parameters. Any allocated fields in codec that have a corresponding field in * par are freed and replaced with duplicates of the corresponding field in par. * Fields in codec that do not have a counterpart in par are not touched. * * @return >= 0 on success, a negative AVERROR code on failure. */ int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par); /** * Initialize the AVCodecContext to use the given AVCodec. Prior to using this * function the context has to be allocated with avcodec_alloc_context3(). * * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(), * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for * retrieving a codec. * * @warning This function is not thread safe! * * @note Always call this function before using decoding routines (such as * @ref avcodec_receive_frame()). * * @code * avcodec_register_all(); * av_dict_set(&opts, "b", "2.5M", 0); * codec = avcodec_find_decoder(AV_CODEC_ID_H264); * if (!codec) * exit(1); * * context = avcodec_alloc_context3(codec); * * if (avcodec_open2(context, codec, opts) < 0) * exit(1); * @endcode * * @param avctx The context to initialize. * @param codec The codec to open this context for. If a non-NULL codec has been * previously passed to avcodec_alloc_context3() or * for this context, then this parameter MUST be either NULL or * equal to the previously passed codec. * @param options A dictionary filled with AVCodecContext and codec-private options. * On return this object will be filled with options that were not found. * * @return zero on success, a negative value on error * @see avcodec_alloc_context3(), avcodec_find_decoder(), avcodec_find_encoder(), * av_dict_set(), av_opt_find(). */ int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options); /** * Close a given AVCodecContext and free all the data associated with it * (but not the AVCodecContext itself). * * Calling this function on an AVCodecContext that hasn't been opened will free * the codec-specific data allocated in avcodec_alloc_context3() with a non-NULL * codec. Subsequent calls will do nothing. * * @note Do not use this function. Use avcodec_free_context() to destroy a * codec context (either open or closed). Opening and closing a codec context * multiple times is not supported anymore -- use multiple codec contexts * instead. */ int avcodec_close(AVCodecContext *avctx); /** * Free all allocated data in the given subtitle struct. * * @param sub AVSubtitle to free. */ void avsubtitle_free(AVSubtitle *sub); /** * @} */ /** * @addtogroup lavc_packet * @{ */ /** * Allocate an AVPacket and set its fields to default values. The resulting * struct must be freed using av_packet_free(). * * @return An AVPacket filled with default values or NULL on failure. * * @note this only allocates the AVPacket itself, not the data buffers. Those * must be allocated through other means such as av_new_packet. * * @see av_new_packet */ AVPacket *av_packet_alloc(void); /** * Create a new packet that references the same data as src. * * This is a shortcut for av_packet_alloc()+av_packet_ref(). * * @return newly created AVPacket on success, NULL on error. * * @see av_packet_alloc * @see av_packet_ref */ AVPacket *av_packet_clone(const AVPacket *src); /** * Free the packet, if the packet is reference counted, it will be * unreferenced first. * * @param pkt packet to be freed. The pointer will be set to NULL. * @note passing NULL is a no-op. */ void av_packet_free(AVPacket **pkt); /** * Initialize optional fields of a packet with default values. * * Note, this does not touch the data and size members, which have to be * initialized separately. * * @param pkt packet */ void av_init_packet(AVPacket *pkt); /** * Allocate the payload of a packet and initialize its fields with * default values. * * @param pkt packet * @param size wanted payload size * @return 0 if OK, AVERROR_xxx otherwise */ int av_new_packet(AVPacket *pkt, int size); /** * Reduce packet size, correctly zeroing padding * * @param pkt packet * @param size new size */ void av_shrink_packet(AVPacket *pkt, int size); /** * Increase packet size, correctly zeroing padding * * @param pkt packet * @param grow_by number of bytes by which to increase the size of the packet */ int av_grow_packet(AVPacket *pkt, int grow_by); /** * Initialize a reference-counted packet from av_malloc()ed data. * * @param pkt packet to be initialized. This function will set the data, size, * and buf fields, all others are left untouched. * @param data Data allocated by av_malloc() to be used as packet data. If this * function returns successfully, the data is owned by the underlying AVBuffer. * The caller may not access the data through other means. * @param size size of data in bytes, without the padding. I.e. the full buffer * size is assumed to be size + AV_INPUT_BUFFER_PADDING_SIZE. * * @return 0 on success, a negative AVERROR on error */ int av_packet_from_data(AVPacket *pkt, uint8_t *data, int size); #if FF_API_AVPACKET_OLD_API /** * @warning This is a hack - the packet memory allocation stuff is broken. The * packet is allocated if it was not really allocated. * * @deprecated Use av_packet_ref or av_packet_make_refcounted */ attribute_deprecated int av_dup_packet(AVPacket *pkt); /** * Copy packet, including contents * * @return 0 on success, negative AVERROR on fail * * @deprecated Use av_packet_ref */ attribute_deprecated int av_copy_packet(AVPacket *dst, const AVPacket *src); /** * Copy packet side data * * @return 0 on success, negative AVERROR on fail * * @deprecated Use av_packet_copy_props */ attribute_deprecated int av_copy_packet_side_data(AVPacket *dst, const AVPacket *src); /** * Free a packet. * * @deprecated Use av_packet_unref * * @param pkt packet to free */ attribute_deprecated void av_free_packet(AVPacket *pkt); #endif /** * Allocate new information of a packet. * * @param pkt packet * @param type side information type * @param size side information size * @return pointer to fresh allocated data or NULL otherwise */ uint8_t* av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size); /** * Wrap an existing array as a packet side data. * * @param pkt packet * @param type side information type * @param data the side data array. It must be allocated with the av_malloc() * family of functions. The ownership of the data is transferred to * pkt. * @param size side information size * @return a non-negative number on success, a negative AVERROR code on * failure. On failure, the packet is unchanged and the data remains * owned by the caller. */ int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type, uint8_t *data, size_t size); /** * Shrink the already allocated side data buffer * * @param pkt packet * @param type side information type * @param size new side information size * @return 0 on success, < 0 on failure */ int av_packet_shrink_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size); /** * Get side information from packet. * * @param pkt packet * @param type desired side information type * @param size pointer for side information size to store (optional) * @return pointer to data if present or NULL otherwise */ uint8_t* av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, int *size); #if FF_API_MERGE_SD_API attribute_deprecated int av_packet_merge_side_data(AVPacket *pkt); attribute_deprecated int av_packet_split_side_data(AVPacket *pkt); #endif const char *av_packet_side_data_name(enum AVPacketSideDataType type); /** * Pack a dictionary for use in side_data. * * @param dict The dictionary to pack. * @param size pointer to store the size of the returned data * @return pointer to data if successful, NULL otherwise */ uint8_t *av_packet_pack_dictionary(AVDictionary *dict, int *size); /** * Unpack a dictionary from side_data. * * @param data data from side_data * @param size size of the data * @param dict the metadata storage dictionary * @return 0 on success, < 0 on failure */ int av_packet_unpack_dictionary(const uint8_t *data, int size, AVDictionary **dict); /** * Convenience function to free all the side data stored. * All the other fields stay untouched. * * @param pkt packet */ void av_packet_free_side_data(AVPacket *pkt); /** * Setup a new reference to the data described by a given packet * * If src is reference-counted, setup dst as a new reference to the * buffer in src. Otherwise allocate a new buffer in dst and copy the * data from src into it. * * All the other fields are copied from src. * * @see av_packet_unref * * @param dst Destination packet * @param src Source packet * * @return 0 on success, a negative AVERROR on error. */ int av_packet_ref(AVPacket *dst, const AVPacket *src); /** * Wipe the packet. * * Unreference the buffer referenced by the packet and reset the * remaining packet fields to their default values. * * @param pkt The packet to be unreferenced. */ void av_packet_unref(AVPacket *pkt); /** * Move every field in src to dst and reset src. * * @see av_packet_unref * * @param src Source packet, will be reset * @param dst Destination packet */ void av_packet_move_ref(AVPacket *dst, AVPacket *src); /** * Copy only "properties" fields from src to dst. * * Properties for the purpose of this function are all the fields * beside those related to the packet data (buf, data, size) * * @param dst Destination packet * @param src Source packet * * @return 0 on success AVERROR on failure. */ int av_packet_copy_props(AVPacket *dst, const AVPacket *src); /** * Ensure the data described by a given packet is reference counted. * * @note This function does not ensure that the reference will be writable. * Use av_packet_make_writable instead for that purpose. * * @see av_packet_ref * @see av_packet_make_writable * * @param pkt packet whose data should be made reference counted. * * @return 0 on success, a negative AVERROR on error. On failure, the * packet is unchanged. */ int av_packet_make_refcounted(AVPacket *pkt); /** * Create a writable reference for the data described by a given packet, * avoiding data copy if possible. * * @param pkt Packet whose data should be made writable. * * @return 0 on success, a negative AVERROR on failure. On failure, the * packet is unchanged. */ int av_packet_make_writable(AVPacket *pkt); /** * Convert valid timing fields (timestamps / durations) in a packet from one * timebase to another. Timestamps with unknown values (AV_NOPTS_VALUE) will be * ignored. * * @param pkt packet on which the conversion will be performed * @param tb_src source timebase, in which the timing fields in pkt are * expressed * @param tb_dst destination timebase, to which the timing fields will be * converted */ void av_packet_rescale_ts(AVPacket *pkt, AVRational tb_src, AVRational tb_dst); /** * @} */ /** * @addtogroup lavc_decoding * @{ */ /** * Find a registered decoder with a matching codec ID. * * @param id AVCodecID of the requested decoder * @return A decoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_decoder(enum AVCodecID id); /** * Find a registered decoder with the specified name. * * @param name name of the requested decoder * @return A decoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_decoder_by_name(const char *name); /** * The default callback for AVCodecContext.get_buffer2(). It is made public so * it can be called by custom get_buffer2() implementations for decoders without * AV_CODEC_CAP_DR1 set. */ int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags); /** * Modify width and height values so that they will result in a memory * buffer that is acceptable for the codec if you do not use any horizontal * padding. * * May only be used if a codec with AV_CODEC_CAP_DR1 has been opened. */ void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height); /** * Modify width and height values so that they will result in a memory * buffer that is acceptable for the codec if you also ensure that all * line sizes are a multiple of the respective linesize_align[i]. * * May only be used if a codec with AV_CODEC_CAP_DR1 has been opened. */ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[AV_NUM_DATA_POINTERS]); /** * Converts AVChromaLocation to swscale x/y chroma position. * * The positions represent the chroma (0,0) position in a coordinates system * with luma (0,0) representing the origin and luma(1,1) representing 256,256 * * @param xpos horizontal chroma sample position * @param ypos vertical chroma sample position */ int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos); /** * Converts swscale x/y chroma position to AVChromaLocation. * * The positions represent the chroma (0,0) position in a coordinates system * with luma (0,0) representing the origin and luma(1,1) representing 256,256 * * @param xpos horizontal chroma sample position * @param ypos vertical chroma sample position */ enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos); /** * Decode the audio frame of size avpkt->size from avpkt->data into frame. * * Some decoders may support multiple frames in a single AVPacket. Such * decoders would then just decode the first frame and the return value would be * less than the packet size. In this case, avcodec_decode_audio4 has to be * called again with an AVPacket containing the remaining data in order to * decode the second frame, etc... Even if no frames are returned, the packet * needs to be fed to the decoder with remaining data until it is completely * consumed or an error occurs. * * Some decoders (those marked with AV_CODEC_CAP_DELAY) have a delay between input * and output. This means that for some packets they will not immediately * produce decoded output and need to be flushed at the end of decoding to get * all the decoded data. Flushing is done by calling this function with packets * with avpkt->data set to NULL and avpkt->size set to 0 until it stops * returning samples. It is safe to flush even those decoders that are not * marked with AV_CODEC_CAP_DELAY, then no samples will be returned. * * @warning The input buffer, avpkt->data must be AV_INPUT_BUFFER_PADDING_SIZE * larger than the actual read bytes because some optimized bitstream * readers read 32 or 64 bits at once and could read over the end. * * @note The AVCodecContext MUST have been opened with @ref avcodec_open2() * before packets may be fed to the decoder. * * @param avctx the codec context * @param[out] frame The AVFrame in which to store decoded audio samples. * The decoder will allocate a buffer for the decoded frame by * calling the AVCodecContext.get_buffer2() callback. * When AVCodecContext.refcounted_frames is set to 1, the frame is * reference counted and the returned reference belongs to the * caller. The caller must release the frame using av_frame_unref() * when the frame is no longer needed. The caller may safely write * to the frame if av_frame_is_writable() returns 1. * When AVCodecContext.refcounted_frames is set to 0, the returned * reference belongs to the decoder and is valid only until the * next call to this function or until closing or flushing the * decoder. The caller may not write to it. * @param[out] got_frame_ptr Zero if no frame could be decoded, otherwise it is * non-zero. Note that this field being set to zero * does not mean that an error has occurred. For * decoders with AV_CODEC_CAP_DELAY set, no given decode * call is guaranteed to produce a frame. * @param[in] avpkt The input AVPacket containing the input buffer. * At least avpkt->data and avpkt->size should be set. Some * decoders might also require additional fields to be set. * @return A negative error code is returned if an error occurred during * decoding, otherwise the number of bytes consumed from the input * AVPacket is returned. * * @deprecated Use avcodec_send_packet() and avcodec_receive_frame(). */ attribute_deprecated int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt); /** * Decode the video frame of size avpkt->size from avpkt->data into picture. * Some decoders may support multiple frames in a single AVPacket, such * decoders would then just decode the first frame. * * @warning The input buffer must be AV_INPUT_BUFFER_PADDING_SIZE larger than * the actual read bytes because some optimized bitstream readers read 32 or 64 * bits at once and could read over the end. * * @warning The end of the input buffer buf should be set to 0 to ensure that * no overreading happens for damaged MPEG streams. * * @note Codecs which have the AV_CODEC_CAP_DELAY capability set have a delay * between input and output, these need to be fed with avpkt->data=NULL, * avpkt->size=0 at the end to return the remaining frames. * * @note The AVCodecContext MUST have been opened with @ref avcodec_open2() * before packets may be fed to the decoder. * * @param avctx the codec context * @param[out] picture The AVFrame in which the decoded video frame will be stored. * Use av_frame_alloc() to get an AVFrame. The codec will * allocate memory for the actual bitmap by calling the * AVCodecContext.get_buffer2() callback. * When AVCodecContext.refcounted_frames is set to 1, the frame is * reference counted and the returned reference belongs to the * caller. The caller must release the frame using av_frame_unref() * when the frame is no longer needed. The caller may safely write * to the frame if av_frame_is_writable() returns 1. * When AVCodecContext.refcounted_frames is set to 0, the returned * reference belongs to the decoder and is valid only until the * next call to this function or until closing or flushing the * decoder. The caller may not write to it. * * @param[in] avpkt The input AVPacket containing the input buffer. * You can create such packet with av_init_packet() and by then setting * data and size, some decoders might in addition need other fields like * flags&AV_PKT_FLAG_KEY. All decoders are designed to use the least * fields possible. * @param[in,out] got_picture_ptr Zero if no frame could be decompressed, otherwise, it is nonzero. * @return On error a negative value is returned, otherwise the number of bytes * used or zero if no frame could be decompressed. * * @deprecated Use avcodec_send_packet() and avcodec_receive_frame(). */ attribute_deprecated int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, const AVPacket *avpkt); /** * Decode a subtitle message. * Return a negative value on error, otherwise return the number of bytes used. * If no subtitle could be decompressed, got_sub_ptr is zero. * Otherwise, the subtitle is stored in *sub. * Note that AV_CODEC_CAP_DR1 is not available for subtitle codecs. This is for * simplicity, because the performance difference is expect to be negligible * and reusing a get_buffer written for video codecs would probably perform badly * due to a potentially very different allocation pattern. * * Some decoders (those marked with AV_CODEC_CAP_DELAY) have a delay between input * and output. This means that for some packets they will not immediately * produce decoded output and need to be flushed at the end of decoding to get * all the decoded data. Flushing is done by calling this function with packets * with avpkt->data set to NULL and avpkt->size set to 0 until it stops * returning subtitles. It is safe to flush even those decoders that are not * marked with AV_CODEC_CAP_DELAY, then no subtitles will be returned. * * @note The AVCodecContext MUST have been opened with @ref avcodec_open2() * before packets may be fed to the decoder. * * @param avctx the codec context * @param[out] sub The Preallocated AVSubtitle in which the decoded subtitle will be stored, * must be freed with avsubtitle_free if *got_sub_ptr is set. * @param[in,out] got_sub_ptr Zero if no subtitle could be decompressed, otherwise, it is nonzero. * @param[in] avpkt The input AVPacket containing the input buffer. */ int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt); /** * Supply raw packet data as input to a decoder. * * Internally, this call will copy relevant AVCodecContext fields, which can * influence decoding per-packet, and apply them when the packet is actually * decoded. (For example AVCodecContext.skip_frame, which might direct the * decoder to drop the frame contained by the packet sent with this function.) * * @warning The input buffer, avpkt->data must be AV_INPUT_BUFFER_PADDING_SIZE * larger than the actual read bytes because some optimized bitstream * readers read 32 or 64 bits at once and could read over the end. * * @warning Do not mix this API with the legacy API (like avcodec_decode_video2()) * on the same AVCodecContext. It will return unexpected results now * or in future libavcodec versions. * * @note The AVCodecContext MUST have been opened with @ref avcodec_open2() * before packets may be fed to the decoder. * * @param avctx codec context * @param[in] avpkt The input AVPacket. Usually, this will be a single video * frame, or several complete audio frames. * Ownership of the packet remains with the caller, and the * decoder will not write to the packet. The decoder may create * a reference to the packet data (or copy it if the packet is * not reference-counted). * Unlike with older APIs, the packet is always fully consumed, * and if it contains multiple frames (e.g. some audio codecs), * will require you to call avcodec_receive_frame() multiple * times afterwards before you can send a new packet. * It can be NULL (or an AVPacket with data set to NULL and * size set to 0); in this case, it is considered a flush * packet, which signals the end of the stream. Sending the * first flush packet will return success. Subsequent ones are * unnecessary and will return AVERROR_EOF. If the decoder * still has frames buffered, it will return them after sending * a flush packet. * * @return 0 on success, otherwise negative error code: * AVERROR(EAGAIN): input is not accepted in the current state - user * must read output with avcodec_receive_frame() (once * all output is read, the packet should be resent, and * the call will not fail with EAGAIN). * AVERROR_EOF: the decoder has been flushed, and no new packets can * be sent to it (also returned if more than 1 flush * packet is sent) * AVERROR(EINVAL): codec not opened, it is an encoder, or requires flush * AVERROR(ENOMEM): failed to add packet to internal queue, or similar * other errors: legitimate decoding errors */ int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt); /** * Return decoded output data from a decoder. * * @param avctx codec context * @param frame This will be set to a reference-counted video or audio * frame (depending on the decoder type) allocated by the * decoder. Note that the function will always call * av_frame_unref(frame) before doing anything else. * * @return * 0: success, a frame was returned * AVERROR(EAGAIN): output is not available in this state - user must try * to send new input * AVERROR_EOF: the decoder has been fully flushed, and there will be * no more output frames * AVERROR(EINVAL): codec not opened, or it is an encoder * AVERROR_INPUT_CHANGED: current decoded frame has changed parameters * with respect to first decoded frame. Applicable * when flag AV_CODEC_FLAG_DROPCHANGED is set. * other negative values: legitimate decoding errors */ int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame); /** * Supply a raw video or audio frame to the encoder. Use avcodec_receive_packet() * to retrieve buffered output packets. * * @param avctx codec context * @param[in] frame AVFrame containing the raw audio or video frame to be encoded. * Ownership of the frame remains with the caller, and the * encoder will not write to the frame. The encoder may create * a reference to the frame data (or copy it if the frame is * not reference-counted). * It can be NULL, in which case it is considered a flush * packet. This signals the end of the stream. If the encoder * still has packets buffered, it will return them after this * call. Once flushing mode has been entered, additional flush * packets are ignored, and sending frames will return * AVERROR_EOF. * * For audio: * If AV_CODEC_CAP_VARIABLE_FRAME_SIZE is set, then each frame * can have any number of samples. * If it is not set, frame->nb_samples must be equal to * avctx->frame_size for all frames except the last. * The final frame may be smaller than avctx->frame_size. * @return 0 on success, otherwise negative error code: * AVERROR(EAGAIN): input is not accepted in the current state - user * must read output with avcodec_receive_packet() (once * all output is read, the packet should be resent, and * the call will not fail with EAGAIN). * AVERROR_EOF: the encoder has been flushed, and no new frames can * be sent to it * AVERROR(EINVAL): codec not opened, refcounted_frames not set, it is a * decoder, or requires flush * AVERROR(ENOMEM): failed to add packet to internal queue, or similar * other errors: legitimate decoding errors */ int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame); /** * Read encoded data from the encoder. * * @param avctx codec context * @param avpkt This will be set to a reference-counted packet allocated by the * encoder. Note that the function will always call * av_frame_unref(frame) before doing anything else. * @return 0 on success, otherwise negative error code: * AVERROR(EAGAIN): output is not available in the current state - user * must try to send input * AVERROR_EOF: the encoder has been fully flushed, and there will be * no more output packets * AVERROR(EINVAL): codec not opened, or it is an encoder * other errors: legitimate decoding errors */ int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt); /** * Create and return a AVHWFramesContext with values adequate for hardware * decoding. This is meant to get called from the get_format callback, and is * a helper for preparing a AVHWFramesContext for AVCodecContext.hw_frames_ctx. * This API is for decoding with certain hardware acceleration modes/APIs only. * * The returned AVHWFramesContext is not initialized. The caller must do this * with av_hwframe_ctx_init(). * * Calling this function is not a requirement, but makes it simpler to avoid * codec or hardware API specific details when manually allocating frames. * * Alternatively to this, an API user can set AVCodecContext.hw_device_ctx, * which sets up AVCodecContext.hw_frames_ctx fully automatically, and makes * it unnecessary to call this function or having to care about * AVHWFramesContext initialization at all. * * There are a number of requirements for calling this function: * * - It must be called from get_format with the same avctx parameter that was * passed to get_format. Calling it outside of get_format is not allowed, and * can trigger undefined behavior. * - The function is not always supported (see description of return values). * Even if this function returns successfully, hwaccel initialization could * fail later. (The degree to which implementations check whether the stream * is actually supported varies. Some do this check only after the user's * get_format callback returns.) * - The hw_pix_fmt must be one of the choices suggested by get_format. If the * user decides to use a AVHWFramesContext prepared with this API function, * the user must return the same hw_pix_fmt from get_format. * - The device_ref passed to this function must support the given hw_pix_fmt. * - After calling this API function, it is the user's responsibility to * initialize the AVHWFramesContext (returned by the out_frames_ref parameter), * and to set AVCodecContext.hw_frames_ctx to it. If done, this must be done * before returning from get_format (this is implied by the normal * AVCodecContext.hw_frames_ctx API rules). * - The AVHWFramesContext parameters may change every time time get_format is * called. Also, AVCodecContext.hw_frames_ctx is reset before get_format. So * you are inherently required to go through this process again on every * get_format call. * - It is perfectly possible to call this function without actually using * the resulting AVHWFramesContext. One use-case might be trying to reuse a * previously initialized AVHWFramesContext, and calling this API function * only to test whether the required frame parameters have changed. * - Fields that use dynamically allocated values of any kind must not be set * by the user unless setting them is explicitly allowed by the documentation. * If the user sets AVHWFramesContext.free and AVHWFramesContext.user_opaque, * the new free callback must call the potentially set previous free callback. * This API call may set any dynamically allocated fields, including the free * callback. * * The function will set at least the following fields on AVHWFramesContext * (potentially more, depending on hwaccel API): * * - All fields set by av_hwframe_ctx_alloc(). * - Set the format field to hw_pix_fmt. * - Set the sw_format field to the most suited and most versatile format. (An * implication is that this will prefer generic formats over opaque formats * with arbitrary restrictions, if possible.) * - Set the width/height fields to the coded frame size, rounded up to the * API-specific minimum alignment. * - Only _if_ the hwaccel requires a pre-allocated pool: set the initial_pool_size * field to the number of maximum reference surfaces possible with the codec, * plus 1 surface for the user to work (meaning the user can safely reference * at most 1 decoded surface at a time), plus additional buffering introduced * by frame threading. If the hwaccel does not require pre-allocation, the * field is left to 0, and the decoder will allocate new surfaces on demand * during decoding. * - Possibly AVHWFramesContext.hwctx fields, depending on the underlying * hardware API. * * Essentially, out_frames_ref returns the same as av_hwframe_ctx_alloc(), but * with basic frame parameters set. * * The function is stateless, and does not change the AVCodecContext or the * device_ref AVHWDeviceContext. * * @param avctx The context which is currently calling get_format, and which * implicitly contains all state needed for filling the returned * AVHWFramesContext properly. * @param device_ref A reference to the AVHWDeviceContext describing the device * which will be used by the hardware decoder. * @param hw_pix_fmt The hwaccel format you are going to return from get_format. * @param out_frames_ref On success, set to a reference to an _uninitialized_ * AVHWFramesContext, created from the given device_ref. * Fields will be set to values required for decoding. * Not changed if an error is returned. * @return zero on success, a negative value on error. The following error codes * have special semantics: * AVERROR(ENOENT): the decoder does not support this functionality. Setup * is always manual, or it is a decoder which does not * support setting AVCodecContext.hw_frames_ctx at all, * or it is a software format. * AVERROR(EINVAL): it is known that hardware decoding is not supported for * this configuration, or the device_ref is not supported * for the hwaccel referenced by hw_pix_fmt. */ int avcodec_get_hw_frames_parameters(AVCodecContext *avctx, AVBufferRef *device_ref, enum AVPixelFormat hw_pix_fmt, AVBufferRef **out_frames_ref); /** * @defgroup lavc_parsing Frame parsing * @{ */ enum AVPictureStructure { AV_PICTURE_STRUCTURE_UNKNOWN, //< unknown AV_PICTURE_STRUCTURE_TOP_FIELD, //< coded as top field AV_PICTURE_STRUCTURE_BOTTOM_FIELD, //< coded as bottom field AV_PICTURE_STRUCTURE_FRAME, //< coded as frame }; typedef struct AVCodecParserContext { void *priv_data; struct AVCodecParser *parser; int64_t frame_offset; /* offset of the current frame */ int64_t cur_offset; /* current offset (incremented by each av_parser_parse()) */ int64_t next_frame_offset; /* offset of the next frame */ /* video info */ int pict_type; /* XXX: Put it back in AVCodecContext. */ /** * This field is used for proper frame duration computation in lavf. * It signals, how much longer the frame duration of the current frame * is compared to normal frame duration. * * frame_duration = (1 + repeat_pict) * time_base * * It is used by codecs like H.264 to display telecined material. */ int repeat_pict; /* XXX: Put it back in AVCodecContext. */ int64_t pts; /* pts of the current frame */ int64_t dts; /* dts of the current frame */ /* private data */ int64_t last_pts; int64_t last_dts; int fetch_timestamp; #define AV_PARSER_PTS_NB 4 int cur_frame_start_index; int64_t cur_frame_offset[AV_PARSER_PTS_NB]; int64_t cur_frame_pts[AV_PARSER_PTS_NB]; int64_t cur_frame_dts[AV_PARSER_PTS_NB]; int flags; #define PARSER_FLAG_COMPLETE_FRAMES 0x0001 #define PARSER_FLAG_ONCE 0x0002 /// Set if the parser has a valid file offset #define PARSER_FLAG_FETCHED_OFFSET 0x0004 #define PARSER_FLAG_USE_CODEC_TS 0x1000 int64_t offset; ///< byte offset from starting packet start int64_t cur_frame_end[AV_PARSER_PTS_NB]; /** * Set by parser to 1 for key frames and 0 for non-key frames. * It is initialized to -1, so if the parser doesn't set this flag, * old-style fallback using AV_PICTURE_TYPE_I picture type as key frames * will be used. */ int key_frame; #if FF_API_CONVERGENCE_DURATION /** * @deprecated unused */ attribute_deprecated int64_t convergence_duration; #endif // Timestamp generation support: /** * Synchronization point for start of timestamp generation. * * Set to >0 for sync point, 0 for no sync point and <0 for undefined * (default). * * For example, this corresponds to presence of H.264 buffering period * SEI message. */ int dts_sync_point; /** * Offset of the current timestamp against last timestamp sync point in * units of AVCodecContext.time_base. * * Set to INT_MIN when dts_sync_point unused. Otherwise, it must * contain a valid timestamp offset. * * Note that the timestamp of sync point has usually a nonzero * dts_ref_dts_delta, which refers to the previous sync point. Offset of * the next frame after timestamp sync point will be usually 1. * * For example, this corresponds to H.264 cpb_removal_delay. */ int dts_ref_dts_delta; /** * Presentation delay of current frame in units of AVCodecContext.time_base. * * Set to INT_MIN when dts_sync_point unused. Otherwise, it must * contain valid non-negative timestamp delta (presentation time of a frame * must not lie in the past). * * This delay represents the difference between decoding and presentation * time of the frame. * * For example, this corresponds to H.264 dpb_output_delay. */ int pts_dts_delta; /** * Position of the packet in file. * * Analogous to cur_frame_pts/dts */ int64_t cur_frame_pos[AV_PARSER_PTS_NB]; /** * Byte position of currently parsed frame in stream. */ int64_t pos; /** * Previous frame byte position. */ int64_t last_pos; /** * Duration of the current frame. * For audio, this is in units of 1 / AVCodecContext.sample_rate. * For all other types, this is in units of AVCodecContext.time_base. */ int duration; enum AVFieldOrder field_order; /** * Indicate whether a picture is coded as a frame, top field or bottom field. * * For example, H.264 field_pic_flag equal to 0 corresponds to * AV_PICTURE_STRUCTURE_FRAME. An H.264 picture with field_pic_flag * equal to 1 and bottom_field_flag equal to 0 corresponds to * AV_PICTURE_STRUCTURE_TOP_FIELD. */ enum AVPictureStructure picture_structure; /** * Picture number incremented in presentation or output order. * This field may be reinitialized at the first picture of a new sequence. * * For example, this corresponds to H.264 PicOrderCnt. */ int output_picture_number; /** * Dimensions of the decoded video intended for presentation. */ int width; int height; /** * Dimensions of the coded video. */ int coded_width; int coded_height; /** * The format of the coded data, corresponds to enum AVPixelFormat for video * and for enum AVSampleFormat for audio. * * Note that a decoder can have considerable freedom in how exactly it * decodes the data, so the format reported here might be different from the * one returned by a decoder. */ int format; } AVCodecParserContext; typedef struct AVCodecParser { int codec_ids[5]; /* several codec IDs are permitted */ int priv_data_size; int (*parser_init)(AVCodecParserContext *s); /* This callback never returns an error, a negative value means that * the frame start was in a previous packet. */ int (*parser_parse)(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size); void (*parser_close)(AVCodecParserContext *s); int (*split)(AVCodecContext *avctx, const uint8_t *buf, int buf_size); struct AVCodecParser *next; } AVCodecParser; /** * Iterate over all registered codec parsers. * * @param opaque a pointer where libavcodec will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered codec parser or NULL when the iteration is * finished */ const AVCodecParser *av_parser_iterate(void **opaque); attribute_deprecated AVCodecParser *av_parser_next(const AVCodecParser *c); attribute_deprecated void av_register_codec_parser(AVCodecParser *parser); AVCodecParserContext *av_parser_init(int codec_id); /** * Parse a packet. * * @param s parser context. * @param avctx codec context. * @param poutbuf set to pointer to parsed buffer or NULL if not yet finished. * @param poutbuf_size set to size of parsed buffer or zero if not yet finished. * @param buf input buffer. * @param buf_size buffer size in bytes without the padding. I.e. the full buffer size is assumed to be buf_size + AV_INPUT_BUFFER_PADDING_SIZE. To signal EOF, this should be 0 (so that the last frame can be output). * @param pts input presentation timestamp. * @param dts input decoding timestamp. * @param pos input byte position in stream. * @return the number of bytes of the input bitstream used. * * Example: * @code * while(in_len){ * len = av_parser_parse2(myparser, AVCodecContext, &data, &size, * in_data, in_len, * pts, dts, pos); * in_data += len; * in_len -= len; * * if(size) * decode_frame(data, size); * } * @endcode */ int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int64_t pts, int64_t dts, int64_t pos); /** * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed * @deprecated use AVBitStreamFilter */ int av_parser_change(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe); void av_parser_close(AVCodecParserContext *s); /** * @} * @} */ /** * @addtogroup lavc_encoding * @{ */ /** * Find a registered encoder with a matching codec ID. * * @param id AVCodecID of the requested encoder * @return An encoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_encoder(enum AVCodecID id); /** * Find a registered encoder with the specified name. * * @param name name of the requested encoder * @return An encoder if one was found, NULL otherwise. */ AVCodec *avcodec_find_encoder_by_name(const char *name); /** * Encode a frame of audio. * * Takes input samples from frame and writes the next output packet, if * available, to avpkt. The output packet does not necessarily contain data for * the most recent frame, as encoders can delay, split, and combine input frames * internally as needed. * * @param avctx codec context * @param avpkt output AVPacket. * The user can supply an output buffer by setting * avpkt->data and avpkt->size prior to calling the * function, but if the size of the user-provided data is not * large enough, encoding will fail. If avpkt->data and * avpkt->size are set, avpkt->destruct must also be set. All * other AVPacket fields will be reset by the encoder using * av_init_packet(). If avpkt->data is NULL, the encoder will * allocate it. The encoder will set avpkt->size to the size * of the output packet. * * If this function fails or produces no output, avpkt will be * freed using av_packet_unref(). * @param[in] frame AVFrame containing the raw audio data to be encoded. * May be NULL when flushing an encoder that has the * AV_CODEC_CAP_DELAY capability set. * If AV_CODEC_CAP_VARIABLE_FRAME_SIZE is set, then each frame * can have any number of samples. * If it is not set, frame->nb_samples must be equal to * avctx->frame_size for all frames except the last. * The final frame may be smaller than avctx->frame_size. * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the * output packet is non-empty, and to 0 if it is * empty. If the function returns an error, the * packet can be assumed to be invalid, and the * value of got_packet_ptr is undefined and should * not be used. * @return 0 on success, negative error code on failure * * @deprecated use avcodec_send_frame()/avcodec_receive_packet() instead */ attribute_deprecated int avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr); /** * Encode a frame of video. * * Takes input raw video data from frame and writes the next output packet, if * available, to avpkt. The output packet does not necessarily contain data for * the most recent frame, as encoders can delay and reorder input frames * internally as needed. * * @param avctx codec context * @param avpkt output AVPacket. * The user can supply an output buffer by setting * avpkt->data and avpkt->size prior to calling the * function, but if the size of the user-provided data is not * large enough, encoding will fail. All other AVPacket fields * will be reset by the encoder using av_init_packet(). If * avpkt->data is NULL, the encoder will allocate it. * The encoder will set avpkt->size to the size of the * output packet. The returned data (if any) belongs to the * caller, he is responsible for freeing it. * * If this function fails or produces no output, avpkt will be * freed using av_packet_unref(). * @param[in] frame AVFrame containing the raw video data to be encoded. * May be NULL when flushing an encoder that has the * AV_CODEC_CAP_DELAY capability set. * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the * output packet is non-empty, and to 0 if it is * empty. If the function returns an error, the * packet can be assumed to be invalid, and the * value of got_packet_ptr is undefined and should * not be used. * @return 0 on success, negative error code on failure * * @deprecated use avcodec_send_frame()/avcodec_receive_packet() instead */ attribute_deprecated int avcodec_encode_video2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr); int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVSubtitle *sub); /** * @} */ #if FF_API_AVPICTURE /** * @addtogroup lavc_picture * @{ */ /** * @deprecated unused */ attribute_deprecated int avpicture_alloc(AVPicture *picture, enum AVPixelFormat pix_fmt, int width, int height); /** * @deprecated unused */ attribute_deprecated void avpicture_free(AVPicture *picture); /** * @deprecated use av_image_fill_arrays() instead. */ attribute_deprecated int avpicture_fill(AVPicture *picture, const uint8_t *ptr, enum AVPixelFormat pix_fmt, int width, int height); /** * @deprecated use av_image_copy_to_buffer() instead. */ attribute_deprecated int avpicture_layout(const AVPicture *src, enum AVPixelFormat pix_fmt, int width, int height, unsigned char *dest, int dest_size); /** * @deprecated use av_image_get_buffer_size() instead. */ attribute_deprecated int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height); /** * @deprecated av_image_copy() instead. */ attribute_deprecated void av_picture_copy(AVPicture *dst, const AVPicture *src, enum AVPixelFormat pix_fmt, int width, int height); /** * @deprecated unused */ attribute_deprecated int av_picture_crop(AVPicture *dst, const AVPicture *src, enum AVPixelFormat pix_fmt, int top_band, int left_band); /** * @deprecated unused */ attribute_deprecated int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width, enum AVPixelFormat pix_fmt, int padtop, int padbottom, int padleft, int padright, int *color); /** * @} */ #endif /** * @defgroup lavc_misc Utility functions * @ingroup libavc * * Miscellaneous utility functions related to both encoding and decoding * (or neither). * @{ */ /** * @defgroup lavc_misc_pixfmt Pixel formats * * Functions for working with pixel formats. * @{ */ #if FF_API_GETCHROMA /** * @deprecated Use av_pix_fmt_get_chroma_sub_sample */ attribute_deprecated void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift); #endif /** * Return a value representing the fourCC code associated to the * pixel format pix_fmt, or 0 if no associated fourCC code can be * found. */ unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat pix_fmt); /** * @deprecated see av_get_pix_fmt_loss() */ int avcodec_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt, enum AVPixelFormat src_pix_fmt, int has_alpha); /** * Find the best pixel format to convert to given a certain source pixel * format. When converting from one pixel format to another, information loss * may occur. For example, when converting from RGB24 to GRAY, the color * information will be lost. Similarly, other losses occur when converting from * some formats to other formats. avcodec_find_best_pix_fmt_of_2() searches which of * the given pixel formats should be used to suffer the least amount of loss. * The pixel formats from which it chooses one, are determined by the * pix_fmt_list parameter. * * * @param[in] pix_fmt_list AV_PIX_FMT_NONE terminated array of pixel formats to choose from * @param[in] src_pix_fmt source pixel format * @param[in] has_alpha Whether the source pixel format alpha channel is used. * @param[out] loss_ptr Combination of flags informing you what kind of losses will occur. * @return The best pixel format to convert to or -1 if none was found. */ enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(const enum AVPixelFormat *pix_fmt_list, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); /** * @deprecated see av_find_best_pix_fmt_of_2() */ enum AVPixelFormat avcodec_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); attribute_deprecated enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat * fmt); /** * @} */ #if FF_API_TAG_STRING /** * Put a string representing the codec tag codec_tag in buf. * * @param buf buffer to place codec tag in * @param buf_size size in bytes of buf * @param codec_tag codec tag to assign * @return the length of the string that would have been generated if * enough space had been available, excluding the trailing null * * @deprecated see av_fourcc_make_string() and av_fourcc2str(). */ attribute_deprecated size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag); #endif void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode); /** * Return a name for the specified profile, if available. * * @param codec the codec that is searched for the given profile * @param profile the profile value for which a name is requested * @return A name for the profile if found, NULL otherwise. */ const char *av_get_profile_name(const AVCodec *codec, int profile); /** * Return a name for the specified profile, if available. * * @param codec_id the ID of the codec to which the requested profile belongs * @param profile the profile value for which a name is requested * @return A name for the profile if found, NULL otherwise. * * @note unlike av_get_profile_name(), which searches a list of profiles * supported by a specific decoder or encoder implementation, this * function searches the list of profiles from the AVCodecDescriptor */ const char *avcodec_profile_name(enum AVCodecID codec_id, int profile); int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size); int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int, int),void *arg, int *ret, int count); //FIXME func typedef /** * Fill AVFrame audio data and linesize pointers. * * The buffer buf must be a preallocated buffer with a size big enough * to contain the specified samples amount. The filled AVFrame data * pointers will point to this buffer. * * AVFrame extended_data channel pointers are allocated if necessary for * planar audio. * * @param frame the AVFrame * frame->nb_samples must be set prior to calling the * function. This function fills in frame->data, * frame->extended_data, frame->linesize[0]. * @param nb_channels channel count * @param sample_fmt sample format * @param buf buffer to use for frame data * @param buf_size size of buffer * @param align plane size sample alignment (0 = default) * @return >=0 on success, negative error code on failure * @todo return the size in bytes required to store the samples in * case of success, at the next libavutil bump */ int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels, enum AVSampleFormat sample_fmt, const uint8_t *buf, int buf_size, int align); /** * Reset the internal decoder state / flush internal buffers. Should be called * e.g. when seeking or when switching to a different stream. * * @note when refcounted frames are not used (i.e. avctx->refcounted_frames is 0), * this invalidates the frames previously returned from the decoder. When * refcounted frames are used, the decoder just releases any references it might * keep internally, but the caller's reference remains valid. */ void avcodec_flush_buffers(AVCodecContext *avctx); /** * Return codec bits per sample. * * @param[in] codec_id the codec * @return Number of bits per sample or zero if unknown for the given codec. */ int av_get_bits_per_sample(enum AVCodecID codec_id); /** * Return the PCM codec associated with a sample format. * @param be endianness, 0 for little, 1 for big, * -1 (or anything else) for native * @return AV_CODEC_ID_PCM_* or AV_CODEC_ID_NONE */ enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be); /** * Return codec bits per sample. * Only return non-zero if the bits per sample is exactly correct, not an * approximation. * * @param[in] codec_id the codec * @return Number of bits per sample or zero if unknown for the given codec. */ int av_get_exact_bits_per_sample(enum AVCodecID codec_id); /** * Return audio frame duration. * * @param avctx codec context * @param frame_bytes size of the frame, or 0 if unknown * @return frame duration, in samples, if known. 0 if not able to * determine. */ int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes); /** * This function is the same as av_get_audio_frame_duration(), except it works * with AVCodecParameters instead of an AVCodecContext. */ int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes); #if FF_API_OLD_BSF typedef struct AVBitStreamFilterContext { void *priv_data; const struct AVBitStreamFilter *filter; AVCodecParserContext *parser; struct AVBitStreamFilterContext *next; /** * Internal default arguments, used if NULL is passed to av_bitstream_filter_filter(). * Not for access by library users. */ char *args; } AVBitStreamFilterContext; #endif typedef struct AVBSFInternal AVBSFInternal; /** * The bitstream filter state. * * This struct must be allocated with av_bsf_alloc() and freed with * av_bsf_free(). * * The fields in the struct will only be changed (by the caller or by the * filter) as described in their documentation, and are to be considered * immutable otherwise. */ typedef struct AVBSFContext { /** * A class for logging and AVOptions */ const AVClass *av_class; /** * The bitstream filter this context is an instance of. */ const struct AVBitStreamFilter *filter; /** * Opaque libavcodec internal data. Must not be touched by the caller in any * way. */ AVBSFInternal *internal; /** * Opaque filter-specific private data. If filter->priv_class is non-NULL, * this is an AVOptions-enabled struct. */ void *priv_data; /** * Parameters of the input stream. This field is allocated in * av_bsf_alloc(), it needs to be filled by the caller before * av_bsf_init(). */ AVCodecParameters *par_in; /** * Parameters of the output stream. This field is allocated in * av_bsf_alloc(), it is set by the filter in av_bsf_init(). */ AVCodecParameters *par_out; /** * The timebase used for the timestamps of the input packets. Set by the * caller before av_bsf_init(). */ AVRational time_base_in; /** * The timebase used for the timestamps of the output packets. Set by the * filter in av_bsf_init(). */ AVRational time_base_out; } AVBSFContext; typedef struct AVBitStreamFilter { const char *name; /** * A list of codec ids supported by the filter, terminated by * AV_CODEC_ID_NONE. * May be NULL, in that case the bitstream filter works with any codec id. */ const enum AVCodecID *codec_ids; /** * A class for the private data, used to declare bitstream filter private * AVOptions. This field is NULL for bitstream filters that do not declare * any options. * * If this field is non-NULL, the first member of the filter private data * must be a pointer to AVClass, which will be set by libavcodec generic * code to this class. */ const AVClass *priv_class; /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavcodec and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ int priv_data_size; int (*init)(AVBSFContext *ctx); int (*filter)(AVBSFContext *ctx, AVPacket *pkt); void (*close)(AVBSFContext *ctx); void (*flush)(AVBSFContext *ctx); } AVBitStreamFilter; #if FF_API_OLD_BSF /** * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext) * is deprecated. Use the new bitstream filtering API (using AVBSFContext). */ attribute_deprecated void av_register_bitstream_filter(AVBitStreamFilter *bsf); /** * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext) * is deprecated. Use av_bsf_get_by_name(), av_bsf_alloc(), and av_bsf_init() * from the new bitstream filtering API (using AVBSFContext). */ attribute_deprecated AVBitStreamFilterContext *av_bitstream_filter_init(const char *name); /** * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext) * is deprecated. Use av_bsf_send_packet() and av_bsf_receive_packet() from the * new bitstream filtering API (using AVBSFContext). */ attribute_deprecated int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe); /** * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext) * is deprecated. Use av_bsf_free() from the new bitstream filtering API (using * AVBSFContext). */ attribute_deprecated void av_bitstream_filter_close(AVBitStreamFilterContext *bsf); /** * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext) * is deprecated. Use av_bsf_iterate() from the new bitstream filtering API (using * AVBSFContext). */ attribute_deprecated const AVBitStreamFilter *av_bitstream_filter_next(const AVBitStreamFilter *f); #endif /** * @return a bitstream filter with the specified name or NULL if no such * bitstream filter exists. */ const AVBitStreamFilter *av_bsf_get_by_name(const char *name); /** * Iterate over all registered bitstream filters. * * @param opaque a pointer where libavcodec will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered bitstream filter or NULL when the iteration is * finished */ const AVBitStreamFilter *av_bsf_iterate(void **opaque); #if FF_API_NEXT attribute_deprecated const AVBitStreamFilter *av_bsf_next(void **opaque); #endif /** * Allocate a context for a given bitstream filter. The caller must fill in the * context parameters as described in the documentation and then call * av_bsf_init() before sending any data to the filter. * * @param filter the filter for which to allocate an instance. * @param ctx a pointer into which the pointer to the newly-allocated context * will be written. It must be freed with av_bsf_free() after the * filtering is done. * * @return 0 on success, a negative AVERROR code on failure */ int av_bsf_alloc(const AVBitStreamFilter *filter, AVBSFContext **ctx); /** * Prepare the filter for use, after all the parameters and options have been * set. */ int av_bsf_init(AVBSFContext *ctx); /** * Submit a packet for filtering. * * After sending each packet, the filter must be completely drained by calling * av_bsf_receive_packet() repeatedly until it returns AVERROR(EAGAIN) or * AVERROR_EOF. * * @param pkt the packet to filter. The bitstream filter will take ownership of * the packet and reset the contents of pkt. pkt is not touched if an error occurs. * This parameter may be NULL, which signals the end of the stream (i.e. no more * packets will be sent). That will cause the filter to output any packets it * may have buffered internally. * * @return 0 on success, a negative AVERROR on error. */ int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt); /** * Retrieve a filtered packet. * * @param[out] pkt this struct will be filled with the contents of the filtered * packet. It is owned by the caller and must be freed using * av_packet_unref() when it is no longer needed. * This parameter should be "clean" (i.e. freshly allocated * with av_packet_alloc() or unreffed with av_packet_unref()) * when this function is called. If this function returns * successfully, the contents of pkt will be completely * overwritten by the returned data. On failure, pkt is not * touched. * * @return 0 on success. AVERROR(EAGAIN) if more packets need to be sent to the * filter (using av_bsf_send_packet()) to get more output. AVERROR_EOF if there * will be no further output from the filter. Another negative AVERROR value if * an error occurs. * * @note one input packet may result in several output packets, so after sending * a packet with av_bsf_send_packet(), this function needs to be called * repeatedly until it stops returning 0. It is also possible for a filter to * output fewer packets than were sent to it, so this function may return * AVERROR(EAGAIN) immediately after a successful av_bsf_send_packet() call. */ int av_bsf_receive_packet(AVBSFContext *ctx, AVPacket *pkt); /** * Reset the internal bitstream filter state / flush internal buffers. */ void av_bsf_flush(AVBSFContext *ctx); /** * Free a bitstream filter context and everything associated with it; write NULL * into the supplied pointer. */ void av_bsf_free(AVBSFContext **ctx); /** * Get the AVClass for AVBSFContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *av_bsf_get_class(void); /** * Structure for chain/list of bitstream filters. * Empty list can be allocated by av_bsf_list_alloc(). */ typedef struct AVBSFList AVBSFList; /** * Allocate empty list of bitstream filters. * The list must be later freed by av_bsf_list_free() * or finalized by av_bsf_list_finalize(). * * @return Pointer to @ref AVBSFList on success, NULL in case of failure */ AVBSFList *av_bsf_list_alloc(void); /** * Free list of bitstream filters. * * @param lst Pointer to pointer returned by av_bsf_list_alloc() */ void av_bsf_list_free(AVBSFList **lst); /** * Append bitstream filter to the list of bitstream filters. * * @param lst List to append to * @param bsf Filter context to be appended * * @return >=0 on success, negative AVERROR in case of failure */ int av_bsf_list_append(AVBSFList *lst, AVBSFContext *bsf); /** * Construct new bitstream filter context given it's name and options * and append it to the list of bitstream filters. * * @param lst List to append to * @param bsf_name Name of the bitstream filter * @param options Options for the bitstream filter, can be set to NULL * * @return >=0 on success, negative AVERROR in case of failure */ int av_bsf_list_append2(AVBSFList *lst, const char * bsf_name, AVDictionary **options); /** * Finalize list of bitstream filters. * * This function will transform @ref AVBSFList to single @ref AVBSFContext, * so the whole chain of bitstream filters can be treated as single filter * freshly allocated by av_bsf_alloc(). * If the call is successful, @ref AVBSFList structure is freed and lst * will be set to NULL. In case of failure, caller is responsible for * freeing the structure by av_bsf_list_free() * * @param lst Filter list structure to be transformed * @param[out] bsf Pointer to be set to newly created @ref AVBSFContext structure * representing the chain of bitstream filters * * @return >=0 on success, negative AVERROR in case of failure */ int av_bsf_list_finalize(AVBSFList **lst, AVBSFContext **bsf); /** * Parse string describing list of bitstream filters and create single * @ref AVBSFContext describing the whole chain of bitstream filters. * Resulting @ref AVBSFContext can be treated as any other @ref AVBSFContext freshly * allocated by av_bsf_alloc(). * * @param str String describing chain of bitstream filters in format * `bsf1[=opt1=val1:opt2=val2][,bsf2]` * @param[out] bsf Pointer to be set to newly created @ref AVBSFContext structure * representing the chain of bitstream filters * * @return >=0 on success, negative AVERROR in case of failure */ int av_bsf_list_parse_str(const char *str, AVBSFContext **bsf); /** * Get null/pass-through bitstream filter. * * @param[out] bsf Pointer to be set to new instance of pass-through bitstream filter * * @return */ int av_bsf_get_null_filter(AVBSFContext **bsf); /* memory */ /** * Same behaviour av_fast_malloc but the buffer has additional * AV_INPUT_BUFFER_PADDING_SIZE at the end which will always be 0. * * In addition the whole buffer will initially and after resizes * be 0-initialized so that no uninitialized data will ever appear. */ void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size); /** * Same behaviour av_fast_padded_malloc except that buffer will always * be 0-initialized after call. */ void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size); /** * Encode extradata length to a buffer. Used by xiph codecs. * * @param s buffer to write to; must be at least (v/255+1) bytes long * @param v size of extradata in bytes * @return number of bytes written to the buffer. */ unsigned int av_xiphlacing(unsigned char *s, unsigned int v); #if FF_API_USER_VISIBLE_AVHWACCEL /** * Register the hardware accelerator hwaccel. * * @deprecated This function doesn't do anything. */ attribute_deprecated void av_register_hwaccel(AVHWAccel *hwaccel); /** * If hwaccel is NULL, returns the first registered hardware accelerator, * if hwaccel is non-NULL, returns the next registered hardware accelerator * after hwaccel, or NULL if hwaccel is the last one. * * @deprecated AVHWaccel structures contain no user-serviceable parts, so * this function should not be used. */ attribute_deprecated AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel); #endif #if FF_API_LOCKMGR /** * Lock operation used by lockmgr * * @deprecated Deprecated together with av_lockmgr_register(). */ enum AVLockOp { AV_LOCK_CREATE, ///< Create a mutex AV_LOCK_OBTAIN, ///< Lock the mutex AV_LOCK_RELEASE, ///< Unlock the mutex AV_LOCK_DESTROY, ///< Free mutex resources }; /** * Register a user provided lock manager supporting the operations * specified by AVLockOp. The "mutex" argument to the function points * to a (void *) where the lockmgr should store/get a pointer to a user * allocated mutex. It is NULL upon AV_LOCK_CREATE and equal to the * value left by the last call for all other ops. If the lock manager is * unable to perform the op then it should leave the mutex in the same * state as when it was called and return a non-zero value. However, * when called with AV_LOCK_DESTROY the mutex will always be assumed to * have been successfully destroyed. If av_lockmgr_register succeeds * it will return a non-negative value, if it fails it will return a * negative value and destroy all mutex and unregister all callbacks. * av_lockmgr_register is not thread-safe, it must be called from a * single thread before any calls which make use of locking are used. * * @param cb User defined callback. av_lockmgr_register invokes calls * to this callback and the previously registered callback. * The callback will be used to create more than one mutex * each of which must be backed by its own underlying locking * mechanism (i.e. do not use a single static object to * implement your lock manager). If cb is set to NULL the * lockmgr will be unregistered. * * @deprecated This function does nothing, and always returns 0. Be sure to * build with thread support to get basic thread safety. */ attribute_deprecated int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op)); #endif /** * Get the type of the given codec. */ enum AVMediaType avcodec_get_type(enum AVCodecID codec_id); /** * Get the name of a codec. * @return a static string identifying the codec; never NULL */ const char *avcodec_get_name(enum AVCodecID id); /** * @return a positive value if s is open (i.e. avcodec_open2() was called on it * with no corresponding avcodec_close()), 0 otherwise. */ int avcodec_is_open(AVCodecContext *s); /** * @return a non-zero number if codec is an encoder, zero otherwise */ int av_codec_is_encoder(const AVCodec *codec); /** * @return a non-zero number if codec is a decoder, zero otherwise */ int av_codec_is_decoder(const AVCodec *codec); /** * @return descriptor for given codec ID or NULL if no descriptor exists. */ const AVCodecDescriptor *avcodec_descriptor_get(enum AVCodecID id); /** * Iterate over all codec descriptors known to libavcodec. * * @param prev previous descriptor. NULL to get the first descriptor. * * @return next descriptor or NULL after the last descriptor */ const AVCodecDescriptor *avcodec_descriptor_next(const AVCodecDescriptor *prev); /** * @return codec descriptor with the given name or NULL if no such descriptor * exists. */ const AVCodecDescriptor *avcodec_descriptor_get_by_name(const char *name); /** * Allocate a CPB properties structure and initialize its fields to default * values. * * @param size if non-NULL, the size of the allocated struct will be written * here. This is useful for embedding it in side data. * * @return the newly allocated struct or NULL on failure */ AVCPBProperties *av_cpb_properties_alloc(size_t *size); /** * @} */ #endif /* AVCODEC_AVCODEC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/avdct.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_AVDCT_H #define AVCODEC_AVDCT_H #include "libavutil/opt.h" /** * AVDCT context. * @note function pointers can be NULL if the specific features have been * disabled at build time. */ typedef struct AVDCT { const AVClass *av_class; void (*idct)(int16_t *block /* align 16 */); /** * IDCT input permutation. * Several optimized IDCTs need a permutated input (relative to the * normal order of the reference IDCT). * This permutation must be performed before the idct_put/add. * Note, normally this can be merged with the zigzag/alternate scan
* An example to avoid confusion: * - (->decode coeffs -> zigzag reorder -> dequant -> reference IDCT -> ...) * - (x -> reference DCT -> reference IDCT -> x) * - (x -> reference DCT -> simple_mmx_perm = idct_permutation * -> simple_idct_mmx -> x) * - (-> decode coeffs -> zigzag reorder -> simple_mmx_perm -> dequant * -> simple_idct_mmx -> ...) */ uint8_t idct_permutation[64]; void (*fdct)(int16_t *block /* align 16 */); /** * DCT algorithm. * must use AVOptions to set this field. */ int dct_algo; /** * IDCT algorithm. * must use AVOptions to set this field. */ int idct_algo; void (*get_pixels)(int16_t *block /* align 16 */, const uint8_t *pixels /* align 8 */, ptrdiff_t line_size); int bits_per_sample; } AVDCT; /** * Allocates a AVDCT context. * This needs to be initialized with avcodec_dct_init() after optionally * configuring it with AVOptions. * * To free it use av_free() */ AVDCT *avcodec_dct_alloc(void); int avcodec_dct_init(AVDCT *); const AVClass *avcodec_dct_get_class(void); #endif /* AVCODEC_AVDCT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/avfft.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_AVFFT_H #define AVCODEC_AVFFT_H /** * @file * @ingroup lavc_fft * FFT functions */ /** * @defgroup lavc_fft FFT functions * @ingroup lavc_misc * * @{ */ typedef float FFTSample; typedef struct FFTComplex { FFTSample re, im; } FFTComplex; typedef struct FFTContext FFTContext; /** * Set up a complex FFT. * @param nbits log2 of the length of the input array * @param inverse if 0 perform the forward transform, if 1 perform the inverse */ FFTContext *av_fft_init(int nbits, int inverse); /** * Do the permutation needed BEFORE calling ff_fft_calc(). */ void av_fft_permute(FFTContext *s, FFTComplex *z); /** * Do a complex FFT with the parameters defined in av_fft_init(). The * input data must be permuted before. No 1.0/sqrt(n) normalization is done. */ void av_fft_calc(FFTContext *s, FFTComplex *z); void av_fft_end(FFTContext *s); FFTContext *av_mdct_init(int nbits, int inverse, double scale); void av_imdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input); void av_imdct_half(FFTContext *s, FFTSample *output, const FFTSample *input); void av_mdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input); void av_mdct_end(FFTContext *s); /* Real Discrete Fourier Transform */ enum RDFTransformType { DFT_R2C, IDFT_C2R, IDFT_R2C, DFT_C2R, }; typedef struct RDFTContext RDFTContext; /** * Set up a real FFT. * @param nbits log2 of the length of the input array * @param trans the type of transform */ RDFTContext *av_rdft_init(int nbits, enum RDFTransformType trans); void av_rdft_calc(RDFTContext *s, FFTSample *data); void av_rdft_end(RDFTContext *s); /* Discrete Cosine Transform */ typedef struct DCTContext DCTContext; enum DCTTransformType { DCT_II = 0, DCT_III, DCT_I, DST_I, }; /** * Set up DCT. * * @param nbits size of the input array: * (1 << nbits) for DCT-II, DCT-III and DST-I * (1 << nbits) + 1 for DCT-I * @param type the type of transform * * @note the first element of the input of DST-I is ignored */ DCTContext *av_dct_init(int nbits, enum DCTTransformType type); void av_dct_calc(DCTContext *s, FFTSample *data); void av_dct_end (DCTContext *s); /** * @} */ #endif /* AVCODEC_AVFFT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/d3d11va.h ================================================ /* * Direct3D11 HW acceleration * * copyright (c) 2009 Laurent Aimar * copyright (c) 2015 Steve Lhomme * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_D3D11VA_H #define AVCODEC_D3D11VA_H /** * @file * @ingroup lavc_codec_hwaccel_d3d11va * Public libavcodec D3D11VA header. */ #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0602 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0602 #endif #include #include /** * @defgroup lavc_codec_hwaccel_d3d11va Direct3D11 * @ingroup lavc_codec_hwaccel * * @{ */ #define FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG 1 ///< Work around for Direct3D11 and old UVD/UVD+ ATI video cards #define FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO 2 ///< Work around for Direct3D11 and old Intel GPUs with ClearVideo interface /** * This structure is used to provides the necessary configurations and data * to the Direct3D11 FFmpeg HWAccel implementation. * * The application must make it available as AVCodecContext.hwaccel_context. * * Use av_d3d11va_alloc_context() exclusively to allocate an AVD3D11VAContext. */ typedef struct AVD3D11VAContext { /** * D3D11 decoder object */ ID3D11VideoDecoder *decoder; /** * D3D11 VideoContext */ ID3D11VideoContext *video_context; /** * D3D11 configuration used to create the decoder */ D3D11_VIDEO_DECODER_CONFIG *cfg; /** * The number of surface in the surface array */ unsigned surface_count; /** * The array of Direct3D surfaces used to create the decoder */ ID3D11VideoDecoderOutputView **surface; /** * A bit field configuring the workarounds needed for using the decoder */ uint64_t workaround; /** * Private to the FFmpeg AVHWAccel implementation */ unsigned report_id; /** * Mutex to access video_context */ HANDLE context_mutex; } AVD3D11VAContext; /** * Allocate an AVD3D11VAContext. * * @return Newly-allocated AVD3D11VAContext or NULL on failure. */ AVD3D11VAContext *av_d3d11va_alloc_context(void); /** * @} */ #endif /* AVCODEC_D3D11VA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/dirac.h ================================================ /* * Copyright (C) 2007 Marco Gerards * Copyright (C) 2009 David Conrad * Copyright (C) 2011 Jordi Ortiz * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_DIRAC_H #define AVCODEC_DIRAC_H /** * @file * Interface to Dirac Decoder/Encoder * @author Marco Gerards * @author David Conrad * @author Jordi Ortiz */ #include "avcodec.h" /** * The spec limits the number of wavelet decompositions to 4 for both * level 1 (VC-2) and 128 (long-gop default). * 5 decompositions is the maximum before >16-bit buffers are needed. * Schroedinger allows this for DD 9,7 and 13,7 wavelets only, limiting * the others to 4 decompositions (or 3 for the fidelity filter). * * We use this instead of MAX_DECOMPOSITIONS to save some memory. */ #define MAX_DWT_LEVELS 5 /** * Parse code values: * * Dirac Specification -> * 9.6.1 Table 9.1 * * VC-2 Specification -> * 10.4.1 Table 10.1 */ enum DiracParseCodes { DIRAC_PCODE_SEQ_HEADER = 0x00, DIRAC_PCODE_END_SEQ = 0x10, DIRAC_PCODE_AUX = 0x20, DIRAC_PCODE_PAD = 0x30, DIRAC_PCODE_PICTURE_CODED = 0x08, DIRAC_PCODE_PICTURE_RAW = 0x48, DIRAC_PCODE_PICTURE_LOW_DEL = 0xC8, DIRAC_PCODE_PICTURE_HQ = 0xE8, DIRAC_PCODE_INTER_NOREF_CO1 = 0x0A, DIRAC_PCODE_INTER_NOREF_CO2 = 0x09, DIRAC_PCODE_INTER_REF_CO1 = 0x0D, DIRAC_PCODE_INTER_REF_CO2 = 0x0E, DIRAC_PCODE_INTRA_REF_CO = 0x0C, DIRAC_PCODE_INTRA_REF_RAW = 0x4C, DIRAC_PCODE_INTRA_REF_PICT = 0xCC, DIRAC_PCODE_MAGIC = 0x42424344, }; typedef struct DiracVersionInfo { int major; int minor; } DiracVersionInfo; typedef struct AVDiracSeqHeader { unsigned width; unsigned height; uint8_t chroma_format; ///< 0: 444 1: 422 2: 420 uint8_t interlaced; uint8_t top_field_first; uint8_t frame_rate_index; ///< index into dirac_frame_rate[] uint8_t aspect_ratio_index; ///< index into dirac_aspect_ratio[] uint16_t clean_width; uint16_t clean_height; uint16_t clean_left_offset; uint16_t clean_right_offset; uint8_t pixel_range_index; ///< index into dirac_pixel_range_presets[] uint8_t color_spec_index; ///< index into dirac_color_spec_presets[] int profile; int level; AVRational framerate; AVRational sample_aspect_ratio; enum AVPixelFormat pix_fmt; enum AVColorRange color_range; enum AVColorPrimaries color_primaries; enum AVColorTransferCharacteristic color_trc; enum AVColorSpace colorspace; DiracVersionInfo version; int bit_depth; } AVDiracSeqHeader; /** * Parse a Dirac sequence header. * * @param dsh this function will allocate and fill an AVDiracSeqHeader struct * and write it into this pointer. The caller must free it with * av_free(). * @param buf the data buffer * @param buf_size the size of the data buffer in bytes * @param log_ctx if non-NULL, this function will log errors here * @return 0 on success, a negative AVERROR code on failure */ int av_dirac_parse_sequence_header(AVDiracSeqHeader **dsh, const uint8_t *buf, size_t buf_size, void *log_ctx); #endif /* AVCODEC_DIRAC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/dv_profile.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_DV_PROFILE_H #define AVCODEC_DV_PROFILE_H #include #include "libavutil/pixfmt.h" #include "libavutil/rational.h" #include "avcodec.h" /* minimum number of bytes to read from a DV stream in order to * determine the profile */ #define DV_PROFILE_BYTES (6 * 80) /* 6 DIF blocks */ /* * AVDVProfile is used to express the differences between various * DV flavors. For now it's primarily used for differentiating * 525/60 and 625/50, but the plans are to use it for various * DV specs as well (e.g. SMPTE314M vs. IEC 61834). */ typedef struct AVDVProfile { int dsf; /* value of the dsf in the DV header */ int video_stype; /* stype for VAUX source pack */ int frame_size; /* total size of one frame in bytes */ int difseg_size; /* number of DIF segments per DIF channel */ int n_difchan; /* number of DIF channels per frame */ AVRational time_base; /* 1/framerate */ int ltc_divisor; /* FPS from the LTS standpoint */ int height; /* picture height in pixels */ int width; /* picture width in pixels */ AVRational sar[2]; /* sample aspect ratios for 4:3 and 16:9 */ enum AVPixelFormat pix_fmt; /* picture pixel format */ int bpm; /* blocks per macroblock */ const uint8_t *block_sizes; /* AC block sizes, in bits */ int audio_stride; /* size of audio_shuffle table */ int audio_min_samples[3]; /* min amount of audio samples */ /* for 48kHz, 44.1kHz and 32kHz */ int audio_samples_dist[5]; /* how many samples are supposed to be */ /* in each frame in a 5 frames window */ const uint8_t (*audio_shuffle)[9]; /* PCM shuffling table */ } AVDVProfile; /** * Get a DV profile for the provided compressed frame. * * @param sys the profile used for the previous frame, may be NULL * @param frame the compressed data buffer * @param buf_size size of the buffer in bytes * @return the DV profile for the supplied data or NULL on failure */ const AVDVProfile *av_dv_frame_profile(const AVDVProfile *sys, const uint8_t *frame, unsigned buf_size); /** * Get a DV profile for the provided stream parameters. */ const AVDVProfile *av_dv_codec_profile(int width, int height, enum AVPixelFormat pix_fmt); /** * Get a DV profile for the provided stream parameters. * The frame rate is used as a best-effort parameter. */ const AVDVProfile *av_dv_codec_profile2(int width, int height, enum AVPixelFormat pix_fmt, AVRational frame_rate); #endif /* AVCODEC_DV_PROFILE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/dxva2.h ================================================ /* * DXVA2 HW acceleration * * copyright (c) 2009 Laurent Aimar * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_DXVA2_H #define AVCODEC_DXVA2_H /** * @file * @ingroup lavc_codec_hwaccel_dxva2 * Public libavcodec DXVA2 header. */ #if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0602 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0602 #endif #include #include #include /** * @defgroup lavc_codec_hwaccel_dxva2 DXVA2 * @ingroup lavc_codec_hwaccel * * @{ */ #define FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG 1 ///< Work around for DXVA2 and old UVD/UVD+ ATI video cards #define FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO 2 ///< Work around for DXVA2 and old Intel GPUs with ClearVideo interface /** * This structure is used to provides the necessary configurations and data * to the DXVA2 FFmpeg HWAccel implementation. * * The application must make it available as AVCodecContext.hwaccel_context. */ struct dxva_context { /** * DXVA2 decoder object */ IDirectXVideoDecoder *decoder; /** * DXVA2 configuration used to create the decoder */ const DXVA2_ConfigPictureDecode *cfg; /** * The number of surface in the surface array */ unsigned surface_count; /** * The array of Direct3D surfaces used to create the decoder */ LPDIRECT3DSURFACE9 *surface; /** * A bit field configuring the workarounds needed for using the decoder */ uint64_t workaround; /** * Private to the FFmpeg AVHWAccel implementation */ unsigned report_id; }; /** * @} */ #endif /* AVCODEC_DXVA2_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/jni.h ================================================ /* * JNI public API functions * * Copyright (c) 2015-2016 Matthieu Bouron * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_JNI_H #define AVCODEC_JNI_H /* * Manually set a Java virtual machine which will be used to retrieve the JNI * environment. Once a Java VM is set it cannot be changed afterwards, meaning * you can call multiple times av_jni_set_java_vm with the same Java VM pointer * however it will error out if you try to set a different Java VM. * * @param vm Java virtual machine * @param log_ctx context used for logging, can be NULL * @return 0 on success, < 0 otherwise */ int av_jni_set_java_vm(void *vm, void *log_ctx); /* * Get the Java virtual machine which has been set with av_jni_set_java_vm. * * @param vm Java virtual machine * @return a pointer to the Java virtual machine */ void *av_jni_get_java_vm(void *log_ctx); #endif /* AVCODEC_JNI_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/mediacodec.h ================================================ /* * Android MediaCodec public API * * Copyright (c) 2016 Matthieu Bouron * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_MEDIACODEC_H #define AVCODEC_MEDIACODEC_H #include "libavcodec/avcodec.h" /** * This structure holds a reference to a android/view/Surface object that will * be used as output by the decoder. * */ typedef struct AVMediaCodecContext { /** * android/view/Surface object reference. */ void *surface; } AVMediaCodecContext; /** * Allocate and initialize a MediaCodec context. * * When decoding with MediaCodec is finished, the caller must free the * MediaCodec context with av_mediacodec_default_free. * * @return a pointer to a newly allocated AVMediaCodecContext on success, NULL otherwise */ AVMediaCodecContext *av_mediacodec_alloc_context(void); /** * Convenience function that sets up the MediaCodec context. * * @param avctx codec context * @param ctx MediaCodec context to initialize * @param surface reference to an android/view/Surface * @return 0 on success, < 0 otherwise */ int av_mediacodec_default_init(AVCodecContext *avctx, AVMediaCodecContext *ctx, void *surface); /** * This function must be called to free the MediaCodec context initialized with * av_mediacodec_default_init(). * * @param avctx codec context */ void av_mediacodec_default_free(AVCodecContext *avctx); /** * Opaque structure representing a MediaCodec buffer to render. */ typedef struct MediaCodecBuffer AVMediaCodecBuffer; /** * Release a MediaCodec buffer and render it to the surface that is associated * with the decoder. This function should only be called once on a given * buffer, once released the underlying buffer returns to the codec, thus * subsequent calls to this function will have no effect. * * @param buffer the buffer to render * @param render 1 to release and render the buffer to the surface or 0 to * discard the buffer * @return 0 on success, < 0 otherwise */ int av_mediacodec_release_buffer(AVMediaCodecBuffer *buffer, int render); /** * Release a MediaCodec buffer and render it at the given time to the surface * that is associated with the decoder. The timestamp must be within one second * of the current java/lang/System#nanoTime() (which is implemented using * CLOCK_MONOTONIC on Android). See the Android MediaCodec documentation * of android/media/MediaCodec#releaseOutputBuffer(int,long) for more details. * * @param buffer the buffer to render * @param time timestamp in nanoseconds of when to render the buffer * @return 0 on success, < 0 otherwise */ int av_mediacodec_render_buffer_at_time(AVMediaCodecBuffer *buffer, int64_t time); #endif /* AVCODEC_MEDIACODEC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/qsv.h ================================================ /* * Intel MediaSDK QSV public API * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_QSV_H #define AVCODEC_QSV_H #include #include "libavutil/buffer.h" /** * This struct is used for communicating QSV parameters between libavcodec and * the caller. It is managed by the caller and must be assigned to * AVCodecContext.hwaccel_context. * - decoding: hwaccel_context must be set on return from the get_format() * callback * - encoding: hwaccel_context must be set before avcodec_open2() */ typedef struct AVQSVContext { /** * If non-NULL, the session to use for encoding or decoding. * Otherwise, libavcodec will try to create an internal session. */ mfxSession session; /** * The IO pattern to use. */ int iopattern; /** * Extra buffers to pass to encoder or decoder initialization. */ mfxExtBuffer **ext_buffers; int nb_ext_buffers; /** * Encoding only. If this field is set to non-zero by the caller, libavcodec * will create an mfxExtOpaqueSurfaceAlloc extended buffer and pass it to * the encoder initialization. This only makes sense if iopattern is also * set to MFX_IOPATTERN_IN_OPAQUE_MEMORY. * * The number of allocated opaque surfaces will be the sum of the number * required by the encoder and the user-provided value nb_opaque_surfaces. * The array of the opaque surfaces will be exported to the caller through * the opaque_surfaces field. */ int opaque_alloc; /** * Encoding only, and only if opaque_alloc is set to non-zero. Before * calling avcodec_open2(), the caller should set this field to the number * of extra opaque surfaces to allocate beyond what is required by the * encoder. * * On return from avcodec_open2(), this field will be set by libavcodec to * the total number of allocated opaque surfaces. */ int nb_opaque_surfaces; /** * Encoding only, and only if opaque_alloc is set to non-zero. On return * from avcodec_open2(), this field will be used by libavcodec to export the * array of the allocated opaque surfaces to the caller, so they can be * passed to other parts of the pipeline. * * The buffer reference exported here is owned and managed by libavcodec, * the callers should make their own reference with av_buffer_ref() and free * it with av_buffer_unref() when it is no longer needed. * * The buffer data is an nb_opaque_surfaces-sized array of mfxFrameSurface1. */ AVBufferRef *opaque_surfaces; /** * Encoding only, and only if opaque_alloc is set to non-zero. On return * from avcodec_open2(), this field will be set to the surface type used in * the opaque allocation request. */ int opaque_alloc_type; } AVQSVContext; /** * Allocate a new context. * * It must be freed by the caller with av_free(). */ AVQSVContext *av_qsv_alloc_context(void); #endif /* AVCODEC_QSV_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/vaapi.h ================================================ /* * Video Acceleration API (shared data between FFmpeg and the video player) * HW decode acceleration for MPEG-2, MPEG-4, H.264 and VC-1 * * Copyright (C) 2008-2009 Splitted-Desktop Systems * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VAAPI_H #define AVCODEC_VAAPI_H /** * @file * @ingroup lavc_codec_hwaccel_vaapi * Public libavcodec VA API header. */ #include #include "libavutil/attributes.h" #include "version.h" #if FF_API_STRUCT_VAAPI_CONTEXT /** * @defgroup lavc_codec_hwaccel_vaapi VA API Decoding * @ingroup lavc_codec_hwaccel * @{ */ /** * This structure is used to share data between the FFmpeg library and * the client video application. * This shall be zero-allocated and available as * AVCodecContext.hwaccel_context. All user members can be set once * during initialization or through each AVCodecContext.get_buffer() * function call. In any case, they must be valid prior to calling * decoding functions. * * Deprecated: use AVCodecContext.hw_frames_ctx instead. */ struct attribute_deprecated vaapi_context { /** * Window system dependent data * * - encoding: unused * - decoding: Set by user */ void *display; /** * Configuration ID * * - encoding: unused * - decoding: Set by user */ uint32_t config_id; /** * Context ID (video decode pipeline) * * - encoding: unused * - decoding: Set by user */ uint32_t context_id; }; /* @} */ #endif /* FF_API_STRUCT_VAAPI_CONTEXT */ #endif /* AVCODEC_VAAPI_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/vdpau.h ================================================ /* * The Video Decode and Presentation API for UNIX (VDPAU) is used for * hardware-accelerated decoding of MPEG-1/2, H.264 and VC-1. * * Copyright (C) 2008 NVIDIA * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VDPAU_H #define AVCODEC_VDPAU_H /** * @file * @ingroup lavc_codec_hwaccel_vdpau * Public libavcodec VDPAU header. */ /** * @defgroup lavc_codec_hwaccel_vdpau VDPAU Decoder and Renderer * @ingroup lavc_codec_hwaccel * * VDPAU hardware acceleration has two modules * - VDPAU decoding * - VDPAU presentation * * The VDPAU decoding module parses all headers using FFmpeg * parsing mechanisms and uses VDPAU for the actual decoding. * * As per the current implementation, the actual decoding * and rendering (API calls) are done as part of the VDPAU * presentation (vo_vdpau.c) module. * * @{ */ #include #include "libavutil/avconfig.h" #include "libavutil/attributes.h" #include "avcodec.h" #include "version.h" struct AVCodecContext; struct AVFrame; typedef int (*AVVDPAU_Render2)(struct AVCodecContext *, struct AVFrame *, const VdpPictureInfo *, uint32_t, const VdpBitstreamBuffer *); /** * This structure is used to share data between the libavcodec library and * the client video application. * The user shall allocate the structure via the av_alloc_vdpau_hwaccel * function and make it available as * AVCodecContext.hwaccel_context. Members can be set by the user once * during initialization or through each AVCodecContext.get_buffer() * function call. In any case, they must be valid prior to calling * decoding functions. * * The size of this structure is not a part of the public ABI and must not * be used outside of libavcodec. Use av_vdpau_alloc_context() to allocate an * AVVDPAUContext. */ typedef struct AVVDPAUContext { /** * VDPAU decoder handle * * Set by user. */ VdpDecoder decoder; /** * VDPAU decoder render callback * * Set by the user. */ VdpDecoderRender *render; AVVDPAU_Render2 render2; } AVVDPAUContext; /** * @brief allocation function for AVVDPAUContext * * Allows extending the struct without breaking API/ABI */ AVVDPAUContext *av_alloc_vdpaucontext(void); AVVDPAU_Render2 av_vdpau_hwaccel_get_render2(const AVVDPAUContext *); void av_vdpau_hwaccel_set_render2(AVVDPAUContext *, AVVDPAU_Render2); /** * Associate a VDPAU device with a codec context for hardware acceleration. * This function is meant to be called from the get_format() codec callback, * or earlier. It can also be called after avcodec_flush_buffers() to change * the underlying VDPAU device mid-stream (e.g. to recover from non-transparent * display preemption). * * @note get_format() must return AV_PIX_FMT_VDPAU if this function completes * successfully. * * @param avctx decoding context whose get_format() callback is invoked * @param device VDPAU device handle to use for hardware acceleration * @param get_proc_address VDPAU device driver * @param flags zero of more OR'd AV_HWACCEL_FLAG_* flags * * @return 0 on success, an AVERROR code on failure. */ int av_vdpau_bind_context(AVCodecContext *avctx, VdpDevice device, VdpGetProcAddress *get_proc_address, unsigned flags); /** * Gets the parameters to create an adequate VDPAU video surface for the codec * context using VDPAU hardware decoding acceleration. * * @note Behavior is undefined if the context was not successfully bound to a * VDPAU device using av_vdpau_bind_context(). * * @param avctx the codec context being used for decoding the stream * @param type storage space for the VDPAU video surface chroma type * (or NULL to ignore) * @param width storage space for the VDPAU video surface pixel width * (or NULL to ignore) * @param height storage space for the VDPAU video surface pixel height * (or NULL to ignore) * * @return 0 on success, a negative AVERROR code on failure. */ int av_vdpau_get_surface_parameters(AVCodecContext *avctx, VdpChromaType *type, uint32_t *width, uint32_t *height); /** * Allocate an AVVDPAUContext. * * @return Newly-allocated AVVDPAUContext or NULL on failure. */ AVVDPAUContext *av_vdpau_alloc_context(void); #if FF_API_VDPAU_PROFILE /** * Get a decoder profile that should be used for initializing a VDPAU decoder. * Should be called from the AVCodecContext.get_format() callback. * * @deprecated Use av_vdpau_bind_context() instead. * * @param avctx the codec context being used for decoding the stream * @param profile a pointer into which the result will be written on success. * The contents of profile are undefined if this function returns * an error. * * @return 0 on success (non-negative), a negative AVERROR on failure. */ attribute_deprecated int av_vdpau_get_profile(AVCodecContext *avctx, VdpDecoderProfile *profile); #endif /* @}*/ #endif /* AVCODEC_VDPAU_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/version.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VERSION_H #define AVCODEC_VERSION_H /** * @file * @ingroup libavc * Libavcodec version macros. */ #include "libavutil/version.h" #define LIBAVCODEC_VERSION_MAJOR 58 #define LIBAVCODEC_VERSION_MINOR 54 #define LIBAVCODEC_VERSION_MICRO 100 #define LIBAVCODEC_VERSION_INT AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \ LIBAVCODEC_VERSION_MINOR, \ LIBAVCODEC_VERSION_MICRO) #define LIBAVCODEC_VERSION AV_VERSION(LIBAVCODEC_VERSION_MAJOR, \ LIBAVCODEC_VERSION_MINOR, \ LIBAVCODEC_VERSION_MICRO) #define LIBAVCODEC_BUILD LIBAVCODEC_VERSION_INT #define LIBAVCODEC_IDENT "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. * * @note, when bumping the major version it is recommended to manually * disable each FF_API_* in its own commit instead of disabling them all * at once through the bump. This improves the git bisect-ability of the change. */ #ifndef FF_API_LOWRES #define FF_API_LOWRES (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_DEBUG_MV #define FF_API_DEBUG_MV (LIBAVCODEC_VERSION_MAJOR < 58) #endif #ifndef FF_API_AVCTX_TIMEBASE #define FF_API_AVCTX_TIMEBASE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CODED_FRAME #define FF_API_CODED_FRAME (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_SIDEDATA_ONLY_PKT #define FF_API_SIDEDATA_ONLY_PKT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_VDPAU_PROFILE #define FF_API_VDPAU_PROFILE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CONVERGENCE_DURATION #define FF_API_CONVERGENCE_DURATION (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_AVPICTURE #define FF_API_AVPICTURE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_AVPACKET_OLD_API #define FF_API_AVPACKET_OLD_API (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_RTP_CALLBACK #define FF_API_RTP_CALLBACK (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_VBV_DELAY #define FF_API_VBV_DELAY (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CODER_TYPE #define FF_API_CODER_TYPE (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_STAT_BITS #define FF_API_STAT_BITS (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_PRIVATE_OPT #define FF_API_PRIVATE_OPT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_ASS_TIMING #define FF_API_ASS_TIMING (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_OLD_BSF #define FF_API_OLD_BSF (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_COPY_CONTEXT #define FF_API_COPY_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_GET_CONTEXT_DEFAULTS #define FF_API_GET_CONTEXT_DEFAULTS (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_NVENC_OLD_NAME #define FF_API_NVENC_OLD_NAME (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_STRUCT_VAAPI_CONTEXT #define FF_API_STRUCT_VAAPI_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_MERGE_SD_API #define FF_API_MERGE_SD_API (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_TAG_STRING #define FF_API_TAG_STRING (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_GETCHROMA #define FF_API_GETCHROMA (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_CODEC_GET_SET #define FF_API_CODEC_GET_SET (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_USER_VISIBLE_AVHWACCEL #define FF_API_USER_VISIBLE_AVHWACCEL (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_LOCKMGR #define FF_API_LOCKMGR (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_NEXT #define FF_API_NEXT (LIBAVCODEC_VERSION_MAJOR < 59) #endif #ifndef FF_API_UNSANITIZED_BITRATES #define FF_API_UNSANITIZED_BITRATES (LIBAVCODEC_VERSION_MAJOR < 59) #endif #endif /* AVCODEC_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/videotoolbox.h ================================================ /* * Videotoolbox hardware acceleration * * copyright (c) 2012 Sebastien Zwickert * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_VIDEOTOOLBOX_H #define AVCODEC_VIDEOTOOLBOX_H /** * @file * @ingroup lavc_codec_hwaccel_videotoolbox * Public libavcodec Videotoolbox header. */ #include #define Picture QuickdrawPicture #include #undef Picture #include "libavcodec/avcodec.h" /** * This struct holds all the information that needs to be passed * between the caller and libavcodec for initializing Videotoolbox decoding. * Its size is not a part of the public ABI, it must be allocated with * av_videotoolbox_alloc_context() and freed with av_free(). */ typedef struct AVVideotoolboxContext { /** * Videotoolbox decompression session object. * Created and freed the caller. */ VTDecompressionSessionRef session; /** * The output callback that must be passed to the session. * Set by av_videottoolbox_default_init() */ VTDecompressionOutputCallback output_callback; /** * CVPixelBuffer Format Type that Videotoolbox will use for decoded frames. * set by the caller. If this is set to 0, then no specific format is * requested from the decoder, and its native format is output. */ OSType cv_pix_fmt_type; /** * CoreMedia Format Description that Videotoolbox will use to create the decompression session. * Set by the caller. */ CMVideoFormatDescriptionRef cm_fmt_desc; /** * CoreMedia codec type that Videotoolbox will use to create the decompression session. * Set by the caller. */ int cm_codec_type; } AVVideotoolboxContext; /** * Allocate and initialize a Videotoolbox context. * * This function should be called from the get_format() callback when the caller * selects the AV_PIX_FMT_VIDETOOLBOX format. The caller must then create * the decoder object (using the output callback provided by libavcodec) that * will be used for Videotoolbox-accelerated decoding. * * When decoding with Videotoolbox is finished, the caller must destroy the decoder * object and free the Videotoolbox context using av_free(). * * @return the newly allocated context or NULL on failure */ AVVideotoolboxContext *av_videotoolbox_alloc_context(void); /** * This is a convenience function that creates and sets up the Videotoolbox context using * an internal implementation. * * @param avctx the corresponding codec context * * @return >= 0 on success, a negative AVERROR code on failure */ int av_videotoolbox_default_init(AVCodecContext *avctx); /** * This is a convenience function that creates and sets up the Videotoolbox context using * an internal implementation. * * @param avctx the corresponding codec context * @param vtctx the Videotoolbox context to use * * @return >= 0 on success, a negative AVERROR code on failure */ int av_videotoolbox_default_init2(AVCodecContext *avctx, AVVideotoolboxContext *vtctx); /** * This function must be called to free the Videotoolbox context initialized with * av_videotoolbox_default_init(). * * @param avctx the corresponding codec context */ void av_videotoolbox_default_free(AVCodecContext *avctx); /** * @} */ #endif /* AVCODEC_VIDEOTOOLBOX_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/vorbis_parser.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * A public API for Vorbis parsing * * Determines the duration for each packet. */ #ifndef AVCODEC_VORBIS_PARSER_H #define AVCODEC_VORBIS_PARSER_H #include typedef struct AVVorbisParseContext AVVorbisParseContext; /** * Allocate and initialize the Vorbis parser using headers in the extradata. */ AVVorbisParseContext *av_vorbis_parse_init(const uint8_t *extradata, int extradata_size); /** * Free the parser and everything associated with it. */ void av_vorbis_parse_free(AVVorbisParseContext **s); #define VORBIS_FLAG_HEADER 0x00000001 #define VORBIS_FLAG_COMMENT 0x00000002 #define VORBIS_FLAG_SETUP 0x00000004 /** * Get the duration for a Vorbis packet. * * If @p flags is @c NULL, * special frames are considered invalid. * * @param s Vorbis parser context * @param buf buffer containing a Vorbis frame * @param buf_size size of the buffer * @param flags flags for special frames */ int av_vorbis_parse_frame_flags(AVVorbisParseContext *s, const uint8_t *buf, int buf_size, int *flags); /** * Get the duration for a Vorbis packet. * * @param s Vorbis parser context * @param buf buffer containing a Vorbis frame * @param buf_size size of the buffer */ int av_vorbis_parse_frame(AVVorbisParseContext *s, const uint8_t *buf, int buf_size); void av_vorbis_parse_reset(AVVorbisParseContext *s); #endif /* AVCODEC_VORBIS_PARSER_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavcodec/xvmc.h ================================================ /* * Copyright (C) 2003 Ivan Kalvachev * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVCODEC_XVMC_H #define AVCODEC_XVMC_H /** * @file * @ingroup lavc_codec_hwaccel_xvmc * Public libavcodec XvMC header. */ #include #include "libavutil/attributes.h" #include "version.h" #include "avcodec.h" /** * @defgroup lavc_codec_hwaccel_xvmc XvMC * @ingroup lavc_codec_hwaccel * * @{ */ #define AV_XVMC_ID 0x1DC711C0 /**< special value to ensure that regular pixel routines haven't corrupted the struct the number is 1337 speak for the letters IDCT MCo (motion compensation) */ struct attribute_deprecated xvmc_pix_fmt { /** The field contains the special constant value AV_XVMC_ID. It is used as a test that the application correctly uses the API, and that there is no corruption caused by pixel routines. - application - set during initialization - libavcodec - unchanged */ int xvmc_id; /** Pointer to the block array allocated by XvMCCreateBlocks(). The array has to be freed by XvMCDestroyBlocks(). Each group of 64 values represents one data block of differential pixel information (in MoCo mode) or coefficients for IDCT. - application - set the pointer during initialization - libavcodec - fills coefficients/pixel data into the array */ short* data_blocks; /** Pointer to the macroblock description array allocated by XvMCCreateMacroBlocks() and freed by XvMCDestroyMacroBlocks(). - application - set the pointer during initialization - libavcodec - fills description data into the array */ XvMCMacroBlock* mv_blocks; /** Number of macroblock descriptions that can be stored in the mv_blocks array. - application - set during initialization - libavcodec - unchanged */ int allocated_mv_blocks; /** Number of blocks that can be stored at once in the data_blocks array. - application - set during initialization - libavcodec - unchanged */ int allocated_data_blocks; /** Indicate that the hardware would interpret data_blocks as IDCT coefficients and perform IDCT on them. - application - set during initialization - libavcodec - unchanged */ int idct; /** In MoCo mode it indicates that intra macroblocks are assumed to be in unsigned format; same as the XVMC_INTRA_UNSIGNED flag. - application - set during initialization - libavcodec - unchanged */ int unsigned_intra; /** Pointer to the surface allocated by XvMCCreateSurface(). It has to be freed by XvMCDestroySurface() on application exit. It identifies the frame and its state on the video hardware. - application - set during initialization - libavcodec - unchanged */ XvMCSurface* p_surface; /** Set by the decoder before calling ff_draw_horiz_band(), needed by the XvMCRenderSurface function. */ //@{ /** Pointer to the surface used as past reference - application - unchanged - libavcodec - set */ XvMCSurface* p_past_surface; /** Pointer to the surface used as future reference - application - unchanged - libavcodec - set */ XvMCSurface* p_future_surface; /** top/bottom field or frame - application - unchanged - libavcodec - set */ unsigned int picture_structure; /** XVMC_SECOND_FIELD - 1st or 2nd field in the sequence - application - unchanged - libavcodec - set */ unsigned int flags; //}@ /** Number of macroblock descriptions in the mv_blocks array that have already been passed to the hardware. - application - zeroes it on get_buffer(). A successful ff_draw_horiz_band() may increment it with filled_mb_block_num or zero both. - libavcodec - unchanged */ int start_mv_blocks_num; /** Number of new macroblock descriptions in the mv_blocks array (after start_mv_blocks_num) that are filled by libavcodec and have to be passed to the hardware. - application - zeroes it on get_buffer() or after successful ff_draw_horiz_band(). - libavcodec - increment with one of each stored MB */ int filled_mv_blocks_num; /** Number of the next free data block; one data block consists of 64 short values in the data_blocks array. All blocks before this one have already been claimed by placing their position into the corresponding block description structure field, that are part of the mv_blocks array. - application - zeroes it on get_buffer(). A successful ff_draw_horiz_band() may zero it together with start_mb_blocks_num. - libavcodec - each decoded macroblock increases it by the number of coded blocks it contains. */ int next_free_data_block_num; }; /** * @} */ #endif /* AVCODEC_XVMC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavdevice/avdevice.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVDEVICE_AVDEVICE_H #define AVDEVICE_AVDEVICE_H #include "version.h" /** * @file * @ingroup lavd * Main libavdevice API header */ /** * @defgroup lavd libavdevice * Special devices muxing/demuxing library. * * Libavdevice is a complementary library to @ref libavf "libavformat". It * provides various "special" platform-specific muxers and demuxers, e.g. for * grabbing devices, audio capture and playback etc. As a consequence, the * (de)muxers in libavdevice are of the AVFMT_NOFILE type (they use their own * I/O functions). The filename passed to avformat_open_input() often does not * refer to an actually existing file, but has some special device-specific * meaning - e.g. for xcbgrab it is the display name. * * To use libavdevice, simply call avdevice_register_all() to register all * compiled muxers and demuxers. They all use standard libavformat API. * * @{ */ #include "libavutil/log.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavformat/avformat.h" /** * Return the LIBAVDEVICE_VERSION_INT constant. */ unsigned avdevice_version(void); /** * Return the libavdevice build-time configuration. */ const char *avdevice_configuration(void); /** * Return the libavdevice license. */ const char *avdevice_license(void); /** * Initialize libavdevice and register all the input and output devices. */ void avdevice_register_all(void); /** * Audio input devices iterator. * * If d is NULL, returns the first registered input audio/video device, * if d is non-NULL, returns the next registered input audio/video device after d * or NULL if d is the last one. */ AVInputFormat *av_input_audio_device_next(AVInputFormat *d); /** * Video input devices iterator. * * If d is NULL, returns the first registered input audio/video device, * if d is non-NULL, returns the next registered input audio/video device after d * or NULL if d is the last one. */ AVInputFormat *av_input_video_device_next(AVInputFormat *d); /** * Audio output devices iterator. * * If d is NULL, returns the first registered output audio/video device, * if d is non-NULL, returns the next registered output audio/video device after d * or NULL if d is the last one. */ AVOutputFormat *av_output_audio_device_next(AVOutputFormat *d); /** * Video output devices iterator. * * If d is NULL, returns the first registered output audio/video device, * if d is non-NULL, returns the next registered output audio/video device after d * or NULL if d is the last one. */ AVOutputFormat *av_output_video_device_next(AVOutputFormat *d); typedef struct AVDeviceRect { int x; /**< x coordinate of top left corner */ int y; /**< y coordinate of top left corner */ int width; /**< width */ int height; /**< height */ } AVDeviceRect; /** * Message types used by avdevice_app_to_dev_control_message(). */ enum AVAppToDevMessageType { /** * Dummy message. */ AV_APP_TO_DEV_NONE = MKBETAG('N','O','N','E'), /** * Window size change message. * * Message is sent to the device every time the application changes the size * of the window device renders to. * Message should also be sent right after window is created. * * data: AVDeviceRect: new window size. */ AV_APP_TO_DEV_WINDOW_SIZE = MKBETAG('G','E','O','M'), /** * Repaint request message. * * Message is sent to the device when window has to be repainted. * * data: AVDeviceRect: area required to be repainted. * NULL: whole area is required to be repainted. */ AV_APP_TO_DEV_WINDOW_REPAINT = MKBETAG('R','E','P','A'), /** * Request pause/play. * * Application requests pause/unpause playback. * Mostly usable with devices that have internal buffer. * By default devices are not paused. * * data: NULL */ AV_APP_TO_DEV_PAUSE = MKBETAG('P', 'A', 'U', ' '), AV_APP_TO_DEV_PLAY = MKBETAG('P', 'L', 'A', 'Y'), AV_APP_TO_DEV_TOGGLE_PAUSE = MKBETAG('P', 'A', 'U', 'T'), /** * Volume control message. * * Set volume level. It may be device-dependent if volume * is changed per stream or system wide. Per stream volume * change is expected when possible. * * data: double: new volume with range of 0.0 - 1.0. */ AV_APP_TO_DEV_SET_VOLUME = MKBETAG('S', 'V', 'O', 'L'), /** * Mute control messages. * * Change mute state. It may be device-dependent if mute status * is changed per stream or system wide. Per stream mute status * change is expected when possible. * * data: NULL. */ AV_APP_TO_DEV_MUTE = MKBETAG(' ', 'M', 'U', 'T'), AV_APP_TO_DEV_UNMUTE = MKBETAG('U', 'M', 'U', 'T'), AV_APP_TO_DEV_TOGGLE_MUTE = MKBETAG('T', 'M', 'U', 'T'), /** * Get volume/mute messages. * * Force the device to send AV_DEV_TO_APP_VOLUME_LEVEL_CHANGED or * AV_DEV_TO_APP_MUTE_STATE_CHANGED command respectively. * * data: NULL. */ AV_APP_TO_DEV_GET_VOLUME = MKBETAG('G', 'V', 'O', 'L'), AV_APP_TO_DEV_GET_MUTE = MKBETAG('G', 'M', 'U', 'T'), }; /** * Message types used by avdevice_dev_to_app_control_message(). */ enum AVDevToAppMessageType { /** * Dummy message. */ AV_DEV_TO_APP_NONE = MKBETAG('N','O','N','E'), /** * Create window buffer message. * * Device requests to create a window buffer. Exact meaning is device- * and application-dependent. Message is sent before rendering first * frame and all one-shot initializations should be done here. * Application is allowed to ignore preferred window buffer size. * * @note: Application is obligated to inform about window buffer size * with AV_APP_TO_DEV_WINDOW_SIZE message. * * data: AVDeviceRect: preferred size of the window buffer. * NULL: no preferred size of the window buffer. */ AV_DEV_TO_APP_CREATE_WINDOW_BUFFER = MKBETAG('B','C','R','E'), /** * Prepare window buffer message. * * Device requests to prepare a window buffer for rendering. * Exact meaning is device- and application-dependent. * Message is sent before rendering of each frame. * * data: NULL. */ AV_DEV_TO_APP_PREPARE_WINDOW_BUFFER = MKBETAG('B','P','R','E'), /** * Display window buffer message. * * Device requests to display a window buffer. * Message is sent when new frame is ready to be displayed. * Usually buffers need to be swapped in handler of this message. * * data: NULL. */ AV_DEV_TO_APP_DISPLAY_WINDOW_BUFFER = MKBETAG('B','D','I','S'), /** * Destroy window buffer message. * * Device requests to destroy a window buffer. * Message is sent when device is about to be destroyed and window * buffer is not required anymore. * * data: NULL. */ AV_DEV_TO_APP_DESTROY_WINDOW_BUFFER = MKBETAG('B','D','E','S'), /** * Buffer fullness status messages. * * Device signals buffer overflow/underflow. * * data: NULL. */ AV_DEV_TO_APP_BUFFER_OVERFLOW = MKBETAG('B','O','F','L'), AV_DEV_TO_APP_BUFFER_UNDERFLOW = MKBETAG('B','U','F','L'), /** * Buffer readable/writable. * * Device informs that buffer is readable/writable. * When possible, device informs how many bytes can be read/write. * * @warning Device may not inform when number of bytes than can be read/write changes. * * data: int64_t: amount of bytes available to read/write. * NULL: amount of bytes available to read/write is not known. */ AV_DEV_TO_APP_BUFFER_READABLE = MKBETAG('B','R','D',' '), AV_DEV_TO_APP_BUFFER_WRITABLE = MKBETAG('B','W','R',' '), /** * Mute state change message. * * Device informs that mute state has changed. * * data: int: 0 for not muted state, non-zero for muted state. */ AV_DEV_TO_APP_MUTE_STATE_CHANGED = MKBETAG('C','M','U','T'), /** * Volume level change message. * * Device informs that volume level has changed. * * data: double: new volume with range of 0.0 - 1.0. */ AV_DEV_TO_APP_VOLUME_LEVEL_CHANGED = MKBETAG('C','V','O','L'), }; /** * Send control message from application to device. * * @param s device context. * @param type message type. * @param data message data. Exact type depends on message type. * @param data_size size of message data. * @return >= 0 on success, negative on error. * AVERROR(ENOSYS) when device doesn't implement handler of the message. */ int avdevice_app_to_dev_control_message(struct AVFormatContext *s, enum AVAppToDevMessageType type, void *data, size_t data_size); /** * Send control message from device to application. * * @param s device context. * @param type message type. * @param data message data. Can be NULL. * @param data_size size of message data. * @return >= 0 on success, negative on error. * AVERROR(ENOSYS) when application doesn't implement handler of the message. */ int avdevice_dev_to_app_control_message(struct AVFormatContext *s, enum AVDevToAppMessageType type, void *data, size_t data_size); /** * Following API allows user to probe device capabilities (supported codecs, * pixel formats, sample formats, resolutions, channel counts, etc). * It is build on top op AVOption API. * Queried capabilities make it possible to set up converters of video or audio * parameters that fit to the device. * * List of capabilities that can be queried: * - Capabilities valid for both audio and video devices: * - codec: supported audio/video codecs. * type: AV_OPT_TYPE_INT (AVCodecID value) * - Capabilities valid for audio devices: * - sample_format: supported sample formats. * type: AV_OPT_TYPE_INT (AVSampleFormat value) * - sample_rate: supported sample rates. * type: AV_OPT_TYPE_INT * - channels: supported number of channels. * type: AV_OPT_TYPE_INT * - channel_layout: supported channel layouts. * type: AV_OPT_TYPE_INT64 * - Capabilities valid for video devices: * - pixel_format: supported pixel formats. * type: AV_OPT_TYPE_INT (AVPixelFormat value) * - window_size: supported window sizes (describes size of the window size presented to the user). * type: AV_OPT_TYPE_IMAGE_SIZE * - frame_size: supported frame sizes (describes size of provided video frames). * type: AV_OPT_TYPE_IMAGE_SIZE * - fps: supported fps values * type: AV_OPT_TYPE_RATIONAL * * Value of the capability may be set by user using av_opt_set() function * and AVDeviceCapabilitiesQuery object. Following queries will * limit results to the values matching already set capabilities. * For example, setting a codec may impact number of formats or fps values * returned during next query. Setting invalid value may limit results to zero. * * Example of the usage basing on opengl output device: * * @code * AVFormatContext *oc = NULL; * AVDeviceCapabilitiesQuery *caps = NULL; * AVOptionRanges *ranges; * int ret; * * if ((ret = avformat_alloc_output_context2(&oc, NULL, "opengl", NULL)) < 0) * goto fail; * if (avdevice_capabilities_create(&caps, oc, NULL) < 0) * goto fail; * * //query codecs * if (av_opt_query_ranges(&ranges, caps, "codec", AV_OPT_MULTI_COMPONENT_RANGE)) < 0) * goto fail; * //pick codec here and set it * av_opt_set(caps, "codec", AV_CODEC_ID_RAWVIDEO, 0); * * //query format * if (av_opt_query_ranges(&ranges, caps, "pixel_format", AV_OPT_MULTI_COMPONENT_RANGE)) < 0) * goto fail; * //pick format here and set it * av_opt_set(caps, "pixel_format", AV_PIX_FMT_YUV420P, 0); * * //query and set more capabilities * * fail: * //clean up code * avdevice_capabilities_free(&query, oc); * avformat_free_context(oc); * @endcode */ /** * Structure describes device capabilities. * * It is used by devices in conjunction with av_device_capabilities AVOption table * to implement capabilities probing API based on AVOption API. Should not be used directly. */ typedef struct AVDeviceCapabilitiesQuery { const AVClass *av_class; AVFormatContext *device_context; enum AVCodecID codec; enum AVSampleFormat sample_format; enum AVPixelFormat pixel_format; int sample_rate; int channels; int64_t channel_layout; int window_width; int window_height; int frame_width; int frame_height; AVRational fps; } AVDeviceCapabilitiesQuery; /** * AVOption table used by devices to implement device capabilities API. Should not be used by a user. */ extern const AVOption av_device_capabilities[]; /** * Initialize capabilities probing API based on AVOption API. * * avdevice_capabilities_free() must be called when query capabilities API is * not used anymore. * * @param[out] caps Device capabilities data. Pointer to a NULL pointer must be passed. * @param s Context of the device. * @param device_options An AVDictionary filled with device-private options. * On return this parameter will be destroyed and replaced with a dict * containing options that were not found. May be NULL. * The same options must be passed later to avformat_write_header() for output * devices or avformat_open_input() for input devices, or at any other place * that affects device-private options. * * @return >= 0 on success, negative otherwise. */ int avdevice_capabilities_create(AVDeviceCapabilitiesQuery **caps, AVFormatContext *s, AVDictionary **device_options); /** * Free resources created by avdevice_capabilities_create() * * @param caps Device capabilities data to be freed. * @param s Context of the device. */ void avdevice_capabilities_free(AVDeviceCapabilitiesQuery **caps, AVFormatContext *s); /** * Structure describes basic parameters of the device. */ typedef struct AVDeviceInfo { char *device_name; /**< device name, format depends on device */ char *device_description; /**< human friendly name */ } AVDeviceInfo; /** * List of devices. */ typedef struct AVDeviceInfoList { AVDeviceInfo **devices; /**< list of autodetected devices */ int nb_devices; /**< number of autodetected devices */ int default_device; /**< index of default device or -1 if no default */ } AVDeviceInfoList; /** * List devices. * * Returns available device names and their parameters. * * @note: Some devices may accept system-dependent device names that cannot be * autodetected. The list returned by this function cannot be assumed to * be always completed. * * @param s device context. * @param[out] device_list list of autodetected devices. * @return count of autodetected devices, negative on error. */ int avdevice_list_devices(struct AVFormatContext *s, AVDeviceInfoList **device_list); /** * Convenient function to free result of avdevice_list_devices(). * * @param devices device list to be freed. */ void avdevice_free_list_devices(AVDeviceInfoList **device_list); /** * List devices. * * Returns available device names and their parameters. * These are convinient wrappers for avdevice_list_devices(). * Device context is allocated and deallocated internally. * * @param device device format. May be NULL if device name is set. * @param device_name device name. May be NULL if device format is set. * @param device_options An AVDictionary filled with device-private options. May be NULL. * The same options must be passed later to avformat_write_header() for output * devices or avformat_open_input() for input devices, or at any other place * that affects device-private options. * @param[out] device_list list of autodetected devices * @return count of autodetected devices, negative on error. * @note device argument takes precedence over device_name when both are set. */ int avdevice_list_input_sources(struct AVInputFormat *device, const char *device_name, AVDictionary *device_options, AVDeviceInfoList **device_list); int avdevice_list_output_sinks(struct AVOutputFormat *device, const char *device_name, AVDictionary *device_options, AVDeviceInfoList **device_list); /** * @} */ #endif /* AVDEVICE_AVDEVICE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavdevice/version.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVDEVICE_VERSION_H #define AVDEVICE_VERSION_H /** * @file * @ingroup lavd * Libavdevice version macros */ #include "libavutil/version.h" #define LIBAVDEVICE_VERSION_MAJOR 58 #define LIBAVDEVICE_VERSION_MINOR 8 #define LIBAVDEVICE_VERSION_MICRO 100 #define LIBAVDEVICE_VERSION_INT AV_VERSION_INT(LIBAVDEVICE_VERSION_MAJOR, \ LIBAVDEVICE_VERSION_MINOR, \ LIBAVDEVICE_VERSION_MICRO) #define LIBAVDEVICE_VERSION AV_VERSION(LIBAVDEVICE_VERSION_MAJOR, \ LIBAVDEVICE_VERSION_MINOR, \ LIBAVDEVICE_VERSION_MICRO) #define LIBAVDEVICE_BUILD LIBAVDEVICE_VERSION_INT #define LIBAVDEVICE_IDENT "Lavd" AV_STRINGIFY(LIBAVDEVICE_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #endif /* AVDEVICE_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavfilter/avfilter.h ================================================ /* * filter layer * Copyright (c) 2007 Bobby Bingham * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_AVFILTER_H #define AVFILTER_AVFILTER_H /** * @file * @ingroup lavfi * Main libavfilter public API header */ /** * @defgroup lavfi libavfilter * Graph-based frame editing library. * * @{ */ #include #include "libavutil/attributes.h" #include "libavutil/avutil.h" #include "libavutil/buffer.h" #include "libavutil/dict.h" #include "libavutil/frame.h" #include "libavutil/log.h" #include "libavutil/samplefmt.h" #include "libavutil/pixfmt.h" #include "libavutil/rational.h" #include "libavfilter/version.h" /** * Return the LIBAVFILTER_VERSION_INT constant. */ unsigned avfilter_version(void); /** * Return the libavfilter build-time configuration. */ const char *avfilter_configuration(void); /** * Return the libavfilter license. */ const char *avfilter_license(void); typedef struct AVFilterContext AVFilterContext; typedef struct AVFilterLink AVFilterLink; typedef struct AVFilterPad AVFilterPad; typedef struct AVFilterFormats AVFilterFormats; /** * Get the number of elements in a NULL-terminated array of AVFilterPads (e.g. * AVFilter.inputs/outputs). */ int avfilter_pad_count(const AVFilterPad *pads); /** * Get the name of an AVFilterPad. * * @param pads an array of AVFilterPads * @param pad_idx index of the pad in the array it; is the caller's * responsibility to ensure the index is valid * * @return name of the pad_idx'th pad in pads */ const char *avfilter_pad_get_name(const AVFilterPad *pads, int pad_idx); /** * Get the type of an AVFilterPad. * * @param pads an array of AVFilterPads * @param pad_idx index of the pad in the array; it is the caller's * responsibility to ensure the index is valid * * @return type of the pad_idx'th pad in pads */ enum AVMediaType avfilter_pad_get_type(const AVFilterPad *pads, int pad_idx); /** * The number of the filter inputs is not determined just by AVFilter.inputs. * The filter might add additional inputs during initialization depending on the * options supplied to it. */ #define AVFILTER_FLAG_DYNAMIC_INPUTS (1 << 0) /** * The number of the filter outputs is not determined just by AVFilter.outputs. * The filter might add additional outputs during initialization depending on * the options supplied to it. */ #define AVFILTER_FLAG_DYNAMIC_OUTPUTS (1 << 1) /** * The filter supports multithreading by splitting frames into multiple parts * and processing them concurrently. */ #define AVFILTER_FLAG_SLICE_THREADS (1 << 2) /** * Some filters support a generic "enable" expression option that can be used * to enable or disable a filter in the timeline. Filters supporting this * option have this flag set. When the enable expression is false, the default * no-op filter_frame() function is called in place of the filter_frame() * callback defined on each input pad, thus the frame is passed unchanged to * the next filters. */ #define AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC (1 << 16) /** * Same as AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC, except that the filter will * have its filter_frame() callback(s) called as usual even when the enable * expression is false. The filter will disable filtering within the * filter_frame() callback(s) itself, for example executing code depending on * the AVFilterContext->is_disabled value. */ #define AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL (1 << 17) /** * Handy mask to test whether the filter supports or no the timeline feature * (internally or generically). */ #define AVFILTER_FLAG_SUPPORT_TIMELINE (AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL) /** * Filter definition. This defines the pads a filter contains, and all the * callback functions used to interact with the filter. */ typedef struct AVFilter { /** * Filter name. Must be non-NULL and unique among filters. */ const char *name; /** * A description of the filter. May be NULL. * * You should use the NULL_IF_CONFIG_SMALL() macro to define it. */ const char *description; /** * List of inputs, terminated by a zeroed element. * * NULL if there are no (static) inputs. Instances of filters with * AVFILTER_FLAG_DYNAMIC_INPUTS set may have more inputs than present in * this list. */ const AVFilterPad *inputs; /** * List of outputs, terminated by a zeroed element. * * NULL if there are no (static) outputs. Instances of filters with * AVFILTER_FLAG_DYNAMIC_OUTPUTS set may have more outputs than present in * this list. */ const AVFilterPad *outputs; /** * A class for the private data, used to declare filter private AVOptions. * This field is NULL for filters that do not declare any options. * * If this field is non-NULL, the first member of the filter private data * must be a pointer to AVClass, which will be set by libavfilter generic * code to this class. */ const AVClass *priv_class; /** * A combination of AVFILTER_FLAG_* */ int flags; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavfilter and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * Filter pre-initialization function * * This callback will be called immediately after the filter context is * allocated, to allow allocating and initing sub-objects. * * If this callback is not NULL, the uninit callback will be called on * allocation failure. * * @return 0 on success, * AVERROR code on failure (but the code will be * dropped and treated as ENOMEM by the calling code) */ int (*preinit)(AVFilterContext *ctx); /** * Filter initialization function. * * This callback will be called only once during the filter lifetime, after * all the options have been set, but before links between filters are * established and format negotiation is done. * * Basic filter initialization should be done here. Filters with dynamic * inputs and/or outputs should create those inputs/outputs here based on * provided options. No more changes to this filter's inputs/outputs can be * done after this callback. * * This callback must not assume that the filter links exist or frame * parameters are known. * * @ref AVFilter.uninit "uninit" is guaranteed to be called even if * initialization fails, so this callback does not have to clean up on * failure. * * @return 0 on success, a negative AVERROR on failure */ int (*init)(AVFilterContext *ctx); /** * Should be set instead of @ref AVFilter.init "init" by the filters that * want to pass a dictionary of AVOptions to nested contexts that are * allocated during init. * * On return, the options dict should be freed and replaced with one that * contains all the options which could not be processed by this filter (or * with NULL if all the options were processed). * * Otherwise the semantics is the same as for @ref AVFilter.init "init". */ int (*init_dict)(AVFilterContext *ctx, AVDictionary **options); /** * Filter uninitialization function. * * Called only once right before the filter is freed. Should deallocate any * memory held by the filter, release any buffer references, etc. It does * not need to deallocate the AVFilterContext.priv memory itself. * * This callback may be called even if @ref AVFilter.init "init" was not * called or failed, so it must be prepared to handle such a situation. */ void (*uninit)(AVFilterContext *ctx); /** * Query formats supported by the filter on its inputs and outputs. * * This callback is called after the filter is initialized (so the inputs * and outputs are fixed), shortly before the format negotiation. This * callback may be called more than once. * * This callback must set AVFilterLink.out_formats on every input link and * AVFilterLink.in_formats on every output link to a list of pixel/sample * formats that the filter supports on that link. For audio links, this * filter must also set @ref AVFilterLink.in_samplerates "in_samplerates" / * @ref AVFilterLink.out_samplerates "out_samplerates" and * @ref AVFilterLink.in_channel_layouts "in_channel_layouts" / * @ref AVFilterLink.out_channel_layouts "out_channel_layouts" analogously. * * This callback may be NULL for filters with one input, in which case * libavfilter assumes that it supports all input formats and preserves * them on output. * * @return zero on success, a negative value corresponding to an * AVERROR code otherwise */ int (*query_formats)(AVFilterContext *); int priv_size; ///< size of private data to allocate for the filter int flags_internal; ///< Additional flags for avfilter internal use only. /** * Used by the filter registration system. Must not be touched by any other * code. */ struct AVFilter *next; /** * Make the filter instance process a command. * * @param cmd the command to process, for handling simplicity all commands must be alphanumeric only * @param arg the argument for the command * @param res a buffer with size res_size where the filter(s) can return a response. This must not change when the command is not supported. * @param flags if AVFILTER_CMD_FLAG_FAST is set and the command would be * time consuming then a filter should treat it like an unsupported command * * @returns >=0 on success otherwise an error code. * AVERROR(ENOSYS) on unsupported commands */ int (*process_command)(AVFilterContext *, const char *cmd, const char *arg, char *res, int res_len, int flags); /** * Filter initialization function, alternative to the init() * callback. Args contains the user-supplied parameters, opaque is * used for providing binary data. */ int (*init_opaque)(AVFilterContext *ctx, void *opaque); /** * Filter activation function. * * Called when any processing is needed from the filter, instead of any * filter_frame and request_frame on pads. * * The function must examine inlinks and outlinks and perform a single * step of processing. If there is nothing to do, the function must do * nothing and not return an error. If more steps are or may be * possible, it must use ff_filter_set_ready() to schedule another * activation. */ int (*activate)(AVFilterContext *ctx); } AVFilter; /** * Process multiple parts of the frame concurrently. */ #define AVFILTER_THREAD_SLICE (1 << 0) typedef struct AVFilterInternal AVFilterInternal; /** An instance of a filter */ struct AVFilterContext { const AVClass *av_class; ///< needed for av_log() and filters common options const AVFilter *filter; ///< the AVFilter of which this is an instance char *name; ///< name of this filter instance AVFilterPad *input_pads; ///< array of input pads AVFilterLink **inputs; ///< array of pointers to input links unsigned nb_inputs; ///< number of input pads AVFilterPad *output_pads; ///< array of output pads AVFilterLink **outputs; ///< array of pointers to output links unsigned nb_outputs; ///< number of output pads void *priv; ///< private data for use by the filter struct AVFilterGraph *graph; ///< filtergraph this filter belongs to /** * Type of multithreading being allowed/used. A combination of * AVFILTER_THREAD_* flags. * * May be set by the caller before initializing the filter to forbid some * or all kinds of multithreading for this filter. The default is allowing * everything. * * When the filter is initialized, this field is combined using bit AND with * AVFilterGraph.thread_type to get the final mask used for determining * allowed threading types. I.e. a threading type needs to be set in both * to be allowed. * * After the filter is initialized, libavfilter sets this field to the * threading type that is actually used (0 for no multithreading). */ int thread_type; /** * An opaque struct for libavfilter internal use. */ AVFilterInternal *internal; struct AVFilterCommand *command_queue; char *enable_str; ///< enable expression string void *enable; ///< parsed expression (AVExpr*) double *var_values; ///< variable values for the enable expression int is_disabled; ///< the enabled state from the last expression evaluation /** * For filters which will create hardware frames, sets the device the * filter should create them in. All other filters will ignore this field: * in particular, a filter which consumes or processes hardware frames will * instead use the hw_frames_ctx field in AVFilterLink to carry the * hardware context information. */ AVBufferRef *hw_device_ctx; /** * Max number of threads allowed in this filter instance. * If <= 0, its value is ignored. * Overrides global number of threads set per filter graph. */ int nb_threads; /** * Ready status of the filter. * A non-0 value means that the filter needs activating; * a higher value suggests a more urgent activation. */ unsigned ready; /** * Sets the number of extra hardware frames which the filter will * allocate on its output links for use in following filters or by * the caller. * * Some hardware filters require all frames that they will use for * output to be defined in advance before filtering starts. For such * filters, any hardware frame pools used for output must therefore be * of fixed size. The extra frames set here are on top of any number * that the filter needs internally in order to operate normally. * * This field must be set before the graph containing this filter is * configured. */ int extra_hw_frames; }; /** * A link between two filters. This contains pointers to the source and * destination filters between which this link exists, and the indexes of * the pads involved. In addition, this link also contains the parameters * which have been negotiated and agreed upon between the filter, such as * image dimensions, format, etc. * * Applications must not normally access the link structure directly. * Use the buffersrc and buffersink API instead. * In the future, access to the header may be reserved for filters * implementation. */ struct AVFilterLink { AVFilterContext *src; ///< source filter AVFilterPad *srcpad; ///< output pad on the source filter AVFilterContext *dst; ///< dest filter AVFilterPad *dstpad; ///< input pad on the dest filter enum AVMediaType type; ///< filter media type /* These parameters apply only to video */ int w; ///< agreed upon image width int h; ///< agreed upon image height AVRational sample_aspect_ratio; ///< agreed upon sample aspect ratio /* These parameters apply only to audio */ uint64_t channel_layout; ///< channel layout of current buffer (see libavutil/channel_layout.h) int sample_rate; ///< samples per second int format; ///< agreed upon media format /** * Define the time base used by the PTS of the frames/samples * which will pass through this link. * During the configuration stage, each filter is supposed to * change only the output timebase, while the timebase of the * input link is assumed to be an unchangeable property. */ AVRational time_base; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavfilter and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * Lists of formats and channel layouts supported by the input and output * filters respectively. These lists are used for negotiating the format * to actually be used, which will be loaded into the format and * channel_layout members, above, when chosen. * */ AVFilterFormats *in_formats; AVFilterFormats *out_formats; /** * Lists of channel layouts and sample rates used for automatic * negotiation. */ AVFilterFormats *in_samplerates; AVFilterFormats *out_samplerates; struct AVFilterChannelLayouts *in_channel_layouts; struct AVFilterChannelLayouts *out_channel_layouts; /** * Audio only, the destination filter sets this to a non-zero value to * request that buffers with the given number of samples should be sent to * it. AVFilterPad.needs_fifo must also be set on the corresponding input * pad. * Last buffer before EOF will be padded with silence. */ int request_samples; /** stage of the initialization of the link properties (dimensions, etc) */ enum { AVLINK_UNINIT = 0, ///< not started AVLINK_STARTINIT, ///< started, but incomplete AVLINK_INIT ///< complete } init_state; /** * Graph the filter belongs to. */ struct AVFilterGraph *graph; /** * Current timestamp of the link, as defined by the most recent * frame(s), in link time_base units. */ int64_t current_pts; /** * Current timestamp of the link, as defined by the most recent * frame(s), in AV_TIME_BASE units. */ int64_t current_pts_us; /** * Index in the age array. */ int age_index; /** * Frame rate of the stream on the link, or 1/0 if unknown or variable; * if left to 0/0, will be automatically copied from the first input * of the source filter if it exists. * * Sources should set it to the best estimation of the real frame rate. * If the source frame rate is unknown or variable, set this to 1/0. * Filters should update it if necessary depending on their function. * Sinks can use it to set a default output frame rate. * It is similar to the r_frame_rate field in AVStream. */ AVRational frame_rate; /** * Buffer partially filled with samples to achieve a fixed/minimum size. */ AVFrame *partial_buf; /** * Size of the partial buffer to allocate. * Must be between min_samples and max_samples. */ int partial_buf_size; /** * Minimum number of samples to filter at once. If filter_frame() is * called with fewer samples, it will accumulate them in partial_buf. * This field and the related ones must not be changed after filtering * has started. * If 0, all related fields are ignored. */ int min_samples; /** * Maximum number of samples to filter at once. If filter_frame() is * called with more samples, it will split them. */ int max_samples; /** * Number of channels. */ int channels; /** * Link processing flags. */ unsigned flags; /** * Number of past frames sent through the link. */ int64_t frame_count_in, frame_count_out; /** * A pointer to a FFFramePool struct. */ void *frame_pool; /** * True if a frame is currently wanted on the output of this filter. * Set when ff_request_frame() is called by the output, * cleared when a frame is filtered. */ int frame_wanted_out; /** * For hwaccel pixel formats, this should be a reference to the * AVHWFramesContext describing the frames. */ AVBufferRef *hw_frames_ctx; #ifndef FF_INTERNAL_FIELDS /** * Internal structure members. * The fields below this limit are internal for libavfilter's use * and must in no way be accessed by applications. */ char reserved[0xF000]; #else /* FF_INTERNAL_FIELDS */ /** * Queue of frames waiting to be filtered. */ FFFrameQueue fifo; /** * If set, the source filter can not generate a frame as is. * The goal is to avoid repeatedly calling the request_frame() method on * the same link. */ int frame_blocked_in; /** * Link input status. * If not zero, all attempts of filter_frame will fail with the * corresponding code. */ int status_in; /** * Timestamp of the input status change. */ int64_t status_in_pts; /** * Link output status. * If not zero, all attempts of request_frame will fail with the * corresponding code. */ int status_out; #endif /* FF_INTERNAL_FIELDS */ }; /** * Link two filters together. * * @param src the source filter * @param srcpad index of the output pad on the source filter * @param dst the destination filter * @param dstpad index of the input pad on the destination filter * @return zero on success */ int avfilter_link(AVFilterContext *src, unsigned srcpad, AVFilterContext *dst, unsigned dstpad); /** * Free the link in *link, and set its pointer to NULL. */ void avfilter_link_free(AVFilterLink **link); #if FF_API_FILTER_GET_SET /** * Get the number of channels of a link. * @deprecated Use av_buffersink_get_channels() */ attribute_deprecated int avfilter_link_get_channels(AVFilterLink *link); #endif /** * Set the closed field of a link. * @deprecated applications are not supposed to mess with links, they should * close the sinks. */ attribute_deprecated void avfilter_link_set_closed(AVFilterLink *link, int closed); /** * Negotiate the media format, dimensions, etc of all inputs to a filter. * * @param filter the filter to negotiate the properties for its inputs * @return zero on successful negotiation */ int avfilter_config_links(AVFilterContext *filter); #define AVFILTER_CMD_FLAG_ONE 1 ///< Stop once a filter understood the command (for target=all for example), fast filters are favored automatically #define AVFILTER_CMD_FLAG_FAST 2 ///< Only execute command when its fast (like a video out that supports contrast adjustment in hw) /** * Make the filter instance process a command. * It is recommended to use avfilter_graph_send_command(). */ int avfilter_process_command(AVFilterContext *filter, const char *cmd, const char *arg, char *res, int res_len, int flags); /** * Iterate over all registered filters. * * @param opaque a pointer where libavfilter will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered filter or NULL when the iteration is * finished */ const AVFilter *av_filter_iterate(void **opaque); #if FF_API_NEXT /** Initialize the filter system. Register all builtin filters. */ attribute_deprecated void avfilter_register_all(void); /** * Register a filter. This is only needed if you plan to use * avfilter_get_by_name later to lookup the AVFilter structure by name. A * filter can still by instantiated with avfilter_graph_alloc_filter even if it * is not registered. * * @param filter the filter to register * @return 0 if the registration was successful, a negative value * otherwise */ attribute_deprecated int avfilter_register(AVFilter *filter); /** * Iterate over all registered filters. * @return If prev is non-NULL, next registered filter after prev or NULL if * prev is the last filter. If prev is NULL, return the first registered filter. */ attribute_deprecated const AVFilter *avfilter_next(const AVFilter *prev); #endif /** * Get a filter definition matching the given name. * * @param name the filter name to find * @return the filter definition, if any matching one is registered. * NULL if none found. */ const AVFilter *avfilter_get_by_name(const char *name); /** * Initialize a filter with the supplied parameters. * * @param ctx uninitialized filter context to initialize * @param args Options to initialize the filter with. This must be a * ':'-separated list of options in the 'key=value' form. * May be NULL if the options have been set directly using the * AVOptions API or there are no options that need to be set. * @return 0 on success, a negative AVERROR on failure */ int avfilter_init_str(AVFilterContext *ctx, const char *args); /** * Initialize a filter with the supplied dictionary of options. * * @param ctx uninitialized filter context to initialize * @param options An AVDictionary filled with options for this filter. On * return this parameter will be destroyed and replaced with * a dict containing options that were not found. This dictionary * must be freed by the caller. * May be NULL, then this function is equivalent to * avfilter_init_str() with the second parameter set to NULL. * @return 0 on success, a negative AVERROR on failure * * @note This function and avfilter_init_str() do essentially the same thing, * the difference is in manner in which the options are passed. It is up to the * calling code to choose whichever is more preferable. The two functions also * behave differently when some of the provided options are not declared as * supported by the filter. In such a case, avfilter_init_str() will fail, but * this function will leave those extra options in the options AVDictionary and * continue as usual. */ int avfilter_init_dict(AVFilterContext *ctx, AVDictionary **options); /** * Free a filter context. This will also remove the filter from its * filtergraph's list of filters. * * @param filter the filter to free */ void avfilter_free(AVFilterContext *filter); /** * Insert a filter in the middle of an existing link. * * @param link the link into which the filter should be inserted * @param filt the filter to be inserted * @param filt_srcpad_idx the input pad on the filter to connect * @param filt_dstpad_idx the output pad on the filter to connect * @return zero on success */ int avfilter_insert_filter(AVFilterLink *link, AVFilterContext *filt, unsigned filt_srcpad_idx, unsigned filt_dstpad_idx); /** * @return AVClass for AVFilterContext. * * @see av_opt_find(). */ const AVClass *avfilter_get_class(void); typedef struct AVFilterGraphInternal AVFilterGraphInternal; /** * A function pointer passed to the @ref AVFilterGraph.execute callback to be * executed multiple times, possibly in parallel. * * @param ctx the filter context the job belongs to * @param arg an opaque parameter passed through from @ref * AVFilterGraph.execute * @param jobnr the index of the job being executed * @param nb_jobs the total number of jobs * * @return 0 on success, a negative AVERROR on error */ typedef int (avfilter_action_func)(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs); /** * A function executing multiple jobs, possibly in parallel. * * @param ctx the filter context to which the jobs belong * @param func the function to be called multiple times * @param arg the argument to be passed to func * @param ret a nb_jobs-sized array to be filled with return values from each * invocation of func * @param nb_jobs the number of jobs to execute * * @return 0 on success, a negative AVERROR on error */ typedef int (avfilter_execute_func)(AVFilterContext *ctx, avfilter_action_func *func, void *arg, int *ret, int nb_jobs); typedef struct AVFilterGraph { const AVClass *av_class; AVFilterContext **filters; unsigned nb_filters; char *scale_sws_opts; ///< sws options to use for the auto-inserted scale filters #if FF_API_LAVR_OPTS attribute_deprecated char *resample_lavr_opts; ///< libavresample options to use for the auto-inserted resample filters #endif /** * Type of multithreading allowed for filters in this graph. A combination * of AVFILTER_THREAD_* flags. * * May be set by the caller at any point, the setting will apply to all * filters initialized after that. The default is allowing everything. * * When a filter in this graph is initialized, this field is combined using * bit AND with AVFilterContext.thread_type to get the final mask used for * determining allowed threading types. I.e. a threading type needs to be * set in both to be allowed. */ int thread_type; /** * Maximum number of threads used by filters in this graph. May be set by * the caller before adding any filters to the filtergraph. Zero (the * default) means that the number of threads is determined automatically. */ int nb_threads; /** * Opaque object for libavfilter internal use. */ AVFilterGraphInternal *internal; /** * Opaque user data. May be set by the caller to an arbitrary value, e.g. to * be used from callbacks like @ref AVFilterGraph.execute. * Libavfilter will not touch this field in any way. */ void *opaque; /** * This callback may be set by the caller immediately after allocating the * graph and before adding any filters to it, to provide a custom * multithreading implementation. * * If set, filters with slice threading capability will call this callback * to execute multiple jobs in parallel. * * If this field is left unset, libavfilter will use its internal * implementation, which may or may not be multithreaded depending on the * platform and build options. */ avfilter_execute_func *execute; char *aresample_swr_opts; ///< swr options to use for the auto-inserted aresample filters, Access ONLY through AVOptions /** * Private fields * * The following fields are for internal use only. * Their type, offset, number and semantic can change without notice. */ AVFilterLink **sink_links; int sink_links_count; unsigned disable_auto_convert; } AVFilterGraph; /** * Allocate a filter graph. * * @return the allocated filter graph on success or NULL. */ AVFilterGraph *avfilter_graph_alloc(void); /** * Create a new filter instance in a filter graph. * * @param graph graph in which the new filter will be used * @param filter the filter to create an instance of * @param name Name to give to the new instance (will be copied to * AVFilterContext.name). This may be used by the caller to identify * different filters, libavfilter itself assigns no semantics to * this parameter. May be NULL. * * @return the context of the newly created filter instance (note that it is * also retrievable directly through AVFilterGraph.filters or with * avfilter_graph_get_filter()) on success or NULL on failure. */ AVFilterContext *avfilter_graph_alloc_filter(AVFilterGraph *graph, const AVFilter *filter, const char *name); /** * Get a filter instance identified by instance name from graph. * * @param graph filter graph to search through. * @param name filter instance name (should be unique in the graph). * @return the pointer to the found filter instance or NULL if it * cannot be found. */ AVFilterContext *avfilter_graph_get_filter(AVFilterGraph *graph, const char *name); /** * Create and add a filter instance into an existing graph. * The filter instance is created from the filter filt and inited * with the parameters args and opaque. * * In case of success put in *filt_ctx the pointer to the created * filter instance, otherwise set *filt_ctx to NULL. * * @param name the instance name to give to the created filter instance * @param graph_ctx the filter graph * @return a negative AVERROR error code in case of failure, a non * negative value otherwise */ int avfilter_graph_create_filter(AVFilterContext **filt_ctx, const AVFilter *filt, const char *name, const char *args, void *opaque, AVFilterGraph *graph_ctx); /** * Enable or disable automatic format conversion inside the graph. * * Note that format conversion can still happen inside explicitly inserted * scale and aresample filters. * * @param flags any of the AVFILTER_AUTO_CONVERT_* constants */ void avfilter_graph_set_auto_convert(AVFilterGraph *graph, unsigned flags); enum { AVFILTER_AUTO_CONVERT_ALL = 0, /**< all automatic conversions enabled */ AVFILTER_AUTO_CONVERT_NONE = -1, /**< all automatic conversions disabled */ }; /** * Check validity and configure all the links and formats in the graph. * * @param graphctx the filter graph * @param log_ctx context used for logging * @return >= 0 in case of success, a negative AVERROR code otherwise */ int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx); /** * Free a graph, destroy its links, and set *graph to NULL. * If *graph is NULL, do nothing. */ void avfilter_graph_free(AVFilterGraph **graph); /** * A linked-list of the inputs/outputs of the filter chain. * * This is mainly useful for avfilter_graph_parse() / avfilter_graph_parse2(), * where it is used to communicate open (unlinked) inputs and outputs from and * to the caller. * This struct specifies, per each not connected pad contained in the graph, the * filter context and the pad index required for establishing a link. */ typedef struct AVFilterInOut { /** unique name for this input/output in the list */ char *name; /** filter context associated to this input/output */ AVFilterContext *filter_ctx; /** index of the filt_ctx pad to use for linking */ int pad_idx; /** next input/input in the list, NULL if this is the last */ struct AVFilterInOut *next; } AVFilterInOut; /** * Allocate a single AVFilterInOut entry. * Must be freed with avfilter_inout_free(). * @return allocated AVFilterInOut on success, NULL on failure. */ AVFilterInOut *avfilter_inout_alloc(void); /** * Free the supplied list of AVFilterInOut and set *inout to NULL. * If *inout is NULL, do nothing. */ void avfilter_inout_free(AVFilterInOut **inout); /** * Add a graph described by a string to a graph. * * @note The caller must provide the lists of inputs and outputs, * which therefore must be known before calling the function. * * @note The inputs parameter describes inputs of the already existing * part of the graph; i.e. from the point of view of the newly created * part, they are outputs. Similarly the outputs parameter describes * outputs of the already existing filters, which are provided as * inputs to the parsed filters. * * @param graph the filter graph where to link the parsed graph context * @param filters string to be parsed * @param inputs linked list to the inputs of the graph * @param outputs linked list to the outputs of the graph * @return zero on success, a negative AVERROR code on error */ int avfilter_graph_parse(AVFilterGraph *graph, const char *filters, AVFilterInOut *inputs, AVFilterInOut *outputs, void *log_ctx); /** * Add a graph described by a string to a graph. * * In the graph filters description, if the input label of the first * filter is not specified, "in" is assumed; if the output label of * the last filter is not specified, "out" is assumed. * * @param graph the filter graph where to link the parsed graph context * @param filters string to be parsed * @param inputs pointer to a linked list to the inputs of the graph, may be NULL. * If non-NULL, *inputs is updated to contain the list of open inputs * after the parsing, should be freed with avfilter_inout_free(). * @param outputs pointer to a linked list to the outputs of the graph, may be NULL. * If non-NULL, *outputs is updated to contain the list of open outputs * after the parsing, should be freed with avfilter_inout_free(). * @return non negative on success, a negative AVERROR code on error */ int avfilter_graph_parse_ptr(AVFilterGraph *graph, const char *filters, AVFilterInOut **inputs, AVFilterInOut **outputs, void *log_ctx); /** * Add a graph described by a string to a graph. * * @param[in] graph the filter graph where to link the parsed graph context * @param[in] filters string to be parsed * @param[out] inputs a linked list of all free (unlinked) inputs of the * parsed graph will be returned here. It is to be freed * by the caller using avfilter_inout_free(). * @param[out] outputs a linked list of all free (unlinked) outputs of the * parsed graph will be returned here. It is to be freed by the * caller using avfilter_inout_free(). * @return zero on success, a negative AVERROR code on error * * @note This function returns the inputs and outputs that are left * unlinked after parsing the graph and the caller then deals with * them. * @note This function makes no reference whatsoever to already * existing parts of the graph and the inputs parameter will on return * contain inputs of the newly parsed part of the graph. Analogously * the outputs parameter will contain outputs of the newly created * filters. */ int avfilter_graph_parse2(AVFilterGraph *graph, const char *filters, AVFilterInOut **inputs, AVFilterInOut **outputs); /** * Send a command to one or more filter instances. * * @param graph the filter graph * @param target the filter(s) to which the command should be sent * "all" sends to all filters * otherwise it can be a filter or filter instance name * which will send the command to all matching filters. * @param cmd the command to send, for handling simplicity all commands must be alphanumeric only * @param arg the argument for the command * @param res a buffer with size res_size where the filter(s) can return a response. * * @returns >=0 on success otherwise an error code. * AVERROR(ENOSYS) on unsupported commands */ int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags); /** * Queue a command for one or more filter instances. * * @param graph the filter graph * @param target the filter(s) to which the command should be sent * "all" sends to all filters * otherwise it can be a filter or filter instance name * which will send the command to all matching filters. * @param cmd the command to sent, for handling simplicity all commands must be alphanumeric only * @param arg the argument for the command * @param ts time at which the command should be sent to the filter * * @note As this executes commands after this function returns, no return code * from the filter is provided, also AVFILTER_CMD_FLAG_ONE is not supported. */ int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, int flags, double ts); /** * Dump a graph into a human-readable string representation. * * @param graph the graph to dump * @param options formatting options; currently ignored * @return a string, or NULL in case of memory allocation failure; * the string must be freed using av_free */ char *avfilter_graph_dump(AVFilterGraph *graph, const char *options); /** * Request a frame on the oldest sink link. * * If the request returns AVERROR_EOF, try the next. * * Note that this function is not meant to be the sole scheduling mechanism * of a filtergraph, only a convenience function to help drain a filtergraph * in a balanced way under normal circumstances. * * Also note that AVERROR_EOF does not mean that frames did not arrive on * some of the sinks during the process. * When there are multiple sink links, in case the requested link * returns an EOF, this may cause a filter to flush pending frames * which are sent to another sink link, although unrequested. * * @return the return value of ff_request_frame(), * or AVERROR_EOF if all links returned AVERROR_EOF */ int avfilter_graph_request_oldest(AVFilterGraph *graph); /** * @} */ #endif /* AVFILTER_AVFILTER_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavfilter/buffersink.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_BUFFERSINK_H #define AVFILTER_BUFFERSINK_H /** * @file * @ingroup lavfi_buffersink * memory buffer sink API for audio and video */ #include "avfilter.h" /** * @defgroup lavfi_buffersink Buffer sink API * @ingroup lavfi * @{ */ /** * Get a frame with filtered data from sink and put it in frame. * * @param ctx pointer to a buffersink or abuffersink filter context. * @param frame pointer to an allocated frame that will be filled with data. * The data must be freed using av_frame_unref() / av_frame_free() * @param flags a combination of AV_BUFFERSINK_FLAG_* flags * * @return >= 0 in for success, a negative AVERROR code for failure. */ int av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags); /** * Tell av_buffersink_get_buffer_ref() to read video/samples buffer * reference, but not remove it from the buffer. This is useful if you * need only to read a video/samples buffer, without to fetch it. */ #define AV_BUFFERSINK_FLAG_PEEK 1 /** * Tell av_buffersink_get_buffer_ref() not to request a frame from its input. * If a frame is already buffered, it is read (and removed from the buffer), * but if no frame is present, return AVERROR(EAGAIN). */ #define AV_BUFFERSINK_FLAG_NO_REQUEST 2 /** * Struct to use for initializing a buffersink context. */ typedef struct AVBufferSinkParams { const enum AVPixelFormat *pixel_fmts; ///< list of allowed pixel formats, terminated by AV_PIX_FMT_NONE } AVBufferSinkParams; /** * Create an AVBufferSinkParams structure. * * Must be freed with av_free(). */ AVBufferSinkParams *av_buffersink_params_alloc(void); /** * Struct to use for initializing an abuffersink context. */ typedef struct AVABufferSinkParams { const enum AVSampleFormat *sample_fmts; ///< list of allowed sample formats, terminated by AV_SAMPLE_FMT_NONE const int64_t *channel_layouts; ///< list of allowed channel layouts, terminated by -1 const int *channel_counts; ///< list of allowed channel counts, terminated by -1 int all_channel_counts; ///< if not 0, accept any channel count or layout int *sample_rates; ///< list of allowed sample rates, terminated by -1 } AVABufferSinkParams; /** * Create an AVABufferSinkParams structure. * * Must be freed with av_free(). */ AVABufferSinkParams *av_abuffersink_params_alloc(void); /** * Set the frame size for an audio buffer sink. * * All calls to av_buffersink_get_buffer_ref will return a buffer with * exactly the specified number of samples, or AVERROR(EAGAIN) if there is * not enough. The last buffer at EOF will be padded with 0. */ void av_buffersink_set_frame_size(AVFilterContext *ctx, unsigned frame_size); /** * @defgroup lavfi_buffersink_accessors Buffer sink accessors * Get the properties of the stream * @{ */ enum AVMediaType av_buffersink_get_type (const AVFilterContext *ctx); AVRational av_buffersink_get_time_base (const AVFilterContext *ctx); int av_buffersink_get_format (const AVFilterContext *ctx); AVRational av_buffersink_get_frame_rate (const AVFilterContext *ctx); int av_buffersink_get_w (const AVFilterContext *ctx); int av_buffersink_get_h (const AVFilterContext *ctx); AVRational av_buffersink_get_sample_aspect_ratio (const AVFilterContext *ctx); int av_buffersink_get_channels (const AVFilterContext *ctx); uint64_t av_buffersink_get_channel_layout (const AVFilterContext *ctx); int av_buffersink_get_sample_rate (const AVFilterContext *ctx); AVBufferRef * av_buffersink_get_hw_frames_ctx (const AVFilterContext *ctx); /** @} */ /** * Get a frame with filtered data from sink and put it in frame. * * @param ctx pointer to a context of a buffersink or abuffersink AVFilter. * @param frame pointer to an allocated frame that will be filled with data. * The data must be freed using av_frame_unref() / av_frame_free() * * @return * - >= 0 if a frame was successfully returned. * - AVERROR(EAGAIN) if no frames are available at this point; more * input frames must be added to the filtergraph to get more output. * - AVERROR_EOF if there will be no more output frames on this sink. * - A different negative AVERROR code in other failure cases. */ int av_buffersink_get_frame(AVFilterContext *ctx, AVFrame *frame); /** * Same as av_buffersink_get_frame(), but with the ability to specify the number * of samples read. This function is less efficient than * av_buffersink_get_frame(), because it copies the data around. * * @param ctx pointer to a context of the abuffersink AVFilter. * @param frame pointer to an allocated frame that will be filled with data. * The data must be freed using av_frame_unref() / av_frame_free() * frame will contain exactly nb_samples audio samples, except at * the end of stream, when it can contain less than nb_samples. * * @return The return codes have the same meaning as for * av_buffersink_get_frame(). * * @warning do not mix this function with av_buffersink_get_frame(). Use only one or * the other with a single sink, not both. */ int av_buffersink_get_samples(AVFilterContext *ctx, AVFrame *frame, int nb_samples); /** * @} */ #endif /* AVFILTER_BUFFERSINK_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavfilter/buffersrc.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_BUFFERSRC_H #define AVFILTER_BUFFERSRC_H /** * @file * @ingroup lavfi_buffersrc * Memory buffer source API. */ #include "avfilter.h" /** * @defgroup lavfi_buffersrc Buffer source API * @ingroup lavfi * @{ */ enum { /** * Do not check for format changes. */ AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = 1, /** * Immediately push the frame to the output. */ AV_BUFFERSRC_FLAG_PUSH = 4, /** * Keep a reference to the frame. * If the frame if reference-counted, create a new reference; otherwise * copy the frame data. */ AV_BUFFERSRC_FLAG_KEEP_REF = 8, }; /** * Get the number of failed requests. * * A failed request is when the request_frame method is called while no * frame is present in the buffer. * The number is reset when a frame is added. */ unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src); /** * This structure contains the parameters describing the frames that will be * passed to this filter. * * It should be allocated with av_buffersrc_parameters_alloc() and freed with * av_free(). All the allocated fields in it remain owned by the caller. */ typedef struct AVBufferSrcParameters { /** * video: the pixel format, value corresponds to enum AVPixelFormat * audio: the sample format, value corresponds to enum AVSampleFormat */ int format; /** * The timebase to be used for the timestamps on the input frames. */ AVRational time_base; /** * Video only, the display dimensions of the input frames. */ int width, height; /** * Video only, the sample (pixel) aspect ratio. */ AVRational sample_aspect_ratio; /** * Video only, the frame rate of the input video. This field must only be * set to a non-zero value if input stream has a known constant framerate * and should be left at its initial value if the framerate is variable or * unknown. */ AVRational frame_rate; /** * Video with a hwaccel pixel format only. This should be a reference to an * AVHWFramesContext instance describing the input frames. */ AVBufferRef *hw_frames_ctx; /** * Audio only, the audio sampling rate in samples per second. */ int sample_rate; /** * Audio only, the audio channel layout */ uint64_t channel_layout; } AVBufferSrcParameters; /** * Allocate a new AVBufferSrcParameters instance. It should be freed by the * caller with av_free(). */ AVBufferSrcParameters *av_buffersrc_parameters_alloc(void); /** * Initialize the buffersrc or abuffersrc filter with the provided parameters. * This function may be called multiple times, the later calls override the * previous ones. Some of the parameters may also be set through AVOptions, then * whatever method is used last takes precedence. * * @param ctx an instance of the buffersrc or abuffersrc filter * @param param the stream parameters. The frames later passed to this filter * must conform to those parameters. All the allocated fields in * param remain owned by the caller, libavfilter will make internal * copies or references when necessary. * @return 0 on success, a negative AVERROR code on failure. */ int av_buffersrc_parameters_set(AVFilterContext *ctx, AVBufferSrcParameters *param); /** * Add a frame to the buffer source. * * @param ctx an instance of the buffersrc filter * @param frame frame to be added. If the frame is reference counted, this * function will make a new reference to it. Otherwise the frame data will be * copied. * * @return 0 on success, a negative AVERROR on error * * This function is equivalent to av_buffersrc_add_frame_flags() with the * AV_BUFFERSRC_FLAG_KEEP_REF flag. */ av_warn_unused_result int av_buffersrc_write_frame(AVFilterContext *ctx, const AVFrame *frame); /** * Add a frame to the buffer source. * * @param ctx an instance of the buffersrc filter * @param frame frame to be added. If the frame is reference counted, this * function will take ownership of the reference(s) and reset the frame. * Otherwise the frame data will be copied. If this function returns an error, * the input frame is not touched. * * @return 0 on success, a negative AVERROR on error. * * @note the difference between this function and av_buffersrc_write_frame() is * that av_buffersrc_write_frame() creates a new reference to the input frame, * while this function takes ownership of the reference passed to it. * * This function is equivalent to av_buffersrc_add_frame_flags() without the * AV_BUFFERSRC_FLAG_KEEP_REF flag. */ av_warn_unused_result int av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame); /** * Add a frame to the buffer source. * * By default, if the frame is reference-counted, this function will take * ownership of the reference(s) and reset the frame. This can be controlled * using the flags. * * If this function returns an error, the input frame is not touched. * * @param buffer_src pointer to a buffer source context * @param frame a frame, or NULL to mark EOF * @param flags a combination of AV_BUFFERSRC_FLAG_* * @return >= 0 in case of success, a negative AVERROR code * in case of failure */ av_warn_unused_result int av_buffersrc_add_frame_flags(AVFilterContext *buffer_src, AVFrame *frame, int flags); /** * Close the buffer source after EOF. * * This is similar to passing NULL to av_buffersrc_add_frame_flags() * except it takes the timestamp of the EOF, i.e. the timestamp of the end * of the last frame. */ int av_buffersrc_close(AVFilterContext *ctx, int64_t pts, unsigned flags); /** * @} */ #endif /* AVFILTER_BUFFERSRC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavfilter/version.h ================================================ /* * Version macros. * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFILTER_VERSION_H #define AVFILTER_VERSION_H /** * @file * @ingroup lavfi * Libavfilter version macros */ #include "libavutil/version.h" #define LIBAVFILTER_VERSION_MAJOR 7 #define LIBAVFILTER_VERSION_MINOR 57 #define LIBAVFILTER_VERSION_MICRO 100 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \ LIBAVFILTER_VERSION_MINOR, \ LIBAVFILTER_VERSION_MICRO) #define LIBAVFILTER_VERSION AV_VERSION(LIBAVFILTER_VERSION_MAJOR, \ LIBAVFILTER_VERSION_MINOR, \ LIBAVFILTER_VERSION_MICRO) #define LIBAVFILTER_BUILD LIBAVFILTER_VERSION_INT #define LIBAVFILTER_IDENT "Lavfi" AV_STRINGIFY(LIBAVFILTER_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #ifndef FF_API_OLD_FILTER_OPTS_ERROR #define FF_API_OLD_FILTER_OPTS_ERROR (LIBAVFILTER_VERSION_MAJOR < 8) #endif #ifndef FF_API_LAVR_OPTS #define FF_API_LAVR_OPTS (LIBAVFILTER_VERSION_MAJOR < 8) #endif #ifndef FF_API_FILTER_GET_SET #define FF_API_FILTER_GET_SET (LIBAVFILTER_VERSION_MAJOR < 8) #endif #ifndef FF_API_NEXT #define FF_API_NEXT (LIBAVFILTER_VERSION_MAJOR < 8) #endif #endif /* AVFILTER_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavformat/avformat.h ================================================ /* * copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_AVFORMAT_H #define AVFORMAT_AVFORMAT_H /** * @file * @ingroup libavf * Main libavformat public API header */ /** * @defgroup libavf libavformat * I/O and Muxing/Demuxing Library * * Libavformat (lavf) is a library for dealing with various media container * formats. Its main two purposes are demuxing - i.e. splitting a media file * into component streams, and the reverse process of muxing - writing supplied * data in a specified container format. It also has an @ref lavf_io * "I/O module" which supports a number of protocols for accessing the data (e.g. * file, tcp, http and others). * Unless you are absolutely sure you won't use libavformat's network * capabilities, you should also call avformat_network_init(). * * A supported input format is described by an AVInputFormat struct, conversely * an output format is described by AVOutputFormat. You can iterate over all * input/output formats using the av_demuxer_iterate / av_muxer_iterate() functions. * The protocols layer is not part of the public API, so you can only get the names * of supported protocols with the avio_enum_protocols() function. * * Main lavf structure used for both muxing and demuxing is AVFormatContext, * which exports all information about the file being read or written. As with * most Libavformat structures, its size is not part of public ABI, so it cannot be * allocated on stack or directly with av_malloc(). To create an * AVFormatContext, use avformat_alloc_context() (some functions, like * avformat_open_input() might do that for you). * * Most importantly an AVFormatContext contains: * @li the @ref AVFormatContext.iformat "input" or @ref AVFormatContext.oformat * "output" format. It is either autodetected or set by user for input; * always set by user for output. * @li an @ref AVFormatContext.streams "array" of AVStreams, which describe all * elementary streams stored in the file. AVStreams are typically referred to * using their index in this array. * @li an @ref AVFormatContext.pb "I/O context". It is either opened by lavf or * set by user for input, always set by user for output (unless you are dealing * with an AVFMT_NOFILE format). * * @section lavf_options Passing options to (de)muxers * It is possible to configure lavf muxers and demuxers using the @ref avoptions * mechanism. Generic (format-independent) libavformat options are provided by * AVFormatContext, they can be examined from a user program by calling * av_opt_next() / av_opt_find() on an allocated AVFormatContext (or its AVClass * from avformat_get_class()). Private (format-specific) options are provided by * AVFormatContext.priv_data if and only if AVInputFormat.priv_class / * AVOutputFormat.priv_class of the corresponding format struct is non-NULL. * Further options may be provided by the @ref AVFormatContext.pb "I/O context", * if its AVClass is non-NULL, and the protocols layer. See the discussion on * nesting in @ref avoptions documentation to learn how to access those. * * @section urls * URL strings in libavformat are made of a scheme/protocol, a ':', and a * scheme specific string. URLs without a scheme and ':' used for local files * are supported but deprecated. "file:" should be used for local files. * * It is important that the scheme string is not taken from untrusted * sources without checks. * * Note that some schemes/protocols are quite powerful, allowing access to * both local and remote files, parts of them, concatenations of them, local * audio and video devices and so on. * * @{ * * @defgroup lavf_decoding Demuxing * @{ * Demuxers read a media file and split it into chunks of data (@em packets). A * @ref AVPacket "packet" contains one or more encoded frames which belongs to a * single elementary stream. In the lavf API this process is represented by the * avformat_open_input() function for opening a file, av_read_frame() for * reading a single packet and finally avformat_close_input(), which does the * cleanup. * * @section lavf_decoding_open Opening a media file * The minimum information required to open a file is its URL, which * is passed to avformat_open_input(), as in the following code: * @code * const char *url = "file:in.mp3"; * AVFormatContext *s = NULL; * int ret = avformat_open_input(&s, url, NULL, NULL); * if (ret < 0) * abort(); * @endcode * The above code attempts to allocate an AVFormatContext, open the * specified file (autodetecting the format) and read the header, exporting the * information stored there into s. Some formats do not have a header or do not * store enough information there, so it is recommended that you call the * avformat_find_stream_info() function which tries to read and decode a few * frames to find missing information. * * In some cases you might want to preallocate an AVFormatContext yourself with * avformat_alloc_context() and do some tweaking on it before passing it to * avformat_open_input(). One such case is when you want to use custom functions * for reading input data instead of lavf internal I/O layer. * To do that, create your own AVIOContext with avio_alloc_context(), passing * your reading callbacks to it. Then set the @em pb field of your * AVFormatContext to newly created AVIOContext. * * Since the format of the opened file is in general not known until after * avformat_open_input() has returned, it is not possible to set demuxer private * options on a preallocated context. Instead, the options should be passed to * avformat_open_input() wrapped in an AVDictionary: * @code * AVDictionary *options = NULL; * av_dict_set(&options, "video_size", "640x480", 0); * av_dict_set(&options, "pixel_format", "rgb24", 0); * * if (avformat_open_input(&s, url, NULL, &options) < 0) * abort(); * av_dict_free(&options); * @endcode * This code passes the private options 'video_size' and 'pixel_format' to the * demuxer. They would be necessary for e.g. the rawvideo demuxer, since it * cannot know how to interpret raw video data otherwise. If the format turns * out to be something different than raw video, those options will not be * recognized by the demuxer and therefore will not be applied. Such unrecognized * options are then returned in the options dictionary (recognized options are * consumed). The calling program can handle such unrecognized options as it * wishes, e.g. * @code * AVDictionaryEntry *e; * if (e = av_dict_get(options, "", NULL, AV_DICT_IGNORE_SUFFIX)) { * fprintf(stderr, "Option %s not recognized by the demuxer.\n", e->key); * abort(); * } * @endcode * * After you have finished reading the file, you must close it with * avformat_close_input(). It will free everything associated with the file. * * @section lavf_decoding_read Reading from an opened file * Reading data from an opened AVFormatContext is done by repeatedly calling * av_read_frame() on it. Each call, if successful, will return an AVPacket * containing encoded data for one AVStream, identified by * AVPacket.stream_index. This packet may be passed straight into the libavcodec * decoding functions avcodec_send_packet() or avcodec_decode_subtitle2() if the * caller wishes to decode the data. * * AVPacket.pts, AVPacket.dts and AVPacket.duration timing information will be * set if known. They may also be unset (i.e. AV_NOPTS_VALUE for * pts/dts, 0 for duration) if the stream does not provide them. The timing * information will be in AVStream.time_base units, i.e. it has to be * multiplied by the timebase to convert them to seconds. * * If AVPacket.buf is set on the returned packet, then the packet is * allocated dynamically and the user may keep it indefinitely. * Otherwise, if AVPacket.buf is NULL, the packet data is backed by a * static storage somewhere inside the demuxer and the packet is only valid * until the next av_read_frame() call or closing the file. If the caller * requires a longer lifetime, av_packet_make_refcounted() will ensure that * the data is reference counted, copying the data if necessary. * In both cases, the packet must be freed with av_packet_unref() when it is no * longer needed. * * @section lavf_decoding_seek Seeking * @} * * @defgroup lavf_encoding Muxing * @{ * Muxers take encoded data in the form of @ref AVPacket "AVPackets" and write * it into files or other output bytestreams in the specified container format. * * The main API functions for muxing are avformat_write_header() for writing the * file header, av_write_frame() / av_interleaved_write_frame() for writing the * packets and av_write_trailer() for finalizing the file. * * At the beginning of the muxing process, the caller must first call * avformat_alloc_context() to create a muxing context. The caller then sets up * the muxer by filling the various fields in this context: * * - The @ref AVFormatContext.oformat "oformat" field must be set to select the * muxer that will be used. * - Unless the format is of the AVFMT_NOFILE type, the @ref AVFormatContext.pb * "pb" field must be set to an opened IO context, either returned from * avio_open2() or a custom one. * - Unless the format is of the AVFMT_NOSTREAMS type, at least one stream must * be created with the avformat_new_stream() function. The caller should fill * the @ref AVStream.codecpar "stream codec parameters" information, such as the * codec @ref AVCodecParameters.codec_type "type", @ref AVCodecParameters.codec_id * "id" and other parameters (e.g. width / height, the pixel or sample format, * etc.) as known. The @ref AVStream.time_base "stream timebase" should * be set to the timebase that the caller desires to use for this stream (note * that the timebase actually used by the muxer can be different, as will be * described later). * - It is advised to manually initialize only the relevant fields in * AVCodecParameters, rather than using @ref avcodec_parameters_copy() during * remuxing: there is no guarantee that the codec context values remain valid * for both input and output format contexts. * - The caller may fill in additional information, such as @ref * AVFormatContext.metadata "global" or @ref AVStream.metadata "per-stream" * metadata, @ref AVFormatContext.chapters "chapters", @ref * AVFormatContext.programs "programs", etc. as described in the * AVFormatContext documentation. Whether such information will actually be * stored in the output depends on what the container format and the muxer * support. * * When the muxing context is fully set up, the caller must call * avformat_write_header() to initialize the muxer internals and write the file * header. Whether anything actually is written to the IO context at this step * depends on the muxer, but this function must always be called. Any muxer * private options must be passed in the options parameter to this function. * * The data is then sent to the muxer by repeatedly calling av_write_frame() or * av_interleaved_write_frame() (consult those functions' documentation for * discussion on the difference between them; only one of them may be used with * a single muxing context, they should not be mixed). Do note that the timing * information on the packets sent to the muxer must be in the corresponding * AVStream's timebase. That timebase is set by the muxer (in the * avformat_write_header() step) and may be different from the timebase * requested by the caller. * * Once all the data has been written, the caller must call av_write_trailer() * to flush any buffered packets and finalize the output file, then close the IO * context (if any) and finally free the muxing context with * avformat_free_context(). * @} * * @defgroup lavf_io I/O Read/Write * @{ * @section lavf_io_dirlist Directory listing * The directory listing API makes it possible to list files on remote servers. * * Some of possible use cases: * - an "open file" dialog to choose files from a remote location, * - a recursive media finder providing a player with an ability to play all * files from a given directory. * * @subsection lavf_io_dirlist_open Opening a directory * At first, a directory needs to be opened by calling avio_open_dir() * supplied with a URL and, optionally, ::AVDictionary containing * protocol-specific parameters. The function returns zero or positive * integer and allocates AVIODirContext on success. * * @code * AVIODirContext *ctx = NULL; * if (avio_open_dir(&ctx, "smb://example.com/some_dir", NULL) < 0) { * fprintf(stderr, "Cannot open directory.\n"); * abort(); * } * @endcode * * This code tries to open a sample directory using smb protocol without * any additional parameters. * * @subsection lavf_io_dirlist_read Reading entries * Each directory's entry (i.e. file, another directory, anything else * within ::AVIODirEntryType) is represented by AVIODirEntry. * Reading consecutive entries from an opened AVIODirContext is done by * repeatedly calling avio_read_dir() on it. Each call returns zero or * positive integer if successful. Reading can be stopped right after the * NULL entry has been read -- it means there are no entries left to be * read. The following code reads all entries from a directory associated * with ctx and prints their names to standard output. * @code * AVIODirEntry *entry = NULL; * for (;;) { * if (avio_read_dir(ctx, &entry) < 0) { * fprintf(stderr, "Cannot list directory.\n"); * abort(); * } * if (!entry) * break; * printf("%s\n", entry->name); * avio_free_directory_entry(&entry); * } * @endcode * @} * * @defgroup lavf_codec Demuxers * @{ * @defgroup lavf_codec_native Native Demuxers * @{ * @} * @defgroup lavf_codec_wrappers External library wrappers * @{ * @} * @} * @defgroup lavf_protos I/O Protocols * @{ * @} * @defgroup lavf_internal Internal * @{ * @} * @} */ #include #include /* FILE */ #include "libavcodec/avcodec.h" #include "libavutil/dict.h" #include "libavutil/log.h" #include "avio.h" #include "libavformat/version.h" struct AVFormatContext; struct AVDeviceInfoList; struct AVDeviceCapabilitiesQuery; /** * @defgroup metadata_api Public Metadata API * @{ * @ingroup libavf * The metadata API allows libavformat to export metadata tags to a client * application when demuxing. Conversely it allows a client application to * set metadata when muxing. * * Metadata is exported or set as pairs of key/value strings in the 'metadata' * fields of the AVFormatContext, AVStream, AVChapter and AVProgram structs * using the @ref lavu_dict "AVDictionary" API. Like all strings in FFmpeg, * metadata is assumed to be UTF-8 encoded Unicode. Note that metadata * exported by demuxers isn't checked to be valid UTF-8 in most cases. * * Important concepts to keep in mind: * - Keys are unique; there can never be 2 tags with the same key. This is * also meant semantically, i.e., a demuxer should not knowingly produce * several keys that are literally different but semantically identical. * E.g., key=Author5, key=Author6. In this example, all authors must be * placed in the same tag. * - Metadata is flat, not hierarchical; there are no subtags. If you * want to store, e.g., the email address of the child of producer Alice * and actor Bob, that could have key=alice_and_bobs_childs_email_address. * - Several modifiers can be applied to the tag name. This is done by * appending a dash character ('-') and the modifier name in the order * they appear in the list below -- e.g. foo-eng-sort, not foo-sort-eng. * - language -- a tag whose value is localized for a particular language * is appended with the ISO 639-2/B 3-letter language code. * For example: Author-ger=Michael, Author-eng=Mike * The original/default language is in the unqualified "Author" tag. * A demuxer should set a default if it sets any translated tag. * - sorting -- a modified version of a tag that should be used for * sorting will have '-sort' appended. E.g. artist="The Beatles", * artist-sort="Beatles, The". * - Some protocols and demuxers support metadata updates. After a successful * call to av_read_packet(), AVFormatContext.event_flags or AVStream.event_flags * will be updated to indicate if metadata changed. In order to detect metadata * changes on a stream, you need to loop through all streams in the AVFormatContext * and check their individual event_flags. * * - Demuxers attempt to export metadata in a generic format, however tags * with no generic equivalents are left as they are stored in the container. * Follows a list of generic tag names: * @verbatim album -- name of the set this work belongs to album_artist -- main creator of the set/album, if different from artist. e.g. "Various Artists" for compilation albums. artist -- main creator of the work comment -- any additional description of the file. composer -- who composed the work, if different from artist. copyright -- name of copyright holder. creation_time-- date when the file was created, preferably in ISO 8601. date -- date when the work was created, preferably in ISO 8601. disc -- number of a subset, e.g. disc in a multi-disc collection. encoder -- name/settings of the software/hardware that produced the file. encoded_by -- person/group who created the file. filename -- original name of the file. genre -- . language -- main language in which the work is performed, preferably in ISO 639-2 format. Multiple languages can be specified by separating them with commas. performer -- artist who performed the work, if different from artist. E.g for "Also sprach Zarathustra", artist would be "Richard Strauss" and performer "London Philharmonic Orchestra". publisher -- name of the label/publisher. service_name -- name of the service in broadcasting (channel name). service_provider -- name of the service provider in broadcasting. title -- name of the work. track -- number of this work in the set, can be in form current/total. variant_bitrate -- the total bitrate of the bitrate variant that the current stream is part of @endverbatim * * Look in the examples section for an application example how to use the Metadata API. * * @} */ /* packet functions */ /** * Allocate and read the payload of a packet and initialize its * fields with default values. * * @param s associated IO context * @param pkt packet * @param size desired payload size * @return >0 (read size) if OK, AVERROR_xxx otherwise */ int av_get_packet(AVIOContext *s, AVPacket *pkt, int size); /** * Read data and append it to the current content of the AVPacket. * If pkt->size is 0 this is identical to av_get_packet. * Note that this uses av_grow_packet and thus involves a realloc * which is inefficient. Thus this function should only be used * when there is no reasonable way to know (an upper bound of) * the final size. * * @param s associated IO context * @param pkt packet * @param size amount of data to read * @return >0 (read size) if OK, AVERROR_xxx otherwise, previous data * will not be lost even if an error occurs. */ int av_append_packet(AVIOContext *s, AVPacket *pkt, int size); /*************************************************/ /* input/output formats */ struct AVCodecTag; /** * This structure contains the data a format has to probe a file. */ typedef struct AVProbeData { const char *filename; unsigned char *buf; /**< Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero. */ int buf_size; /**< Size of buf except extra allocated bytes */ const char *mime_type; /**< mime_type, when known. */ } AVProbeData; #define AVPROBE_SCORE_RETRY (AVPROBE_SCORE_MAX/4) #define AVPROBE_SCORE_STREAM_RETRY (AVPROBE_SCORE_MAX/4-1) #define AVPROBE_SCORE_EXTENSION 50 ///< score for file extension #define AVPROBE_SCORE_MIME 75 ///< score for file mime type #define AVPROBE_SCORE_MAX 100 ///< maximum score #define AVPROBE_PADDING_SIZE 32 ///< extra allocated bytes at the end of the probe buffer /// Demuxer will use avio_open, no opened file should be provided by the caller. #define AVFMT_NOFILE 0x0001 #define AVFMT_NEEDNUMBER 0x0002 /**< Needs '%d' in filename. */ #define AVFMT_SHOW_IDS 0x0008 /**< Show format stream IDs numbers. */ #define AVFMT_GLOBALHEADER 0x0040 /**< Format wants global header. */ #define AVFMT_NOTIMESTAMPS 0x0080 /**< Format does not need / have any timestamps. */ #define AVFMT_GENERIC_INDEX 0x0100 /**< Use generic index building code. */ #define AVFMT_TS_DISCONT 0x0200 /**< Format allows timestamp discontinuities. Note, muxers always require valid (monotone) timestamps */ #define AVFMT_VARIABLE_FPS 0x0400 /**< Format allows variable fps. */ #define AVFMT_NODIMENSIONS 0x0800 /**< Format does not need width/height */ #define AVFMT_NOSTREAMS 0x1000 /**< Format does not require any streams */ #define AVFMT_NOBINSEARCH 0x2000 /**< Format does not allow to fall back on binary search via read_timestamp */ #define AVFMT_NOGENSEARCH 0x4000 /**< Format does not allow to fall back on generic search */ #define AVFMT_NO_BYTE_SEEK 0x8000 /**< Format does not allow seeking by bytes */ #define AVFMT_ALLOW_FLUSH 0x10000 /**< Format allows flushing. If not set, the muxer will not receive a NULL packet in the write_packet function. */ #define AVFMT_TS_NONSTRICT 0x20000 /**< Format does not require strictly increasing timestamps, but they must still be monotonic */ #define AVFMT_TS_NEGATIVE 0x40000 /**< Format allows muxing negative timestamps. If not set the timestamp will be shifted in av_write_frame and av_interleaved_write_frame so they start from 0. The user or muxer can override this through AVFormatContext.avoid_negative_ts */ #define AVFMT_SEEK_TO_PTS 0x4000000 /**< Seeking is based on PTS */ /** * @addtogroup lavf_encoding * @{ */ typedef struct AVOutputFormat { const char *name; /** * Descriptive name for the format, meant to be more human-readable * than name. You should use the NULL_IF_CONFIG_SMALL() macro * to define it. */ const char *long_name; const char *mime_type; const char *extensions; /**< comma-separated filename extensions */ /* output support */ enum AVCodecID audio_codec; /**< default audio codec */ enum AVCodecID video_codec; /**< default video codec */ enum AVCodecID subtitle_codec; /**< default subtitle codec */ /** * can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, * AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS, * AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS, AVFMT_ALLOW_FLUSH, * AVFMT_TS_NONSTRICT, AVFMT_TS_NEGATIVE */ int flags; /** * List of supported codec_id-codec_tag pairs, ordered by "better * choice first". The arrays are all terminated by AV_CODEC_ID_NONE. */ const struct AVCodecTag * const *codec_tag; const AVClass *priv_class; ///< AVClass for the private context /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ /** * The ff_const59 define is not part of the public API and will * be removed without further warning. */ #if FF_API_AVIOFORMAT #define ff_const59 #else #define ff_const59 const #endif ff_const59 struct AVOutputFormat *next; /** * size of private data so that it can be allocated in the wrapper */ int priv_data_size; int (*write_header)(struct AVFormatContext *); /** * Write a packet. If AVFMT_ALLOW_FLUSH is set in flags, * pkt can be NULL in order to flush data buffered in the muxer. * When flushing, return 0 if there still is more data to flush, * or 1 if everything was flushed and there is no more buffered * data. */ int (*write_packet)(struct AVFormatContext *, AVPacket *pkt); int (*write_trailer)(struct AVFormatContext *); /** * Currently only used to set pixel format if not YUV420P. */ int (*interleave_packet)(struct AVFormatContext *, AVPacket *out, AVPacket *in, int flush); /** * Test if the given codec can be stored in this container. * * @return 1 if the codec is supported, 0 if it is not. * A negative number if unknown. * MKTAG('A', 'P', 'I', 'C') if the codec is only supported as AV_DISPOSITION_ATTACHED_PIC */ int (*query_codec)(enum AVCodecID id, int std_compliance); void (*get_output_timestamp)(struct AVFormatContext *s, int stream, int64_t *dts, int64_t *wall); /** * Allows sending messages from application to device. */ int (*control_message)(struct AVFormatContext *s, int type, void *data, size_t data_size); /** * Write an uncoded AVFrame. * * See av_write_uncoded_frame() for details. * * The library will free *frame afterwards, but the muxer can prevent it * by setting the pointer to NULL. */ int (*write_uncoded_frame)(struct AVFormatContext *, int stream_index, AVFrame **frame, unsigned flags); /** * Returns device list with it properties. * @see avdevice_list_devices() for more details. */ int (*get_device_list)(struct AVFormatContext *s, struct AVDeviceInfoList *device_list); /** * Initialize device capabilities submodule. * @see avdevice_capabilities_create() for more details. */ int (*create_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); /** * Free device capabilities submodule. * @see avdevice_capabilities_free() for more details. */ int (*free_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); enum AVCodecID data_codec; /**< default data codec */ /** * Initialize format. May allocate data here, and set any AVFormatContext or * AVStream parameters that need to be set before packets are sent. * This method must not write output. * * Return 0 if streams were fully configured, 1 if not, negative AVERROR on failure * * Any allocations made here must be freed in deinit(). */ int (*init)(struct AVFormatContext *); /** * Deinitialize format. If present, this is called whenever the muxer is being * destroyed, regardless of whether or not the header has been written. * * If a trailer is being written, this is called after write_trailer(). * * This is called if init() fails as well. */ void (*deinit)(struct AVFormatContext *); /** * Set up any necessary bitstream filtering and extract any extra data needed * for the global header. * Return 0 if more packets from this stream must be checked; 1 if not. */ int (*check_bitstream)(struct AVFormatContext *, const AVPacket *pkt); } AVOutputFormat; /** * @} */ /** * @addtogroup lavf_decoding * @{ */ typedef struct AVInputFormat { /** * A comma separated list of short names for the format. New names * may be appended with a minor bump. */ const char *name; /** * Descriptive name for the format, meant to be more human-readable * than name. You should use the NULL_IF_CONFIG_SMALL() macro * to define it. */ const char *long_name; /** * Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS, * AVFMT_NOTIMESTAMPS, AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH, * AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS. */ int flags; /** * If extensions are defined, then no probe is done. You should * usually not use extension format guessing because it is not * reliable enough */ const char *extensions; const struct AVCodecTag * const *codec_tag; const AVClass *priv_class; ///< AVClass for the private context /** * Comma-separated list of mime types. * It is used check for matching mime types while probing. * @see av_probe_input_format2 */ const char *mime_type; /***************************************************************** * No fields below this line are part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ ff_const59 struct AVInputFormat *next; /** * Raw demuxers store their codec ID here. */ int raw_codec_id; /** * Size of private data so that it can be allocated in the wrapper. */ int priv_data_size; /** * Tell if a given file has a chance of being parsed as this format. * The buffer provided is guaranteed to be AVPROBE_PADDING_SIZE bytes * big so you do not have to check for that unless you need more. */ int (*read_probe)(const AVProbeData *); /** * Read the format header and initialize the AVFormatContext * structure. Return 0 if OK. 'avformat_new_stream' should be * called to create new streams. */ int (*read_header)(struct AVFormatContext *); /** * Read one packet and put it in 'pkt'. pts and flags are also * set. 'avformat_new_stream' can be called only if the flag * AVFMTCTX_NOHEADER is used and only in the calling thread (not in a * background thread). * @return 0 on success, < 0 on error. * When returning an error, pkt must not have been allocated * or must be freed before returning */ int (*read_packet)(struct AVFormatContext *, AVPacket *pkt); /** * Close the stream. The AVFormatContext and AVStreams are not * freed by this function */ int (*read_close)(struct AVFormatContext *); /** * Seek to a given timestamp relative to the frames in * stream component stream_index. * @param stream_index Must not be -1. * @param flags Selects which direction should be preferred if no exact * match is available. * @return >= 0 on success (but not necessarily the new offset) */ int (*read_seek)(struct AVFormatContext *, int stream_index, int64_t timestamp, int flags); /** * Get the next timestamp in stream[stream_index].time_base units. * @return the timestamp or AV_NOPTS_VALUE if an error occurred */ int64_t (*read_timestamp)(struct AVFormatContext *s, int stream_index, int64_t *pos, int64_t pos_limit); /** * Start/resume playing - only meaningful if using a network-based format * (RTSP). */ int (*read_play)(struct AVFormatContext *); /** * Pause playing - only meaningful if using a network-based format * (RTSP). */ int (*read_pause)(struct AVFormatContext *); /** * Seek to timestamp ts. * Seeking will be done so that the point from which all active streams * can be presented successfully will be closest to ts and within min/max_ts. * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL. */ int (*read_seek2)(struct AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags); /** * Returns device list with it properties. * @see avdevice_list_devices() for more details. */ int (*get_device_list)(struct AVFormatContext *s, struct AVDeviceInfoList *device_list); /** * Initialize device capabilities submodule. * @see avdevice_capabilities_create() for more details. */ int (*create_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); /** * Free device capabilities submodule. * @see avdevice_capabilities_free() for more details. */ int (*free_device_capabilities)(struct AVFormatContext *s, struct AVDeviceCapabilitiesQuery *caps); } AVInputFormat; /** * @} */ enum AVStreamParseType { AVSTREAM_PARSE_NONE, AVSTREAM_PARSE_FULL, /**< full parsing and repack */ AVSTREAM_PARSE_HEADERS, /**< Only parse headers, do not repack. */ AVSTREAM_PARSE_TIMESTAMPS, /**< full parsing and interpolation of timestamps for frames not starting on a packet boundary */ AVSTREAM_PARSE_FULL_ONCE, /**< full parsing and repack of the first frame only, only implemented for H.264 currently */ AVSTREAM_PARSE_FULL_RAW, /**< full parsing and repack with timestamp and position generation by parser for raw this assumes that each packet in the file contains no demuxer level headers and just codec level data, otherwise position generation would fail */ }; typedef struct AVIndexEntry { int64_t pos; int64_t timestamp; /**< * Timestamp in AVStream.time_base units, preferably the time from which on correctly decoded frames are available * when seeking to this entry. That means preferable PTS on keyframe based formats. * But demuxers can choose to store a different timestamp, if it is more convenient for the implementation or nothing better * is known */ #define AVINDEX_KEYFRAME 0x0001 #define AVINDEX_DISCARD_FRAME 0x0002 /** * Flag is used to indicate which frame should be discarded after decoding. */ int flags:2; int size:30; //Yeah, trying to keep the size of this small to reduce memory requirements (it is 24 vs. 32 bytes due to possible 8-byte alignment). int min_distance; /**< Minimum distance between this and the previous keyframe, used to avoid unneeded searching. */ } AVIndexEntry; #define AV_DISPOSITION_DEFAULT 0x0001 #define AV_DISPOSITION_DUB 0x0002 #define AV_DISPOSITION_ORIGINAL 0x0004 #define AV_DISPOSITION_COMMENT 0x0008 #define AV_DISPOSITION_LYRICS 0x0010 #define AV_DISPOSITION_KARAOKE 0x0020 /** * Track should be used during playback by default. * Useful for subtitle track that should be displayed * even when user did not explicitly ask for subtitles. */ #define AV_DISPOSITION_FORCED 0x0040 #define AV_DISPOSITION_HEARING_IMPAIRED 0x0080 /**< stream for hearing impaired audiences */ #define AV_DISPOSITION_VISUAL_IMPAIRED 0x0100 /**< stream for visual impaired audiences */ #define AV_DISPOSITION_CLEAN_EFFECTS 0x0200 /**< stream without voice */ /** * The stream is stored in the file as an attached picture/"cover art" (e.g. * APIC frame in ID3v2). The first (usually only) packet associated with it * will be returned among the first few packets read from the file unless * seeking takes place. It can also be accessed at any time in * AVStream.attached_pic. */ #define AV_DISPOSITION_ATTACHED_PIC 0x0400 /** * The stream is sparse, and contains thumbnail images, often corresponding * to chapter markers. Only ever used with AV_DISPOSITION_ATTACHED_PIC. */ #define AV_DISPOSITION_TIMED_THUMBNAILS 0x0800 typedef struct AVStreamInternal AVStreamInternal; /** * To specify text track kind (different from subtitles default). */ #define AV_DISPOSITION_CAPTIONS 0x10000 #define AV_DISPOSITION_DESCRIPTIONS 0x20000 #define AV_DISPOSITION_METADATA 0x40000 #define AV_DISPOSITION_DEPENDENT 0x80000 ///< dependent audio stream (mix_type=0 in mpegts) #define AV_DISPOSITION_STILL_IMAGE 0x100000 ///< still images in video stream (still_picture_flag=1 in mpegts) /** * Options for behavior on timestamp wrap detection. */ #define AV_PTS_WRAP_IGNORE 0 ///< ignore the wrap #define AV_PTS_WRAP_ADD_OFFSET 1 ///< add the format specific offset on wrap detection #define AV_PTS_WRAP_SUB_OFFSET -1 ///< subtract the format specific offset on wrap detection /** * Stream structure. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVStream) must not be used outside libav*. */ typedef struct AVStream { int index; /**< stream index in AVFormatContext */ /** * Format-specific stream ID. * decoding: set by libavformat * encoding: set by the user, replaced by libavformat if left unset */ int id; #if FF_API_LAVF_AVCTX /** * @deprecated use the codecpar struct instead */ attribute_deprecated AVCodecContext *codec; #endif void *priv_data; /** * This is the fundamental unit of time (in seconds) in terms * of which frame timestamps are represented. * * decoding: set by libavformat * encoding: May be set by the caller before avformat_write_header() to * provide a hint to the muxer about the desired timebase. In * avformat_write_header(), the muxer will overwrite this field * with the timebase that will actually be used for the timestamps * written into the file (which may or may not be related to the * user-provided one, depending on the format). */ AVRational time_base; /** * Decoding: pts of the first frame of the stream in presentation order, in stream time base. * Only set this if you are absolutely 100% sure that the value you set * it to really is the pts of the first frame. * This may be undefined (AV_NOPTS_VALUE). * @note The ASF header does NOT contain a correct start_time the ASF * demuxer must NOT set this. */ int64_t start_time; /** * Decoding: duration of the stream, in stream time base. * If a source file does not specify a duration, but does specify * a bitrate, this value will be estimated from bitrate and file size. * * Encoding: May be set by the caller before avformat_write_header() to * provide a hint to the muxer about the estimated duration. */ int64_t duration; int64_t nb_frames; ///< number of frames in this stream if known or 0 int disposition; /**< AV_DISPOSITION_* bit field */ enum AVDiscard discard; ///< Selects which packets can be discarded at will and do not need to be demuxed. /** * sample aspect ratio (0 if unknown) * - encoding: Set by user. * - decoding: Set by libavformat. */ AVRational sample_aspect_ratio; AVDictionary *metadata; /** * Average framerate * * - demuxing: May be set by libavformat when creating the stream or in * avformat_find_stream_info(). * - muxing: May be set by the caller before avformat_write_header(). */ AVRational avg_frame_rate; /** * For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet * will contain the attached picture. * * decoding: set by libavformat, must not be modified by the caller. * encoding: unused */ AVPacket attached_pic; /** * An array of side data that applies to the whole stream (i.e. the * container does not allow it to change between packets). * * There may be no overlap between the side data in this array and side data * in the packets. I.e. a given side data is either exported by the muxer * (demuxing) / set by the caller (muxing) in this array, then it never * appears in the packets, or the side data is exported / sent through * the packets (always in the first packet where the value becomes known or * changes), then it does not appear in this array. * * - demuxing: Set by libavformat when the stream is created. * - muxing: May be set by the caller before avformat_write_header(). * * Freed by libavformat in avformat_free_context(). * * @see av_format_inject_global_side_data() */ AVPacketSideData *side_data; /** * The number of elements in the AVStream.side_data array. */ int nb_side_data; /** * Flags for the user to detect events happening on the stream. Flags must * be cleared by the user once the event has been handled. * A combination of AVSTREAM_EVENT_FLAG_*. */ int event_flags; #define AVSTREAM_EVENT_FLAG_METADATA_UPDATED 0x0001 ///< The call resulted in updated metadata. /** * Real base framerate of the stream. * This is the lowest framerate with which all timestamps can be * represented accurately (it is the least common multiple of all * framerates in the stream). Note, this value is just a guess! * For example, if the time base is 1/90000 and all frames have either * approximately 3600 or 1800 timer ticks, then r_frame_rate will be 50/1. */ AVRational r_frame_rate; #if FF_API_LAVF_FFSERVER /** * String containing pairs of key and values describing recommended encoder configuration. * Pairs are separated by ','. * Keys are separated from values by '='. * * @deprecated unused */ attribute_deprecated char *recommended_encoder_configuration; #endif /** * Codec parameters associated with this stream. Allocated and freed by * libavformat in avformat_new_stream() and avformat_free_context() * respectively. * * - demuxing: filled by libavformat on stream creation or in * avformat_find_stream_info() * - muxing: filled by the caller before avformat_write_header() */ AVCodecParameters *codecpar; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * Internal note: be aware that physically removing these fields * will break ABI. Replace removed fields with dummy fields, and * add new fields to AVStreamInternal. ***************************************************************** */ #define MAX_STD_TIMEBASES (30*12+30+3+6) /** * Stream information used internally by avformat_find_stream_info() */ struct { int64_t last_dts; int64_t duration_gcd; int duration_count; int64_t rfps_duration_sum; double (*duration_error)[2][MAX_STD_TIMEBASES]; int64_t codec_info_duration; int64_t codec_info_duration_fields; int frame_delay_evidence; /** * 0 -> decoder has not been searched for yet. * >0 -> decoder found * <0 -> decoder with codec_id == -found_decoder has not been found */ int found_decoder; int64_t last_duration; /** * Those are used for average framerate estimation. */ int64_t fps_first_dts; int fps_first_dts_idx; int64_t fps_last_dts; int fps_last_dts_idx; } *info; int pts_wrap_bits; /**< number of bits in pts (used for wrapping control) */ // Timestamp generation support: /** * Timestamp corresponding to the last dts sync point. * * Initialized when AVCodecParserContext.dts_sync_point >= 0 and * a DTS is received from the underlying container. Otherwise set to * AV_NOPTS_VALUE by default. */ int64_t first_dts; int64_t cur_dts; int64_t last_IP_pts; int last_IP_duration; /** * Number of packets to buffer for codec probing */ int probe_packets; /** * Number of frames that have been demuxed during avformat_find_stream_info() */ int codec_info_nb_frames; /* av_read_frame() support */ enum AVStreamParseType need_parsing; struct AVCodecParserContext *parser; /** * last packet in packet_buffer for this stream when muxing. */ struct AVPacketList *last_in_packet_buffer; AVProbeData probe_data; #define MAX_REORDER_DELAY 16 int64_t pts_buffer[MAX_REORDER_DELAY+1]; AVIndexEntry *index_entries; /**< Only used if the format does not support seeking natively. */ int nb_index_entries; unsigned int index_entries_allocated_size; /** * Stream Identifier * This is the MPEG-TS stream identifier +1 * 0 means unknown */ int stream_identifier; /** * Details of the MPEG-TS program which created this stream. */ int program_num; int pmt_version; int pmt_stream_idx; int64_t interleaver_chunk_size; int64_t interleaver_chunk_duration; /** * stream probing state * -1 -> probing finished * 0 -> no probing requested * rest -> perform probing with request_probe being the minimum score to accept. * NOT PART OF PUBLIC API */ int request_probe; /** * Indicates that everything up to the next keyframe * should be discarded. */ int skip_to_keyframe; /** * Number of samples to skip at the start of the frame decoded from the next packet. */ int skip_samples; /** * If not 0, the number of samples that should be skipped from the start of * the stream (the samples are removed from packets with pts==0, which also * assumes negative timestamps do not happen). * Intended for use with formats such as mp3 with ad-hoc gapless audio * support. */ int64_t start_skip_samples; /** * If not 0, the first audio sample that should be discarded from the stream. * This is broken by design (needs global sample count), but can't be * avoided for broken by design formats such as mp3 with ad-hoc gapless * audio support. */ int64_t first_discard_sample; /** * The sample after last sample that is intended to be discarded after * first_discard_sample. Works on frame boundaries only. Used to prevent * early EOF if the gapless info is broken (considered concatenated mp3s). */ int64_t last_discard_sample; /** * Number of internally decoded frames, used internally in libavformat, do not access * its lifetime differs from info which is why it is not in that structure. */ int nb_decoded_frames; /** * Timestamp offset added to timestamps before muxing * NOT PART OF PUBLIC API */ int64_t mux_ts_offset; /** * Internal data to check for wrapping of the time stamp */ int64_t pts_wrap_reference; /** * Options for behavior, when a wrap is detected. * * Defined by AV_PTS_WRAP_ values. * * If correction is enabled, there are two possibilities: * If the first time stamp is near the wrap point, the wrap offset * will be subtracted, which will create negative time stamps. * Otherwise the offset will be added. */ int pts_wrap_behavior; /** * Internal data to prevent doing update_initial_durations() twice */ int update_initial_durations_done; /** * Internal data to generate dts from pts */ int64_t pts_reorder_error[MAX_REORDER_DELAY+1]; uint8_t pts_reorder_error_count[MAX_REORDER_DELAY+1]; /** * Internal data to analyze DTS and detect faulty mpeg streams */ int64_t last_dts_for_order_check; uint8_t dts_ordered; uint8_t dts_misordered; /** * Internal data to inject global side data */ int inject_global_side_data; /** * display aspect ratio (0 if unknown) * - encoding: unused * - decoding: Set by libavformat to calculate sample_aspect_ratio internally */ AVRational display_aspect_ratio; /** * An opaque field for libavformat internal usage. * Must not be accessed in any way by callers. */ AVStreamInternal *internal; } AVStream; #if FF_API_FORMAT_GET_SET /** * Accessors for some AVStream fields. These used to be provided for ABI * compatibility, and do not need to be used anymore. */ attribute_deprecated AVRational av_stream_get_r_frame_rate(const AVStream *s); attribute_deprecated void av_stream_set_r_frame_rate(AVStream *s, AVRational r); #if FF_API_LAVF_FFSERVER attribute_deprecated char* av_stream_get_recommended_encoder_configuration(const AVStream *s); attribute_deprecated void av_stream_set_recommended_encoder_configuration(AVStream *s, char *configuration); #endif #endif struct AVCodecParserContext *av_stream_get_parser(const AVStream *s); /** * Returns the pts of the last muxed packet + its duration * * the retuned value is undefined when used with a demuxer. */ int64_t av_stream_get_end_pts(const AVStream *st); #define AV_PROGRAM_RUNNING 1 /** * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVProgram) must not be used outside libav*. */ typedef struct AVProgram { int id; int flags; enum AVDiscard discard; ///< selects which program to discard and which to feed to the caller unsigned int *stream_index; unsigned int nb_stream_indexes; AVDictionary *metadata; int program_num; int pmt_pid; int pcr_pid; int pmt_version; /***************************************************************** * All fields below this line are not part of the public API. They * may not be used outside of libavformat and can be changed and * removed at will. * New public fields should be added right above. ***************************************************************** */ int64_t start_time; int64_t end_time; int64_t pts_wrap_reference; ///< reference dts for wrap detection int pts_wrap_behavior; ///< behavior on wrap detection } AVProgram; #define AVFMTCTX_NOHEADER 0x0001 /**< signal that no header is present (streams are added dynamically) */ #define AVFMTCTX_UNSEEKABLE 0x0002 /**< signal that the stream is definitely not seekable, and attempts to call the seek function will fail. For some network protocols (e.g. HLS), this can change dynamically at runtime. */ typedef struct AVChapter { int id; ///< unique ID to identify the chapter AVRational time_base; ///< time base in which the start/end timestamps are specified int64_t start, end; ///< chapter start/end time in time_base units AVDictionary *metadata; } AVChapter; /** * Callback used by devices to communicate with application. */ typedef int (*av_format_control_message)(struct AVFormatContext *s, int type, void *data, size_t data_size); typedef int (*AVOpenCallback)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options); /** * The duration of a video can be estimated through various ways, and this enum can be used * to know how the duration was estimated. */ enum AVDurationEstimationMethod { AVFMT_DURATION_FROM_PTS, ///< Duration accurately estimated from PTSes AVFMT_DURATION_FROM_STREAM, ///< Duration estimated from a stream with a known duration AVFMT_DURATION_FROM_BITRATE ///< Duration estimated from bitrate (less accurate) }; typedef struct AVFormatInternal AVFormatInternal; /** * Format I/O context. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVFormatContext) must not be used outside libav*, use * avformat_alloc_context() to create an AVFormatContext. * * Fields can be accessed through AVOptions (av_opt*), * the name string used matches the associated command line parameter name and * can be found in libavformat/options_table.h. * The AVOption/command line parameter names differ in some cases from the C * structure field names for historic reasons or brevity. */ typedef struct AVFormatContext { /** * A class for logging and @ref avoptions. Set by avformat_alloc_context(). * Exports (de)muxer private options if they exist. */ const AVClass *av_class; /** * The input container format. * * Demuxing only, set by avformat_open_input(). */ ff_const59 struct AVInputFormat *iformat; /** * The output container format. * * Muxing only, must be set by the caller before avformat_write_header(). */ ff_const59 struct AVOutputFormat *oformat; /** * Format private data. This is an AVOptions-enabled struct * if and only if iformat/oformat.priv_class is not NULL. * * - muxing: set by avformat_write_header() * - demuxing: set by avformat_open_input() */ void *priv_data; /** * I/O context. * * - demuxing: either set by the user before avformat_open_input() (then * the user must close it manually) or set by avformat_open_input(). * - muxing: set by the user before avformat_write_header(). The caller must * take care of closing / freeing the IO context. * * Do NOT set this field if AVFMT_NOFILE flag is set in * iformat/oformat.flags. In such a case, the (de)muxer will handle * I/O in some other way and this field will be NULL. */ AVIOContext *pb; /* stream info */ /** * Flags signalling stream properties. A combination of AVFMTCTX_*. * Set by libavformat. */ int ctx_flags; /** * Number of elements in AVFormatContext.streams. * * Set by avformat_new_stream(), must not be modified by any other code. */ unsigned int nb_streams; /** * A list of all streams in the file. New streams are created with * avformat_new_stream(). * * - demuxing: streams are created by libavformat in avformat_open_input(). * If AVFMTCTX_NOHEADER is set in ctx_flags, then new streams may also * appear in av_read_frame(). * - muxing: streams are created by the user before avformat_write_header(). * * Freed by libavformat in avformat_free_context(). */ AVStream **streams; #if FF_API_FORMAT_FILENAME /** * input or output filename * * - demuxing: set by avformat_open_input() * - muxing: may be set by the caller before avformat_write_header() * * @deprecated Use url instead. */ attribute_deprecated char filename[1024]; #endif /** * input or output URL. Unlike the old filename field, this field has no * length restriction. * * - demuxing: set by avformat_open_input(), initialized to an empty * string if url parameter was NULL in avformat_open_input(). * - muxing: may be set by the caller before calling avformat_write_header() * (or avformat_init_output() if that is called first) to a string * which is freeable by av_free(). Set to an empty string if it * was NULL in avformat_init_output(). * * Freed by libavformat in avformat_free_context(). */ char *url; /** * Position of the first frame of the component, in * AV_TIME_BASE fractional seconds. NEVER set this value directly: * It is deduced from the AVStream values. * * Demuxing only, set by libavformat. */ int64_t start_time; /** * Duration of the stream, in AV_TIME_BASE fractional * seconds. Only set this value if you know none of the individual stream * durations and also do not set any of them. This is deduced from the * AVStream values if not set. * * Demuxing only, set by libavformat. */ int64_t duration; /** * Total stream bitrate in bit/s, 0 if not * available. Never set it directly if the file_size and the * duration are known as FFmpeg can compute it automatically. */ int64_t bit_rate; unsigned int packet_size; int max_delay; /** * Flags modifying the (de)muxer behaviour. A combination of AVFMT_FLAG_*. * Set by the user before avformat_open_input() / avformat_write_header(). */ int flags; #define AVFMT_FLAG_GENPTS 0x0001 ///< Generate missing pts even if it requires parsing future frames. #define AVFMT_FLAG_IGNIDX 0x0002 ///< Ignore index. #define AVFMT_FLAG_NONBLOCK 0x0004 ///< Do not block when reading packets from input. #define AVFMT_FLAG_IGNDTS 0x0008 ///< Ignore DTS on frames that contain both DTS & PTS #define AVFMT_FLAG_NOFILLIN 0x0010 ///< Do not infer any values from other values, just return what is stored in the container #define AVFMT_FLAG_NOPARSE 0x0020 ///< Do not use AVParsers, you also must set AVFMT_FLAG_NOFILLIN as the fillin code works on frames and no parsing -> no frames. Also seeking to frames can not work if parsing to find frame boundaries has been disabled #define AVFMT_FLAG_NOBUFFER 0x0040 ///< Do not buffer frames when possible #define AVFMT_FLAG_CUSTOM_IO 0x0080 ///< The caller has supplied a custom AVIOContext, don't avio_close() it. #define AVFMT_FLAG_DISCARD_CORRUPT 0x0100 ///< Discard frames marked corrupted #define AVFMT_FLAG_FLUSH_PACKETS 0x0200 ///< Flush the AVIOContext every packet. /** * When muxing, try to avoid writing any random/volatile data to the output. * This includes any random IDs, real-time timestamps/dates, muxer version, etc. * * This flag is mainly intended for testing. */ #define AVFMT_FLAG_BITEXACT 0x0400 #if FF_API_LAVF_MP4A_LATM #define AVFMT_FLAG_MP4A_LATM 0x8000 ///< Deprecated, does nothing. #endif #define AVFMT_FLAG_SORT_DTS 0x10000 ///< try to interleave outputted packets by dts (using this flag can slow demuxing down) #define AVFMT_FLAG_PRIV_OPT 0x20000 ///< Enable use of private options by delaying codec open (this could be made default once all code is converted) #if FF_API_LAVF_KEEPSIDE_FLAG #define AVFMT_FLAG_KEEP_SIDE_DATA 0x40000 ///< Deprecated, does nothing. #endif #define AVFMT_FLAG_FAST_SEEK 0x80000 ///< Enable fast, but inaccurate seeks for some formats #define AVFMT_FLAG_SHORTEST 0x100000 ///< Stop muxing when the shortest stream stops. #define AVFMT_FLAG_AUTO_BSF 0x200000 ///< Add bitstream filters as requested by the muxer /** * Maximum size of the data read from input for determining * the input container format. * Demuxing only, set by the caller before avformat_open_input(). */ int64_t probesize; /** * Maximum duration (in AV_TIME_BASE units) of the data read * from input in avformat_find_stream_info(). * Demuxing only, set by the caller before avformat_find_stream_info(). * Can be set to 0 to let avformat choose using a heuristic. */ int64_t max_analyze_duration; const uint8_t *key; int keylen; unsigned int nb_programs; AVProgram **programs; /** * Forced video codec_id. * Demuxing: Set by user. */ enum AVCodecID video_codec_id; /** * Forced audio codec_id. * Demuxing: Set by user. */ enum AVCodecID audio_codec_id; /** * Forced subtitle codec_id. * Demuxing: Set by user. */ enum AVCodecID subtitle_codec_id; /** * Maximum amount of memory in bytes to use for the index of each stream. * If the index exceeds this size, entries will be discarded as * needed to maintain a smaller size. This can lead to slower or less * accurate seeking (depends on demuxer). * Demuxers for which a full in-memory index is mandatory will ignore * this. * - muxing: unused * - demuxing: set by user */ unsigned int max_index_size; /** * Maximum amount of memory in bytes to use for buffering frames * obtained from realtime capture devices. */ unsigned int max_picture_buffer; /** * Number of chapters in AVChapter array. * When muxing, chapters are normally written in the file header, * so nb_chapters should normally be initialized before write_header * is called. Some muxers (e.g. mov and mkv) can also write chapters * in the trailer. To write chapters in the trailer, nb_chapters * must be zero when write_header is called and non-zero when * write_trailer is called. * - muxing: set by user * - demuxing: set by libavformat */ unsigned int nb_chapters; AVChapter **chapters; /** * Metadata that applies to the whole file. * * - demuxing: set by libavformat in avformat_open_input() * - muxing: may be set by the caller before avformat_write_header() * * Freed by libavformat in avformat_free_context(). */ AVDictionary *metadata; /** * Start time of the stream in real world time, in microseconds * since the Unix epoch (00:00 1st January 1970). That is, pts=0 in the * stream was captured at this real world time. * - muxing: Set by the caller before avformat_write_header(). If set to * either 0 or AV_NOPTS_VALUE, then the current wall-time will * be used. * - demuxing: Set by libavformat. AV_NOPTS_VALUE if unknown. Note that * the value may become known after some number of frames * have been received. */ int64_t start_time_realtime; /** * The number of frames used for determining the framerate in * avformat_find_stream_info(). * Demuxing only, set by the caller before avformat_find_stream_info(). */ int fps_probe_size; /** * Error recognition; higher values will detect more errors but may * misdetect some more or less valid parts as errors. * Demuxing only, set by the caller before avformat_open_input(). */ int error_recognition; /** * Custom interrupt callbacks for the I/O layer. * * demuxing: set by the user before avformat_open_input(). * muxing: set by the user before avformat_write_header() * (mainly useful for AVFMT_NOFILE formats). The callback * should also be passed to avio_open2() if it's used to * open the file. */ AVIOInterruptCB interrupt_callback; /** * Flags to enable debugging. */ int debug; #define FF_FDEBUG_TS 0x0001 /** * Maximum buffering duration for interleaving. * * To ensure all the streams are interleaved correctly, * av_interleaved_write_frame() will wait until it has at least one packet * for each stream before actually writing any packets to the output file. * When some streams are "sparse" (i.e. there are large gaps between * successive packets), this can result in excessive buffering. * * This field specifies the maximum difference between the timestamps of the * first and the last packet in the muxing queue, above which libavformat * will output a packet regardless of whether it has queued a packet for all * the streams. * * Muxing only, set by the caller before avformat_write_header(). */ int64_t max_interleave_delta; /** * Allow non-standard and experimental extension * @see AVCodecContext.strict_std_compliance */ int strict_std_compliance; /** * Flags for the user to detect events happening on the file. Flags must * be cleared by the user once the event has been handled. * A combination of AVFMT_EVENT_FLAG_*. */ int event_flags; #define AVFMT_EVENT_FLAG_METADATA_UPDATED 0x0001 ///< The call resulted in updated metadata. /** * Maximum number of packets to read while waiting for the first timestamp. * Decoding only. */ int max_ts_probe; /** * Avoid negative timestamps during muxing. * Any value of the AVFMT_AVOID_NEG_TS_* constants. * Note, this only works when using av_interleaved_write_frame. (interleave_packet_per_dts is in use) * - muxing: Set by user * - demuxing: unused */ int avoid_negative_ts; #define AVFMT_AVOID_NEG_TS_AUTO -1 ///< Enabled when required by target format #define AVFMT_AVOID_NEG_TS_MAKE_NON_NEGATIVE 1 ///< Shift timestamps so they are non negative #define AVFMT_AVOID_NEG_TS_MAKE_ZERO 2 ///< Shift timestamps so that they start at 0 /** * Transport stream id. * This will be moved into demuxer private options. Thus no API/ABI compatibility */ int ts_id; /** * Audio preload in microseconds. * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user * - decoding: unused */ int audio_preload; /** * Max chunk time in microseconds. * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user * - decoding: unused */ int max_chunk_duration; /** * Max chunk size in bytes * Note, not all formats support this and unpredictable things may happen if it is used when not supported. * - encoding: Set by user * - decoding: unused */ int max_chunk_size; /** * forces the use of wallclock timestamps as pts/dts of packets * This has undefined results in the presence of B frames. * - encoding: unused * - decoding: Set by user */ int use_wallclock_as_timestamps; /** * avio flags, used to force AVIO_FLAG_DIRECT. * - encoding: unused * - decoding: Set by user */ int avio_flags; /** * The duration field can be estimated through various ways, and this field can be used * to know how the duration was estimated. * - encoding: unused * - decoding: Read by user */ enum AVDurationEstimationMethod duration_estimation_method; /** * Skip initial bytes when opening stream * - encoding: unused * - decoding: Set by user */ int64_t skip_initial_bytes; /** * Correct single timestamp overflows * - encoding: unused * - decoding: Set by user */ unsigned int correct_ts_overflow; /** * Force seeking to any (also non key) frames. * - encoding: unused * - decoding: Set by user */ int seek2any; /** * Flush the I/O context after each packet. * - encoding: Set by user * - decoding: unused */ int flush_packets; /** * format probing score. * The maximal score is AVPROBE_SCORE_MAX, its set when the demuxer probes * the format. * - encoding: unused * - decoding: set by avformat, read by user */ int probe_score; /** * number of bytes to read maximally to identify format. * - encoding: unused * - decoding: set by user */ int format_probesize; /** * ',' separated list of allowed decoders. * If NULL then all are allowed * - encoding: unused * - decoding: set by user */ char *codec_whitelist; /** * ',' separated list of allowed demuxers. * If NULL then all are allowed * - encoding: unused * - decoding: set by user */ char *format_whitelist; /** * An opaque field for libavformat internal usage. * Must not be accessed in any way by callers. */ AVFormatInternal *internal; /** * IO repositioned flag. * This is set by avformat when the underlaying IO context read pointer * is repositioned, for example when doing byte based seeking. * Demuxers can use the flag to detect such changes. */ int io_repositioned; /** * Forced video codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user */ AVCodec *video_codec; /** * Forced audio codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user */ AVCodec *audio_codec; /** * Forced subtitle codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user */ AVCodec *subtitle_codec; /** * Forced data codec. * This allows forcing a specific decoder, even when there are multiple with * the same codec_id. * Demuxing: Set by user */ AVCodec *data_codec; /** * Number of bytes to be written as padding in a metadata header. * Demuxing: Unused. * Muxing: Set by user via av_format_set_metadata_header_padding. */ int metadata_header_padding; /** * User data. * This is a place for some private data of the user. */ void *opaque; /** * Callback used by devices to communicate with application. */ av_format_control_message control_message_cb; /** * Output timestamp offset, in microseconds. * Muxing: set by user */ int64_t output_ts_offset; /** * dump format separator. * can be ", " or "\n " or anything else * - muxing: Set by user. * - demuxing: Set by user. */ uint8_t *dump_separator; /** * Forced Data codec_id. * Demuxing: Set by user. */ enum AVCodecID data_codec_id; #if FF_API_OLD_OPEN_CALLBACKS /** * Called to open further IO contexts when needed for demuxing. * * This can be set by the user application to perform security checks on * the URLs before opening them. * The function should behave like avio_open2(), AVFormatContext is provided * as contextual information and to reach AVFormatContext.opaque. * * If NULL then some simple checks are used together with avio_open2(). * * Must not be accessed directly from outside avformat. * @See av_format_set_open_cb() * * Demuxing: Set by user. * * @deprecated Use io_open and io_close. */ attribute_deprecated int (*open_cb)(struct AVFormatContext *s, AVIOContext **p, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options); #endif /** * ',' separated list of allowed protocols. * - encoding: unused * - decoding: set by user */ char *protocol_whitelist; /** * A callback for opening new IO streams. * * Whenever a muxer or a demuxer needs to open an IO stream (typically from * avformat_open_input() for demuxers, but for certain formats can happen at * other times as well), it will call this callback to obtain an IO context. * * @param s the format context * @param pb on success, the newly opened IO context should be returned here * @param url the url to open * @param flags a combination of AVIO_FLAG_* * @param options a dictionary of additional options, with the same * semantics as in avio_open2() * @return 0 on success, a negative AVERROR code on failure * * @note Certain muxers and demuxers do nesting, i.e. they open one or more * additional internal format contexts. Thus the AVFormatContext pointer * passed to this callback may be different from the one facing the caller. * It will, however, have the same 'opaque' field. */ int (*io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options); /** * A callback for closing the streams opened with AVFormatContext.io_open(). */ void (*io_close)(struct AVFormatContext *s, AVIOContext *pb); /** * ',' separated list of disallowed protocols. * - encoding: unused * - decoding: set by user */ char *protocol_blacklist; /** * The maximum number of streams. * - encoding: unused * - decoding: set by user */ int max_streams; /** * Skip duration calcuation in estimate_timings_from_pts. * - encoding: unused * - decoding: set by user */ int skip_estimate_duration_from_pts; } AVFormatContext; #if FF_API_FORMAT_GET_SET /** * Accessors for some AVFormatContext fields. These used to be provided for ABI * compatibility, and do not need to be used anymore. */ attribute_deprecated int av_format_get_probe_score(const AVFormatContext *s); attribute_deprecated AVCodec * av_format_get_video_codec(const AVFormatContext *s); attribute_deprecated void av_format_set_video_codec(AVFormatContext *s, AVCodec *c); attribute_deprecated AVCodec * av_format_get_audio_codec(const AVFormatContext *s); attribute_deprecated void av_format_set_audio_codec(AVFormatContext *s, AVCodec *c); attribute_deprecated AVCodec * av_format_get_subtitle_codec(const AVFormatContext *s); attribute_deprecated void av_format_set_subtitle_codec(AVFormatContext *s, AVCodec *c); attribute_deprecated AVCodec * av_format_get_data_codec(const AVFormatContext *s); attribute_deprecated void av_format_set_data_codec(AVFormatContext *s, AVCodec *c); attribute_deprecated int av_format_get_metadata_header_padding(const AVFormatContext *s); attribute_deprecated void av_format_set_metadata_header_padding(AVFormatContext *s, int c); attribute_deprecated void * av_format_get_opaque(const AVFormatContext *s); attribute_deprecated void av_format_set_opaque(AVFormatContext *s, void *opaque); attribute_deprecated av_format_control_message av_format_get_control_message_cb(const AVFormatContext *s); attribute_deprecated void av_format_set_control_message_cb(AVFormatContext *s, av_format_control_message callback); #if FF_API_OLD_OPEN_CALLBACKS attribute_deprecated AVOpenCallback av_format_get_open_cb(const AVFormatContext *s); attribute_deprecated void av_format_set_open_cb(AVFormatContext *s, AVOpenCallback callback); #endif #endif /** * This function will cause global side data to be injected in the next packet * of each stream as well as after any subsequent seek. */ void av_format_inject_global_side_data(AVFormatContext *s); /** * Returns the method used to set ctx->duration. * * @return AVFMT_DURATION_FROM_PTS, AVFMT_DURATION_FROM_STREAM, or AVFMT_DURATION_FROM_BITRATE. */ enum AVDurationEstimationMethod av_fmt_ctx_get_duration_estimation_method(const AVFormatContext* ctx); typedef struct AVPacketList { AVPacket pkt; struct AVPacketList *next; } AVPacketList; /** * @defgroup lavf_core Core functions * @ingroup libavf * * Functions for querying libavformat capabilities, allocating core structures, * etc. * @{ */ /** * Return the LIBAVFORMAT_VERSION_INT constant. */ unsigned avformat_version(void); /** * Return the libavformat build-time configuration. */ const char *avformat_configuration(void); /** * Return the libavformat license. */ const char *avformat_license(void); #if FF_API_NEXT /** * Initialize libavformat and register all the muxers, demuxers and * protocols. If you do not call this function, then you can select * exactly which formats you want to support. * * @see av_register_input_format() * @see av_register_output_format() */ attribute_deprecated void av_register_all(void); attribute_deprecated void av_register_input_format(AVInputFormat *format); attribute_deprecated void av_register_output_format(AVOutputFormat *format); #endif /** * Do global initialization of network libraries. This is optional, * and not recommended anymore. * * This functions only exists to work around thread-safety issues * with older GnuTLS or OpenSSL libraries. If libavformat is linked * to newer versions of those libraries, or if you do not use them, * calling this function is unnecessary. Otherwise, you need to call * this function before any other threads using them are started. * * This function will be deprecated once support for older GnuTLS and * OpenSSL libraries is removed, and this function has no purpose * anymore. */ int avformat_network_init(void); /** * Undo the initialization done by avformat_network_init. Call it only * once for each time you called avformat_network_init. */ int avformat_network_deinit(void); #if FF_API_NEXT /** * If f is NULL, returns the first registered input format, * if f is non-NULL, returns the next registered input format after f * or NULL if f is the last one. */ attribute_deprecated AVInputFormat *av_iformat_next(const AVInputFormat *f); /** * If f is NULL, returns the first registered output format, * if f is non-NULL, returns the next registered output format after f * or NULL if f is the last one. */ attribute_deprecated AVOutputFormat *av_oformat_next(const AVOutputFormat *f); #endif /** * Iterate over all registered muxers. * * @param opaque a pointer where libavformat will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered muxer or NULL when the iteration is * finished */ const AVOutputFormat *av_muxer_iterate(void **opaque); /** * Iterate over all registered demuxers. * * @param opaque a pointer where libavformat will store the iteration state. Must * point to NULL to start the iteration. * * @return the next registered demuxer or NULL when the iteration is * finished */ const AVInputFormat *av_demuxer_iterate(void **opaque); /** * Allocate an AVFormatContext. * avformat_free_context() can be used to free the context and everything * allocated by the framework within it. */ AVFormatContext *avformat_alloc_context(void); /** * Free an AVFormatContext and all its streams. * @param s context to free */ void avformat_free_context(AVFormatContext *s); /** * Get the AVClass for AVFormatContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *avformat_get_class(void); /** * Add a new stream to a media file. * * When demuxing, it is called by the demuxer in read_header(). If the * flag AVFMTCTX_NOHEADER is set in s.ctx_flags, then it may also * be called in read_packet(). * * When muxing, should be called by the user before avformat_write_header(). * * User is required to call avcodec_close() and avformat_free_context() to * clean up the allocation by avformat_new_stream(). * * @param s media file handle * @param c If non-NULL, the AVCodecContext corresponding to the new stream * will be initialized to use this codec. This is needed for e.g. codec-specific * defaults to be set, so codec should be provided if it is known. * * @return newly created stream or NULL on error. */ AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c); /** * Wrap an existing array as stream side data. * * @param st stream * @param type side information type * @param data the side data array. It must be allocated with the av_malloc() * family of functions. The ownership of the data is transferred to * st. * @param size side information size * @return zero on success, a negative AVERROR code on failure. On failure, * the stream is unchanged and the data remains owned by the caller. */ int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type, uint8_t *data, size_t size); /** * Allocate new information from stream. * * @param stream stream * @param type desired side information type * @param size side information size * @return pointer to fresh allocated data or NULL otherwise */ uint8_t *av_stream_new_side_data(AVStream *stream, enum AVPacketSideDataType type, int size); /** * Get side information from stream. * * @param stream stream * @param type desired side information type * @param size pointer for side information size to store (optional) * @return pointer to data if present or NULL otherwise */ uint8_t *av_stream_get_side_data(const AVStream *stream, enum AVPacketSideDataType type, int *size); AVProgram *av_new_program(AVFormatContext *s, int id); /** * @} */ /** * Allocate an AVFormatContext for an output format. * avformat_free_context() can be used to free the context and * everything allocated by the framework within it. * * @param *ctx is set to the created format context, or to NULL in * case of failure * @param oformat format to use for allocating the context, if NULL * format_name and filename are used instead * @param format_name the name of output format to use for allocating the * context, if NULL filename is used instead * @param filename the name of the filename to use for allocating the * context, may be NULL * @return >= 0 in case of success, a negative AVERROR code in case of * failure */ int avformat_alloc_output_context2(AVFormatContext **ctx, ff_const59 AVOutputFormat *oformat, const char *format_name, const char *filename); /** * @addtogroup lavf_decoding * @{ */ /** * Find AVInputFormat based on the short name of the input format. */ ff_const59 AVInputFormat *av_find_input_format(const char *short_name); /** * Guess the file format. * * @param pd data to be probed * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. */ ff_const59 AVInputFormat *av_probe_input_format(ff_const59 AVProbeData *pd, int is_opened); /** * Guess the file format. * * @param pd data to be probed * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. * @param score_max A probe score larger that this is required to accept a * detection, the variable is set to the actual detection * score afterwards. * If the score is <= AVPROBE_SCORE_MAX / 4 it is recommended * to retry with a larger probe buffer. */ ff_const59 AVInputFormat *av_probe_input_format2(ff_const59 AVProbeData *pd, int is_opened, int *score_max); /** * Guess the file format. * * @param is_opened Whether the file is already opened; determines whether * demuxers with or without AVFMT_NOFILE are probed. * @param score_ret The score of the best detection. */ ff_const59 AVInputFormat *av_probe_input_format3(ff_const59 AVProbeData *pd, int is_opened, int *score_ret); /** * Probe a bytestream to determine the input format. Each time a probe returns * with a score that is too low, the probe buffer size is increased and another * attempt is made. When the maximum probe size is reached, the input format * with the highest score is returned. * * @param pb the bytestream to probe * @param fmt the input format is put here * @param url the url of the stream * @param logctx the log context * @param offset the offset within the bytestream to probe from * @param max_probe_size the maximum probe buffer size (zero for default) * @return the score in case of success, a negative value corresponding to an * the maximal score is AVPROBE_SCORE_MAX * AVERROR code otherwise */ int av_probe_input_buffer2(AVIOContext *pb, ff_const59 AVInputFormat **fmt, const char *url, void *logctx, unsigned int offset, unsigned int max_probe_size); /** * Like av_probe_input_buffer2() but returns 0 on success */ int av_probe_input_buffer(AVIOContext *pb, ff_const59 AVInputFormat **fmt, const char *url, void *logctx, unsigned int offset, unsigned int max_probe_size); /** * Open an input stream and read the header. The codecs are not opened. * The stream must be closed with avformat_close_input(). * * @param ps Pointer to user-supplied AVFormatContext (allocated by avformat_alloc_context). * May be a pointer to NULL, in which case an AVFormatContext is allocated by this * function and written into ps. * Note that a user-supplied AVFormatContext will be freed on failure. * @param url URL of the stream to open. * @param fmt If non-NULL, this parameter forces a specific input format. * Otherwise the format is autodetected. * @param options A dictionary filled with AVFormatContext and demuxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return 0 on success, a negative AVERROR on failure. * * @note If you want to use custom IO, preallocate the format context and set its pb field. */ int avformat_open_input(AVFormatContext **ps, const char *url, ff_const59 AVInputFormat *fmt, AVDictionary **options); attribute_deprecated int av_demuxer_open(AVFormatContext *ic); /** * Read packets of a media file to get stream information. This * is useful for file formats with no headers such as MPEG. This * function also computes the real framerate in case of MPEG-2 repeat * frame mode. * The logical file position is not changed by this function; * examined packets may be buffered for later processing. * * @param ic media file handle * @param options If non-NULL, an ic.nb_streams long array of pointers to * dictionaries, where i-th member contains options for * codec corresponding to i-th stream. * On return each dictionary will be filled with options that were not found. * @return >=0 if OK, AVERROR_xxx on error * * @note this function isn't guaranteed to open all the codecs, so * options being non-empty at return is a perfectly normal behavior. * * @todo Let the user decide somehow what information is needed so that * we do not waste time getting stuff the user does not need. */ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options); /** * Find the programs which belong to a given stream. * * @param ic media file handle * @param last the last found program, the search will start after this * program, or from the beginning if it is NULL * @param s stream index * @return the next program which belongs to s, NULL if no program is found or * the last program is not among the programs of ic. */ AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s); void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx); /** * Find the "best" stream in the file. * The best stream is determined according to various heuristics as the most * likely to be what the user expects. * If the decoder parameter is non-NULL, av_find_best_stream will find the * default decoder for the stream's codec; streams for which no decoder can * be found are ignored. * * @param ic media file handle * @param type stream type: video, audio, subtitles, etc. * @param wanted_stream_nb user-requested stream number, * or -1 for automatic selection * @param related_stream try to find a stream related (eg. in the same * program) to this one, or -1 if none * @param decoder_ret if non-NULL, returns the decoder for the * selected stream * @param flags flags; none are currently defined * @return the non-negative stream number in case of success, * AVERROR_STREAM_NOT_FOUND if no stream with the requested type * could be found, * AVERROR_DECODER_NOT_FOUND if streams were found but no decoder * @note If av_find_best_stream returns successfully and decoder_ret is not * NULL, then *decoder_ret is guaranteed to be set to a valid AVCodec. */ int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type, int wanted_stream_nb, int related_stream, AVCodec **decoder_ret, int flags); /** * Return the next frame of a stream. * This function returns what is stored in the file, and does not validate * that what is there are valid frames for the decoder. It will split what is * stored in the file into frames and return one for each call. It will not * omit invalid data between valid frames so as to give the decoder the maximum * information possible for decoding. * * If pkt->buf is NULL, then the packet is valid until the next * av_read_frame() or until avformat_close_input(). Otherwise the packet * is valid indefinitely. In both cases the packet must be freed with * av_packet_unref when it is no longer needed. For video, the packet contains * exactly one frame. For audio, it contains an integer number of frames if each * frame has a known fixed size (e.g. PCM or ADPCM data). If the audio frames * have a variable size (e.g. MPEG audio), then it contains one frame. * * pkt->pts, pkt->dts and pkt->duration are always set to correct * values in AVStream.time_base units (and guessed if the format cannot * provide them). pkt->pts can be AV_NOPTS_VALUE if the video format * has B-frames, so it is better to rely on pkt->dts if you do not * decompress the payload. * * @return 0 if OK, < 0 on error or end of file */ int av_read_frame(AVFormatContext *s, AVPacket *pkt); /** * Seek to the keyframe at timestamp. * 'timestamp' in 'stream_index'. * * @param s media file handle * @param stream_index If stream_index is (-1), a default * stream is selected, and timestamp is automatically converted * from AV_TIME_BASE units to the stream specific time_base. * @param timestamp Timestamp in AVStream.time_base units * or, if no stream is specified, in AV_TIME_BASE units. * @param flags flags which select direction and seeking mode * @return >= 0 on success */ int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags); /** * Seek to timestamp ts. * Seeking will be done so that the point from which all active streams * can be presented successfully will be closest to ts and within min/max_ts. * Active streams are all streams that have AVStream.discard < AVDISCARD_ALL. * * If flags contain AVSEEK_FLAG_BYTE, then all timestamps are in bytes and * are the file position (this may not be supported by all demuxers). * If flags contain AVSEEK_FLAG_FRAME, then all timestamps are in frames * in the stream with stream_index (this may not be supported by all demuxers). * Otherwise all timestamps are in units of the stream selected by stream_index * or if stream_index is -1, in AV_TIME_BASE units. * If flags contain AVSEEK_FLAG_ANY, then non-keyframes are treated as * keyframes (this may not be supported by all demuxers). * If flags contain AVSEEK_FLAG_BACKWARD, it is ignored. * * @param s media file handle * @param stream_index index of the stream which is used as time base reference * @param min_ts smallest acceptable timestamp * @param ts target timestamp * @param max_ts largest acceptable timestamp * @param flags flags * @return >=0 on success, error code otherwise * * @note This is part of the new seek API which is still under construction. * Thus do not use this yet. It may change at any time, do not expect * ABI compatibility yet! */ int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags); /** * Discard all internally buffered data. This can be useful when dealing with * discontinuities in the byte stream. Generally works only with formats that * can resync. This includes headerless formats like MPEG-TS/TS but should also * work with NUT, Ogg and in a limited way AVI for example. * * The set of streams, the detected duration, stream parameters and codecs do * not change when calling this function. If you want a complete reset, it's * better to open a new AVFormatContext. * * This does not flush the AVIOContext (s->pb). If necessary, call * avio_flush(s->pb) before calling this function. * * @param s media file handle * @return >=0 on success, error code otherwise */ int avformat_flush(AVFormatContext *s); /** * Start playing a network-based stream (e.g. RTSP stream) at the * current position. */ int av_read_play(AVFormatContext *s); /** * Pause a network-based stream (e.g. RTSP stream). * * Use av_read_play() to resume it. */ int av_read_pause(AVFormatContext *s); /** * Close an opened input AVFormatContext. Free it and all its contents * and set *s to NULL. */ void avformat_close_input(AVFormatContext **s); /** * @} */ #define AVSEEK_FLAG_BACKWARD 1 ///< seek backward #define AVSEEK_FLAG_BYTE 2 ///< seeking based on position in bytes #define AVSEEK_FLAG_ANY 4 ///< seek to any frame, even non-keyframes #define AVSEEK_FLAG_FRAME 8 ///< seeking based on frame number /** * @addtogroup lavf_encoding * @{ */ #define AVSTREAM_INIT_IN_WRITE_HEADER 0 ///< stream parameters initialized in avformat_write_header #define AVSTREAM_INIT_IN_INIT_OUTPUT 1 ///< stream parameters initialized in avformat_init_output /** * Allocate the stream private data and write the stream header to * an output media file. * * @param s Media file handle, must be allocated with avformat_alloc_context(). * Its oformat field must be set to the desired output format; * Its pb field must be set to an already opened AVIOContext. * @param options An AVDictionary filled with AVFormatContext and muxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return AVSTREAM_INIT_IN_WRITE_HEADER on success if the codec had not already been fully initialized in avformat_init, * AVSTREAM_INIT_IN_INIT_OUTPUT on success if the codec had already been fully initialized in avformat_init, * negative AVERROR on failure. * * @see av_opt_find, av_dict_set, avio_open, av_oformat_next, avformat_init_output. */ av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options); /** * Allocate the stream private data and initialize the codec, but do not write the header. * May optionally be used before avformat_write_header to initialize stream parameters * before actually writing the header. * If using this function, do not pass the same options to avformat_write_header. * * @param s Media file handle, must be allocated with avformat_alloc_context(). * Its oformat field must be set to the desired output format; * Its pb field must be set to an already opened AVIOContext. * @param options An AVDictionary filled with AVFormatContext and muxer-private options. * On return this parameter will be destroyed and replaced with a dict containing * options that were not found. May be NULL. * * @return AVSTREAM_INIT_IN_WRITE_HEADER on success if the codec requires avformat_write_header to fully initialize, * AVSTREAM_INIT_IN_INIT_OUTPUT on success if the codec has been fully initialized, * negative AVERROR on failure. * * @see av_opt_find, av_dict_set, avio_open, av_oformat_next, avformat_write_header. */ av_warn_unused_result int avformat_init_output(AVFormatContext *s, AVDictionary **options); /** * Write a packet to an output media file. * * This function passes the packet directly to the muxer, without any buffering * or reordering. The caller is responsible for correctly interleaving the * packets if the format requires it. Callers that want libavformat to handle * the interleaving should call av_interleaved_write_frame() instead of this * function. * * @param s media file handle * @param pkt The packet containing the data to be written. Note that unlike * av_interleaved_write_frame(), this function does not take * ownership of the packet passed to it (though some muxers may make * an internal reference to the input packet). *
* This parameter can be NULL (at any time, not just at the end), in * order to immediately flush data buffered within the muxer, for * muxers that buffer up data internally before writing it to the * output. *
* Packet's @ref AVPacket.stream_index "stream_index" field must be * set to the index of the corresponding stream in @ref * AVFormatContext.streams "s->streams". *
* The timestamps (@ref AVPacket.pts "pts", @ref AVPacket.dts "dts") * must be set to correct values in the stream's timebase (unless the * output format is flagged with the AVFMT_NOTIMESTAMPS flag, then * they can be set to AV_NOPTS_VALUE). * The dts for subsequent packets passed to this function must be strictly * increasing when compared in their respective timebases (unless the * output format is flagged with the AVFMT_TS_NONSTRICT, then they * merely have to be nondecreasing). @ref AVPacket.duration * "duration") should also be set if known. * @return < 0 on error, = 0 if OK, 1 if flushed and there is no more data to flush * * @see av_interleaved_write_frame() */ int av_write_frame(AVFormatContext *s, AVPacket *pkt); /** * Write a packet to an output media file ensuring correct interleaving. * * This function will buffer the packets internally as needed to make sure the * packets in the output file are properly interleaved in the order of * increasing dts. Callers doing their own interleaving should call * av_write_frame() instead of this function. * * Using this function instead of av_write_frame() can give muxers advance * knowledge of future packets, improving e.g. the behaviour of the mp4 * muxer for VFR content in fragmenting mode. * * @param s media file handle * @param pkt The packet containing the data to be written. *
* If the packet is reference-counted, this function will take * ownership of this reference and unreference it later when it sees * fit. * The caller must not access the data through this reference after * this function returns. If the packet is not reference-counted, * libavformat will make a copy. *
* This parameter can be NULL (at any time, not just at the end), to * flush the interleaving queues. *
* Packet's @ref AVPacket.stream_index "stream_index" field must be * set to the index of the corresponding stream in @ref * AVFormatContext.streams "s->streams". *
* The timestamps (@ref AVPacket.pts "pts", @ref AVPacket.dts "dts") * must be set to correct values in the stream's timebase (unless the * output format is flagged with the AVFMT_NOTIMESTAMPS flag, then * they can be set to AV_NOPTS_VALUE). * The dts for subsequent packets in one stream must be strictly * increasing (unless the output format is flagged with the * AVFMT_TS_NONSTRICT, then they merely have to be nondecreasing). * @ref AVPacket.duration "duration") should also be set if known. * * @return 0 on success, a negative AVERROR on error. Libavformat will always * take care of freeing the packet, even if this function fails. * * @see av_write_frame(), AVFormatContext.max_interleave_delta */ int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt); /** * Write an uncoded frame to an output media file. * * The frame must be correctly interleaved according to the container * specification; if not, then av_interleaved_write_frame() must be used. * * See av_interleaved_write_frame() for details. */ int av_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame); /** * Write an uncoded frame to an output media file. * * If the muxer supports it, this function makes it possible to write an AVFrame * structure directly, without encoding it into a packet. * It is mostly useful for devices and similar special muxers that use raw * video or PCM data and will not serialize it into a byte stream. * * To test whether it is possible to use it with a given muxer and stream, * use av_write_uncoded_frame_query(). * * The caller gives up ownership of the frame and must not access it * afterwards. * * @return >=0 for success, a negative code on error */ int av_interleaved_write_uncoded_frame(AVFormatContext *s, int stream_index, AVFrame *frame); /** * Test whether a muxer supports uncoded frame. * * @return >=0 if an uncoded frame can be written to that muxer and stream, * <0 if not */ int av_write_uncoded_frame_query(AVFormatContext *s, int stream_index); /** * Write the stream trailer to an output media file and free the * file private data. * * May only be called after a successful call to avformat_write_header. * * @param s media file handle * @return 0 if OK, AVERROR_xxx on error */ int av_write_trailer(AVFormatContext *s); /** * Return the output format in the list of registered output formats * which best matches the provided parameters, or return NULL if * there is no match. * * @param short_name if non-NULL checks if short_name matches with the * names of the registered formats * @param filename if non-NULL checks if filename terminates with the * extensions of the registered formats * @param mime_type if non-NULL checks if mime_type matches with the * MIME type of the registered formats */ ff_const59 AVOutputFormat *av_guess_format(const char *short_name, const char *filename, const char *mime_type); /** * Guess the codec ID based upon muxer and filename. */ enum AVCodecID av_guess_codec(ff_const59 AVOutputFormat *fmt, const char *short_name, const char *filename, const char *mime_type, enum AVMediaType type); /** * Get timing information for the data currently output. * The exact meaning of "currently output" depends on the format. * It is mostly relevant for devices that have an internal buffer and/or * work in real time. * @param s media file handle * @param stream stream in the media file * @param[out] dts DTS of the last packet output for the stream, in stream * time_base units * @param[out] wall absolute time when that packet whas output, * in microsecond * @return 0 if OK, AVERROR(ENOSYS) if the format does not support it * Note: some formats or devices may not allow to measure dts and wall * atomically. */ int av_get_output_timestamp(struct AVFormatContext *s, int stream, int64_t *dts, int64_t *wall); /** * @} */ /** * @defgroup lavf_misc Utility functions * @ingroup libavf * @{ * * Miscellaneous utility functions related to both muxing and demuxing * (or neither). */ /** * Send a nice hexadecimal dump of a buffer to the specified file stream. * * @param f The file stream pointer where the dump should be sent to. * @param buf buffer * @param size buffer size * * @see av_hex_dump_log, av_pkt_dump2, av_pkt_dump_log2 */ void av_hex_dump(FILE *f, const uint8_t *buf, int size); /** * Send a nice hexadecimal dump of a buffer to the log. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message, lower values signifying * higher importance. * @param buf buffer * @param size buffer size * * @see av_hex_dump, av_pkt_dump2, av_pkt_dump_log2 */ void av_hex_dump_log(void *avcl, int level, const uint8_t *buf, int size); /** * Send a nice dump of a packet to the specified file stream. * * @param f The file stream pointer where the dump should be sent to. * @param pkt packet to dump * @param dump_payload True if the payload must be displayed, too. * @param st AVStream that the packet belongs to */ void av_pkt_dump2(FILE *f, const AVPacket *pkt, int dump_payload, const AVStream *st); /** * Send a nice dump of a packet to the log. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message, lower values signifying * higher importance. * @param pkt packet to dump * @param dump_payload True if the payload must be displayed, too. * @param st AVStream that the packet belongs to */ void av_pkt_dump_log2(void *avcl, int level, const AVPacket *pkt, int dump_payload, const AVStream *st); /** * Get the AVCodecID for the given codec tag tag. * If no codec id is found returns AV_CODEC_ID_NONE. * * @param tags list of supported codec_id-codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param tag codec tag to match to a codec ID */ enum AVCodecID av_codec_get_id(const struct AVCodecTag * const *tags, unsigned int tag); /** * Get the codec tag for the given codec id id. * If no codec tag is found returns 0. * * @param tags list of supported codec_id-codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param id codec ID to match to a codec tag */ unsigned int av_codec_get_tag(const struct AVCodecTag * const *tags, enum AVCodecID id); /** * Get the codec tag for the given codec id. * * @param tags list of supported codec_id - codec_tag pairs, as stored * in AVInputFormat.codec_tag and AVOutputFormat.codec_tag * @param id codec id that should be searched for in the list * @param tag A pointer to the found tag * @return 0 if id was not found in tags, > 0 if it was found */ int av_codec_get_tag2(const struct AVCodecTag * const *tags, enum AVCodecID id, unsigned int *tag); int av_find_default_stream_index(AVFormatContext *s); /** * Get the index for a specific timestamp. * * @param st stream that the timestamp belongs to * @param timestamp timestamp to retrieve the index for * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond * to the timestamp which is <= the requested one, if backward * is 0, then it will be >= * if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise * @return < 0 if no such timestamp could be found */ int av_index_search_timestamp(AVStream *st, int64_t timestamp, int flags); /** * Add an index entry into a sorted list. Update the entry if the list * already contains it. * * @param timestamp timestamp in the time base of the given stream */ int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags); /** * Split a URL string into components. * * The pointers to buffers for storing individual components may be null, * in order to ignore that component. Buffers for components not found are * set to empty strings. If the port is not found, it is set to a negative * value. * * @param proto the buffer for the protocol * @param proto_size the size of the proto buffer * @param authorization the buffer for the authorization * @param authorization_size the size of the authorization buffer * @param hostname the buffer for the host name * @param hostname_size the size of the hostname buffer * @param port_ptr a pointer to store the port number in * @param path the buffer for the path * @param path_size the size of the path buffer * @param url the URL to split */ void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url); /** * Print detailed information about the input or output format, such as * duration, bitrate, streams, container, programs, metadata, side data, * codec and time base. * * @param ic the context to analyze * @param index index of the stream to dump information about * @param url the URL to print, such as source or destination file * @param is_output Select whether the specified context is an input(0) or output(1) */ void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output); #define AV_FRAME_FILENAME_FLAGS_MULTIPLE 1 ///< Allow multiple %d /** * Return in 'buf' the path with '%d' replaced by a number. * * Also handles the '%0nd' format where 'n' is the total number * of digits and '%%'. * * @param buf destination buffer * @param buf_size destination buffer size * @param path numbered sequence string * @param number frame number * @param flags AV_FRAME_FILENAME_FLAGS_* * @return 0 if OK, -1 on format error */ int av_get_frame_filename2(char *buf, int buf_size, const char *path, int number, int flags); int av_get_frame_filename(char *buf, int buf_size, const char *path, int number); /** * Check whether filename actually is a numbered sequence generator. * * @param filename possible numbered sequence string * @return 1 if a valid numbered sequence string, 0 otherwise */ int av_filename_number_test(const char *filename); /** * Generate an SDP for an RTP session. * * Note, this overwrites the id values of AVStreams in the muxer contexts * for getting unique dynamic payload types. * * @param ac array of AVFormatContexts describing the RTP streams. If the * array is composed by only one context, such context can contain * multiple AVStreams (one AVStream per RTP stream). Otherwise, * all the contexts in the array (an AVCodecContext per RTP stream) * must contain only one AVStream. * @param n_files number of AVCodecContexts contained in ac * @param buf buffer where the SDP will be stored (must be allocated by * the caller) * @param size the size of the buffer * @return 0 if OK, AVERROR_xxx on error */ int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size); /** * Return a positive value if the given filename has one of the given * extensions, 0 otherwise. * * @param filename file name to check against the given extensions * @param extensions a comma-separated list of filename extensions */ int av_match_ext(const char *filename, const char *extensions); /** * Test if the given container can store a codec. * * @param ofmt container to check for compatibility * @param codec_id codec to potentially store in container * @param std_compliance standards compliance level, one of FF_COMPLIANCE_* * * @return 1 if codec with ID codec_id can be stored in ofmt, 0 if it cannot. * A negative number if this information is not available. */ int avformat_query_codec(const AVOutputFormat *ofmt, enum AVCodecID codec_id, int std_compliance); /** * @defgroup riff_fourcc RIFF FourCCs * @{ * Get the tables mapping RIFF FourCCs to libavcodec AVCodecIDs. The tables are * meant to be passed to av_codec_get_id()/av_codec_get_tag() as in the * following code: * @code * uint32_t tag = MKTAG('H', '2', '6', '4'); * const struct AVCodecTag *table[] = { avformat_get_riff_video_tags(), 0 }; * enum AVCodecID id = av_codec_get_id(table, tag); * @endcode */ /** * @return the table mapping RIFF FourCCs for video to libavcodec AVCodecID. */ const struct AVCodecTag *avformat_get_riff_video_tags(void); /** * @return the table mapping RIFF FourCCs for audio to AVCodecID. */ const struct AVCodecTag *avformat_get_riff_audio_tags(void); /** * @return the table mapping MOV FourCCs for video to libavcodec AVCodecID. */ const struct AVCodecTag *avformat_get_mov_video_tags(void); /** * @return the table mapping MOV FourCCs for audio to AVCodecID. */ const struct AVCodecTag *avformat_get_mov_audio_tags(void); /** * @} */ /** * Guess the sample aspect ratio of a frame, based on both the stream and the * frame aspect ratio. * * Since the frame aspect ratio is set by the codec but the stream aspect ratio * is set by the demuxer, these two may not be equal. This function tries to * return the value that you should use if you would like to display the frame. * * Basic logic is to use the stream aspect ratio if it is set to something sane * otherwise use the frame aspect ratio. This way a container setting, which is * usually easy to modify can override the coded value in the frames. * * @param format the format context which the stream is part of * @param stream the stream which the frame is part of * @param frame the frame with the aspect ratio to be determined * @return the guessed (valid) sample_aspect_ratio, 0/1 if no idea */ AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame); /** * Guess the frame rate, based on both the container and codec information. * * @param ctx the format context which the stream is part of * @param stream the stream which the frame is part of * @param frame the frame for which the frame rate should be determined, may be NULL * @return the guessed (valid) frame rate, 0/1 if no idea */ AVRational av_guess_frame_rate(AVFormatContext *ctx, AVStream *stream, AVFrame *frame); /** * Check if the stream st contained in s is matched by the stream specifier * spec. * * See the "stream specifiers" chapter in the documentation for the syntax * of spec. * * @return >0 if st is matched by spec; * 0 if st is not matched by spec; * AVERROR code if spec is invalid * * @note A stream specifier can match several streams in the format. */ int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec); int avformat_queue_attached_pictures(AVFormatContext *s); #if FF_API_OLD_BSF /** * Apply a list of bitstream filters to a packet. * * @param codec AVCodecContext, usually from an AVStream * @param pkt the packet to apply filters to. If, on success, the returned * packet has size == 0 and side_data_elems == 0, it indicates that * the packet should be dropped * @param bsfc a NULL-terminated list of filters to apply * @return >=0 on success; * AVERROR code on failure */ attribute_deprecated int av_apply_bitstream_filters(AVCodecContext *codec, AVPacket *pkt, AVBitStreamFilterContext *bsfc); #endif enum AVTimebaseSource { AVFMT_TBCF_AUTO = -1, AVFMT_TBCF_DECODER, AVFMT_TBCF_DEMUXER, #if FF_API_R_FRAME_RATE AVFMT_TBCF_R_FRAMERATE, #endif }; /** * Transfer internal timing information from one stream to another. * * This function is useful when doing stream copy. * * @param ofmt target output format for ost * @param ost output stream which needs timings copy and adjustments * @param ist reference input stream to copy timings from * @param copy_tb define from where the stream codec timebase needs to be imported */ int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt, AVStream *ost, const AVStream *ist, enum AVTimebaseSource copy_tb); /** * Get the internal codec timebase from a stream. * * @param st input stream to extract the timebase from */ AVRational av_stream_get_codec_timebase(const AVStream *st); /** * @} */ #endif /* AVFORMAT_AVFORMAT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavformat/avio.h ================================================ /* * copyright (c) 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_AVIO_H #define AVFORMAT_AVIO_H /** * @file * @ingroup lavf_io * Buffered I/O operations */ #include #include "libavutil/common.h" #include "libavutil/dict.h" #include "libavutil/log.h" #include "libavformat/version.h" /** * Seeking works like for a local file. */ #define AVIO_SEEKABLE_NORMAL (1 << 0) /** * Seeking by timestamp with avio_seek_time() is possible. */ #define AVIO_SEEKABLE_TIME (1 << 1) /** * Callback for checking whether to abort blocking functions. * AVERROR_EXIT is returned in this case by the interrupted * function. During blocking operations, callback is called with * opaque as parameter. If the callback returns 1, the * blocking operation will be aborted. * * No members can be added to this struct without a major bump, if * new elements have been added after this struct in AVFormatContext * or AVIOContext. */ typedef struct AVIOInterruptCB { int (*callback)(void*); void *opaque; } AVIOInterruptCB; /** * Directory entry types. */ enum AVIODirEntryType { AVIO_ENTRY_UNKNOWN, AVIO_ENTRY_BLOCK_DEVICE, AVIO_ENTRY_CHARACTER_DEVICE, AVIO_ENTRY_DIRECTORY, AVIO_ENTRY_NAMED_PIPE, AVIO_ENTRY_SYMBOLIC_LINK, AVIO_ENTRY_SOCKET, AVIO_ENTRY_FILE, AVIO_ENTRY_SERVER, AVIO_ENTRY_SHARE, AVIO_ENTRY_WORKGROUP, }; /** * Describes single entry of the directory. * * Only name and type fields are guaranteed be set. * Rest of fields are protocol or/and platform dependent and might be unknown. */ typedef struct AVIODirEntry { char *name; /**< Filename */ int type; /**< Type of the entry */ int utf8; /**< Set to 1 when name is encoded with UTF-8, 0 otherwise. Name can be encoded with UTF-8 even though 0 is set. */ int64_t size; /**< File size in bytes, -1 if unknown. */ int64_t modification_timestamp; /**< Time of last modification in microseconds since unix epoch, -1 if unknown. */ int64_t access_timestamp; /**< Time of last access in microseconds since unix epoch, -1 if unknown. */ int64_t status_change_timestamp; /**< Time of last status change in microseconds since unix epoch, -1 if unknown. */ int64_t user_id; /**< User ID of owner, -1 if unknown. */ int64_t group_id; /**< Group ID of owner, -1 if unknown. */ int64_t filemode; /**< Unix file mode, -1 if unknown. */ } AVIODirEntry; typedef struct AVIODirContext { struct URLContext *url_context; } AVIODirContext; /** * Different data types that can be returned via the AVIO * write_data_type callback. */ enum AVIODataMarkerType { /** * Header data; this needs to be present for the stream to be decodeable. */ AVIO_DATA_MARKER_HEADER, /** * A point in the output bytestream where a decoder can start decoding * (i.e. a keyframe). A demuxer/decoder given the data flagged with * AVIO_DATA_MARKER_HEADER, followed by any AVIO_DATA_MARKER_SYNC_POINT, * should give decodeable results. */ AVIO_DATA_MARKER_SYNC_POINT, /** * A point in the output bytestream where a demuxer can start parsing * (for non self synchronizing bytestream formats). That is, any * non-keyframe packet start point. */ AVIO_DATA_MARKER_BOUNDARY_POINT, /** * This is any, unlabelled data. It can either be a muxer not marking * any positions at all, it can be an actual boundary/sync point * that the muxer chooses not to mark, or a later part of a packet/fragment * that is cut into multiple write callbacks due to limited IO buffer size. */ AVIO_DATA_MARKER_UNKNOWN, /** * Trailer data, which doesn't contain actual content, but only for * finalizing the output file. */ AVIO_DATA_MARKER_TRAILER, /** * A point in the output bytestream where the underlying AVIOContext might * flush the buffer depending on latency or buffering requirements. Typically * means the end of a packet. */ AVIO_DATA_MARKER_FLUSH_POINT, }; /** * Bytestream IO Context. * New fields can be added to the end with minor version bumps. * Removal, reordering and changes to existing fields require a major * version bump. * sizeof(AVIOContext) must not be used outside libav*. * * @note None of the function pointers in AVIOContext should be called * directly, they should only be set by the client application * when implementing custom I/O. Normally these are set to the * function pointers specified in avio_alloc_context() */ typedef struct AVIOContext { /** * A class for private options. * * If this AVIOContext is created by avio_open2(), av_class is set and * passes the options down to protocols. * * If this AVIOContext is manually allocated, then av_class may be set by * the caller. * * warning -- this field can be NULL, be sure to not pass this AVIOContext * to any av_opt_* functions in that case. */ const AVClass *av_class; /* * The following shows the relationship between buffer, buf_ptr, * buf_ptr_max, buf_end, buf_size, and pos, when reading and when writing * (since AVIOContext is used for both): * ********************************************************************************** * READING ********************************************************************************** * * | buffer_size | * |---------------------------------------| * | | * * buffer buf_ptr buf_end * +---------------+-----------------------+ * |/ / / / / / / /|/ / / / / / /| | * read buffer: |/ / consumed / | to be read /| | * |/ / / / / / / /|/ / / / / / /| | * +---------------+-----------------------+ * * pos * +-------------------------------------------+-----------------+ * input file: | | | * +-------------------------------------------+-----------------+ * * ********************************************************************************** * WRITING ********************************************************************************** * * | buffer_size | * |--------------------------------------| * | | * * buf_ptr_max * buffer (buf_ptr) buf_end * +-----------------------+--------------+ * |/ / / / / / / / / / / /| | * write buffer: | / / to be flushed / / | | * |/ / / / / / / / / / / /| | * +-----------------------+--------------+ * buf_ptr can be in this * due to a backward seek * * pos * +-------------+----------------------------------------------+ * output file: | | | * +-------------+----------------------------------------------+ * */ unsigned char *buffer; /**< Start of the buffer. */ int buffer_size; /**< Maximum buffer size */ unsigned char *buf_ptr; /**< Current position in the buffer */ unsigned char *buf_end; /**< End of the data, may be less than buffer+buffer_size if the read function returned less data than requested, e.g. for streams where no more data has been received yet. */ void *opaque; /**< A private pointer, passed to the read/write/seek/... functions. */ int (*read_packet)(void *opaque, uint8_t *buf, int buf_size); int (*write_packet)(void *opaque, uint8_t *buf, int buf_size); int64_t (*seek)(void *opaque, int64_t offset, int whence); int64_t pos; /**< position in the file of the current buffer */ int eof_reached; /**< true if was unable to read due to error or eof */ int write_flag; /**< true if open for writing */ int max_packet_size; unsigned long checksum; unsigned char *checksum_ptr; unsigned long (*update_checksum)(unsigned long checksum, const uint8_t *buf, unsigned int size); int error; /**< contains the error code or 0 if no error happened */ /** * Pause or resume playback for network streaming protocols - e.g. MMS. */ int (*read_pause)(void *opaque, int pause); /** * Seek to a given timestamp in stream with the specified stream_index. * Needed for some network streaming protocols which don't support seeking * to byte position. */ int64_t (*read_seek)(void *opaque, int stream_index, int64_t timestamp, int flags); /** * A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable. */ int seekable; /** * max filesize, used to limit allocations * This field is internal to libavformat and access from outside is not allowed. */ int64_t maxsize; /** * avio_read and avio_write should if possible be satisfied directly * instead of going through a buffer, and avio_seek will always * call the underlying seek function directly. */ int direct; /** * Bytes read statistic * This field is internal to libavformat and access from outside is not allowed. */ int64_t bytes_read; /** * seek statistic * This field is internal to libavformat and access from outside is not allowed. */ int seek_count; /** * writeout statistic * This field is internal to libavformat and access from outside is not allowed. */ int writeout_count; /** * Original buffer size * used internally after probing and ensure seekback to reset the buffer size * This field is internal to libavformat and access from outside is not allowed. */ int orig_buffer_size; /** * Threshold to favor readahead over seek. * This is current internal only, do not use from outside. */ int short_seek_threshold; /** * ',' separated list of allowed protocols. */ const char *protocol_whitelist; /** * ',' separated list of disallowed protocols. */ const char *protocol_blacklist; /** * A callback that is used instead of write_packet. */ int (*write_data_type)(void *opaque, uint8_t *buf, int buf_size, enum AVIODataMarkerType type, int64_t time); /** * If set, don't call write_data_type separately for AVIO_DATA_MARKER_BOUNDARY_POINT, * but ignore them and treat them as AVIO_DATA_MARKER_UNKNOWN (to avoid needlessly * small chunks of data returned from the callback). */ int ignore_boundary_point; /** * Internal, not meant to be used from outside of AVIOContext. */ enum AVIODataMarkerType current_type; int64_t last_time; /** * A callback that is used instead of short_seek_threshold. * This is current internal only, do not use from outside. */ int (*short_seek_get)(void *opaque); int64_t written; /** * Maximum reached position before a backward seek in the write buffer, * used keeping track of already written data for a later flush. */ unsigned char *buf_ptr_max; /** * Try to buffer at least this amount of data before flushing it */ int min_packet_size; } AVIOContext; /** * Return the name of the protocol that will handle the passed URL. * * NULL is returned if no protocol could be found for the given URL. * * @return Name of the protocol or NULL. */ const char *avio_find_protocol_name(const char *url); /** * Return AVIO_FLAG_* access flags corresponding to the access permissions * of the resource in url, or a negative value corresponding to an * AVERROR code in case of failure. The returned access flags are * masked by the value in flags. * * @note This function is intrinsically unsafe, in the sense that the * checked resource may change its existence or permission status from * one call to another. Thus you should not trust the returned value, * unless you are sure that no other processes are accessing the * checked resource. */ int avio_check(const char *url, int flags); /** * Move or rename a resource. * * @note url_src and url_dst should share the same protocol and authority. * * @param url_src url to resource to be moved * @param url_dst new url to resource if the operation succeeded * @return >=0 on success or negative on error. */ int avpriv_io_move(const char *url_src, const char *url_dst); /** * Delete a resource. * * @param url resource to be deleted. * @return >=0 on success or negative on error. */ int avpriv_io_delete(const char *url); /** * Open directory for reading. * * @param s directory read context. Pointer to a NULL pointer must be passed. * @param url directory to be listed. * @param options A dictionary filled with protocol-private options. On return * this parameter will be destroyed and replaced with a dictionary * containing options that were not found. May be NULL. * @return >=0 on success or negative on error. */ int avio_open_dir(AVIODirContext **s, const char *url, AVDictionary **options); /** * Get next directory entry. * * Returned entry must be freed with avio_free_directory_entry(). In particular * it may outlive AVIODirContext. * * @param s directory read context. * @param[out] next next entry or NULL when no more entries. * @return >=0 on success or negative on error. End of list is not considered an * error. */ int avio_read_dir(AVIODirContext *s, AVIODirEntry **next); /** * Close directory. * * @note Entries created using avio_read_dir() are not deleted and must be * freeded with avio_free_directory_entry(). * * @param s directory read context. * @return >=0 on success or negative on error. */ int avio_close_dir(AVIODirContext **s); /** * Free entry allocated by avio_read_dir(). * * @param entry entry to be freed. */ void avio_free_directory_entry(AVIODirEntry **entry); /** * Allocate and initialize an AVIOContext for buffered I/O. It must be later * freed with avio_context_free(). * * @param buffer Memory block for input/output operations via AVIOContext. * The buffer must be allocated with av_malloc() and friends. * It may be freed and replaced with a new buffer by libavformat. * AVIOContext.buffer holds the buffer currently in use, * which must be later freed with av_free(). * @param buffer_size The buffer size is very important for performance. * For protocols with fixed blocksize it should be set to this blocksize. * For others a typical size is a cache page, e.g. 4kb. * @param write_flag Set to 1 if the buffer should be writable, 0 otherwise. * @param opaque An opaque pointer to user-specific data. * @param read_packet A function for refilling the buffer, may be NULL. * For stream protocols, must never return 0 but rather * a proper AVERROR code. * @param write_packet A function for writing the buffer contents, may be NULL. * The function may not change the input buffers content. * @param seek A function for seeking to specified byte position, may be NULL. * * @return Allocated AVIOContext or NULL on failure. */ AVIOContext *avio_alloc_context( unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int (*read_packet)(void *opaque, uint8_t *buf, int buf_size), int (*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t (*seek)(void *opaque, int64_t offset, int whence)); /** * Free the supplied IO context and everything associated with it. * * @param s Double pointer to the IO context. This function will write NULL * into s. */ void avio_context_free(AVIOContext **s); void avio_w8(AVIOContext *s, int b); void avio_write(AVIOContext *s, const unsigned char *buf, int size); void avio_wl64(AVIOContext *s, uint64_t val); void avio_wb64(AVIOContext *s, uint64_t val); void avio_wl32(AVIOContext *s, unsigned int val); void avio_wb32(AVIOContext *s, unsigned int val); void avio_wl24(AVIOContext *s, unsigned int val); void avio_wb24(AVIOContext *s, unsigned int val); void avio_wl16(AVIOContext *s, unsigned int val); void avio_wb16(AVIOContext *s, unsigned int val); /** * Write a NULL-terminated string. * @return number of bytes written. */ int avio_put_str(AVIOContext *s, const char *str); /** * Convert an UTF-8 string to UTF-16LE and write it. * @param s the AVIOContext * @param str NULL-terminated UTF-8 string * * @return number of bytes written. */ int avio_put_str16le(AVIOContext *s, const char *str); /** * Convert an UTF-8 string to UTF-16BE and write it. * @param s the AVIOContext * @param str NULL-terminated UTF-8 string * * @return number of bytes written. */ int avio_put_str16be(AVIOContext *s, const char *str); /** * Mark the written bytestream as a specific type. * * Zero-length ranges are omitted from the output. * * @param time the stream time the current bytestream pos corresponds to * (in AV_TIME_BASE units), or AV_NOPTS_VALUE if unknown or not * applicable * @param type the kind of data written starting at the current pos */ void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type); /** * ORing this as the "whence" parameter to a seek function causes it to * return the filesize without seeking anywhere. Supporting this is optional. * If it is not supported then the seek function will return <0. */ #define AVSEEK_SIZE 0x10000 /** * Passing this flag as the "whence" parameter to a seek function causes it to * seek by any means (like reopening and linear reading) or other normally unreasonable * means that can be extremely slow. * This may be ignored by the seek code. */ #define AVSEEK_FORCE 0x20000 /** * fseek() equivalent for AVIOContext. * @return new position or AVERROR. */ int64_t avio_seek(AVIOContext *s, int64_t offset, int whence); /** * Skip given number of bytes forward * @return new position or AVERROR. */ int64_t avio_skip(AVIOContext *s, int64_t offset); /** * ftell() equivalent for AVIOContext. * @return position or AVERROR. */ static av_always_inline int64_t avio_tell(AVIOContext *s) { return avio_seek(s, 0, SEEK_CUR); } /** * Get the filesize. * @return filesize or AVERROR */ int64_t avio_size(AVIOContext *s); /** * Similar to feof() but also returns nonzero on read errors. * @return non zero if and only if at end of file or a read error happened when reading. */ int avio_feof(AVIOContext *s); /** @warning Writes up to 4 KiB per call */ int avio_printf(AVIOContext *s, const char *fmt, ...) av_printf_format(2, 3); /** * Force flushing of buffered data. * * For write streams, force the buffered data to be immediately written to the output, * without to wait to fill the internal buffer. * * For read streams, discard all currently buffered data, and advance the * reported file position to that of the underlying stream. This does not * read new data, and does not perform any seeks. */ void avio_flush(AVIOContext *s); /** * Read size bytes from AVIOContext into buf. * @return number of bytes read or AVERROR */ int avio_read(AVIOContext *s, unsigned char *buf, int size); /** * Read size bytes from AVIOContext into buf. Unlike avio_read(), this is allowed * to read fewer bytes than requested. The missing bytes can be read in the next * call. This always tries to read at least 1 byte. * Useful to reduce latency in certain cases. * @return number of bytes read or AVERROR */ int avio_read_partial(AVIOContext *s, unsigned char *buf, int size); /** * @name Functions for reading from AVIOContext * @{ * * @note return 0 if EOF, so you cannot use it if EOF handling is * necessary */ int avio_r8 (AVIOContext *s); unsigned int avio_rl16(AVIOContext *s); unsigned int avio_rl24(AVIOContext *s); unsigned int avio_rl32(AVIOContext *s); uint64_t avio_rl64(AVIOContext *s); unsigned int avio_rb16(AVIOContext *s); unsigned int avio_rb24(AVIOContext *s); unsigned int avio_rb32(AVIOContext *s); uint64_t avio_rb64(AVIOContext *s); /** * @} */ /** * Read a string from pb into buf. The reading will terminate when either * a NULL character was encountered, maxlen bytes have been read, or nothing * more can be read from pb. The result is guaranteed to be NULL-terminated, it * will be truncated if buf is too small. * Note that the string is not interpreted or validated in any way, it * might get truncated in the middle of a sequence for multi-byte encodings. * * @return number of bytes read (is always <= maxlen). * If reading ends on EOF or error, the return value will be one more than * bytes actually read. */ int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen); /** * Read a UTF-16 string from pb and convert it to UTF-8. * The reading will terminate when either a null or invalid character was * encountered or maxlen bytes have been read. * @return number of bytes read (is always <= maxlen) */ int avio_get_str16le(AVIOContext *pb, int maxlen, char *buf, int buflen); int avio_get_str16be(AVIOContext *pb, int maxlen, char *buf, int buflen); /** * @name URL open modes * The flags argument to avio_open must be one of the following * constants, optionally ORed with other flags. * @{ */ #define AVIO_FLAG_READ 1 /**< read-only */ #define AVIO_FLAG_WRITE 2 /**< write-only */ #define AVIO_FLAG_READ_WRITE (AVIO_FLAG_READ|AVIO_FLAG_WRITE) /**< read-write pseudo flag */ /** * @} */ /** * Use non-blocking mode. * If this flag is set, operations on the context will return * AVERROR(EAGAIN) if they can not be performed immediately. * If this flag is not set, operations on the context will never return * AVERROR(EAGAIN). * Note that this flag does not affect the opening/connecting of the * context. Connecting a protocol will always block if necessary (e.g. on * network protocols) but never hang (e.g. on busy devices). * Warning: non-blocking protocols is work-in-progress; this flag may be * silently ignored. */ #define AVIO_FLAG_NONBLOCK 8 /** * Use direct mode. * avio_read and avio_write should if possible be satisfied directly * instead of going through a buffer, and avio_seek will always * call the underlying seek function directly. */ #define AVIO_FLAG_DIRECT 0x8000 /** * Create and initialize a AVIOContext for accessing the * resource indicated by url. * @note When the resource indicated by url has been opened in * read+write mode, the AVIOContext can be used only for writing. * * @param s Used to return the pointer to the created AVIOContext. * In case of failure the pointed to value is set to NULL. * @param url resource to access * @param flags flags which control how the resource indicated by url * is to be opened * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code in case of failure */ int avio_open(AVIOContext **s, const char *url, int flags); /** * Create and initialize a AVIOContext for accessing the * resource indicated by url. * @note When the resource indicated by url has been opened in * read+write mode, the AVIOContext can be used only for writing. * * @param s Used to return the pointer to the created AVIOContext. * In case of failure the pointed to value is set to NULL. * @param url resource to access * @param flags flags which control how the resource indicated by url * is to be opened * @param int_cb an interrupt callback to be used at the protocols level * @param options A dictionary filled with protocol-private options. On return * this parameter will be destroyed and replaced with a dict containing options * that were not found. May be NULL. * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code in case of failure */ int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options); /** * Close the resource accessed by the AVIOContext s and free it. * This function can only be used if s was opened by avio_open(). * * The internal buffer is automatically flushed before closing the * resource. * * @return 0 on success, an AVERROR < 0 on error. * @see avio_closep */ int avio_close(AVIOContext *s); /** * Close the resource accessed by the AVIOContext *s, free it * and set the pointer pointing to it to NULL. * This function can only be used if s was opened by avio_open(). * * The internal buffer is automatically flushed before closing the * resource. * * @return 0 on success, an AVERROR < 0 on error. * @see avio_close */ int avio_closep(AVIOContext **s); /** * Open a write only memory stream. * * @param s new IO context * @return zero if no error. */ int avio_open_dyn_buf(AVIOContext **s); /** * Return the written size and a pointer to the buffer. * The AVIOContext stream is left intact. * The buffer must NOT be freed. * No padding is added to the buffer. * * @param s IO context * @param pbuffer pointer to a byte buffer * @return the length of the byte buffer */ int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer); /** * Return the written size and a pointer to the buffer. The buffer * must be freed with av_free(). * Padding of AV_INPUT_BUFFER_PADDING_SIZE is added to the buffer. * * @param s IO context * @param pbuffer pointer to a byte buffer * @return the length of the byte buffer */ int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer); /** * Iterate through names of available protocols. * * @param opaque A private pointer representing current protocol. * It must be a pointer to NULL on first iteration and will * be updated by successive calls to avio_enum_protocols. * @param output If set to 1, iterate over output protocols, * otherwise over input protocols. * * @return A static string containing the name of current protocol or NULL */ const char *avio_enum_protocols(void **opaque, int output); /** * Pause and resume playing - only meaningful if using a network streaming * protocol (e.g. MMS). * * @param h IO context from which to call the read_pause function pointer * @param pause 1 for pause, 0 for resume */ int avio_pause(AVIOContext *h, int pause); /** * Seek to a given timestamp relative to some component stream. * Only meaningful if using a network streaming protocol (e.g. MMS.). * * @param h IO context from which to call the seek function pointers * @param stream_index The stream index that the timestamp is relative to. * If stream_index is (-1) the timestamp should be in AV_TIME_BASE * units from the beginning of the presentation. * If a stream_index >= 0 is used and the protocol does not support * seeking based on component streams, the call will fail. * @param timestamp timestamp in AVStream.time_base units * or if there is no stream specified then in AV_TIME_BASE units. * @param flags Optional combination of AVSEEK_FLAG_BACKWARD, AVSEEK_FLAG_BYTE * and AVSEEK_FLAG_ANY. The protocol may silently ignore * AVSEEK_FLAG_BACKWARD and AVSEEK_FLAG_ANY, but AVSEEK_FLAG_BYTE will * fail if used and not supported. * @return >= 0 on success * @see AVInputFormat::read_seek */ int64_t avio_seek_time(AVIOContext *h, int stream_index, int64_t timestamp, int flags); /* Avoid a warning. The header can not be included because it breaks c++. */ struct AVBPrint; /** * Read contents of h into print buffer, up to max_size bytes, or up to EOF. * * @return 0 for success (max_size bytes read or EOF reached), negative error * code otherwise */ int avio_read_to_bprint(AVIOContext *h, struct AVBPrint *pb, size_t max_size); /** * Accept and allocate a client context on a server context. * @param s the server context * @param c the client context, must be unallocated * @return >= 0 on success or a negative value corresponding * to an AVERROR on failure */ int avio_accept(AVIOContext *s, AVIOContext **c); /** * Perform one step of the protocol handshake to accept a new client. * This function must be called on a client returned by avio_accept() before * using it as a read/write context. * It is separate from avio_accept() because it may block. * A step of the handshake is defined by places where the application may * decide to change the proceedings. * For example, on a protocol with a request header and a reply header, each * one can constitute a step because the application may use the parameters * from the request to change parameters in the reply; or each individual * chunk of the request can constitute a step. * If the handshake is already finished, avio_handshake() does nothing and * returns 0 immediately. * * @param c the client context to perform the handshake on * @return 0 on a complete and successful handshake * > 0 if the handshake progressed, but is not complete * < 0 for an AVERROR code */ int avio_handshake(AVIOContext *c); #endif /* AVFORMAT_AVIO_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavformat/version.h ================================================ /* * Version macros. * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVFORMAT_VERSION_H #define AVFORMAT_VERSION_H /** * @file * @ingroup libavf * Libavformat version macros */ #include "libavutil/version.h" // Major bumping may affect Ticket5467, 5421, 5451(compatibility with Chromium) // Also please add any ticket numbers that you believe might be affected here #define LIBAVFORMAT_VERSION_MAJOR 58 #define LIBAVFORMAT_VERSION_MINOR 29 #define LIBAVFORMAT_VERSION_MICRO 100 #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \ LIBAVFORMAT_VERSION_MINOR, \ LIBAVFORMAT_VERSION_MICRO) #define LIBAVFORMAT_VERSION AV_VERSION(LIBAVFORMAT_VERSION_MAJOR, \ LIBAVFORMAT_VERSION_MINOR, \ LIBAVFORMAT_VERSION_MICRO) #define LIBAVFORMAT_BUILD LIBAVFORMAT_VERSION_INT #define LIBAVFORMAT_IDENT "Lavf" AV_STRINGIFY(LIBAVFORMAT_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. * * @note, when bumping the major version it is recommended to manually * disable each FF_API_* in its own commit instead of disabling them all * at once through the bump. This improves the git bisect-ability of the change. * */ #ifndef FF_API_COMPUTE_PKT_FIELDS2 #define FF_API_COMPUTE_PKT_FIELDS2 (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_OLD_OPEN_CALLBACKS #define FF_API_OLD_OPEN_CALLBACKS (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_LAVF_AVCTX #define FF_API_LAVF_AVCTX (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_HTTP_USER_AGENT #define FF_API_HTTP_USER_AGENT (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_HLS_WRAP #define FF_API_HLS_WRAP (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_HLS_USE_LOCALTIME #define FF_API_HLS_USE_LOCALTIME (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_LAVF_KEEPSIDE_FLAG #define FF_API_LAVF_KEEPSIDE_FLAG (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_OLD_ROTATE_API #define FF_API_OLD_ROTATE_API (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_FORMAT_GET_SET #define FF_API_FORMAT_GET_SET (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_OLD_AVIO_EOF_0 #define FF_API_OLD_AVIO_EOF_0 (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_LAVF_FFSERVER #define FF_API_LAVF_FFSERVER (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_FORMAT_FILENAME #define FF_API_FORMAT_FILENAME (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_OLD_RTSP_OPTIONS #define FF_API_OLD_RTSP_OPTIONS (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_NEXT #define FF_API_NEXT (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_DASH_MIN_SEG_DURATION #define FF_API_DASH_MIN_SEG_DURATION (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_LAVF_MP4A_LATM #define FF_API_LAVF_MP4A_LATM (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_AVIOFORMAT #define FF_API_AVIOFORMAT (LIBAVFORMAT_VERSION_MAJOR < 59) #endif #ifndef FF_API_R_FRAME_RATE #define FF_API_R_FRAME_RATE 1 #endif #endif /* AVFORMAT_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/adler32.h ================================================ /* * copyright (c) 2006 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_adler32 * Public header for Adler-32 hash function implementation. */ #ifndef AVUTIL_ADLER32_H #define AVUTIL_ADLER32_H #include #include "attributes.h" /** * @defgroup lavu_adler32 Adler-32 * @ingroup lavu_hash * Adler-32 hash function implementation. * * @{ */ /** * Calculate the Adler32 checksum of a buffer. * * Passing the return value to a subsequent av_adler32_update() call * allows the checksum of multiple buffers to be calculated as though * they were concatenated. * * @param adler initial checksum value * @param buf pointer to input buffer * @param len size of input buffer * @return updated checksum */ unsigned long av_adler32_update(unsigned long adler, const uint8_t *buf, unsigned int len) av_pure; /** * @} */ #endif /* AVUTIL_ADLER32_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/aes.h ================================================ /* * copyright (c) 2007 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AES_H #define AVUTIL_AES_H #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_aes AES * @ingroup lavu_crypto * @{ */ extern const int av_aes_size; struct AVAES; /** * Allocate an AVAES context. */ struct AVAES *av_aes_alloc(void); /** * Initialize an AVAES context. * @param key_bits 128, 192 or 256 * @param decrypt 0 for encryption, 1 for decryption */ int av_aes_init(struct AVAES *a, const uint8_t *key, int key_bits, int decrypt); /** * Encrypt or decrypt a buffer using a previously initialized context. * @param count number of 16 byte blocks * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param iv initialization vector for CBC mode, if NULL then ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_aes_crypt(struct AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_AES_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/aes_ctr.h ================================================ /* * AES-CTR cipher * Copyright (c) 2015 Eran Kornblau * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AES_CTR_H #define AVUTIL_AES_CTR_H #include #include "attributes.h" #include "version.h" #define AES_CTR_KEY_SIZE (16) #define AES_CTR_IV_SIZE (8) struct AVAESCTR; /** * Allocate an AVAESCTR context. */ struct AVAESCTR *av_aes_ctr_alloc(void); /** * Initialize an AVAESCTR context. * @param key encryption key, must have a length of AES_CTR_KEY_SIZE */ int av_aes_ctr_init(struct AVAESCTR *a, const uint8_t *key); /** * Release an AVAESCTR context. */ void av_aes_ctr_free(struct AVAESCTR *a); /** * Process a buffer using a previously initialized context. * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param size the size of src and dst */ void av_aes_ctr_crypt(struct AVAESCTR *a, uint8_t *dst, const uint8_t *src, int size); /** * Get the current iv */ const uint8_t* av_aes_ctr_get_iv(struct AVAESCTR *a); /** * Generate a random iv */ void av_aes_ctr_set_random_iv(struct AVAESCTR *a); /** * Forcefully change the 8-byte iv */ void av_aes_ctr_set_iv(struct AVAESCTR *a, const uint8_t* iv); /** * Forcefully change the "full" 16-byte iv, including the counter */ void av_aes_ctr_set_full_iv(struct AVAESCTR *a, const uint8_t* iv); /** * Increment the top 64 bit of the iv (performed after each frame) */ void av_aes_ctr_increment_iv(struct AVAESCTR *a); /** * @} */ #endif /* AVUTIL_AES_CTR_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/attributes.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Macro definitions for various function/variable attributes */ #ifndef AVUTIL_ATTRIBUTES_H #define AVUTIL_ATTRIBUTES_H #ifdef __GNUC__ # define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > (x) || __GNUC__ == (x) && __GNUC_MINOR__ >= (y)) # define AV_GCC_VERSION_AT_MOST(x,y) (__GNUC__ < (x) || __GNUC__ == (x) && __GNUC_MINOR__ <= (y)) #else # define AV_GCC_VERSION_AT_LEAST(x,y) 0 # define AV_GCC_VERSION_AT_MOST(x,y) 0 #endif #ifndef av_always_inline #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_always_inline __attribute__((always_inline)) inline #elif defined(_MSC_VER) # define av_always_inline __forceinline #else # define av_always_inline inline #endif #endif #ifndef av_extern_inline #if defined(__ICL) && __ICL >= 1210 || defined(__GNUC_STDC_INLINE__) # define av_extern_inline extern inline #else # define av_extern_inline inline #endif #endif #if AV_GCC_VERSION_AT_LEAST(3,4) # define av_warn_unused_result __attribute__((warn_unused_result)) #else # define av_warn_unused_result #endif #if AV_GCC_VERSION_AT_LEAST(3,1) # define av_noinline __attribute__((noinline)) #elif defined(_MSC_VER) # define av_noinline __declspec(noinline) #else # define av_noinline #endif #if AV_GCC_VERSION_AT_LEAST(3,1) || defined(__clang__) # define av_pure __attribute__((pure)) #else # define av_pure #endif #if AV_GCC_VERSION_AT_LEAST(2,6) || defined(__clang__) # define av_const __attribute__((const)) #else # define av_const #endif #if AV_GCC_VERSION_AT_LEAST(4,3) || defined(__clang__) # define av_cold __attribute__((cold)) #else # define av_cold #endif #if AV_GCC_VERSION_AT_LEAST(4,1) && !defined(__llvm__) # define av_flatten __attribute__((flatten)) #else # define av_flatten #endif #if AV_GCC_VERSION_AT_LEAST(3,1) # define attribute_deprecated __attribute__((deprecated)) #elif defined(_MSC_VER) # define attribute_deprecated __declspec(deprecated) #else # define attribute_deprecated #endif /** * Disable warnings about deprecated features * This is useful for sections of code kept for backward compatibility and * scheduled for removal. */ #ifndef AV_NOWARN_DEPRECATED #if AV_GCC_VERSION_AT_LEAST(4,6) # define AV_NOWARN_DEPRECATED(code) \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \ code \ _Pragma("GCC diagnostic pop") #elif defined(_MSC_VER) # define AV_NOWARN_DEPRECATED(code) \ __pragma(warning(push)) \ __pragma(warning(disable : 4996)) \ code; \ __pragma(warning(pop)) #else # define AV_NOWARN_DEPRECATED(code) code #endif #endif #if defined(__GNUC__) || defined(__clang__) # define av_unused __attribute__((unused)) #else # define av_unused #endif /** * Mark a variable as used and prevent the compiler from optimizing it * away. This is useful for variables accessed only from inline * assembler without the compiler being aware. */ #if AV_GCC_VERSION_AT_LEAST(3,1) || defined(__clang__) # define av_used __attribute__((used)) #else # define av_used #endif #if AV_GCC_VERSION_AT_LEAST(3,3) || defined(__clang__) # define av_alias __attribute__((may_alias)) #else # define av_alias #endif #if (defined(__GNUC__) || defined(__clang__)) && !defined(__INTEL_COMPILER) # define av_uninit(x) x=x #else # define av_uninit(x) x #endif #if defined(__GNUC__) || defined(__clang__) # define av_builtin_constant_p __builtin_constant_p # define av_printf_format(fmtpos, attrpos) __attribute__((__format__(__printf__, fmtpos, attrpos))) #else # define av_builtin_constant_p(x) 0 # define av_printf_format(fmtpos, attrpos) #endif #if AV_GCC_VERSION_AT_LEAST(2,5) || defined(__clang__) # define av_noreturn __attribute__((noreturn)) #else # define av_noreturn #endif #endif /* AVUTIL_ATTRIBUTES_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/audio_fifo.h ================================================ /* * Audio FIFO * Copyright (c) 2012 Justin Ruggles * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Audio FIFO Buffer */ #ifndef AVUTIL_AUDIO_FIFO_H #define AVUTIL_AUDIO_FIFO_H #include "avutil.h" #include "fifo.h" #include "samplefmt.h" /** * @addtogroup lavu_audio * @{ * * @defgroup lavu_audiofifo Audio FIFO Buffer * @{ */ /** * Context for an Audio FIFO Buffer. * * - Operates at the sample level rather than the byte level. * - Supports multiple channels with either planar or packed sample format. * - Automatic reallocation when writing to a full buffer. */ typedef struct AVAudioFifo AVAudioFifo; /** * Free an AVAudioFifo. * * @param af AVAudioFifo to free */ void av_audio_fifo_free(AVAudioFifo *af); /** * Allocate an AVAudioFifo. * * @param sample_fmt sample format * @param channels number of channels * @param nb_samples initial allocation size, in samples * @return newly allocated AVAudioFifo, or NULL on error */ AVAudioFifo *av_audio_fifo_alloc(enum AVSampleFormat sample_fmt, int channels, int nb_samples); /** * Reallocate an AVAudioFifo. * * @param af AVAudioFifo to reallocate * @param nb_samples new allocation size, in samples * @return 0 if OK, or negative AVERROR code on failure */ av_warn_unused_result int av_audio_fifo_realloc(AVAudioFifo *af, int nb_samples); /** * Write data to an AVAudioFifo. * * The AVAudioFifo will be reallocated automatically if the available space * is less than nb_samples. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param af AVAudioFifo to write to * @param data audio data plane pointers * @param nb_samples number of samples to write * @return number of samples actually written, or negative AVERROR * code on failure. If successful, the number of samples * actually written will always be nb_samples. */ int av_audio_fifo_write(AVAudioFifo *af, void **data, int nb_samples); /** * Peek data from an AVAudioFifo. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param af AVAudioFifo to read from * @param data audio data plane pointers * @param nb_samples number of samples to peek * @return number of samples actually peek, or negative AVERROR code * on failure. The number of samples actually peek will not * be greater than nb_samples, and will only be less than * nb_samples if av_audio_fifo_size is less than nb_samples. */ int av_audio_fifo_peek(AVAudioFifo *af, void **data, int nb_samples); /** * Peek data from an AVAudioFifo. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param af AVAudioFifo to read from * @param data audio data plane pointers * @param nb_samples number of samples to peek * @param offset offset from current read position * @return number of samples actually peek, or negative AVERROR code * on failure. The number of samples actually peek will not * be greater than nb_samples, and will only be less than * nb_samples if av_audio_fifo_size is less than nb_samples. */ int av_audio_fifo_peek_at(AVAudioFifo *af, void **data, int nb_samples, int offset); /** * Read data from an AVAudioFifo. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param af AVAudioFifo to read from * @param data audio data plane pointers * @param nb_samples number of samples to read * @return number of samples actually read, or negative AVERROR code * on failure. The number of samples actually read will not * be greater than nb_samples, and will only be less than * nb_samples if av_audio_fifo_size is less than nb_samples. */ int av_audio_fifo_read(AVAudioFifo *af, void **data, int nb_samples); /** * Drain data from an AVAudioFifo. * * Removes the data without reading it. * * @param af AVAudioFifo to drain * @param nb_samples number of samples to drain * @return 0 if OK, or negative AVERROR code on failure */ int av_audio_fifo_drain(AVAudioFifo *af, int nb_samples); /** * Reset the AVAudioFifo buffer. * * This empties all data in the buffer. * * @param af AVAudioFifo to reset */ void av_audio_fifo_reset(AVAudioFifo *af); /** * Get the current number of samples in the AVAudioFifo available for reading. * * @param af the AVAudioFifo to query * @return number of samples available for reading */ int av_audio_fifo_size(AVAudioFifo *af); /** * Get the current number of samples in the AVAudioFifo available for writing. * * @param af the AVAudioFifo to query * @return number of samples available for writing */ int av_audio_fifo_space(AVAudioFifo *af); /** * @} * @} */ #endif /* AVUTIL_AUDIO_FIFO_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/avassert.h ================================================ /* * copyright (c) 2010 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * simple assert() macros that are a bit more flexible than ISO C assert(). * @author Michael Niedermayer */ #ifndef AVUTIL_AVASSERT_H #define AVUTIL_AVASSERT_H #include #include "avutil.h" #include "log.h" /** * assert() equivalent, that is always enabled. */ #define av_assert0(cond) do { \ if (!(cond)) { \ av_log(NULL, AV_LOG_PANIC, "Assertion %s failed at %s:%d\n", \ AV_STRINGIFY(cond), __FILE__, __LINE__); \ abort(); \ } \ } while (0) /** * assert() equivalent, that does not lie in speed critical code. * These asserts() thus can be enabled without fearing speed loss. */ #if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 0 #define av_assert1(cond) av_assert0(cond) #else #define av_assert1(cond) ((void)0) #endif /** * assert() equivalent, that does lie in speed critical code. */ #if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 1 #define av_assert2(cond) av_assert0(cond) #define av_assert2_fpu() av_assert0_fpu() #else #define av_assert2(cond) ((void)0) #define av_assert2_fpu() ((void)0) #endif /** * Assert that floating point operations can be executed. * * This will av_assert0() that the cpu is not in MMX state on X86 */ void av_assert0_fpu(void); #endif /* AVUTIL_AVASSERT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/avconfig.h ================================================ /* Generated by ffmpeg configure */ #ifndef AVUTIL_AVCONFIG_H #define AVUTIL_AVCONFIG_H #define AV_HAVE_BIGENDIAN 0 #define AV_HAVE_FAST_UNALIGNED 1 #endif /* AVUTIL_AVCONFIG_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/avstring.h ================================================ /* * Copyright (c) 2007 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVSTRING_H #define AVUTIL_AVSTRING_H #include #include #include "attributes.h" /** * @addtogroup lavu_string * @{ */ /** * Return non-zero if pfx is a prefix of str. If it is, *ptr is set to * the address of the first character in str after the prefix. * * @param str input string * @param pfx prefix to test * @param ptr updated if the prefix is matched inside str * @return non-zero if the prefix matches, zero otherwise */ int av_strstart(const char *str, const char *pfx, const char **ptr); /** * Return non-zero if pfx is a prefix of str independent of case. If * it is, *ptr is set to the address of the first character in str * after the prefix. * * @param str input string * @param pfx prefix to test * @param ptr updated if the prefix is matched inside str * @return non-zero if the prefix matches, zero otherwise */ int av_stristart(const char *str, const char *pfx, const char **ptr); /** * Locate the first case-independent occurrence in the string haystack * of the string needle. A zero-length string needle is considered to * match at the start of haystack. * * This function is a case-insensitive version of the standard strstr(). * * @param haystack string to search in * @param needle string to search for * @return pointer to the located match within haystack * or a null pointer if no match */ char *av_stristr(const char *haystack, const char *needle); /** * Locate the first occurrence of the string needle in the string haystack * where not more than hay_length characters are searched. A zero-length * string needle is considered to match at the start of haystack. * * This function is a length-limited version of the standard strstr(). * * @param haystack string to search in * @param needle string to search for * @param hay_length length of string to search in * @return pointer to the located match within haystack * or a null pointer if no match */ char *av_strnstr(const char *haystack, const char *needle, size_t hay_length); /** * Copy the string src to dst, but no more than size - 1 bytes, and * null-terminate dst. * * This function is the same as BSD strlcpy(). * * @param dst destination buffer * @param src source string * @param size size of destination buffer * @return the length of src * * @warning since the return value is the length of src, src absolutely * _must_ be a properly 0-terminated string, otherwise this will read beyond * the end of the buffer and possibly crash. */ size_t av_strlcpy(char *dst, const char *src, size_t size); /** * Append the string src to the string dst, but to a total length of * no more than size - 1 bytes, and null-terminate dst. * * This function is similar to BSD strlcat(), but differs when * size <= strlen(dst). * * @param dst destination buffer * @param src source string * @param size size of destination buffer * @return the total length of src and dst * * @warning since the return value use the length of src and dst, these * absolutely _must_ be a properly 0-terminated strings, otherwise this * will read beyond the end of the buffer and possibly crash. */ size_t av_strlcat(char *dst, const char *src, size_t size); /** * Append output to a string, according to a format. Never write out of * the destination buffer, and always put a terminating 0 within * the buffer. * @param dst destination buffer (string to which the output is * appended) * @param size total size of the destination buffer * @param fmt printf-compatible format string, specifying how the * following parameters are used * @return the length of the string that would have been generated * if enough space had been available */ size_t av_strlcatf(char *dst, size_t size, const char *fmt, ...) av_printf_format(3, 4); /** * Get the count of continuous non zero chars starting from the beginning. * * @param len maximum number of characters to check in the string, that * is the maximum value which is returned by the function */ static inline size_t av_strnlen(const char *s, size_t len) { size_t i; for (i = 0; i < len && s[i]; i++) ; return i; } /** * Print arguments following specified format into a large enough auto * allocated buffer. It is similar to GNU asprintf(). * @param fmt printf-compatible format string, specifying how the * following parameters are used. * @return the allocated string * @note You have to free the string yourself with av_free(). */ char *av_asprintf(const char *fmt, ...) av_printf_format(1, 2); /** * Convert a number to an av_malloced string. */ char *av_d2str(double d); /** * Unescape the given string until a non escaped terminating char, * and return the token corresponding to the unescaped string. * * The normal \ and ' escaping is supported. Leading and trailing * whitespaces are removed, unless they are escaped with '\' or are * enclosed between ''. * * @param buf the buffer to parse, buf will be updated to point to the * terminating char * @param term a 0-terminated list of terminating chars * @return the malloced unescaped string, which must be av_freed by * the user, NULL in case of allocation failure */ char *av_get_token(const char **buf, const char *term); /** * Split the string into several tokens which can be accessed by * successive calls to av_strtok(). * * A token is defined as a sequence of characters not belonging to the * set specified in delim. * * On the first call to av_strtok(), s should point to the string to * parse, and the value of saveptr is ignored. In subsequent calls, s * should be NULL, and saveptr should be unchanged since the previous * call. * * This function is similar to strtok_r() defined in POSIX.1. * * @param s the string to parse, may be NULL * @param delim 0-terminated list of token delimiters, must be non-NULL * @param saveptr user-provided pointer which points to stored * information necessary for av_strtok() to continue scanning the same * string. saveptr is updated to point to the next character after the * first delimiter found, or to NULL if the string was terminated * @return the found token, or NULL when no token is found */ char *av_strtok(char *s, const char *delim, char **saveptr); /** * Locale-independent conversion of ASCII isdigit. */ static inline av_const int av_isdigit(int c) { return c >= '0' && c <= '9'; } /** * Locale-independent conversion of ASCII isgraph. */ static inline av_const int av_isgraph(int c) { return c > 32 && c < 127; } /** * Locale-independent conversion of ASCII isspace. */ static inline av_const int av_isspace(int c) { return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'; } /** * Locale-independent conversion of ASCII characters to uppercase. */ static inline av_const int av_toupper(int c) { if (c >= 'a' && c <= 'z') c ^= 0x20; return c; } /** * Locale-independent conversion of ASCII characters to lowercase. */ static inline av_const int av_tolower(int c) { if (c >= 'A' && c <= 'Z') c ^= 0x20; return c; } /** * Locale-independent conversion of ASCII isxdigit. */ static inline av_const int av_isxdigit(int c) { c = av_tolower(c); return av_isdigit(c) || (c >= 'a' && c <= 'f'); } /** * Locale-independent case-insensitive compare. * @note This means only ASCII-range characters are case-insensitive */ int av_strcasecmp(const char *a, const char *b); /** * Locale-independent case-insensitive compare. * @note This means only ASCII-range characters are case-insensitive */ int av_strncasecmp(const char *a, const char *b, size_t n); /** * Locale-independent strings replace. * @note This means only ASCII-range characters are replace */ char *av_strireplace(const char *str, const char *from, const char *to); /** * Thread safe basename. * @param path the path, on DOS both \ and / are considered separators. * @return pointer to the basename substring. */ const char *av_basename(const char *path); /** * Thread safe dirname. * @param path the path, on DOS both \ and / are considered separators. * @return the path with the separator replaced by the string terminator or ".". * @note the function may change the input string. */ const char *av_dirname(char *path); /** * Match instances of a name in a comma-separated list of names. * List entries are checked from the start to the end of the names list, * the first match ends further processing. If an entry prefixed with '-' * matches, then 0 is returned. The "ALL" list entry is considered to * match all names. * * @param name Name to look for. * @param names List of names. * @return 1 on match, 0 otherwise. */ int av_match_name(const char *name, const char *names); /** * Append path component to the existing path. * Path separator '/' is placed between when needed. * Resulting string have to be freed with av_free(). * @param path base path * @param component component to be appended * @return new path or NULL on error. */ char *av_append_path_component(const char *path, const char *component); enum AVEscapeMode { AV_ESCAPE_MODE_AUTO, ///< Use auto-selected escaping mode. AV_ESCAPE_MODE_BACKSLASH, ///< Use backslash escaping. AV_ESCAPE_MODE_QUOTE, ///< Use single-quote escaping. }; /** * Consider spaces special and escape them even in the middle of the * string. * * This is equivalent to adding the whitespace characters to the special * characters lists, except it is guaranteed to use the exact same list * of whitespace characters as the rest of libavutil. */ #define AV_ESCAPE_FLAG_WHITESPACE (1 << 0) /** * Escape only specified special characters. * Without this flag, escape also any characters that may be considered * special by av_get_token(), such as the single quote. */ #define AV_ESCAPE_FLAG_STRICT (1 << 1) /** * Escape string in src, and put the escaped string in an allocated * string in *dst, which must be freed with av_free(). * * @param dst pointer where an allocated string is put * @param src string to escape, must be non-NULL * @param special_chars string containing the special characters which * need to be escaped, can be NULL * @param mode escape mode to employ, see AV_ESCAPE_MODE_* macros. * Any unknown value for mode will be considered equivalent to * AV_ESCAPE_MODE_BACKSLASH, but this behaviour can change without * notice. * @param flags flags which control how to escape, see AV_ESCAPE_FLAG_ macros * @return the length of the allocated string, or a negative error code in case of error * @see av_bprint_escape() */ av_warn_unused_result int av_escape(char **dst, const char *src, const char *special_chars, enum AVEscapeMode mode, int flags); #define AV_UTF8_FLAG_ACCEPT_INVALID_BIG_CODES 1 ///< accept codepoints over 0x10FFFF #define AV_UTF8_FLAG_ACCEPT_NON_CHARACTERS 2 ///< accept non-characters - 0xFFFE and 0xFFFF #define AV_UTF8_FLAG_ACCEPT_SURROGATES 4 ///< accept UTF-16 surrogates codes #define AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES 8 ///< exclude control codes not accepted by XML #define AV_UTF8_FLAG_ACCEPT_ALL \ AV_UTF8_FLAG_ACCEPT_INVALID_BIG_CODES|AV_UTF8_FLAG_ACCEPT_NON_CHARACTERS|AV_UTF8_FLAG_ACCEPT_SURROGATES /** * Read and decode a single UTF-8 code point (character) from the * buffer in *buf, and update *buf to point to the next byte to * decode. * * In case of an invalid byte sequence, the pointer will be updated to * the next byte after the invalid sequence and the function will * return an error code. * * Depending on the specified flags, the function will also fail in * case the decoded code point does not belong to a valid range. * * @note For speed-relevant code a carefully implemented use of * GET_UTF8() may be preferred. * * @param codep pointer used to return the parsed code in case of success. * The value in *codep is set even in case the range check fails. * @param bufp pointer to the address the first byte of the sequence * to decode, updated by the function to point to the * byte next after the decoded sequence * @param buf_end pointer to the end of the buffer, points to the next * byte past the last in the buffer. This is used to * avoid buffer overreads (in case of an unfinished * UTF-8 sequence towards the end of the buffer). * @param flags a collection of AV_UTF8_FLAG_* flags * @return >= 0 in case a sequence was successfully read, a negative * value in case of invalid sequence */ av_warn_unused_result int av_utf8_decode(int32_t *codep, const uint8_t **bufp, const uint8_t *buf_end, unsigned int flags); /** * Check if a name is in a list. * @returns 0 if not found, or the 1 based index where it has been found in the * list. */ int av_match_list(const char *name, const char *list, char separator); /** * See libc sscanf manual for more information. * Locale-independent sscanf implementation. */ int av_sscanf(const char *string, const char *format, ...); /** * @} */ #endif /* AVUTIL_AVSTRING_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/avutil.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_AVUTIL_H #define AVUTIL_AVUTIL_H /** * @file * @ingroup lavu * Convenience header that includes @ref lavu "libavutil"'s core. */ /** * @mainpage * * @section ffmpeg_intro Introduction * * This document describes the usage of the different libraries * provided by FFmpeg. * * @li @ref libavc "libavcodec" encoding/decoding library * @li @ref lavfi "libavfilter" graph-based frame editing library * @li @ref libavf "libavformat" I/O and muxing/demuxing library * @li @ref lavd "libavdevice" special devices muxing/demuxing library * @li @ref lavu "libavutil" common utility library * @li @ref lswr "libswresample" audio resampling, format conversion and mixing * @li @ref lpp "libpostproc" post processing library * @li @ref libsws "libswscale" color conversion and scaling library * * @section ffmpeg_versioning Versioning and compatibility * * Each of the FFmpeg libraries contains a version.h header, which defines a * major, minor and micro version number with the * LIBRARYNAME_VERSION_{MAJOR,MINOR,MICRO} macros. The major version * number is incremented with backward incompatible changes - e.g. removing * parts of the public API, reordering public struct members, etc. The minor * version number is incremented for backward compatible API changes or major * new features - e.g. adding a new public function or a new decoder. The micro * version number is incremented for smaller changes that a calling program * might still want to check for - e.g. changing behavior in a previously * unspecified situation. * * FFmpeg guarantees backward API and ABI compatibility for each library as long * as its major version number is unchanged. This means that no public symbols * will be removed or renamed. Types and names of the public struct members and * values of public macros and enums will remain the same (unless they were * explicitly declared as not part of the public API). Documented behavior will * not change. * * In other words, any correct program that works with a given FFmpeg snapshot * should work just as well without any changes with any later snapshot with the * same major versions. This applies to both rebuilding the program against new * FFmpeg versions or to replacing the dynamic FFmpeg libraries that a program * links against. * * However, new public symbols may be added and new members may be appended to * public structs whose size is not part of public ABI (most public structs in * FFmpeg). New macros and enum values may be added. Behavior in undocumented * situations may change slightly (and be documented). All those are accompanied * by an entry in doc/APIchanges and incrementing either the minor or micro * version number. */ /** * @defgroup lavu libavutil * Common code shared across all FFmpeg libraries. * * @note * libavutil is designed to be modular. In most cases, in order to use the * functions provided by one component of libavutil you must explicitly include * the specific header containing that feature. If you are only using * media-related components, you could simply include libavutil/avutil.h, which * brings in most of the "core" components. * * @{ * * @defgroup lavu_crypto Crypto and Hashing * * @{ * @} * * @defgroup lavu_math Mathematics * @{ * * @} * * @defgroup lavu_string String Manipulation * * @{ * * @} * * @defgroup lavu_mem Memory Management * * @{ * * @} * * @defgroup lavu_data Data Structures * @{ * * @} * * @defgroup lavu_video Video related * * @{ * * @} * * @defgroup lavu_audio Audio related * * @{ * * @} * * @defgroup lavu_error Error Codes * * @{ * * @} * * @defgroup lavu_log Logging Facility * * @{ * * @} * * @defgroup lavu_misc Other * * @{ * * @defgroup preproc_misc Preprocessor String Macros * * @{ * * @} * * @defgroup version_utils Library Version Macros * * @{ * * @} */ /** * @addtogroup lavu_ver * @{ */ /** * Return the LIBAVUTIL_VERSION_INT constant. */ unsigned avutil_version(void); /** * Return an informative version string. This usually is the actual release * version number or a git commit description. This string has no fixed format * and can change any time. It should never be parsed by code. */ const char *av_version_info(void); /** * Return the libavutil build-time configuration. */ const char *avutil_configuration(void); /** * Return the libavutil license. */ const char *avutil_license(void); /** * @} */ /** * @addtogroup lavu_media Media Type * @brief Media Type */ enum AVMediaType { AVMEDIA_TYPE_UNKNOWN = -1, ///< Usually treated as AVMEDIA_TYPE_DATA AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA, ///< Opaque data information usually continuous AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_ATTACHMENT, ///< Opaque data information usually sparse AVMEDIA_TYPE_NB }; /** * Return a string describing the media_type enum, NULL if media_type * is unknown. */ const char *av_get_media_type_string(enum AVMediaType media_type); /** * @defgroup lavu_const Constants * @{ * * @defgroup lavu_enc Encoding specific * * @note those definition should move to avcodec * @{ */ #define FF_LAMBDA_SHIFT 7 #define FF_LAMBDA_SCALE (1< /** * @defgroup lavu_base64 Base64 * @ingroup lavu_crypto * @{ */ /** * Decode a base64-encoded string. * * @param out buffer for decoded data * @param in null-terminated input string * @param out_size size in bytes of the out buffer, must be at * least 3/4 of the length of in, that is AV_BASE64_DECODE_SIZE(strlen(in)) * @return number of bytes written, or a negative value in case of * invalid input */ int av_base64_decode(uint8_t *out, const char *in, int out_size); /** * Calculate the output size in bytes needed to decode a base64 string * with length x to a data buffer. */ #define AV_BASE64_DECODE_SIZE(x) ((x) * 3LL / 4) /** * Encode data to base64 and null-terminate. * * @param out buffer for encoded data * @param out_size size in bytes of the out buffer (including the * null terminator), must be at least AV_BASE64_SIZE(in_size) * @param in input buffer containing the data to encode * @param in_size size in bytes of the in buffer * @return out or NULL in case of error */ char *av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size); /** * Calculate the output size needed to base64-encode x bytes to a * null-terminated string. */ #define AV_BASE64_SIZE(x) (((x)+2) / 3 * 4 + 1) /** * @} */ #endif /* AVUTIL_BASE64_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/blowfish.h ================================================ /* * Blowfish algorithm * Copyright (c) 2012 Samuel Pitoiset * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_BLOWFISH_H #define AVUTIL_BLOWFISH_H #include /** * @defgroup lavu_blowfish Blowfish * @ingroup lavu_crypto * @{ */ #define AV_BF_ROUNDS 16 typedef struct AVBlowfish { uint32_t p[AV_BF_ROUNDS + 2]; uint32_t s[4][256]; } AVBlowfish; /** * Allocate an AVBlowfish context. */ AVBlowfish *av_blowfish_alloc(void); /** * Initialize an AVBlowfish context. * * @param ctx an AVBlowfish context * @param key a key * @param key_len length of the key */ void av_blowfish_init(struct AVBlowfish *ctx, const uint8_t *key, int key_len); /** * Encrypt or decrypt a buffer using a previously initialized context. * * @param ctx an AVBlowfish context * @param xl left four bytes halves of input to be encrypted * @param xr right four bytes halves of input to be encrypted * @param decrypt 0 for encryption, 1 for decryption */ void av_blowfish_crypt_ecb(struct AVBlowfish *ctx, uint32_t *xl, uint32_t *xr, int decrypt); /** * Encrypt or decrypt a buffer using a previously initialized context. * * @param ctx an AVBlowfish context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param iv initialization vector for CBC mode, if NULL ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_blowfish_crypt(struct AVBlowfish *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_BLOWFISH_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/bprint.h ================================================ /* * Copyright (c) 2012 Nicolas George * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_BPRINT_H #define AVUTIL_BPRINT_H #include #include "attributes.h" #include "avstring.h" /** * Define a structure with extra padding to a fixed size * This helps ensuring binary compatibility with future versions. */ #define FF_PAD_STRUCTURE(name, size, ...) \ struct ff_pad_helper_##name { __VA_ARGS__ }; \ typedef struct name { \ __VA_ARGS__ \ char reserved_padding[size - sizeof(struct ff_pad_helper_##name)]; \ } name; /** * Buffer to print data progressively * * The string buffer grows as necessary and is always 0-terminated. * The content of the string is never accessed, and thus is * encoding-agnostic and can even hold binary data. * * Small buffers are kept in the structure itself, and thus require no * memory allocation at all (unless the contents of the buffer is needed * after the structure goes out of scope). This is almost as lightweight as * declaring a local "char buf[512]". * * The length of the string can go beyond the allocated size: the buffer is * then truncated, but the functions still keep account of the actual total * length. * * In other words, buf->len can be greater than buf->size and records the * total length of what would have been to the buffer if there had been * enough memory. * * Append operations do not need to be tested for failure: if a memory * allocation fails, data stop being appended to the buffer, but the length * is still updated. This situation can be tested with * av_bprint_is_complete(). * * The size_max field determines several possible behaviours: * * size_max = -1 (= UINT_MAX) or any large value will let the buffer be * reallocated as necessary, with an amortized linear cost. * * size_max = 0 prevents writing anything to the buffer: only the total * length is computed. The write operations can then possibly be repeated in * a buffer with exactly the necessary size * (using size_init = size_max = len + 1). * * size_max = 1 is automatically replaced by the exact size available in the * structure itself, thus ensuring no dynamic memory allocation. The * internal buffer is large enough to hold a reasonable paragraph of text, * such as the current paragraph. */ FF_PAD_STRUCTURE(AVBPrint, 1024, char *str; /**< string so far */ unsigned len; /**< length so far */ unsigned size; /**< allocated memory */ unsigned size_max; /**< maximum allocated memory */ char reserved_internal_buffer[1]; ) /** * Convenience macros for special values for av_bprint_init() size_max * parameter. */ #define AV_BPRINT_SIZE_UNLIMITED ((unsigned)-1) #define AV_BPRINT_SIZE_AUTOMATIC 1 #define AV_BPRINT_SIZE_COUNT_ONLY 0 /** * Init a print buffer. * * @param buf buffer to init * @param size_init initial size (including the final 0) * @param size_max maximum size; * 0 means do not write anything, just count the length; * 1 is replaced by the maximum value for automatic storage; * any large value means that the internal buffer will be * reallocated as needed up to that limit; -1 is converted to * UINT_MAX, the largest limit possible. * Check also AV_BPRINT_SIZE_* macros. */ void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max); /** * Init a print buffer using a pre-existing buffer. * * The buffer will not be reallocated. * * @param buf buffer structure to init * @param buffer byte buffer to use for the string data * @param size size of buffer */ void av_bprint_init_for_buffer(AVBPrint *buf, char *buffer, unsigned size); /** * Append a formatted string to a print buffer. */ void av_bprintf(AVBPrint *buf, const char *fmt, ...) av_printf_format(2, 3); /** * Append a formatted string to a print buffer. */ void av_vbprintf(AVBPrint *buf, const char *fmt, va_list vl_arg); /** * Append char c n times to a print buffer. */ void av_bprint_chars(AVBPrint *buf, char c, unsigned n); /** * Append data to a print buffer. * * param buf bprint buffer to use * param data pointer to data * param size size of data */ void av_bprint_append_data(AVBPrint *buf, const char *data, unsigned size); struct tm; /** * Append a formatted date and time to a print buffer. * * param buf bprint buffer to use * param fmt date and time format string, see strftime() * param tm broken-down time structure to translate * * @note due to poor design of the standard strftime function, it may * produce poor results if the format string expands to a very long text and * the bprint buffer is near the limit stated by the size_max option. */ void av_bprint_strftime(AVBPrint *buf, const char *fmt, const struct tm *tm); /** * Allocate bytes in the buffer for external use. * * @param[in] buf buffer structure * @param[in] size required size * @param[out] mem pointer to the memory area * @param[out] actual_size size of the memory area after allocation; * can be larger or smaller than size */ void av_bprint_get_buffer(AVBPrint *buf, unsigned size, unsigned char **mem, unsigned *actual_size); /** * Reset the string to "" but keep internal allocated data. */ void av_bprint_clear(AVBPrint *buf); /** * Test if the print buffer is complete (not truncated). * * It may have been truncated due to a memory allocation failure * or the size_max limit (compare size and size_max if necessary). */ static inline int av_bprint_is_complete(const AVBPrint *buf) { return buf->len < buf->size; } /** * Finalize a print buffer. * * The print buffer can no longer be used afterwards, * but the len and size fields are still valid. * * @arg[out] ret_str if not NULL, used to return a permanent copy of the * buffer contents, or NULL if memory allocation fails; * if NULL, the buffer is discarded and freed * @return 0 for success or error code (probably AVERROR(ENOMEM)) */ int av_bprint_finalize(AVBPrint *buf, char **ret_str); /** * Escape the content in src and append it to dstbuf. * * @param dstbuf already inited destination bprint buffer * @param src string containing the text to escape * @param special_chars string containing the special characters which * need to be escaped, can be NULL * @param mode escape mode to employ, see AV_ESCAPE_MODE_* macros. * Any unknown value for mode will be considered equivalent to * AV_ESCAPE_MODE_BACKSLASH, but this behaviour can change without * notice. * @param flags flags which control how to escape, see AV_ESCAPE_FLAG_* macros */ void av_bprint_escape(AVBPrint *dstbuf, const char *src, const char *special_chars, enum AVEscapeMode mode, int flags); #endif /* AVUTIL_BPRINT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/bswap.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * byte swapping routines */ #ifndef AVUTIL_BSWAP_H #define AVUTIL_BSWAP_H #include #include "libavutil/avconfig.h" #include "attributes.h" #ifdef HAVE_AV_CONFIG_H #include "config.h" #if ARCH_AARCH64 # include "aarch64/bswap.h" #elif ARCH_ARM # include "arm/bswap.h" #elif ARCH_AVR32 # include "avr32/bswap.h" #elif ARCH_SH4 # include "sh4/bswap.h" #elif ARCH_X86 # include "x86/bswap.h" #endif #endif /* HAVE_AV_CONFIG_H */ #define AV_BSWAP16C(x) (((x) << 8 & 0xff00) | ((x) >> 8 & 0x00ff)) #define AV_BSWAP32C(x) (AV_BSWAP16C(x) << 16 | AV_BSWAP16C((x) >> 16)) #define AV_BSWAP64C(x) (AV_BSWAP32C(x) << 32 | AV_BSWAP32C((x) >> 32)) #define AV_BSWAPC(s, x) AV_BSWAP##s##C(x) #ifndef av_bswap16 static av_always_inline av_const uint16_t av_bswap16(uint16_t x) { x= (x>>8) | (x<<8); return x; } #endif #ifndef av_bswap32 static av_always_inline av_const uint32_t av_bswap32(uint32_t x) { return AV_BSWAP32C(x); } #endif #ifndef av_bswap64 static inline uint64_t av_const av_bswap64(uint64_t x) { return (uint64_t)av_bswap32(x) << 32 | av_bswap32(x >> 32); } #endif // be2ne ... big-endian to native-endian // le2ne ... little-endian to native-endian #if AV_HAVE_BIGENDIAN #define av_be2ne16(x) (x) #define av_be2ne32(x) (x) #define av_be2ne64(x) (x) #define av_le2ne16(x) av_bswap16(x) #define av_le2ne32(x) av_bswap32(x) #define av_le2ne64(x) av_bswap64(x) #define AV_BE2NEC(s, x) (x) #define AV_LE2NEC(s, x) AV_BSWAPC(s, x) #else #define av_be2ne16(x) av_bswap16(x) #define av_be2ne32(x) av_bswap32(x) #define av_be2ne64(x) av_bswap64(x) #define av_le2ne16(x) (x) #define av_le2ne32(x) (x) #define av_le2ne64(x) (x) #define AV_BE2NEC(s, x) AV_BSWAPC(s, x) #define AV_LE2NEC(s, x) (x) #endif #define AV_BE2NE16C(x) AV_BE2NEC(16, x) #define AV_BE2NE32C(x) AV_BE2NEC(32, x) #define AV_BE2NE64C(x) AV_BE2NEC(64, x) #define AV_LE2NE16C(x) AV_LE2NEC(16, x) #define AV_LE2NE32C(x) AV_LE2NEC(32, x) #define AV_LE2NE64C(x) AV_LE2NEC(64, x) #endif /* AVUTIL_BSWAP_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/buffer.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_buffer * refcounted data buffer API */ #ifndef AVUTIL_BUFFER_H #define AVUTIL_BUFFER_H #include /** * @defgroup lavu_buffer AVBuffer * @ingroup lavu_data * * @{ * AVBuffer is an API for reference-counted data buffers. * * There are two core objects in this API -- AVBuffer and AVBufferRef. AVBuffer * represents the data buffer itself; it is opaque and not meant to be accessed * by the caller directly, but only through AVBufferRef. However, the caller may * e.g. compare two AVBuffer pointers to check whether two different references * are describing the same data buffer. AVBufferRef represents a single * reference to an AVBuffer and it is the object that may be manipulated by the * caller directly. * * There are two functions provided for creating a new AVBuffer with a single * reference -- av_buffer_alloc() to just allocate a new buffer, and * av_buffer_create() to wrap an existing array in an AVBuffer. From an existing * reference, additional references may be created with av_buffer_ref(). * Use av_buffer_unref() to free a reference (this will automatically free the * data once all the references are freed). * * The convention throughout this API and the rest of FFmpeg is such that the * buffer is considered writable if there exists only one reference to it (and * it has not been marked as read-only). The av_buffer_is_writable() function is * provided to check whether this is true and av_buffer_make_writable() will * automatically create a new writable buffer when necessary. * Of course nothing prevents the calling code from violating this convention, * however that is safe only when all the existing references are under its * control. * * @note Referencing and unreferencing the buffers is thread-safe and thus * may be done from multiple threads simultaneously without any need for * additional locking. * * @note Two different references to the same buffer can point to different * parts of the buffer (i.e. their AVBufferRef.data will not be equal). */ /** * A reference counted buffer type. It is opaque and is meant to be used through * references (AVBufferRef). */ typedef struct AVBuffer AVBuffer; /** * A reference to a data buffer. * * The size of this struct is not a part of the public ABI and it is not meant * to be allocated directly. */ typedef struct AVBufferRef { AVBuffer *buffer; /** * The data buffer. It is considered writable if and only if * this is the only reference to the buffer, in which case * av_buffer_is_writable() returns 1. */ uint8_t *data; /** * Size of data in bytes. */ int size; } AVBufferRef; /** * Allocate an AVBuffer of the given size using av_malloc(). * * @return an AVBufferRef of given size or NULL when out of memory */ AVBufferRef *av_buffer_alloc(int size); /** * Same as av_buffer_alloc(), except the returned buffer will be initialized * to zero. */ AVBufferRef *av_buffer_allocz(int size); /** * Always treat the buffer as read-only, even when it has only one * reference. */ #define AV_BUFFER_FLAG_READONLY (1 << 0) /** * Create an AVBuffer from an existing array. * * If this function is successful, data is owned by the AVBuffer. The caller may * only access data through the returned AVBufferRef and references derived from * it. * If this function fails, data is left untouched. * @param data data array * @param size size of data in bytes * @param free a callback for freeing this buffer's data * @param opaque parameter to be got for processing or passed to free * @param flags a combination of AV_BUFFER_FLAG_* * * @return an AVBufferRef referring to data on success, NULL on failure. */ AVBufferRef *av_buffer_create(uint8_t *data, int size, void (*free)(void *opaque, uint8_t *data), void *opaque, int flags); /** * Default free callback, which calls av_free() on the buffer data. * This function is meant to be passed to av_buffer_create(), not called * directly. */ void av_buffer_default_free(void *opaque, uint8_t *data); /** * Create a new reference to an AVBuffer. * * @return a new AVBufferRef referring to the same AVBuffer as buf or NULL on * failure. */ AVBufferRef *av_buffer_ref(AVBufferRef *buf); /** * Free a given reference and automatically free the buffer if there are no more * references to it. * * @param buf the reference to be freed. The pointer is set to NULL on return. */ void av_buffer_unref(AVBufferRef **buf); /** * @return 1 if the caller may write to the data referred to by buf (which is * true if and only if buf is the only reference to the underlying AVBuffer). * Return 0 otherwise. * A positive answer is valid until av_buffer_ref() is called on buf. */ int av_buffer_is_writable(const AVBufferRef *buf); /** * @return the opaque parameter set by av_buffer_create. */ void *av_buffer_get_opaque(const AVBufferRef *buf); int av_buffer_get_ref_count(const AVBufferRef *buf); /** * Create a writable reference from a given buffer reference, avoiding data copy * if possible. * * @param buf buffer reference to make writable. On success, buf is either left * untouched, or it is unreferenced and a new writable AVBufferRef is * written in its place. On failure, buf is left untouched. * @return 0 on success, a negative AVERROR on failure. */ int av_buffer_make_writable(AVBufferRef **buf); /** * Reallocate a given buffer. * * @param buf a buffer reference to reallocate. On success, buf will be * unreferenced and a new reference with the required size will be * written in its place. On failure buf will be left untouched. *buf * may be NULL, then a new buffer is allocated. * @param size required new buffer size. * @return 0 on success, a negative AVERROR on failure. * * @note the buffer is actually reallocated with av_realloc() only if it was * initially allocated through av_buffer_realloc(NULL) and there is only one * reference to it (i.e. the one passed to this function). In all other cases * a new buffer is allocated and the data is copied. */ int av_buffer_realloc(AVBufferRef **buf, int size); /** * @} */ /** * @defgroup lavu_bufferpool AVBufferPool * @ingroup lavu_data * * @{ * AVBufferPool is an API for a lock-free thread-safe pool of AVBuffers. * * Frequently allocating and freeing large buffers may be slow. AVBufferPool is * meant to solve this in cases when the caller needs a set of buffers of the * same size (the most obvious use case being buffers for raw video or audio * frames). * * At the beginning, the user must call av_buffer_pool_init() to create the * buffer pool. Then whenever a buffer is needed, call av_buffer_pool_get() to * get a reference to a new buffer, similar to av_buffer_alloc(). This new * reference works in all aspects the same way as the one created by * av_buffer_alloc(). However, when the last reference to this buffer is * unreferenced, it is returned to the pool instead of being freed and will be * reused for subsequent av_buffer_pool_get() calls. * * When the caller is done with the pool and no longer needs to allocate any new * buffers, av_buffer_pool_uninit() must be called to mark the pool as freeable. * Once all the buffers are released, it will automatically be freed. * * Allocating and releasing buffers with this API is thread-safe as long as * either the default alloc callback is used, or the user-supplied one is * thread-safe. */ /** * The buffer pool. This structure is opaque and not meant to be accessed * directly. It is allocated with av_buffer_pool_init() and freed with * av_buffer_pool_uninit(). */ typedef struct AVBufferPool AVBufferPool; /** * Allocate and initialize a buffer pool. * * @param size size of each buffer in this pool * @param alloc a function that will be used to allocate new buffers when the * pool is empty. May be NULL, then the default allocator will be used * (av_buffer_alloc()). * @return newly created buffer pool on success, NULL on error. */ AVBufferPool *av_buffer_pool_init(int size, AVBufferRef* (*alloc)(int size)); /** * Allocate and initialize a buffer pool with a more complex allocator. * * @param size size of each buffer in this pool * @param opaque arbitrary user data used by the allocator * @param alloc a function that will be used to allocate new buffers when the * pool is empty. * @param pool_free a function that will be called immediately before the pool * is freed. I.e. after av_buffer_pool_uninit() is called * by the caller and all the frames are returned to the pool * and freed. It is intended to uninitialize the user opaque * data. * @return newly created buffer pool on success, NULL on error. */ AVBufferPool *av_buffer_pool_init2(int size, void *opaque, AVBufferRef* (*alloc)(void *opaque, int size), void (*pool_free)(void *opaque)); /** * Mark the pool as being available for freeing. It will actually be freed only * once all the allocated buffers associated with the pool are released. Thus it * is safe to call this function while some of the allocated buffers are still * in use. * * @param pool pointer to the pool to be freed. It will be set to NULL. */ void av_buffer_pool_uninit(AVBufferPool **pool); /** * Allocate a new AVBuffer, reusing an old buffer from the pool when available. * This function may be called simultaneously from multiple threads. * * @return a reference to the new buffer on success, NULL on error. */ AVBufferRef *av_buffer_pool_get(AVBufferPool *pool); /** * @} */ #endif /* AVUTIL_BUFFER_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/camellia.h ================================================ /* * An implementation of the CAMELLIA algorithm as mentioned in RFC3713 * Copyright (c) 2014 Supraja Meedinti * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CAMELLIA_H #define AVUTIL_CAMELLIA_H #include /** * @file * @brief Public header for libavutil CAMELLIA algorithm * @defgroup lavu_camellia CAMELLIA * @ingroup lavu_crypto * @{ */ extern const int av_camellia_size; struct AVCAMELLIA; /** * Allocate an AVCAMELLIA context * To free the struct: av_free(ptr) */ struct AVCAMELLIA *av_camellia_alloc(void); /** * Initialize an AVCAMELLIA context. * * @param ctx an AVCAMELLIA context * @param key a key of 16, 24, 32 bytes used for encryption/decryption * @param key_bits number of keybits: possible are 128, 192, 256 */ int av_camellia_init(struct AVCAMELLIA *ctx, const uint8_t *key, int key_bits); /** * Encrypt or decrypt a buffer using a previously initialized context * * @param ctx an AVCAMELLIA context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 16 byte blocks * @paran iv initialization vector for CBC mode, NULL for ECB mode * @param decrypt 0 for encryption, 1 for decryption */ void av_camellia_crypt(struct AVCAMELLIA *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t* iv, int decrypt); /** * @} */ #endif /* AVUTIL_CAMELLIA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/cast5.h ================================================ /* * An implementation of the CAST128 algorithm as mentioned in RFC2144 * Copyright (c) 2014 Supraja Meedinti * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CAST5_H #define AVUTIL_CAST5_H #include /** * @file * @brief Public header for libavutil CAST5 algorithm * @defgroup lavu_cast5 CAST5 * @ingroup lavu_crypto * @{ */ extern const int av_cast5_size; struct AVCAST5; /** * Allocate an AVCAST5 context * To free the struct: av_free(ptr) */ struct AVCAST5 *av_cast5_alloc(void); /** * Initialize an AVCAST5 context. * * @param ctx an AVCAST5 context * @param key a key of 5,6,...16 bytes used for encryption/decryption * @param key_bits number of keybits: possible are 40,48,...,128 * @return 0 on success, less than 0 on failure */ int av_cast5_init(struct AVCAST5 *ctx, const uint8_t *key, int key_bits); /** * Encrypt or decrypt a buffer using a previously initialized context, ECB mode only * * @param ctx an AVCAST5 context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param decrypt 0 for encryption, 1 for decryption */ void av_cast5_crypt(struct AVCAST5 *ctx, uint8_t *dst, const uint8_t *src, int count, int decrypt); /** * Encrypt or decrypt a buffer using a previously initialized context * * @param ctx an AVCAST5 context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param iv initialization vector for CBC mode, NULL for ECB mode * @param decrypt 0 for encryption, 1 for decryption */ void av_cast5_crypt2(struct AVCAST5 *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_CAST5_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/channel_layout.h ================================================ /* * Copyright (c) 2006 Michael Niedermayer * Copyright (c) 2008 Peter Ross * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CHANNEL_LAYOUT_H #define AVUTIL_CHANNEL_LAYOUT_H #include /** * @file * audio channel layout utility functions */ /** * @addtogroup lavu_audio * @{ */ /** * @defgroup channel_masks Audio channel masks * * A channel layout is a 64-bits integer with a bit set for every channel. * The number of bits set must be equal to the number of channels. * The value 0 means that the channel layout is not known. * @note this data structure is not powerful enough to handle channels * combinations that have the same channel multiple times, such as * dual-mono. * * @{ */ #define AV_CH_FRONT_LEFT 0x00000001 #define AV_CH_FRONT_RIGHT 0x00000002 #define AV_CH_FRONT_CENTER 0x00000004 #define AV_CH_LOW_FREQUENCY 0x00000008 #define AV_CH_BACK_LEFT 0x00000010 #define AV_CH_BACK_RIGHT 0x00000020 #define AV_CH_FRONT_LEFT_OF_CENTER 0x00000040 #define AV_CH_FRONT_RIGHT_OF_CENTER 0x00000080 #define AV_CH_BACK_CENTER 0x00000100 #define AV_CH_SIDE_LEFT 0x00000200 #define AV_CH_SIDE_RIGHT 0x00000400 #define AV_CH_TOP_CENTER 0x00000800 #define AV_CH_TOP_FRONT_LEFT 0x00001000 #define AV_CH_TOP_FRONT_CENTER 0x00002000 #define AV_CH_TOP_FRONT_RIGHT 0x00004000 #define AV_CH_TOP_BACK_LEFT 0x00008000 #define AV_CH_TOP_BACK_CENTER 0x00010000 #define AV_CH_TOP_BACK_RIGHT 0x00020000 #define AV_CH_STEREO_LEFT 0x20000000 ///< Stereo downmix. #define AV_CH_STEREO_RIGHT 0x40000000 ///< See AV_CH_STEREO_LEFT. #define AV_CH_WIDE_LEFT 0x0000000080000000ULL #define AV_CH_WIDE_RIGHT 0x0000000100000000ULL #define AV_CH_SURROUND_DIRECT_LEFT 0x0000000200000000ULL #define AV_CH_SURROUND_DIRECT_RIGHT 0x0000000400000000ULL #define AV_CH_LOW_FREQUENCY_2 0x0000000800000000ULL /** Channel mask value used for AVCodecContext.request_channel_layout to indicate that the user requests the channel order of the decoder output to be the native codec channel order. */ #define AV_CH_LAYOUT_NATIVE 0x8000000000000000ULL /** * @} * @defgroup channel_mask_c Audio channel layouts * @{ * */ #define AV_CH_LAYOUT_MONO (AV_CH_FRONT_CENTER) #define AV_CH_LAYOUT_STEREO (AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT) #define AV_CH_LAYOUT_2POINT1 (AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_2_1 (AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_SURROUND (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) #define AV_CH_LAYOUT_3POINT1 (AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_4POINT0 (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_4POINT1 (AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_2_2 (AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT) #define AV_CH_LAYOUT_QUAD (AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_5POINT0 (AV_CH_LAYOUT_SURROUND|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT) #define AV_CH_LAYOUT_5POINT1 (AV_CH_LAYOUT_5POINT0|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_5POINT0_BACK (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_5POINT1_BACK (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_6POINT0 (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT0_FRONT (AV_CH_LAYOUT_2_2|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_HEXAGONAL (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT1 (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT1_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER) #define AV_CH_LAYOUT_6POINT1_FRONT (AV_CH_LAYOUT_6POINT0_FRONT|AV_CH_LOW_FREQUENCY) #define AV_CH_LAYOUT_7POINT0 (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_7POINT0_FRONT (AV_CH_LAYOUT_5POINT0|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_7POINT1 (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_7POINT1_WIDE (AV_CH_LAYOUT_5POINT1|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_7POINT1_WIDE_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER) #define AV_CH_LAYOUT_OCTAGONAL (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_CENTER|AV_CH_BACK_RIGHT) #define AV_CH_LAYOUT_HEXADECAGONAL (AV_CH_LAYOUT_OCTAGONAL|AV_CH_WIDE_LEFT|AV_CH_WIDE_RIGHT|AV_CH_TOP_BACK_LEFT|AV_CH_TOP_BACK_RIGHT|AV_CH_TOP_BACK_CENTER|AV_CH_TOP_FRONT_CENTER|AV_CH_TOP_FRONT_LEFT|AV_CH_TOP_FRONT_RIGHT) #define AV_CH_LAYOUT_STEREO_DOWNMIX (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT) enum AVMatrixEncoding { AV_MATRIX_ENCODING_NONE, AV_MATRIX_ENCODING_DOLBY, AV_MATRIX_ENCODING_DPLII, AV_MATRIX_ENCODING_DPLIIX, AV_MATRIX_ENCODING_DPLIIZ, AV_MATRIX_ENCODING_DOLBYEX, AV_MATRIX_ENCODING_DOLBYHEADPHONE, AV_MATRIX_ENCODING_NB }; /** * Return a channel layout id that matches name, or 0 if no match is found. * * name can be one or several of the following notations, * separated by '+' or '|': * - the name of an usual channel layout (mono, stereo, 4.0, quad, 5.0, * 5.0(side), 5.1, 5.1(side), 7.1, 7.1(wide), downmix); * - the name of a single channel (FL, FR, FC, LFE, BL, BR, FLC, FRC, BC, * SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR); * - a number of channels, in decimal, followed by 'c', yielding * the default channel layout for that number of channels (@see * av_get_default_channel_layout); * - a channel layout mask, in hexadecimal starting with "0x" (see the * AV_CH_* macros). * * Example: "stereo+FC" = "2c+FC" = "2c+1c" = "0x7" */ uint64_t av_get_channel_layout(const char *name); /** * Return a channel layout and the number of channels based on the specified name. * * This function is similar to (@see av_get_channel_layout), but can also parse * unknown channel layout specifications. * * @param[in] name channel layout specification string * @param[out] channel_layout parsed channel layout (0 if unknown) * @param[out] nb_channels number of channels * * @return 0 on success, AVERROR(EINVAL) if the parsing fails. */ int av_get_extended_channel_layout(const char *name, uint64_t* channel_layout, int* nb_channels); /** * Return a description of a channel layout. * If nb_channels is <= 0, it is guessed from the channel_layout. * * @param buf put here the string containing the channel layout * @param buf_size size in bytes of the buffer */ void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout); struct AVBPrint; /** * Append a description of a channel layout to a bprint buffer. */ void av_bprint_channel_layout(struct AVBPrint *bp, int nb_channels, uint64_t channel_layout); /** * Return the number of channels in the channel layout. */ int av_get_channel_layout_nb_channels(uint64_t channel_layout); /** * Return default channel layout for a given number of channels. */ int64_t av_get_default_channel_layout(int nb_channels); /** * Get the index of a channel in channel_layout. * * @param channel a channel layout describing exactly one channel which must be * present in channel_layout. * * @return index of channel in channel_layout on success, a negative AVERROR * on error. */ int av_get_channel_layout_channel_index(uint64_t channel_layout, uint64_t channel); /** * Get the channel with the given index in channel_layout. */ uint64_t av_channel_layout_extract_channel(uint64_t channel_layout, int index); /** * Get the name of a given channel. * * @return channel name on success, NULL on error. */ const char *av_get_channel_name(uint64_t channel); /** * Get the description of a given channel. * * @param channel a channel layout with a single channel * @return channel description on success, NULL on error */ const char *av_get_channel_description(uint64_t channel); /** * Get the value and name of a standard channel layout. * * @param[in] index index in an internal list, starting at 0 * @param[out] layout channel layout mask * @param[out] name name of the layout * @return 0 if the layout exists, * <0 if index is beyond the limits */ int av_get_standard_channel_layout(unsigned index, uint64_t *layout, const char **name); /** * @} * @} */ #endif /* AVUTIL_CHANNEL_LAYOUT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/common.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * common internal and external API header */ #ifndef AVUTIL_COMMON_H #define AVUTIL_COMMON_H #if defined(__cplusplus) && !defined(__STDC_CONSTANT_MACROS) && !defined(UINT64_C) #error missing -D__STDC_CONSTANT_MACROS / #define __STDC_CONSTANT_MACROS #endif #include #include #include #include #include #include #include #include #include "attributes.h" #include "macros.h" #include "version.h" #include "libavutil/avconfig.h" #if AV_HAVE_BIGENDIAN # define AV_NE(be, le) (be) #else # define AV_NE(be, le) (le) #endif //rounded division & shift #define RSHIFT(a,b) ((a) > 0 ? ((a) + ((1<<(b))>>1))>>(b) : ((a) + ((1<<(b))>>1)-1)>>(b)) /* assume b>0 */ #define ROUNDED_DIV(a,b) (((a)>0 ? (a) + ((b)>>1) : (a) - ((b)>>1))/(b)) /* Fast a/(1<=0 and b>=0 */ #define AV_CEIL_RSHIFT(a,b) (!av_builtin_constant_p(b) ? -((-(a)) >> (b)) \ : ((a) + (1<<(b)) - 1) >> (b)) /* Backwards compat. */ #define FF_CEIL_RSHIFT AV_CEIL_RSHIFT #define FFUDIV(a,b) (((a)>0 ?(a):(a)-(b)+1) / (b)) #define FFUMOD(a,b) ((a)-(b)*FFUDIV(a,b)) /** * Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they * are not representable as absolute values of their type. This is the same * as with *abs() * @see FFNABS() */ #define FFABS(a) ((a) >= 0 ? (a) : (-(a))) #define FFSIGN(a) ((a) > 0 ? 1 : -1) /** * Negative Absolute value. * this works for all integers of all types. * As with many macros, this evaluates its argument twice, it thus must not have * a sideeffect, that is FFNABS(x++) has undefined behavior. */ #define FFNABS(a) ((a) <= 0 ? (a) : (-(a))) /** * Comparator. * For two numerical expressions x and y, gives 1 if x > y, -1 if x < y, and 0 * if x == y. This is useful for instance in a qsort comparator callback. * Furthermore, compilers are able to optimize this to branchless code, and * there is no risk of overflow with signed types. * As with many macros, this evaluates its argument multiple times, it thus * must not have a side-effect. */ #define FFDIFFSIGN(x,y) (((x)>(y)) - ((x)<(y))) #define FFMAX(a,b) ((a) > (b) ? (a) : (b)) #define FFMAX3(a,b,c) FFMAX(FFMAX(a,b),c) #define FFMIN(a,b) ((a) > (b) ? (b) : (a)) #define FFMIN3(a,b,c) FFMIN(FFMIN(a,b),c) #define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0) #define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0])) /* misc math functions */ #ifdef HAVE_AV_CONFIG_H # include "config.h" # include "intmath.h" #endif /* Pull in unguarded fallback defines at the end of this file. */ #include "common.h" #ifndef av_log2 av_const int av_log2(unsigned v); #endif #ifndef av_log2_16bit av_const int av_log2_16bit(unsigned v); #endif /** * Clip a signed integer value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static av_always_inline av_const int av_clip_c(int a, int amin, int amax) { #if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** * Clip a signed 64bit integer value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static av_always_inline av_const int64_t av_clip64_c(int64_t a, int64_t amin, int64_t amax) { #if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** * Clip a signed integer value into the 0-255 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const uint8_t av_clip_uint8_c(int a) { if (a&(~0xFF)) return (~a)>>31; else return a; } /** * Clip a signed integer value into the -128,127 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const int8_t av_clip_int8_c(int a) { if ((a+0x80U) & ~0xFF) return (a>>31) ^ 0x7F; else return a; } /** * Clip a signed integer value into the 0-65535 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const uint16_t av_clip_uint16_c(int a) { if (a&(~0xFFFF)) return (~a)>>31; else return a; } /** * Clip a signed integer value into the -32768,32767 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const int16_t av_clip_int16_c(int a) { if ((a+0x8000U) & ~0xFFFF) return (a>>31) ^ 0x7FFF; else return a; } /** * Clip a signed 64-bit integer value into the -2147483648,2147483647 range. * @param a value to clip * @return clipped value */ static av_always_inline av_const int32_t av_clipl_int32_c(int64_t a) { if ((a+0x80000000u) & ~UINT64_C(0xFFFFFFFF)) return (int32_t)((a>>63) ^ 0x7FFFFFFF); else return (int32_t)a; } /** * Clip a signed integer into the -(2^p),(2^p-1) range. * @param a value to clip * @param p bit position to clip at * @return clipped value */ static av_always_inline av_const int av_clip_intp2_c(int a, int p) { if (((unsigned)a + (1 << p)) & ~((2 << p) - 1)) return (a >> 31) ^ ((1 << p) - 1); else return a; } /** * Clip a signed integer to an unsigned power of two range. * @param a value to clip * @param p bit position to clip at * @return clipped value */ static av_always_inline av_const unsigned av_clip_uintp2_c(int a, int p) { if (a & ~((1<> 31 & ((1<= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** * Clip a double value into the amin-amax range. * @param a value to clip * @param amin minimum value of the clip range * @param amax maximum value of the clip range * @return clipped value */ static av_always_inline av_const double av_clipd_c(double a, double amin, double amax) { #if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2 if (amin > amax) abort(); #endif if (a < amin) return amin; else if (a > amax) return amax; else return a; } /** Compute ceil(log2(x)). * @param x value used to compute ceil(log2(x)) * @return computed ceiling of log2(x) */ static av_always_inline av_const int av_ceil_log2_c(int x) { return av_log2((x - 1) << 1); } /** * Count number of bits set to one in x * @param x value to count bits of * @return the number of bits set to one in x */ static av_always_inline av_const int av_popcount_c(uint32_t x) { x -= (x >> 1) & 0x55555555; x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0F0F0F0F; x += x >> 8; return (x + (x >> 16)) & 0x3F; } /** * Count number of bits set to one in x * @param x value to count bits of * @return the number of bits set to one in x */ static av_always_inline av_const int av_popcount64_c(uint64_t x) { return av_popcount((uint32_t)x) + av_popcount((uint32_t)(x >> 32)); } static av_always_inline av_const int av_parity_c(uint32_t v) { return av_popcount(v) & 1; } #define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((unsigned)(d) << 24)) #define MKBETAG(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((unsigned)(a) << 24)) /** * Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form. * * @param val Output value, must be an lvalue of type uint32_t. * @param GET_BYTE Expression reading one byte from the input. * Evaluated up to 7 times (4 for the currently * assigned Unicode range). With a memory buffer * input, this could be *ptr++. * @param ERROR Expression to be evaluated on invalid input, * typically a goto statement. * * @warning ERROR should not contain a loop control statement which * could interact with the internal while loop, and should force an * exit from the macro code (e.g. through a goto or a return) in order * to prevent undefined results. */ #define GET_UTF8(val, GET_BYTE, ERROR)\ val= (GET_BYTE);\ {\ uint32_t top = (val & 128) >> 1;\ if ((val & 0xc0) == 0x80 || val >= 0xFE)\ ERROR\ while (val & top) {\ int tmp= (GET_BYTE) - 128;\ if(tmp>>6)\ ERROR\ val= (val<<6) + tmp;\ top <<= 5;\ }\ val &= (top << 1) - 1;\ } /** * Convert a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form. * * @param val Output value, must be an lvalue of type uint32_t. * @param GET_16BIT Expression returning two bytes of UTF-16 data converted * to native byte order. Evaluated one or two times. * @param ERROR Expression to be evaluated on invalid input, * typically a goto statement. */ #define GET_UTF16(val, GET_16BIT, ERROR)\ val = GET_16BIT;\ {\ unsigned int hi = val - 0xD800;\ if (hi < 0x800) {\ val = GET_16BIT - 0xDC00;\ if (val > 0x3FFU || hi > 0x3FFU)\ ERROR\ val += (hi<<10) + 0x10000;\ }\ }\ /** * @def PUT_UTF8(val, tmp, PUT_BYTE) * Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long). * @param val is an input-only argument and should be of type uint32_t. It holds * a UCS-4 encoded Unicode character that is to be converted to UTF-8. If * val is given as a function it is executed only once. * @param tmp is a temporary variable and should be of type uint8_t. It * represents an intermediate value during conversion that is to be * output by PUT_BYTE. * @param PUT_BYTE writes the converted UTF-8 bytes to any proper destination. * It could be a function or a statement, and uses tmp as the input byte. * For example, PUT_BYTE could be "*output++ = tmp;" PUT_BYTE will be * executed up to 4 times for values in the valid UTF-8 range and up to * 7 times in the general case, depending on the length of the converted * Unicode character. */ #define PUT_UTF8(val, tmp, PUT_BYTE)\ {\ int bytes, shift;\ uint32_t in = val;\ if (in < 0x80) {\ tmp = in;\ PUT_BYTE\ } else {\ bytes = (av_log2(in) + 4) / 5;\ shift = (bytes - 1) * 6;\ tmp = (256 - (256 >> bytes)) | (in >> shift);\ PUT_BYTE\ while (shift >= 6) {\ shift -= 6;\ tmp = 0x80 | ((in >> shift) & 0x3f);\ PUT_BYTE\ }\ }\ } /** * @def PUT_UTF16(val, tmp, PUT_16BIT) * Convert a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes). * @param val is an input-only argument and should be of type uint32_t. It holds * a UCS-4 encoded Unicode character that is to be converted to UTF-16. If * val is given as a function it is executed only once. * @param tmp is a temporary variable and should be of type uint16_t. It * represents an intermediate value during conversion that is to be * output by PUT_16BIT. * @param PUT_16BIT writes the converted UTF-16 data to any proper destination * in desired endianness. It could be a function or a statement, and uses tmp * as the input byte. For example, PUT_BYTE could be "*output++ = tmp;" * PUT_BYTE will be executed 1 or 2 times depending on input character. */ #define PUT_UTF16(val, tmp, PUT_16BIT)\ {\ uint32_t in = val;\ if (in < 0x10000) {\ tmp = in;\ PUT_16BIT\ } else {\ tmp = 0xD800 | ((in - 0x10000) >> 10);\ PUT_16BIT\ tmp = 0xDC00 | ((in - 0x10000) & 0x3FF);\ PUT_16BIT\ }\ }\ #include "mem.h" #ifdef HAVE_AV_CONFIG_H # include "internal.h" #endif /* HAVE_AV_CONFIG_H */ #endif /* AVUTIL_COMMON_H */ /* * The following definitions are outside the multiple inclusion guard * to ensure they are immediately available in intmath.h. */ #ifndef av_ceil_log2 # define av_ceil_log2 av_ceil_log2_c #endif #ifndef av_clip # define av_clip av_clip_c #endif #ifndef av_clip64 # define av_clip64 av_clip64_c #endif #ifndef av_clip_uint8 # define av_clip_uint8 av_clip_uint8_c #endif #ifndef av_clip_int8 # define av_clip_int8 av_clip_int8_c #endif #ifndef av_clip_uint16 # define av_clip_uint16 av_clip_uint16_c #endif #ifndef av_clip_int16 # define av_clip_int16 av_clip_int16_c #endif #ifndef av_clipl_int32 # define av_clipl_int32 av_clipl_int32_c #endif #ifndef av_clip_intp2 # define av_clip_intp2 av_clip_intp2_c #endif #ifndef av_clip_uintp2 # define av_clip_uintp2 av_clip_uintp2_c #endif #ifndef av_mod_uintp2 # define av_mod_uintp2 av_mod_uintp2_c #endif #ifndef av_sat_add32 # define av_sat_add32 av_sat_add32_c #endif #ifndef av_sat_dadd32 # define av_sat_dadd32 av_sat_dadd32_c #endif #ifndef av_sat_sub32 # define av_sat_sub32 av_sat_sub32_c #endif #ifndef av_sat_dsub32 # define av_sat_dsub32 av_sat_dsub32_c #endif #ifndef av_clipf # define av_clipf av_clipf_c #endif #ifndef av_clipd # define av_clipd av_clipd_c #endif #ifndef av_popcount # define av_popcount av_popcount_c #endif #ifndef av_popcount64 # define av_popcount64 av_popcount64_c #endif #ifndef av_parity # define av_parity av_parity_c #endif ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/cpu.h ================================================ /* * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_CPU_H #define AVUTIL_CPU_H #include #include "attributes.h" #define AV_CPU_FLAG_FORCE 0x80000000 /* force usage of selected flags (OR) */ /* lower 16 bits - CPU features */ #define AV_CPU_FLAG_MMX 0x0001 ///< standard MMX #define AV_CPU_FLAG_MMXEXT 0x0002 ///< SSE integer functions or AMD MMX ext #define AV_CPU_FLAG_MMX2 0x0002 ///< SSE integer functions or AMD MMX ext #define AV_CPU_FLAG_3DNOW 0x0004 ///< AMD 3DNOW #define AV_CPU_FLAG_SSE 0x0008 ///< SSE functions #define AV_CPU_FLAG_SSE2 0x0010 ///< PIV SSE2 functions #define AV_CPU_FLAG_SSE2SLOW 0x40000000 ///< SSE2 supported, but usually not faster ///< than regular MMX/SSE (e.g. Core1) #define AV_CPU_FLAG_3DNOWEXT 0x0020 ///< AMD 3DNowExt #define AV_CPU_FLAG_SSE3 0x0040 ///< Prescott SSE3 functions #define AV_CPU_FLAG_SSE3SLOW 0x20000000 ///< SSE3 supported, but usually not faster ///< than regular MMX/SSE (e.g. Core1) #define AV_CPU_FLAG_SSSE3 0x0080 ///< Conroe SSSE3 functions #define AV_CPU_FLAG_SSSE3SLOW 0x4000000 ///< SSSE3 supported, but usually not faster #define AV_CPU_FLAG_ATOM 0x10000000 ///< Atom processor, some SSSE3 instructions are slower #define AV_CPU_FLAG_SSE4 0x0100 ///< Penryn SSE4.1 functions #define AV_CPU_FLAG_SSE42 0x0200 ///< Nehalem SSE4.2 functions #define AV_CPU_FLAG_AESNI 0x80000 ///< Advanced Encryption Standard functions #define AV_CPU_FLAG_AVX 0x4000 ///< AVX functions: requires OS support even if YMM registers aren't used #define AV_CPU_FLAG_AVXSLOW 0x8000000 ///< AVX supported, but slow when using YMM registers (e.g. Bulldozer) #define AV_CPU_FLAG_XOP 0x0400 ///< Bulldozer XOP functions #define AV_CPU_FLAG_FMA4 0x0800 ///< Bulldozer FMA4 functions #define AV_CPU_FLAG_CMOV 0x1000 ///< supports cmov instruction #define AV_CPU_FLAG_AVX2 0x8000 ///< AVX2 functions: requires OS support even if YMM registers aren't used #define AV_CPU_FLAG_FMA3 0x10000 ///< Haswell FMA3 functions #define AV_CPU_FLAG_BMI1 0x20000 ///< Bit Manipulation Instruction Set 1 #define AV_CPU_FLAG_BMI2 0x40000 ///< Bit Manipulation Instruction Set 2 #define AV_CPU_FLAG_AVX512 0x100000 ///< AVX-512 functions: requires OS support even if YMM/ZMM registers aren't used #define AV_CPU_FLAG_ALTIVEC 0x0001 ///< standard #define AV_CPU_FLAG_VSX 0x0002 ///< ISA 2.06 #define AV_CPU_FLAG_POWER8 0x0004 ///< ISA 2.07 #define AV_CPU_FLAG_ARMV5TE (1 << 0) #define AV_CPU_FLAG_ARMV6 (1 << 1) #define AV_CPU_FLAG_ARMV6T2 (1 << 2) #define AV_CPU_FLAG_VFP (1 << 3) #define AV_CPU_FLAG_VFPV3 (1 << 4) #define AV_CPU_FLAG_NEON (1 << 5) #define AV_CPU_FLAG_ARMV8 (1 << 6) #define AV_CPU_FLAG_VFP_VM (1 << 7) ///< VFPv2 vector mode, deprecated in ARMv7-A and unavailable in various CPUs implementations #define AV_CPU_FLAG_SETEND (1 <<16) /** * Return the flags which specify extensions supported by the CPU. * The returned value is affected by av_force_cpu_flags() if that was used * before. So av_get_cpu_flags() can easily be used in an application to * detect the enabled cpu flags. */ int av_get_cpu_flags(void); /** * Disables cpu detection and forces the specified flags. * -1 is a special case that disables forcing of specific flags. */ void av_force_cpu_flags(int flags); /** * Set a mask on flags returned by av_get_cpu_flags(). * This function is mainly useful for testing. * Please use av_force_cpu_flags() and av_get_cpu_flags() instead which are more flexible */ attribute_deprecated void av_set_cpu_flags_mask(int mask); /** * Parse CPU flags from a string. * * The returned flags contain the specified flags as well as related unspecified flags. * * This function exists only for compatibility with libav. * Please use av_parse_cpu_caps() when possible. * @return a combination of AV_CPU_* flags, negative on error. */ attribute_deprecated int av_parse_cpu_flags(const char *s); /** * Parse CPU caps from a string and update the given AV_CPU_* flags based on that. * * @return negative on error. */ int av_parse_cpu_caps(unsigned *flags, const char *s); /** * @return the number of logical CPU cores present. */ int av_cpu_count(void); /** * Get the maximum data alignment that may be required by FFmpeg. * * Note that this is affected by the build configuration and the CPU flags mask, * so e.g. if the CPU supports AVX, but libavutil has been built with * --disable-avx or the AV_CPU_FLAG_AVX flag has been disabled through * av_set_cpu_flags_mask(), then this function will behave as if AVX is not * present. */ size_t av_cpu_max_align(void); #endif /* AVUTIL_CPU_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/crc.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_crc32 * Public header for CRC hash function implementation. */ #ifndef AVUTIL_CRC_H #define AVUTIL_CRC_H #include #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_crc32 CRC * @ingroup lavu_hash * CRC (Cyclic Redundancy Check) hash function implementation. * * This module supports numerous CRC polynomials, in addition to the most * widely used CRC-32-IEEE. See @ref AVCRCId for a list of available * polynomials. * * @{ */ typedef uint32_t AVCRC; typedef enum { AV_CRC_8_ATM, AV_CRC_16_ANSI, AV_CRC_16_CCITT, AV_CRC_32_IEEE, AV_CRC_32_IEEE_LE, /*< reversed bitorder version of AV_CRC_32_IEEE */ AV_CRC_16_ANSI_LE, /*< reversed bitorder version of AV_CRC_16_ANSI */ AV_CRC_24_IEEE, AV_CRC_8_EBU, AV_CRC_MAX, /*< Not part of public API! Do not use outside libavutil. */ }AVCRCId; /** * Initialize a CRC table. * @param ctx must be an array of size sizeof(AVCRC)*257 or sizeof(AVCRC)*1024 * @param le If 1, the lowest bit represents the coefficient for the highest * exponent of the corresponding polynomial (both for poly and * actual CRC). * If 0, you must swap the CRC parameter and the result of av_crc * if you need the standard representation (can be simplified in * most cases to e.g. bswap16): * av_bswap32(crc << (32-bits)) * @param bits number of bits for the CRC * @param poly generator polynomial without the x**bits coefficient, in the * representation as specified by le * @param ctx_size size of ctx in bytes * @return <0 on failure */ int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size); /** * Get an initialized standard CRC table. * @param crc_id ID of a standard CRC * @return a pointer to the CRC table or NULL on failure */ const AVCRC *av_crc_get_table(AVCRCId crc_id); /** * Calculate the CRC of a block. * @param crc CRC of previous blocks if any or initial value for CRC * @return CRC updated with the data from the given block * * @see av_crc_init() "le" parameter */ uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length) av_pure; /** * @} */ #endif /* AVUTIL_CRC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/des.h ================================================ /* * DES encryption/decryption * Copyright (c) 2007 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_DES_H #define AVUTIL_DES_H #include /** * @defgroup lavu_des DES * @ingroup lavu_crypto * @{ */ typedef struct AVDES { uint64_t round_keys[3][16]; int triple_des; } AVDES; /** * Allocate an AVDES context. */ AVDES *av_des_alloc(void); /** * @brief Initializes an AVDES context. * * @param key_bits must be 64 or 192 * @param decrypt 0 for encryption/CBC-MAC, 1 for decryption * @return zero on success, negative value otherwise */ int av_des_init(struct AVDES *d, const uint8_t *key, int key_bits, int decrypt); /** * @brief Encrypts / decrypts using the DES algorithm. * * @param count number of 8 byte blocks * @param dst destination array, can be equal to src, must be 8-byte aligned * @param src source array, can be equal to dst, must be 8-byte aligned, may be NULL * @param iv initialization vector for CBC mode, if NULL then ECB will be used, * must be 8-byte aligned * @param decrypt 0 for encryption, 1 for decryption */ void av_des_crypt(struct AVDES *d, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @brief Calculates CBC-MAC using the DES algorithm. * * @param count number of 8 byte blocks * @param dst destination array, can be equal to src, must be 8-byte aligned * @param src source array, can be equal to dst, must be 8-byte aligned, may be NULL */ void av_des_mac(struct AVDES *d, uint8_t *dst, const uint8_t *src, int count); /** * @} */ #endif /* AVUTIL_DES_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/dict.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Public dictionary API. * @deprecated * AVDictionary is provided for compatibility with libav. It is both in * implementation as well as API inefficient. It does not scale and is * extremely slow with large dictionaries. * It is recommended that new code uses our tree container from tree.c/h * where applicable, which uses AVL trees to achieve O(log n) performance. */ #ifndef AVUTIL_DICT_H #define AVUTIL_DICT_H #include #include "version.h" /** * @addtogroup lavu_dict AVDictionary * @ingroup lavu_data * * @brief Simple key:value store * * @{ * Dictionaries are used for storing key:value pairs. To create * an AVDictionary, simply pass an address of a NULL pointer to * av_dict_set(). NULL can be used as an empty dictionary wherever * a pointer to an AVDictionary is required. * Use av_dict_get() to retrieve an entry or iterate over all * entries and finally av_dict_free() to free the dictionary * and all its contents. * @code AVDictionary *d = NULL; // "create" an empty dictionary AVDictionaryEntry *t = NULL; av_dict_set(&d, "foo", "bar", 0); // add an entry char *k = av_strdup("key"); // if your strings are already allocated, char *v = av_strdup("value"); // you can avoid copying them like this av_dict_set(&d, k, v, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL); while (t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX)) { <....> // iterate over all entries in d } av_dict_free(&d); @endcode */ #define AV_DICT_MATCH_CASE 1 /**< Only get an entry with exact-case key match. Only relevant in av_dict_get(). */ #define AV_DICT_IGNORE_SUFFIX 2 /**< Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string. Only relevant in av_dict_get(). */ #define AV_DICT_DONT_STRDUP_KEY 4 /**< Take ownership of a key that's been allocated with av_malloc() or another memory allocation function. */ #define AV_DICT_DONT_STRDUP_VAL 8 /**< Take ownership of a value that's been allocated with av_malloc() or another memory allocation function. */ #define AV_DICT_DONT_OVERWRITE 16 ///< Don't overwrite existing entries. #define AV_DICT_APPEND 32 /**< If the entry already exists, append to it. Note that no delimiter is added, the strings are simply concatenated. */ #define AV_DICT_MULTIKEY 64 /**< Allow to store several equal keys in the dictionary */ typedef struct AVDictionaryEntry { char *key; char *value; } AVDictionaryEntry; typedef struct AVDictionary AVDictionary; /** * Get a dictionary entry with matching key. * * The returned entry key or value must not be changed, or it will * cause undefined behavior. * * To iterate through all the dictionary entries, you can set the matching key * to the null string "" and set the AV_DICT_IGNORE_SUFFIX flag. * * @param prev Set to the previous matching element to find the next. * If set to NULL the first matching element is returned. * @param key matching key * @param flags a collection of AV_DICT_* flags controlling how the entry is retrieved * @return found entry or NULL in case no matching entry was found in the dictionary */ AVDictionaryEntry *av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags); /** * Get number of entries in dictionary. * * @param m dictionary * @return number of entries in dictionary */ int av_dict_count(const AVDictionary *m); /** * Set the given entry in *pm, overwriting an existing entry. * * Note: If AV_DICT_DONT_STRDUP_KEY or AV_DICT_DONT_STRDUP_VAL is set, * these arguments will be freed on error. * * Warning: Adding a new entry to a dictionary invalidates all existing entries * previously returned with av_dict_get. * * @param pm pointer to a pointer to a dictionary struct. If *pm is NULL * a dictionary struct is allocated and put in *pm. * @param key entry key to add to *pm (will either be av_strduped or added as a new key depending on flags) * @param value entry value to add to *pm (will be av_strduped or added as a new key depending on flags). * Passing a NULL value will cause an existing entry to be deleted. * @return >= 0 on success otherwise an error code <0 */ int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags); /** * Convenience wrapper for av_dict_set that converts the value to a string * and stores it. * * Note: If AV_DICT_DONT_STRDUP_KEY is set, key will be freed on error. */ int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags); /** * Parse the key/value pairs list and add the parsed entries to a dictionary. * * In case of failure, all the successfully set entries are stored in * *pm. You may need to manually free the created dictionary. * * @param key_val_sep a 0-terminated list of characters used to separate * key from value * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other * @param flags flags to use when adding to dictionary. * AV_DICT_DONT_STRDUP_KEY and AV_DICT_DONT_STRDUP_VAL * are ignored since the key/value tokens will always * be duplicated. * @return 0 on success, negative AVERROR code on failure */ int av_dict_parse_string(AVDictionary **pm, const char *str, const char *key_val_sep, const char *pairs_sep, int flags); /** * Copy entries from one AVDictionary struct into another. * @param dst pointer to a pointer to a AVDictionary struct. If *dst is NULL, * this function will allocate a struct for you and put it in *dst * @param src pointer to source AVDictionary struct * @param flags flags to use when setting entries in *dst * @note metadata is read using the AV_DICT_IGNORE_SUFFIX flag * @return 0 on success, negative AVERROR code on failure. If dst was allocated * by this function, callers should free the associated memory. */ int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags); /** * Free all the memory allocated for an AVDictionary struct * and all keys and values. */ void av_dict_free(AVDictionary **m); /** * Get dictionary entries as a string. * * Create a string containing dictionary's entries. * Such string may be passed back to av_dict_parse_string(). * @note String is escaped with backslashes ('\'). * * @param[in] m dictionary * @param[out] buffer Pointer to buffer that will be allocated with string containg entries. * Buffer must be freed by the caller when is no longer needed. * @param[in] key_val_sep character used to separate key from value * @param[in] pairs_sep character used to separate two pairs from each other * @return >= 0 on success, negative on error * @warning Separators cannot be neither '\\' nor '\0'. They also cannot be the same. */ int av_dict_get_string(const AVDictionary *m, char **buffer, const char key_val_sep, const char pairs_sep); /** * @} */ #endif /* AVUTIL_DICT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/display.h ================================================ /* * Copyright (c) 2014 Vittorio Giovara * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Display matrix */ #ifndef AVUTIL_DISPLAY_H #define AVUTIL_DISPLAY_H #include #include "common.h" /** * @addtogroup lavu_video * @{ * * @defgroup lavu_video_display Display transformation matrix functions * @{ */ /** * @addtogroup lavu_video_display * The display transformation matrix specifies an affine transformation that * should be applied to video frames for correct presentation. It is compatible * with the matrices stored in the ISO/IEC 14496-12 container format. * * The data is a 3x3 matrix represented as a 9-element array: * * @code{.unparsed} * | a b u | * (a, b, u, c, d, v, x, y, w) -> | c d v | * | x y w | * @endcode * * All numbers are stored in native endianness, as 16.16 fixed-point values, * except for u, v and w, which are stored as 2.30 fixed-point values. * * The transformation maps a point (p, q) in the source (pre-transformation) * frame to the point (p', q') in the destination (post-transformation) frame as * follows: * * @code{.unparsed} * | a b u | * (p, q, 1) . | c d v | = z * (p', q', 1) * | x y w | * @endcode * * The transformation can also be more explicitly written in components as * follows: * * @code{.unparsed} * p' = (a * p + c * q + x) / z; * q' = (b * p + d * q + y) / z; * z = u * p + v * q + w * @endcode */ /** * Extract the rotation component of the transformation matrix. * * @param matrix the transformation matrix * @return the angle (in degrees) by which the transformation rotates the frame * counterclockwise. The angle will be in range [-180.0, 180.0], * or NaN if the matrix is singular. * * @note floating point numbers are inherently inexact, so callers are * recommended to round the return value to nearest integer before use. */ double av_display_rotation_get(const int32_t matrix[9]); /** * Initialize a transformation matrix describing a pure counterclockwise * rotation by the specified angle (in degrees). * * @param matrix an allocated transformation matrix (will be fully overwritten * by this function) * @param angle rotation angle in degrees. */ void av_display_rotation_set(int32_t matrix[9], double angle); /** * Flip the input matrix horizontally and/or vertically. * * @param matrix an allocated transformation matrix * @param hflip whether the matrix should be flipped horizontally * @param vflip whether the matrix should be flipped vertically */ void av_display_matrix_flip(int32_t matrix[9], int hflip, int vflip); /** * @} * @} */ #endif /* AVUTIL_DISPLAY_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/downmix_info.h ================================================ /* * Copyright (c) 2014 Tim Walker * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_DOWNMIX_INFO_H #define AVUTIL_DOWNMIX_INFO_H #include "frame.h" /** * @file * audio downmix medatata */ /** * @addtogroup lavu_audio * @{ */ /** * @defgroup downmix_info Audio downmix metadata * @{ */ /** * Possible downmix types. */ enum AVDownmixType { AV_DOWNMIX_TYPE_UNKNOWN, /**< Not indicated. */ AV_DOWNMIX_TYPE_LORO, /**< Lo/Ro 2-channel downmix (Stereo). */ AV_DOWNMIX_TYPE_LTRT, /**< Lt/Rt 2-channel downmix, Dolby Surround compatible. */ AV_DOWNMIX_TYPE_DPLII, /**< Lt/Rt 2-channel downmix, Dolby Pro Logic II compatible. */ AV_DOWNMIX_TYPE_NB /**< Number of downmix types. Not part of ABI. */ }; /** * This structure describes optional metadata relevant to a downmix procedure. * * All fields are set by the decoder to the value indicated in the audio * bitstream (if present), or to a "sane" default otherwise. */ typedef struct AVDownmixInfo { /** * Type of downmix preferred by the mastering engineer. */ enum AVDownmixType preferred_downmix_type; /** * Absolute scale factor representing the nominal level of the center * channel during a regular downmix. */ double center_mix_level; /** * Absolute scale factor representing the nominal level of the center * channel during an Lt/Rt compatible downmix. */ double center_mix_level_ltrt; /** * Absolute scale factor representing the nominal level of the surround * channels during a regular downmix. */ double surround_mix_level; /** * Absolute scale factor representing the nominal level of the surround * channels during an Lt/Rt compatible downmix. */ double surround_mix_level_ltrt; /** * Absolute scale factor representing the level at which the LFE data is * mixed into L/R channels during downmixing. */ double lfe_mix_level; } AVDownmixInfo; /** * Get a frame's AV_FRAME_DATA_DOWNMIX_INFO side data for editing. * * If the side data is absent, it is created and added to the frame. * * @param frame the frame for which the side data is to be obtained or created * * @return the AVDownmixInfo structure to be edited by the caller, or NULL if * the structure cannot be allocated. */ AVDownmixInfo *av_downmix_info_update_side_data(AVFrame *frame); /** * @} */ /** * @} */ #endif /* AVUTIL_DOWNMIX_INFO_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/encryption_info.h ================================================ /** * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_ENCRYPTION_INFO_H #define AVUTIL_ENCRYPTION_INFO_H #include #include typedef struct AVSubsampleEncryptionInfo { /** The number of bytes that are clear. */ unsigned int bytes_of_clear_data; /** * The number of bytes that are protected. If using pattern encryption, * the pattern applies to only the protected bytes; if not using pattern * encryption, all these bytes are encrypted. */ unsigned int bytes_of_protected_data; } AVSubsampleEncryptionInfo; /** * This describes encryption info for a packet. This contains frame-specific * info for how to decrypt the packet before passing it to the decoder. * * The size of this struct is not part of the public ABI. */ typedef struct AVEncryptionInfo { /** The fourcc encryption scheme, in big-endian byte order. */ uint32_t scheme; /** * Only used for pattern encryption. This is the number of 16-byte blocks * that are encrypted. */ uint32_t crypt_byte_block; /** * Only used for pattern encryption. This is the number of 16-byte blocks * that are clear. */ uint32_t skip_byte_block; /** * The ID of the key used to encrypt the packet. This should always be * 16 bytes long, but may be changed in the future. */ uint8_t *key_id; uint32_t key_id_size; /** * The initialization vector. This may have been zero-filled to be the * correct block size. This should always be 16 bytes long, but may be * changed in the future. */ uint8_t *iv; uint32_t iv_size; /** * An array of subsample encryption info specifying how parts of the sample * are encrypted. If there are no subsamples, then the whole sample is * encrypted. */ AVSubsampleEncryptionInfo *subsamples; uint32_t subsample_count; } AVEncryptionInfo; /** * This describes info used to initialize an encryption key system. * * The size of this struct is not part of the public ABI. */ typedef struct AVEncryptionInitInfo { /** * A unique identifier for the key system this is for, can be NULL if it * is not known. This should always be 16 bytes, but may change in the * future. */ uint8_t* system_id; uint32_t system_id_size; /** * An array of key IDs this initialization data is for. All IDs are the * same length. Can be NULL if there are no known key IDs. */ uint8_t** key_ids; /** The number of key IDs. */ uint32_t num_key_ids; /** * The number of bytes in each key ID. This should always be 16, but may * change in the future. */ uint32_t key_id_size; /** * Key-system specific initialization data. This data is copied directly * from the file and the format depends on the specific key system. This * can be NULL if there is no initialization data; in that case, there * will be at least one key ID. */ uint8_t* data; uint32_t data_size; /** * An optional pointer to the next initialization info in the list. */ struct AVEncryptionInitInfo *next; } AVEncryptionInitInfo; /** * Allocates an AVEncryptionInfo structure and sub-pointers to hold the given * number of subsamples. This will allocate pointers for the key ID, IV, * and subsample entries, set the size members, and zero-initialize the rest. * * @param subsample_count The number of subsamples. * @param key_id_size The number of bytes in the key ID, should be 16. * @param iv_size The number of bytes in the IV, should be 16. * * @return The new AVEncryptionInfo structure, or NULL on error. */ AVEncryptionInfo *av_encryption_info_alloc(uint32_t subsample_count, uint32_t key_id_size, uint32_t iv_size); /** * Allocates an AVEncryptionInfo structure with a copy of the given data. * @return The new AVEncryptionInfo structure, or NULL on error. */ AVEncryptionInfo *av_encryption_info_clone(const AVEncryptionInfo *info); /** * Frees the given encryption info object. This MUST NOT be used to free the * side-data data pointer, that should use normal side-data methods. */ void av_encryption_info_free(AVEncryptionInfo *info); /** * Creates a copy of the AVEncryptionInfo that is contained in the given side * data. The resulting object should be passed to av_encryption_info_free() * when done. * * @return The new AVEncryptionInfo structure, or NULL on error. */ AVEncryptionInfo *av_encryption_info_get_side_data(const uint8_t *side_data, size_t side_data_size); /** * Allocates and initializes side data that holds a copy of the given encryption * info. The resulting pointer should be either freed using av_free or given * to av_packet_add_side_data(). * * @return The new side-data pointer, or NULL. */ uint8_t *av_encryption_info_add_side_data( const AVEncryptionInfo *info, size_t *side_data_size); /** * Allocates an AVEncryptionInitInfo structure and sub-pointers to hold the * given sizes. This will allocate pointers and set all the fields. * * @return The new AVEncryptionInitInfo structure, or NULL on error. */ AVEncryptionInitInfo *av_encryption_init_info_alloc( uint32_t system_id_size, uint32_t num_key_ids, uint32_t key_id_size, uint32_t data_size); /** * Frees the given encryption init info object. This MUST NOT be used to free * the side-data data pointer, that should use normal side-data methods. */ void av_encryption_init_info_free(AVEncryptionInitInfo* info); /** * Creates a copy of the AVEncryptionInitInfo that is contained in the given * side data. The resulting object should be passed to * av_encryption_init_info_free() when done. * * @return The new AVEncryptionInitInfo structure, or NULL on error. */ AVEncryptionInitInfo *av_encryption_init_info_get_side_data( const uint8_t* side_data, size_t side_data_size); /** * Allocates and initializes side data that holds a copy of the given encryption * init info. The resulting pointer should be either freed using av_free or * given to av_packet_add_side_data(). * * @return The new side-data pointer, or NULL. */ uint8_t *av_encryption_init_info_add_side_data( const AVEncryptionInitInfo *info, size_t *side_data_size); #endif /* AVUTIL_ENCRYPTION_INFO_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/error.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * error code definitions */ #ifndef AVUTIL_ERROR_H #define AVUTIL_ERROR_H #include #include /** * @addtogroup lavu_error * * @{ */ /* error handling */ #if EDOM > 0 #define AVERROR(e) (-(e)) ///< Returns a negative error code from a POSIX error code, to return from library functions. #define AVUNERROR(e) (-(e)) ///< Returns a POSIX error code from a library function error return value. #else /* Some platforms have E* and errno already negated. */ #define AVERROR(e) (e) #define AVUNERROR(e) (e) #endif #define FFERRTAG(a, b, c, d) (-(int)MKTAG(a, b, c, d)) #define AVERROR_BSF_NOT_FOUND FFERRTAG(0xF8,'B','S','F') ///< Bitstream filter not found #define AVERROR_BUG FFERRTAG( 'B','U','G','!') ///< Internal bug, also see AVERROR_BUG2 #define AVERROR_BUFFER_TOO_SMALL FFERRTAG( 'B','U','F','S') ///< Buffer too small #define AVERROR_DECODER_NOT_FOUND FFERRTAG(0xF8,'D','E','C') ///< Decoder not found #define AVERROR_DEMUXER_NOT_FOUND FFERRTAG(0xF8,'D','E','M') ///< Demuxer not found #define AVERROR_ENCODER_NOT_FOUND FFERRTAG(0xF8,'E','N','C') ///< Encoder not found #define AVERROR_EOF FFERRTAG( 'E','O','F',' ') ///< End of file #define AVERROR_EXIT FFERRTAG( 'E','X','I','T') ///< Immediate exit was requested; the called function should not be restarted #define AVERROR_EXTERNAL FFERRTAG( 'E','X','T',' ') ///< Generic error in an external library #define AVERROR_FILTER_NOT_FOUND FFERRTAG(0xF8,'F','I','L') ///< Filter not found #define AVERROR_INVALIDDATA FFERRTAG( 'I','N','D','A') ///< Invalid data found when processing input #define AVERROR_MUXER_NOT_FOUND FFERRTAG(0xF8,'M','U','X') ///< Muxer not found #define AVERROR_OPTION_NOT_FOUND FFERRTAG(0xF8,'O','P','T') ///< Option not found #define AVERROR_PATCHWELCOME FFERRTAG( 'P','A','W','E') ///< Not yet implemented in FFmpeg, patches welcome #define AVERROR_PROTOCOL_NOT_FOUND FFERRTAG(0xF8,'P','R','O') ///< Protocol not found #define AVERROR_STREAM_NOT_FOUND FFERRTAG(0xF8,'S','T','R') ///< Stream not found /** * This is semantically identical to AVERROR_BUG * it has been introduced in Libav after our AVERROR_BUG and with a modified value. */ #define AVERROR_BUG2 FFERRTAG( 'B','U','G',' ') #define AVERROR_UNKNOWN FFERRTAG( 'U','N','K','N') ///< Unknown error, typically from an external library #define AVERROR_EXPERIMENTAL (-0x2bb2afa8) ///< Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it. #define AVERROR_INPUT_CHANGED (-0x636e6701) ///< Input changed between calls. Reconfiguration is required. (can be OR-ed with AVERROR_OUTPUT_CHANGED) #define AVERROR_OUTPUT_CHANGED (-0x636e6702) ///< Output changed between calls. Reconfiguration is required. (can be OR-ed with AVERROR_INPUT_CHANGED) /* HTTP & RTSP errors */ #define AVERROR_HTTP_BAD_REQUEST FFERRTAG(0xF8,'4','0','0') #define AVERROR_HTTP_UNAUTHORIZED FFERRTAG(0xF8,'4','0','1') #define AVERROR_HTTP_FORBIDDEN FFERRTAG(0xF8,'4','0','3') #define AVERROR_HTTP_NOT_FOUND FFERRTAG(0xF8,'4','0','4') #define AVERROR_HTTP_OTHER_4XX FFERRTAG(0xF8,'4','X','X') #define AVERROR_HTTP_SERVER_ERROR FFERRTAG(0xF8,'5','X','X') #define AV_ERROR_MAX_STRING_SIZE 64 /** * Put a description of the AVERROR code errnum in errbuf. * In case of failure the global variable errno is set to indicate the * error. Even in case of failure av_strerror() will print a generic * error message indicating the errnum provided to errbuf. * * @param errnum error code to describe * @param errbuf buffer to which description is written * @param errbuf_size the size in bytes of errbuf * @return 0 on success, a negative value if a description for errnum * cannot be found */ int av_strerror(int errnum, char *errbuf, size_t errbuf_size); /** * Fill the provided buffer with a string containing an error string * corresponding to the AVERROR code errnum. * * @param errbuf a buffer * @param errbuf_size size in bytes of errbuf * @param errnum error code to describe * @return the buffer in input, filled with the error description * @see av_strerror() */ static inline char *av_make_error_string(char *errbuf, size_t errbuf_size, int errnum) { av_strerror(errnum, errbuf, errbuf_size); return errbuf; } /** * Convenience macro, the return value should be used only directly in * function arguments but never stand-alone. */ #define av_err2str(errnum) \ av_make_error_string((char[AV_ERROR_MAX_STRING_SIZE]){0}, AV_ERROR_MAX_STRING_SIZE, errnum) /** * @} */ #endif /* AVUTIL_ERROR_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/eval.h ================================================ /* * Copyright (c) 2002 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * simple arithmetic expression evaluator */ #ifndef AVUTIL_EVAL_H #define AVUTIL_EVAL_H #include "avutil.h" typedef struct AVExpr AVExpr; /** * Parse and evaluate an expression. * Note, this is significantly slower than av_expr_eval(). * * @param res a pointer to a double where is put the result value of * the expression, or NAN in case of error * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)" * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0} * @param const_values a zero terminated array of values for the identifiers from const_names * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2 * @param log_ctx parent logging context * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code otherwise */ int av_expr_parse_and_eval(double *res, const char *s, const char * const *const_names, const double *const_values, const char * const *func1_names, double (* const *funcs1)(void *, double), const char * const *func2_names, double (* const *funcs2)(void *, double, double), void *opaque, int log_offset, void *log_ctx); /** * Parse an expression. * * @param expr a pointer where is put an AVExpr containing the parsed * value in case of successful parsing, or NULL otherwise. * The pointed to AVExpr must be freed with av_expr_free() by the user * when it is not needed anymore. * @param s expression as a zero terminated string, for example "1+2^3+5*5+sin(2/3)" * @param const_names NULL terminated array of zero terminated strings of constant identifiers, for example {"PI", "E", 0} * @param func1_names NULL terminated array of zero terminated strings of funcs1 identifiers * @param funcs1 NULL terminated array of function pointers for functions which take 1 argument * @param func2_names NULL terminated array of zero terminated strings of funcs2 identifiers * @param funcs2 NULL terminated array of function pointers for functions which take 2 arguments * @param log_ctx parent logging context * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code otherwise */ int av_expr_parse(AVExpr **expr, const char *s, const char * const *const_names, const char * const *func1_names, double (* const *funcs1)(void *, double), const char * const *func2_names, double (* const *funcs2)(void *, double, double), int log_offset, void *log_ctx); /** * Evaluate a previously parsed expression. * * @param const_values a zero terminated array of values for the identifiers from av_expr_parse() const_names * @param opaque a pointer which will be passed to all functions from funcs1 and funcs2 * @return the value of the expression */ double av_expr_eval(AVExpr *e, const double *const_values, void *opaque); /** * Free a parsed expression previously created with av_expr_parse(). */ void av_expr_free(AVExpr *e); /** * Parse the string in numstr and return its value as a double. If * the string is empty, contains only whitespaces, or does not contain * an initial substring that has the expected syntax for a * floating-point number, no conversion is performed. In this case, * returns a value of zero and the value returned in tail is the value * of numstr. * * @param numstr a string representing a number, may contain one of * the International System number postfixes, for example 'K', 'M', * 'G'. If 'i' is appended after the postfix, powers of 2 are used * instead of powers of 10. The 'B' postfix multiplies the value by * 8, and can be appended after another postfix or used alone. This * allows using for example 'KB', 'MiB', 'G' and 'B' as postfix. * @param tail if non-NULL puts here the pointer to the char next * after the last parsed character */ double av_strtod(const char *numstr, char **tail); #endif /* AVUTIL_EVAL_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/ffversion.h ================================================ /* Automatically generated by version.sh, do not manually edit! */ #ifndef AVUTIL_FFVERSION_H #define AVUTIL_FFVERSION_H #define FFMPEG_VERSION "4.2.1" #endif /* AVUTIL_FFVERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/fifo.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * a very simple circular buffer FIFO implementation */ #ifndef AVUTIL_FIFO_H #define AVUTIL_FIFO_H #include #include "avutil.h" #include "attributes.h" typedef struct AVFifoBuffer { uint8_t *buffer; uint8_t *rptr, *wptr, *end; uint32_t rndx, wndx; } AVFifoBuffer; /** * Initialize an AVFifoBuffer. * @param size of FIFO * @return AVFifoBuffer or NULL in case of memory allocation failure */ AVFifoBuffer *av_fifo_alloc(unsigned int size); /** * Initialize an AVFifoBuffer. * @param nmemb number of elements * @param size size of the single element * @return AVFifoBuffer or NULL in case of memory allocation failure */ AVFifoBuffer *av_fifo_alloc_array(size_t nmemb, size_t size); /** * Free an AVFifoBuffer. * @param f AVFifoBuffer to free */ void av_fifo_free(AVFifoBuffer *f); /** * Free an AVFifoBuffer and reset pointer to NULL. * @param f AVFifoBuffer to free */ void av_fifo_freep(AVFifoBuffer **f); /** * Reset the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied. * @param f AVFifoBuffer to reset */ void av_fifo_reset(AVFifoBuffer *f); /** * Return the amount of data in bytes in the AVFifoBuffer, that is the * amount of data you can read from it. * @param f AVFifoBuffer to read from * @return size */ int av_fifo_size(const AVFifoBuffer *f); /** * Return the amount of space in bytes in the AVFifoBuffer, that is the * amount of data you can write into it. * @param f AVFifoBuffer to write into * @return size */ int av_fifo_space(const AVFifoBuffer *f); /** * Feed data at specific position from an AVFifoBuffer to a user-supplied callback. * Similar as av_fifo_gereric_read but without discarding data. * @param f AVFifoBuffer to read from * @param offset offset from current read position * @param buf_size number of bytes to read * @param func generic read function * @param dest data destination */ int av_fifo_generic_peek_at(AVFifoBuffer *f, void *dest, int offset, int buf_size, void (*func)(void*, void*, int)); /** * Feed data from an AVFifoBuffer to a user-supplied callback. * Similar as av_fifo_gereric_read but without discarding data. * @param f AVFifoBuffer to read from * @param buf_size number of bytes to read * @param func generic read function * @param dest data destination */ int av_fifo_generic_peek(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int)); /** * Feed data from an AVFifoBuffer to a user-supplied callback. * @param f AVFifoBuffer to read from * @param buf_size number of bytes to read * @param func generic read function * @param dest data destination */ int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int)); /** * Feed data from a user-supplied callback to an AVFifoBuffer. * @param f AVFifoBuffer to write to * @param src data source; non-const since it may be used as a * modifiable context by the function defined in func * @param size number of bytes to write * @param func generic write function; the first parameter is src, * the second is dest_buf, the third is dest_buf_size. * func must return the number of bytes written to dest_buf, or <= 0 to * indicate no more data available to write. * If func is NULL, src is interpreted as a simple byte array for source data. * @return the number of bytes written to the FIFO */ int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void*, void*, int)); /** * Resize an AVFifoBuffer. * In case of reallocation failure, the old FIFO is kept unchanged. * * @param f AVFifoBuffer to resize * @param size new AVFifoBuffer size in bytes * @return <0 for failure, >=0 otherwise */ int av_fifo_realloc2(AVFifoBuffer *f, unsigned int size); /** * Enlarge an AVFifoBuffer. * In case of reallocation failure, the old FIFO is kept unchanged. * The new fifo size may be larger than the requested size. * * @param f AVFifoBuffer to resize * @param additional_space the amount of space in bytes to allocate in addition to av_fifo_size() * @return <0 for failure, >=0 otherwise */ int av_fifo_grow(AVFifoBuffer *f, unsigned int additional_space); /** * Read and discard the specified amount of data from an AVFifoBuffer. * @param f AVFifoBuffer to read from * @param size amount of data to read in bytes */ void av_fifo_drain(AVFifoBuffer *f, int size); /** * Return a pointer to the data stored in a FIFO buffer at a certain offset. * The FIFO buffer is not modified. * * @param f AVFifoBuffer to peek at, f must be non-NULL * @param offs an offset in bytes, its absolute value must be less * than the used buffer size or the returned pointer will * point outside to the buffer data. * The used buffer size can be checked with av_fifo_size(). */ static inline uint8_t *av_fifo_peek2(const AVFifoBuffer *f, int offs) { uint8_t *ptr = f->rptr + offs; if (ptr >= f->end) ptr = f->buffer + (ptr - f->end); else if (ptr < f->buffer) ptr = f->end - (f->buffer - ptr); return ptr; } #endif /* AVUTIL_FIFO_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/file.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_FILE_H #define AVUTIL_FILE_H #include #include "avutil.h" /** * @file * Misc file utilities. */ /** * Read the file with name filename, and put its content in a newly * allocated buffer or map it with mmap() when available. * In case of success set *bufptr to the read or mmapped buffer, and * *size to the size in bytes of the buffer in *bufptr. * Unlike mmap this function succeeds with zero sized files, in this * case *bufptr will be set to NULL and *size will be set to 0. * The returned buffer must be released with av_file_unmap(). * * @param log_offset loglevel offset used for logging * @param log_ctx context used for logging * @return a non negative number in case of success, a negative value * corresponding to an AVERROR error code in case of failure */ av_warn_unused_result int av_file_map(const char *filename, uint8_t **bufptr, size_t *size, int log_offset, void *log_ctx); /** * Unmap or free the buffer bufptr created by av_file_map(). * * @param size size in bytes of bufptr, must be the same as returned * by av_file_map() */ void av_file_unmap(uint8_t *bufptr, size_t size); /** * Wrapper to work around the lack of mkstemp() on mingw. * Also, tries to create file in /tmp first, if possible. * *prefix can be a character constant; *filename will be allocated internally. * @return file descriptor of opened file (or negative value corresponding to an * AVERROR code on error) * and opened file name in **filename. * @note On very old libcs it is necessary to set a secure umask before * calling this, av_tempfile() can't call umask itself as it is used in * libraries and could interfere with the calling application. * @deprecated as fd numbers cannot be passed saftely between libs on some platforms */ int av_tempfile(const char *prefix, char **filename, int log_offset, void *log_ctx); #endif /* AVUTIL_FILE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/frame.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_frame * reference-counted frame API */ #ifndef AVUTIL_FRAME_H #define AVUTIL_FRAME_H #include #include #include "avutil.h" #include "buffer.h" #include "dict.h" #include "rational.h" #include "samplefmt.h" #include "pixfmt.h" #include "version.h" /** * @defgroup lavu_frame AVFrame * @ingroup lavu_data * * @{ * AVFrame is an abstraction for reference-counted raw multimedia data. */ enum AVFrameSideDataType { /** * The data is the AVPanScan struct defined in libavcodec. */ AV_FRAME_DATA_PANSCAN, /** * ATSC A53 Part 4 Closed Captions. * A53 CC bitstream is stored as uint8_t in AVFrameSideData.data. * The number of bytes of CC data is AVFrameSideData.size. */ AV_FRAME_DATA_A53_CC, /** * Stereoscopic 3d metadata. * The data is the AVStereo3D struct defined in libavutil/stereo3d.h. */ AV_FRAME_DATA_STEREO3D, /** * The data is the AVMatrixEncoding enum defined in libavutil/channel_layout.h. */ AV_FRAME_DATA_MATRIXENCODING, /** * Metadata relevant to a downmix procedure. * The data is the AVDownmixInfo struct defined in libavutil/downmix_info.h. */ AV_FRAME_DATA_DOWNMIX_INFO, /** * ReplayGain information in the form of the AVReplayGain struct. */ AV_FRAME_DATA_REPLAYGAIN, /** * This side data contains a 3x3 transformation matrix describing an affine * transformation that needs to be applied to the frame for correct * presentation. * * See libavutil/display.h for a detailed description of the data. */ AV_FRAME_DATA_DISPLAYMATRIX, /** * Active Format Description data consisting of a single byte as specified * in ETSI TS 101 154 using AVActiveFormatDescription enum. */ AV_FRAME_DATA_AFD, /** * Motion vectors exported by some codecs (on demand through the export_mvs * flag set in the libavcodec AVCodecContext flags2 option). * The data is the AVMotionVector struct defined in * libavutil/motion_vector.h. */ AV_FRAME_DATA_MOTION_VECTORS, /** * Recommmends skipping the specified number of samples. This is exported * only if the "skip_manual" AVOption is set in libavcodec. * This has the same format as AV_PKT_DATA_SKIP_SAMPLES. * @code * u32le number of samples to skip from start of this packet * u32le number of samples to skip from end of this packet * u8 reason for start skip * u8 reason for end skip (0=padding silence, 1=convergence) * @endcode */ AV_FRAME_DATA_SKIP_SAMPLES, /** * This side data must be associated with an audio frame and corresponds to * enum AVAudioServiceType defined in avcodec.h. */ AV_FRAME_DATA_AUDIO_SERVICE_TYPE, /** * Mastering display metadata associated with a video frame. The payload is * an AVMasteringDisplayMetadata type and contains information about the * mastering display color volume. */ AV_FRAME_DATA_MASTERING_DISPLAY_METADATA, /** * The GOP timecode in 25 bit timecode format. Data format is 64-bit integer. * This is set on the first frame of a GOP that has a temporal reference of 0. */ AV_FRAME_DATA_GOP_TIMECODE, /** * The data represents the AVSphericalMapping structure defined in * libavutil/spherical.h. */ AV_FRAME_DATA_SPHERICAL, /** * Content light level (based on CTA-861.3). This payload contains data in * the form of the AVContentLightMetadata struct. */ AV_FRAME_DATA_CONTENT_LIGHT_LEVEL, /** * The data contains an ICC profile as an opaque octet buffer following the * format described by ISO 15076-1 with an optional name defined in the * metadata key entry "name". */ AV_FRAME_DATA_ICC_PROFILE, #if FF_API_FRAME_QP /** * Implementation-specific description of the format of AV_FRAME_QP_TABLE_DATA. * The contents of this side data are undocumented and internal; use * av_frame_set_qp_table() and av_frame_get_qp_table() to access this in a * meaningful way instead. */ AV_FRAME_DATA_QP_TABLE_PROPERTIES, /** * Raw QP table data. Its format is described by * AV_FRAME_DATA_QP_TABLE_PROPERTIES. Use av_frame_set_qp_table() and * av_frame_get_qp_table() to access this instead. */ AV_FRAME_DATA_QP_TABLE_DATA, #endif /** * Timecode which conforms to SMPTE ST 12-1. The data is an array of 4 uint32_t * where the first uint32_t describes how many (1-3) of the other timecodes are used. * The timecode format is described in the av_timecode_get_smpte_from_framenum() * function in libavutil/timecode.c. */ AV_FRAME_DATA_S12M_TIMECODE, /** * HDR dynamic metadata associated with a video frame. The payload is * an AVDynamicHDRPlus type and contains information for color * volume transform - application 4 of SMPTE 2094-40:2016 standard. */ AV_FRAME_DATA_DYNAMIC_HDR_PLUS, /** * Regions Of Interest, the data is an array of AVRegionOfInterest type, the number of * array element is implied by AVFrameSideData.size / AVRegionOfInterest.self_size. */ AV_FRAME_DATA_REGIONS_OF_INTEREST, }; enum AVActiveFormatDescription { AV_AFD_SAME = 8, AV_AFD_4_3 = 9, AV_AFD_16_9 = 10, AV_AFD_14_9 = 11, AV_AFD_4_3_SP_14_9 = 13, AV_AFD_16_9_SP_14_9 = 14, AV_AFD_SP_4_3 = 15, }; /** * Structure to hold side data for an AVFrame. * * sizeof(AVFrameSideData) is not a part of the public ABI, so new fields may be added * to the end with a minor bump. */ typedef struct AVFrameSideData { enum AVFrameSideDataType type; uint8_t *data; int size; AVDictionary *metadata; AVBufferRef *buf; } AVFrameSideData; /** * Structure describing a single Region Of Interest. * * When multiple regions are defined in a single side-data block, they * should be ordered from most to least important - some encoders are only * capable of supporting a limited number of distinct regions, so will have * to truncate the list. * * When overlapping regions are defined, the first region containing a given * area of the frame applies. */ typedef struct AVRegionOfInterest { /** * Must be set to the size of this data structure (that is, * sizeof(AVRegionOfInterest)). */ uint32_t self_size; /** * Distance in pixels from the top edge of the frame to the top and * bottom edges and from the left edge of the frame to the left and * right edges of the rectangle defining this region of interest. * * The constraints on a region are encoder dependent, so the region * actually affected may be slightly larger for alignment or other * reasons. */ int top; int bottom; int left; int right; /** * Quantisation offset. * * Must be in the range -1 to +1. A value of zero indicates no quality * change. A negative value asks for better quality (less quantisation), * while a positive value asks for worse quality (greater quantisation). * * The range is calibrated so that the extreme values indicate the * largest possible offset - if the rest of the frame is encoded with the * worst possible quality, an offset of -1 indicates that this region * should be encoded with the best possible quality anyway. Intermediate * values are then interpolated in some codec-dependent way. * * For example, in 10-bit H.264 the quantisation parameter varies between * -12 and 51. A typical qoffset value of -1/10 therefore indicates that * this region should be encoded with a QP around one-tenth of the full * range better than the rest of the frame. So, if most of the frame * were to be encoded with a QP of around 30, this region would get a QP * of around 24 (an offset of approximately -1/10 * (51 - -12) = -6.3). * An extreme value of -1 would indicate that this region should be * encoded with the best possible quality regardless of the treatment of * the rest of the frame - that is, should be encoded at a QP of -12. */ AVRational qoffset; } AVRegionOfInterest; /** * This structure describes decoded (raw) audio or video data. * * AVFrame must be allocated using av_frame_alloc(). Note that this only * allocates the AVFrame itself, the buffers for the data must be managed * through other means (see below). * AVFrame must be freed with av_frame_free(). * * AVFrame is typically allocated once and then reused multiple times to hold * different data (e.g. a single AVFrame to hold frames received from a * decoder). In such a case, av_frame_unref() will free any references held by * the frame and reset it to its original clean state before it * is reused again. * * The data described by an AVFrame is usually reference counted through the * AVBuffer API. The underlying buffer references are stored in AVFrame.buf / * AVFrame.extended_buf. An AVFrame is considered to be reference counted if at * least one reference is set, i.e. if AVFrame.buf[0] != NULL. In such a case, * every single data plane must be contained in one of the buffers in * AVFrame.buf or AVFrame.extended_buf. * There may be a single buffer for all the data, or one separate buffer for * each plane, or anything in between. * * sizeof(AVFrame) is not a part of the public ABI, so new fields may be added * to the end with a minor bump. * * Fields can be accessed through AVOptions, the name string used, matches the * C structure field name for fields accessible through AVOptions. The AVClass * for AVFrame can be obtained from avcodec_get_frame_class() */ typedef struct AVFrame { #define AV_NUM_DATA_POINTERS 8 /** * pointer to the picture/channel planes. * This might be different from the first allocated byte * * Some decoders access areas outside 0,0 - width,height, please * see avcodec_align_dimensions2(). Some filters and swscale can read * up to 16 bytes beyond the planes, if these filters are to be used, * then 16 extra bytes must be allocated. * * NOTE: Except for hwaccel formats, pointers not needed by the format * MUST be set to NULL. */ uint8_t *data[AV_NUM_DATA_POINTERS]; /** * For video, size in bytes of each picture line. * For audio, size in bytes of each plane. * * For audio, only linesize[0] may be set. For planar audio, each channel * plane must be the same size. * * For video the linesizes should be multiples of the CPUs alignment * preference, this is 16 or 32 for modern desktop CPUs. * Some code requires such alignment other code can be slower without * correct alignment, for yet other it makes no difference. * * @note The linesize may be larger than the size of usable data -- there * may be extra padding present for performance reasons. */ int linesize[AV_NUM_DATA_POINTERS]; /** * pointers to the data planes/channels. * * For video, this should simply point to data[]. * * For planar audio, each channel has a separate data pointer, and * linesize[0] contains the size of each channel buffer. * For packed audio, there is just one data pointer, and linesize[0] * contains the total size of the buffer for all channels. * * Note: Both data and extended_data should always be set in a valid frame, * but for planar audio with more channels that can fit in data, * extended_data must be used in order to access all channels. */ uint8_t **extended_data; /** * @name Video dimensions * Video frames only. The coded dimensions (in pixels) of the video frame, * i.e. the size of the rectangle that contains some well-defined values. * * @note The part of the frame intended for display/presentation is further * restricted by the @ref cropping "Cropping rectangle". * @{ */ int width, height; /** * @} */ /** * number of audio samples (per channel) described by this frame */ int nb_samples; /** * format of the frame, -1 if unknown or unset * Values correspond to enum AVPixelFormat for video frames, * enum AVSampleFormat for audio) */ int format; /** * 1 -> keyframe, 0-> not */ int key_frame; /** * Picture type of the frame. */ enum AVPictureType pict_type; /** * Sample aspect ratio for the video frame, 0/1 if unknown/unspecified. */ AVRational sample_aspect_ratio; /** * Presentation timestamp in time_base units (time when frame should be shown to user). */ int64_t pts; #if FF_API_PKT_PTS /** * PTS copied from the AVPacket that was decoded to produce this frame. * @deprecated use the pts field instead */ attribute_deprecated int64_t pkt_pts; #endif /** * DTS copied from the AVPacket that triggered returning this frame. (if frame threading isn't used) * This is also the Presentation time of this AVFrame calculated from * only AVPacket.dts values without pts values. */ int64_t pkt_dts; /** * picture number in bitstream order */ int coded_picture_number; /** * picture number in display order */ int display_picture_number; /** * quality (between 1 (good) and FF_LAMBDA_MAX (bad)) */ int quality; /** * for some private data of the user */ void *opaque; #if FF_API_ERROR_FRAME /** * @deprecated unused */ attribute_deprecated uint64_t error[AV_NUM_DATA_POINTERS]; #endif /** * When decoding, this signals how much the picture must be delayed. * extra_delay = repeat_pict / (2*fps) */ int repeat_pict; /** * The content of the picture is interlaced. */ int interlaced_frame; /** * If the content is interlaced, is top field displayed first. */ int top_field_first; /** * Tell user application that palette has changed from previous frame. */ int palette_has_changed; /** * reordered opaque 64 bits (generally an integer or a double precision float * PTS but can be anything). * The user sets AVCodecContext.reordered_opaque to represent the input at * that time, * the decoder reorders values as needed and sets AVFrame.reordered_opaque * to exactly one of the values provided by the user through AVCodecContext.reordered_opaque */ int64_t reordered_opaque; /** * Sample rate of the audio data. */ int sample_rate; /** * Channel layout of the audio data. */ uint64_t channel_layout; /** * AVBuffer references backing the data for this frame. If all elements of * this array are NULL, then this frame is not reference counted. This array * must be filled contiguously -- if buf[i] is non-NULL then buf[j] must * also be non-NULL for all j < i. * * There may be at most one AVBuffer per data plane, so for video this array * always contains all the references. For planar audio with more than * AV_NUM_DATA_POINTERS channels, there may be more buffers than can fit in * this array. Then the extra AVBufferRef pointers are stored in the * extended_buf array. */ AVBufferRef *buf[AV_NUM_DATA_POINTERS]; /** * For planar audio which requires more than AV_NUM_DATA_POINTERS * AVBufferRef pointers, this array will hold all the references which * cannot fit into AVFrame.buf. * * Note that this is different from AVFrame.extended_data, which always * contains all the pointers. This array only contains the extra pointers, * which cannot fit into AVFrame.buf. * * This array is always allocated using av_malloc() by whoever constructs * the frame. It is freed in av_frame_unref(). */ AVBufferRef **extended_buf; /** * Number of elements in extended_buf. */ int nb_extended_buf; AVFrameSideData **side_data; int nb_side_data; /** * @defgroup lavu_frame_flags AV_FRAME_FLAGS * @ingroup lavu_frame * Flags describing additional frame properties. * * @{ */ /** * The frame data may be corrupted, e.g. due to decoding errors. */ #define AV_FRAME_FLAG_CORRUPT (1 << 0) /** * A flag to mark the frames which need to be decoded, but shouldn't be output. */ #define AV_FRAME_FLAG_DISCARD (1 << 2) /** * @} */ /** * Frame flags, a combination of @ref lavu_frame_flags */ int flags; /** * MPEG vs JPEG YUV range. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorRange color_range; enum AVColorPrimaries color_primaries; enum AVColorTransferCharacteristic color_trc; /** * YUV colorspace type. * - encoding: Set by user * - decoding: Set by libavcodec */ enum AVColorSpace colorspace; enum AVChromaLocation chroma_location; /** * frame timestamp estimated using various heuristics, in stream time base * - encoding: unused * - decoding: set by libavcodec, read by user. */ int64_t best_effort_timestamp; /** * reordered pos from the last AVPacket that has been input into the decoder * - encoding: unused * - decoding: Read by user. */ int64_t pkt_pos; /** * duration of the corresponding packet, expressed in * AVStream->time_base units, 0 if unknown. * - encoding: unused * - decoding: Read by user. */ int64_t pkt_duration; /** * metadata. * - encoding: Set by user. * - decoding: Set by libavcodec. */ AVDictionary *metadata; /** * decode error flags of the frame, set to a combination of * FF_DECODE_ERROR_xxx flags if the decoder produced a frame, but there * were errors during the decoding. * - encoding: unused * - decoding: set by libavcodec, read by user. */ int decode_error_flags; #define FF_DECODE_ERROR_INVALID_BITSTREAM 1 #define FF_DECODE_ERROR_MISSING_REFERENCE 2 #define FF_DECODE_ERROR_CONCEALMENT_ACTIVE 4 #define FF_DECODE_ERROR_DECODE_SLICES 8 /** * number of audio channels, only used for audio. * - encoding: unused * - decoding: Read by user. */ int channels; /** * size of the corresponding packet containing the compressed * frame. * It is set to a negative value if unknown. * - encoding: unused * - decoding: set by libavcodec, read by user. */ int pkt_size; #if FF_API_FRAME_QP /** * QP table */ attribute_deprecated int8_t *qscale_table; /** * QP store stride */ attribute_deprecated int qstride; attribute_deprecated int qscale_type; attribute_deprecated AVBufferRef *qp_table_buf; #endif /** * For hwaccel-format frames, this should be a reference to the * AVHWFramesContext describing the frame. */ AVBufferRef *hw_frames_ctx; /** * AVBufferRef for free use by the API user. FFmpeg will never check the * contents of the buffer ref. FFmpeg calls av_buffer_unref() on it when * the frame is unreferenced. av_frame_copy_props() calls create a new * reference with av_buffer_ref() for the target frame's opaque_ref field. * * This is unrelated to the opaque field, although it serves a similar * purpose. */ AVBufferRef *opaque_ref; /** * @anchor cropping * @name Cropping * Video frames only. The number of pixels to discard from the the * top/bottom/left/right border of the frame to obtain the sub-rectangle of * the frame intended for presentation. * @{ */ size_t crop_top; size_t crop_bottom; size_t crop_left; size_t crop_right; /** * @} */ /** * AVBufferRef for internal use by a single libav* library. * Must not be used to transfer data between libraries. * Has to be NULL when ownership of the frame leaves the respective library. * * Code outside the FFmpeg libs should never check or change the contents of the buffer ref. * * FFmpeg calls av_buffer_unref() on it when the frame is unreferenced. * av_frame_copy_props() calls create a new reference with av_buffer_ref() * for the target frame's private_ref field. */ AVBufferRef *private_ref; } AVFrame; #if FF_API_FRAME_GET_SET /** * Accessors for some AVFrame fields. These used to be provided for ABI * compatibility, and do not need to be used anymore. */ attribute_deprecated int64_t av_frame_get_best_effort_timestamp(const AVFrame *frame); attribute_deprecated void av_frame_set_best_effort_timestamp(AVFrame *frame, int64_t val); attribute_deprecated int64_t av_frame_get_pkt_duration (const AVFrame *frame); attribute_deprecated void av_frame_set_pkt_duration (AVFrame *frame, int64_t val); attribute_deprecated int64_t av_frame_get_pkt_pos (const AVFrame *frame); attribute_deprecated void av_frame_set_pkt_pos (AVFrame *frame, int64_t val); attribute_deprecated int64_t av_frame_get_channel_layout (const AVFrame *frame); attribute_deprecated void av_frame_set_channel_layout (AVFrame *frame, int64_t val); attribute_deprecated int av_frame_get_channels (const AVFrame *frame); attribute_deprecated void av_frame_set_channels (AVFrame *frame, int val); attribute_deprecated int av_frame_get_sample_rate (const AVFrame *frame); attribute_deprecated void av_frame_set_sample_rate (AVFrame *frame, int val); attribute_deprecated AVDictionary *av_frame_get_metadata (const AVFrame *frame); attribute_deprecated void av_frame_set_metadata (AVFrame *frame, AVDictionary *val); attribute_deprecated int av_frame_get_decode_error_flags (const AVFrame *frame); attribute_deprecated void av_frame_set_decode_error_flags (AVFrame *frame, int val); attribute_deprecated int av_frame_get_pkt_size(const AVFrame *frame); attribute_deprecated void av_frame_set_pkt_size(AVFrame *frame, int val); #if FF_API_FRAME_QP attribute_deprecated int8_t *av_frame_get_qp_table(AVFrame *f, int *stride, int *type); attribute_deprecated int av_frame_set_qp_table(AVFrame *f, AVBufferRef *buf, int stride, int type); #endif attribute_deprecated enum AVColorSpace av_frame_get_colorspace(const AVFrame *frame); attribute_deprecated void av_frame_set_colorspace(AVFrame *frame, enum AVColorSpace val); attribute_deprecated enum AVColorRange av_frame_get_color_range(const AVFrame *frame); attribute_deprecated void av_frame_set_color_range(AVFrame *frame, enum AVColorRange val); #endif /** * Get the name of a colorspace. * @return a static string identifying the colorspace; can be NULL. */ const char *av_get_colorspace_name(enum AVColorSpace val); /** * Allocate an AVFrame and set its fields to default values. The resulting * struct must be freed using av_frame_free(). * * @return An AVFrame filled with default values or NULL on failure. * * @note this only allocates the AVFrame itself, not the data buffers. Those * must be allocated through other means, e.g. with av_frame_get_buffer() or * manually. */ AVFrame *av_frame_alloc(void); /** * Free the frame and any dynamically allocated objects in it, * e.g. extended_data. If the frame is reference counted, it will be * unreferenced first. * * @param frame frame to be freed. The pointer will be set to NULL. */ void av_frame_free(AVFrame **frame); /** * Set up a new reference to the data described by the source frame. * * Copy frame properties from src to dst and create a new reference for each * AVBufferRef from src. * * If src is not reference counted, new buffers are allocated and the data is * copied. * * @warning: dst MUST have been either unreferenced with av_frame_unref(dst), * or newly allocated with av_frame_alloc() before calling this * function, or undefined behavior will occur. * * @return 0 on success, a negative AVERROR on error */ int av_frame_ref(AVFrame *dst, const AVFrame *src); /** * Create a new frame that references the same data as src. * * This is a shortcut for av_frame_alloc()+av_frame_ref(). * * @return newly created AVFrame on success, NULL on error. */ AVFrame *av_frame_clone(const AVFrame *src); /** * Unreference all the buffers referenced by frame and reset the frame fields. */ void av_frame_unref(AVFrame *frame); /** * Move everything contained in src to dst and reset src. * * @warning: dst is not unreferenced, but directly overwritten without reading * or deallocating its contents. Call av_frame_unref(dst) manually * before calling this function to ensure that no memory is leaked. */ void av_frame_move_ref(AVFrame *dst, AVFrame *src); /** * Allocate new buffer(s) for audio or video data. * * The following fields must be set on frame before calling this function: * - format (pixel format for video, sample format for audio) * - width and height for video * - nb_samples and channel_layout for audio * * This function will fill AVFrame.data and AVFrame.buf arrays and, if * necessary, allocate and fill AVFrame.extended_data and AVFrame.extended_buf. * For planar formats, one buffer will be allocated for each plane. * * @warning: if frame already has been allocated, calling this function will * leak memory. In addition, undefined behavior can occur in certain * cases. * * @param frame frame in which to store the new buffers. * @param align Required buffer size alignment. If equal to 0, alignment will be * chosen automatically for the current CPU. It is highly * recommended to pass 0 here unless you know what you are doing. * * @return 0 on success, a negative AVERROR on error. */ int av_frame_get_buffer(AVFrame *frame, int align); /** * Check if the frame data is writable. * * @return A positive value if the frame data is writable (which is true if and * only if each of the underlying buffers has only one reference, namely the one * stored in this frame). Return 0 otherwise. * * If 1 is returned the answer is valid until av_buffer_ref() is called on any * of the underlying AVBufferRefs (e.g. through av_frame_ref() or directly). * * @see av_frame_make_writable(), av_buffer_is_writable() */ int av_frame_is_writable(AVFrame *frame); /** * Ensure that the frame data is writable, avoiding data copy if possible. * * Do nothing if the frame is writable, allocate new buffers and copy the data * if it is not. * * @return 0 on success, a negative AVERROR on error. * * @see av_frame_is_writable(), av_buffer_is_writable(), * av_buffer_make_writable() */ int av_frame_make_writable(AVFrame *frame); /** * Copy the frame data from src to dst. * * This function does not allocate anything, dst must be already initialized and * allocated with the same parameters as src. * * This function only copies the frame data (i.e. the contents of the data / * extended data arrays), not any other properties. * * @return >= 0 on success, a negative AVERROR on error. */ int av_frame_copy(AVFrame *dst, const AVFrame *src); /** * Copy only "metadata" fields from src to dst. * * Metadata for the purpose of this function are those fields that do not affect * the data layout in the buffers. E.g. pts, sample rate (for audio) or sample * aspect ratio (for video), but not width/height or channel layout. * Side data is also copied. */ int av_frame_copy_props(AVFrame *dst, const AVFrame *src); /** * Get the buffer reference a given data plane is stored in. * * @param plane index of the data plane of interest in frame->extended_data. * * @return the buffer reference that contains the plane or NULL if the input * frame is not valid. */ AVBufferRef *av_frame_get_plane_buffer(AVFrame *frame, int plane); /** * Add a new side data to a frame. * * @param frame a frame to which the side data should be added * @param type type of the added side data * @param size size of the side data * * @return newly added side data on success, NULL on error */ AVFrameSideData *av_frame_new_side_data(AVFrame *frame, enum AVFrameSideDataType type, int size); /** * Add a new side data to a frame from an existing AVBufferRef * * @param frame a frame to which the side data should be added * @param type the type of the added side data * @param buf an AVBufferRef to add as side data. The ownership of * the reference is transferred to the frame. * * @return newly added side data on success, NULL on error. On failure * the frame is unchanged and the AVBufferRef remains owned by * the caller. */ AVFrameSideData *av_frame_new_side_data_from_buf(AVFrame *frame, enum AVFrameSideDataType type, AVBufferRef *buf); /** * @return a pointer to the side data of a given type on success, NULL if there * is no side data with such type in this frame. */ AVFrameSideData *av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type); /** * If side data of the supplied type exists in the frame, free it and remove it * from the frame. */ void av_frame_remove_side_data(AVFrame *frame, enum AVFrameSideDataType type); /** * Flags for frame cropping. */ enum { /** * Apply the maximum possible cropping, even if it requires setting the * AVFrame.data[] entries to unaligned pointers. Passing unaligned data * to FFmpeg API is generally not allowed, and causes undefined behavior * (such as crashes). You can pass unaligned data only to FFmpeg APIs that * are explicitly documented to accept it. Use this flag only if you * absolutely know what you are doing. */ AV_FRAME_CROP_UNALIGNED = 1 << 0, }; /** * Crop the given video AVFrame according to its crop_left/crop_top/crop_right/ * crop_bottom fields. If cropping is successful, the function will adjust the * data pointers and the width/height fields, and set the crop fields to 0. * * In all cases, the cropping boundaries will be rounded to the inherent * alignment of the pixel format. In some cases, such as for opaque hwaccel * formats, the left/top cropping is ignored. The crop fields are set to 0 even * if the cropping was rounded or ignored. * * @param frame the frame which should be cropped * @param flags Some combination of AV_FRAME_CROP_* flags, or 0. * * @return >= 0 on success, a negative AVERROR on error. If the cropping fields * were invalid, AVERROR(ERANGE) is returned, and nothing is changed. */ int av_frame_apply_cropping(AVFrame *frame, int flags); /** * @return a string identifying the side data type */ const char *av_frame_side_data_name(enum AVFrameSideDataType type); /** * @} */ #endif /* AVUTIL_FRAME_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hash.h ================================================ /* * Copyright (C) 2013 Reimar Döffinger * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_hash_generic * Generic hashing API */ #ifndef AVUTIL_HASH_H #define AVUTIL_HASH_H #include #include "version.h" /** * @defgroup lavu_hash Hash Functions * @ingroup lavu_crypto * Hash functions useful in multimedia. * * Hash functions are widely used in multimedia, from error checking and * concealment to internal regression testing. libavutil has efficient * implementations of a variety of hash functions that may be useful for * FFmpeg and other multimedia applications. * * @{ * * @defgroup lavu_hash_generic Generic Hashing API * An abstraction layer for all hash functions supported by libavutil. * * If your application needs to support a wide range of different hash * functions, then the Generic Hashing API is for you. It provides a generic, * reusable API for @ref lavu_hash "all hash functions" implemented in libavutil. * If you just need to use one particular hash function, use the @ref lavu_hash * "individual hash" directly. * * @section Sample Code * * A basic template for using the Generic Hashing API follows: * * @code * struct AVHashContext *ctx = NULL; * const char *hash_name = NULL; * uint8_t *output_buf = NULL; * * // Select from a string returned by av_hash_names() * hash_name = ...; * * // Allocate a hash context * ret = av_hash_alloc(&ctx, hash_name); * if (ret < 0) * return ret; * * // Initialize the hash context * av_hash_init(ctx); * * // Update the hash context with data * while (data_left) { * av_hash_update(ctx, data, size); * } * * // Now we have no more data, so it is time to finalize the hash and get the * // output. But we need to first allocate an output buffer. Note that you can * // use any memory allocation function, including malloc(), not just * // av_malloc(). * output_buf = av_malloc(av_hash_get_size(ctx)); * if (!output_buf) * return AVERROR(ENOMEM); * * // Finalize the hash context. * // You can use any of the av_hash_final*() functions provided, for other * // output formats. If you do so, be sure to adjust the memory allocation * // above. See the function documentation below for the exact amount of extra * // memory needed. * av_hash_final(ctx, output_buffer); * * // Free the context * av_hash_freep(&ctx); * @endcode * * @section Hash Function-Specific Information * If the CRC32 hash is selected, the #AV_CRC_32_IEEE polynomial will be * used. * * If the Murmur3 hash is selected, the default seed will be used. See @ref * lavu_murmur3_seedinfo "Murmur3" for more information. * * @{ */ /** * @example ffhash.c * This example is a simple command line application that takes one or more * arguments. It demonstrates a typical use of the hashing API with allocation, * initialization, updating, and finalizing. */ struct AVHashContext; /** * Allocate a hash context for the algorithm specified by name. * * @return >= 0 for success, a negative error code for failure * * @note The context is not initialized after a call to this function; you must * call av_hash_init() to do so. */ int av_hash_alloc(struct AVHashContext **ctx, const char *name); /** * Get the names of available hash algorithms. * * This function can be used to enumerate the algorithms. * * @param[in] i Index of the hash algorithm, starting from 0 * @return Pointer to a static string or `NULL` if `i` is out of range */ const char *av_hash_names(int i); /** * Get the name of the algorithm corresponding to the given hash context. */ const char *av_hash_get_name(const struct AVHashContext *ctx); /** * Maximum value that av_hash_get_size() will currently return. * * You can use this if you absolutely want or need to use static allocation for * the output buffer and are fine with not supporting hashes newly added to * libavutil without recompilation. * * @warning * Adding new hashes with larger sizes, and increasing the macro while doing * so, will not be considered an ABI change. To prevent your code from * overflowing a buffer, either dynamically allocate the output buffer with * av_hash_get_size(), or limit your use of the Hashing API to hashes that are * already in FFmpeg during the time of compilation. */ #define AV_HASH_MAX_SIZE 64 /** * Get the size of the resulting hash value in bytes. * * The maximum value this function will currently return is available as macro * #AV_HASH_MAX_SIZE. * * @param[in] ctx Hash context * @return Size of the hash value in bytes */ int av_hash_get_size(const struct AVHashContext *ctx); /** * Initialize or reset a hash context. * * @param[in,out] ctx Hash context */ void av_hash_init(struct AVHashContext *ctx); /** * Update a hash context with additional data. * * @param[in,out] ctx Hash context * @param[in] src Data to be added to the hash context * @param[in] len Size of the additional data */ #if FF_API_CRYPTO_SIZE_T void av_hash_update(struct AVHashContext *ctx, const uint8_t *src, int len); #else void av_hash_update(struct AVHashContext *ctx, const uint8_t *src, size_t len); #endif /** * Finalize a hash context and compute the actual hash value. * * The minimum size of `dst` buffer is given by av_hash_get_size() or * #AV_HASH_MAX_SIZE. The use of the latter macro is discouraged. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * @param[in,out] ctx Hash context * @param[out] dst Where the final hash value will be stored * * @see av_hash_final_bin() provides an alternative API */ void av_hash_final(struct AVHashContext *ctx, uint8_t *dst); /** * Finalize a hash context and store the actual hash value in a buffer. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * If `size` is smaller than the hash size (given by av_hash_get_size()), the * hash is truncated; if size is larger, the buffer is padded with 0. * * @param[in,out] ctx Hash context * @param[out] dst Where the final hash value will be stored * @param[in] size Number of bytes to write to `dst` */ void av_hash_final_bin(struct AVHashContext *ctx, uint8_t *dst, int size); /** * Finalize a hash context and store the hexadecimal representation of the * actual hash value as a string. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * The string is always 0-terminated. * * If `size` is smaller than `2 * hash_size + 1`, where `hash_size` is the * value returned by av_hash_get_size(), the string will be truncated. * * @param[in,out] ctx Hash context * @param[out] dst Where the string will be stored * @param[in] size Maximum number of bytes to write to `dst` */ void av_hash_final_hex(struct AVHashContext *ctx, uint8_t *dst, int size); /** * Finalize a hash context and store the Base64 representation of the * actual hash value as a string. * * It is not safe to update or finalize a hash context again, if it has already * been finalized. * * The string is always 0-terminated. * * If `size` is smaller than AV_BASE64_SIZE(hash_size), where `hash_size` is * the value returned by av_hash_get_size(), the string will be truncated. * * @param[in,out] ctx Hash context * @param[out] dst Where the final hash value will be stored * @param[in] size Maximum number of bytes to write to `dst` */ void av_hash_final_b64(struct AVHashContext *ctx, uint8_t *dst, int size); /** * Free hash context and set hash context pointer to `NULL`. * * @param[in,out] ctx Pointer to hash context */ void av_hash_freep(struct AVHashContext **ctx); /** * @} * @} */ #endif /* AVUTIL_HASH_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hdr_dynamic_metadata.h ================================================ /* * Copyright (c) 2018 Mohammad Izadi * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HDR_DYNAMIC_METADATA_H #define AVUTIL_HDR_DYNAMIC_METADATA_H #include "frame.h" #include "rational.h" /** * Option for overlapping elliptical pixel selectors in an image. */ enum AVHDRPlusOverlapProcessOption { AV_HDR_PLUS_OVERLAP_PROCESS_WEIGHTED_AVERAGING = 0, AV_HDR_PLUS_OVERLAP_PROCESS_LAYERING = 1, }; /** * Represents the percentile at a specific percentage in * a distribution. */ typedef struct AVHDRPlusPercentile { /** * The percentage value corresponding to a specific percentile linearized * RGB value in the processing window in the scene. The value shall be in * the range of 0 to100, inclusive. */ uint8_t percentage; /** * The linearized maxRGB value at a specific percentile in the processing * window in the scene. The value shall be in the range of 0 to 1, inclusive * and in multiples of 0.00001. */ AVRational percentile; } AVHDRPlusPercentile; /** * Color transform parameters at a processing window in a dynamic metadata for * SMPTE 2094-40. */ typedef struct AVHDRPlusColorTransformParams { /** * The relative x coordinate of the top left pixel of the processing * window. The value shall be in the range of 0 and 1, inclusive and * in multiples of 1/(width of Picture - 1). The value 1 corresponds * to the absolute coordinate of width of Picture - 1. The value for * first processing window shall be 0. */ AVRational window_upper_left_corner_x; /** * The relative y coordinate of the top left pixel of the processing * window. The value shall be in the range of 0 and 1, inclusive and * in multiples of 1/(height of Picture - 1). The value 1 corresponds * to the absolute coordinate of height of Picture - 1. The value for * first processing window shall be 0. */ AVRational window_upper_left_corner_y; /** * The relative x coordinate of the bottom right pixel of the processing * window. The value shall be in the range of 0 and 1, inclusive and * in multiples of 1/(width of Picture - 1). The value 1 corresponds * to the absolute coordinate of width of Picture - 1. The value for * first processing window shall be 1. */ AVRational window_lower_right_corner_x; /** * The relative y coordinate of the bottom right pixel of the processing * window. The value shall be in the range of 0 and 1, inclusive and * in multiples of 1/(height of Picture - 1). The value 1 corresponds * to the absolute coordinate of height of Picture - 1. The value for * first processing window shall be 1. */ AVRational window_lower_right_corner_y; /** * The x coordinate of the center position of the concentric internal and * external ellipses of the elliptical pixel selector in the processing * window. The value shall be in the range of 0 to (width of Picture - 1), * inclusive and in multiples of 1 pixel. */ uint16_t center_of_ellipse_x; /** * The y coordinate of the center position of the concentric internal and * external ellipses of the elliptical pixel selector in the processing * window. The value shall be in the range of 0 to (height of Picture - 1), * inclusive and in multiples of 1 pixel. */ uint16_t center_of_ellipse_y; /** * The clockwise rotation angle in degree of arc with respect to the * positive direction of the x-axis of the concentric internal and external * ellipses of the elliptical pixel selector in the processing window. The * value shall be in the range of 0 to 180, inclusive and in multiples of 1. */ uint8_t rotation_angle; /** * The semi-major axis value of the internal ellipse of the elliptical pixel * selector in amount of pixels in the processing window. The value shall be * in the range of 1 to 65535, inclusive and in multiples of 1 pixel. */ uint16_t semimajor_axis_internal_ellipse; /** * The semi-major axis value of the external ellipse of the elliptical pixel * selector in amount of pixels in the processing window. The value * shall not be less than semimajor_axis_internal_ellipse of the current * processing window. The value shall be in the range of 1 to 65535, * inclusive and in multiples of 1 pixel. */ uint16_t semimajor_axis_external_ellipse; /** * The semi-minor axis value of the external ellipse of the elliptical pixel * selector in amount of pixels in the processing window. The value shall be * in the range of 1 to 65535, inclusive and in multiples of 1 pixel. */ uint16_t semiminor_axis_external_ellipse; /** * Overlap process option indicates one of the two methods of combining * rendered pixels in the processing window in an image with at least one * elliptical pixel selector. For overlapping elliptical pixel selectors * in an image, overlap_process_option shall have the same value. */ enum AVHDRPlusOverlapProcessOption overlap_process_option; /** * The maximum of the color components of linearized RGB values in the * processing window in the scene. The values should be in the range of 0 to * 1, inclusive and in multiples of 0.00001. maxscl[ 0 ], maxscl[ 1 ], and * maxscl[ 2 ] are corresponding to R, G, B color components respectively. */ AVRational maxscl[3]; /** * The average of linearized maxRGB values in the processing window in the * scene. The value should be in the range of 0 to 1, inclusive and in * multiples of 0.00001. */ AVRational average_maxrgb; /** * The number of linearized maxRGB values at given percentiles in the * processing window in the scene. The maximum value shall be 15. */ uint8_t num_distribution_maxrgb_percentiles; /** * The linearized maxRGB values at given percentiles in the * processing window in the scene. */ AVHDRPlusPercentile distribution_maxrgb[15]; /** * The fraction of selected pixels in the image that contains the brightest * pixel in the scene. The value shall be in the range of 0 to 1, inclusive * and in multiples of 0.001. */ AVRational fraction_bright_pixels; /** * This flag indicates that the metadata for the tone mapping function in * the processing window is present (for value of 1). */ uint8_t tone_mapping_flag; /** * The x coordinate of the separation point between the linear part and the * curved part of the tone mapping function. The value shall be in the range * of 0 to 1, excluding 0 and in multiples of 1/4095. */ AVRational knee_point_x; /** * The y coordinate of the separation point between the linear part and the * curved part of the tone mapping function. The value shall be in the range * of 0 to 1, excluding 0 and in multiples of 1/4095. */ AVRational knee_point_y; /** * The number of the intermediate anchor parameters of the tone mapping * function in the processing window. The maximum value shall be 15. */ uint8_t num_bezier_curve_anchors; /** * The intermediate anchor parameters of the tone mapping function in the * processing window in the scene. The values should be in the range of 0 * to 1, inclusive and in multiples of 1/1023. */ AVRational bezier_curve_anchors[15]; /** * This flag shall be equal to 0 in bitstreams conforming to this version of * this Specification. Other values are reserved for future use. */ uint8_t color_saturation_mapping_flag; /** * The color saturation gain in the processing window in the scene. The * value shall be in the range of 0 to 63/8, inclusive and in multiples of * 1/8. The default value shall be 1. */ AVRational color_saturation_weight; } AVHDRPlusColorTransformParams; /** * This struct represents dynamic metadata for color volume transform - * application 4 of SMPTE 2094-40:2016 standard. * * To be used as payload of a AVFrameSideData or AVPacketSideData with the * appropriate type. * * @note The struct should be allocated with * av_dynamic_hdr_plus_alloc() and its size is not a part of * the public ABI. */ typedef struct AVDynamicHDRPlus { /** * Country code by Rec. ITU-T T.35 Annex A. The value shall be 0xB5. */ uint8_t itu_t_t35_country_code; /** * Application version in the application defining document in ST-2094 * suite. The value shall be set to 0. */ uint8_t application_version; /** * The number of processing windows. The value shall be in the range * of 1 to 3, inclusive. */ uint8_t num_windows; /** * The color transform parameters for every processing window. */ AVHDRPlusColorTransformParams params[3]; /** * The nominal maximum display luminance of the targeted system display, * in units of 0.0001 candelas per square metre. The value shall be in * the range of 0 to 10000, inclusive. */ AVRational targeted_system_display_maximum_luminance; /** * This flag shall be equal to 0 in bit streams conforming to this version * of this Specification. The value 1 is reserved for future use. */ uint8_t targeted_system_display_actual_peak_luminance_flag; /** * The number of rows in the targeted system_display_actual_peak_luminance * array. The value shall be in the range of 2 to 25, inclusive. */ uint8_t num_rows_targeted_system_display_actual_peak_luminance; /** * The number of columns in the * targeted_system_display_actual_peak_luminance array. The value shall be * in the range of 2 to 25, inclusive. */ uint8_t num_cols_targeted_system_display_actual_peak_luminance; /** * The normalized actual peak luminance of the targeted system display. The * values should be in the range of 0 to 1, inclusive and in multiples of * 1/15. */ AVRational targeted_system_display_actual_peak_luminance[25][25]; /** * This flag shall be equal to 0 in bitstreams conforming to this version of * this Specification. The value 1 is reserved for future use. */ uint8_t mastering_display_actual_peak_luminance_flag; /** * The number of rows in the mastering_display_actual_peak_luminance array. * The value shall be in the range of 2 to 25, inclusive. */ uint8_t num_rows_mastering_display_actual_peak_luminance; /** * The number of columns in the mastering_display_actual_peak_luminance * array. The value shall be in the range of 2 to 25, inclusive. */ uint8_t num_cols_mastering_display_actual_peak_luminance; /** * The normalized actual peak luminance of the mastering display used for * mastering the image essence. The values should be in the range of 0 to 1, * inclusive and in multiples of 1/15. */ AVRational mastering_display_actual_peak_luminance[25][25]; } AVDynamicHDRPlus; /** * Allocate an AVDynamicHDRPlus structure and set its fields to * default values. The resulting struct can be freed using av_freep(). * * @return An AVDynamicHDRPlus filled with default values or NULL * on failure. */ AVDynamicHDRPlus *av_dynamic_hdr_plus_alloc(size_t *size); /** * Allocate a complete AVDynamicHDRPlus and add it to the frame. * @param frame The frame which side data is added to. * * @return The AVDynamicHDRPlus structure to be filled by caller or NULL * on failure. */ AVDynamicHDRPlus *av_dynamic_hdr_plus_create_side_data(AVFrame *frame); #endif /* AVUTIL_HDR_DYNAMIC_METADATA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hmac.h ================================================ /* * Copyright (C) 2012 Martin Storsjo * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HMAC_H #define AVUTIL_HMAC_H #include #include "version.h" /** * @defgroup lavu_hmac HMAC * @ingroup lavu_crypto * @{ */ enum AVHMACType { AV_HMAC_MD5, AV_HMAC_SHA1, AV_HMAC_SHA224, AV_HMAC_SHA256, AV_HMAC_SHA384, AV_HMAC_SHA512, }; typedef struct AVHMAC AVHMAC; /** * Allocate an AVHMAC context. * @param type The hash function used for the HMAC. */ AVHMAC *av_hmac_alloc(enum AVHMACType type); /** * Free an AVHMAC context. * @param ctx The context to free, may be NULL */ void av_hmac_free(AVHMAC *ctx); /** * Initialize an AVHMAC context with an authentication key. * @param ctx The HMAC context * @param key The authentication key * @param keylen The length of the key, in bytes */ void av_hmac_init(AVHMAC *ctx, const uint8_t *key, unsigned int keylen); /** * Hash data with the HMAC. * @param ctx The HMAC context * @param data The data to hash * @param len The length of the data, in bytes */ void av_hmac_update(AVHMAC *ctx, const uint8_t *data, unsigned int len); /** * Finish hashing and output the HMAC digest. * @param ctx The HMAC context * @param out The output buffer to write the digest into * @param outlen The length of the out buffer, in bytes * @return The number of bytes written to out, or a negative error code. */ int av_hmac_final(AVHMAC *ctx, uint8_t *out, unsigned int outlen); /** * Hash an array of data with a key. * @param ctx The HMAC context * @param data The data to hash * @param len The length of the data, in bytes * @param key The authentication key * @param keylen The length of the key, in bytes * @param out The output buffer to write the digest into * @param outlen The length of the out buffer, in bytes * @return The number of bytes written to out, or a negative error code. */ int av_hmac_calc(AVHMAC *ctx, const uint8_t *data, unsigned int len, const uint8_t *key, unsigned int keylen, uint8_t *out, unsigned int outlen); /** * @} */ #endif /* AVUTIL_HMAC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_H #define AVUTIL_HWCONTEXT_H #include "buffer.h" #include "frame.h" #include "log.h" #include "pixfmt.h" enum AVHWDeviceType { AV_HWDEVICE_TYPE_NONE, AV_HWDEVICE_TYPE_VDPAU, AV_HWDEVICE_TYPE_CUDA, AV_HWDEVICE_TYPE_VAAPI, AV_HWDEVICE_TYPE_DXVA2, AV_HWDEVICE_TYPE_QSV, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, AV_HWDEVICE_TYPE_D3D11VA, AV_HWDEVICE_TYPE_DRM, AV_HWDEVICE_TYPE_OPENCL, AV_HWDEVICE_TYPE_MEDIACODEC, }; typedef struct AVHWDeviceInternal AVHWDeviceInternal; /** * This struct aggregates all the (hardware/vendor-specific) "high-level" state, * i.e. state that is not tied to a concrete processing configuration. * E.g., in an API that supports hardware-accelerated encoding and decoding, * this struct will (if possible) wrap the state that is common to both encoding * and decoding and from which specific instances of encoders or decoders can be * derived. * * This struct is reference-counted with the AVBuffer mechanism. The * av_hwdevice_ctx_alloc() constructor yields a reference, whose data field * points to the actual AVHWDeviceContext. Further objects derived from * AVHWDeviceContext (such as AVHWFramesContext, describing a frame pool with * specific properties) will hold an internal reference to it. After all the * references are released, the AVHWDeviceContext itself will be freed, * optionally invoking a user-specified callback for uninitializing the hardware * state. */ typedef struct AVHWDeviceContext { /** * A class for logging. Set by av_hwdevice_ctx_alloc(). */ const AVClass *av_class; /** * Private data used internally by libavutil. Must not be accessed in any * way by the caller. */ AVHWDeviceInternal *internal; /** * This field identifies the underlying API used for hardware access. * * This field is set when this struct is allocated and never changed * afterwards. */ enum AVHWDeviceType type; /** * The format-specific data, allocated and freed by libavutil along with * this context. * * Should be cast by the user to the format-specific context defined in the * corresponding header (hwcontext_*.h) and filled as described in the * documentation before calling av_hwdevice_ctx_init(). * * After calling av_hwdevice_ctx_init() this struct should not be modified * by the caller. */ void *hwctx; /** * This field may be set by the caller before calling av_hwdevice_ctx_init(). * * If non-NULL, this callback will be called when the last reference to * this context is unreferenced, immediately before it is freed. * * @note when other objects (e.g an AVHWFramesContext) are derived from this * struct, this callback will be invoked after all such child objects * are fully uninitialized and their respective destructors invoked. */ void (*free)(struct AVHWDeviceContext *ctx); /** * Arbitrary user data, to be used e.g. by the free() callback. */ void *user_opaque; } AVHWDeviceContext; typedef struct AVHWFramesInternal AVHWFramesInternal; /** * This struct describes a set or pool of "hardware" frames (i.e. those with * data not located in normal system memory). All the frames in the pool are * assumed to be allocated in the same way and interchangeable. * * This struct is reference-counted with the AVBuffer mechanism and tied to a * given AVHWDeviceContext instance. The av_hwframe_ctx_alloc() constructor * yields a reference, whose data field points to the actual AVHWFramesContext * struct. */ typedef struct AVHWFramesContext { /** * A class for logging. */ const AVClass *av_class; /** * Private data used internally by libavutil. Must not be accessed in any * way by the caller. */ AVHWFramesInternal *internal; /** * A reference to the parent AVHWDeviceContext. This reference is owned and * managed by the enclosing AVHWFramesContext, but the caller may derive * additional references from it. */ AVBufferRef *device_ref; /** * The parent AVHWDeviceContext. This is simply a pointer to * device_ref->data provided for convenience. * * Set by libavutil in av_hwframe_ctx_init(). */ AVHWDeviceContext *device_ctx; /** * The format-specific data, allocated and freed automatically along with * this context. * * Should be cast by the user to the format-specific context defined in the * corresponding header (hwframe_*.h) and filled as described in the * documentation before calling av_hwframe_ctx_init(). * * After any frames using this context are created, the contents of this * struct should not be modified by the caller. */ void *hwctx; /** * This field may be set by the caller before calling av_hwframe_ctx_init(). * * If non-NULL, this callback will be called when the last reference to * this context is unreferenced, immediately before it is freed. */ void (*free)(struct AVHWFramesContext *ctx); /** * Arbitrary user data, to be used e.g. by the free() callback. */ void *user_opaque; /** * A pool from which the frames are allocated by av_hwframe_get_buffer(). * This field may be set by the caller before calling av_hwframe_ctx_init(). * The buffers returned by calling av_buffer_pool_get() on this pool must * have the properties described in the documentation in the corresponding hw * type's header (hwcontext_*.h). The pool will be freed strictly before * this struct's free() callback is invoked. * * This field may be NULL, then libavutil will attempt to allocate a pool * internally. Note that certain device types enforce pools allocated at * fixed size (frame count), which cannot be extended dynamically. In such a * case, initial_pool_size must be set appropriately. */ AVBufferPool *pool; /** * Initial size of the frame pool. If a device type does not support * dynamically resizing the pool, then this is also the maximum pool size. * * May be set by the caller before calling av_hwframe_ctx_init(). Must be * set if pool is NULL and the device type does not support dynamic pools. */ int initial_pool_size; /** * The pixel format identifying the underlying HW surface type. * * Must be a hwaccel format, i.e. the corresponding descriptor must have the * AV_PIX_FMT_FLAG_HWACCEL flag set. * * Must be set by the user before calling av_hwframe_ctx_init(). */ enum AVPixelFormat format; /** * The pixel format identifying the actual data layout of the hardware * frames. * * Must be set by the caller before calling av_hwframe_ctx_init(). * * @note when the underlying API does not provide the exact data layout, but * only the colorspace/bit depth, this field should be set to the fully * planar version of that format (e.g. for 8-bit 420 YUV it should be * AV_PIX_FMT_YUV420P, not AV_PIX_FMT_NV12 or anything else). */ enum AVPixelFormat sw_format; /** * The allocated dimensions of the frames in this pool. * * Must be set by the user before calling av_hwframe_ctx_init(). */ int width, height; } AVHWFramesContext; /** * Look up an AVHWDeviceType by name. * * @param name String name of the device type (case-insensitive). * @return The type from enum AVHWDeviceType, or AV_HWDEVICE_TYPE_NONE if * not found. */ enum AVHWDeviceType av_hwdevice_find_type_by_name(const char *name); /** Get the string name of an AVHWDeviceType. * * @param type Type from enum AVHWDeviceType. * @return Pointer to a static string containing the name, or NULL if the type * is not valid. */ const char *av_hwdevice_get_type_name(enum AVHWDeviceType type); /** * Iterate over supported device types. * * @param type AV_HWDEVICE_TYPE_NONE initially, then the previous type * returned by this function in subsequent iterations. * @return The next usable device type from enum AVHWDeviceType, or * AV_HWDEVICE_TYPE_NONE if there are no more. */ enum AVHWDeviceType av_hwdevice_iterate_types(enum AVHWDeviceType prev); /** * Allocate an AVHWDeviceContext for a given hardware type. * * @param type the type of the hardware device to allocate. * @return a reference to the newly created AVHWDeviceContext on success or NULL * on failure. */ AVBufferRef *av_hwdevice_ctx_alloc(enum AVHWDeviceType type); /** * Finalize the device context before use. This function must be called after * the context is filled with all the required information and before it is * used in any way. * * @param ref a reference to the AVHWDeviceContext * @return 0 on success, a negative AVERROR code on failure */ int av_hwdevice_ctx_init(AVBufferRef *ref); /** * Open a device of the specified type and create an AVHWDeviceContext for it. * * This is a convenience function intended to cover the simple cases. Callers * who need to fine-tune device creation/management should open the device * manually and then wrap it in an AVHWDeviceContext using * av_hwdevice_ctx_alloc()/av_hwdevice_ctx_init(). * * The returned context is already initialized and ready for use, the caller * should not call av_hwdevice_ctx_init() on it. The user_opaque/free fields of * the created AVHWDeviceContext are set by this function and should not be * touched by the caller. * * @param device_ctx On success, a reference to the newly-created device context * will be written here. The reference is owned by the caller * and must be released with av_buffer_unref() when no longer * needed. On failure, NULL will be written to this pointer. * @param type The type of the device to create. * @param device A type-specific string identifying the device to open. * @param opts A dictionary of additional (type-specific) options to use in * opening the device. The dictionary remains owned by the caller. * @param flags currently unused * * @return 0 on success, a negative AVERROR code on failure. */ int av_hwdevice_ctx_create(AVBufferRef **device_ctx, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int flags); /** * Create a new device of the specified type from an existing device. * * If the source device is a device of the target type or was originally * derived from such a device (possibly through one or more intermediate * devices of other types), then this will return a reference to the * existing device of the same type as is requested. * * Otherwise, it will attempt to derive a new device from the given source * device. If direct derivation to the new type is not implemented, it will * attempt the same derivation from each ancestor of the source device in * turn looking for an implemented derivation method. * * @param dst_ctx On success, a reference to the newly-created * AVHWDeviceContext. * @param type The type of the new device to create. * @param src_ctx A reference to an existing AVHWDeviceContext which will be * used to create the new device. * @param flags Currently unused; should be set to zero. * @return Zero on success, a negative AVERROR code on failure. */ int av_hwdevice_ctx_create_derived(AVBufferRef **dst_ctx, enum AVHWDeviceType type, AVBufferRef *src_ctx, int flags); /** * Allocate an AVHWFramesContext tied to a given device context. * * @param device_ctx a reference to a AVHWDeviceContext. This function will make * a new reference for internal use, the one passed to the * function remains owned by the caller. * @return a reference to the newly created AVHWFramesContext on success or NULL * on failure. */ AVBufferRef *av_hwframe_ctx_alloc(AVBufferRef *device_ctx); /** * Finalize the context before use. This function must be called after the * context is filled with all the required information and before it is attached * to any frames. * * @param ref a reference to the AVHWFramesContext * @return 0 on success, a negative AVERROR code on failure */ int av_hwframe_ctx_init(AVBufferRef *ref); /** * Allocate a new frame attached to the given AVHWFramesContext. * * @param hwframe_ctx a reference to an AVHWFramesContext * @param frame an empty (freshly allocated or unreffed) frame to be filled with * newly allocated buffers. * @param flags currently unused, should be set to zero * @return 0 on success, a negative AVERROR code on failure */ int av_hwframe_get_buffer(AVBufferRef *hwframe_ctx, AVFrame *frame, int flags); /** * Copy data to or from a hw surface. At least one of dst/src must have an * AVHWFramesContext attached. * * If src has an AVHWFramesContext attached, then the format of dst (if set) * must use one of the formats returned by av_hwframe_transfer_get_formats(src, * AV_HWFRAME_TRANSFER_DIRECTION_FROM). * If dst has an AVHWFramesContext attached, then the format of src must use one * of the formats returned by av_hwframe_transfer_get_formats(dst, * AV_HWFRAME_TRANSFER_DIRECTION_TO) * * dst may be "clean" (i.e. with data/buf pointers unset), in which case the * data buffers will be allocated by this function using av_frame_get_buffer(). * If dst->format is set, then this format will be used, otherwise (when * dst->format is AV_PIX_FMT_NONE) the first acceptable format will be chosen. * * The two frames must have matching allocated dimensions (i.e. equal to * AVHWFramesContext.width/height), since not all device types support * transferring a sub-rectangle of the whole surface. The display dimensions * (i.e. AVFrame.width/height) may be smaller than the allocated dimensions, but * also have to be equal for both frames. When the display dimensions are * smaller than the allocated dimensions, the content of the padding in the * destination frame is unspecified. * * @param dst the destination frame. dst is not touched on failure. * @param src the source frame. * @param flags currently unused, should be set to zero * @return 0 on success, a negative AVERROR error code on failure. */ int av_hwframe_transfer_data(AVFrame *dst, const AVFrame *src, int flags); enum AVHWFrameTransferDirection { /** * Transfer the data from the queried hw frame. */ AV_HWFRAME_TRANSFER_DIRECTION_FROM, /** * Transfer the data to the queried hw frame. */ AV_HWFRAME_TRANSFER_DIRECTION_TO, }; /** * Get a list of possible source or target formats usable in * av_hwframe_transfer_data(). * * @param hwframe_ctx the frame context to obtain the information for * @param dir the direction of the transfer * @param formats the pointer to the output format list will be written here. * The list is terminated with AV_PIX_FMT_NONE and must be freed * by the caller when no longer needed using av_free(). * If this function returns successfully, the format list will * have at least one item (not counting the terminator). * On failure, the contents of this pointer are unspecified. * @param flags currently unused, should be set to zero * @return 0 on success, a negative AVERROR code on failure. */ int av_hwframe_transfer_get_formats(AVBufferRef *hwframe_ctx, enum AVHWFrameTransferDirection dir, enum AVPixelFormat **formats, int flags); /** * This struct describes the constraints on hardware frames attached to * a given device with a hardware-specific configuration. This is returned * by av_hwdevice_get_hwframe_constraints() and must be freed by * av_hwframe_constraints_free() after use. */ typedef struct AVHWFramesConstraints { /** * A list of possible values for format in the hw_frames_ctx, * terminated by AV_PIX_FMT_NONE. This member will always be filled. */ enum AVPixelFormat *valid_hw_formats; /** * A list of possible values for sw_format in the hw_frames_ctx, * terminated by AV_PIX_FMT_NONE. Can be NULL if this information is * not known. */ enum AVPixelFormat *valid_sw_formats; /** * The minimum size of frames in this hw_frames_ctx. * (Zero if not known.) */ int min_width; int min_height; /** * The maximum size of frames in this hw_frames_ctx. * (INT_MAX if not known / no limit.) */ int max_width; int max_height; } AVHWFramesConstraints; /** * Allocate a HW-specific configuration structure for a given HW device. * After use, the user must free all members as required by the specific * hardware structure being used, then free the structure itself with * av_free(). * * @param device_ctx a reference to the associated AVHWDeviceContext. * @return The newly created HW-specific configuration structure on * success or NULL on failure. */ void *av_hwdevice_hwconfig_alloc(AVBufferRef *device_ctx); /** * Get the constraints on HW frames given a device and the HW-specific * configuration to be used with that device. If no HW-specific * configuration is provided, returns the maximum possible capabilities * of the device. * * @param ref a reference to the associated AVHWDeviceContext. * @param hwconfig a filled HW-specific configuration structure, or NULL * to return the maximum possible capabilities of the device. * @return AVHWFramesConstraints structure describing the constraints * on the device, or NULL if not available. */ AVHWFramesConstraints *av_hwdevice_get_hwframe_constraints(AVBufferRef *ref, const void *hwconfig); /** * Free an AVHWFrameConstraints structure. * * @param constraints The (filled or unfilled) AVHWFrameConstraints structure. */ void av_hwframe_constraints_free(AVHWFramesConstraints **constraints); /** * Flags to apply to frame mappings. */ enum { /** * The mapping must be readable. */ AV_HWFRAME_MAP_READ = 1 << 0, /** * The mapping must be writeable. */ AV_HWFRAME_MAP_WRITE = 1 << 1, /** * The mapped frame will be overwritten completely in subsequent * operations, so the current frame data need not be loaded. Any values * which are not overwritten are unspecified. */ AV_HWFRAME_MAP_OVERWRITE = 1 << 2, /** * The mapping must be direct. That is, there must not be any copying in * the map or unmap steps. Note that performance of direct mappings may * be much lower than normal memory. */ AV_HWFRAME_MAP_DIRECT = 1 << 3, }; /** * Map a hardware frame. * * This has a number of different possible effects, depending on the format * and origin of the src and dst frames. On input, src should be a usable * frame with valid buffers and dst should be blank (typically as just created * by av_frame_alloc()). src should have an associated hwframe context, and * dst may optionally have a format and associated hwframe context. * * If src was created by mapping a frame from the hwframe context of dst, * then this function undoes the mapping - dst is replaced by a reference to * the frame that src was originally mapped from. * * If both src and dst have an associated hwframe context, then this function * attempts to map the src frame from its hardware context to that of dst and * then fill dst with appropriate data to be usable there. This will only be * possible if the hwframe contexts and associated devices are compatible - * given compatible devices, av_hwframe_ctx_create_derived() can be used to * create a hwframe context for dst in which mapping should be possible. * * If src has a hwframe context but dst does not, then the src frame is * mapped to normal memory and should thereafter be usable as a normal frame. * If the format is set on dst, then the mapping will attempt to create dst * with that format and fail if it is not possible. If format is unset (is * AV_PIX_FMT_NONE) then dst will be mapped with whatever the most appropriate * format to use is (probably the sw_format of the src hwframe context). * * A return value of AVERROR(ENOSYS) indicates that the mapping is not * possible with the given arguments and hwframe setup, while other return * values indicate that it failed somehow. * * @param dst Destination frame, to contain the mapping. * @param src Source frame, to be mapped. * @param flags Some combination of AV_HWFRAME_MAP_* flags. * @return Zero on success, negative AVERROR code on failure. */ int av_hwframe_map(AVFrame *dst, const AVFrame *src, int flags); /** * Create and initialise an AVHWFramesContext as a mapping of another existing * AVHWFramesContext on a different device. * * av_hwframe_ctx_init() should not be called after this. * * @param derived_frame_ctx On success, a reference to the newly created * AVHWFramesContext. * @param derived_device_ctx A reference to the device to create the new * AVHWFramesContext on. * @param source_frame_ctx A reference to an existing AVHWFramesContext * which will be mapped to the derived context. * @param flags Some combination of AV_HWFRAME_MAP_* flags, defining the * mapping parameters to apply to frames which are allocated * in the derived device. * @return Zero on success, negative AVERROR code on failure. */ int av_hwframe_ctx_create_derived(AVBufferRef **derived_frame_ctx, enum AVPixelFormat format, AVBufferRef *derived_device_ctx, AVBufferRef *source_frame_ctx, int flags); #endif /* AVUTIL_HWCONTEXT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_cuda.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_CUDA_H #define AVUTIL_HWCONTEXT_CUDA_H #ifndef CUDA_VERSION #include #endif #include "pixfmt.h" /** * @file * An API-specific header for AV_HWDEVICE_TYPE_CUDA. * * This API supports dynamic frame pools. AVHWFramesContext.pool must return * AVBufferRefs whose data pointer is a CUdeviceptr. */ typedef struct AVCUDADeviceContextInternal AVCUDADeviceContextInternal; /** * This struct is allocated as AVHWDeviceContext.hwctx */ typedef struct AVCUDADeviceContext { CUcontext cuda_ctx; CUstream stream; AVCUDADeviceContextInternal *internal; } AVCUDADeviceContext; /** * AVHWFramesContext.hwctx is currently not used */ #endif /* AVUTIL_HWCONTEXT_CUDA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_d3d11va.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_D3D11VA_H #define AVUTIL_HWCONTEXT_D3D11VA_H /** * @file * An API-specific header for AV_HWDEVICE_TYPE_D3D11VA. * * The default pool implementation will be fixed-size if initial_pool_size is * set (and allocate elements from an array texture). Otherwise it will allocate * individual textures. Be aware that decoding requires a single array texture. * * Using sw_format==AV_PIX_FMT_YUV420P has special semantics, and maps to * DXGI_FORMAT_420_OPAQUE. av_hwframe_transfer_data() is not supported for * this format. Refer to MSDN for details. * * av_hwdevice_ctx_create() for this device type supports a key named "debug" * for the AVDictionary entry. If this is set to any value, the device creation * code will try to load various supported D3D debugging layers. */ #include #include /** * This struct is allocated as AVHWDeviceContext.hwctx */ typedef struct AVD3D11VADeviceContext { /** * Device used for texture creation and access. This can also be used to * set the libavcodec decoding device. * * Must be set by the user. This is the only mandatory field - the other * device context fields are set from this and are available for convenience. * * Deallocating the AVHWDeviceContext will always release this interface, * and it does not matter whether it was user-allocated. */ ID3D11Device *device; /** * If unset, this will be set from the device field on init. * * Deallocating the AVHWDeviceContext will always release this interface, * and it does not matter whether it was user-allocated. */ ID3D11DeviceContext *device_context; /** * If unset, this will be set from the device field on init. * * Deallocating the AVHWDeviceContext will always release this interface, * and it does not matter whether it was user-allocated. */ ID3D11VideoDevice *video_device; /** * If unset, this will be set from the device_context field on init. * * Deallocating the AVHWDeviceContext will always release this interface, * and it does not matter whether it was user-allocated. */ ID3D11VideoContext *video_context; /** * Callbacks for locking. They protect accesses to device_context and * video_context calls. They also protect access to the internal staging * texture (for av_hwframe_transfer_data() calls). They do NOT protect * access to hwcontext or decoder state in general. * * If unset on init, the hwcontext implementation will set them to use an * internal mutex. * * The underlying lock must be recursive. lock_ctx is for free use by the * locking implementation. */ void (*lock)(void *lock_ctx); void (*unlock)(void *lock_ctx); void *lock_ctx; } AVD3D11VADeviceContext; /** * D3D11 frame descriptor for pool allocation. * * In user-allocated pools, AVHWFramesContext.pool must return AVBufferRefs * with the data pointer pointing at an object of this type describing the * planes of the frame. * * This has no use outside of custom allocation, and AVFrame AVBufferRef do not * necessarily point to an instance of this struct. */ typedef struct AVD3D11FrameDescriptor { /** * The texture in which the frame is located. The reference count is * managed by the AVBufferRef, and destroying the reference will release * the interface. * * Normally stored in AVFrame.data[0]. */ ID3D11Texture2D *texture; /** * The index into the array texture element representing the frame, or 0 * if the texture is not an array texture. * * Normally stored in AVFrame.data[1] (cast from intptr_t). */ intptr_t index; } AVD3D11FrameDescriptor; /** * This struct is allocated as AVHWFramesContext.hwctx */ typedef struct AVD3D11VAFramesContext { /** * The canonical texture used for pool allocation. If this is set to NULL * on init, the hwframes implementation will allocate and set an array * texture if initial_pool_size > 0. * * The only situation when the API user should set this is: * - the user wants to do manual pool allocation (setting * AVHWFramesContext.pool), instead of letting AVHWFramesContext * allocate the pool * - of an array texture * - and wants it to use it for decoding * - this has to be done before calling av_hwframe_ctx_init() * * Deallocating the AVHWFramesContext will always release this interface, * and it does not matter whether it was user-allocated. * * This is in particular used by the libavcodec D3D11VA hwaccel, which * requires a single array texture. It will create ID3D11VideoDecoderOutputView * objects for each array texture element on decoder initialization. */ ID3D11Texture2D *texture; /** * D3D11_TEXTURE2D_DESC.BindFlags used for texture creation. The user must * at least set D3D11_BIND_DECODER if the frames context is to be used for * video decoding. * This field is ignored/invalid if a user-allocated texture is provided. */ UINT BindFlags; /** * D3D11_TEXTURE2D_DESC.MiscFlags used for texture creation. * This field is ignored/invalid if a user-allocated texture is provided. */ UINT MiscFlags; } AVD3D11VAFramesContext; #endif /* AVUTIL_HWCONTEXT_D3D11VA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_drm.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_DRM_H #define AVUTIL_HWCONTEXT_DRM_H #include #include /** * @file * API-specific header for AV_HWDEVICE_TYPE_DRM. * * Internal frame allocation is not currently supported - all frames * must be allocated by the user. Thus AVHWFramesContext is always * NULL, though this may change if support for frame allocation is * added in future. */ enum { /** * The maximum number of layers/planes in a DRM frame. */ AV_DRM_MAX_PLANES = 4 }; /** * DRM object descriptor. * * Describes a single DRM object, addressing it as a PRIME file * descriptor. */ typedef struct AVDRMObjectDescriptor { /** * DRM PRIME fd for the object. */ int fd; /** * Total size of the object. * * (This includes any parts not which do not contain image data.) */ size_t size; /** * Format modifier applied to the object (DRM_FORMAT_MOD_*). * * If the format modifier is unknown then this should be set to * DRM_FORMAT_MOD_INVALID. */ uint64_t format_modifier; } AVDRMObjectDescriptor; /** * DRM plane descriptor. * * Describes a single plane of a layer, which is contained within * a single object. */ typedef struct AVDRMPlaneDescriptor { /** * Index of the object containing this plane in the objects * array of the enclosing frame descriptor. */ int object_index; /** * Offset within that object of this plane. */ ptrdiff_t offset; /** * Pitch (linesize) of this plane. */ ptrdiff_t pitch; } AVDRMPlaneDescriptor; /** * DRM layer descriptor. * * Describes a single layer within a frame. This has the structure * defined by its format, and will contain one or more planes. */ typedef struct AVDRMLayerDescriptor { /** * Format of the layer (DRM_FORMAT_*). */ uint32_t format; /** * Number of planes in the layer. * * This must match the number of planes required by format. */ int nb_planes; /** * Array of planes in this layer. */ AVDRMPlaneDescriptor planes[AV_DRM_MAX_PLANES]; } AVDRMLayerDescriptor; /** * DRM frame descriptor. * * This is used as the data pointer for AV_PIX_FMT_DRM_PRIME frames. * It is also used by user-allocated frame pools - allocating in * AVHWFramesContext.pool must return AVBufferRefs which contain * an object of this type. * * The fields of this structure should be set such it can be * imported directly by EGL using the EGL_EXT_image_dma_buf_import * and EGL_EXT_image_dma_buf_import_modifiers extensions. * (Note that the exact layout of a particular format may vary between * platforms - we only specify that the same platform should be able * to import it.) * * The total number of planes must not exceed AV_DRM_MAX_PLANES, and * the order of the planes by increasing layer index followed by * increasing plane index must be the same as the order which would * be used for the data pointers in the equivalent software format. */ typedef struct AVDRMFrameDescriptor { /** * Number of DRM objects making up this frame. */ int nb_objects; /** * Array of objects making up the frame. */ AVDRMObjectDescriptor objects[AV_DRM_MAX_PLANES]; /** * Number of layers in the frame. */ int nb_layers; /** * Array of layers in the frame. */ AVDRMLayerDescriptor layers[AV_DRM_MAX_PLANES]; } AVDRMFrameDescriptor; /** * DRM device. * * Allocated as AVHWDeviceContext.hwctx. */ typedef struct AVDRMDeviceContext { /** * File descriptor of DRM device. * * This is used as the device to create frames on, and may also be * used in some derivation and mapping operations. * * If no device is required, set to -1. */ int fd; } AVDRMDeviceContext; #endif /* AVUTIL_HWCONTEXT_DRM_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_dxva2.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_DXVA2_H #define AVUTIL_HWCONTEXT_DXVA2_H /** * @file * An API-specific header for AV_HWDEVICE_TYPE_DXVA2. * * Only fixed-size pools are supported. * * For user-allocated pools, AVHWFramesContext.pool must return AVBufferRefs * with the data pointer set to a pointer to IDirect3DSurface9. */ #include #include /** * This struct is allocated as AVHWDeviceContext.hwctx */ typedef struct AVDXVA2DeviceContext { IDirect3DDeviceManager9 *devmgr; } AVDXVA2DeviceContext; /** * This struct is allocated as AVHWFramesContext.hwctx */ typedef struct AVDXVA2FramesContext { /** * The surface type (e.g. DXVA2_VideoProcessorRenderTarget or * DXVA2_VideoDecoderRenderTarget). Must be set by the caller. */ DWORD surface_type; /** * The surface pool. When an external pool is not provided by the caller, * this will be managed (allocated and filled on init, freed on uninit) by * libavutil. */ IDirect3DSurface9 **surfaces; int nb_surfaces; /** * Certain drivers require the decoder to be destroyed before the surfaces. * To allow internally managed pools to work properly in such cases, this * field is provided. * * If it is non-NULL, libavutil will call IDirectXVideoDecoder_Release() on * it just before the internal surface pool is freed. * * This is for convenience only. Some code uses other methods to manage the * decoder reference. */ IDirectXVideoDecoder *decoder_to_release; } AVDXVA2FramesContext; #endif /* AVUTIL_HWCONTEXT_DXVA2_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_mediacodec.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_MEDIACODEC_H #define AVUTIL_HWCONTEXT_MEDIACODEC_H /** * MediaCodec details. * * Allocated as AVHWDeviceContext.hwctx */ typedef struct AVMediaCodecDeviceContext { /** * android/view/Surface handle, to be filled by the user. * * This is the default surface used by decoders on this device. */ void *surface; } AVMediaCodecDeviceContext; #endif /* AVUTIL_HWCONTEXT_MEDIACODEC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_qsv.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_QSV_H #define AVUTIL_HWCONTEXT_QSV_H #include /** * @file * An API-specific header for AV_HWDEVICE_TYPE_QSV. * * This API does not support dynamic frame pools. AVHWFramesContext.pool must * contain AVBufferRefs whose data pointer points to an mfxFrameSurface1 struct. */ /** * This struct is allocated as AVHWDeviceContext.hwctx */ typedef struct AVQSVDeviceContext { mfxSession session; } AVQSVDeviceContext; /** * This struct is allocated as AVHWFramesContext.hwctx */ typedef struct AVQSVFramesContext { mfxFrameSurface1 *surfaces; int nb_surfaces; /** * A combination of MFX_MEMTYPE_* describing the frame pool. */ int frame_type; } AVQSVFramesContext; #endif /* AVUTIL_HWCONTEXT_QSV_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_vaapi.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_VAAPI_H #define AVUTIL_HWCONTEXT_VAAPI_H #include /** * @file * API-specific header for AV_HWDEVICE_TYPE_VAAPI. * * Dynamic frame pools are supported, but note that any pool used as a render * target is required to be of fixed size in order to be be usable as an * argument to vaCreateContext(). * * For user-allocated pools, AVHWFramesContext.pool must return AVBufferRefs * with the data pointer set to a VASurfaceID. */ enum { /** * The quirks field has been set by the user and should not be detected * automatically by av_hwdevice_ctx_init(). */ AV_VAAPI_DRIVER_QUIRK_USER_SET = (1 << 0), /** * The driver does not destroy parameter buffers when they are used by * vaRenderPicture(). Additional code will be required to destroy them * separately afterwards. */ AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS = (1 << 1), /** * The driver does not support the VASurfaceAttribMemoryType attribute, * so the surface allocation code will not try to use it. */ AV_VAAPI_DRIVER_QUIRK_ATTRIB_MEMTYPE = (1 << 2), /** * The driver does not support surface attributes at all. * The surface allocation code will never pass them to surface allocation, * and the results of the vaQuerySurfaceAttributes() call will be faked. */ AV_VAAPI_DRIVER_QUIRK_SURFACE_ATTRIBUTES = (1 << 3), }; /** * VAAPI connection details. * * Allocated as AVHWDeviceContext.hwctx */ typedef struct AVVAAPIDeviceContext { /** * The VADisplay handle, to be filled by the user. */ VADisplay display; /** * Driver quirks to apply - this is filled by av_hwdevice_ctx_init(), * with reference to a table of known drivers, unless the * AV_VAAPI_DRIVER_QUIRK_USER_SET bit is already present. The user * may need to refer to this field when performing any later * operations using VAAPI with the same VADisplay. */ unsigned int driver_quirks; } AVVAAPIDeviceContext; /** * VAAPI-specific data associated with a frame pool. * * Allocated as AVHWFramesContext.hwctx. */ typedef struct AVVAAPIFramesContext { /** * Set by the user to apply surface attributes to all surfaces in * the frame pool. If null, default settings are used. */ VASurfaceAttrib *attributes; int nb_attributes; /** * The surfaces IDs of all surfaces in the pool after creation. * Only valid if AVHWFramesContext.initial_pool_size was positive. * These are intended to be used as the render_targets arguments to * vaCreateContext(). */ VASurfaceID *surface_ids; int nb_surfaces; } AVVAAPIFramesContext; /** * VAAPI hardware pipeline configuration details. * * Allocated with av_hwdevice_hwconfig_alloc(). */ typedef struct AVVAAPIHWConfig { /** * ID of a VAAPI pipeline configuration. */ VAConfigID config_id; } AVVAAPIHWConfig; #endif /* AVUTIL_HWCONTEXT_VAAPI_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_vdpau.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_VDPAU_H #define AVUTIL_HWCONTEXT_VDPAU_H #include /** * @file * An API-specific header for AV_HWDEVICE_TYPE_VDPAU. * * This API supports dynamic frame pools. AVHWFramesContext.pool must return * AVBufferRefs whose data pointer is a VdpVideoSurface. */ /** * This struct is allocated as AVHWDeviceContext.hwctx */ typedef struct AVVDPAUDeviceContext { VdpDevice device; VdpGetProcAddress *get_proc_address; } AVVDPAUDeviceContext; /** * AVHWFramesContext.hwctx is currently not used */ #endif /* AVUTIL_HWCONTEXT_VDPAU_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/hwcontext_videotoolbox.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_HWCONTEXT_VIDEOTOOLBOX_H #define AVUTIL_HWCONTEXT_VIDEOTOOLBOX_H #include #include #include "pixfmt.h" /** * @file * An API-specific header for AV_HWDEVICE_TYPE_VIDEOTOOLBOX. * * This API currently does not support frame allocation, as the raw VideoToolbox * API does allocation, and FFmpeg itself never has the need to allocate frames. * * If the API user sets a custom pool, AVHWFramesContext.pool must return * AVBufferRefs whose data pointer is a CVImageBufferRef or CVPixelBufferRef. * * Currently AVHWDeviceContext.hwctx and AVHWFramesContext.hwctx are always * NULL. */ /** * Convert a VideoToolbox (actually CoreVideo) format to AVPixelFormat. * Returns AV_PIX_FMT_NONE if no known equivalent was found. */ enum AVPixelFormat av_map_videotoolbox_format_to_pixfmt(uint32_t cv_fmt); /** * Convert an AVPixelFormat to a VideoToolbox (actually CoreVideo) format. * Returns 0 if no known equivalent was found. */ uint32_t av_map_videotoolbox_format_from_pixfmt(enum AVPixelFormat pix_fmt); #endif /* AVUTIL_HWCONTEXT_VIDEOTOOLBOX_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/imgutils.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_IMGUTILS_H #define AVUTIL_IMGUTILS_H /** * @file * misc image utilities * * @addtogroup lavu_picture * @{ */ #include "avutil.h" #include "pixdesc.h" #include "rational.h" /** * Compute the max pixel step for each plane of an image with a * format described by pixdesc. * * The pixel step is the distance in bytes between the first byte of * the group of bytes which describe a pixel component and the first * byte of the successive group in the same plane for the same * component. * * @param max_pixsteps an array which is filled with the max pixel step * for each plane. Since a plane may contain different pixel * components, the computed max_pixsteps[plane] is relative to the * component in the plane with the max pixel step. * @param max_pixstep_comps an array which is filled with the component * for each plane which has the max pixel step. May be NULL. */ void av_image_fill_max_pixsteps(int max_pixsteps[4], int max_pixstep_comps[4], const AVPixFmtDescriptor *pixdesc); /** * Compute the size of an image line with format pix_fmt and width * width for the plane plane. * * @return the computed size in bytes */ int av_image_get_linesize(enum AVPixelFormat pix_fmt, int width, int plane); /** * Fill plane linesizes for an image with pixel format pix_fmt and * width width. * * @param linesizes array to be filled with the linesize for each plane * @return >= 0 in case of success, a negative error code otherwise */ int av_image_fill_linesizes(int linesizes[4], enum AVPixelFormat pix_fmt, int width); /** * Fill plane data pointers for an image with pixel format pix_fmt and * height height. * * @param data pointers array to be filled with the pointer for each image plane * @param ptr the pointer to a buffer which will contain the image * @param linesizes the array containing the linesize for each * plane, should be filled by av_image_fill_linesizes() * @return the size in bytes required for the image buffer, a negative * error code in case of failure */ int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height, uint8_t *ptr, const int linesizes[4]); /** * Allocate an image with size w and h and pixel format pix_fmt, and * fill pointers and linesizes accordingly. * The allocated image buffer has to be freed by using * av_freep(&pointers[0]). * * @param align the value to use for buffer size alignment * @return the size in bytes required for the image buffer, a negative * error code in case of failure */ int av_image_alloc(uint8_t *pointers[4], int linesizes[4], int w, int h, enum AVPixelFormat pix_fmt, int align); /** * Copy image plane from src to dst. * That is, copy "height" number of lines of "bytewidth" bytes each. * The first byte of each successive line is separated by *_linesize * bytes. * * bytewidth must be contained by both absolute values of dst_linesize * and src_linesize, otherwise the function behavior is undefined. * * @param dst_linesize linesize for the image plane in dst * @param src_linesize linesize for the image plane in src */ void av_image_copy_plane(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize, int bytewidth, int height); /** * Copy image in src_data to dst_data. * * @param dst_linesizes linesizes for the image in dst_data * @param src_linesizes linesizes for the image in src_data */ void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height); /** * Copy image data located in uncacheable (e.g. GPU mapped) memory. Where * available, this function will use special functionality for reading from such * memory, which may result in greatly improved performance compared to plain * av_image_copy(). * * The data pointers and the linesizes must be aligned to the maximum required * by the CPU architecture. * * @note The linesize parameters have the type ptrdiff_t here, while they are * int for av_image_copy(). * @note On x86, the linesizes currently need to be aligned to the cacheline * size (i.e. 64) to get improved performance. */ void av_image_copy_uc_from(uint8_t *dst_data[4], const ptrdiff_t dst_linesizes[4], const uint8_t *src_data[4], const ptrdiff_t src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height); /** * Setup the data pointers and linesizes based on the specified image * parameters and the provided array. * * The fields of the given image are filled in by using the src * address which points to the image data buffer. Depending on the * specified pixel format, one or multiple image data pointers and * line sizes will be set. If a planar format is specified, several * pointers will be set pointing to the different picture planes and * the line sizes of the different planes will be stored in the * lines_sizes array. Call with src == NULL to get the required * size for the src buffer. * * To allocate the buffer and fill in the dst_data and dst_linesize in * one call, use av_image_alloc(). * * @param dst_data data pointers to be filled in * @param dst_linesize linesizes for the image in dst_data to be filled in * @param src buffer which will contain or contains the actual image data, can be NULL * @param pix_fmt the pixel format of the image * @param width the width of the image in pixels * @param height the height of the image in pixels * @param align the value used in src for linesize alignment * @return the size in bytes required for src, a negative error code * in case of failure */ int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4], const uint8_t *src, enum AVPixelFormat pix_fmt, int width, int height, int align); /** * Return the size in bytes of the amount of data required to store an * image with the given parameters. * * @param pix_fmt the pixel format of the image * @param width the width of the image in pixels * @param height the height of the image in pixels * @param align the assumed linesize alignment * @return the buffer size in bytes, a negative error code in case of failure */ int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align); /** * Copy image data from an image into a buffer. * * av_image_get_buffer_size() can be used to compute the required size * for the buffer to fill. * * @param dst a buffer into which picture data will be copied * @param dst_size the size in bytes of dst * @param src_data pointers containing the source image data * @param src_linesize linesizes for the image in src_data * @param pix_fmt the pixel format of the source image * @param width the width of the source image in pixels * @param height the height of the source image in pixels * @param align the assumed linesize alignment for dst * @return the number of bytes written to dst, or a negative value * (error code) on error */ int av_image_copy_to_buffer(uint8_t *dst, int dst_size, const uint8_t * const src_data[4], const int src_linesize[4], enum AVPixelFormat pix_fmt, int width, int height, int align); /** * Check if the given dimension of an image is valid, meaning that all * bytes of the image can be addressed with a signed int. * * @param w the width of the picture * @param h the height of the picture * @param log_offset the offset to sum to the log level for logging with log_ctx * @param log_ctx the parent logging context, it may be NULL * @return >= 0 if valid, a negative error code otherwise */ int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx); /** * Check if the given dimension of an image is valid, meaning that all * bytes of a plane of an image with the specified pix_fmt can be addressed * with a signed int. * * @param w the width of the picture * @param h the height of the picture * @param max_pixels the maximum number of pixels the user wants to accept * @param pix_fmt the pixel format, can be AV_PIX_FMT_NONE if unknown. * @param log_offset the offset to sum to the log level for logging with log_ctx * @param log_ctx the parent logging context, it may be NULL * @return >= 0 if valid, a negative error code otherwise */ int av_image_check_size2(unsigned int w, unsigned int h, int64_t max_pixels, enum AVPixelFormat pix_fmt, int log_offset, void *log_ctx); /** * Check if the given sample aspect ratio of an image is valid. * * It is considered invalid if the denominator is 0 or if applying the ratio * to the image size would make the smaller dimension less than 1. If the * sar numerator is 0, it is considered unknown and will return as valid. * * @param w width of the image * @param h height of the image * @param sar sample aspect ratio of the image * @return 0 if valid, a negative AVERROR code otherwise */ int av_image_check_sar(unsigned int w, unsigned int h, AVRational sar); /** * Overwrite the image data with black. This is suitable for filling a * sub-rectangle of an image, meaning the padding between the right most pixel * and the left most pixel on the next line will not be overwritten. For some * formats, the image size might be rounded up due to inherent alignment. * * If the pixel format has alpha, the alpha is cleared to opaque. * * This can return an error if the pixel format is not supported. Normally, all * non-hwaccel pixel formats should be supported. * * Passing NULL for dst_data is allowed. Then the function returns whether the * operation would have succeeded. (It can return an error if the pix_fmt is * not supported.) * * @param dst_data data pointers to destination image * @param dst_linesize linesizes for the destination image * @param pix_fmt the pixel format of the image * @param range the color range of the image (important for colorspaces such as YUV) * @param width the width of the image in pixels * @param height the height of the image in pixels * @return 0 if the image data was cleared, a negative AVERROR code otherwise */ int av_image_fill_black(uint8_t *dst_data[4], const ptrdiff_t dst_linesize[4], enum AVPixelFormat pix_fmt, enum AVColorRange range, int width, int height); /** * @} */ #endif /* AVUTIL_IMGUTILS_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/intfloat.h ================================================ /* * Copyright (c) 2011 Mans Rullgard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_INTFLOAT_H #define AVUTIL_INTFLOAT_H #include #include "attributes.h" union av_intfloat32 { uint32_t i; float f; }; union av_intfloat64 { uint64_t i; double f; }; /** * Reinterpret a 32-bit integer as a float. */ static av_always_inline float av_int2float(uint32_t i) { union av_intfloat32 v; v.i = i; return v.f; } /** * Reinterpret a float as a 32-bit integer. */ static av_always_inline uint32_t av_float2int(float f) { union av_intfloat32 v; v.f = f; return v.i; } /** * Reinterpret a 64-bit integer as a double. */ static av_always_inline double av_int2double(uint64_t i) { union av_intfloat64 v; v.i = i; return v.f; } /** * Reinterpret a double as a 64-bit integer. */ static av_always_inline uint64_t av_double2int(double f) { union av_intfloat64 v; v.f = f; return v.i; } #endif /* AVUTIL_INTFLOAT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/intreadwrite.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_INTREADWRITE_H #define AVUTIL_INTREADWRITE_H #include #include "libavutil/avconfig.h" #include "attributes.h" #include "bswap.h" typedef union { uint64_t u64; uint32_t u32[2]; uint16_t u16[4]; uint8_t u8 [8]; double f64; float f32[2]; } av_alias av_alias64; typedef union { uint32_t u32; uint16_t u16[2]; uint8_t u8 [4]; float f32; } av_alias av_alias32; typedef union { uint16_t u16; uint8_t u8 [2]; } av_alias av_alias16; /* * Arch-specific headers can provide any combination of * AV_[RW][BLN](16|24|32|48|64) and AV_(COPY|SWAP|ZERO)(64|128) macros. * Preprocessor symbols must be defined, even if these are implemented * as inline functions. * * R/W means read/write, B/L/N means big/little/native endianness. * The following macros require aligned access, compared to their * unaligned variants: AV_(COPY|SWAP|ZERO)(64|128), AV_[RW]N[8-64]A. * Incorrect usage may range from abysmal performance to crash * depending on the platform. * * The unaligned variants are AV_[RW][BLN][8-64] and AV_COPY*U. */ #ifdef HAVE_AV_CONFIG_H #include "config.h" #if ARCH_ARM # include "arm/intreadwrite.h" #elif ARCH_AVR32 # include "avr32/intreadwrite.h" #elif ARCH_MIPS # include "mips/intreadwrite.h" #elif ARCH_PPC # include "ppc/intreadwrite.h" #elif ARCH_TOMI # include "tomi/intreadwrite.h" #elif ARCH_X86 # include "x86/intreadwrite.h" #endif #endif /* HAVE_AV_CONFIG_H */ /* * Map AV_RNXX <-> AV_R[BL]XX for all variants provided by per-arch headers. */ #if AV_HAVE_BIGENDIAN # if defined(AV_RN16) && !defined(AV_RB16) # define AV_RB16(p) AV_RN16(p) # elif !defined(AV_RN16) && defined(AV_RB16) # define AV_RN16(p) AV_RB16(p) # endif # if defined(AV_WN16) && !defined(AV_WB16) # define AV_WB16(p, v) AV_WN16(p, v) # elif !defined(AV_WN16) && defined(AV_WB16) # define AV_WN16(p, v) AV_WB16(p, v) # endif # if defined(AV_RN24) && !defined(AV_RB24) # define AV_RB24(p) AV_RN24(p) # elif !defined(AV_RN24) && defined(AV_RB24) # define AV_RN24(p) AV_RB24(p) # endif # if defined(AV_WN24) && !defined(AV_WB24) # define AV_WB24(p, v) AV_WN24(p, v) # elif !defined(AV_WN24) && defined(AV_WB24) # define AV_WN24(p, v) AV_WB24(p, v) # endif # if defined(AV_RN32) && !defined(AV_RB32) # define AV_RB32(p) AV_RN32(p) # elif !defined(AV_RN32) && defined(AV_RB32) # define AV_RN32(p) AV_RB32(p) # endif # if defined(AV_WN32) && !defined(AV_WB32) # define AV_WB32(p, v) AV_WN32(p, v) # elif !defined(AV_WN32) && defined(AV_WB32) # define AV_WN32(p, v) AV_WB32(p, v) # endif # if defined(AV_RN48) && !defined(AV_RB48) # define AV_RB48(p) AV_RN48(p) # elif !defined(AV_RN48) && defined(AV_RB48) # define AV_RN48(p) AV_RB48(p) # endif # if defined(AV_WN48) && !defined(AV_WB48) # define AV_WB48(p, v) AV_WN48(p, v) # elif !defined(AV_WN48) && defined(AV_WB48) # define AV_WN48(p, v) AV_WB48(p, v) # endif # if defined(AV_RN64) && !defined(AV_RB64) # define AV_RB64(p) AV_RN64(p) # elif !defined(AV_RN64) && defined(AV_RB64) # define AV_RN64(p) AV_RB64(p) # endif # if defined(AV_WN64) && !defined(AV_WB64) # define AV_WB64(p, v) AV_WN64(p, v) # elif !defined(AV_WN64) && defined(AV_WB64) # define AV_WN64(p, v) AV_WB64(p, v) # endif #else /* AV_HAVE_BIGENDIAN */ # if defined(AV_RN16) && !defined(AV_RL16) # define AV_RL16(p) AV_RN16(p) # elif !defined(AV_RN16) && defined(AV_RL16) # define AV_RN16(p) AV_RL16(p) # endif # if defined(AV_WN16) && !defined(AV_WL16) # define AV_WL16(p, v) AV_WN16(p, v) # elif !defined(AV_WN16) && defined(AV_WL16) # define AV_WN16(p, v) AV_WL16(p, v) # endif # if defined(AV_RN24) && !defined(AV_RL24) # define AV_RL24(p) AV_RN24(p) # elif !defined(AV_RN24) && defined(AV_RL24) # define AV_RN24(p) AV_RL24(p) # endif # if defined(AV_WN24) && !defined(AV_WL24) # define AV_WL24(p, v) AV_WN24(p, v) # elif !defined(AV_WN24) && defined(AV_WL24) # define AV_WN24(p, v) AV_WL24(p, v) # endif # if defined(AV_RN32) && !defined(AV_RL32) # define AV_RL32(p) AV_RN32(p) # elif !defined(AV_RN32) && defined(AV_RL32) # define AV_RN32(p) AV_RL32(p) # endif # if defined(AV_WN32) && !defined(AV_WL32) # define AV_WL32(p, v) AV_WN32(p, v) # elif !defined(AV_WN32) && defined(AV_WL32) # define AV_WN32(p, v) AV_WL32(p, v) # endif # if defined(AV_RN48) && !defined(AV_RL48) # define AV_RL48(p) AV_RN48(p) # elif !defined(AV_RN48) && defined(AV_RL48) # define AV_RN48(p) AV_RL48(p) # endif # if defined(AV_WN48) && !defined(AV_WL48) # define AV_WL48(p, v) AV_WN48(p, v) # elif !defined(AV_WN48) && defined(AV_WL48) # define AV_WN48(p, v) AV_WL48(p, v) # endif # if defined(AV_RN64) && !defined(AV_RL64) # define AV_RL64(p) AV_RN64(p) # elif !defined(AV_RN64) && defined(AV_RL64) # define AV_RN64(p) AV_RL64(p) # endif # if defined(AV_WN64) && !defined(AV_WL64) # define AV_WL64(p, v) AV_WN64(p, v) # elif !defined(AV_WN64) && defined(AV_WL64) # define AV_WN64(p, v) AV_WL64(p, v) # endif #endif /* !AV_HAVE_BIGENDIAN */ /* * Define AV_[RW]N helper macros to simplify definitions not provided * by per-arch headers. */ #if defined(__GNUC__) union unaligned_64 { uint64_t l; } __attribute__((packed)) av_alias; union unaligned_32 { uint32_t l; } __attribute__((packed)) av_alias; union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias; # define AV_RN(s, p) (((const union unaligned_##s *) (p))->l) # define AV_WN(s, p, v) ((((union unaligned_##s *) (p))->l) = (v)) #elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_X64) || defined(_M_ARM64)) && AV_HAVE_FAST_UNALIGNED # define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p))) # define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v)) #elif AV_HAVE_FAST_UNALIGNED # define AV_RN(s, p) (((const av_alias##s*)(p))->u##s) # define AV_WN(s, p, v) (((av_alias##s*)(p))->u##s = (v)) #else #ifndef AV_RB16 # define AV_RB16(x) \ ((((const uint8_t*)(x))[0] << 8) | \ ((const uint8_t*)(x))[1]) #endif #ifndef AV_WB16 # define AV_WB16(p, val) do { \ uint16_t d = (val); \ ((uint8_t*)(p))[1] = (d); \ ((uint8_t*)(p))[0] = (d)>>8; \ } while(0) #endif #ifndef AV_RL16 # define AV_RL16(x) \ ((((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[0]) #endif #ifndef AV_WL16 # define AV_WL16(p, val) do { \ uint16_t d = (val); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ } while(0) #endif #ifndef AV_RB32 # define AV_RB32(x) \ (((uint32_t)((const uint8_t*)(x))[0] << 24) | \ (((const uint8_t*)(x))[1] << 16) | \ (((const uint8_t*)(x))[2] << 8) | \ ((const uint8_t*)(x))[3]) #endif #ifndef AV_WB32 # define AV_WB32(p, val) do { \ uint32_t d = (val); \ ((uint8_t*)(p))[3] = (d); \ ((uint8_t*)(p))[2] = (d)>>8; \ ((uint8_t*)(p))[1] = (d)>>16; \ ((uint8_t*)(p))[0] = (d)>>24; \ } while(0) #endif #ifndef AV_RL32 # define AV_RL32(x) \ (((uint32_t)((const uint8_t*)(x))[3] << 24) | \ (((const uint8_t*)(x))[2] << 16) | \ (((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[0]) #endif #ifndef AV_WL32 # define AV_WL32(p, val) do { \ uint32_t d = (val); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ ((uint8_t*)(p))[3] = (d)>>24; \ } while(0) #endif #ifndef AV_RB64 # define AV_RB64(x) \ (((uint64_t)((const uint8_t*)(x))[0] << 56) | \ ((uint64_t)((const uint8_t*)(x))[1] << 48) | \ ((uint64_t)((const uint8_t*)(x))[2] << 40) | \ ((uint64_t)((const uint8_t*)(x))[3] << 32) | \ ((uint64_t)((const uint8_t*)(x))[4] << 24) | \ ((uint64_t)((const uint8_t*)(x))[5] << 16) | \ ((uint64_t)((const uint8_t*)(x))[6] << 8) | \ (uint64_t)((const uint8_t*)(x))[7]) #endif #ifndef AV_WB64 # define AV_WB64(p, val) do { \ uint64_t d = (val); \ ((uint8_t*)(p))[7] = (d); \ ((uint8_t*)(p))[6] = (d)>>8; \ ((uint8_t*)(p))[5] = (d)>>16; \ ((uint8_t*)(p))[4] = (d)>>24; \ ((uint8_t*)(p))[3] = (d)>>32; \ ((uint8_t*)(p))[2] = (d)>>40; \ ((uint8_t*)(p))[1] = (d)>>48; \ ((uint8_t*)(p))[0] = (d)>>56; \ } while(0) #endif #ifndef AV_RL64 # define AV_RL64(x) \ (((uint64_t)((const uint8_t*)(x))[7] << 56) | \ ((uint64_t)((const uint8_t*)(x))[6] << 48) | \ ((uint64_t)((const uint8_t*)(x))[5] << 40) | \ ((uint64_t)((const uint8_t*)(x))[4] << 32) | \ ((uint64_t)((const uint8_t*)(x))[3] << 24) | \ ((uint64_t)((const uint8_t*)(x))[2] << 16) | \ ((uint64_t)((const uint8_t*)(x))[1] << 8) | \ (uint64_t)((const uint8_t*)(x))[0]) #endif #ifndef AV_WL64 # define AV_WL64(p, val) do { \ uint64_t d = (val); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ ((uint8_t*)(p))[3] = (d)>>24; \ ((uint8_t*)(p))[4] = (d)>>32; \ ((uint8_t*)(p))[5] = (d)>>40; \ ((uint8_t*)(p))[6] = (d)>>48; \ ((uint8_t*)(p))[7] = (d)>>56; \ } while(0) #endif #if AV_HAVE_BIGENDIAN # define AV_RN(s, p) AV_RB##s(p) # define AV_WN(s, p, v) AV_WB##s(p, v) #else # define AV_RN(s, p) AV_RL##s(p) # define AV_WN(s, p, v) AV_WL##s(p, v) #endif #endif /* HAVE_FAST_UNALIGNED */ #ifndef AV_RN16 # define AV_RN16(p) AV_RN(16, p) #endif #ifndef AV_RN32 # define AV_RN32(p) AV_RN(32, p) #endif #ifndef AV_RN64 # define AV_RN64(p) AV_RN(64, p) #endif #ifndef AV_WN16 # define AV_WN16(p, v) AV_WN(16, p, v) #endif #ifndef AV_WN32 # define AV_WN32(p, v) AV_WN(32, p, v) #endif #ifndef AV_WN64 # define AV_WN64(p, v) AV_WN(64, p, v) #endif #if AV_HAVE_BIGENDIAN # define AV_RB(s, p) AV_RN##s(p) # define AV_WB(s, p, v) AV_WN##s(p, v) # define AV_RL(s, p) av_bswap##s(AV_RN##s(p)) # define AV_WL(s, p, v) AV_WN##s(p, av_bswap##s(v)) #else # define AV_RB(s, p) av_bswap##s(AV_RN##s(p)) # define AV_WB(s, p, v) AV_WN##s(p, av_bswap##s(v)) # define AV_RL(s, p) AV_RN##s(p) # define AV_WL(s, p, v) AV_WN##s(p, v) #endif #define AV_RB8(x) (((const uint8_t*)(x))[0]) #define AV_WB8(p, d) do { ((uint8_t*)(p))[0] = (d); } while(0) #define AV_RL8(x) AV_RB8(x) #define AV_WL8(p, d) AV_WB8(p, d) #ifndef AV_RB16 # define AV_RB16(p) AV_RB(16, p) #endif #ifndef AV_WB16 # define AV_WB16(p, v) AV_WB(16, p, v) #endif #ifndef AV_RL16 # define AV_RL16(p) AV_RL(16, p) #endif #ifndef AV_WL16 # define AV_WL16(p, v) AV_WL(16, p, v) #endif #ifndef AV_RB32 # define AV_RB32(p) AV_RB(32, p) #endif #ifndef AV_WB32 # define AV_WB32(p, v) AV_WB(32, p, v) #endif #ifndef AV_RL32 # define AV_RL32(p) AV_RL(32, p) #endif #ifndef AV_WL32 # define AV_WL32(p, v) AV_WL(32, p, v) #endif #ifndef AV_RB64 # define AV_RB64(p) AV_RB(64, p) #endif #ifndef AV_WB64 # define AV_WB64(p, v) AV_WB(64, p, v) #endif #ifndef AV_RL64 # define AV_RL64(p) AV_RL(64, p) #endif #ifndef AV_WL64 # define AV_WL64(p, v) AV_WL(64, p, v) #endif #ifndef AV_RB24 # define AV_RB24(x) \ ((((const uint8_t*)(x))[0] << 16) | \ (((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[2]) #endif #ifndef AV_WB24 # define AV_WB24(p, d) do { \ ((uint8_t*)(p))[2] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[0] = (d)>>16; \ } while(0) #endif #ifndef AV_RL24 # define AV_RL24(x) \ ((((const uint8_t*)(x))[2] << 16) | \ (((const uint8_t*)(x))[1] << 8) | \ ((const uint8_t*)(x))[0]) #endif #ifndef AV_WL24 # define AV_WL24(p, d) do { \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ } while(0) #endif #ifndef AV_RB48 # define AV_RB48(x) \ (((uint64_t)((const uint8_t*)(x))[0] << 40) | \ ((uint64_t)((const uint8_t*)(x))[1] << 32) | \ ((uint64_t)((const uint8_t*)(x))[2] << 24) | \ ((uint64_t)((const uint8_t*)(x))[3] << 16) | \ ((uint64_t)((const uint8_t*)(x))[4] << 8) | \ (uint64_t)((const uint8_t*)(x))[5]) #endif #ifndef AV_WB48 # define AV_WB48(p, darg) do { \ uint64_t d = (darg); \ ((uint8_t*)(p))[5] = (d); \ ((uint8_t*)(p))[4] = (d)>>8; \ ((uint8_t*)(p))[3] = (d)>>16; \ ((uint8_t*)(p))[2] = (d)>>24; \ ((uint8_t*)(p))[1] = (d)>>32; \ ((uint8_t*)(p))[0] = (d)>>40; \ } while(0) #endif #ifndef AV_RL48 # define AV_RL48(x) \ (((uint64_t)((const uint8_t*)(x))[5] << 40) | \ ((uint64_t)((const uint8_t*)(x))[4] << 32) | \ ((uint64_t)((const uint8_t*)(x))[3] << 24) | \ ((uint64_t)((const uint8_t*)(x))[2] << 16) | \ ((uint64_t)((const uint8_t*)(x))[1] << 8) | \ (uint64_t)((const uint8_t*)(x))[0]) #endif #ifndef AV_WL48 # define AV_WL48(p, darg) do { \ uint64_t d = (darg); \ ((uint8_t*)(p))[0] = (d); \ ((uint8_t*)(p))[1] = (d)>>8; \ ((uint8_t*)(p))[2] = (d)>>16; \ ((uint8_t*)(p))[3] = (d)>>24; \ ((uint8_t*)(p))[4] = (d)>>32; \ ((uint8_t*)(p))[5] = (d)>>40; \ } while(0) #endif /* * The AV_[RW]NA macros access naturally aligned data * in a type-safe way. */ #define AV_RNA(s, p) (((const av_alias##s*)(p))->u##s) #define AV_WNA(s, p, v) (((av_alias##s*)(p))->u##s = (v)) #ifndef AV_RN16A # define AV_RN16A(p) AV_RNA(16, p) #endif #ifndef AV_RN32A # define AV_RN32A(p) AV_RNA(32, p) #endif #ifndef AV_RN64A # define AV_RN64A(p) AV_RNA(64, p) #endif #ifndef AV_WN16A # define AV_WN16A(p, v) AV_WNA(16, p, v) #endif #ifndef AV_WN32A # define AV_WN32A(p, v) AV_WNA(32, p, v) #endif #ifndef AV_WN64A # define AV_WN64A(p, v) AV_WNA(64, p, v) #endif #if AV_HAVE_BIGENDIAN # define AV_RLA(s, p) av_bswap##s(AV_RN##s##A(p)) # define AV_WLA(s, p, v) AV_WN##s##A(p, av_bswap##s(v)) #else # define AV_RLA(s, p) AV_RN##s##A(p) # define AV_WLA(s, p, v) AV_WN##s##A(p, v) #endif #ifndef AV_RL64A # define AV_RL64A(p) AV_RLA(64, p) #endif #ifndef AV_WL64A # define AV_WL64A(p, v) AV_WLA(64, p, v) #endif /* * The AV_COPYxxU macros are suitable for copying data to/from unaligned * memory locations. */ #define AV_COPYU(n, d, s) AV_WN##n(d, AV_RN##n(s)); #ifndef AV_COPY16U # define AV_COPY16U(d, s) AV_COPYU(16, d, s) #endif #ifndef AV_COPY32U # define AV_COPY32U(d, s) AV_COPYU(32, d, s) #endif #ifndef AV_COPY64U # define AV_COPY64U(d, s) AV_COPYU(64, d, s) #endif #ifndef AV_COPY128U # define AV_COPY128U(d, s) \ do { \ AV_COPY64U(d, s); \ AV_COPY64U((char *)(d) + 8, (const char *)(s) + 8); \ } while(0) #endif /* Parameters for AV_COPY*, AV_SWAP*, AV_ZERO* must be * naturally aligned. They may be implemented using MMX, * so emms_c() must be called before using any float code * afterwards. */ #define AV_COPY(n, d, s) \ (((av_alias##n*)(d))->u##n = ((const av_alias##n*)(s))->u##n) #ifndef AV_COPY16 # define AV_COPY16(d, s) AV_COPY(16, d, s) #endif #ifndef AV_COPY32 # define AV_COPY32(d, s) AV_COPY(32, d, s) #endif #ifndef AV_COPY64 # define AV_COPY64(d, s) AV_COPY(64, d, s) #endif #ifndef AV_COPY128 # define AV_COPY128(d, s) \ do { \ AV_COPY64(d, s); \ AV_COPY64((char*)(d)+8, (char*)(s)+8); \ } while(0) #endif #define AV_SWAP(n, a, b) FFSWAP(av_alias##n, *(av_alias##n*)(a), *(av_alias##n*)(b)) #ifndef AV_SWAP64 # define AV_SWAP64(a, b) AV_SWAP(64, a, b) #endif #define AV_ZERO(n, d) (((av_alias##n*)(d))->u##n = 0) #ifndef AV_ZERO16 # define AV_ZERO16(d) AV_ZERO(16, d) #endif #ifndef AV_ZERO32 # define AV_ZERO32(d) AV_ZERO(32, d) #endif #ifndef AV_ZERO64 # define AV_ZERO64(d) AV_ZERO(64, d) #endif #ifndef AV_ZERO128 # define AV_ZERO128(d) \ do { \ AV_ZERO64(d); \ AV_ZERO64((char*)(d)+8); \ } while(0) #endif #endif /* AVUTIL_INTREADWRITE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/lfg.h ================================================ /* * Lagged Fibonacci PRNG * Copyright (c) 2008 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LFG_H #define AVUTIL_LFG_H #include typedef struct AVLFG { unsigned int state[64]; int index; } AVLFG; void av_lfg_init(AVLFG *c, unsigned int seed); /** * Seed the state of the ALFG using binary data. * * Return value: 0 on success, negative value (AVERROR) on failure. */ int av_lfg_init_from_data(AVLFG *c, const uint8_t *data, unsigned int length); /** * Get the next random unsigned 32-bit number using an ALFG. * * Please also consider a simple LCG like state= state*1664525+1013904223, * it may be good enough and faster for your specific use case. */ static inline unsigned int av_lfg_get(AVLFG *c){ c->state[c->index & 63] = c->state[(c->index-24) & 63] + c->state[(c->index-55) & 63]; return c->state[c->index++ & 63]; } /** * Get the next random unsigned 32-bit number using a MLFG. * * Please also consider av_lfg_get() above, it is faster. */ static inline unsigned int av_mlfg_get(AVLFG *c){ unsigned int a= c->state[(c->index-55) & 63]; unsigned int b= c->state[(c->index-24) & 63]; return c->state[c->index++ & 63] = 2*a*b+a+b; } /** * Get the next two numbers generated by a Box-Muller Gaussian * generator using the random numbers issued by lfg. * * @param out array where the two generated numbers are placed */ void av_bmg_get(AVLFG *lfg, double out[2]); #endif /* AVUTIL_LFG_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/log.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LOG_H #define AVUTIL_LOG_H #include #include "avutil.h" #include "attributes.h" #include "version.h" typedef enum { AV_CLASS_CATEGORY_NA = 0, AV_CLASS_CATEGORY_INPUT, AV_CLASS_CATEGORY_OUTPUT, AV_CLASS_CATEGORY_MUXER, AV_CLASS_CATEGORY_DEMUXER, AV_CLASS_CATEGORY_ENCODER, AV_CLASS_CATEGORY_DECODER, AV_CLASS_CATEGORY_FILTER, AV_CLASS_CATEGORY_BITSTREAM_FILTER, AV_CLASS_CATEGORY_SWSCALER, AV_CLASS_CATEGORY_SWRESAMPLER, AV_CLASS_CATEGORY_DEVICE_VIDEO_OUTPUT = 40, AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT, AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT, AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT, AV_CLASS_CATEGORY_DEVICE_OUTPUT, AV_CLASS_CATEGORY_DEVICE_INPUT, AV_CLASS_CATEGORY_NB ///< not part of ABI/API }AVClassCategory; #define AV_IS_INPUT_DEVICE(category) \ (((category) == AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT) || \ ((category) == AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT) || \ ((category) == AV_CLASS_CATEGORY_DEVICE_INPUT)) #define AV_IS_OUTPUT_DEVICE(category) \ (((category) == AV_CLASS_CATEGORY_DEVICE_VIDEO_OUTPUT) || \ ((category) == AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT) || \ ((category) == AV_CLASS_CATEGORY_DEVICE_OUTPUT)) struct AVOptionRanges; /** * Describe the class of an AVClass context structure. That is an * arbitrary struct of which the first field is a pointer to an * AVClass struct (e.g. AVCodecContext, AVFormatContext etc.). */ typedef struct AVClass { /** * The name of the class; usually it is the same name as the * context structure type to which the AVClass is associated. */ const char* class_name; /** * A pointer to a function which returns the name of a context * instance ctx associated with the class. */ const char* (*item_name)(void* ctx); /** * a pointer to the first option specified in the class if any or NULL * * @see av_set_default_options() */ const struct AVOption *option; /** * LIBAVUTIL_VERSION with which this structure was created. * This is used to allow fields to be added without requiring major * version bumps everywhere. */ int version; /** * Offset in the structure where log_level_offset is stored. * 0 means there is no such variable */ int log_level_offset_offset; /** * Offset in the structure where a pointer to the parent context for * logging is stored. For example a decoder could pass its AVCodecContext * to eval as such a parent context, which an av_log() implementation * could then leverage to display the parent context. * The offset can be NULL. */ int parent_log_context_offset; /** * Return next AVOptions-enabled child or NULL */ void* (*child_next)(void *obj, void *prev); /** * Return an AVClass corresponding to the next potential * AVOptions-enabled child. * * The difference between child_next and this is that * child_next iterates over _already existing_ objects, while * child_class_next iterates over _all possible_ children. */ const struct AVClass* (*child_class_next)(const struct AVClass *prev); /** * Category used for visualization (like color) * This is only set if the category is equal for all objects using this class. * available since version (51 << 16 | 56 << 8 | 100) */ AVClassCategory category; /** * Callback to return the category. * available since version (51 << 16 | 59 << 8 | 100) */ AVClassCategory (*get_category)(void* ctx); /** * Callback to return the supported/allowed ranges. * available since version (52.12) */ int (*query_ranges)(struct AVOptionRanges **, void *obj, const char *key, int flags); } AVClass; /** * @addtogroup lavu_log * * @{ * * @defgroup lavu_log_constants Logging Constants * * @{ */ /** * Print no output. */ #define AV_LOG_QUIET -8 /** * Something went really wrong and we will crash now. */ #define AV_LOG_PANIC 0 /** * Something went wrong and recovery is not possible. * For example, no header was found for a format which depends * on headers or an illegal combination of parameters is used. */ #define AV_LOG_FATAL 8 /** * Something went wrong and cannot losslessly be recovered. * However, not all future data is affected. */ #define AV_LOG_ERROR 16 /** * Something somehow does not look correct. This may or may not * lead to problems. An example would be the use of '-vstrict -2'. */ #define AV_LOG_WARNING 24 /** * Standard information. */ #define AV_LOG_INFO 32 /** * Detailed information. */ #define AV_LOG_VERBOSE 40 /** * Stuff which is only useful for libav* developers. */ #define AV_LOG_DEBUG 48 /** * Extremely verbose debugging, useful for libav* development. */ #define AV_LOG_TRACE 56 #define AV_LOG_MAX_OFFSET (AV_LOG_TRACE - AV_LOG_QUIET) /** * @} */ /** * Sets additional colors for extended debugging sessions. * @code av_log(ctx, AV_LOG_DEBUG|AV_LOG_C(134), "Message in purple\n"); @endcode * Requires 256color terminal support. Uses outside debugging is not * recommended. */ #define AV_LOG_C(x) ((x) << 8) /** * Send the specified message to the log if the level is less than or equal * to the current av_log_level. By default, all logging messages are sent to * stderr. This behavior can be altered by setting a different logging callback * function. * @see av_log_set_callback * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct or NULL if general log. * @param level The importance level of the message expressed using a @ref * lavu_log_constants "Logging Constant". * @param fmt The format string (printf-compatible) that specifies how * subsequent arguments are converted to output. */ void av_log(void *avcl, int level, const char *fmt, ...) av_printf_format(3, 4); /** * Send the specified message to the log if the level is less than or equal * to the current av_log_level. By default, all logging messages are sent to * stderr. This behavior can be altered by setting a different logging callback * function. * @see av_log_set_callback * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message expressed using a @ref * lavu_log_constants "Logging Constant". * @param fmt The format string (printf-compatible) that specifies how * subsequent arguments are converted to output. * @param vl The arguments referenced by the format string. */ void av_vlog(void *avcl, int level, const char *fmt, va_list vl); /** * Get the current log level * * @see lavu_log_constants * * @return Current log level */ int av_log_get_level(void); /** * Set the log level * * @see lavu_log_constants * * @param level Logging level */ void av_log_set_level(int level); /** * Set the logging callback * * @note The callback must be thread safe, even if the application does not use * threads itself as some codecs are multithreaded. * * @see av_log_default_callback * * @param callback A logging function with a compatible signature. */ void av_log_set_callback(void (*callback)(void*, int, const char*, va_list)); /** * Default logging callback * * It prints the message to stderr, optionally colorizing it. * * @param avcl A pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct. * @param level The importance level of the message expressed using a @ref * lavu_log_constants "Logging Constant". * @param fmt The format string (printf-compatible) that specifies how * subsequent arguments are converted to output. * @param vl The arguments referenced by the format string. */ void av_log_default_callback(void *avcl, int level, const char *fmt, va_list vl); /** * Return the context name * * @param ctx The AVClass context * * @return The AVClass class_name */ const char* av_default_item_name(void* ctx); AVClassCategory av_default_get_category(void *ptr); /** * Format a line of log the same way as the default callback. * @param line buffer to receive the formatted line * @param line_size size of the buffer * @param print_prefix used to store whether the prefix must be printed; * must point to a persistent integer initially set to 1 */ void av_log_format_line(void *ptr, int level, const char *fmt, va_list vl, char *line, int line_size, int *print_prefix); /** * Format a line of log the same way as the default callback. * @param line buffer to receive the formatted line; * may be NULL if line_size is 0 * @param line_size size of the buffer; at most line_size-1 characters will * be written to the buffer, plus one null terminator * @param print_prefix used to store whether the prefix must be printed; * must point to a persistent integer initially set to 1 * @return Returns a negative value if an error occurred, otherwise returns * the number of characters that would have been written for a * sufficiently large buffer, not including the terminating null * character. If the return value is not less than line_size, it means * that the log message was truncated to fit the buffer. */ int av_log_format_line2(void *ptr, int level, const char *fmt, va_list vl, char *line, int line_size, int *print_prefix); /** * Skip repeated messages, this requires the user app to use av_log() instead of * (f)printf as the 2 would otherwise interfere and lead to * "Last message repeated x times" messages below (f)printf messages with some * bad luck. * Also to receive the last, "last repeated" line if any, the user app must * call av_log(NULL, AV_LOG_QUIET, "%s", ""); at the end */ #define AV_LOG_SKIP_REPEATED 1 /** * Include the log severity in messages originating from codecs. * * Results in messages such as: * [rawvideo @ 0xDEADBEEF] [error] encode did not produce valid pts */ #define AV_LOG_PRINT_LEVEL 2 void av_log_set_flags(int arg); int av_log_get_flags(void); /** * @} */ #endif /* AVUTIL_LOG_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/lzo.h ================================================ /* * LZO 1x decompression * copyright (c) 2006 Reimar Doeffinger * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_LZO_H #define AVUTIL_LZO_H /** * @defgroup lavu_lzo LZO * @ingroup lavu_crypto * * @{ */ #include /** @name Error flags returned by av_lzo1x_decode * @{ */ /// end of the input buffer reached before decoding finished #define AV_LZO_INPUT_DEPLETED 1 /// decoded data did not fit into output buffer #define AV_LZO_OUTPUT_FULL 2 /// a reference to previously decoded data was wrong #define AV_LZO_INVALID_BACKPTR 4 /// a non-specific error in the compressed bitstream #define AV_LZO_ERROR 8 /** @} */ #define AV_LZO_INPUT_PADDING 8 #define AV_LZO_OUTPUT_PADDING 12 /** * @brief Decodes LZO 1x compressed data. * @param out output buffer * @param outlen size of output buffer, number of bytes left are returned here * @param in input buffer * @param inlen size of input buffer, number of bytes left are returned here * @return 0 on success, otherwise a combination of the error flags above * * Make sure all buffers are appropriately padded, in must provide * AV_LZO_INPUT_PADDING, out must provide AV_LZO_OUTPUT_PADDING additional bytes. */ int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen); /** * @} */ #endif /* AVUTIL_LZO_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/macros.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu * Utility Preprocessor macros */ #ifndef AVUTIL_MACROS_H #define AVUTIL_MACROS_H /** * @addtogroup preproc_misc Preprocessor String Macros * * String manipulation macros * * @{ */ #define AV_STRINGIFY(s) AV_TOSTRING(s) #define AV_TOSTRING(s) #s #define AV_GLUE(a, b) a ## b #define AV_JOIN(a, b) AV_GLUE(a, b) /** * @} */ #define AV_PRAGMA(s) _Pragma(#s) #define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1)) #endif /* AVUTIL_MACROS_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/mastering_display_metadata.h ================================================ /* * Copyright (c) 2016 Neil Birkbeck * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_MASTERING_DISPLAY_METADATA_H #define AVUTIL_MASTERING_DISPLAY_METADATA_H #include "frame.h" #include "rational.h" /** * Mastering display metadata capable of representing the color volume of * the display used to master the content (SMPTE 2086:2014). * * To be used as payload of a AVFrameSideData or AVPacketSideData with the * appropriate type. * * @note The struct should be allocated with av_mastering_display_metadata_alloc() * and its size is not a part of the public ABI. */ typedef struct AVMasteringDisplayMetadata { /** * CIE 1931 xy chromaticity coords of color primaries (r, g, b order). */ AVRational display_primaries[3][2]; /** * CIE 1931 xy chromaticity coords of white point. */ AVRational white_point[2]; /** * Min luminance of mastering display (cd/m^2). */ AVRational min_luminance; /** * Max luminance of mastering display (cd/m^2). */ AVRational max_luminance; /** * Flag indicating whether the display primaries (and white point) are set. */ int has_primaries; /** * Flag indicating whether the luminance (min_ and max_) have been set. */ int has_luminance; } AVMasteringDisplayMetadata; /** * Allocate an AVMasteringDisplayMetadata structure and set its fields to * default values. The resulting struct can be freed using av_freep(). * * @return An AVMasteringDisplayMetadata filled with default values or NULL * on failure. */ AVMasteringDisplayMetadata *av_mastering_display_metadata_alloc(void); /** * Allocate a complete AVMasteringDisplayMetadata and add it to the frame. * * @param frame The frame which side data is added to. * * @return The AVMasteringDisplayMetadata structure to be filled by caller. */ AVMasteringDisplayMetadata *av_mastering_display_metadata_create_side_data(AVFrame *frame); /** * Content light level needed by to transmit HDR over HDMI (CTA-861.3). * * To be used as payload of a AVFrameSideData or AVPacketSideData with the * appropriate type. * * @note The struct should be allocated with av_content_light_metadata_alloc() * and its size is not a part of the public ABI. */ typedef struct AVContentLightMetadata { /** * Max content light level (cd/m^2). */ unsigned MaxCLL; /** * Max average light level per frame (cd/m^2). */ unsigned MaxFALL; } AVContentLightMetadata; /** * Allocate an AVContentLightMetadata structure and set its fields to * default values. The resulting struct can be freed using av_freep(). * * @return An AVContentLightMetadata filled with default values or NULL * on failure. */ AVContentLightMetadata *av_content_light_metadata_alloc(size_t *size); /** * Allocate a complete AVContentLightMetadata and add it to the frame. * * @param frame The frame which side data is added to. * * @return The AVContentLightMetadata structure to be filled by caller. */ AVContentLightMetadata *av_content_light_metadata_create_side_data(AVFrame *frame); #endif /* AVUTIL_MASTERING_DISPLAY_METADATA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/mathematics.h ================================================ /* * copyright (c) 2005-2012 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @addtogroup lavu_math * Mathematical utilities for working with timestamp and time base. */ #ifndef AVUTIL_MATHEMATICS_H #define AVUTIL_MATHEMATICS_H #include #include #include "attributes.h" #include "rational.h" #include "intfloat.h" #ifndef M_E #define M_E 2.7182818284590452354 /* e */ #endif #ifndef M_LN2 #define M_LN2 0.69314718055994530942 /* log_e 2 */ #endif #ifndef M_LN10 #define M_LN10 2.30258509299404568402 /* log_e 10 */ #endif #ifndef M_LOG2_10 #define M_LOG2_10 3.32192809488736234787 /* log_2 10 */ #endif #ifndef M_PHI #define M_PHI 1.61803398874989484820 /* phi / golden ratio */ #endif #ifndef M_PI #define M_PI 3.14159265358979323846 /* pi */ #endif #ifndef M_PI_2 #define M_PI_2 1.57079632679489661923 /* pi/2 */ #endif #ifndef M_SQRT1_2 #define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */ #endif #ifndef M_SQRT2 #define M_SQRT2 1.41421356237309504880 /* sqrt(2) */ #endif #ifndef NAN #define NAN av_int2float(0x7fc00000) #endif #ifndef INFINITY #define INFINITY av_int2float(0x7f800000) #endif /** * @addtogroup lavu_math * * @{ */ /** * Rounding methods. */ enum AVRounding { AV_ROUND_ZERO = 0, ///< Round toward zero. AV_ROUND_INF = 1, ///< Round away from zero. AV_ROUND_DOWN = 2, ///< Round toward -infinity. AV_ROUND_UP = 3, ///< Round toward +infinity. AV_ROUND_NEAR_INF = 5, ///< Round to nearest and halfway cases away from zero. /** * Flag telling rescaling functions to pass `INT64_MIN`/`MAX` through * unchanged, avoiding special cases for #AV_NOPTS_VALUE. * * Unlike other values of the enumeration AVRounding, this value is a * bitmask that must be used in conjunction with another value of the * enumeration through a bitwise OR, in order to set behavior for normal * cases. * * @code{.c} * av_rescale_rnd(3, 1, 2, AV_ROUND_UP | AV_ROUND_PASS_MINMAX); * // Rescaling 3: * // Calculating 3 * 1 / 2 * // 3 / 2 is rounded up to 2 * // => 2 * * av_rescale_rnd(AV_NOPTS_VALUE, 1, 2, AV_ROUND_UP | AV_ROUND_PASS_MINMAX); * // Rescaling AV_NOPTS_VALUE: * // AV_NOPTS_VALUE == INT64_MIN * // AV_NOPTS_VALUE is passed through * // => AV_NOPTS_VALUE * @endcode */ AV_ROUND_PASS_MINMAX = 8192, }; /** * Compute the greatest common divisor of two integer operands. * * @param a,b Operands * @return GCD of a and b up to sign; if a >= 0 and b >= 0, return value is >= 0; * if a == 0 and b == 0, returns 0. */ int64_t av_const av_gcd(int64_t a, int64_t b); /** * Rescale a 64-bit integer with rounding to nearest. * * The operation is mathematically equivalent to `a * b / c`, but writing that * directly can overflow. * * This function is equivalent to av_rescale_rnd() with #AV_ROUND_NEAR_INF. * * @see av_rescale_rnd(), av_rescale_q(), av_rescale_q_rnd() */ int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const; /** * Rescale a 64-bit integer with specified rounding. * * The operation is mathematically equivalent to `a * b / c`, but writing that * directly can overflow, and does not support different rounding methods. * * @see av_rescale(), av_rescale_q(), av_rescale_q_rnd() */ int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd) av_const; /** * Rescale a 64-bit integer by 2 rational numbers. * * The operation is mathematically equivalent to `a * bq / cq`. * * This function is equivalent to av_rescale_q_rnd() with #AV_ROUND_NEAR_INF. * * @see av_rescale(), av_rescale_rnd(), av_rescale_q_rnd() */ int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const; /** * Rescale a 64-bit integer by 2 rational numbers with specified rounding. * * The operation is mathematically equivalent to `a * bq / cq`. * * @see av_rescale(), av_rescale_rnd(), av_rescale_q() */ int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding rnd) av_const; /** * Compare two timestamps each in its own time base. * * @return One of the following values: * - -1 if `ts_a` is before `ts_b` * - 1 if `ts_a` is after `ts_b` * - 0 if they represent the same position * * @warning * The result of the function is undefined if one of the timestamps is outside * the `int64_t` range when represented in the other's timebase. */ int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b); /** * Compare the remainders of two integer operands divided by a common divisor. * * In other words, compare the least significant `log2(mod)` bits of integers * `a` and `b`. * * @code{.c} * av_compare_mod(0x11, 0x02, 0x10) < 0 // since 0x11 % 0x10 (0x1) < 0x02 % 0x10 (0x2) * av_compare_mod(0x11, 0x02, 0x20) > 0 // since 0x11 % 0x20 (0x11) > 0x02 % 0x20 (0x02) * @endcode * * @param a,b Operands * @param mod Divisor; must be a power of 2 * @return * - a negative value if `a % mod < b % mod` * - a positive value if `a % mod > b % mod` * - zero if `a % mod == b % mod` */ int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod); /** * Rescale a timestamp while preserving known durations. * * This function is designed to be called per audio packet to scale the input * timestamp to a different time base. Compared to a simple av_rescale_q() * call, this function is robust against possible inconsistent frame durations. * * The `last` parameter is a state variable that must be preserved for all * subsequent calls for the same stream. For the first call, `*last` should be * initialized to #AV_NOPTS_VALUE. * * @param[in] in_tb Input time base * @param[in] in_ts Input timestamp * @param[in] fs_tb Duration time base; typically this is finer-grained * (greater) than `in_tb` and `out_tb` * @param[in] duration Duration till the next call to this function (i.e. * duration of the current packet/frame) * @param[in,out] last Pointer to a timestamp expressed in terms of * `fs_tb`, acting as a state variable * @param[in] out_tb Output timebase * @return Timestamp expressed in terms of `out_tb` * * @note In the context of this function, "duration" is in term of samples, not * seconds. */ int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb); /** * Add a value to a timestamp. * * This function guarantees that when the same value is repeatly added that * no accumulation of rounding errors occurs. * * @param[in] ts Input timestamp * @param[in] ts_tb Input timestamp time base * @param[in] inc Value to be added * @param[in] inc_tb Time base of `inc` */ int64_t av_add_stable(AVRational ts_tb, int64_t ts, AVRational inc_tb, int64_t inc); /** * @} */ #endif /* AVUTIL_MATHEMATICS_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/md5.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_md5 * Public header for MD5 hash function implementation. */ #ifndef AVUTIL_MD5_H #define AVUTIL_MD5_H #include #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_md5 MD5 * @ingroup lavu_hash * MD5 hash function implementation. * * @{ */ extern const int av_md5_size; struct AVMD5; /** * Allocate an AVMD5 context. */ struct AVMD5 *av_md5_alloc(void); /** * Initialize MD5 hashing. * * @param ctx pointer to the function context (of size av_md5_size) */ void av_md5_init(struct AVMD5 *ctx); /** * Update hash value. * * @param ctx hash function context * @param src input data to update hash with * @param len input data length */ #if FF_API_CRYPTO_SIZE_T void av_md5_update(struct AVMD5 *ctx, const uint8_t *src, int len); #else void av_md5_update(struct AVMD5 *ctx, const uint8_t *src, size_t len); #endif /** * Finish hashing and output digest value. * * @param ctx hash function context * @param dst buffer where output digest value is stored */ void av_md5_final(struct AVMD5 *ctx, uint8_t *dst); /** * Hash an array of data. * * @param dst The output buffer to write the digest into * @param src The data to hash * @param len The length of the data, in bytes */ #if FF_API_CRYPTO_SIZE_T void av_md5_sum(uint8_t *dst, const uint8_t *src, const int len); #else void av_md5_sum(uint8_t *dst, const uint8_t *src, size_t len); #endif /** * @} */ #endif /* AVUTIL_MD5_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/mem.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_mem * Memory handling functions */ #ifndef AVUTIL_MEM_H #define AVUTIL_MEM_H #include #include #include "attributes.h" #include "error.h" #include "avutil.h" /** * @addtogroup lavu_mem * Utilities for manipulating memory. * * FFmpeg has several applications of memory that are not required of a typical * program. For example, the computing-heavy components like video decoding and * encoding can be sped up significantly through the use of aligned memory. * * However, for each of FFmpeg's applications of memory, there might not be a * recognized or standardized API for that specific use. Memory alignment, for * instance, varies wildly depending on operating systems, architectures, and * compilers. Hence, this component of @ref libavutil is created to make * dealing with memory consistently possible on all platforms. * * @{ * * @defgroup lavu_mem_macros Alignment Macros * Helper macros for declaring aligned variables. * @{ */ /** * @def DECLARE_ALIGNED(n,t,v) * Declare a variable that is aligned in memory. * * @code{.c} * DECLARE_ALIGNED(16, uint16_t, aligned_int) = 42; * DECLARE_ALIGNED(32, uint8_t, aligned_array)[128]; * * // The default-alignment equivalent would be * uint16_t aligned_int = 42; * uint8_t aligned_array[128]; * @endcode * * @param n Minimum alignment in bytes * @param t Type of the variable (or array element) * @param v Name of the variable */ /** * @def DECLARE_ASM_ALIGNED(n,t,v) * Declare an aligned variable appropriate for use in inline assembly code. * * @code{.c} * DECLARE_ASM_ALIGNED(16, uint64_t, pw_08) = UINT64_C(0x0008000800080008); * @endcode * * @param n Minimum alignment in bytes * @param t Type of the variable (or array element) * @param v Name of the variable */ /** * @def DECLARE_ASM_CONST(n,t,v) * Declare a static constant aligned variable appropriate for use in inline * assembly code. * * @code{.c} * DECLARE_ASM_CONST(16, uint64_t, pw_08) = UINT64_C(0x0008000800080008); * @endcode * * @param n Minimum alignment in bytes * @param t Type of the variable (or array element) * @param v Name of the variable */ #if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1110 || defined(__SUNPRO_C) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) const t __attribute__ ((aligned (n))) v #elif defined(__DJGPP__) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (FFMIN(n, 16)))) v #define DECLARE_ASM_ALIGNED(n,t,v) t av_used __attribute__ ((aligned (FFMIN(n, 16)))) v #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (FFMIN(n, 16)))) v #elif defined(__GNUC__) || defined(__clang__) #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v #define DECLARE_ASM_ALIGNED(n,t,v) t av_used __attribute__ ((aligned (n))) v #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (n))) v #elif defined(_MSC_VER) #define DECLARE_ALIGNED(n,t,v) __declspec(align(n)) t v #define DECLARE_ASM_ALIGNED(n,t,v) __declspec(align(n)) t v #define DECLARE_ASM_CONST(n,t,v) __declspec(align(n)) static const t v #else #define DECLARE_ALIGNED(n,t,v) t v #define DECLARE_ASM_ALIGNED(n,t,v) t v #define DECLARE_ASM_CONST(n,t,v) static const t v #endif /** * @} */ /** * @defgroup lavu_mem_attrs Function Attributes * Function attributes applicable to memory handling functions. * * These function attributes can help compilers emit more useful warnings, or * generate better code. * @{ */ /** * @def av_malloc_attrib * Function attribute denoting a malloc-like function. * * @see Function attribute `malloc` in GCC's documentation */ #if AV_GCC_VERSION_AT_LEAST(3,1) #define av_malloc_attrib __attribute__((__malloc__)) #else #define av_malloc_attrib #endif /** * @def av_alloc_size(...) * Function attribute used on a function that allocates memory, whose size is * given by the specified parameter(s). * * @code{.c} * void *av_malloc(size_t size) av_alloc_size(1); * void *av_calloc(size_t nmemb, size_t size) av_alloc_size(1, 2); * @endcode * * @param ... One or two parameter indexes, separated by a comma * * @see Function attribute `alloc_size` in GCC's documentation */ #if AV_GCC_VERSION_AT_LEAST(4,3) #define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__))) #else #define av_alloc_size(...) #endif /** * @} */ /** * @defgroup lavu_mem_funcs Heap Management * Functions responsible for allocating, freeing, and copying memory. * * All memory allocation functions have a built-in upper limit of `INT_MAX` * bytes. This may be changed with av_max_alloc(), although exercise extreme * caution when doing so. * * @{ */ /** * Allocate a memory block with alignment suitable for all memory accesses * (including vectors if available on the CPU). * * @param size Size in bytes for the memory block to be allocated * @return Pointer to the allocated block, or `NULL` if the block cannot * be allocated * @see av_mallocz() */ void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1); /** * Allocate a memory block with alignment suitable for all memory accesses * (including vectors if available on the CPU) and zero all the bytes of the * block. * * @param size Size in bytes for the memory block to be allocated * @return Pointer to the allocated block, or `NULL` if it cannot be allocated * @see av_malloc() */ void *av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1); /** * Allocate a memory block for an array with av_malloc(). * * The allocated memory will have size `size * nmemb` bytes. * * @param nmemb Number of element * @param size Size of a single element * @return Pointer to the allocated block, or `NULL` if the block cannot * be allocated * @see av_malloc() */ av_alloc_size(1, 2) void *av_malloc_array(size_t nmemb, size_t size); /** * Allocate a memory block for an array with av_mallocz(). * * The allocated memory will have size `size * nmemb` bytes. * * @param nmemb Number of elements * @param size Size of the single element * @return Pointer to the allocated block, or `NULL` if the block cannot * be allocated * * @see av_mallocz() * @see av_malloc_array() */ av_alloc_size(1, 2) void *av_mallocz_array(size_t nmemb, size_t size); /** * Non-inlined equivalent of av_mallocz_array(). * * Created for symmetry with the calloc() C function. */ void *av_calloc(size_t nmemb, size_t size) av_malloc_attrib; /** * Allocate, reallocate, or free a block of memory. * * If `ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is * zero, free the memory block pointed to by `ptr`. Otherwise, expand or * shrink that block of memory according to `size`. * * @param ptr Pointer to a memory block already allocated with * av_realloc() or `NULL` * @param size Size in bytes of the memory block to be allocated or * reallocated * * @return Pointer to a newly-reallocated block or `NULL` if the block * cannot be reallocated or the function is used to free the memory block * * @warning Unlike av_malloc(), the returned pointer is not guaranteed to be * correctly aligned. * @see av_fast_realloc() * @see av_reallocp() */ void *av_realloc(void *ptr, size_t size) av_alloc_size(2); /** * Allocate, reallocate, or free a block of memory through a pointer to a * pointer. * * If `*ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is * zero, free the memory block pointed to by `*ptr`. Otherwise, expand or * shrink that block of memory according to `size`. * * @param[in,out] ptr Pointer to a pointer to a memory block already allocated * with av_realloc(), or a pointer to `NULL`. The pointer * is updated on success, or freed on failure. * @param[in] size Size in bytes for the memory block to be allocated or * reallocated * * @return Zero on success, an AVERROR error code on failure * * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be * correctly aligned. */ av_warn_unused_result int av_reallocp(void *ptr, size_t size); /** * Allocate, reallocate, or free a block of memory. * * This function does the same thing as av_realloc(), except: * - It takes two size arguments and allocates `nelem * elsize` bytes, * after checking the result of the multiplication for integer overflow. * - It frees the input block in case of failure, thus avoiding the memory * leak with the classic * @code{.c} * buf = realloc(buf); * if (!buf) * return -1; * @endcode * pattern. */ void *av_realloc_f(void *ptr, size_t nelem, size_t elsize); /** * Allocate, reallocate, or free an array. * * If `ptr` is `NULL` and `nmemb` > 0, allocate a new block. If * `nmemb` is zero, free the memory block pointed to by `ptr`. * * @param ptr Pointer to a memory block already allocated with * av_realloc() or `NULL` * @param nmemb Number of elements in the array * @param size Size of the single element of the array * * @return Pointer to a newly-reallocated block or NULL if the block * cannot be reallocated or the function is used to free the memory block * * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be * correctly aligned. * @see av_reallocp_array() */ av_alloc_size(2, 3) void *av_realloc_array(void *ptr, size_t nmemb, size_t size); /** * Allocate, reallocate, or free an array through a pointer to a pointer. * * If `*ptr` is `NULL` and `nmemb` > 0, allocate a new block. If `nmemb` is * zero, free the memory block pointed to by `*ptr`. * * @param[in,out] ptr Pointer to a pointer to a memory block already * allocated with av_realloc(), or a pointer to `NULL`. * The pointer is updated on success, or freed on failure. * @param[in] nmemb Number of elements * @param[in] size Size of the single element * * @return Zero on success, an AVERROR error code on failure * * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be * correctly aligned. */ int av_reallocp_array(void *ptr, size_t nmemb, size_t size); /** * Reallocate the given buffer if it is not large enough, otherwise do nothing. * * If the given buffer is `NULL`, then a new uninitialized buffer is allocated. * * If the given buffer is not large enough, and reallocation fails, `NULL` is * returned and `*size` is set to 0, but the original buffer is not changed or * freed. * * A typical use pattern follows: * * @code{.c} * uint8_t *buf = ...; * uint8_t *new_buf = av_fast_realloc(buf, ¤t_size, size_needed); * if (!new_buf) { * // Allocation failed; clean up original buffer * av_freep(&buf); * return AVERROR(ENOMEM); * } * @endcode * * @param[in,out] ptr Already allocated buffer, or `NULL` * @param[in,out] size Pointer to the size of buffer `ptr`. `*size` is * updated to the new allocated size, in particular 0 * in case of failure. * @param[in] min_size Desired minimal size of buffer `ptr` * @return `ptr` if the buffer is large enough, a pointer to newly reallocated * buffer if the buffer was not large enough, or `NULL` in case of * error * @see av_realloc() * @see av_fast_malloc() */ void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size); /** * Allocate a buffer, reusing the given one if large enough. * * Contrary to av_fast_realloc(), the current buffer contents might not be * preserved and on error the old buffer is freed, thus no special handling to * avoid memleaks is necessary. * * `*ptr` is allowed to be `NULL`, in which case allocation always happens if * `size_needed` is greater than 0. * * @code{.c} * uint8_t *buf = ...; * av_fast_malloc(&buf, ¤t_size, size_needed); * if (!buf) { * // Allocation failed; buf already freed * return AVERROR(ENOMEM); * } * @endcode * * @param[in,out] ptr Pointer to pointer to an already allocated buffer. * `*ptr` will be overwritten with pointer to new * buffer on success or `NULL` on failure * @param[in,out] size Pointer to the size of buffer `*ptr`. `*size` is * updated to the new allocated size, in particular 0 * in case of failure. * @param[in] min_size Desired minimal size of buffer `*ptr` * @see av_realloc() * @see av_fast_mallocz() */ void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size); /** * Allocate and clear a buffer, reusing the given one if large enough. * * Like av_fast_malloc(), but all newly allocated space is initially cleared. * Reused buffer is not cleared. * * `*ptr` is allowed to be `NULL`, in which case allocation always happens if * `size_needed` is greater than 0. * * @param[in,out] ptr Pointer to pointer to an already allocated buffer. * `*ptr` will be overwritten with pointer to new * buffer on success or `NULL` on failure * @param[in,out] size Pointer to the size of buffer `*ptr`. `*size` is * updated to the new allocated size, in particular 0 * in case of failure. * @param[in] min_size Desired minimal size of buffer `*ptr` * @see av_fast_malloc() */ void av_fast_mallocz(void *ptr, unsigned int *size, size_t min_size); /** * Free a memory block which has been allocated with a function of av_malloc() * or av_realloc() family. * * @param ptr Pointer to the memory block which should be freed. * * @note `ptr = NULL` is explicitly allowed. * @note It is recommended that you use av_freep() instead, to prevent leaving * behind dangling pointers. * @see av_freep() */ void av_free(void *ptr); /** * Free a memory block which has been allocated with a function of av_malloc() * or av_realloc() family, and set the pointer pointing to it to `NULL`. * * @code{.c} * uint8_t *buf = av_malloc(16); * av_free(buf); * // buf now contains a dangling pointer to freed memory, and accidental * // dereference of buf will result in a use-after-free, which may be a * // security risk. * * uint8_t *buf = av_malloc(16); * av_freep(&buf); * // buf is now NULL, and accidental dereference will only result in a * // NULL-pointer dereference. * @endcode * * @param ptr Pointer to the pointer to the memory block which should be freed * @note `*ptr = NULL` is safe and leads to no action. * @see av_free() */ void av_freep(void *ptr); /** * Duplicate a string. * * @param s String to be duplicated * @return Pointer to a newly-allocated string containing a * copy of `s` or `NULL` if the string cannot be allocated * @see av_strndup() */ char *av_strdup(const char *s) av_malloc_attrib; /** * Duplicate a substring of a string. * * @param s String to be duplicated * @param len Maximum length of the resulting string (not counting the * terminating byte) * @return Pointer to a newly-allocated string containing a * substring of `s` or `NULL` if the string cannot be allocated */ char *av_strndup(const char *s, size_t len) av_malloc_attrib; /** * Duplicate a buffer with av_malloc(). * * @param p Buffer to be duplicated * @param size Size in bytes of the buffer copied * @return Pointer to a newly allocated buffer containing a * copy of `p` or `NULL` if the buffer cannot be allocated */ void *av_memdup(const void *p, size_t size); /** * Overlapping memcpy() implementation. * * @param dst Destination buffer * @param back Number of bytes back to start copying (i.e. the initial size of * the overlapping window); must be > 0 * @param cnt Number of bytes to copy; must be >= 0 * * @note `cnt > back` is valid, this will copy the bytes we just copied, * thus creating a repeating pattern with a period length of `back`. */ void av_memcpy_backptr(uint8_t *dst, int back, int cnt); /** * @} */ /** * @defgroup lavu_mem_dynarray Dynamic Array * * Utilities to make an array grow when needed. * * Sometimes, the programmer would want to have an array that can grow when * needed. The libavutil dynamic array utilities fill that need. * * libavutil supports two systems of appending elements onto a dynamically * allocated array, the first one storing the pointer to the value in the * array, and the second storing the value directly. In both systems, the * caller is responsible for maintaining a variable containing the length of * the array, as well as freeing of the array after use. * * The first system stores pointers to values in a block of dynamically * allocated memory. Since only pointers are stored, the function does not need * to know the size of the type. Both av_dynarray_add() and * av_dynarray_add_nofree() implement this system. * * @code * type **array = NULL; //< an array of pointers to values * int nb = 0; //< a variable to keep track of the length of the array * * type to_be_added = ...; * type to_be_added2 = ...; * * av_dynarray_add(&array, &nb, &to_be_added); * if (nb == 0) * return AVERROR(ENOMEM); * * av_dynarray_add(&array, &nb, &to_be_added2); * if (nb == 0) * return AVERROR(ENOMEM); * * // Now: * // nb == 2 * // &to_be_added == array[0] * // &to_be_added2 == array[1] * * av_freep(&array); * @endcode * * The second system stores the value directly in a block of memory. As a * result, the function has to know the size of the type. av_dynarray2_add() * implements this mechanism. * * @code * type *array = NULL; //< an array of values * int nb = 0; //< a variable to keep track of the length of the array * * type to_be_added = ...; * type to_be_added2 = ...; * * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array), NULL); * if (!addr) * return AVERROR(ENOMEM); * memcpy(addr, &to_be_added, sizeof(to_be_added)); * * // Shortcut of the above. * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array), * (const void *)&to_be_added2); * if (!addr) * return AVERROR(ENOMEM); * * // Now: * // nb == 2 * // to_be_added == array[0] * // to_be_added2 == array[1] * * av_freep(&array); * @endcode * * @{ */ /** * Add the pointer to an element to a dynamic array. * * The array to grow is supposed to be an array of pointers to * structures, and the element to add must be a pointer to an already * allocated structure. * * The array is reallocated when its size reaches powers of 2. * Therefore, the amortized cost of adding an element is constant. * * In case of success, the pointer to the array is updated in order to * point to the new grown array, and the number pointed to by `nb_ptr` * is incremented. * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and * `*nb_ptr` is set to 0. * * @param[in,out] tab_ptr Pointer to the array to grow * @param[in,out] nb_ptr Pointer to the number of elements in the array * @param[in] elem Element to add * @see av_dynarray_add_nofree(), av_dynarray2_add() */ void av_dynarray_add(void *tab_ptr, int *nb_ptr, void *elem); /** * Add an element to a dynamic array. * * Function has the same functionality as av_dynarray_add(), * but it doesn't free memory on fails. It returns error code * instead and leave current buffer untouched. * * @return >=0 on success, negative otherwise * @see av_dynarray_add(), av_dynarray2_add() */ av_warn_unused_result int av_dynarray_add_nofree(void *tab_ptr, int *nb_ptr, void *elem); /** * Add an element of size `elem_size` to a dynamic array. * * The array is reallocated when its number of elements reaches powers of 2. * Therefore, the amortized cost of adding an element is constant. * * In case of success, the pointer to the array is updated in order to * point to the new grown array, and the number pointed to by `nb_ptr` * is incremented. * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and * `*nb_ptr` is set to 0. * * @param[in,out] tab_ptr Pointer to the array to grow * @param[in,out] nb_ptr Pointer to the number of elements in the array * @param[in] elem_size Size in bytes of an element in the array * @param[in] elem_data Pointer to the data of the element to add. If * `NULL`, the space of the newly added element is * allocated but left uninitialized. * * @return Pointer to the data of the element to copy in the newly allocated * space * @see av_dynarray_add(), av_dynarray_add_nofree() */ void *av_dynarray2_add(void **tab_ptr, int *nb_ptr, size_t elem_size, const uint8_t *elem_data); /** * @} */ /** * @defgroup lavu_mem_misc Miscellaneous Functions * * Other functions related to memory allocation. * * @{ */ /** * Multiply two `size_t` values checking for overflow. * * @param[in] a,b Operands of multiplication * @param[out] r Pointer to the result of the operation * @return 0 on success, AVERROR(EINVAL) on overflow */ static inline int av_size_mult(size_t a, size_t b, size_t *r) { size_t t = a * b; /* Hack inspired from glibc: don't try the division if nelem and elsize * are both less than sqrt(SIZE_MAX). */ if ((a | b) >= ((size_t)1 << (sizeof(size_t) * 4)) && a && t / a != b) return AVERROR(EINVAL); *r = t; return 0; } /** * Set the maximum size that may be allocated in one block. * * The value specified with this function is effective for all libavutil's @ref * lavu_mem_funcs "heap management functions." * * By default, the max value is defined as `INT_MAX`. * * @param max Value to be set as the new maximum size * * @warning Exercise extreme caution when using this function. Don't touch * this if you do not understand the full consequence of doing so. */ void av_max_alloc(size_t max); /** * @} * @} */ #endif /* AVUTIL_MEM_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/motion_vector.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_MOTION_VECTOR_H #define AVUTIL_MOTION_VECTOR_H #include typedef struct AVMotionVector { /** * Where the current macroblock comes from; negative value when it comes * from the past, positive value when it comes from the future. * XXX: set exact relative ref frame reference instead of a +/- 1 "direction". */ int32_t source; /** * Width and height of the block. */ uint8_t w, h; /** * Absolute source position. Can be outside the frame area. */ int16_t src_x, src_y; /** * Absolute destination position. Can be outside the frame area. */ int16_t dst_x, dst_y; /** * Extra flag information. * Currently unused. */ uint64_t flags; /** * Motion vector * src_x = dst_x + motion_x / motion_scale * src_y = dst_y + motion_y / motion_scale */ int32_t motion_x, motion_y; uint16_t motion_scale; } AVMotionVector; #endif /* AVUTIL_MOTION_VECTOR_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/murmur3.h ================================================ /* * Copyright (C) 2013 Reimar Döffinger * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_murmur3 * Public header for MurmurHash3 hash function implementation. */ #ifndef AVUTIL_MURMUR3_H #define AVUTIL_MURMUR3_H #include #include "version.h" /** * @defgroup lavu_murmur3 Murmur3 * @ingroup lavu_hash * MurmurHash3 hash function implementation. * * MurmurHash3 is a non-cryptographic hash function, of which three * incompatible versions were created by its inventor Austin Appleby: * * - 32-bit output * - 128-bit output for 32-bit platforms * - 128-bit output for 64-bit platforms * * FFmpeg only implements the last variant: 128-bit output designed for 64-bit * platforms. Even though the hash function was designed for 64-bit platforms, * the function in reality works on 32-bit systems too, only with reduced * performance. * * @anchor lavu_murmur3_seedinfo * By design, MurmurHash3 requires a seed to operate. In response to this, * libavutil provides two functions for hash initiation, one that requires a * seed (av_murmur3_init_seeded()) and one that uses a fixed arbitrary integer * as the seed, and therefore does not (av_murmur3_init()). * * To make hashes comparable, you should provide the same seed for all calls to * this hash function -- if you are supplying one yourself, that is. * * @{ */ /** * Allocate an AVMurMur3 hash context. * * @return Uninitialized hash context or `NULL` in case of error */ struct AVMurMur3 *av_murmur3_alloc(void); /** * Initialize or reinitialize an AVMurMur3 hash context with a seed. * * @param[out] c Hash context * @param[in] seed Random seed * * @see av_murmur3_init() * @see @ref lavu_murmur3_seedinfo "Detailed description" on a discussion of * seeds for MurmurHash3. */ void av_murmur3_init_seeded(struct AVMurMur3 *c, uint64_t seed); /** * Initialize or reinitialize an AVMurMur3 hash context. * * Equivalent to av_murmur3_init_seeded() with a built-in seed. * * @param[out] c Hash context * * @see av_murmur3_init_seeded() * @see @ref lavu_murmur3_seedinfo "Detailed description" on a discussion of * seeds for MurmurHash3. */ void av_murmur3_init(struct AVMurMur3 *c); /** * Update hash context with new data. * * @param[out] c Hash context * @param[in] src Input data to update hash with * @param[in] len Number of bytes to read from `src` */ #if FF_API_CRYPTO_SIZE_T void av_murmur3_update(struct AVMurMur3 *c, const uint8_t *src, int len); #else void av_murmur3_update(struct AVMurMur3 *c, const uint8_t *src, size_t len); #endif /** * Finish hashing and output digest value. * * @param[in,out] c Hash context * @param[out] dst Buffer where output digest value is stored */ void av_murmur3_final(struct AVMurMur3 *c, uint8_t dst[16]); /** * @} */ #endif /* AVUTIL_MURMUR3_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/opt.h ================================================ /* * AVOptions * copyright (c) 2005 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_OPT_H #define AVUTIL_OPT_H /** * @file * AVOptions */ #include "rational.h" #include "avutil.h" #include "dict.h" #include "log.h" #include "pixfmt.h" #include "samplefmt.h" #include "version.h" /** * @defgroup avoptions AVOptions * @ingroup lavu_data * @{ * AVOptions provide a generic system to declare options on arbitrary structs * ("objects"). An option can have a help text, a type and a range of possible * values. Options may then be enumerated, read and written to. * * @section avoptions_implement Implementing AVOptions * This section describes how to add AVOptions capabilities to a struct. * * All AVOptions-related information is stored in an AVClass. Therefore * the first member of the struct should be a pointer to an AVClass describing it. * The option field of the AVClass must be set to a NULL-terminated static array * of AVOptions. Each AVOption must have a non-empty name, a type, a default * value and for number-type AVOptions also a range of allowed values. It must * also declare an offset in bytes from the start of the struct, where the field * associated with this AVOption is located. Other fields in the AVOption struct * should also be set when applicable, but are not required. * * The following example illustrates an AVOptions-enabled struct: * @code * typedef struct test_struct { * const AVClass *class; * int int_opt; * char *str_opt; * uint8_t *bin_opt; * int bin_len; * } test_struct; * * static const AVOption test_options[] = { * { "test_int", "This is a test option of int type.", offsetof(test_struct, int_opt), * AV_OPT_TYPE_INT, { .i64 = -1 }, INT_MIN, INT_MAX }, * { "test_str", "This is a test option of string type.", offsetof(test_struct, str_opt), * AV_OPT_TYPE_STRING }, * { "test_bin", "This is a test option of binary type.", offsetof(test_struct, bin_opt), * AV_OPT_TYPE_BINARY }, * { NULL }, * }; * * static const AVClass test_class = { * .class_name = "test class", * .item_name = av_default_item_name, * .option = test_options, * .version = LIBAVUTIL_VERSION_INT, * }; * @endcode * * Next, when allocating your struct, you must ensure that the AVClass pointer * is set to the correct value. Then, av_opt_set_defaults() can be called to * initialize defaults. After that the struct is ready to be used with the * AVOptions API. * * When cleaning up, you may use the av_opt_free() function to automatically * free all the allocated string and binary options. * * Continuing with the above example: * * @code * test_struct *alloc_test_struct(void) * { * test_struct *ret = av_mallocz(sizeof(*ret)); * ret->class = &test_class; * av_opt_set_defaults(ret); * return ret; * } * void free_test_struct(test_struct **foo) * { * av_opt_free(*foo); * av_freep(foo); * } * @endcode * * @subsection avoptions_implement_nesting Nesting * It may happen that an AVOptions-enabled struct contains another * AVOptions-enabled struct as a member (e.g. AVCodecContext in * libavcodec exports generic options, while its priv_data field exports * codec-specific options). In such a case, it is possible to set up the * parent struct to export a child's options. To do that, simply * implement AVClass.child_next() and AVClass.child_class_next() in the * parent struct's AVClass. * Assuming that the test_struct from above now also contains a * child_struct field: * * @code * typedef struct child_struct { * AVClass *class; * int flags_opt; * } child_struct; * static const AVOption child_opts[] = { * { "test_flags", "This is a test option of flags type.", * offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX }, * { NULL }, * }; * static const AVClass child_class = { * .class_name = "child class", * .item_name = av_default_item_name, * .option = child_opts, * .version = LIBAVUTIL_VERSION_INT, * }; * * void *child_next(void *obj, void *prev) * { * test_struct *t = obj; * if (!prev && t->child_struct) * return t->child_struct; * return NULL * } * const AVClass child_class_next(const AVClass *prev) * { * return prev ? NULL : &child_class; * } * @endcode * Putting child_next() and child_class_next() as defined above into * test_class will now make child_struct's options accessible through * test_struct (again, proper setup as described above needs to be done on * child_struct right after it is created). * * From the above example it might not be clear why both child_next() * and child_class_next() are needed. The distinction is that child_next() * iterates over actually existing objects, while child_class_next() * iterates over all possible child classes. E.g. if an AVCodecContext * was initialized to use a codec which has private options, then its * child_next() will return AVCodecContext.priv_data and finish * iterating. OTOH child_class_next() on AVCodecContext.av_class will * iterate over all available codecs with private options. * * @subsection avoptions_implement_named_constants Named constants * It is possible to create named constants for options. Simply set the unit * field of the option the constants should apply to a string and * create the constants themselves as options of type AV_OPT_TYPE_CONST * with their unit field set to the same string. * Their default_val field should contain the value of the named * constant. * For example, to add some named constants for the test_flags option * above, put the following into the child_opts array: * @code * { "test_flags", "This is a test option of flags type.", * offsetof(child_struct, flags_opt), AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT_MIN, INT_MAX, "test_unit" }, * { "flag1", "This is a flag with value 16", 0, AV_OPT_TYPE_CONST, { .i64 = 16 }, 0, 0, "test_unit" }, * @endcode * * @section avoptions_use Using AVOptions * This section deals with accessing options in an AVOptions-enabled struct. * Such structs in FFmpeg are e.g. AVCodecContext in libavcodec or * AVFormatContext in libavformat. * * @subsection avoptions_use_examine Examining AVOptions * The basic functions for examining options are av_opt_next(), which iterates * over all options defined for one object, and av_opt_find(), which searches * for an option with the given name. * * The situation is more complicated with nesting. An AVOptions-enabled struct * may have AVOptions-enabled children. Passing the AV_OPT_SEARCH_CHILDREN flag * to av_opt_find() will make the function search children recursively. * * For enumerating there are basically two cases. The first is when you want to * get all options that may potentially exist on the struct and its children * (e.g. when constructing documentation). In that case you should call * av_opt_child_class_next() recursively on the parent struct's AVClass. The * second case is when you have an already initialized struct with all its * children and you want to get all options that can be actually written or read * from it. In that case you should call av_opt_child_next() recursively (and * av_opt_next() on each result). * * @subsection avoptions_use_get_set Reading and writing AVOptions * When setting options, you often have a string read directly from the * user. In such a case, simply passing it to av_opt_set() is enough. For * non-string type options, av_opt_set() will parse the string according to the * option type. * * Similarly av_opt_get() will read any option type and convert it to a string * which will be returned. Do not forget that the string is allocated, so you * have to free it with av_free(). * * In some cases it may be more convenient to put all options into an * AVDictionary and call av_opt_set_dict() on it. A specific case of this * are the format/codec open functions in lavf/lavc which take a dictionary * filled with option as a parameter. This makes it possible to set some options * that cannot be set otherwise, since e.g. the input file format is not known * before the file is actually opened. */ enum AVOptionType{ AV_OPT_TYPE_FLAGS, AV_OPT_TYPE_INT, AV_OPT_TYPE_INT64, AV_OPT_TYPE_DOUBLE, AV_OPT_TYPE_FLOAT, AV_OPT_TYPE_STRING, AV_OPT_TYPE_RATIONAL, AV_OPT_TYPE_BINARY, ///< offset must point to a pointer immediately followed by an int for the length AV_OPT_TYPE_DICT, AV_OPT_TYPE_UINT64, AV_OPT_TYPE_CONST, AV_OPT_TYPE_IMAGE_SIZE, ///< offset must point to two consecutive integers AV_OPT_TYPE_PIXEL_FMT, AV_OPT_TYPE_SAMPLE_FMT, AV_OPT_TYPE_VIDEO_RATE, ///< offset must point to AVRational AV_OPT_TYPE_DURATION, AV_OPT_TYPE_COLOR, AV_OPT_TYPE_CHANNEL_LAYOUT, AV_OPT_TYPE_BOOL, }; /** * AVOption */ typedef struct AVOption { const char *name; /** * short English help text * @todo What about other languages? */ const char *help; /** * The offset relative to the context structure where the option * value is stored. It should be 0 for named constants. */ int offset; enum AVOptionType type; /** * the default value for scalar options */ union { int64_t i64; double dbl; const char *str; /* TODO those are unused now */ AVRational q; } default_val; double min; ///< minimum valid value for the option double max; ///< maximum valid value for the option int flags; #define AV_OPT_FLAG_ENCODING_PARAM 1 ///< a generic parameter which can be set by the user for muxing or encoding #define AV_OPT_FLAG_DECODING_PARAM 2 ///< a generic parameter which can be set by the user for demuxing or decoding #define AV_OPT_FLAG_AUDIO_PARAM 8 #define AV_OPT_FLAG_VIDEO_PARAM 16 #define AV_OPT_FLAG_SUBTITLE_PARAM 32 /** * The option is intended for exporting values to the caller. */ #define AV_OPT_FLAG_EXPORT 64 /** * The option may not be set through the AVOptions API, only read. * This flag only makes sense when AV_OPT_FLAG_EXPORT is also set. */ #define AV_OPT_FLAG_READONLY 128 #define AV_OPT_FLAG_BSF_PARAM (1<<8) ///< a generic parameter which can be set by the user for bit stream filtering #define AV_OPT_FLAG_FILTERING_PARAM (1<<16) ///< a generic parameter which can be set by the user for filtering #define AV_OPT_FLAG_DEPRECATED (1<<17) ///< set if option is deprecated, users should refer to AVOption.help text for more information //FIXME think about enc-audio, ... style flags /** * The logical unit to which the option belongs. Non-constant * options and corresponding named constants share the same * unit. May be NULL. */ const char *unit; } AVOption; /** * A single allowed range of values, or a single allowed value. */ typedef struct AVOptionRange { const char *str; /** * Value range. * For string ranges this represents the min/max length. * For dimensions this represents the min/max pixel count or width/height in multi-component case. */ double value_min, value_max; /** * Value's component range. * For string this represents the unicode range for chars, 0-127 limits to ASCII. */ double component_min, component_max; /** * Range flag. * If set to 1 the struct encodes a range, if set to 0 a single value. */ int is_range; } AVOptionRange; /** * List of AVOptionRange structs. */ typedef struct AVOptionRanges { /** * Array of option ranges. * * Most of option types use just one component. * Following describes multi-component option types: * * AV_OPT_TYPE_IMAGE_SIZE: * component index 0: range of pixel count (width * height). * component index 1: range of width. * component index 2: range of height. * * @note To obtain multi-component version of this structure, user must * provide AV_OPT_MULTI_COMPONENT_RANGE to av_opt_query_ranges or * av_opt_query_ranges_default function. * * Multi-component range can be read as in following example: * * @code * int range_index, component_index; * AVOptionRanges *ranges; * AVOptionRange *range[3]; //may require more than 3 in the future. * av_opt_query_ranges(&ranges, obj, key, AV_OPT_MULTI_COMPONENT_RANGE); * for (range_index = 0; range_index < ranges->nb_ranges; range_index++) { * for (component_index = 0; component_index < ranges->nb_components; component_index++) * range[component_index] = ranges->range[ranges->nb_ranges * component_index + range_index]; * //do something with range here. * } * av_opt_freep_ranges(&ranges); * @endcode */ AVOptionRange **range; /** * Number of ranges per component. */ int nb_ranges; /** * Number of componentes. */ int nb_components; } AVOptionRanges; /** * Show the obj options. * * @param req_flags requested flags for the options to show. Show only the * options for which it is opt->flags & req_flags. * @param rej_flags rejected flags for the options to show. Show only the * options for which it is !(opt->flags & req_flags). * @param av_log_obj log context to use for showing the options */ int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags); /** * Set the values of all AVOption fields to their default values. * * @param s an AVOption-enabled struct (its first member must be a pointer to AVClass) */ void av_opt_set_defaults(void *s); /** * Set the values of all AVOption fields to their default values. Only these * AVOption fields for which (opt->flags & mask) == flags will have their * default applied to s. * * @param s an AVOption-enabled struct (its first member must be a pointer to AVClass) * @param mask combination of AV_OPT_FLAG_* * @param flags combination of AV_OPT_FLAG_* */ void av_opt_set_defaults2(void *s, int mask, int flags); /** * Parse the key/value pairs list in opts. For each key/value pair * found, stores the value in the field in ctx that is named like the * key. ctx must be an AVClass context, storing is done using * AVOptions. * * @param opts options string to parse, may be NULL * @param key_val_sep a 0-terminated list of characters used to * separate key from value * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other * @return the number of successfully set key/value pairs, or a negative * value corresponding to an AVERROR code in case of error: * AVERROR(EINVAL) if opts cannot be parsed, * the error code issued by av_opt_set() if a key/value pair * cannot be set */ int av_set_options_string(void *ctx, const char *opts, const char *key_val_sep, const char *pairs_sep); /** * Parse the key-value pairs list in opts. For each key=value pair found, * set the value of the corresponding option in ctx. * * @param ctx the AVClass object to set options on * @param opts the options string, key-value pairs separated by a * delimiter * @param shorthand a NULL-terminated array of options names for shorthand * notation: if the first field in opts has no key part, * the key is taken from the first element of shorthand; * then again for the second, etc., until either opts is * finished, shorthand is finished or a named option is * found; after that, all options must be named * @param key_val_sep a 0-terminated list of characters used to separate * key from value, for example '=' * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other, for example ':' or ',' * @return the number of successfully set key=value pairs, or a negative * value corresponding to an AVERROR code in case of error: * AVERROR(EINVAL) if opts cannot be parsed, * the error code issued by av_set_string3() if a key/value pair * cannot be set * * Options names must use only the following characters: a-z A-Z 0-9 - . / _ * Separators must use characters distinct from option names and from each * other. */ int av_opt_set_from_string(void *ctx, const char *opts, const char *const *shorthand, const char *key_val_sep, const char *pairs_sep); /** * Free all allocated objects in obj. */ void av_opt_free(void *obj); /** * Check whether a particular flag is set in a flags field. * * @param field_name the name of the flag field option * @param flag_name the name of the flag to check * @return non-zero if the flag is set, zero if the flag isn't set, * isn't of the right type, or the flags field doesn't exist. */ int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name); /** * Set all the options from a given dictionary on an object. * * @param obj a struct whose first element is a pointer to AVClass * @param options options to process. This dictionary will be freed and replaced * by a new one containing all options not found in obj. * Of course this new dictionary needs to be freed by caller * with av_dict_free(). * * @return 0 on success, a negative AVERROR if some option was found in obj, * but could not be set. * * @see av_dict_copy() */ int av_opt_set_dict(void *obj, struct AVDictionary **options); /** * Set all the options from a given dictionary on an object. * * @param obj a struct whose first element is a pointer to AVClass * @param options options to process. This dictionary will be freed and replaced * by a new one containing all options not found in obj. * Of course this new dictionary needs to be freed by caller * with av_dict_free(). * @param search_flags A combination of AV_OPT_SEARCH_*. * * @return 0 on success, a negative AVERROR if some option was found in obj, * but could not be set. * * @see av_dict_copy() */ int av_opt_set_dict2(void *obj, struct AVDictionary **options, int search_flags); /** * Extract a key-value pair from the beginning of a string. * * @param ropts pointer to the options string, will be updated to * point to the rest of the string (one of the pairs_sep * or the final NUL) * @param key_val_sep a 0-terminated list of characters used to separate * key from value, for example '=' * @param pairs_sep a 0-terminated list of characters used to separate * two pairs from each other, for example ':' or ',' * @param flags flags; see the AV_OPT_FLAG_* values below * @param rkey parsed key; must be freed using av_free() * @param rval parsed value; must be freed using av_free() * * @return >=0 for success, or a negative value corresponding to an * AVERROR code in case of error; in particular: * AVERROR(EINVAL) if no key is present * */ int av_opt_get_key_value(const char **ropts, const char *key_val_sep, const char *pairs_sep, unsigned flags, char **rkey, char **rval); enum { /** * Accept to parse a value without a key; the key will then be returned * as NULL. */ AV_OPT_FLAG_IMPLICIT_KEY = 1, }; /** * @defgroup opt_eval_funcs Evaluating option strings * @{ * This group of functions can be used to evaluate option strings * and get numbers out of them. They do the same thing as av_opt_set(), * except the result is written into the caller-supplied pointer. * * @param obj a struct whose first element is a pointer to AVClass. * @param o an option for which the string is to be evaluated. * @param val string to be evaluated. * @param *_out value of the string will be written here. * * @return 0 on success, a negative number on failure. */ int av_opt_eval_flags (void *obj, const AVOption *o, const char *val, int *flags_out); int av_opt_eval_int (void *obj, const AVOption *o, const char *val, int *int_out); int av_opt_eval_int64 (void *obj, const AVOption *o, const char *val, int64_t *int64_out); int av_opt_eval_float (void *obj, const AVOption *o, const char *val, float *float_out); int av_opt_eval_double(void *obj, const AVOption *o, const char *val, double *double_out); int av_opt_eval_q (void *obj, const AVOption *o, const char *val, AVRational *q_out); /** * @} */ #define AV_OPT_SEARCH_CHILDREN (1 << 0) /**< Search in possible children of the given object first. */ /** * The obj passed to av_opt_find() is fake -- only a double pointer to AVClass * instead of a required pointer to a struct containing AVClass. This is * useful for searching for options without needing to allocate the corresponding * object. */ #define AV_OPT_SEARCH_FAKE_OBJ (1 << 1) /** * In av_opt_get, return NULL if the option has a pointer type and is set to NULL, * rather than returning an empty string. */ #define AV_OPT_ALLOW_NULL (1 << 2) /** * Allows av_opt_query_ranges and av_opt_query_ranges_default to return more than * one component for certain option types. * @see AVOptionRanges for details. */ #define AV_OPT_MULTI_COMPONENT_RANGE (1 << 12) /** * Look for an option in an object. Consider only options which * have all the specified flags set. * * @param[in] obj A pointer to a struct whose first element is a * pointer to an AVClass. * Alternatively a double pointer to an AVClass, if * AV_OPT_SEARCH_FAKE_OBJ search flag is set. * @param[in] name The name of the option to look for. * @param[in] unit When searching for named constants, name of the unit * it belongs to. * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG). * @param search_flags A combination of AV_OPT_SEARCH_*. * * @return A pointer to the option found, or NULL if no option * was found. * * @note Options found with AV_OPT_SEARCH_CHILDREN flag may not be settable * directly with av_opt_set(). Use special calls which take an options * AVDictionary (e.g. avformat_open_input()) to set options found with this * flag. */ const AVOption *av_opt_find(void *obj, const char *name, const char *unit, int opt_flags, int search_flags); /** * Look for an option in an object. Consider only options which * have all the specified flags set. * * @param[in] obj A pointer to a struct whose first element is a * pointer to an AVClass. * Alternatively a double pointer to an AVClass, if * AV_OPT_SEARCH_FAKE_OBJ search flag is set. * @param[in] name The name of the option to look for. * @param[in] unit When searching for named constants, name of the unit * it belongs to. * @param opt_flags Find only options with all the specified flags set (AV_OPT_FLAG). * @param search_flags A combination of AV_OPT_SEARCH_*. * @param[out] target_obj if non-NULL, an object to which the option belongs will be * written here. It may be different from obj if AV_OPT_SEARCH_CHILDREN is present * in search_flags. This parameter is ignored if search_flags contain * AV_OPT_SEARCH_FAKE_OBJ. * * @return A pointer to the option found, or NULL if no option * was found. */ const AVOption *av_opt_find2(void *obj, const char *name, const char *unit, int opt_flags, int search_flags, void **target_obj); /** * Iterate over all AVOptions belonging to obj. * * @param obj an AVOptions-enabled struct or a double pointer to an * AVClass describing it. * @param prev result of the previous call to av_opt_next() on this object * or NULL * @return next AVOption or NULL */ const AVOption *av_opt_next(const void *obj, const AVOption *prev); /** * Iterate over AVOptions-enabled children of obj. * * @param prev result of a previous call to this function or NULL * @return next AVOptions-enabled child or NULL */ void *av_opt_child_next(void *obj, void *prev); /** * Iterate over potential AVOptions-enabled children of parent. * * @param prev result of a previous call to this function or NULL * @return AVClass corresponding to next potential child or NULL */ const AVClass *av_opt_child_class_next(const AVClass *parent, const AVClass *prev); /** * @defgroup opt_set_funcs Option setting functions * @{ * Those functions set the field of obj with the given name to value. * * @param[in] obj A struct whose first element is a pointer to an AVClass. * @param[in] name the name of the field to set * @param[in] val The value to set. In case of av_opt_set() if the field is not * of a string type, then the given string is parsed. * SI postfixes and some named scalars are supported. * If the field is of a numeric type, it has to be a numeric or named * scalar. Behavior with more than one scalar and +- infix operators * is undefined. * If the field is of a flags type, it has to be a sequence of numeric * scalars or named flags separated by '+' or '-'. Prefixing a flag * with '+' causes it to be set without affecting the other flags; * similarly, '-' unsets a flag. * @param search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN * is passed here, then the option may be set on a child of obj. * * @return 0 if the value has been set, or an AVERROR code in case of * error: * AVERROR_OPTION_NOT_FOUND if no matching option exists * AVERROR(ERANGE) if the value is out of range * AVERROR(EINVAL) if the value is not valid */ int av_opt_set (void *obj, const char *name, const char *val, int search_flags); int av_opt_set_int (void *obj, const char *name, int64_t val, int search_flags); int av_opt_set_double (void *obj, const char *name, double val, int search_flags); int av_opt_set_q (void *obj, const char *name, AVRational val, int search_flags); int av_opt_set_bin (void *obj, const char *name, const uint8_t *val, int size, int search_flags); int av_opt_set_image_size(void *obj, const char *name, int w, int h, int search_flags); int av_opt_set_pixel_fmt (void *obj, const char *name, enum AVPixelFormat fmt, int search_flags); int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags); int av_opt_set_video_rate(void *obj, const char *name, AVRational val, int search_flags); int av_opt_set_channel_layout(void *obj, const char *name, int64_t ch_layout, int search_flags); /** * @note Any old dictionary present is discarded and replaced with a copy of the new one. The * caller still owns val is and responsible for freeing it. */ int av_opt_set_dict_val(void *obj, const char *name, const AVDictionary *val, int search_flags); /** * Set a binary option to an integer list. * * @param obj AVClass object to set options on * @param name name of the binary option * @param val pointer to an integer list (must have the correct type with * regard to the contents of the list) * @param term list terminator (usually 0 or -1) * @param flags search flags */ #define av_opt_set_int_list(obj, name, val, term, flags) \ (av_int_list_length(val, term) > INT_MAX / sizeof(*(val)) ? \ AVERROR(EINVAL) : \ av_opt_set_bin(obj, name, (const uint8_t *)(val), \ av_int_list_length(val, term) * sizeof(*(val)), flags)) /** * @} */ /** * @defgroup opt_get_funcs Option getting functions * @{ * Those functions get a value of the option with the given name from an object. * * @param[in] obj a struct whose first element is a pointer to an AVClass. * @param[in] name name of the option to get. * @param[in] search_flags flags passed to av_opt_find2. I.e. if AV_OPT_SEARCH_CHILDREN * is passed here, then the option may be found in a child of obj. * @param[out] out_val value of the option will be written here * @return >=0 on success, a negative error code otherwise */ /** * @note the returned string will be av_malloc()ed and must be av_free()ed by the caller * * @note if AV_OPT_ALLOW_NULL is set in search_flags in av_opt_get, and the option has * AV_OPT_TYPE_STRING or AV_OPT_TYPE_BINARY and is set to NULL, *out_val will be set * to NULL instead of an allocated empty string. */ int av_opt_get (void *obj, const char *name, int search_flags, uint8_t **out_val); int av_opt_get_int (void *obj, const char *name, int search_flags, int64_t *out_val); int av_opt_get_double (void *obj, const char *name, int search_flags, double *out_val); int av_opt_get_q (void *obj, const char *name, int search_flags, AVRational *out_val); int av_opt_get_image_size(void *obj, const char *name, int search_flags, int *w_out, int *h_out); int av_opt_get_pixel_fmt (void *obj, const char *name, int search_flags, enum AVPixelFormat *out_fmt); int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt); int av_opt_get_video_rate(void *obj, const char *name, int search_flags, AVRational *out_val); int av_opt_get_channel_layout(void *obj, const char *name, int search_flags, int64_t *ch_layout); /** * @param[out] out_val The returned dictionary is a copy of the actual value and must * be freed with av_dict_free() by the caller */ int av_opt_get_dict_val(void *obj, const char *name, int search_flags, AVDictionary **out_val); /** * @} */ /** * Gets a pointer to the requested field in a struct. * This function allows accessing a struct even when its fields are moved or * renamed since the application making the access has been compiled, * * @returns a pointer to the field, it can be cast to the correct type and read * or written to. */ void *av_opt_ptr(const AVClass *avclass, void *obj, const char *name); /** * Free an AVOptionRanges struct and set it to NULL. */ void av_opt_freep_ranges(AVOptionRanges **ranges); /** * Get a list of allowed ranges for the given option. * * The returned list may depend on other fields in obj like for example profile. * * @param flags is a bitmask of flags, undefined flags should not be set and should be ignored * AV_OPT_SEARCH_FAKE_OBJ indicates that the obj is a double pointer to a AVClass instead of a full instance * AV_OPT_MULTI_COMPONENT_RANGE indicates that function may return more than one component, @see AVOptionRanges * * The result must be freed with av_opt_freep_ranges. * * @return number of compontents returned on success, a negative errro code otherwise */ int av_opt_query_ranges(AVOptionRanges **, void *obj, const char *key, int flags); /** * Copy options from src object into dest object. * * Options that require memory allocation (e.g. string or binary) are malloc'ed in dest object. * Original memory allocated for such options is freed unless both src and dest options points to the same memory. * * @param dest Object to copy from * @param src Object to copy into * @return 0 on success, negative on error */ int av_opt_copy(void *dest, const void *src); /** * Get a default list of allowed ranges for the given option. * * This list is constructed without using the AVClass.query_ranges() callback * and can be used as fallback from within the callback. * * @param flags is a bitmask of flags, undefined flags should not be set and should be ignored * AV_OPT_SEARCH_FAKE_OBJ indicates that the obj is a double pointer to a AVClass instead of a full instance * AV_OPT_MULTI_COMPONENT_RANGE indicates that function may return more than one component, @see AVOptionRanges * * The result must be freed with av_opt_free_ranges. * * @return number of compontents returned on success, a negative errro code otherwise */ int av_opt_query_ranges_default(AVOptionRanges **, void *obj, const char *key, int flags); /** * Check if given option is set to its default value. * * Options o must belong to the obj. This function must not be called to check child's options state. * @see av_opt_is_set_to_default_by_name(). * * @param obj AVClass object to check option on * @param o option to be checked * @return >0 when option is set to its default, * 0 when option is not set its default, * <0 on error */ int av_opt_is_set_to_default(void *obj, const AVOption *o); /** * Check if given option is set to its default value. * * @param obj AVClass object to check option on * @param name option name * @param search_flags combination of AV_OPT_SEARCH_* * @return >0 when option is set to its default, * 0 when option is not set its default, * <0 on error */ int av_opt_is_set_to_default_by_name(void *obj, const char *name, int search_flags); #define AV_OPT_SERIALIZE_SKIP_DEFAULTS 0x00000001 ///< Serialize options that are not set to default values only. #define AV_OPT_SERIALIZE_OPT_FLAGS_EXACT 0x00000002 ///< Serialize options that exactly match opt_flags only. /** * Serialize object's options. * * Create a string containing object's serialized options. * Such string may be passed back to av_opt_set_from_string() in order to restore option values. * A key/value or pairs separator occurring in the serialized value or * name string are escaped through the av_escape() function. * * @param[in] obj AVClass object to serialize * @param[in] opt_flags serialize options with all the specified flags set (AV_OPT_FLAG) * @param[in] flags combination of AV_OPT_SERIALIZE_* flags * @param[out] buffer Pointer to buffer that will be allocated with string containg serialized options. * Buffer must be freed by the caller when is no longer needed. * @param[in] key_val_sep character used to separate key from value * @param[in] pairs_sep character used to separate two pairs from each other * @return >= 0 on success, negative on error * @warning Separators cannot be neither '\\' nor '\0'. They also cannot be the same. */ int av_opt_serialize(void *obj, int opt_flags, int flags, char **buffer, const char key_val_sep, const char pairs_sep); /** * @} */ #endif /* AVUTIL_OPT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/parseutils.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PARSEUTILS_H #define AVUTIL_PARSEUTILS_H #include #include "rational.h" /** * @file * misc parsing utilities */ /** * Parse str and store the parsed ratio in q. * * Note that a ratio with infinite (1/0) or negative value is * considered valid, so you should check on the returned value if you * want to exclude those values. * * The undefined value can be expressed using the "0:0" string. * * @param[in,out] q pointer to the AVRational which will contain the ratio * @param[in] str the string to parse: it has to be a string in the format * num:den, a float number or an expression * @param[in] max the maximum allowed numerator and denominator * @param[in] log_offset log level offset which is applied to the log * level of log_ctx * @param[in] log_ctx parent logging context * @return >= 0 on success, a negative error code otherwise */ int av_parse_ratio(AVRational *q, const char *str, int max, int log_offset, void *log_ctx); #define av_parse_ratio_quiet(rate, str, max) \ av_parse_ratio(rate, str, max, AV_LOG_MAX_OFFSET, NULL) /** * Parse str and put in width_ptr and height_ptr the detected values. * * @param[in,out] width_ptr pointer to the variable which will contain the detected * width value * @param[in,out] height_ptr pointer to the variable which will contain the detected * height value * @param[in] str the string to parse: it has to be a string in the format * width x height or a valid video size abbreviation. * @return >= 0 on success, a negative error code otherwise */ int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str); /** * Parse str and store the detected values in *rate. * * @param[in,out] rate pointer to the AVRational which will contain the detected * frame rate * @param[in] str the string to parse: it has to be a string in the format * rate_num / rate_den, a float number or a valid video rate abbreviation * @return >= 0 on success, a negative error code otherwise */ int av_parse_video_rate(AVRational *rate, const char *str); /** * Put the RGBA values that correspond to color_string in rgba_color. * * @param color_string a string specifying a color. It can be the name of * a color (case insensitive match) or a [0x|#]RRGGBB[AA] sequence, * possibly followed by "@" and a string representing the alpha * component. * The alpha component may be a string composed by "0x" followed by an * hexadecimal number or a decimal number between 0.0 and 1.0, which * represents the opacity value (0x00/0.0 means completely transparent, * 0xff/1.0 completely opaque). * If the alpha component is not specified then 0xff is assumed. * The string "random" will result in a random color. * @param slen length of the initial part of color_string containing the * color. It can be set to -1 if color_string is a null terminated string * containing nothing else than the color. * @return >= 0 in case of success, a negative value in case of * failure (for example if color_string cannot be parsed). */ int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen, void *log_ctx); /** * Get the name of a color from the internal table of hard-coded named * colors. * * This function is meant to enumerate the color names recognized by * av_parse_color(). * * @param color_idx index of the requested color, starting from 0 * @param rgbp if not NULL, will point to a 3-elements array with the color value in RGB * @return the color name string or NULL if color_idx is not in the array */ const char *av_get_known_color_name(int color_idx, const uint8_t **rgb); /** * Parse timestr and return in *time a corresponding number of * microseconds. * * @param timeval puts here the number of microseconds corresponding * to the string in timestr. If the string represents a duration, it * is the number of microseconds contained in the time interval. If * the string is a date, is the number of microseconds since 1st of * January, 1970 up to the time of the parsed date. If timestr cannot * be successfully parsed, set *time to INT64_MIN. * @param timestr a string representing a date or a duration. * - If a date the syntax is: * @code * [{YYYY-MM-DD|YYYYMMDD}[T|t| ]]{{HH:MM:SS[.m...]]]}|{HHMMSS[.m...]]]}}[Z] * now * @endcode * If the value is "now" it takes the current time. * Time is local time unless Z is appended, in which case it is * interpreted as UTC. * If the year-month-day part is not specified it takes the current * year-month-day. * - If a duration the syntax is: * @code * [-][HH:]MM:SS[.m...] * [-]S+[.m...] * @endcode * @param duration flag which tells how to interpret timestr, if not * zero timestr is interpreted as a duration, otherwise as a date * @return >= 0 in case of success, a negative value corresponding to an * AVERROR code otherwise */ int av_parse_time(int64_t *timeval, const char *timestr, int duration); /** * Attempt to find a specific tag in a URL. * * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. * Return 1 if found. */ int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info); /** * Simplified version of strptime * * Parse the input string p according to the format string fmt and * store its results in the structure dt. * This implementation supports only a subset of the formats supported * by the standard strptime(). * * The supported input field descriptors are listed below. * - %H: the hour as a decimal number, using a 24-hour clock, in the * range '00' through '23' * - %J: hours as a decimal number, in the range '0' through INT_MAX * - %M: the minute as a decimal number, using a 24-hour clock, in the * range '00' through '59' * - %S: the second as a decimal number, using a 24-hour clock, in the * range '00' through '59' * - %Y: the year as a decimal number, using the Gregorian calendar * - %m: the month as a decimal number, in the range '1' through '12' * - %d: the day of the month as a decimal number, in the range '1' * through '31' * - %T: alias for '%H:%M:%S' * - %%: a literal '%' * * @return a pointer to the first character not processed in this function * call. In case the input string contains more characters than * required by the format string the return value points right after * the last consumed input character. In case the whole input string * is consumed the return value points to the null byte at the end of * the string. On failure NULL is returned. */ char *av_small_strptime(const char *p, const char *fmt, struct tm *dt); /** * Convert the decomposed UTC time in tm to a time_t value. */ time_t av_timegm(struct tm *tm); #endif /* AVUTIL_PARSEUTILS_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/pixdesc.h ================================================ /* * pixel format descriptor * Copyright (c) 2009 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PIXDESC_H #define AVUTIL_PIXDESC_H #include #include "attributes.h" #include "pixfmt.h" #include "version.h" typedef struct AVComponentDescriptor { /** * Which of the 4 planes contains the component. */ int plane; /** * Number of elements between 2 horizontally consecutive pixels. * Elements are bits for bitstream formats, bytes otherwise. */ int step; /** * Number of elements before the component of the first pixel. * Elements are bits for bitstream formats, bytes otherwise. */ int offset; /** * Number of least significant bits that must be shifted away * to get the value. */ int shift; /** * Number of bits in the component. */ int depth; #if FF_API_PLUS1_MINUS1 /** deprecated, use step instead */ attribute_deprecated int step_minus1; /** deprecated, use depth instead */ attribute_deprecated int depth_minus1; /** deprecated, use offset instead */ attribute_deprecated int offset_plus1; #endif } AVComponentDescriptor; /** * Descriptor that unambiguously describes how the bits of a pixel are * stored in the up to 4 data planes of an image. It also stores the * subsampling factors and number of components. * * @note This is separate of the colorspace (RGB, YCbCr, YPbPr, JPEG-style YUV * and all the YUV variants) AVPixFmtDescriptor just stores how values * are stored not what these values represent. */ typedef struct AVPixFmtDescriptor { const char *name; uint8_t nb_components; ///< The number of components each pixel has, (1-4) /** * Amount to shift the luma width right to find the chroma width. * For YV12 this is 1 for example. * chroma_width = AV_CEIL_RSHIFT(luma_width, log2_chroma_w) * The note above is needed to ensure rounding up. * This value only refers to the chroma components. */ uint8_t log2_chroma_w; /** * Amount to shift the luma height right to find the chroma height. * For YV12 this is 1 for example. * chroma_height= AV_CEIL_RSHIFT(luma_height, log2_chroma_h) * The note above is needed to ensure rounding up. * This value only refers to the chroma components. */ uint8_t log2_chroma_h; /** * Combination of AV_PIX_FMT_FLAG_... flags. */ uint64_t flags; /** * Parameters that describe how pixels are packed. * If the format has 1 or 2 components, then luma is 0. * If the format has 3 or 4 components: * if the RGB flag is set then 0 is red, 1 is green and 2 is blue; * otherwise 0 is luma, 1 is chroma-U and 2 is chroma-V. * * If present, the Alpha channel is always the last component. */ AVComponentDescriptor comp[4]; /** * Alternative comma-separated names. */ const char *alias; } AVPixFmtDescriptor; /** * Pixel format is big-endian. */ #define AV_PIX_FMT_FLAG_BE (1 << 0) /** * Pixel format has a palette in data[1], values are indexes in this palette. */ #define AV_PIX_FMT_FLAG_PAL (1 << 1) /** * All values of a component are bit-wise packed end to end. */ #define AV_PIX_FMT_FLAG_BITSTREAM (1 << 2) /** * Pixel format is an HW accelerated format. */ #define AV_PIX_FMT_FLAG_HWACCEL (1 << 3) /** * At least one pixel component is not in the first data plane. */ #define AV_PIX_FMT_FLAG_PLANAR (1 << 4) /** * The pixel format contains RGB-like data (as opposed to YUV/grayscale). */ #define AV_PIX_FMT_FLAG_RGB (1 << 5) /** * The pixel format is "pseudo-paletted". This means that it contains a * fixed palette in the 2nd plane but the palette is fixed/constant for each * PIX_FMT. This allows interpreting the data as if it was PAL8, which can * in some cases be simpler. Or the data can be interpreted purely based on * the pixel format without using the palette. * An example of a pseudo-paletted format is AV_PIX_FMT_GRAY8 * * @deprecated This flag is deprecated, and will be removed. When it is removed, * the extra palette allocation in AVFrame.data[1] is removed as well. Only * actual paletted formats (as indicated by AV_PIX_FMT_FLAG_PAL) will have a * palette. Starting with FFmpeg versions which have this flag deprecated, the * extra "pseudo" palette is already ignored, and API users are not required to * allocate a palette for AV_PIX_FMT_FLAG_PSEUDOPAL formats (it was required * before the deprecation, though). */ #define AV_PIX_FMT_FLAG_PSEUDOPAL (1 << 6) /** * The pixel format has an alpha channel. This is set on all formats that * support alpha in some way, including AV_PIX_FMT_PAL8. The alpha is always * straight, never pre-multiplied. * * If a codec or a filter does not support alpha, it should set all alpha to * opaque, or use the equivalent pixel formats without alpha component, e.g. * AV_PIX_FMT_RGB0 (or AV_PIX_FMT_RGB24 etc.) instead of AV_PIX_FMT_RGBA. */ #define AV_PIX_FMT_FLAG_ALPHA (1 << 7) /** * The pixel format is following a Bayer pattern */ #define AV_PIX_FMT_FLAG_BAYER (1 << 8) /** * The pixel format contains IEEE-754 floating point values. Precision (double, * single, or half) should be determined by the pixel size (64, 32, or 16 bits). */ #define AV_PIX_FMT_FLAG_FLOAT (1 << 9) /** * Return the number of bits per pixel used by the pixel format * described by pixdesc. Note that this is not the same as the number * of bits per sample. * * The returned number of bits refers to the number of bits actually * used for storing the pixel information, that is padding bits are * not counted. */ int av_get_bits_per_pixel(const AVPixFmtDescriptor *pixdesc); /** * Return the number of bits per pixel for the pixel format * described by pixdesc, including any padding or unused bits. */ int av_get_padded_bits_per_pixel(const AVPixFmtDescriptor *pixdesc); /** * @return a pixel format descriptor for provided pixel format or NULL if * this pixel format is unknown. */ const AVPixFmtDescriptor *av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt); /** * Iterate over all pixel format descriptors known to libavutil. * * @param prev previous descriptor. NULL to get the first descriptor. * * @return next descriptor or NULL after the last descriptor */ const AVPixFmtDescriptor *av_pix_fmt_desc_next(const AVPixFmtDescriptor *prev); /** * @return an AVPixelFormat id described by desc, or AV_PIX_FMT_NONE if desc * is not a valid pointer to a pixel format descriptor. */ enum AVPixelFormat av_pix_fmt_desc_get_id(const AVPixFmtDescriptor *desc); /** * Utility function to access log2_chroma_w log2_chroma_h from * the pixel format AVPixFmtDescriptor. * * @param[in] pix_fmt the pixel format * @param[out] h_shift store log2_chroma_w (horizontal/width shift) * @param[out] v_shift store log2_chroma_h (vertical/height shift) * * @return 0 on success, AVERROR(ENOSYS) on invalid or unknown pixel format */ int av_pix_fmt_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift); /** * @return number of planes in pix_fmt, a negative AVERROR if pix_fmt is not a * valid pixel format. */ int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt); /** * @return the name for provided color range or NULL if unknown. */ const char *av_color_range_name(enum AVColorRange range); /** * @return the AVColorRange value for name or an AVError if not found. */ int av_color_range_from_name(const char *name); /** * @return the name for provided color primaries or NULL if unknown. */ const char *av_color_primaries_name(enum AVColorPrimaries primaries); /** * @return the AVColorPrimaries value for name or an AVError if not found. */ int av_color_primaries_from_name(const char *name); /** * @return the name for provided color transfer or NULL if unknown. */ const char *av_color_transfer_name(enum AVColorTransferCharacteristic transfer); /** * @return the AVColorTransferCharacteristic value for name or an AVError if not found. */ int av_color_transfer_from_name(const char *name); /** * @return the name for provided color space or NULL if unknown. */ const char *av_color_space_name(enum AVColorSpace space); /** * @return the AVColorSpace value for name or an AVError if not found. */ int av_color_space_from_name(const char *name); /** * @return the name for provided chroma location or NULL if unknown. */ const char *av_chroma_location_name(enum AVChromaLocation location); /** * @return the AVChromaLocation value for name or an AVError if not found. */ int av_chroma_location_from_name(const char *name); /** * Return the pixel format corresponding to name. * * If there is no pixel format with name name, then looks for a * pixel format with the name corresponding to the native endian * format of name. * For example in a little-endian system, first looks for "gray16", * then for "gray16le". * * Finally if no pixel format has been found, returns AV_PIX_FMT_NONE. */ enum AVPixelFormat av_get_pix_fmt(const char *name); /** * Return the short name for a pixel format, NULL in case pix_fmt is * unknown. * * @see av_get_pix_fmt(), av_get_pix_fmt_string() */ const char *av_get_pix_fmt_name(enum AVPixelFormat pix_fmt); /** * Print in buf the string corresponding to the pixel format with * number pix_fmt, or a header if pix_fmt is negative. * * @param buf the buffer where to write the string * @param buf_size the size of buf * @param pix_fmt the number of the pixel format to print the * corresponding info string, or a negative value to print the * corresponding header. */ char *av_get_pix_fmt_string(char *buf, int buf_size, enum AVPixelFormat pix_fmt); /** * Read a line from an image, and write the values of the * pixel format component c to dst. * * @param data the array containing the pointers to the planes of the image * @param linesize the array containing the linesizes of the image * @param desc the pixel format descriptor for the image * @param x the horizontal coordinate of the first pixel to read * @param y the vertical coordinate of the first pixel to read * @param w the width of the line to read, that is the number of * values to write to dst * @param read_pal_component if not zero and the format is a paletted * format writes the values corresponding to the palette * component c in data[1] to dst, rather than the palette indexes in * data[0]. The behavior is undefined if the format is not paletted. * @param dst_element_size size of elements in dst array (2 or 4 byte) */ void av_read_image_line2(void *dst, const uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component, int dst_element_size); void av_read_image_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component); /** * Write the values from src to the pixel format component c of an * image line. * * @param src array containing the values to write * @param data the array containing the pointers to the planes of the * image to write into. It is supposed to be zeroed. * @param linesize the array containing the linesizes of the image * @param desc the pixel format descriptor for the image * @param x the horizontal coordinate of the first pixel to write * @param y the vertical coordinate of the first pixel to write * @param w the width of the line to write, that is the number of * values to write to the image line * @param src_element_size size of elements in src array (2 or 4 byte) */ void av_write_image_line2(const void *src, uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int src_element_size); void av_write_image_line(const uint16_t *src, uint8_t *data[4], const int linesize[4], const AVPixFmtDescriptor *desc, int x, int y, int c, int w); /** * Utility function to swap the endianness of a pixel format. * * @param[in] pix_fmt the pixel format * * @return pixel format with swapped endianness if it exists, * otherwise AV_PIX_FMT_NONE */ enum AVPixelFormat av_pix_fmt_swap_endianness(enum AVPixelFormat pix_fmt); #define FF_LOSS_RESOLUTION 0x0001 /**< loss due to resolution change */ #define FF_LOSS_DEPTH 0x0002 /**< loss due to color depth change */ #define FF_LOSS_COLORSPACE 0x0004 /**< loss due to color space conversion */ #define FF_LOSS_ALPHA 0x0008 /**< loss of alpha bits */ #define FF_LOSS_COLORQUANT 0x0010 /**< loss due to color quantization */ #define FF_LOSS_CHROMA 0x0020 /**< loss of chroma (e.g. RGB to gray conversion) */ /** * Compute what kind of losses will occur when converting from one specific * pixel format to another. * When converting from one pixel format to another, information loss may occur. * For example, when converting from RGB24 to GRAY, the color information will * be lost. Similarly, other losses occur when converting from some formats to * other formats. These losses can involve loss of chroma, but also loss of * resolution, loss of color depth, loss due to the color space conversion, loss * of the alpha bits or loss due to color quantization. * av_get_fix_fmt_loss() informs you about the various types of losses * which will occur when converting from one pixel format to another. * * @param[in] dst_pix_fmt destination pixel format * @param[in] src_pix_fmt source pixel format * @param[in] has_alpha Whether the source pixel format alpha channel is used. * @return Combination of flags informing you what kind of losses will occur * (maximum loss for an invalid dst_pix_fmt). */ int av_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt, enum AVPixelFormat src_pix_fmt, int has_alpha); /** * Compute what kind of losses will occur when converting from one specific * pixel format to another. * When converting from one pixel format to another, information loss may occur. * For example, when converting from RGB24 to GRAY, the color information will * be lost. Similarly, other losses occur when converting from some formats to * other formats. These losses can involve loss of chroma, but also loss of * resolution, loss of color depth, loss due to the color space conversion, loss * of the alpha bits or loss due to color quantization. * av_get_fix_fmt_loss() informs you about the various types of losses * which will occur when converting from one pixel format to another. * * @param[in] dst_pix_fmt destination pixel format * @param[in] src_pix_fmt source pixel format * @param[in] has_alpha Whether the source pixel format alpha channel is used. * @return Combination of flags informing you what kind of losses will occur * (maximum loss for an invalid dst_pix_fmt). */ enum AVPixelFormat av_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2, enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr); #endif /* AVUTIL_PIXDESC_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/pixelutils.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PIXELUTILS_H #define AVUTIL_PIXELUTILS_H #include #include #include "common.h" /** * Sum of abs(src1[x] - src2[x]) */ typedef int (*av_pixelutils_sad_fn)(const uint8_t *src1, ptrdiff_t stride1, const uint8_t *src2, ptrdiff_t stride2); /** * Get a potentially optimized pointer to a Sum-of-absolute-differences * function (see the av_pixelutils_sad_fn prototype). * * @param w_bits 1< * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_PIXFMT_H #define AVUTIL_PIXFMT_H /** * @file * pixel format definitions */ #include "libavutil/avconfig.h" #include "version.h" #define AVPALETTE_SIZE 1024 #define AVPALETTE_COUNT 256 /** * Pixel format. * * @note * AV_PIX_FMT_RGB32 is handled in an endian-specific manner. An RGBA * color is put together as: * (A << 24) | (R << 16) | (G << 8) | B * This is stored as BGRA on little-endian CPU architectures and ARGB on * big-endian CPUs. * * @note * If the resolution is not a multiple of the chroma subsampling factor * then the chroma plane resolution must be rounded up. * * @par * When the pixel format is palettized RGB32 (AV_PIX_FMT_PAL8), the palettized * image data is stored in AVFrame.data[0]. The palette is transported in * AVFrame.data[1], is 1024 bytes long (256 4-byte entries) and is * formatted the same as in AV_PIX_FMT_RGB32 described above (i.e., it is * also endian-specific). Note also that the individual RGB32 palette * components stored in AVFrame.data[1] should be in the range 0..255. * This is important as many custom PAL8 video codecs that were designed * to run on the IBM VGA graphics adapter use 6-bit palette components. * * @par * For all the 8 bits per pixel formats, an RGB32 palette is in data[1] like * for pal8. This palette is filled in automatically by the function * allocating the picture. */ enum AVPixelFormat { AV_PIX_FMT_NONE = -1, AV_PIX_FMT_YUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples) AV_PIX_FMT_YUYV422, ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr AV_PIX_FMT_RGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB... AV_PIX_FMT_BGR24, ///< packed RGB 8:8:8, 24bpp, BGRBGR... AV_PIX_FMT_YUV422P, ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) AV_PIX_FMT_YUV444P, ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples) AV_PIX_FMT_YUV410P, ///< planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples) AV_PIX_FMT_YUV411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) AV_PIX_FMT_GRAY8, ///< Y , 8bpp AV_PIX_FMT_MONOWHITE, ///< Y , 1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb AV_PIX_FMT_MONOBLACK, ///< Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb AV_PIX_FMT_PAL8, ///< 8 bits with AV_PIX_FMT_RGB32 palette AV_PIX_FMT_YUVJ420P, ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting color_range AV_PIX_FMT_YUVJ422P, ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting color_range AV_PIX_FMT_YUVJ444P, ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting color_range AV_PIX_FMT_UYVY422, ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1 AV_PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3 AV_PIX_FMT_BGR8, ///< packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb) AV_PIX_FMT_BGR4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits AV_PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb) AV_PIX_FMT_RGB8, ///< packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb) AV_PIX_FMT_RGB4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits AV_PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb) AV_PIX_FMT_NV12, ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) AV_PIX_FMT_NV21, ///< as above, but U and V bytes are swapped AV_PIX_FMT_ARGB, ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB... AV_PIX_FMT_RGBA, ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA... AV_PIX_FMT_ABGR, ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR... AV_PIX_FMT_BGRA, ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA... AV_PIX_FMT_GRAY16BE, ///< Y , 16bpp, big-endian AV_PIX_FMT_GRAY16LE, ///< Y , 16bpp, little-endian AV_PIX_FMT_YUV440P, ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples) AV_PIX_FMT_YUVJ440P, ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV440P and setting color_range AV_PIX_FMT_YUVA420P, ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples) AV_PIX_FMT_RGB48BE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian AV_PIX_FMT_RGB48LE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian AV_PIX_FMT_RGB565BE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian AV_PIX_FMT_RGB565LE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian AV_PIX_FMT_RGB555BE, ///< packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused/undefined AV_PIX_FMT_RGB555LE, ///< packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused/undefined AV_PIX_FMT_BGR565BE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), big-endian AV_PIX_FMT_BGR565LE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), little-endian AV_PIX_FMT_BGR555BE, ///< packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), big-endian , X=unused/undefined AV_PIX_FMT_BGR555LE, ///< packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), little-endian, X=unused/undefined #if FF_API_VAAPI /** @name Deprecated pixel formats */ /**@{*/ AV_PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers AV_PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers AV_PIX_FMT_VAAPI_VLD, ///< HW decoding through VA API, Picture.data[3] contains a VASurfaceID /**@}*/ AV_PIX_FMT_VAAPI = AV_PIX_FMT_VAAPI_VLD, #else /** * Hardware acceleration through VA-API, data[3] contains a * VASurfaceID. */ AV_PIX_FMT_VAAPI, #endif AV_PIX_FMT_YUV420P16LE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV420P16BE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV422P16LE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV422P16BE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV444P16LE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV444P16BE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_DXVA2_VLD, ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer AV_PIX_FMT_RGB444LE, ///< packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), little-endian, X=unused/undefined AV_PIX_FMT_RGB444BE, ///< packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), big-endian, X=unused/undefined AV_PIX_FMT_BGR444LE, ///< packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), little-endian, X=unused/undefined AV_PIX_FMT_BGR444BE, ///< packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), big-endian, X=unused/undefined AV_PIX_FMT_YA8, ///< 8 bits gray, 8 bits alpha AV_PIX_FMT_Y400A = AV_PIX_FMT_YA8, ///< alias for AV_PIX_FMT_YA8 AV_PIX_FMT_GRAY8A= AV_PIX_FMT_YA8, ///< alias for AV_PIX_FMT_YA8 AV_PIX_FMT_BGR48BE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian AV_PIX_FMT_BGR48LE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian /** * The following 12 formats have the disadvantage of needing 1 format for each bit depth. * Notice that each 9/10 bits sample is stored in 16 bits with extra padding. * If you want to support multiple bit depths, then using AV_PIX_FMT_YUV420P16* with the bpp stored separately is better. */ AV_PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_GBRP, ///< planar GBR 4:4:4 24bpp AV_PIX_FMT_GBR24P = AV_PIX_FMT_GBRP, // alias for #AV_PIX_FMT_GBRP AV_PIX_FMT_GBRP9BE, ///< planar GBR 4:4:4 27bpp, big-endian AV_PIX_FMT_GBRP9LE, ///< planar GBR 4:4:4 27bpp, little-endian AV_PIX_FMT_GBRP10BE, ///< planar GBR 4:4:4 30bpp, big-endian AV_PIX_FMT_GBRP10LE, ///< planar GBR 4:4:4 30bpp, little-endian AV_PIX_FMT_GBRP16BE, ///< planar GBR 4:4:4 48bpp, big-endian AV_PIX_FMT_GBRP16LE, ///< planar GBR 4:4:4 48bpp, little-endian AV_PIX_FMT_YUVA422P, ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples) AV_PIX_FMT_YUVA444P, ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples) AV_PIX_FMT_YUVA420P9BE, ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), big-endian AV_PIX_FMT_YUVA420P9LE, ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), little-endian AV_PIX_FMT_YUVA422P9BE, ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), big-endian AV_PIX_FMT_YUVA422P9LE, ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), little-endian AV_PIX_FMT_YUVA444P9BE, ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), big-endian AV_PIX_FMT_YUVA444P9LE, ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), little-endian AV_PIX_FMT_YUVA420P10BE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian) AV_PIX_FMT_YUVA420P10LE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian) AV_PIX_FMT_YUVA422P10BE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA422P10LE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian) AV_PIX_FMT_YUVA444P10BE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA444P10LE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian) AV_PIX_FMT_YUVA420P16BE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian) AV_PIX_FMT_YUVA420P16LE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian) AV_PIX_FMT_YUVA422P16BE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA422P16LE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian) AV_PIX_FMT_YUVA444P16BE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian) AV_PIX_FMT_YUVA444P16LE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian) AV_PIX_FMT_VDPAU, ///< HW acceleration through VDPAU, Picture.data[3] contains a VdpVideoSurface AV_PIX_FMT_XYZ12LE, ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as little-endian, the 4 lower bits are set to 0 AV_PIX_FMT_XYZ12BE, ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as big-endian, the 4 lower bits are set to 0 AV_PIX_FMT_NV16, ///< interleaved chroma YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples) AV_PIX_FMT_NV20LE, ///< interleaved chroma YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_NV20BE, ///< interleaved chroma YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_RGBA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian AV_PIX_FMT_RGBA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian AV_PIX_FMT_BGRA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian AV_PIX_FMT_BGRA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian AV_PIX_FMT_YVYU422, ///< packed YUV 4:2:2, 16bpp, Y0 Cr Y1 Cb AV_PIX_FMT_YA16BE, ///< 16 bits gray, 16 bits alpha (big-endian) AV_PIX_FMT_YA16LE, ///< 16 bits gray, 16 bits alpha (little-endian) AV_PIX_FMT_GBRAP, ///< planar GBRA 4:4:4:4 32bpp AV_PIX_FMT_GBRAP16BE, ///< planar GBRA 4:4:4:4 64bpp, big-endian AV_PIX_FMT_GBRAP16LE, ///< planar GBRA 4:4:4:4 64bpp, little-endian /** * HW acceleration through QSV, data[3] contains a pointer to the * mfxFrameSurface1 structure. */ AV_PIX_FMT_QSV, /** * HW acceleration though MMAL, data[3] contains a pointer to the * MMAL_BUFFER_HEADER_T structure. */ AV_PIX_FMT_MMAL, AV_PIX_FMT_D3D11VA_VLD, ///< HW decoding through Direct3D11 via old API, Picture.data[3] contains a ID3D11VideoDecoderOutputView pointer /** * HW acceleration through CUDA. data[i] contain CUdeviceptr pointers * exactly as for system memory frames. */ AV_PIX_FMT_CUDA, AV_PIX_FMT_0RGB, ///< packed RGB 8:8:8, 32bpp, XRGBXRGB... X=unused/undefined AV_PIX_FMT_RGB0, ///< packed RGB 8:8:8, 32bpp, RGBXRGBX... X=unused/undefined AV_PIX_FMT_0BGR, ///< packed BGR 8:8:8, 32bpp, XBGRXBGR... X=unused/undefined AV_PIX_FMT_BGR0, ///< packed BGR 8:8:8, 32bpp, BGRXBGRX... X=unused/undefined AV_PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian AV_PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian AV_PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian AV_PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian AV_PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian AV_PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian AV_PIX_FMT_GBRP12BE, ///< planar GBR 4:4:4 36bpp, big-endian AV_PIX_FMT_GBRP12LE, ///< planar GBR 4:4:4 36bpp, little-endian AV_PIX_FMT_GBRP14BE, ///< planar GBR 4:4:4 42bpp, big-endian AV_PIX_FMT_GBRP14LE, ///< planar GBR 4:4:4 42bpp, little-endian AV_PIX_FMT_YUVJ411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV411P and setting color_range AV_PIX_FMT_BAYER_BGGR8, ///< bayer, BGBG..(odd line), GRGR..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_RGGB8, ///< bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_GBRG8, ///< bayer, GBGB..(odd line), RGRG..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_GRBG8, ///< bayer, GRGR..(odd line), BGBG..(even line), 8-bit samples */ AV_PIX_FMT_BAYER_BGGR16LE, ///< bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_BGGR16BE, ///< bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, big-endian */ AV_PIX_FMT_BAYER_RGGB16LE, ///< bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_RGGB16BE, ///< bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, big-endian */ AV_PIX_FMT_BAYER_GBRG16LE, ///< bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_GBRG16BE, ///< bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, big-endian */ AV_PIX_FMT_BAYER_GRBG16LE, ///< bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, little-endian */ AV_PIX_FMT_BAYER_GRBG16BE, ///< bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, big-endian */ AV_PIX_FMT_XVMC,///< XVideo Motion Acceleration via common packet passing AV_PIX_FMT_YUV440P10LE, ///< planar YUV 4:4:0,20bpp, (1 Cr & Cb sample per 1x2 Y samples), little-endian AV_PIX_FMT_YUV440P10BE, ///< planar YUV 4:4:0,20bpp, (1 Cr & Cb sample per 1x2 Y samples), big-endian AV_PIX_FMT_YUV440P12LE, ///< planar YUV 4:4:0,24bpp, (1 Cr & Cb sample per 1x2 Y samples), little-endian AV_PIX_FMT_YUV440P12BE, ///< planar YUV 4:4:0,24bpp, (1 Cr & Cb sample per 1x2 Y samples), big-endian AV_PIX_FMT_AYUV64LE, ///< packed AYUV 4:4:4,64bpp (1 Cr & Cb sample per 1x1 Y & A samples), little-endian AV_PIX_FMT_AYUV64BE, ///< packed AYUV 4:4:4,64bpp (1 Cr & Cb sample per 1x1 Y & A samples), big-endian AV_PIX_FMT_VIDEOTOOLBOX, ///< hardware decoding through Videotoolbox AV_PIX_FMT_P010LE, ///< like NV12, with 10bpp per component, data in the high bits, zeros in the low bits, little-endian AV_PIX_FMT_P010BE, ///< like NV12, with 10bpp per component, data in the high bits, zeros in the low bits, big-endian AV_PIX_FMT_GBRAP12BE, ///< planar GBR 4:4:4:4 48bpp, big-endian AV_PIX_FMT_GBRAP12LE, ///< planar GBR 4:4:4:4 48bpp, little-endian AV_PIX_FMT_GBRAP10BE, ///< planar GBR 4:4:4:4 40bpp, big-endian AV_PIX_FMT_GBRAP10LE, ///< planar GBR 4:4:4:4 40bpp, little-endian AV_PIX_FMT_MEDIACODEC, ///< hardware decoding through MediaCodec AV_PIX_FMT_GRAY12BE, ///< Y , 12bpp, big-endian AV_PIX_FMT_GRAY12LE, ///< Y , 12bpp, little-endian AV_PIX_FMT_GRAY10BE, ///< Y , 10bpp, big-endian AV_PIX_FMT_GRAY10LE, ///< Y , 10bpp, little-endian AV_PIX_FMT_P016LE, ///< like NV12, with 16bpp per component, little-endian AV_PIX_FMT_P016BE, ///< like NV12, with 16bpp per component, big-endian /** * Hardware surfaces for Direct3D11. * * This is preferred over the legacy AV_PIX_FMT_D3D11VA_VLD. The new D3D11 * hwaccel API and filtering support AV_PIX_FMT_D3D11 only. * * data[0] contains a ID3D11Texture2D pointer, and data[1] contains the * texture array index of the frame as intptr_t if the ID3D11Texture2D is * an array texture (or always 0 if it's a normal texture). */ AV_PIX_FMT_D3D11, AV_PIX_FMT_GRAY9BE, ///< Y , 9bpp, big-endian AV_PIX_FMT_GRAY9LE, ///< Y , 9bpp, little-endian AV_PIX_FMT_GBRPF32BE, ///< IEEE-754 single precision planar GBR 4:4:4, 96bpp, big-endian AV_PIX_FMT_GBRPF32LE, ///< IEEE-754 single precision planar GBR 4:4:4, 96bpp, little-endian AV_PIX_FMT_GBRAPF32BE, ///< IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, big-endian AV_PIX_FMT_GBRAPF32LE, ///< IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, little-endian /** * DRM-managed buffers exposed through PRIME buffer sharing. * * data[0] points to an AVDRMFrameDescriptor. */ AV_PIX_FMT_DRM_PRIME, /** * Hardware surfaces for OpenCL. * * data[i] contain 2D image objects (typed in C as cl_mem, used * in OpenCL as image2d_t) for each plane of the surface. */ AV_PIX_FMT_OPENCL, AV_PIX_FMT_GRAY14BE, ///< Y , 14bpp, big-endian AV_PIX_FMT_GRAY14LE, ///< Y , 14bpp, little-endian AV_PIX_FMT_GRAYF32BE, ///< IEEE-754 single precision Y, 32bpp, big-endian AV_PIX_FMT_GRAYF32LE, ///< IEEE-754 single precision Y, 32bpp, little-endian AV_PIX_FMT_YUVA422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), 12b alpha, big-endian AV_PIX_FMT_YUVA422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), 12b alpha, little-endian AV_PIX_FMT_YUVA444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), 12b alpha, big-endian AV_PIX_FMT_YUVA444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), 12b alpha, little-endian AV_PIX_FMT_NV24, ///< planar YUV 4:4:4, 24bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V) AV_PIX_FMT_NV42, ///< as above, but U and V bytes are swapped AV_PIX_FMT_NB ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions }; #if AV_HAVE_BIGENDIAN # define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##be #else # define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##le #endif #define AV_PIX_FMT_RGB32 AV_PIX_FMT_NE(ARGB, BGRA) #define AV_PIX_FMT_RGB32_1 AV_PIX_FMT_NE(RGBA, ABGR) #define AV_PIX_FMT_BGR32 AV_PIX_FMT_NE(ABGR, RGBA) #define AV_PIX_FMT_BGR32_1 AV_PIX_FMT_NE(BGRA, ARGB) #define AV_PIX_FMT_0RGB32 AV_PIX_FMT_NE(0RGB, BGR0) #define AV_PIX_FMT_0BGR32 AV_PIX_FMT_NE(0BGR, RGB0) #define AV_PIX_FMT_GRAY9 AV_PIX_FMT_NE(GRAY9BE, GRAY9LE) #define AV_PIX_FMT_GRAY10 AV_PIX_FMT_NE(GRAY10BE, GRAY10LE) #define AV_PIX_FMT_GRAY12 AV_PIX_FMT_NE(GRAY12BE, GRAY12LE) #define AV_PIX_FMT_GRAY14 AV_PIX_FMT_NE(GRAY14BE, GRAY14LE) #define AV_PIX_FMT_GRAY16 AV_PIX_FMT_NE(GRAY16BE, GRAY16LE) #define AV_PIX_FMT_YA16 AV_PIX_FMT_NE(YA16BE, YA16LE) #define AV_PIX_FMT_RGB48 AV_PIX_FMT_NE(RGB48BE, RGB48LE) #define AV_PIX_FMT_RGB565 AV_PIX_FMT_NE(RGB565BE, RGB565LE) #define AV_PIX_FMT_RGB555 AV_PIX_FMT_NE(RGB555BE, RGB555LE) #define AV_PIX_FMT_RGB444 AV_PIX_FMT_NE(RGB444BE, RGB444LE) #define AV_PIX_FMT_RGBA64 AV_PIX_FMT_NE(RGBA64BE, RGBA64LE) #define AV_PIX_FMT_BGR48 AV_PIX_FMT_NE(BGR48BE, BGR48LE) #define AV_PIX_FMT_BGR565 AV_PIX_FMT_NE(BGR565BE, BGR565LE) #define AV_PIX_FMT_BGR555 AV_PIX_FMT_NE(BGR555BE, BGR555LE) #define AV_PIX_FMT_BGR444 AV_PIX_FMT_NE(BGR444BE, BGR444LE) #define AV_PIX_FMT_BGRA64 AV_PIX_FMT_NE(BGRA64BE, BGRA64LE) #define AV_PIX_FMT_YUV420P9 AV_PIX_FMT_NE(YUV420P9BE , YUV420P9LE) #define AV_PIX_FMT_YUV422P9 AV_PIX_FMT_NE(YUV422P9BE , YUV422P9LE) #define AV_PIX_FMT_YUV444P9 AV_PIX_FMT_NE(YUV444P9BE , YUV444P9LE) #define AV_PIX_FMT_YUV420P10 AV_PIX_FMT_NE(YUV420P10BE, YUV420P10LE) #define AV_PIX_FMT_YUV422P10 AV_PIX_FMT_NE(YUV422P10BE, YUV422P10LE) #define AV_PIX_FMT_YUV440P10 AV_PIX_FMT_NE(YUV440P10BE, YUV440P10LE) #define AV_PIX_FMT_YUV444P10 AV_PIX_FMT_NE(YUV444P10BE, YUV444P10LE) #define AV_PIX_FMT_YUV420P12 AV_PIX_FMT_NE(YUV420P12BE, YUV420P12LE) #define AV_PIX_FMT_YUV422P12 AV_PIX_FMT_NE(YUV422P12BE, YUV422P12LE) #define AV_PIX_FMT_YUV440P12 AV_PIX_FMT_NE(YUV440P12BE, YUV440P12LE) #define AV_PIX_FMT_YUV444P12 AV_PIX_FMT_NE(YUV444P12BE, YUV444P12LE) #define AV_PIX_FMT_YUV420P14 AV_PIX_FMT_NE(YUV420P14BE, YUV420P14LE) #define AV_PIX_FMT_YUV422P14 AV_PIX_FMT_NE(YUV422P14BE, YUV422P14LE) #define AV_PIX_FMT_YUV444P14 AV_PIX_FMT_NE(YUV444P14BE, YUV444P14LE) #define AV_PIX_FMT_YUV420P16 AV_PIX_FMT_NE(YUV420P16BE, YUV420P16LE) #define AV_PIX_FMT_YUV422P16 AV_PIX_FMT_NE(YUV422P16BE, YUV422P16LE) #define AV_PIX_FMT_YUV444P16 AV_PIX_FMT_NE(YUV444P16BE, YUV444P16LE) #define AV_PIX_FMT_GBRP9 AV_PIX_FMT_NE(GBRP9BE , GBRP9LE) #define AV_PIX_FMT_GBRP10 AV_PIX_FMT_NE(GBRP10BE, GBRP10LE) #define AV_PIX_FMT_GBRP12 AV_PIX_FMT_NE(GBRP12BE, GBRP12LE) #define AV_PIX_FMT_GBRP14 AV_PIX_FMT_NE(GBRP14BE, GBRP14LE) #define AV_PIX_FMT_GBRP16 AV_PIX_FMT_NE(GBRP16BE, GBRP16LE) #define AV_PIX_FMT_GBRAP10 AV_PIX_FMT_NE(GBRAP10BE, GBRAP10LE) #define AV_PIX_FMT_GBRAP12 AV_PIX_FMT_NE(GBRAP12BE, GBRAP12LE) #define AV_PIX_FMT_GBRAP16 AV_PIX_FMT_NE(GBRAP16BE, GBRAP16LE) #define AV_PIX_FMT_BAYER_BGGR16 AV_PIX_FMT_NE(BAYER_BGGR16BE, BAYER_BGGR16LE) #define AV_PIX_FMT_BAYER_RGGB16 AV_PIX_FMT_NE(BAYER_RGGB16BE, BAYER_RGGB16LE) #define AV_PIX_FMT_BAYER_GBRG16 AV_PIX_FMT_NE(BAYER_GBRG16BE, BAYER_GBRG16LE) #define AV_PIX_FMT_BAYER_GRBG16 AV_PIX_FMT_NE(BAYER_GRBG16BE, BAYER_GRBG16LE) #define AV_PIX_FMT_GBRPF32 AV_PIX_FMT_NE(GBRPF32BE, GBRPF32LE) #define AV_PIX_FMT_GBRAPF32 AV_PIX_FMT_NE(GBRAPF32BE, GBRAPF32LE) #define AV_PIX_FMT_GRAYF32 AV_PIX_FMT_NE(GRAYF32BE, GRAYF32LE) #define AV_PIX_FMT_YUVA420P9 AV_PIX_FMT_NE(YUVA420P9BE , YUVA420P9LE) #define AV_PIX_FMT_YUVA422P9 AV_PIX_FMT_NE(YUVA422P9BE , YUVA422P9LE) #define AV_PIX_FMT_YUVA444P9 AV_PIX_FMT_NE(YUVA444P9BE , YUVA444P9LE) #define AV_PIX_FMT_YUVA420P10 AV_PIX_FMT_NE(YUVA420P10BE, YUVA420P10LE) #define AV_PIX_FMT_YUVA422P10 AV_PIX_FMT_NE(YUVA422P10BE, YUVA422P10LE) #define AV_PIX_FMT_YUVA444P10 AV_PIX_FMT_NE(YUVA444P10BE, YUVA444P10LE) #define AV_PIX_FMT_YUVA422P12 AV_PIX_FMT_NE(YUVA422P12BE, YUVA422P12LE) #define AV_PIX_FMT_YUVA444P12 AV_PIX_FMT_NE(YUVA444P12BE, YUVA444P12LE) #define AV_PIX_FMT_YUVA420P16 AV_PIX_FMT_NE(YUVA420P16BE, YUVA420P16LE) #define AV_PIX_FMT_YUVA422P16 AV_PIX_FMT_NE(YUVA422P16BE, YUVA422P16LE) #define AV_PIX_FMT_YUVA444P16 AV_PIX_FMT_NE(YUVA444P16BE, YUVA444P16LE) #define AV_PIX_FMT_XYZ12 AV_PIX_FMT_NE(XYZ12BE, XYZ12LE) #define AV_PIX_FMT_NV20 AV_PIX_FMT_NE(NV20BE, NV20LE) #define AV_PIX_FMT_AYUV64 AV_PIX_FMT_NE(AYUV64BE, AYUV64LE) #define AV_PIX_FMT_P010 AV_PIX_FMT_NE(P010BE, P010LE) #define AV_PIX_FMT_P016 AV_PIX_FMT_NE(P016BE, P016LE) /** * Chromaticity coordinates of the source primaries. * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.1. */ enum AVColorPrimaries { AVCOL_PRI_RESERVED0 = 0, AVCOL_PRI_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B AVCOL_PRI_UNSPECIFIED = 2, AVCOL_PRI_RESERVED = 3, AVCOL_PRI_BT470M = 4, ///< also FCC Title 47 Code of Federal Regulations 73.682 (a)(20) AVCOL_PRI_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM AVCOL_PRI_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC AVCOL_PRI_SMPTE240M = 7, ///< functionally identical to above AVCOL_PRI_FILM = 8, ///< colour filters using Illuminant C AVCOL_PRI_BT2020 = 9, ///< ITU-R BT2020 AVCOL_PRI_SMPTE428 = 10, ///< SMPTE ST 428-1 (CIE 1931 XYZ) AVCOL_PRI_SMPTEST428_1 = AVCOL_PRI_SMPTE428, AVCOL_PRI_SMPTE431 = 11, ///< SMPTE ST 431-2 (2011) / DCI P3 AVCOL_PRI_SMPTE432 = 12, ///< SMPTE ST 432-1 (2010) / P3 D65 / Display P3 AVCOL_PRI_JEDEC_P22 = 22, ///< JEDEC P22 phosphors AVCOL_PRI_NB ///< Not part of ABI }; /** * Color Transfer Characteristic. * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.2. */ enum AVColorTransferCharacteristic { AVCOL_TRC_RESERVED0 = 0, AVCOL_TRC_BT709 = 1, ///< also ITU-R BT1361 AVCOL_TRC_UNSPECIFIED = 2, AVCOL_TRC_RESERVED = 3, AVCOL_TRC_GAMMA22 = 4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM AVCOL_TRC_GAMMA28 = 5, ///< also ITU-R BT470BG AVCOL_TRC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 or 625 / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC AVCOL_TRC_SMPTE240M = 7, AVCOL_TRC_LINEAR = 8, ///< "Linear transfer characteristics" AVCOL_TRC_LOG = 9, ///< "Logarithmic transfer characteristic (100:1 range)" AVCOL_TRC_LOG_SQRT = 10, ///< "Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)" AVCOL_TRC_IEC61966_2_4 = 11, ///< IEC 61966-2-4 AVCOL_TRC_BT1361_ECG = 12, ///< ITU-R BT1361 Extended Colour Gamut AVCOL_TRC_IEC61966_2_1 = 13, ///< IEC 61966-2-1 (sRGB or sYCC) AVCOL_TRC_BT2020_10 = 14, ///< ITU-R BT2020 for 10-bit system AVCOL_TRC_BT2020_12 = 15, ///< ITU-R BT2020 for 12-bit system AVCOL_TRC_SMPTE2084 = 16, ///< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems AVCOL_TRC_SMPTEST2084 = AVCOL_TRC_SMPTE2084, AVCOL_TRC_SMPTE428 = 17, ///< SMPTE ST 428-1 AVCOL_TRC_SMPTEST428_1 = AVCOL_TRC_SMPTE428, AVCOL_TRC_ARIB_STD_B67 = 18, ///< ARIB STD-B67, known as "Hybrid log-gamma" AVCOL_TRC_NB ///< Not part of ABI }; /** * YUV colorspace type. * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.3. */ enum AVColorSpace { AVCOL_SPC_RGB = 0, ///< order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB) AVCOL_SPC_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B AVCOL_SPC_UNSPECIFIED = 2, AVCOL_SPC_RESERVED = 3, AVCOL_SPC_FCC = 4, ///< FCC Title 47 Code of Federal Regulations 73.682 (a)(20) AVCOL_SPC_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601 AVCOL_SPC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC AVCOL_SPC_SMPTE240M = 7, ///< functionally identical to above AVCOL_SPC_YCGCO = 8, ///< Used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16 AVCOL_SPC_YCOCG = AVCOL_SPC_YCGCO, AVCOL_SPC_BT2020_NCL = 9, ///< ITU-R BT2020 non-constant luminance system AVCOL_SPC_BT2020_CL = 10, ///< ITU-R BT2020 constant luminance system AVCOL_SPC_SMPTE2085 = 11, ///< SMPTE 2085, Y'D'zD'x AVCOL_SPC_CHROMA_DERIVED_NCL = 12, ///< Chromaticity-derived non-constant luminance system AVCOL_SPC_CHROMA_DERIVED_CL = 13, ///< Chromaticity-derived constant luminance system AVCOL_SPC_ICTCP = 14, ///< ITU-R BT.2100-0, ICtCp AVCOL_SPC_NB ///< Not part of ABI }; /** * MPEG vs JPEG YUV range. */ enum AVColorRange { AVCOL_RANGE_UNSPECIFIED = 0, AVCOL_RANGE_MPEG = 1, ///< the normal 219*2^(n-8) "MPEG" YUV ranges AVCOL_RANGE_JPEG = 2, ///< the normal 2^n-1 "JPEG" YUV ranges AVCOL_RANGE_NB ///< Not part of ABI }; /** * Location of chroma samples. * * Illustration showing the location of the first (top left) chroma sample of the * image, the left shows only luma, the right * shows the location of the chroma sample, the 2 could be imagined to overlay * each other but are drawn separately due to limitations of ASCII * * 1st 2nd 1st 2nd horizontal luma sample positions * v v v v * ______ ______ *1st luma line > |X X ... |3 4 X ... X are luma samples, * | |1 2 1-6 are possible chroma positions *2nd luma line > |X X ... |5 6 X ... 0 is undefined/unknown position */ enum AVChromaLocation { AVCHROMA_LOC_UNSPECIFIED = 0, AVCHROMA_LOC_LEFT = 1, ///< MPEG-2/4 4:2:0, H.264 default for 4:2:0 AVCHROMA_LOC_CENTER = 2, ///< MPEG-1 4:2:0, JPEG 4:2:0, H.263 4:2:0 AVCHROMA_LOC_TOPLEFT = 3, ///< ITU-R 601, SMPTE 274M 296M S314M(DV 4:1:1), mpeg2 4:2:2 AVCHROMA_LOC_TOP = 4, AVCHROMA_LOC_BOTTOMLEFT = 5, AVCHROMA_LOC_BOTTOM = 6, AVCHROMA_LOC_NB ///< Not part of ABI }; #endif /* AVUTIL_PIXFMT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/random_seed.h ================================================ /* * Copyright (c) 2009 Baptiste Coudurier * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_RANDOM_SEED_H #define AVUTIL_RANDOM_SEED_H #include /** * @addtogroup lavu_crypto * @{ */ /** * Get a seed to use in conjunction with random functions. * This function tries to provide a good seed at a best effort bases. * Its possible to call this function multiple times if more bits are needed. * It can be quite slow, which is why it should only be used as seed for a faster * PRNG. The quality of the seed depends on the platform. */ uint32_t av_get_random_seed(void); /** * @} */ #endif /* AVUTIL_RANDOM_SEED_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/rational.h ================================================ /* * rational numbers * Copyright (c) 2003 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_math_rational * Utilties for rational number calculation. * @author Michael Niedermayer */ #ifndef AVUTIL_RATIONAL_H #define AVUTIL_RATIONAL_H #include #include #include "attributes.h" /** * @defgroup lavu_math_rational AVRational * @ingroup lavu_math * Rational number calculation. * * While rational numbers can be expressed as floating-point numbers, the * conversion process is a lossy one, so are floating-point operations. On the * other hand, the nature of FFmpeg demands highly accurate calculation of * timestamps. This set of rational number utilities serves as a generic * interface for manipulating rational numbers as pairs of numerators and * denominators. * * Many of the functions that operate on AVRational's have the suffix `_q`, in * reference to the mathematical symbol "ℚ" (Q) which denotes the set of all * rational numbers. * * @{ */ /** * Rational number (pair of numerator and denominator). */ typedef struct AVRational{ int num; ///< Numerator int den; ///< Denominator } AVRational; /** * Create an AVRational. * * Useful for compilers that do not support compound literals. * * @note The return value is not reduced. * @see av_reduce() */ static inline AVRational av_make_q(int num, int den) { AVRational r = { num, den }; return r; } /** * Compare two rationals. * * @param a First rational * @param b Second rational * * @return One of the following values: * - 0 if `a == b` * - 1 if `a > b` * - -1 if `a < b` * - `INT_MIN` if one of the values is of the form `0 / 0` */ static inline int av_cmp_q(AVRational a, AVRational b){ const int64_t tmp= a.num * (int64_t)b.den - b.num * (int64_t)a.den; if(tmp) return (int)((tmp ^ a.den ^ b.den)>>63)|1; else if(b.den && a.den) return 0; else if(a.num && b.num) return (a.num>>31) - (b.num>>31); else return INT_MIN; } /** * Convert an AVRational to a `double`. * @param a AVRational to convert * @return `a` in floating-point form * @see av_d2q() */ static inline double av_q2d(AVRational a){ return a.num / (double) a.den; } /** * Reduce a fraction. * * This is useful for framerate calculations. * * @param[out] dst_num Destination numerator * @param[out] dst_den Destination denominator * @param[in] num Source numerator * @param[in] den Source denominator * @param[in] max Maximum allowed values for `dst_num` & `dst_den` * @return 1 if the operation is exact, 0 otherwise */ int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max); /** * Multiply two rationals. * @param b First rational * @param c Second rational * @return b*c */ AVRational av_mul_q(AVRational b, AVRational c) av_const; /** * Divide one rational by another. * @param b First rational * @param c Second rational * @return b/c */ AVRational av_div_q(AVRational b, AVRational c) av_const; /** * Add two rationals. * @param b First rational * @param c Second rational * @return b+c */ AVRational av_add_q(AVRational b, AVRational c) av_const; /** * Subtract one rational from another. * @param b First rational * @param c Second rational * @return b-c */ AVRational av_sub_q(AVRational b, AVRational c) av_const; /** * Invert a rational. * @param q value * @return 1 / q */ static av_always_inline AVRational av_inv_q(AVRational q) { AVRational r = { q.den, q.num }; return r; } /** * Convert a double precision floating point number to a rational. * * In case of infinity, the returned value is expressed as `{1, 0}` or * `{-1, 0}` depending on the sign. * * @param d `double` to convert * @param max Maximum allowed numerator and denominator * @return `d` in AVRational form * @see av_q2d() */ AVRational av_d2q(double d, int max) av_const; /** * Find which of the two rationals is closer to another rational. * * @param q Rational to be compared against * @param q1,q2 Rationals to be tested * @return One of the following values: * - 1 if `q1` is nearer to `q` than `q2` * - -1 if `q2` is nearer to `q` than `q1` * - 0 if they have the same distance */ int av_nearer_q(AVRational q, AVRational q1, AVRational q2); /** * Find the value in a list of rationals nearest a given reference rational. * * @param q Reference rational * @param q_list Array of rationals terminated by `{0, 0}` * @return Index of the nearest value found in the array */ int av_find_nearest_q_idx(AVRational q, const AVRational* q_list); /** * Convert an AVRational to a IEEE 32-bit `float` expressed in fixed-point * format. * * @param q Rational to be converted * @return Equivalent floating-point value, expressed as an unsigned 32-bit * integer. * @note The returned value is platform-indepedant. */ uint32_t av_q2intfloat(AVRational q); /** * @} */ #endif /* AVUTIL_RATIONAL_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/rc4.h ================================================ /* * RC4 encryption/decryption/pseudo-random number generator * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_RC4_H #define AVUTIL_RC4_H #include /** * @defgroup lavu_rc4 RC4 * @ingroup lavu_crypto * @{ */ typedef struct AVRC4 { uint8_t state[256]; int x, y; } AVRC4; /** * Allocate an AVRC4 context. */ AVRC4 *av_rc4_alloc(void); /** * @brief Initializes an AVRC4 context. * * @param key_bits must be a multiple of 8 * @param decrypt 0 for encryption, 1 for decryption, currently has no effect * @return zero on success, negative value otherwise */ int av_rc4_init(struct AVRC4 *d, const uint8_t *key, int key_bits, int decrypt); /** * @brief Encrypts / decrypts using the RC4 algorithm. * * @param count number of bytes * @param dst destination array, can be equal to src * @param src source array, can be equal to dst, may be NULL * @param iv not (yet) used for RC4, should be NULL * @param decrypt 0 for encryption, 1 for decryption, not (yet) used */ void av_rc4_crypt(struct AVRC4 *d, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_RC4_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/replaygain.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_REPLAYGAIN_H #define AVUTIL_REPLAYGAIN_H #include /** * ReplayGain information (see * http://wiki.hydrogenaudio.org/index.php?title=ReplayGain_1.0_specification). * The size of this struct is a part of the public ABI. */ typedef struct AVReplayGain { /** * Track replay gain in microbels (divide by 100000 to get the value in dB). * Should be set to INT32_MIN when unknown. */ int32_t track_gain; /** * Peak track amplitude, with 100000 representing full scale (but values * may overflow). 0 when unknown. */ uint32_t track_peak; /** * Same as track_gain, but for the whole album. */ int32_t album_gain; /** * Same as track_peak, but for the whole album, */ uint32_t album_peak; } AVReplayGain; #endif /* AVUTIL_REPLAYGAIN_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/ripemd.h ================================================ /* * Copyright (C) 2007 Michael Niedermayer * Copyright (C) 2013 James Almer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_ripemd * Public header for RIPEMD hash function implementation. */ #ifndef AVUTIL_RIPEMD_H #define AVUTIL_RIPEMD_H #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_ripemd RIPEMD * @ingroup lavu_hash * RIPEMD hash function implementation. * * @{ */ extern const int av_ripemd_size; struct AVRIPEMD; /** * Allocate an AVRIPEMD context. */ struct AVRIPEMD *av_ripemd_alloc(void); /** * Initialize RIPEMD hashing. * * @param context pointer to the function context (of size av_ripemd_size) * @param bits number of bits in digest (128, 160, 256 or 320 bits) * @return zero if initialization succeeded, -1 otherwise */ int av_ripemd_init(struct AVRIPEMD* context, int bits); /** * Update hash value. * * @param context hash function context * @param data input data to update hash with * @param len input data length */ #if FF_API_CRYPTO_SIZE_T void av_ripemd_update(struct AVRIPEMD* context, const uint8_t* data, unsigned int len); #else void av_ripemd_update(struct AVRIPEMD* context, const uint8_t* data, size_t len); #endif /** * Finish hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored */ void av_ripemd_final(struct AVRIPEMD* context, uint8_t *digest); /** * @} */ #endif /* AVUTIL_RIPEMD_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/samplefmt.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_SAMPLEFMT_H #define AVUTIL_SAMPLEFMT_H #include #include "avutil.h" #include "attributes.h" /** * @addtogroup lavu_audio * @{ * * @defgroup lavu_sampfmts Audio sample formats * * Audio sample format enumeration and related convenience functions. * @{ */ /** * Audio sample formats * * - The data described by the sample format is always in native-endian order. * Sample values can be expressed by native C types, hence the lack of a signed * 24-bit sample format even though it is a common raw audio data format. * * - The floating-point formats are based on full volume being in the range * [-1.0, 1.0]. Any values outside this range are beyond full volume level. * * - The data layout as used in av_samples_fill_arrays() and elsewhere in FFmpeg * (such as AVFrame in libavcodec) is as follows: * * @par * For planar sample formats, each audio channel is in a separate data plane, * and linesize is the buffer size, in bytes, for a single plane. All data * planes must be the same size. For packed sample formats, only the first data * plane is used, and samples for each channel are interleaved. In this case, * linesize is the buffer size, in bytes, for the 1 plane. * */ enum AVSampleFormat { AV_SAMPLE_FMT_NONE = -1, AV_SAMPLE_FMT_U8, ///< unsigned 8 bits AV_SAMPLE_FMT_S16, ///< signed 16 bits AV_SAMPLE_FMT_S32, ///< signed 32 bits AV_SAMPLE_FMT_FLT, ///< float AV_SAMPLE_FMT_DBL, ///< double AV_SAMPLE_FMT_U8P, ///< unsigned 8 bits, planar AV_SAMPLE_FMT_S16P, ///< signed 16 bits, planar AV_SAMPLE_FMT_S32P, ///< signed 32 bits, planar AV_SAMPLE_FMT_FLTP, ///< float, planar AV_SAMPLE_FMT_DBLP, ///< double, planar AV_SAMPLE_FMT_S64, ///< signed 64 bits AV_SAMPLE_FMT_S64P, ///< signed 64 bits, planar AV_SAMPLE_FMT_NB ///< Number of sample formats. DO NOT USE if linking dynamically }; /** * Return the name of sample_fmt, or NULL if sample_fmt is not * recognized. */ const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt); /** * Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE * on error. */ enum AVSampleFormat av_get_sample_fmt(const char *name); /** * Return the planar<->packed alternative form of the given sample format, or * AV_SAMPLE_FMT_NONE on error. If the passed sample_fmt is already in the * requested planar/packed format, the format returned is the same as the * input. */ enum AVSampleFormat av_get_alt_sample_fmt(enum AVSampleFormat sample_fmt, int planar); /** * Get the packed alternative form of the given sample format. * * If the passed sample_fmt is already in packed format, the format returned is * the same as the input. * * @return the packed alternative form of the given sample format or AV_SAMPLE_FMT_NONE on error. */ enum AVSampleFormat av_get_packed_sample_fmt(enum AVSampleFormat sample_fmt); /** * Get the planar alternative form of the given sample format. * * If the passed sample_fmt is already in planar format, the format returned is * the same as the input. * * @return the planar alternative form of the given sample format or AV_SAMPLE_FMT_NONE on error. */ enum AVSampleFormat av_get_planar_sample_fmt(enum AVSampleFormat sample_fmt); /** * Generate a string corresponding to the sample format with * sample_fmt, or a header if sample_fmt is negative. * * @param buf the buffer where to write the string * @param buf_size the size of buf * @param sample_fmt the number of the sample format to print the * corresponding info string, or a negative value to print the * corresponding header. * @return the pointer to the filled buffer or NULL if sample_fmt is * unknown or in case of other errors */ char *av_get_sample_fmt_string(char *buf, int buf_size, enum AVSampleFormat sample_fmt); /** * Return number of bytes per sample. * * @param sample_fmt the sample format * @return number of bytes per sample or zero if unknown for the given * sample format */ int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt); /** * Check if the sample format is planar. * * @param sample_fmt the sample format to inspect * @return 1 if the sample format is planar, 0 if it is interleaved */ int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt); /** * Get the required buffer size for the given audio parameters. * * @param[out] linesize calculated linesize, may be NULL * @param nb_channels the number of channels * @param nb_samples the number of samples in a single channel * @param sample_fmt the sample format * @param align buffer size alignment (0 = default, 1 = no alignment) * @return required buffer size, or negative error code on failure */ int av_samples_get_buffer_size(int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * @} * * @defgroup lavu_sampmanip Samples manipulation * * Functions that manipulate audio samples * @{ */ /** * Fill plane data pointers and linesize for samples with sample * format sample_fmt. * * The audio_data array is filled with the pointers to the samples data planes: * for planar, set the start point of each channel's data within the buffer, * for packed, set the start point of the entire buffer only. * * The value pointed to by linesize is set to the aligned size of each * channel's data buffer for planar layout, or to the aligned size of the * buffer for all channels for packed layout. * * The buffer in buf must be big enough to contain all the samples * (use av_samples_get_buffer_size() to compute its minimum size), * otherwise the audio_data pointers will point to invalid data. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param[out] audio_data array to be filled with the pointer for each channel * @param[out] linesize calculated linesize, may be NULL * @param buf the pointer to a buffer containing the samples * @param nb_channels the number of channels * @param nb_samples the number of samples in a single channel * @param sample_fmt the sample format * @param align buffer size alignment (0 = default, 1 = no alignment) * @return >=0 on success or a negative error code on failure * @todo return minimum size in bytes required for the buffer in case * of success at the next bump */ int av_samples_fill_arrays(uint8_t **audio_data, int *linesize, const uint8_t *buf, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * Allocate a samples buffer for nb_samples samples, and fill data pointers and * linesize accordingly. * The allocated samples buffer can be freed by using av_freep(&audio_data[0]) * Allocated data will be initialized to silence. * * @see enum AVSampleFormat * The documentation for AVSampleFormat describes the data layout. * * @param[out] audio_data array to be filled with the pointer for each channel * @param[out] linesize aligned size for audio buffer(s), may be NULL * @param nb_channels number of audio channels * @param nb_samples number of samples per channel * @param align buffer size alignment (0 = default, 1 = no alignment) * @return >=0 on success or a negative error code on failure * @todo return the size of the allocated buffer in case of success at the next bump * @see av_samples_fill_arrays() * @see av_samples_alloc_array_and_samples() */ int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * Allocate a data pointers array, samples buffer for nb_samples * samples, and fill data pointers and linesize accordingly. * * This is the same as av_samples_alloc(), but also allocates the data * pointers array. * * @see av_samples_alloc() */ int av_samples_alloc_array_and_samples(uint8_t ***audio_data, int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align); /** * Copy samples from src to dst. * * @param dst destination array of pointers to data planes * @param src source array of pointers to data planes * @param dst_offset offset in samples at which the data will be written to dst * @param src_offset offset in samples at which the data will be read from src * @param nb_samples number of samples to be copied * @param nb_channels number of audio channels * @param sample_fmt audio sample format */ int av_samples_copy(uint8_t **dst, uint8_t * const *src, int dst_offset, int src_offset, int nb_samples, int nb_channels, enum AVSampleFormat sample_fmt); /** * Fill an audio buffer with silence. * * @param audio_data array of pointers to data planes * @param offset offset in samples at which to start filling * @param nb_samples number of samples to fill * @param nb_channels number of audio channels * @param sample_fmt audio sample format */ int av_samples_set_silence(uint8_t **audio_data, int offset, int nb_samples, int nb_channels, enum AVSampleFormat sample_fmt); /** * @} * @} */ #endif /* AVUTIL_SAMPLEFMT_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/sha.h ================================================ /* * Copyright (C) 2007 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_sha * Public header for SHA-1 & SHA-256 hash function implementations. */ #ifndef AVUTIL_SHA_H #define AVUTIL_SHA_H #include #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_sha SHA * @ingroup lavu_hash * SHA-1 and SHA-256 (Secure Hash Algorithm) hash function implementations. * * This module supports the following SHA hash functions: * * - SHA-1: 160 bits * - SHA-224: 224 bits, as a variant of SHA-2 * - SHA-256: 256 bits, as a variant of SHA-2 * * @see For SHA-384, SHA-512, and variants thereof, see @ref lavu_sha512. * * @{ */ extern const int av_sha_size; struct AVSHA; /** * Allocate an AVSHA context. */ struct AVSHA *av_sha_alloc(void); /** * Initialize SHA-1 or SHA-2 hashing. * * @param context pointer to the function context (of size av_sha_size) * @param bits number of bits in digest (SHA-1 - 160 bits, SHA-2 224 or 256 bits) * @return zero if initialization succeeded, -1 otherwise */ int av_sha_init(struct AVSHA* context, int bits); /** * Update hash value. * * @param ctx hash function context * @param data input data to update hash with * @param len input data length */ #if FF_API_CRYPTO_SIZE_T void av_sha_update(struct AVSHA *ctx, const uint8_t *data, unsigned int len); #else void av_sha_update(struct AVSHA *ctx, const uint8_t *data, size_t len); #endif /** * Finish hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored */ void av_sha_final(struct AVSHA* context, uint8_t *digest); /** * @} */ #endif /* AVUTIL_SHA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/sha512.h ================================================ /* * Copyright (C) 2007 Michael Niedermayer * Copyright (C) 2013 James Almer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu_sha512 * Public header for SHA-512 implementation. */ #ifndef AVUTIL_SHA512_H #define AVUTIL_SHA512_H #include #include #include "attributes.h" #include "version.h" /** * @defgroup lavu_sha512 SHA-512 * @ingroup lavu_hash * SHA-512 (Secure Hash Algorithm) hash function implementations. * * This module supports the following SHA-2 hash functions: * * - SHA-512/224: 224 bits * - SHA-512/256: 256 bits * - SHA-384: 384 bits * - SHA-512: 512 bits * * @see For SHA-1, SHA-256, and variants thereof, see @ref lavu_sha. * * @{ */ extern const int av_sha512_size; struct AVSHA512; /** * Allocate an AVSHA512 context. */ struct AVSHA512 *av_sha512_alloc(void); /** * Initialize SHA-2 512 hashing. * * @param context pointer to the function context (of size av_sha512_size) * @param bits number of bits in digest (224, 256, 384 or 512 bits) * @return zero if initialization succeeded, -1 otherwise */ int av_sha512_init(struct AVSHA512* context, int bits); /** * Update hash value. * * @param context hash function context * @param data input data to update hash with * @param len input data length */ #if FF_API_CRYPTO_SIZE_T void av_sha512_update(struct AVSHA512* context, const uint8_t* data, unsigned int len); #else void av_sha512_update(struct AVSHA512* context, const uint8_t* data, size_t len); #endif /** * Finish hashing and output digest value. * * @param context hash function context * @param digest buffer where output digest value is stored */ void av_sha512_final(struct AVSHA512* context, uint8_t *digest); /** * @} */ #endif /* AVUTIL_SHA512_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/spherical.h ================================================ /* * Copyright (c) 2016 Vittorio Giovara * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Spherical video */ #ifndef AVUTIL_SPHERICAL_H #define AVUTIL_SPHERICAL_H #include #include /** * @addtogroup lavu_video * @{ * * @defgroup lavu_video_spherical Spherical video mapping * @{ */ /** * @addtogroup lavu_video_spherical * A spherical video file contains surfaces that need to be mapped onto a * sphere. Depending on how the frame was converted, a different distortion * transformation or surface recomposition function needs to be applied before * the video should be mapped and displayed. */ /** * Projection of the video surface(s) on a sphere. */ enum AVSphericalProjection { /** * Video represents a sphere mapped on a flat surface using * equirectangular projection. */ AV_SPHERICAL_EQUIRECTANGULAR, /** * Video frame is split into 6 faces of a cube, and arranged on a * 3x2 layout. Faces are oriented upwards for the front, left, right, * and back faces. The up face is oriented so the top of the face is * forwards and the down face is oriented so the top of the face is * to the back. */ AV_SPHERICAL_CUBEMAP, /** * Video represents a portion of a sphere mapped on a flat surface * using equirectangular projection. The @ref bounding fields indicate * the position of the current video in a larger surface. */ AV_SPHERICAL_EQUIRECTANGULAR_TILE, }; /** * This structure describes how to handle spherical videos, outlining * information about projection, initial layout, and any other view modifier. * * @note The struct must be allocated with av_spherical_alloc() and * its size is not a part of the public ABI. */ typedef struct AVSphericalMapping { /** * Projection type. */ enum AVSphericalProjection projection; /** * @name Initial orientation * @{ * There fields describe additional rotations applied to the sphere after * the video frame is mapped onto it. The sphere is rotated around the * viewer, who remains stationary. The order of transformation is always * yaw, followed by pitch, and finally by roll. * * The coordinate system matches the one defined in OpenGL, where the * forward vector (z) is coming out of screen, and it is equivalent to * a rotation matrix of R = r_y(yaw) * r_x(pitch) * r_z(roll). * * A positive yaw rotates the portion of the sphere in front of the viewer * toward their right. A positive pitch rotates the portion of the sphere * in front of the viewer upwards. A positive roll tilts the portion of * the sphere in front of the viewer to the viewer's right. * * These values are exported as 16.16 fixed point. * * See this equirectangular projection as example: * * @code{.unparsed} * Yaw * -180 0 180 * 90 +-------------+-------------+ 180 * | | | up * P | | | y| forward * i | ^ | | /z * t 0 +-------------X-------------+ 0 Roll | / * c | | | | / * h | | | 0|/_____right * | | | x * -90 +-------------+-------------+ -180 * * X - the default camera center * ^ - the default up vector * @endcode */ int32_t yaw; ///< Rotation around the up vector [-180, 180]. int32_t pitch; ///< Rotation around the right vector [-90, 90]. int32_t roll; ///< Rotation around the forward vector [-180, 180]. /** * @} */ /** * @name Bounding rectangle * @anchor bounding * @{ * These fields indicate the location of the current tile, and where * it should be mapped relative to the original surface. They are * exported as 0.32 fixed point, and can be converted to classic * pixel values with av_spherical_bounds(). * * @code{.unparsed} * +----------------+----------+ * | |bound_top | * | +--------+ | * | bound_left |tile | | * +<---------->| |<--->+bound_right * | +--------+ | * | | | * | bound_bottom| | * +----------------+----------+ * @endcode * * If needed, the original video surface dimensions can be derived * by adding the current stream or frame size to the related bounds, * like in the following example: * * @code{c} * original_width = tile->width + bound_left + bound_right; * original_height = tile->height + bound_top + bound_bottom; * @endcode * * @note These values are valid only for the tiled equirectangular * projection type (@ref AV_SPHERICAL_EQUIRECTANGULAR_TILE), * and should be ignored in all other cases. */ uint32_t bound_left; ///< Distance from the left edge uint32_t bound_top; ///< Distance from the top edge uint32_t bound_right; ///< Distance from the right edge uint32_t bound_bottom; ///< Distance from the bottom edge /** * @} */ /** * Number of pixels to pad from the edge of each cube face. * * @note This value is valid for only for the cubemap projection type * (@ref AV_SPHERICAL_CUBEMAP), and should be ignored in all other * cases. */ uint32_t padding; } AVSphericalMapping; /** * Allocate a AVSphericalVideo structure and initialize its fields to default * values. * * @return the newly allocated struct or NULL on failure */ AVSphericalMapping *av_spherical_alloc(size_t *size); /** * Convert the @ref bounding fields from an AVSphericalVideo * from 0.32 fixed point to pixels. * * @param map The AVSphericalVideo map to read bound values from. * @param width Width of the current frame or stream. * @param height Height of the current frame or stream. * @param left Pixels from the left edge. * @param top Pixels from the top edge. * @param right Pixels from the right edge. * @param bottom Pixels from the bottom edge. */ void av_spherical_tile_bounds(const AVSphericalMapping *map, size_t width, size_t height, size_t *left, size_t *top, size_t *right, size_t *bottom); /** * Provide a human-readable name of a given AVSphericalProjection. * * @param projection The input AVSphericalProjection. * * @return The name of the AVSphericalProjection, or "unknown". */ const char *av_spherical_projection_name(enum AVSphericalProjection projection); /** * Get the AVSphericalProjection form a human-readable name. * * @param name The input string. * * @return The AVSphericalProjection value, or -1 if not found. */ int av_spherical_from_name(const char *name); /** * @} * @} */ #endif /* AVUTIL_SPHERICAL_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/stereo3d.h ================================================ /* * Copyright (c) 2013 Vittorio Giovara * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Stereoscopic video */ #ifndef AVUTIL_STEREO3D_H #define AVUTIL_STEREO3D_H #include #include "frame.h" /** * @addtogroup lavu_video * @{ * * @defgroup lavu_video_stereo3d Stereo3D types and functions * @{ */ /** * @addtogroup lavu_video_stereo3d * A stereoscopic video file consists in multiple views embedded in a single * frame, usually describing two views of a scene. This file describes all * possible codec-independent view arrangements. * */ /** * List of possible 3D Types */ enum AVStereo3DType { /** * Video is not stereoscopic (and metadata has to be there). */ AV_STEREO3D_2D, /** * Views are next to each other. * * @code{.unparsed} * LLLLRRRR * LLLLRRRR * LLLLRRRR * ... * @endcode */ AV_STEREO3D_SIDEBYSIDE, /** * Views are on top of each other. * * @code{.unparsed} * LLLLLLLL * LLLLLLLL * RRRRRRRR * RRRRRRRR * @endcode */ AV_STEREO3D_TOPBOTTOM, /** * Views are alternated temporally. * * @code{.unparsed} * frame0 frame1 frame2 ... * LLLLLLLL RRRRRRRR LLLLLLLL * LLLLLLLL RRRRRRRR LLLLLLLL * LLLLLLLL RRRRRRRR LLLLLLLL * ... ... ... * @endcode */ AV_STEREO3D_FRAMESEQUENCE, /** * Views are packed in a checkerboard-like structure per pixel. * * @code{.unparsed} * LRLRLRLR * RLRLRLRL * LRLRLRLR * ... * @endcode */ AV_STEREO3D_CHECKERBOARD, /** * Views are next to each other, but when upscaling * apply a checkerboard pattern. * * @code{.unparsed} * LLLLRRRR L L L L R R R R * LLLLRRRR => L L L L R R R R * LLLLRRRR L L L L R R R R * LLLLRRRR L L L L R R R R * @endcode */ AV_STEREO3D_SIDEBYSIDE_QUINCUNX, /** * Views are packed per line, as if interlaced. * * @code{.unparsed} * LLLLLLLL * RRRRRRRR * LLLLLLLL * ... * @endcode */ AV_STEREO3D_LINES, /** * Views are packed per column. * * @code{.unparsed} * LRLRLRLR * LRLRLRLR * LRLRLRLR * ... * @endcode */ AV_STEREO3D_COLUMNS, }; /** * List of possible view types. */ enum AVStereo3DView { /** * Frame contains two packed views. */ AV_STEREO3D_VIEW_PACKED, /** * Frame contains only the left view. */ AV_STEREO3D_VIEW_LEFT, /** * Frame contains only the right view. */ AV_STEREO3D_VIEW_RIGHT, }; /** * Inverted views, Right/Bottom represents the left view. */ #define AV_STEREO3D_FLAG_INVERT (1 << 0) /** * Stereo 3D type: this structure describes how two videos are packed * within a single video surface, with additional information as needed. * * @note The struct must be allocated with av_stereo3d_alloc() and * its size is not a part of the public ABI. */ typedef struct AVStereo3D { /** * How views are packed within the video. */ enum AVStereo3DType type; /** * Additional information about the frame packing. */ int flags; /** * Determines which views are packed. */ enum AVStereo3DView view; } AVStereo3D; /** * Allocate an AVStereo3D structure and set its fields to default values. * The resulting struct can be freed using av_freep(). * * @return An AVStereo3D filled with default values or NULL on failure. */ AVStereo3D *av_stereo3d_alloc(void); /** * Allocate a complete AVFrameSideData and add it to the frame. * * @param frame The frame which side data is added to. * * @return The AVStereo3D structure to be filled by caller. */ AVStereo3D *av_stereo3d_create_side_data(AVFrame *frame); /** * Provide a human-readable name of a given stereo3d type. * * @param type The input stereo3d type value. * * @return The name of the stereo3d value, or "unknown". */ const char *av_stereo3d_type_name(unsigned int type); /** * Get the AVStereo3DType form a human-readable name. * * @param name The input string. * * @return The AVStereo3DType value, or -1 if not found. */ int av_stereo3d_from_name(const char *name); /** * @} * @} */ #endif /* AVUTIL_STEREO3D_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/tea.h ================================================ /* * A 32-bit implementation of the TEA algorithm * Copyright (c) 2015 Vesselin Bontchev * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_TEA_H #define AVUTIL_TEA_H #include /** * @file * @brief Public header for libavutil TEA algorithm * @defgroup lavu_tea TEA * @ingroup lavu_crypto * @{ */ extern const int av_tea_size; struct AVTEA; /** * Allocate an AVTEA context * To free the struct: av_free(ptr) */ struct AVTEA *av_tea_alloc(void); /** * Initialize an AVTEA context. * * @param ctx an AVTEA context * @param key a key of 16 bytes used for encryption/decryption * @param rounds the number of rounds in TEA (64 is the "standard") */ void av_tea_init(struct AVTEA *ctx, const uint8_t key[16], int rounds); /** * Encrypt or decrypt a buffer using a previously initialized context. * * @param ctx an AVTEA context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param iv initialization vector for CBC mode, if NULL then ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_tea_crypt(struct AVTEA *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_TEA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/threadmessage.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_THREADMESSAGE_H #define AVUTIL_THREADMESSAGE_H typedef struct AVThreadMessageQueue AVThreadMessageQueue; typedef enum AVThreadMessageFlags { /** * Perform non-blocking operation. * If this flag is set, send and recv operations are non-blocking and * return AVERROR(EAGAIN) immediately if they can not proceed. */ AV_THREAD_MESSAGE_NONBLOCK = 1, } AVThreadMessageFlags; /** * Allocate a new message queue. * * @param mq pointer to the message queue * @param nelem maximum number of elements in the queue * @param elsize size of each element in the queue * @return >=0 for success; <0 for error, in particular AVERROR(ENOSYS) if * lavu was built without thread support */ int av_thread_message_queue_alloc(AVThreadMessageQueue **mq, unsigned nelem, unsigned elsize); /** * Free a message queue. * * The message queue must no longer be in use by another thread. */ void av_thread_message_queue_free(AVThreadMessageQueue **mq); /** * Send a message on the queue. */ int av_thread_message_queue_send(AVThreadMessageQueue *mq, void *msg, unsigned flags); /** * Receive a message from the queue. */ int av_thread_message_queue_recv(AVThreadMessageQueue *mq, void *msg, unsigned flags); /** * Set the sending error code. * * If the error code is set to non-zero, av_thread_message_queue_send() will * return it immediately. Conventional values, such as AVERROR_EOF or * AVERROR(EAGAIN), can be used to cause the sending thread to stop or * suspend its operation. */ void av_thread_message_queue_set_err_send(AVThreadMessageQueue *mq, int err); /** * Set the receiving error code. * * If the error code is set to non-zero, av_thread_message_queue_recv() will * return it immediately when there are no longer available messages. * Conventional values, such as AVERROR_EOF or AVERROR(EAGAIN), can be used * to cause the receiving thread to stop or suspend its operation. */ void av_thread_message_queue_set_err_recv(AVThreadMessageQueue *mq, int err); /** * Set the optional free message callback function which will be called if an * operation is removing messages from the queue. */ void av_thread_message_queue_set_free_func(AVThreadMessageQueue *mq, void (*free_func)(void *msg)); /** * Return the current number of messages in the queue. * * @return the current number of messages or AVERROR(ENOSYS) if lavu was built * without thread support */ int av_thread_message_queue_nb_elems(AVThreadMessageQueue *mq); /** * Flush the message queue * * This function is mostly equivalent to reading and free-ing every message * except that it will be done in a single operation (no lock/unlock between * reads). */ void av_thread_message_flush(AVThreadMessageQueue *mq); #endif /* AVUTIL_THREADMESSAGE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/time.h ================================================ /* * Copyright (c) 2000-2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_TIME_H #define AVUTIL_TIME_H #include /** * Get the current time in microseconds. */ int64_t av_gettime(void); /** * Get the current time in microseconds since some unspecified starting point. * On platforms that support it, the time comes from a monotonic clock * This property makes this time source ideal for measuring relative time. * The returned values may not be monotonic on platforms where a monotonic * clock is not available. */ int64_t av_gettime_relative(void); /** * Indicates with a boolean result if the av_gettime_relative() time source * is monotonic. */ int av_gettime_relative_is_monotonic(void); /** * Sleep for a period of time. Although the duration is expressed in * microseconds, the actual delay may be rounded to the precision of the * system timer. * * @param usec Number of microseconds to sleep. * @return zero on success or (negative) error code. */ int av_usleep(unsigned usec); #endif /* AVUTIL_TIME_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/timecode.h ================================================ /* * Copyright (c) 2006 Smartjog S.A.S, Baptiste Coudurier * Copyright (c) 2011-2012 Smartjog S.A.S, Clément Bœsch * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Timecode helpers header */ #ifndef AVUTIL_TIMECODE_H #define AVUTIL_TIMECODE_H #include #include "rational.h" #define AV_TIMECODE_STR_SIZE 23 enum AVTimecodeFlag { AV_TIMECODE_FLAG_DROPFRAME = 1<<0, ///< timecode is drop frame AV_TIMECODE_FLAG_24HOURSMAX = 1<<1, ///< timecode wraps after 24 hours AV_TIMECODE_FLAG_ALLOWNEGATIVE = 1<<2, ///< negative time values are allowed }; typedef struct { int start; ///< timecode frame start (first base frame number) uint32_t flags; ///< flags such as drop frame, +24 hours support, ... AVRational rate; ///< frame rate in rational form unsigned fps; ///< frame per second; must be consistent with the rate field } AVTimecode; /** * Adjust frame number for NTSC drop frame time code. * * @param framenum frame number to adjust * @param fps frame per second, 30 or 60 * @return adjusted frame number * @warning adjustment is only valid in NTSC 29.97 and 59.94 */ int av_timecode_adjust_ntsc_framenum2(int framenum, int fps); /** * Convert frame number to SMPTE 12M binary representation. * * @param tc timecode data correctly initialized * @param framenum frame number * @return the SMPTE binary representation * * @note Frame number adjustment is automatically done in case of drop timecode, * you do NOT have to call av_timecode_adjust_ntsc_framenum2(). * @note The frame number is relative to tc->start. * @note Color frame (CF), binary group flags (BGF) and biphase mark polarity * correction (PC) bits are set to zero. */ uint32_t av_timecode_get_smpte_from_framenum(const AVTimecode *tc, int framenum); /** * Load timecode string in buf. * * @param buf destination buffer, must be at least AV_TIMECODE_STR_SIZE long * @param tc timecode data correctly initialized * @param framenum frame number * @return the buf parameter * * @note Timecode representation can be a negative timecode and have more than * 24 hours, but will only be honored if the flags are correctly set. * @note The frame number is relative to tc->start. */ char *av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum); /** * Get the timecode string from the SMPTE timecode format. * * @param buf destination buffer, must be at least AV_TIMECODE_STR_SIZE long * @param tcsmpte the 32-bit SMPTE timecode * @param prevent_df prevent the use of a drop flag when it is known the DF bit * is arbitrary * @return the buf parameter */ char *av_timecode_make_smpte_tc_string(char *buf, uint32_t tcsmpte, int prevent_df); /** * Get the timecode string from the 25-bit timecode format (MPEG GOP format). * * @param buf destination buffer, must be at least AV_TIMECODE_STR_SIZE long * @param tc25bit the 25-bits timecode * @return the buf parameter */ char *av_timecode_make_mpeg_tc_string(char *buf, uint32_t tc25bit); /** * Init a timecode struct with the passed parameters. * * @param log_ctx a pointer to an arbitrary struct of which the first field * is a pointer to an AVClass struct (used for av_log) * @param tc pointer to an allocated AVTimecode * @param rate frame rate in rational form * @param flags miscellaneous flags such as drop frame, +24 hours, ... * (see AVTimecodeFlag) * @param frame_start the first frame number * @return 0 on success, AVERROR otherwise */ int av_timecode_init(AVTimecode *tc, AVRational rate, int flags, int frame_start, void *log_ctx); /** * Parse timecode representation (hh:mm:ss[:;.]ff). * * @param log_ctx a pointer to an arbitrary struct of which the first field is a * pointer to an AVClass struct (used for av_log). * @param tc pointer to an allocated AVTimecode * @param rate frame rate in rational form * @param str timecode string which will determine the frame start * @return 0 on success, AVERROR otherwise */ int av_timecode_init_from_string(AVTimecode *tc, AVRational rate, const char *str, void *log_ctx); /** * Check if the timecode feature is available for the given frame rate * * @return 0 if supported, <0 otherwise */ int av_timecode_check_frame_rate(AVRational rate); #endif /* AVUTIL_TIMECODE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/timestamp.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * timestamp utils, mostly useful for debugging/logging purposes */ #ifndef AVUTIL_TIMESTAMP_H #define AVUTIL_TIMESTAMP_H #include "common.h" #if defined(__cplusplus) && !defined(__STDC_FORMAT_MACROS) && !defined(PRId64) #error missing -D__STDC_FORMAT_MACROS / #define __STDC_FORMAT_MACROS #endif #define AV_TS_MAX_STRING_SIZE 32 /** * Fill the provided buffer with a string containing a timestamp * representation. * * @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE * @param ts the timestamp to represent * @return the buffer in input */ static inline char *av_ts_make_string(char *buf, int64_t ts) { if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS"); else snprintf(buf, AV_TS_MAX_STRING_SIZE, "%" PRId64, ts); return buf; } /** * Convenience macro, the return value should be used only directly in * function arguments but never stand-alone. */ #define av_ts2str(ts) av_ts_make_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts) /** * Fill the provided buffer with a string containing a timestamp time * representation. * * @param buf a buffer with size in bytes of at least AV_TS_MAX_STRING_SIZE * @param ts the timestamp to represent * @param tb the timebase of the timestamp * @return the buffer in input */ static inline char *av_ts_make_time_string(char *buf, int64_t ts, AVRational *tb) { if (ts == AV_NOPTS_VALUE) snprintf(buf, AV_TS_MAX_STRING_SIZE, "NOPTS"); else snprintf(buf, AV_TS_MAX_STRING_SIZE, "%.6g", av_q2d(*tb) * ts); return buf; } /** * Convenience macro, the return value should be used only directly in * function arguments but never stand-alone. */ #define av_ts2timestr(ts, tb) av_ts_make_time_string((char[AV_TS_MAX_STRING_SIZE]){0}, ts, tb) #endif /* AVUTIL_TIMESTAMP_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/tree.h ================================================ /* * copyright (c) 2006 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * A tree container. * @author Michael Niedermayer */ #ifndef AVUTIL_TREE_H #define AVUTIL_TREE_H #include "attributes.h" #include "version.h" /** * @addtogroup lavu_tree AVTree * @ingroup lavu_data * * Low-complexity tree container * * Insertion, removal, finding equal, largest which is smaller than and * smallest which is larger than, all have O(log n) worst-case complexity. * @{ */ struct AVTreeNode; extern const int av_tree_node_size; /** * Allocate an AVTreeNode. */ struct AVTreeNode *av_tree_node_alloc(void); /** * Find an element. * @param root a pointer to the root node of the tree * @param next If next is not NULL, then next[0] will contain the previous * element and next[1] the next element. If either does not exist, * then the corresponding entry in next is unchanged. * @param cmp compare function used to compare elements in the tree, * API identical to that of Standard C's qsort * It is guaranteed that the first and only the first argument to cmp() * will be the key parameter to av_tree_find(), thus it could if the * user wants, be a different type (like an opaque context). * @return An element with cmp(key, elem) == 0 or NULL if no such element * exists in the tree. */ void *av_tree_find(const struct AVTreeNode *root, void *key, int (*cmp)(const void *key, const void *b), void *next[2]); /** * Insert or remove an element. * * If *next is NULL, then the supplied element will be removed if it exists. * If *next is non-NULL, then the supplied element will be inserted, unless * it already exists in the tree. * * @param rootp A pointer to a pointer to the root node of the tree; note that * the root node can change during insertions, this is required * to keep the tree balanced. * @param key pointer to the element key to insert in the tree * @param next Used to allocate and free AVTreeNodes. For insertion the user * must set it to an allocated and zeroed object of at least * av_tree_node_size bytes size. av_tree_insert() will set it to * NULL if it has been consumed. * For deleting elements *next is set to NULL by the user and * av_tree_insert() will set it to the AVTreeNode which was * used for the removed element. * This allows the use of flat arrays, which have * lower overhead compared to many malloced elements. * You might want to define a function like: * @code * void *tree_insert(struct AVTreeNode **rootp, void *key, * int (*cmp)(void *key, const void *b), * AVTreeNode **next) * { * if (!*next) * *next = av_mallocz(av_tree_node_size); * return av_tree_insert(rootp, key, cmp, next); * } * void *tree_remove(struct AVTreeNode **rootp, void *key, * int (*cmp)(void *key, const void *b, AVTreeNode **next)) * { * av_freep(next); * return av_tree_insert(rootp, key, cmp, next); * } * @endcode * @param cmp compare function used to compare elements in the tree, API identical * to that of Standard C's qsort * @return If no insertion happened, the found element; if an insertion or * removal happened, then either key or NULL will be returned. * Which one it is depends on the tree state and the implementation. You * should make no assumptions that it's one or the other in the code. */ void *av_tree_insert(struct AVTreeNode **rootp, void *key, int (*cmp)(const void *key, const void *b), struct AVTreeNode **next); void av_tree_destroy(struct AVTreeNode *t); /** * Apply enu(opaque, &elem) to all the elements in the tree in a given range. * * @param cmp a comparison function that returns < 0 for an element below the * range, > 0 for an element above the range and == 0 for an * element inside the range * * @note The cmp function should use the same ordering used to construct the * tree. */ void av_tree_enumerate(struct AVTreeNode *t, void *opaque, int (*cmp)(void *opaque, void *elem), int (*enu)(void *opaque, void *elem)); /** * @} */ #endif /* AVUTIL_TREE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/twofish.h ================================================ /* * An implementation of the TwoFish algorithm * Copyright (c) 2015 Supraja Meedinti * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_TWOFISH_H #define AVUTIL_TWOFISH_H #include /** * @file * @brief Public header for libavutil TWOFISH algorithm * @defgroup lavu_twofish TWOFISH * @ingroup lavu_crypto * @{ */ extern const int av_twofish_size; struct AVTWOFISH; /** * Allocate an AVTWOFISH context * To free the struct: av_free(ptr) */ struct AVTWOFISH *av_twofish_alloc(void); /** * Initialize an AVTWOFISH context. * * @param ctx an AVTWOFISH context * @param key a key of size ranging from 1 to 32 bytes used for encryption/decryption * @param key_bits number of keybits: 128, 192, 256 If less than the required, padded with zeroes to nearest valid value; return value is 0 if key_bits is 128/192/256, -1 if less than 0, 1 otherwise */ int av_twofish_init(struct AVTWOFISH *ctx, const uint8_t *key, int key_bits); /** * Encrypt or decrypt a buffer using a previously initialized context * * @param ctx an AVTWOFISH context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 16 byte blocks * @paran iv initialization vector for CBC mode, NULL for ECB mode * @param decrypt 0 for encryption, 1 for decryption */ void av_twofish_crypt(struct AVTWOFISH *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t* iv, int decrypt); /** * @} */ #endif /* AVUTIL_TWOFISH_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/tx.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_TX_H #define AVUTIL_TX_H #include #include typedef struct AVTXContext AVTXContext; typedef struct AVComplexFloat { float re, im; } AVComplexFloat; enum AVTXType { /** * Standard complex to complex FFT with sample data type AVComplexFloat. * Scaling currently unsupported */ AV_TX_FLOAT_FFT = 0, /** * Standard MDCT with sample data type of float and a scale type of * float. Length is the frame size, not the window size (which is 2x frame) */ AV_TX_FLOAT_MDCT = 1, }; /** * Function pointer to a function to perform the transform. * * @note Using a different context than the one allocated during av_tx_init() * is not allowed. * * @param s the transform context * @param out the output array * @param in the input array * @param stride the input or output stride (depending on transform direction) * in bytes, currently implemented for all MDCT transforms */ typedef void (*av_tx_fn)(AVTXContext *s, void *out, void *in, ptrdiff_t stride); /** * Initialize a transform context with the given configuration * Currently power of two lengths from 4 to 131072 are supported, along with * any length decomposable to a power of two and either 3, 5 or 15. * * @param ctx the context to allocate, will be NULL on error * @param tx pointer to the transform function pointer to set * @param type type the type of transform * @param inv whether to do an inverse or a forward transform * @param len the size of the transform in samples * @param scale pointer to the value to scale the output if supported by type * @param flags currently unused * * @return 0 on success, negative error code on failure */ int av_tx_init(AVTXContext **ctx, av_tx_fn *tx, enum AVTXType type, int inv, int len, const void *scale, uint64_t flags); /** * Frees a context and sets ctx to NULL, does nothing when ctx == NULL */ void av_tx_uninit(AVTXContext **ctx); #endif /* AVUTIL_TX_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/version.h ================================================ /* * copyright (c) 2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @ingroup lavu * Libavutil version macros */ #ifndef AVUTIL_VERSION_H #define AVUTIL_VERSION_H #include "macros.h" /** * @addtogroup version_utils * * Useful to check and match library version in order to maintain * backward compatibility. * * The FFmpeg libraries follow a versioning sheme very similar to * Semantic Versioning (http://semver.org/) * The difference is that the component called PATCH is called MICRO in FFmpeg * and its value is reset to 100 instead of 0 to keep it above or equal to 100. * Also we do not increase MICRO for every bugfix or change in git master. * * Prior to FFmpeg 3.2 point releases did not change any lib version number to * avoid aliassing different git master checkouts. * Starting with FFmpeg 3.2, the released library versions will occupy * a separate MAJOR.MINOR that is not used on the master development branch. * That is if we branch a release of master 55.10.123 we will bump to 55.11.100 * for the release and master will continue at 55.12.100 after it. Each new * point release will then bump the MICRO improving the usefulness of the lib * versions. * * @{ */ #define AV_VERSION_INT(a, b, c) ((a)<<16 | (b)<<8 | (c)) #define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c #define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c) /** * Extract version components from the full ::AV_VERSION_INT int as returned * by functions like ::avformat_version() and ::avcodec_version() */ #define AV_VERSION_MAJOR(a) ((a) >> 16) #define AV_VERSION_MINOR(a) (((a) & 0x00FF00) >> 8) #define AV_VERSION_MICRO(a) ((a) & 0xFF) /** * @} */ /** * @defgroup lavu_ver Version and Build diagnostics * * Macros and function useful to check at compiletime and at runtime * which version of libavutil is in use. * * @{ */ #define LIBAVUTIL_VERSION_MAJOR 56 #define LIBAVUTIL_VERSION_MINOR 31 #define LIBAVUTIL_VERSION_MICRO 100 #define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_VERSION AV_VERSION(LIBAVUTIL_VERSION_MAJOR, \ LIBAVUTIL_VERSION_MINOR, \ LIBAVUTIL_VERSION_MICRO) #define LIBAVUTIL_BUILD LIBAVUTIL_VERSION_INT #define LIBAVUTIL_IDENT "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION) /** * @defgroup lavu_depr_guards Deprecation Guards * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. * * @note, when bumping the major version it is recommended to manually * disable each FF_API_* in its own commit instead of disabling them all * at once through the bump. This improves the git bisect-ability of the change. * * @{ */ #ifndef FF_API_VAAPI #define FF_API_VAAPI (LIBAVUTIL_VERSION_MAJOR < 57) #endif #ifndef FF_API_FRAME_QP #define FF_API_FRAME_QP (LIBAVUTIL_VERSION_MAJOR < 57) #endif #ifndef FF_API_PLUS1_MINUS1 #define FF_API_PLUS1_MINUS1 (LIBAVUTIL_VERSION_MAJOR < 57) #endif #ifndef FF_API_ERROR_FRAME #define FF_API_ERROR_FRAME (LIBAVUTIL_VERSION_MAJOR < 57) #endif #ifndef FF_API_PKT_PTS #define FF_API_PKT_PTS (LIBAVUTIL_VERSION_MAJOR < 57) #endif #ifndef FF_API_CRYPTO_SIZE_T #define FF_API_CRYPTO_SIZE_T (LIBAVUTIL_VERSION_MAJOR < 57) #endif #ifndef FF_API_FRAME_GET_SET #define FF_API_FRAME_GET_SET (LIBAVUTIL_VERSION_MAJOR < 57) #endif #ifndef FF_API_PSEUDOPAL #define FF_API_PSEUDOPAL (LIBAVUTIL_VERSION_MAJOR < 57) #endif /** * @} * @} */ #endif /* AVUTIL_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libavutil/xtea.h ================================================ /* * A 32-bit implementation of the XTEA algorithm * Copyright (c) 2012 Samuel Pitoiset * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AVUTIL_XTEA_H #define AVUTIL_XTEA_H #include /** * @file * @brief Public header for libavutil XTEA algorithm * @defgroup lavu_xtea XTEA * @ingroup lavu_crypto * @{ */ typedef struct AVXTEA { uint32_t key[16]; } AVXTEA; /** * Allocate an AVXTEA context. */ AVXTEA *av_xtea_alloc(void); /** * Initialize an AVXTEA context. * * @param ctx an AVXTEA context * @param key a key of 16 bytes used for encryption/decryption, * interpreted as big endian 32 bit numbers */ void av_xtea_init(struct AVXTEA *ctx, const uint8_t key[16]); /** * Initialize an AVXTEA context. * * @param ctx an AVXTEA context * @param key a key of 16 bytes used for encryption/decryption, * interpreted as little endian 32 bit numbers */ void av_xtea_le_init(struct AVXTEA *ctx, const uint8_t key[16]); /** * Encrypt or decrypt a buffer using a previously initialized context, * in big endian format. * * @param ctx an AVXTEA context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param iv initialization vector for CBC mode, if NULL then ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_xtea_crypt(struct AVXTEA *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * Encrypt or decrypt a buffer using a previously initialized context, * in little endian format. * * @param ctx an AVXTEA context * @param dst destination array, can be equal to src * @param src source array, can be equal to dst * @param count number of 8 byte blocks * @param iv initialization vector for CBC mode, if NULL then ECB will be used * @param decrypt 0 for encryption, 1 for decryption */ void av_xtea_le_crypt(struct AVXTEA *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt); /** * @} */ #endif /* AVUTIL_XTEA_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libpostproc/postprocess.h ================================================ /* * Copyright (C) 2001-2003 Michael Niedermayer (michaelni@gmx.at) * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef POSTPROC_POSTPROCESS_H #define POSTPROC_POSTPROCESS_H /** * @file * @ingroup lpp * external API header */ /** * @defgroup lpp libpostproc * Video postprocessing library. * * @{ */ #include "libpostproc/version.h" /** * Return the LIBPOSTPROC_VERSION_INT constant. */ unsigned postproc_version(void); /** * Return the libpostproc build-time configuration. */ const char *postproc_configuration(void); /** * Return the libpostproc license. */ const char *postproc_license(void); #define PP_QUALITY_MAX 6 #include typedef void pp_context; typedef void pp_mode; #if LIBPOSTPROC_VERSION_INT < (52<<16) typedef pp_context pp_context_t; typedef pp_mode pp_mode_t; extern const char *const pp_help; ///< a simple help text #else extern const char pp_help[]; ///< a simple help text #endif void pp_postprocess(const uint8_t * src[3], const int srcStride[3], uint8_t * dst[3], const int dstStride[3], int horizontalSize, int verticalSize, const int8_t *QP_store, int QP_stride, pp_mode *mode, pp_context *ppContext, int pict_type); /** * Return a pp_mode or NULL if an error occurred. * * @param name the string after "-pp" on the command line * @param quality a number from 0 to PP_QUALITY_MAX */ pp_mode *pp_get_mode_by_name_and_quality(const char *name, int quality); void pp_free_mode(pp_mode *mode); pp_context *pp_get_context(int width, int height, int flags); void pp_free_context(pp_context *ppContext); #define PP_CPU_CAPS_MMX 0x80000000 #define PP_CPU_CAPS_MMX2 0x20000000 #define PP_CPU_CAPS_3DNOW 0x40000000 #define PP_CPU_CAPS_ALTIVEC 0x10000000 #define PP_CPU_CAPS_AUTO 0x00080000 #define PP_FORMAT 0x00000008 #define PP_FORMAT_420 (0x00000011|PP_FORMAT) #define PP_FORMAT_422 (0x00000001|PP_FORMAT) #define PP_FORMAT_411 (0x00000002|PP_FORMAT) #define PP_FORMAT_444 (0x00000000|PP_FORMAT) #define PP_FORMAT_440 (0x00000010|PP_FORMAT) #define PP_PICT_TYPE_QP2 0x00000010 ///< MPEG2 style QScale /** * @} */ #endif /* POSTPROC_POSTPROCESS_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libpostproc/version.h ================================================ /* * Version macros. * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef POSTPROC_VERSION_H #define POSTPROC_VERSION_H /** * @file * Libpostproc version macros */ #include "libavutil/avutil.h" #define LIBPOSTPROC_VERSION_MAJOR 55 #define LIBPOSTPROC_VERSION_MINOR 5 #define LIBPOSTPROC_VERSION_MICRO 100 #define LIBPOSTPROC_VERSION_INT AV_VERSION_INT(LIBPOSTPROC_VERSION_MAJOR, \ LIBPOSTPROC_VERSION_MINOR, \ LIBPOSTPROC_VERSION_MICRO) #define LIBPOSTPROC_VERSION AV_VERSION(LIBPOSTPROC_VERSION_MAJOR, \ LIBPOSTPROC_VERSION_MINOR, \ LIBPOSTPROC_VERSION_MICRO) #define LIBPOSTPROC_BUILD LIBPOSTPROC_VERSION_INT #define LIBPOSTPROC_IDENT "postproc" AV_STRINGIFY(LIBPOSTPROC_VERSION) #endif /* POSTPROC_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libswresample/swresample.h ================================================ /* * Copyright (C) 2011-2013 Michael Niedermayer (michaelni@gmx.at) * * This file is part of libswresample * * libswresample 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. * * libswresample is distributed in the hope that 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 libswresample; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWRESAMPLE_SWRESAMPLE_H #define SWRESAMPLE_SWRESAMPLE_H /** * @file * @ingroup lswr * libswresample public header */ /** * @defgroup lswr libswresample * @{ * * Audio resampling, sample format conversion and mixing library. * * Interaction with lswr is done through SwrContext, which is * allocated with swr_alloc() or swr_alloc_set_opts(). It is opaque, so all parameters * must be set with the @ref avoptions API. * * The first thing you will need to do in order to use lswr is to allocate * SwrContext. This can be done with swr_alloc() or swr_alloc_set_opts(). If you * are using the former, you must set options through the @ref avoptions API. * The latter function provides the same feature, but it allows you to set some * common options in the same statement. * * For example the following code will setup conversion from planar float sample * format to interleaved signed 16-bit integer, downsampling from 48kHz to * 44.1kHz and downmixing from 5.1 channels to stereo (using the default mixing * matrix). This is using the swr_alloc() function. * @code * SwrContext *swr = swr_alloc(); * av_opt_set_channel_layout(swr, "in_channel_layout", AV_CH_LAYOUT_5POINT1, 0); * av_opt_set_channel_layout(swr, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0); * av_opt_set_int(swr, "in_sample_rate", 48000, 0); * av_opt_set_int(swr, "out_sample_rate", 44100, 0); * av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0); * av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0); * @endcode * * The same job can be done using swr_alloc_set_opts() as well: * @code * SwrContext *swr = swr_alloc_set_opts(NULL, // we're allocating a new context * AV_CH_LAYOUT_STEREO, // out_ch_layout * AV_SAMPLE_FMT_S16, // out_sample_fmt * 44100, // out_sample_rate * AV_CH_LAYOUT_5POINT1, // in_ch_layout * AV_SAMPLE_FMT_FLTP, // in_sample_fmt * 48000, // in_sample_rate * 0, // log_offset * NULL); // log_ctx * @endcode * * Once all values have been set, it must be initialized with swr_init(). If * you need to change the conversion parameters, you can change the parameters * using @ref AVOptions, as described above in the first example; or by using * swr_alloc_set_opts(), but with the first argument the allocated context. * You must then call swr_init() again. * * The conversion itself is done by repeatedly calling swr_convert(). * Note that the samples may get buffered in swr if you provide insufficient * output space or if sample rate conversion is done, which requires "future" * samples. Samples that do not require future input can be retrieved at any * time by using swr_convert() (in_count can be set to 0). * At the end of conversion the resampling buffer can be flushed by calling * swr_convert() with NULL in and 0 in_count. * * The samples used in the conversion process can be managed with the libavutil * @ref lavu_sampmanip "samples manipulation" API, including av_samples_alloc() * function used in the following example. * * The delay between input and output, can at any time be found by using * swr_get_delay(). * * The following code demonstrates the conversion loop assuming the parameters * from above and caller-defined functions get_input() and handle_output(): * @code * uint8_t **input; * int in_samples; * * while (get_input(&input, &in_samples)) { * uint8_t *output; * int out_samples = av_rescale_rnd(swr_get_delay(swr, 48000) + * in_samples, 44100, 48000, AV_ROUND_UP); * av_samples_alloc(&output, NULL, 2, out_samples, * AV_SAMPLE_FMT_S16, 0); * out_samples = swr_convert(swr, &output, out_samples, * input, in_samples); * handle_output(output, out_samples); * av_freep(&output); * } * @endcode * * When the conversion is finished, the conversion * context and everything associated with it must be freed with swr_free(). * A swr_close() function is also available, but it exists mainly for * compatibility with libavresample, and is not required to be called. * * There will be no memory leak if the data is not completely flushed before * swr_free(). */ #include #include "libavutil/channel_layout.h" #include "libavutil/frame.h" #include "libavutil/samplefmt.h" #include "libswresample/version.h" /** * @name Option constants * These constants are used for the @ref avoptions interface for lswr. * @{ * */ #define SWR_FLAG_RESAMPLE 1 ///< Force resampling even if equal sample rate //TODO use int resample ? //long term TODO can we enable this dynamically? /** Dithering algorithms */ enum SwrDitherType { SWR_DITHER_NONE = 0, SWR_DITHER_RECTANGULAR, SWR_DITHER_TRIANGULAR, SWR_DITHER_TRIANGULAR_HIGHPASS, SWR_DITHER_NS = 64, ///< not part of API/ABI SWR_DITHER_NS_LIPSHITZ, SWR_DITHER_NS_F_WEIGHTED, SWR_DITHER_NS_MODIFIED_E_WEIGHTED, SWR_DITHER_NS_IMPROVED_E_WEIGHTED, SWR_DITHER_NS_SHIBATA, SWR_DITHER_NS_LOW_SHIBATA, SWR_DITHER_NS_HIGH_SHIBATA, SWR_DITHER_NB, ///< not part of API/ABI }; /** Resampling Engines */ enum SwrEngine { SWR_ENGINE_SWR, /**< SW Resampler */ SWR_ENGINE_SOXR, /**< SoX Resampler */ SWR_ENGINE_NB, ///< not part of API/ABI }; /** Resampling Filter Types */ enum SwrFilterType { SWR_FILTER_TYPE_CUBIC, /**< Cubic */ SWR_FILTER_TYPE_BLACKMAN_NUTTALL, /**< Blackman Nuttall windowed sinc */ SWR_FILTER_TYPE_KAISER, /**< Kaiser windowed sinc */ }; /** * @} */ /** * The libswresample context. Unlike libavcodec and libavformat, this structure * is opaque. This means that if you would like to set options, you must use * the @ref avoptions API and cannot directly set values to members of the * structure. */ typedef struct SwrContext SwrContext; /** * Get the AVClass for SwrContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). * @return the AVClass of SwrContext */ const AVClass *swr_get_class(void); /** * @name SwrContext constructor functions * @{ */ /** * Allocate SwrContext. * * If you use this function you will need to set the parameters (manually or * with swr_alloc_set_opts()) before calling swr_init(). * * @see swr_alloc_set_opts(), swr_init(), swr_free() * @return NULL on error, allocated context otherwise */ struct SwrContext *swr_alloc(void); /** * Initialize context after user parameters have been set. * @note The context must be configured using the AVOption API. * * @see av_opt_set_int() * @see av_opt_set_dict() * * @param[in,out] s Swr context to initialize * @return AVERROR error code in case of failure. */ int swr_init(struct SwrContext *s); /** * Check whether an swr context has been initialized or not. * * @param[in] s Swr context to check * @see swr_init() * @return positive if it has been initialized, 0 if not initialized */ int swr_is_initialized(struct SwrContext *s); /** * Allocate SwrContext if needed and set/reset common parameters. * * This function does not require s to be allocated with swr_alloc(). On the * other hand, swr_alloc() can use swr_alloc_set_opts() to set the parameters * on the allocated context. * * @param s existing Swr context if available, or NULL if not * @param out_ch_layout output channel layout (AV_CH_LAYOUT_*) * @param out_sample_fmt output sample format (AV_SAMPLE_FMT_*). * @param out_sample_rate output sample rate (frequency in Hz) * @param in_ch_layout input channel layout (AV_CH_LAYOUT_*) * @param in_sample_fmt input sample format (AV_SAMPLE_FMT_*). * @param in_sample_rate input sample rate (frequency in Hz) * @param log_offset logging level offset * @param log_ctx parent logging context, can be NULL * * @see swr_init(), swr_free() * @return NULL on error, allocated context otherwise */ struct SwrContext *swr_alloc_set_opts(struct SwrContext *s, int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate, int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate, int log_offset, void *log_ctx); /** * @} * * @name SwrContext destructor functions * @{ */ /** * Free the given SwrContext and set the pointer to NULL. * * @param[in] s a pointer to a pointer to Swr context */ void swr_free(struct SwrContext **s); /** * Closes the context so that swr_is_initialized() returns 0. * * The context can be brought back to life by running swr_init(), * swr_init() can also be used without swr_close(). * This function is mainly provided for simplifying the usecase * where one tries to support libavresample and libswresample. * * @param[in,out] s Swr context to be closed */ void swr_close(struct SwrContext *s); /** * @} * * @name Core conversion functions * @{ */ /** Convert audio. * * in and in_count can be set to 0 to flush the last few samples out at the * end. * * If more input is provided than output space, then the input will be buffered. * You can avoid this buffering by using swr_get_out_samples() to retrieve an * upper bound on the required number of output samples for the given number of * input samples. Conversion will run directly without copying whenever possible. * * @param s allocated Swr context, with parameters set * @param out output buffers, only the first one need be set in case of packed audio * @param out_count amount of space available for output in samples per channel * @param in input buffers, only the first one need to be set in case of packed audio * @param in_count number of input samples available in one channel * * @return number of samples output per channel, negative value on error */ int swr_convert(struct SwrContext *s, uint8_t **out, int out_count, const uint8_t **in , int in_count); /** * Convert the next timestamp from input to output * timestamps are in 1/(in_sample_rate * out_sample_rate) units. * * @note There are 2 slightly differently behaving modes. * @li When automatic timestamp compensation is not used, (min_compensation >= FLT_MAX) * in this case timestamps will be passed through with delays compensated * @li When automatic timestamp compensation is used, (min_compensation < FLT_MAX) * in this case the output timestamps will match output sample numbers. * See ffmpeg-resampler(1) for the two modes of compensation. * * @param s[in] initialized Swr context * @param pts[in] timestamp for the next input sample, INT64_MIN if unknown * @see swr_set_compensation(), swr_drop_output(), and swr_inject_silence() are * function used internally for timestamp compensation. * @return the output timestamp for the next output sample */ int64_t swr_next_pts(struct SwrContext *s, int64_t pts); /** * @} * * @name Low-level option setting functions * These functons provide a means to set low-level options that is not possible * with the AVOption API. * @{ */ /** * Activate resampling compensation ("soft" compensation). This function is * internally called when needed in swr_next_pts(). * * @param[in,out] s allocated Swr context. If it is not initialized, * or SWR_FLAG_RESAMPLE is not set, swr_init() is * called with the flag set. * @param[in] sample_delta delta in PTS per sample * @param[in] compensation_distance number of samples to compensate for * @return >= 0 on success, AVERROR error codes if: * @li @c s is NULL, * @li @c compensation_distance is less than 0, * @li @c compensation_distance is 0 but sample_delta is not, * @li compensation unsupported by resampler, or * @li swr_init() fails when called. */ int swr_set_compensation(struct SwrContext *s, int sample_delta, int compensation_distance); /** * Set a customized input channel mapping. * * @param[in,out] s allocated Swr context, not yet initialized * @param[in] channel_map customized input channel mapping (array of channel * indexes, -1 for a muted channel) * @return >= 0 on success, or AVERROR error code in case of failure. */ int swr_set_channel_mapping(struct SwrContext *s, const int *channel_map); /** * Generate a channel mixing matrix. * * This function is the one used internally by libswresample for building the * default mixing matrix. It is made public just as a utility function for * building custom matrices. * * @param in_layout input channel layout * @param out_layout output channel layout * @param center_mix_level mix level for the center channel * @param surround_mix_level mix level for the surround channel(s) * @param lfe_mix_level mix level for the low-frequency effects channel * @param rematrix_maxval if 1.0, coefficients will be normalized to prevent * overflow. if INT_MAX, coefficients will not be * normalized. * @param[out] matrix mixing coefficients; matrix[i + stride * o] is * the weight of input channel i in output channel o. * @param stride distance between adjacent input channels in the * matrix array * @param matrix_encoding matrixed stereo downmix mode (e.g. dplii) * @param log_ctx parent logging context, can be NULL * @return 0 on success, negative AVERROR code on failure */ int swr_build_matrix(uint64_t in_layout, uint64_t out_layout, double center_mix_level, double surround_mix_level, double lfe_mix_level, double rematrix_maxval, double rematrix_volume, double *matrix, int stride, enum AVMatrixEncoding matrix_encoding, void *log_ctx); /** * Set a customized remix matrix. * * @param s allocated Swr context, not yet initialized * @param matrix remix coefficients; matrix[i + stride * o] is * the weight of input channel i in output channel o * @param stride offset between lines of the matrix * @return >= 0 on success, or AVERROR error code in case of failure. */ int swr_set_matrix(struct SwrContext *s, const double *matrix, int stride); /** * @} * * @name Sample handling functions * @{ */ /** * Drops the specified number of output samples. * * This function, along with swr_inject_silence(), is called by swr_next_pts() * if needed for "hard" compensation. * * @param s allocated Swr context * @param count number of samples to be dropped * * @return >= 0 on success, or a negative AVERROR code on failure */ int swr_drop_output(struct SwrContext *s, int count); /** * Injects the specified number of silence samples. * * This function, along with swr_drop_output(), is called by swr_next_pts() * if needed for "hard" compensation. * * @param s allocated Swr context * @param count number of samples to be dropped * * @return >= 0 on success, or a negative AVERROR code on failure */ int swr_inject_silence(struct SwrContext *s, int count); /** * Gets the delay the next input sample will experience relative to the next output sample. * * Swresample can buffer data if more input has been provided than available * output space, also converting between sample rates needs a delay. * This function returns the sum of all such delays. * The exact delay is not necessarily an integer value in either input or * output sample rate. Especially when downsampling by a large value, the * output sample rate may be a poor choice to represent the delay, similarly * for upsampling and the input sample rate. * * @param s swr context * @param base timebase in which the returned delay will be: * @li if it's set to 1 the returned delay is in seconds * @li if it's set to 1000 the returned delay is in milliseconds * @li if it's set to the input sample rate then the returned * delay is in input samples * @li if it's set to the output sample rate then the returned * delay is in output samples * @li if it's the least common multiple of in_sample_rate and * out_sample_rate then an exact rounding-free delay will be * returned * @returns the delay in 1 / @c base units. */ int64_t swr_get_delay(struct SwrContext *s, int64_t base); /** * Find an upper bound on the number of samples that the next swr_convert * call will output, if called with in_samples of input samples. This * depends on the internal state, and anything changing the internal state * (like further swr_convert() calls) will may change the number of samples * swr_get_out_samples() returns for the same number of input samples. * * @param in_samples number of input samples. * @note any call to swr_inject_silence(), swr_convert(), swr_next_pts() * or swr_set_compensation() invalidates this limit * @note it is recommended to pass the correct available buffer size * to all functions like swr_convert() even if swr_get_out_samples() * indicates that less would be used. * @returns an upper bound on the number of samples that the next swr_convert * will output or a negative value to indicate an error */ int swr_get_out_samples(struct SwrContext *s, int in_samples); /** * @} * * @name Configuration accessors * @{ */ /** * Return the @ref LIBSWRESAMPLE_VERSION_INT constant. * * This is useful to check if the build-time libswresample has the same version * as the run-time one. * * @returns the unsigned int-typed version */ unsigned swresample_version(void); /** * Return the swr build-time configuration. * * @returns the build-time @c ./configure flags */ const char *swresample_configuration(void); /** * Return the swr license. * * @returns the license of libswresample, determined at build-time */ const char *swresample_license(void); /** * @} * * @name AVFrame based API * @{ */ /** * Convert the samples in the input AVFrame and write them to the output AVFrame. * * Input and output AVFrames must have channel_layout, sample_rate and format set. * * If the output AVFrame does not have the data pointers allocated the nb_samples * field will be set using av_frame_get_buffer() * is called to allocate the frame. * * The output AVFrame can be NULL or have fewer allocated samples than required. * In this case, any remaining samples not written to the output will be added * to an internal FIFO buffer, to be returned at the next call to this function * or to swr_convert(). * * If converting sample rate, there may be data remaining in the internal * resampling delay buffer. swr_get_delay() tells the number of * remaining samples. To get this data as output, call this function or * swr_convert() with NULL input. * * If the SwrContext configuration does not match the output and * input AVFrame settings the conversion does not take place and depending on * which AVFrame is not matching AVERROR_OUTPUT_CHANGED, AVERROR_INPUT_CHANGED * or the result of a bitwise-OR of them is returned. * * @see swr_delay() * @see swr_convert() * @see swr_get_delay() * * @param swr audio resample context * @param output output AVFrame * @param input input AVFrame * @return 0 on success, AVERROR on failure or nonmatching * configuration. */ int swr_convert_frame(SwrContext *swr, AVFrame *output, const AVFrame *input); /** * Configure or reconfigure the SwrContext using the information * provided by the AVFrames. * * The original resampling context is reset even on failure. * The function calls swr_close() internally if the context is open. * * @see swr_close(); * * @param swr audio resample context * @param output output AVFrame * @param input input AVFrame * @return 0 on success, AVERROR on failure. */ int swr_config_frame(SwrContext *swr, const AVFrame *out, const AVFrame *in); /** * @} * @} */ #endif /* SWRESAMPLE_SWRESAMPLE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libswresample/version.h ================================================ /* * Version macros. * * This file is part of libswresample * * libswresample 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. * * libswresample is distributed in the hope that 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 libswresample; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWRESAMPLE_VERSION_H #define SWRESAMPLE_VERSION_H /** * @file * Libswresample version macros */ #include "libavutil/avutil.h" #define LIBSWRESAMPLE_VERSION_MAJOR 3 #define LIBSWRESAMPLE_VERSION_MINOR 5 #define LIBSWRESAMPLE_VERSION_MICRO 100 #define LIBSWRESAMPLE_VERSION_INT AV_VERSION_INT(LIBSWRESAMPLE_VERSION_MAJOR, \ LIBSWRESAMPLE_VERSION_MINOR, \ LIBSWRESAMPLE_VERSION_MICRO) #define LIBSWRESAMPLE_VERSION AV_VERSION(LIBSWRESAMPLE_VERSION_MAJOR, \ LIBSWRESAMPLE_VERSION_MINOR, \ LIBSWRESAMPLE_VERSION_MICRO) #define LIBSWRESAMPLE_BUILD LIBSWRESAMPLE_VERSION_INT #define LIBSWRESAMPLE_IDENT "SwR" AV_STRINGIFY(LIBSWRESAMPLE_VERSION) #endif /* SWRESAMPLE_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libswscale/swscale.h ================================================ /* * Copyright (C) 2001-2011 Michael Niedermayer * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWSCALE_SWSCALE_H #define SWSCALE_SWSCALE_H /** * @file * @ingroup libsws * external API header */ #include #include "libavutil/avutil.h" #include "libavutil/log.h" #include "libavutil/pixfmt.h" #include "version.h" /** * @defgroup libsws libswscale * Color conversion and scaling library. * * @{ * * Return the LIBSWSCALE_VERSION_INT constant. */ unsigned swscale_version(void); /** * Return the libswscale build-time configuration. */ const char *swscale_configuration(void); /** * Return the libswscale license. */ const char *swscale_license(void); /* values for the flags, the stuff on the command line is different */ #define SWS_FAST_BILINEAR 1 #define SWS_BILINEAR 2 #define SWS_BICUBIC 4 #define SWS_X 8 #define SWS_POINT 0x10 #define SWS_AREA 0x20 #define SWS_BICUBLIN 0x40 #define SWS_GAUSS 0x80 #define SWS_SINC 0x100 #define SWS_LANCZOS 0x200 #define SWS_SPLINE 0x400 #define SWS_SRC_V_CHR_DROP_MASK 0x30000 #define SWS_SRC_V_CHR_DROP_SHIFT 16 #define SWS_PARAM_DEFAULT 123456 #define SWS_PRINT_INFO 0x1000 //the following 3 flags are not completely implemented //internal chrominance subsampling info #define SWS_FULL_CHR_H_INT 0x2000 //input subsampling info #define SWS_FULL_CHR_H_INP 0x4000 #define SWS_DIRECT_BGR 0x8000 #define SWS_ACCURATE_RND 0x40000 #define SWS_BITEXACT 0x80000 #define SWS_ERROR_DIFFUSION 0x800000 #define SWS_MAX_REDUCE_CUTOFF 0.002 #define SWS_CS_ITU709 1 #define SWS_CS_FCC 4 #define SWS_CS_ITU601 5 #define SWS_CS_ITU624 5 #define SWS_CS_SMPTE170M 5 #define SWS_CS_SMPTE240M 7 #define SWS_CS_DEFAULT 5 #define SWS_CS_BT2020 9 /** * Return a pointer to yuv<->rgb coefficients for the given colorspace * suitable for sws_setColorspaceDetails(). * * @param colorspace One of the SWS_CS_* macros. If invalid, * SWS_CS_DEFAULT is used. */ const int *sws_getCoefficients(int colorspace); // when used for filters they must have an odd number of elements // coeffs cannot be shared between vectors typedef struct SwsVector { double *coeff; ///< pointer to the list of coefficients int length; ///< number of coefficients in the vector } SwsVector; // vectors can be shared typedef struct SwsFilter { SwsVector *lumH; SwsVector *lumV; SwsVector *chrH; SwsVector *chrV; } SwsFilter; struct SwsContext; /** * Return a positive value if pix_fmt is a supported input format, 0 * otherwise. */ int sws_isSupportedInput(enum AVPixelFormat pix_fmt); /** * Return a positive value if pix_fmt is a supported output format, 0 * otherwise. */ int sws_isSupportedOutput(enum AVPixelFormat pix_fmt); /** * @param[in] pix_fmt the pixel format * @return a positive value if an endianness conversion for pix_fmt is * supported, 0 otherwise. */ int sws_isSupportedEndiannessConversion(enum AVPixelFormat pix_fmt); /** * Allocate an empty SwsContext. This must be filled and passed to * sws_init_context(). For filling see AVOptions, options.c and * sws_setColorspaceDetails(). */ struct SwsContext *sws_alloc_context(void); /** * Initialize the swscaler context sws_context. * * @return zero or positive value on success, a negative value on * error */ av_warn_unused_result int sws_init_context(struct SwsContext *sws_context, SwsFilter *srcFilter, SwsFilter *dstFilter); /** * Free the swscaler context swsContext. * If swsContext is NULL, then does nothing. */ void sws_freeContext(struct SwsContext *swsContext); /** * Allocate and return an SwsContext. You need it to perform * scaling/conversion operations using sws_scale(). * * @param srcW the width of the source image * @param srcH the height of the source image * @param srcFormat the source image format * @param dstW the width of the destination image * @param dstH the height of the destination image * @param dstFormat the destination image format * @param flags specify which algorithm and options to use for rescaling * @param param extra parameters to tune the used scaler * For SWS_BICUBIC param[0] and [1] tune the shape of the basis * function, param[0] tunes f(1) and param[1] f´(1) * For SWS_GAUSS param[0] tunes the exponent and thus cutoff * frequency * For SWS_LANCZOS param[0] tunes the width of the window function * @return a pointer to an allocated context, or NULL in case of error * @note this function is to be removed after a saner alternative is * written */ struct SwsContext *sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param); /** * Scale the image slice in srcSlice and put the resulting scaled * slice in the image in dst. A slice is a sequence of consecutive * rows in an image. * * Slices have to be provided in sequential order, either in * top-bottom or bottom-top order. If slices are provided in * non-sequential order the behavior of the function is undefined. * * @param c the scaling context previously created with * sws_getContext() * @param srcSlice the array containing the pointers to the planes of * the source slice * @param srcStride the array containing the strides for each plane of * the source image * @param srcSliceY the position in the source image of the slice to * process, that is the number (counted starting from * zero) in the image of the first row of the slice * @param srcSliceH the height of the source slice, that is the number * of rows in the slice * @param dst the array containing the pointers to the planes of * the destination image * @param dstStride the array containing the strides for each plane of * the destination image * @return the height of the output slice */ int sws_scale(struct SwsContext *c, const uint8_t *const srcSlice[], const int srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const int dstStride[]); /** * @param dstRange flag indicating the while-black range of the output (1=jpeg / 0=mpeg) * @param srcRange flag indicating the while-black range of the input (1=jpeg / 0=mpeg) * @param table the yuv2rgb coefficients describing the output yuv space, normally ff_yuv2rgb_coeffs[x] * @param inv_table the yuv2rgb coefficients describing the input yuv space, normally ff_yuv2rgb_coeffs[x] * @param brightness 16.16 fixed point brightness correction * @param contrast 16.16 fixed point contrast correction * @param saturation 16.16 fixed point saturation correction * @return -1 if not supported */ int sws_setColorspaceDetails(struct SwsContext *c, const int inv_table[4], int srcRange, const int table[4], int dstRange, int brightness, int contrast, int saturation); /** * @return -1 if not supported */ int sws_getColorspaceDetails(struct SwsContext *c, int **inv_table, int *srcRange, int **table, int *dstRange, int *brightness, int *contrast, int *saturation); /** * Allocate and return an uninitialized vector with length coefficients. */ SwsVector *sws_allocVec(int length); /** * Return a normalized Gaussian curve used to filter stuff * quality = 3 is high quality, lower is lower quality. */ SwsVector *sws_getGaussianVec(double variance, double quality); /** * Scale all the coefficients of a by the scalar value. */ void sws_scaleVec(SwsVector *a, double scalar); /** * Scale all the coefficients of a so that their sum equals height. */ void sws_normalizeVec(SwsVector *a, double height); #if FF_API_SWS_VECTOR attribute_deprecated SwsVector *sws_getConstVec(double c, int length); attribute_deprecated SwsVector *sws_getIdentityVec(void); attribute_deprecated void sws_convVec(SwsVector *a, SwsVector *b); attribute_deprecated void sws_addVec(SwsVector *a, SwsVector *b); attribute_deprecated void sws_subVec(SwsVector *a, SwsVector *b); attribute_deprecated void sws_shiftVec(SwsVector *a, int shift); attribute_deprecated SwsVector *sws_cloneVec(SwsVector *a); attribute_deprecated void sws_printVec2(SwsVector *a, AVClass *log_ctx, int log_level); #endif void sws_freeVec(SwsVector *a); SwsFilter *sws_getDefaultFilter(float lumaGBlur, float chromaGBlur, float lumaSharpen, float chromaSharpen, float chromaHShift, float chromaVShift, int verbose); void sws_freeFilter(SwsFilter *filter); /** * Check if context can be reused, otherwise reallocate a new one. * * If context is NULL, just calls sws_getContext() to get a new * context. Otherwise, checks if the parameters are the ones already * saved in context. If that is the case, returns the current * context. Otherwise, frees context and gets a new context with * the new parameters. * * Be warned that srcFilter and dstFilter are not checked, they * are assumed to remain the same. */ struct SwsContext *sws_getCachedContext(struct SwsContext *context, int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param); /** * Convert an 8-bit paletted frame into a frame with a color depth of 32 bits. * * The output frame will have the same packed format as the palette. * * @param src source frame buffer * @param dst destination frame buffer * @param num_pixels number of pixels to convert * @param palette array with [256] entries, which must match color arrangement (RGB or BGR) of src */ void sws_convertPalette8ToPacked32(const uint8_t *src, uint8_t *dst, int num_pixels, const uint8_t *palette); /** * Convert an 8-bit paletted frame into a frame with a color depth of 24 bits. * * With the palette format "ABCD", the destination frame ends up with the format "ABC". * * @param src source frame buffer * @param dst destination frame buffer * @param num_pixels number of pixels to convert * @param palette array with [256] entries, which must match color arrangement (RGB or BGR) of src */ void sws_convertPalette8ToPacked24(const uint8_t *src, uint8_t *dst, int num_pixels, const uint8_t *palette); /** * Get the AVClass for swsContext. It can be used in combination with * AV_OPT_SEARCH_FAKE_OBJ for examining options. * * @see av_opt_find(). */ const AVClass *sws_get_class(void); /** * @} */ #endif /* SWSCALE_SWSCALE_H */ ================================================ FILE: thirdLibs/ffmpeg/include/libswscale/version.h ================================================ /* * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg is distributed in the hope that 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SWSCALE_VERSION_H #define SWSCALE_VERSION_H /** * @file * swscale version macros */ #include "libavutil/version.h" #define LIBSWSCALE_VERSION_MAJOR 5 #define LIBSWSCALE_VERSION_MINOR 5 #define LIBSWSCALE_VERSION_MICRO 100 #define LIBSWSCALE_VERSION_INT AV_VERSION_INT(LIBSWSCALE_VERSION_MAJOR, \ LIBSWSCALE_VERSION_MINOR, \ LIBSWSCALE_VERSION_MICRO) #define LIBSWSCALE_VERSION AV_VERSION(LIBSWSCALE_VERSION_MAJOR, \ LIBSWSCALE_VERSION_MINOR, \ LIBSWSCALE_VERSION_MICRO) #define LIBSWSCALE_BUILD LIBSWSCALE_VERSION_INT #define LIBSWSCALE_IDENT "SwS" AV_STRINGIFY(LIBSWSCALE_VERSION) /** * FF_API_* defines may be placed below to indicate public API that will be * dropped at a future version bump. The defines themselves are not part of * the public API and may change, break or disappear at any time. */ #ifndef FF_API_SWS_VECTOR #define FF_API_SWS_VECTOR (LIBSWSCALE_VERSION_MAJOR < 6) #endif #endif /* SWSCALE_VERSION_H */ ================================================ FILE: thirdLibs/ffmpeg/libs/avcodec-58.def ================================================ EXPORTS av_ac3_parse_header av_adts_header_parse av_bitstream_filter_close av_bitstream_filter_filter av_bitstream_filter_init av_bitstream_filter_next av_bsf_alloc av_bsf_flush av_bsf_free av_bsf_get_by_name av_bsf_get_class av_bsf_get_null_filter av_bsf_init av_bsf_iterate av_bsf_list_alloc av_bsf_list_append av_bsf_list_append2 av_bsf_list_finalize av_bsf_list_free av_bsf_list_parse_str av_bsf_next av_bsf_receive_packet av_bsf_send_packet av_codec_ffversion av_codec_get_chroma_intra_matrix av_codec_get_codec_descriptor av_codec_get_codec_properties av_codec_get_lowres av_codec_get_max_lowres av_codec_get_pkt_timebase av_codec_get_seek_preroll av_codec_is_decoder av_codec_is_encoder av_codec_iterate av_codec_next av_codec_set_chroma_intra_matrix av_codec_set_codec_descriptor av_codec_set_lowres av_codec_set_pkt_timebase av_codec_set_seek_preroll av_copy_packet av_copy_packet_side_data av_cpb_properties_alloc av_d3d11va_alloc_context av_dct_calc av_dct_end av_dct_init av_dirac_parse_sequence_header av_dup_packet av_dv_codec_profile av_dv_codec_profile2 av_dv_frame_profile av_fast_padded_malloc av_fast_padded_mallocz av_fft_calc av_fft_end av_fft_init av_fft_permute av_free_packet av_get_audio_frame_duration av_get_audio_frame_duration2 av_get_bits_per_sample av_get_codec_tag_string av_get_exact_bits_per_sample av_get_pcm_codec av_get_profile_name av_grow_packet av_hwaccel_next av_imdct_calc av_imdct_half av_init_packet av_jni_get_java_vm av_jni_set_java_vm av_lockmgr_register av_mdct_calc av_mdct_end av_mdct_init av_mediacodec_alloc_context av_mediacodec_default_free av_mediacodec_default_init av_mediacodec_release_buffer av_mediacodec_render_buffer_at_time av_new_packet av_packet_add_side_data av_packet_alloc av_packet_clone av_packet_copy_props av_packet_free av_packet_free_side_data av_packet_from_data av_packet_get_side_data av_packet_make_refcounted av_packet_make_writable av_packet_merge_side_data av_packet_move_ref av_packet_new_side_data av_packet_pack_dictionary av_packet_ref av_packet_rescale_ts av_packet_shrink_side_data av_packet_side_data_name av_packet_split_side_data av_packet_unpack_dictionary av_packet_unref av_parser_change av_parser_close av_parser_init av_parser_iterate av_parser_next av_parser_parse2 av_picture_copy av_picture_crop av_picture_pad av_qsv_alloc_context av_rdft_calc av_rdft_end av_rdft_init av_register_bitstream_filter av_register_codec_parser av_register_hwaccel av_shrink_packet av_vorbis_parse_frame av_vorbis_parse_frame_flags av_vorbis_parse_free av_vorbis_parse_init av_vorbis_parse_reset av_xiphlacing avcodec_align_dimensions avcodec_align_dimensions2 avcodec_alloc_context3 avcodec_chroma_pos_to_enum avcodec_close avcodec_configuration avcodec_copy_context avcodec_dct_alloc avcodec_dct_get_class avcodec_dct_init avcodec_decode_audio4 avcodec_decode_subtitle2 avcodec_decode_video2 avcodec_default_execute avcodec_default_execute2 avcodec_default_get_buffer2 avcodec_default_get_format avcodec_descriptor_get avcodec_descriptor_get_by_name avcodec_descriptor_next avcodec_encode_audio2 avcodec_encode_subtitle avcodec_encode_video2 avcodec_enum_to_chroma_pos avcodec_fill_audio_frame avcodec_find_best_pix_fmt2 avcodec_find_best_pix_fmt_of_2 avcodec_find_best_pix_fmt_of_list avcodec_find_decoder avcodec_find_decoder_by_name avcodec_find_encoder avcodec_find_encoder_by_name avcodec_flush_buffers avcodec_free_context avcodec_get_chroma_sub_sample avcodec_get_class avcodec_get_context_defaults3 avcodec_get_frame_class avcodec_get_hw_config avcodec_get_hw_frames_parameters avcodec_get_name avcodec_get_pix_fmt_loss avcodec_get_subtitle_rect_class avcodec_get_type avcodec_is_open avcodec_license avcodec_open2 avcodec_parameters_alloc avcodec_parameters_copy avcodec_parameters_free avcodec_parameters_from_context avcodec_parameters_to_context avcodec_pix_fmt_to_codec_tag avcodec_profile_name avcodec_receive_frame avcodec_receive_packet avcodec_register avcodec_register_all avcodec_send_frame avcodec_send_packet avcodec_string avcodec_version avpicture_alloc avpicture_fill avpicture_free avpicture_get_size avpicture_layout avpriv_ac3_channel_layout_tab avpriv_ac3_parse_header avpriv_align_put_bits avpriv_bprint_to_extradata avpriv_codec2_mode_bit_rate avpriv_codec2_mode_block_align avpriv_codec2_mode_frame_size avpriv_codec_get_cap_skip_frame_fill_param avpriv_copy_bits avpriv_dca_convert_bitstream avpriv_dca_parse_core_frame_header avpriv_dca_sample_rates avpriv_dnxhd_get_frame_size avpriv_dnxhd_get_hr_frame_size avpriv_dnxhd_get_interlaced avpriv_do_elbg avpriv_exif_decode_ifd avpriv_find_pix_fmt avpriv_find_start_code avpriv_fits_header_init avpriv_fits_header_parse_line avpriv_get_raw_pix_fmt_tags avpriv_h264_has_num_reorder_frames avpriv_init_elbg avpriv_mjpeg_bits_ac_chrominance avpriv_mjpeg_bits_ac_luminance avpriv_mjpeg_bits_dc_chrominance avpriv_mjpeg_bits_dc_luminance avpriv_mjpeg_val_ac_chrominance avpriv_mjpeg_val_ac_luminance avpriv_mjpeg_val_dc avpriv_mpa_bitrate_tab avpriv_mpa_freq_tab avpriv_mpeg4audio_get_config avpriv_mpeg4audio_sample_rates avpriv_mpegaudio_decode_header avpriv_pix_fmt_bps_avi avpriv_pix_fmt_bps_mov avpriv_put_string avpriv_split_xiph_headers avpriv_tak_parse_streaminfo avpriv_toupper4 avsubtitle_free ================================================ FILE: thirdLibs/ffmpeg/libs/avdevice-58.def ================================================ EXPORTS av_device_capabilities av_device_ffversion av_input_audio_device_next av_input_video_device_next av_output_audio_device_next av_output_video_device_next avdevice_app_to_dev_control_message avdevice_capabilities_create avdevice_capabilities_free avdevice_configuration avdevice_dev_to_app_control_message avdevice_free_list_devices avdevice_license avdevice_list_devices avdevice_list_input_sources avdevice_list_output_sinks avdevice_register_all avdevice_version ================================================ FILE: thirdLibs/ffmpeg/libs/avfilter-7.def ================================================ EXPORTS av_abuffersink_params_alloc av_buffersink_get_channel_layout av_buffersink_get_channels av_buffersink_get_format av_buffersink_get_frame av_buffersink_get_frame_flags av_buffersink_get_frame_rate av_buffersink_get_h av_buffersink_get_hw_frames_ctx av_buffersink_get_sample_aspect_ratio av_buffersink_get_sample_rate av_buffersink_get_samples av_buffersink_get_time_base av_buffersink_get_type av_buffersink_get_w av_buffersink_params_alloc av_buffersink_set_frame_size av_buffersrc_add_frame av_buffersrc_add_frame_flags av_buffersrc_close av_buffersrc_get_nb_failed_requests av_buffersrc_parameters_alloc av_buffersrc_parameters_set av_buffersrc_write_frame av_filter_ffversion av_filter_iterate avfilter_add_matrix avfilter_all_channel_layouts avfilter_config_links avfilter_configuration avfilter_free avfilter_get_by_name avfilter_get_class avfilter_get_matrix avfilter_graph_alloc avfilter_graph_alloc_filter avfilter_graph_config avfilter_graph_create_filter avfilter_graph_dump avfilter_graph_free avfilter_graph_get_filter avfilter_graph_parse avfilter_graph_parse2 avfilter_graph_parse_ptr avfilter_graph_queue_command avfilter_graph_request_oldest avfilter_graph_send_command avfilter_graph_set_auto_convert avfilter_init_dict avfilter_init_str avfilter_inout_alloc avfilter_inout_free avfilter_insert_filter avfilter_license avfilter_link avfilter_link_free avfilter_link_get_channels avfilter_link_set_closed avfilter_make_format64_list avfilter_mul_matrix avfilter_next avfilter_pad_count avfilter_pad_get_name avfilter_pad_get_type avfilter_process_command avfilter_register avfilter_register_all avfilter_sub_matrix avfilter_transform avfilter_version ================================================ FILE: thirdLibs/ffmpeg/libs/avformat-58.def ================================================ EXPORTS av_add_index_entry av_append_packet av_apply_bitstream_filters av_codec_get_id av_codec_get_tag av_codec_get_tag2 av_demuxer_iterate av_demuxer_open av_dump_format av_filename_number_test av_find_best_stream av_find_default_stream_index av_find_input_format av_find_program_from_stream av_fmt_ctx_get_duration_estimation_method av_format_ffversion av_format_get_audio_codec av_format_get_control_message_cb av_format_get_data_codec av_format_get_metadata_header_padding av_format_get_opaque av_format_get_open_cb av_format_get_probe_score av_format_get_subtitle_codec av_format_get_video_codec av_format_inject_global_side_data av_format_set_audio_codec av_format_set_control_message_cb av_format_set_data_codec av_format_set_metadata_header_padding av_format_set_opaque av_format_set_open_cb av_format_set_subtitle_codec av_format_set_video_codec av_get_frame_filename av_get_frame_filename2 av_get_output_timestamp av_get_packet av_guess_codec av_guess_format av_guess_frame_rate av_guess_sample_aspect_ratio av_hex_dump av_hex_dump_log av_iformat_next av_index_search_timestamp av_interleaved_write_frame av_interleaved_write_uncoded_frame av_match_ext av_muxer_iterate av_new_program av_oformat_next av_pkt_dump2 av_pkt_dump_log2 av_probe_input_buffer av_probe_input_buffer2 av_probe_input_format av_probe_input_format2 av_probe_input_format3 av_program_add_stream_index av_read_frame av_read_pause av_read_play av_register_all av_register_input_format av_register_output_format av_sdp_create av_seek_frame av_stream_add_side_data av_stream_get_codec_timebase av_stream_get_end_pts av_stream_get_parser av_stream_get_r_frame_rate av_stream_get_recommended_encoder_configuration av_stream_get_side_data av_stream_new_side_data av_stream_set_r_frame_rate av_stream_set_recommended_encoder_configuration av_url_split av_write_frame av_write_trailer av_write_uncoded_frame av_write_uncoded_frame_query avformat_alloc_context avformat_alloc_output_context2 avformat_close_input avformat_configuration avformat_find_stream_info avformat_flush avformat_free_context avformat_get_class avformat_get_mov_audio_tags avformat_get_mov_video_tags avformat_get_riff_audio_tags avformat_get_riff_video_tags avformat_init_output avformat_license avformat_match_stream_specifier avformat_network_deinit avformat_network_init avformat_new_stream avformat_open_input avformat_query_codec avformat_queue_attached_pictures avformat_seek_file avformat_transfer_internal_stream_timing_info avformat_version avformat_write_header avio_accept avio_alloc_context avio_check avio_close avio_close_dir avio_close_dyn_buf avio_closep avio_context_free avio_enum_protocols avio_feof avio_find_protocol_name avio_flush avio_free_directory_entry avio_get_dyn_buf avio_get_str avio_get_str16be avio_get_str16le avio_handshake avio_open avio_open2 avio_open_dir avio_open_dyn_buf avio_pause avio_printf avio_put_str avio_put_str16be avio_put_str16le avio_r8 avio_rb16 avio_rb24 avio_rb32 avio_rb64 avio_read avio_read_dir avio_read_partial avio_read_to_bprint avio_rl16 avio_rl24 avio_rl32 avio_rl64 avio_seek avio_seek_time avio_size avio_skip avio_w8 avio_wb16 avio_wb24 avio_wb32 avio_wb64 avio_wl16 avio_wl24 avio_wl32 avio_wl64 avio_write avio_write_marker avpriv_dv_get_packet avpriv_dv_init_demux avpriv_dv_produce_packet avpriv_io_delete avpriv_io_move avpriv_mpegts_parse_close avpriv_mpegts_parse_open avpriv_mpegts_parse_packet avpriv_new_chapter avpriv_register_devices avpriv_set_pts_info ================================================ FILE: thirdLibs/ffmpeg/libs/avutil-56.def ================================================ EXPORTS av_add_i av_add_q av_add_stable av_adler32_update av_aes_alloc av_aes_crypt av_aes_ctr_alloc av_aes_ctr_crypt av_aes_ctr_free av_aes_ctr_get_iv av_aes_ctr_increment_iv av_aes_ctr_init av_aes_ctr_set_full_iv av_aes_ctr_set_iv av_aes_ctr_set_random_iv av_aes_init av_aes_size av_append_path_component av_asprintf av_assert0_fpu av_audio_fifo_alloc av_audio_fifo_drain av_audio_fifo_free av_audio_fifo_peek av_audio_fifo_peek_at av_audio_fifo_read av_audio_fifo_realloc av_audio_fifo_reset av_audio_fifo_size av_audio_fifo_space av_audio_fifo_write av_base64_decode av_base64_encode av_basename av_blowfish_alloc av_blowfish_crypt av_blowfish_crypt_ecb av_blowfish_init av_bmg_get av_bprint_append_data av_bprint_channel_layout av_bprint_chars av_bprint_clear av_bprint_escape av_bprint_finalize av_bprint_get_buffer av_bprint_init av_bprint_init_for_buffer av_bprint_strftime av_bprintf av_buffer_alloc av_buffer_allocz av_buffer_create av_buffer_default_free av_buffer_get_opaque av_buffer_get_ref_count av_buffer_is_writable av_buffer_make_writable av_buffer_pool_get av_buffer_pool_init av_buffer_pool_init2 av_buffer_pool_uninit av_buffer_realloc av_buffer_ref av_buffer_unref av_calloc av_camellia_alloc av_camellia_crypt av_camellia_init av_camellia_size av_cast5_alloc av_cast5_crypt av_cast5_crypt2 av_cast5_init av_cast5_size av_channel_layout_extract_channel av_chroma_location_from_name av_chroma_location_name av_cmp_i av_color_primaries_from_name av_color_primaries_name av_color_range_from_name av_color_range_name av_color_space_from_name av_color_space_name av_color_transfer_from_name av_color_transfer_name av_compare_mod av_compare_ts av_content_light_metadata_alloc av_content_light_metadata_create_side_data av_cpu_count av_cpu_max_align av_crc av_crc_get_table av_crc_init av_d2q av_d2str av_default_get_category av_default_item_name av_des_alloc av_des_crypt av_des_init av_des_mac av_dict_copy av_dict_count av_dict_free av_dict_get av_dict_get_string av_dict_parse_string av_dict_set av_dict_set_int av_dirname av_display_matrix_flip av_display_rotation_get av_display_rotation_set av_div_i av_div_q av_downmix_info_update_side_data av_dynamic_hdr_plus_alloc av_dynamic_hdr_plus_create_side_data av_dynarray2_add av_dynarray_add av_dynarray_add_nofree av_encryption_info_add_side_data av_encryption_info_alloc av_encryption_info_clone av_encryption_info_free av_encryption_info_get_side_data av_encryption_init_info_add_side_data av_encryption_init_info_alloc av_encryption_init_info_free av_encryption_init_info_get_side_data av_escape av_expr_eval av_expr_free av_expr_parse av_expr_parse_and_eval av_fast_malloc av_fast_mallocz av_fast_realloc av_fifo_alloc av_fifo_alloc_array av_fifo_drain av_fifo_free av_fifo_freep av_fifo_generic_peek av_fifo_generic_peek_at av_fifo_generic_read av_fifo_generic_write av_fifo_grow av_fifo_realloc2 av_fifo_reset av_fifo_size av_fifo_space av_file_map av_file_unmap av_find_best_pix_fmt_of_2 av_find_info_tag av_find_nearest_q_idx av_fopen_utf8 av_force_cpu_flags av_fourcc_make_string av_frame_alloc av_frame_apply_cropping av_frame_clone av_frame_copy av_frame_copy_props av_frame_free av_frame_get_best_effort_timestamp av_frame_get_buffer av_frame_get_channel_layout av_frame_get_channels av_frame_get_color_range av_frame_get_colorspace av_frame_get_decode_error_flags av_frame_get_metadata av_frame_get_pkt_duration av_frame_get_pkt_pos av_frame_get_pkt_size av_frame_get_plane_buffer av_frame_get_qp_table av_frame_get_sample_rate av_frame_get_side_data av_frame_is_writable av_frame_make_writable av_frame_move_ref av_frame_new_side_data av_frame_new_side_data_from_buf av_frame_ref av_frame_remove_side_data av_frame_set_best_effort_timestamp av_frame_set_channel_layout av_frame_set_channels av_frame_set_color_range av_frame_set_colorspace av_frame_set_decode_error_flags av_frame_set_metadata av_frame_set_pkt_duration av_frame_set_pkt_pos av_frame_set_pkt_size av_frame_set_qp_table av_frame_set_sample_rate av_frame_side_data_name av_frame_unref av_free av_freep av_gcd av_get_alt_sample_fmt av_get_bits_per_pixel av_get_bytes_per_sample av_get_channel_description av_get_channel_layout av_get_channel_layout_channel_index av_get_channel_layout_nb_channels av_get_channel_layout_string av_get_channel_name av_get_colorspace_name av_get_cpu_flags av_get_default_channel_layout av_get_extended_channel_layout av_get_known_color_name av_get_media_type_string av_get_packed_sample_fmt av_get_padded_bits_per_pixel av_get_picture_type_char av_get_pix_fmt av_get_pix_fmt_loss av_get_pix_fmt_name av_get_pix_fmt_string av_get_planar_sample_fmt av_get_random_seed av_get_sample_fmt av_get_sample_fmt_name av_get_sample_fmt_string av_get_standard_channel_layout av_get_time_base_q av_get_token av_gettime av_gettime_relative av_gettime_relative_is_monotonic av_hash_alloc av_hash_final av_hash_final_b64 av_hash_final_bin av_hash_final_hex av_hash_freep av_hash_get_name av_hash_get_size av_hash_init av_hash_names av_hash_update av_hmac_alloc av_hmac_calc av_hmac_final av_hmac_free av_hmac_init av_hmac_update av_hwdevice_ctx_alloc av_hwdevice_ctx_create av_hwdevice_ctx_create_derived av_hwdevice_ctx_init av_hwdevice_find_type_by_name av_hwdevice_get_hwframe_constraints av_hwdevice_get_type_name av_hwdevice_hwconfig_alloc av_hwdevice_iterate_types av_hwframe_constraints_free av_hwframe_ctx_alloc av_hwframe_ctx_create_derived av_hwframe_ctx_init av_hwframe_get_buffer av_hwframe_map av_hwframe_transfer_data av_hwframe_transfer_get_formats av_i2int av_image_alloc av_image_check_sar av_image_check_size av_image_check_size2 av_image_copy av_image_copy_plane av_image_copy_to_buffer av_image_copy_uc_from av_image_fill_arrays av_image_fill_black av_image_fill_linesizes av_image_fill_max_pixsteps av_image_fill_pointers av_image_get_buffer_size av_image_get_linesize av_int2i av_int_list_length_for_size av_lfg_init av_lfg_init_from_data av_log av_log2 av_log2_16bit av_log2_i av_log_default_callback av_log_format_line av_log_format_line2 av_log_get_flags av_log_get_level av_log_set_callback av_log_set_flags av_log_set_level av_lzo1x_decode av_malloc av_malloc_array av_mallocz av_mallocz_array av_mastering_display_metadata_alloc av_mastering_display_metadata_create_side_data av_match_list av_match_name av_max_alloc av_md5_alloc av_md5_final av_md5_init av_md5_size av_md5_sum av_md5_update av_memcpy_backptr av_memdup av_mod_i av_mul_i av_mul_q av_murmur3_alloc av_murmur3_final av_murmur3_init av_murmur3_init_seeded av_murmur3_update av_nearer_q av_opt_child_class_next av_opt_child_next av_opt_copy av_opt_eval_double av_opt_eval_flags av_opt_eval_float av_opt_eval_int av_opt_eval_int64 av_opt_eval_q av_opt_find av_opt_find2 av_opt_flag_is_set av_opt_free av_opt_freep_ranges av_opt_get av_opt_get_channel_layout av_opt_get_dict_val av_opt_get_double av_opt_get_image_size av_opt_get_int av_opt_get_key_value av_opt_get_pixel_fmt av_opt_get_q av_opt_get_sample_fmt av_opt_get_video_rate av_opt_is_set_to_default av_opt_is_set_to_default_by_name av_opt_next av_opt_ptr av_opt_query_ranges av_opt_query_ranges_default av_opt_serialize av_opt_set av_opt_set_bin av_opt_set_channel_layout av_opt_set_defaults av_opt_set_defaults2 av_opt_set_dict av_opt_set_dict2 av_opt_set_dict_val av_opt_set_double av_opt_set_from_string av_opt_set_image_size av_opt_set_int av_opt_set_pixel_fmt av_opt_set_q av_opt_set_sample_fmt av_opt_set_video_rate av_opt_show2 av_parse_color av_parse_cpu_caps av_parse_cpu_flags av_parse_ratio av_parse_time av_parse_video_rate av_parse_video_size av_pix_fmt_count_planes av_pix_fmt_desc_get av_pix_fmt_desc_get_id av_pix_fmt_desc_next av_pix_fmt_get_chroma_sub_sample av_pix_fmt_swap_endianness av_pixelutils_get_sad_fn av_q2intfloat av_rc4_alloc av_rc4_crypt av_rc4_init av_read_image_line av_read_image_line2 av_realloc av_realloc_array av_realloc_f av_reallocp av_reallocp_array av_reduce av_rescale av_rescale_delta av_rescale_q av_rescale_q_rnd av_rescale_rnd av_ripemd_alloc av_ripemd_final av_ripemd_init av_ripemd_size av_ripemd_update av_sample_fmt_is_planar av_samples_alloc av_samples_alloc_array_and_samples av_samples_copy av_samples_fill_arrays av_samples_get_buffer_size av_samples_set_silence av_set_cpu_flags_mask av_set_options_string av_sha512_alloc av_sha512_final av_sha512_init av_sha512_size av_sha512_update av_sha_alloc av_sha_final av_sha_init av_sha_size av_sha_update av_shr_i av_small_strptime av_spherical_alloc av_spherical_from_name av_spherical_projection_name av_spherical_tile_bounds av_sscanf av_stereo3d_alloc av_stereo3d_create_side_data av_stereo3d_from_name av_stereo3d_type_name av_strcasecmp av_strdup av_strerror av_strireplace av_stristart av_stristr av_strlcat av_strlcatf av_strlcpy av_strncasecmp av_strndup av_strnstr av_strstart av_strtod av_strtok av_sub_i av_sub_q av_tea_alloc av_tea_crypt av_tea_init av_tea_size av_tempfile av_thread_message_flush av_thread_message_queue_alloc av_thread_message_queue_free av_thread_message_queue_nb_elems av_thread_message_queue_recv av_thread_message_queue_send av_thread_message_queue_set_err_recv av_thread_message_queue_set_err_send av_thread_message_queue_set_free_func av_timecode_adjust_ntsc_framenum2 av_timecode_check_frame_rate av_timecode_get_smpte_from_framenum av_timecode_init av_timecode_init_from_string av_timecode_make_mpeg_tc_string av_timecode_make_smpte_tc_string av_timecode_make_string av_timegm av_tree_destroy av_tree_enumerate av_tree_find av_tree_insert av_tree_node_alloc av_tree_node_size av_twofish_alloc av_twofish_crypt av_twofish_init av_twofish_size av_tx_init av_tx_uninit av_usleep av_utf8_decode av_util_ffversion av_vbprintf av_version_info av_vlog av_write_image_line av_write_image_line2 av_xtea_alloc av_xtea_crypt av_xtea_init av_xtea_le_crypt av_xtea_le_init avpriv_alloc_fixed_dsp avpriv_cga_font avpriv_dict_set_timestamp avpriv_float_dsp_alloc avpriv_get_gamma_from_trc avpriv_get_trc_function_from_trc avpriv_init_lls avpriv_open avpriv_report_missing_feature avpriv_request_sample avpriv_scalarproduct_float_c avpriv_set_systematic_pal2 avpriv_slicethread_create avpriv_slicethread_execute avpriv_slicethread_free avpriv_solve_lls avpriv_tempfile avpriv_vga16_font avutil_configuration avutil_license avutil_version ================================================ FILE: thirdLibs/ffmpeg/libs/postproc-55.def ================================================ EXPORTS postproc_configuration postproc_ffversion postproc_license postproc_version pp_free_context pp_free_mode pp_get_context pp_get_mode_by_name_and_quality pp_help pp_postprocess ================================================ FILE: thirdLibs/ffmpeg/libs/swresample-3.def ================================================ EXPORTS swr_alloc swr_alloc_set_opts swr_build_matrix swr_close swr_config_frame swr_convert swr_convert_frame swr_drop_output swr_ffversion swr_free swr_get_class swr_get_delay swr_get_out_samples swr_init swr_inject_silence swr_is_initialized swr_next_pts swr_set_channel_mapping swr_set_compensation swr_set_matrix swresample_configuration swresample_license swresample_version ================================================ FILE: thirdLibs/ffmpeg/libs/swscale-5.def ================================================ EXPORTS sws_addVec sws_allocVec sws_alloc_context sws_alloc_set_opts sws_cloneVec sws_convVec sws_convertPalette8ToPacked24 sws_convertPalette8ToPacked32 sws_freeContext sws_freeFilter sws_freeVec sws_getCachedContext sws_getCoefficients sws_getColorspaceDetails sws_getConstVec sws_getContext sws_getDefaultFilter sws_getGaussianVec sws_getIdentityVec sws_get_class sws_init_context sws_isSupportedEndiannessConversion sws_isSupportedInput sws_isSupportedOutput sws_normalizeVec sws_printVec2 sws_scale sws_scaleVec sws_setColorspaceDetails sws_shiftVec sws_subVec swscale_configuration swscale_license swscale_version ================================================ FILE: thirdLibs/python3_8/include/Python-ast.h ================================================ /* File automatically generated by Parser/asdl_c.py. */ #ifndef Py_PYTHON_AST_H #define Py_PYTHON_AST_H #ifdef __cplusplus extern "C" { #endif #include "asdl.h" #undef Yield /* undefine macro conflicting with */ typedef struct _mod *mod_ty; typedef struct _stmt *stmt_ty; typedef struct _expr *expr_ty; typedef enum _expr_context { Load=1, Store=2, Del=3, AugLoad=4, AugStore=5, Param=6 } expr_context_ty; typedef struct _slice *slice_ty; typedef enum _boolop { And=1, Or=2 } boolop_ty; typedef enum _operator { Add=1, Sub=2, Mult=3, MatMult=4, Div=5, Mod=6, Pow=7, LShift=8, RShift=9, BitOr=10, BitXor=11, BitAnd=12, FloorDiv=13 } operator_ty; typedef enum _unaryop { Invert=1, Not=2, UAdd=3, USub=4 } unaryop_ty; typedef enum _cmpop { Eq=1, NotEq=2, Lt=3, LtE=4, Gt=5, GtE=6, Is=7, IsNot=8, In=9, NotIn=10 } cmpop_ty; typedef struct _comprehension *comprehension_ty; typedef struct _excepthandler *excepthandler_ty; typedef struct _arguments *arguments_ty; typedef struct _arg *arg_ty; typedef struct _keyword *keyword_ty; typedef struct _alias *alias_ty; typedef struct _withitem *withitem_ty; typedef struct _type_ignore *type_ignore_ty; enum _mod_kind {Module_kind=1, Interactive_kind=2, Expression_kind=3, FunctionType_kind=4, Suite_kind=5}; struct _mod { enum _mod_kind kind; union { struct { asdl_seq *body; asdl_seq *type_ignores; } Module; struct { asdl_seq *body; } Interactive; struct { expr_ty body; } Expression; struct { asdl_seq *argtypes; expr_ty returns; } FunctionType; struct { asdl_seq *body; } Suite; } v; }; enum _stmt_kind {FunctionDef_kind=1, AsyncFunctionDef_kind=2, ClassDef_kind=3, Return_kind=4, Delete_kind=5, Assign_kind=6, AugAssign_kind=7, AnnAssign_kind=8, For_kind=9, AsyncFor_kind=10, While_kind=11, If_kind=12, With_kind=13, AsyncWith_kind=14, Raise_kind=15, Try_kind=16, Assert_kind=17, Import_kind=18, ImportFrom_kind=19, Global_kind=20, Nonlocal_kind=21, Expr_kind=22, Pass_kind=23, Break_kind=24, Continue_kind=25}; struct _stmt { enum _stmt_kind kind; union { struct { identifier name; arguments_ty args; asdl_seq *body; asdl_seq *decorator_list; expr_ty returns; string type_comment; } FunctionDef; struct { identifier name; arguments_ty args; asdl_seq *body; asdl_seq *decorator_list; expr_ty returns; string type_comment; } AsyncFunctionDef; struct { identifier name; asdl_seq *bases; asdl_seq *keywords; asdl_seq *body; asdl_seq *decorator_list; } ClassDef; struct { expr_ty value; } Return; struct { asdl_seq *targets; } Delete; struct { asdl_seq *targets; expr_ty value; string type_comment; } Assign; struct { expr_ty target; operator_ty op; expr_ty value; } AugAssign; struct { expr_ty target; expr_ty annotation; expr_ty value; int simple; } AnnAssign; struct { expr_ty target; expr_ty iter; asdl_seq *body; asdl_seq *orelse; string type_comment; } For; struct { expr_ty target; expr_ty iter; asdl_seq *body; asdl_seq *orelse; string type_comment; } AsyncFor; struct { expr_ty test; asdl_seq *body; asdl_seq *orelse; } While; struct { expr_ty test; asdl_seq *body; asdl_seq *orelse; } If; struct { asdl_seq *items; asdl_seq *body; string type_comment; } With; struct { asdl_seq *items; asdl_seq *body; string type_comment; } AsyncWith; struct { expr_ty exc; expr_ty cause; } Raise; struct { asdl_seq *body; asdl_seq *handlers; asdl_seq *orelse; asdl_seq *finalbody; } Try; struct { expr_ty test; expr_ty msg; } Assert; struct { asdl_seq *names; } Import; struct { identifier module; asdl_seq *names; int level; } ImportFrom; struct { asdl_seq *names; } Global; struct { asdl_seq *names; } Nonlocal; struct { expr_ty value; } Expr; } v; int lineno; int col_offset; int end_lineno; int end_col_offset; }; enum _expr_kind {BoolOp_kind=1, NamedExpr_kind=2, BinOp_kind=3, UnaryOp_kind=4, Lambda_kind=5, IfExp_kind=6, Dict_kind=7, Set_kind=8, ListComp_kind=9, SetComp_kind=10, DictComp_kind=11, GeneratorExp_kind=12, Await_kind=13, Yield_kind=14, YieldFrom_kind=15, Compare_kind=16, Call_kind=17, FormattedValue_kind=18, JoinedStr_kind=19, Constant_kind=20, Attribute_kind=21, Subscript_kind=22, Starred_kind=23, Name_kind=24, List_kind=25, Tuple_kind=26}; struct _expr { enum _expr_kind kind; union { struct { boolop_ty op; asdl_seq *values; } BoolOp; struct { expr_ty target; expr_ty value; } NamedExpr; struct { expr_ty left; operator_ty op; expr_ty right; } BinOp; struct { unaryop_ty op; expr_ty operand; } UnaryOp; struct { arguments_ty args; expr_ty body; } Lambda; struct { expr_ty test; expr_ty body; expr_ty orelse; } IfExp; struct { asdl_seq *keys; asdl_seq *values; } Dict; struct { asdl_seq *elts; } Set; struct { expr_ty elt; asdl_seq *generators; } ListComp; struct { expr_ty elt; asdl_seq *generators; } SetComp; struct { expr_ty key; expr_ty value; asdl_seq *generators; } DictComp; struct { expr_ty elt; asdl_seq *generators; } GeneratorExp; struct { expr_ty value; } Await; struct { expr_ty value; } Yield; struct { expr_ty value; } YieldFrom; struct { expr_ty left; asdl_int_seq *ops; asdl_seq *comparators; } Compare; struct { expr_ty func; asdl_seq *args; asdl_seq *keywords; } Call; struct { expr_ty value; int conversion; expr_ty format_spec; } FormattedValue; struct { asdl_seq *values; } JoinedStr; struct { constant value; string kind; } Constant; struct { expr_ty value; identifier attr; expr_context_ty ctx; } Attribute; struct { expr_ty value; slice_ty slice; expr_context_ty ctx; } Subscript; struct { expr_ty value; expr_context_ty ctx; } Starred; struct { identifier id; expr_context_ty ctx; } Name; struct { asdl_seq *elts; expr_context_ty ctx; } List; struct { asdl_seq *elts; expr_context_ty ctx; } Tuple; } v; int lineno; int col_offset; int end_lineno; int end_col_offset; }; enum _slice_kind {Slice_kind=1, ExtSlice_kind=2, Index_kind=3}; struct _slice { enum _slice_kind kind; union { struct { expr_ty lower; expr_ty upper; expr_ty step; } Slice; struct { asdl_seq *dims; } ExtSlice; struct { expr_ty value; } Index; } v; }; struct _comprehension { expr_ty target; expr_ty iter; asdl_seq *ifs; int is_async; }; enum _excepthandler_kind {ExceptHandler_kind=1}; struct _excepthandler { enum _excepthandler_kind kind; union { struct { expr_ty type; identifier name; asdl_seq *body; } ExceptHandler; } v; int lineno; int col_offset; int end_lineno; int end_col_offset; }; struct _arguments { asdl_seq *posonlyargs; asdl_seq *args; arg_ty vararg; asdl_seq *kwonlyargs; asdl_seq *kw_defaults; arg_ty kwarg; asdl_seq *defaults; }; struct _arg { identifier arg; expr_ty annotation; string type_comment; int lineno; int col_offset; int end_lineno; int end_col_offset; }; struct _keyword { identifier arg; expr_ty value; }; struct _alias { identifier name; identifier asname; }; struct _withitem { expr_ty context_expr; expr_ty optional_vars; }; enum _type_ignore_kind {TypeIgnore_kind=1}; struct _type_ignore { enum _type_ignore_kind kind; union { struct { int lineno; string tag; } TypeIgnore; } v; }; // Note: these macros affect function definitions, not only call sites. #define Module(a0, a1, a2) _Py_Module(a0, a1, a2) mod_ty _Py_Module(asdl_seq * body, asdl_seq * type_ignores, PyArena *arena); #define Interactive(a0, a1) _Py_Interactive(a0, a1) mod_ty _Py_Interactive(asdl_seq * body, PyArena *arena); #define Expression(a0, a1) _Py_Expression(a0, a1) mod_ty _Py_Expression(expr_ty body, PyArena *arena); #define FunctionType(a0, a1, a2) _Py_FunctionType(a0, a1, a2) mod_ty _Py_FunctionType(asdl_seq * argtypes, expr_ty returns, PyArena *arena); #define Suite(a0, a1) _Py_Suite(a0, a1) mod_ty _Py_Suite(asdl_seq * body, PyArena *arena); #define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * decorator_list, expr_ty returns, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define AsyncFunctionDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) _Py_AsyncFunctionDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) stmt_ty _Py_AsyncFunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * decorator_list, expr_ty returns, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) _Py_ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords, asdl_seq * body, asdl_seq * decorator_list, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Return(a0, a1, a2, a3, a4, a5) _Py_Return(a0, a1, a2, a3, a4, a5) stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Delete(a0, a1, a2, a3, a4, a5) _Py_Delete(a0, a1, a2, a3, a4, a5) stmt_ty _Py_Delete(asdl_seq * targets, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Assign(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Assign(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define AugAssign(a0, a1, a2, a3, a4, a5, a6, a7) _Py_AugAssign(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define AnnAssign(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_AnnAssign(a0, a1, a2, a3, a4, a5, a6, a7, a8) stmt_ty _Py_AnnAssign(expr_ty target, expr_ty annotation, expr_ty value, int simple, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define For(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) _Py_For(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define AsyncFor(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) _Py_AsyncFor(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) stmt_ty _Py_AsyncFor(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define While(a0, a1, a2, a3, a4, a5, a6, a7) _Py_While(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define If(a0, a1, a2, a3, a4, a5, a6, a7) _Py_If(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define With(a0, a1, a2, a3, a4, a5, a6, a7) _Py_With(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_With(asdl_seq * items, asdl_seq * body, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define AsyncWith(a0, a1, a2, a3, a4, a5, a6, a7) _Py_AsyncWith(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_AsyncWith(asdl_seq * items, asdl_seq * body, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Raise(a0, a1, a2, a3, a4, a5, a6) _Py_Raise(a0, a1, a2, a3, a4, a5, a6) stmt_ty _Py_Raise(expr_ty exc, expr_ty cause, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Try(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_Try(a0, a1, a2, a3, a4, a5, a6, a7, a8) stmt_ty _Py_Try(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, asdl_seq * finalbody, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Assert(a0, a1, a2, a3, a4, a5, a6) _Py_Assert(a0, a1, a2, a3, a4, a5, a6) stmt_ty _Py_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Import(a0, a1, a2, a3, a4, a5) _Py_Import(a0, a1, a2, a3, a4, a5) stmt_ty _Py_Import(asdl_seq * names, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define ImportFrom(a0, a1, a2, a3, a4, a5, a6, a7) _Py_ImportFrom(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_ImportFrom(identifier module, asdl_seq * names, int level, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Global(a0, a1, a2, a3, a4, a5) _Py_Global(a0, a1, a2, a3, a4, a5) stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Nonlocal(a0, a1, a2, a3, a4, a5) _Py_Nonlocal(a0, a1, a2, a3, a4, a5) stmt_ty _Py_Nonlocal(asdl_seq * names, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Expr(a0, a1, a2, a3, a4, a5) _Py_Expr(a0, a1, a2, a3, a4, a5) stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Pass(a0, a1, a2, a3, a4) _Py_Pass(a0, a1, a2, a3, a4) stmt_ty _Py_Pass(int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Break(a0, a1, a2, a3, a4) _Py_Break(a0, a1, a2, a3, a4) stmt_ty _Py_Break(int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Continue(a0, a1, a2, a3, a4) _Py_Continue(a0, a1, a2, a3, a4) stmt_ty _Py_Continue(int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define BoolOp(a0, a1, a2, a3, a4, a5, a6) _Py_BoolOp(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define NamedExpr(a0, a1, a2, a3, a4, a5, a6) _Py_NamedExpr(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_NamedExpr(expr_ty target, expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define BinOp(a0, a1, a2, a3, a4, a5, a6, a7) _Py_BinOp(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define UnaryOp(a0, a1, a2, a3, a4, a5, a6) _Py_UnaryOp(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Lambda(a0, a1, a2, a3, a4, a5, a6) _Py_Lambda(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define IfExp(a0, a1, a2, a3, a4, a5, a6, a7) _Py_IfExp(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Dict(a0, a1, a2, a3, a4, a5, a6) _Py_Dict(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Set(a0, a1, a2, a3, a4, a5) _Py_Set(a0, a1, a2, a3, a4, a5) expr_ty _Py_Set(asdl_seq * elts, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define ListComp(a0, a1, a2, a3, a4, a5, a6) _Py_ListComp(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define SetComp(a0, a1, a2, a3, a4, a5, a6) _Py_SetComp(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_SetComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define DictComp(a0, a1, a2, a3, a4, a5, a6, a7) _Py_DictComp(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_DictComp(expr_ty key, expr_ty value, asdl_seq * generators, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define GeneratorExp(a0, a1, a2, a3, a4, a5, a6) _Py_GeneratorExp(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Await(a0, a1, a2, a3, a4, a5) _Py_Await(a0, a1, a2, a3, a4, a5) expr_ty _Py_Await(expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Yield(a0, a1, a2, a3, a4, a5) _Py_Yield(a0, a1, a2, a3, a4, a5) expr_ty _Py_Yield(expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define YieldFrom(a0, a1, a2, a3, a4, a5) _Py_YieldFrom(a0, a1, a2, a3, a4, a5) expr_ty _Py_YieldFrom(expr_ty value, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Compare(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Compare(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Call(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Call(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define FormattedValue(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FormattedValue(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_FormattedValue(expr_ty value, int conversion, expr_ty format_spec, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define JoinedStr(a0, a1, a2, a3, a4, a5) _Py_JoinedStr(a0, a1, a2, a3, a4, a5) expr_ty _Py_JoinedStr(asdl_seq * values, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Constant(a0, a1, a2, a3, a4, a5, a6) _Py_Constant(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_Constant(constant value, string kind, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Attribute(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Attribute(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Subscript(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Subscript(a0, a1, a2, a3, a4, a5, a6, a7) expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Starred(a0, a1, a2, a3, a4, a5, a6) _Py_Starred(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_Starred(expr_ty value, expr_context_ty ctx, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Name(a0, a1, a2, a3, a4, a5, a6) _Py_Name(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define List(a0, a1, a2, a3, a4, a5, a6) _Py_List(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_List(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Tuple(a0, a1, a2, a3, a4, a5, a6) _Py_Tuple(a0, a1, a2, a3, a4, a5, a6) expr_ty _Py_Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define Slice(a0, a1, a2, a3) _Py_Slice(a0, a1, a2, a3) slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); #define ExtSlice(a0, a1) _Py_ExtSlice(a0, a1) slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena); #define Index(a0, a1) _Py_Index(a0, a1) slice_ty _Py_Index(expr_ty value, PyArena *arena); #define comprehension(a0, a1, a2, a3, a4) _Py_comprehension(a0, a1, a2, a3, a4) comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs, int is_async, PyArena *arena); #define ExceptHandler(a0, a1, a2, a3, a4, a5, a6, a7) _Py_ExceptHandler(a0, a1, a2, a3, a4, a5, a6, a7) excepthandler_ty _Py_ExceptHandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define arguments(a0, a1, a2, a3, a4, a5, a6, a7) _Py_arguments(a0, a1, a2, a3, a4, a5, a6, a7) arguments_ty _Py_arguments(asdl_seq * posonlyargs, asdl_seq * args, arg_ty vararg, asdl_seq * kwonlyargs, asdl_seq * kw_defaults, arg_ty kwarg, asdl_seq * defaults, PyArena *arena); #define arg(a0, a1, a2, a3, a4, a5, a6, a7) _Py_arg(a0, a1, a2, a3, a4, a5, a6, a7) arg_ty _Py_arg(identifier arg, expr_ty annotation, string type_comment, int lineno, int col_offset, int end_lineno, int end_col_offset, PyArena *arena); #define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2) keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena); #define alias(a0, a1, a2) _Py_alias(a0, a1, a2) alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); #define withitem(a0, a1, a2) _Py_withitem(a0, a1, a2) withitem_ty _Py_withitem(expr_ty context_expr, expr_ty optional_vars, PyArena *arena); #define TypeIgnore(a0, a1, a2) _Py_TypeIgnore(a0, a1, a2) type_ignore_ty _Py_TypeIgnore(int lineno, string tag, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode); int PyAST_Check(PyObject* obj); #ifdef __cplusplus } #endif #endif /* !Py_PYTHON_AST_H */ ================================================ FILE: thirdLibs/python3_8/include/Python.h ================================================ #ifndef Py_PYTHON_H #define Py_PYTHON_H /* Since this is a "meta-include" file, no #ifdef __cplusplus / extern "C" { */ /* Include nearly all Python header files */ #include "patchlevel.h" #include "pyconfig.h" #include "pymacconfig.h" #include #ifndef UCHAR_MAX #error "Something's broken. UCHAR_MAX should be defined in limits.h." #endif #if UCHAR_MAX != 255 #error "Python's source code assumes C's unsigned char is an 8-bit type." #endif #if defined(__sgi) && !defined(_SGI_MP_SOURCE) #define _SGI_MP_SOURCE #endif #include #ifndef NULL # error "Python.h requires that stdio.h define NULL." #endif #include #ifdef HAVE_ERRNO_H #include #endif #include #ifndef MS_WINDOWS #include #endif #ifdef HAVE_CRYPT_H #if defined(HAVE_CRYPT_R) && !defined(_GNU_SOURCE) /* Required for glibc to expose the crypt_r() function prototype. */ # define _GNU_SOURCE # define _Py_GNU_SOURCE_FOR_CRYPT #endif #include #ifdef _Py_GNU_SOURCE_FOR_CRYPT /* Don't leak the _GNU_SOURCE define to other headers. */ # undef _GNU_SOURCE # undef _Py_GNU_SOURCE_FOR_CRYPT #endif #endif /* For size_t? */ #ifdef HAVE_STDDEF_H #include #endif /* CAUTION: Build setups should ensure that NDEBUG is defined on the * compiler command line when building Python in release mode; else * assert() calls won't be removed. */ #include #include "pyport.h" #include "pymacro.h" /* A convenient way for code to know if clang's memory sanitizer is enabled. */ #if defined(__has_feature) # if __has_feature(memory_sanitizer) # if !defined(_Py_MEMORY_SANITIZER) # define _Py_MEMORY_SANITIZER # endif # endif #endif /* Debug-mode build with pymalloc implies PYMALLOC_DEBUG. * PYMALLOC_DEBUG is in error if pymalloc is not in use. */ #if defined(Py_DEBUG) && defined(WITH_PYMALLOC) && !defined(PYMALLOC_DEBUG) #define PYMALLOC_DEBUG #endif #if defined(PYMALLOC_DEBUG) && !defined(WITH_PYMALLOC) #error "PYMALLOC_DEBUG requires WITH_PYMALLOC" #endif #include "pymath.h" #include "pytime.h" #include "pymem.h" #include "object.h" #include "objimpl.h" #include "typeslots.h" #include "pyhash.h" #include "pydebug.h" #include "bytearrayobject.h" #include "bytesobject.h" #include "unicodeobject.h" #include "longobject.h" #include "longintrepr.h" #include "boolobject.h" #include "floatobject.h" #include "complexobject.h" #include "rangeobject.h" #include "memoryobject.h" #include "tupleobject.h" #include "listobject.h" #include "dictobject.h" #include "odictobject.h" #include "enumobject.h" #include "setobject.h" #include "methodobject.h" #include "moduleobject.h" #include "funcobject.h" #include "classobject.h" #include "fileobject.h" #include "pycapsule.h" #include "traceback.h" #include "sliceobject.h" #include "cellobject.h" #include "iterobject.h" #include "genobject.h" #include "descrobject.h" #include "warnings.h" #include "weakrefobject.h" #include "structseq.h" #include "namespaceobject.h" #include "picklebufobject.h" #include "codecs.h" #include "pyerrors.h" #include "cpython/initconfig.h" #include "pystate.h" #include "context.h" #include "pyarena.h" #include "modsupport.h" #include "compile.h" #include "pythonrun.h" #include "pylifecycle.h" #include "ceval.h" #include "sysmodule.h" #include "osmodule.h" #include "intrcheck.h" #include "import.h" #include "abstract.h" #include "bltinmodule.h" #include "eval.h" #include "pyctype.h" #include "pystrtod.h" #include "pystrcmp.h" #include "dtoa.h" #include "fileutils.h" #include "pyfpe.h" #include "tracemalloc.h" #endif /* !Py_PYTHON_H */ ================================================ FILE: thirdLibs/python3_8/include/abstract.h ================================================ /* Abstract Object Interface (many thanks to Jim Fulton) */ #ifndef Py_ABSTRACTOBJECT_H #define Py_ABSTRACTOBJECT_H #ifdef __cplusplus extern "C" { #endif /* === Object Protocol ================================================== */ /* Implemented elsewhere: int PyObject_Print(PyObject *o, FILE *fp, int flags); Print an object 'o' on file 'fp'. Returns -1 on error. The flags argument is used to enable certain printing options. The only option currently supported is Py_Print_RAW. (What should be said about Py_Print_RAW?). */ /* Implemented elsewhere: int PyObject_HasAttrString(PyObject *o, const char *attr_name); Returns 1 if object 'o' has the attribute attr_name, and 0 otherwise. This is equivalent to the Python expression: hasattr(o,attr_name). This function always succeeds. */ /* Implemented elsewhere: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name); Retrieve an attributed named attr_name form object o. Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression: o.attr_name. */ /* Implemented elsewhere: int PyObject_HasAttr(PyObject *o, PyObject *attr_name); Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the Python expression: hasattr(o,attr_name). This function always succeeds. */ /* Implemented elsewhere: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name); Retrieve an attributed named 'attr_name' form object 'o'. Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression: o.attr_name. */ /* Implemented elsewhere: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v); Set the value of the attribute named attr_name, for object 'o', to the value 'v'. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o.attr_name=v. */ /* Implemented elsewhere: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v); Set the value of the attribute named attr_name, for object 'o', to the value 'v'. an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o.attr_name=v. */ /* Implemented as a macro: int PyObject_DelAttrString(PyObject *o, const char *attr_name); Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python statement: del o.attr_name. */ #define PyObject_DelAttrString(O,A) PyObject_SetAttrString((O),(A), NULL) /* Implemented as a macro: int PyObject_DelAttr(PyObject *o, PyObject *attr_name); Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python statement: del o.attr_name. */ #define PyObject_DelAttr(O,A) PyObject_SetAttr((O),(A), NULL) /* Implemented elsewhere: PyObject *PyObject_Repr(PyObject *o); Compute the string representation of object 'o'. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression: repr(o). Called by the repr() built-in function. */ /* Implemented elsewhere: PyObject *PyObject_Str(PyObject *o); Compute the string representation of object, o. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression: str(o). Called by the str() and print() built-in functions. */ /* Declared elsewhere PyAPI_FUNC(int) PyCallable_Check(PyObject *o); Determine if the object, o, is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds. */ #ifdef PY_SSIZE_T_CLEAN # define PyObject_CallFunction _PyObject_CallFunction_SizeT # define PyObject_CallMethod _PyObject_CallMethod_SizeT #endif /* Call a callable Python object 'callable' with arguments given by the tuple 'args' and keywords arguments given by the dictionary 'kwargs'. 'args' must not be NULL, use an empty tuple if no arguments are needed. If no named arguments are needed, 'kwargs' can be NULL. This is the equivalent of the Python expression: callable(*args, **kwargs). */ PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs); /* Call a callable Python object 'callable', with arguments given by the tuple 'args'. If no arguments are needed, then 'args' can be NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: callable(*args). */ PyAPI_FUNC(PyObject *) PyObject_CallObject(PyObject *callable, PyObject *args); /* Call a callable Python object, callable, with a variable number of C arguments. The C arguments are described using a mkvalue-style format string. The format may be NULL, indicating that no arguments are provided. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: callable(arg1, arg2, ...). */ PyAPI_FUNC(PyObject *) PyObject_CallFunction(PyObject *callable, const char *format, ...); /* Call the method named 'name' of object 'obj' with a variable number of C arguments. The C arguments are described by a mkvalue format string. The format can be NULL, indicating that no arguments are provided. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: obj.name(arg1, arg2, ...). */ PyAPI_FUNC(PyObject *) PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...); PyAPI_FUNC(PyObject *) _PyObject_CallFunction_SizeT(PyObject *callable, const char *format, ...); PyAPI_FUNC(PyObject *) _PyObject_CallMethod_SizeT(PyObject *obj, const char *name, const char *format, ...); /* Call a callable Python object 'callable' with a variable number of C arguments. The C arguments are provided as PyObject* values, terminated by a NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: callable(arg1, arg2, ...). */ PyAPI_FUNC(PyObject *) PyObject_CallFunctionObjArgs(PyObject *callable, ...); /* Call the method named 'name' of object 'obj' with a variable number of C arguments. The C arguments are provided as PyObject* values, terminated by NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: obj.name(*args). */ PyAPI_FUNC(PyObject *) PyObject_CallMethodObjArgs( PyObject *obj, PyObject *name, ...); /* Implemented elsewhere: Py_hash_t PyObject_Hash(PyObject *o); Compute and return the hash, hash_value, of an object, o. On failure, return -1. This is the equivalent of the Python expression: hash(o). */ /* Implemented elsewhere: int PyObject_IsTrue(PyObject *o); Returns 1 if the object, o, is considered to be true, 0 if o is considered to be false and -1 on failure. This is equivalent to the Python expression: not not o. */ /* Implemented elsewhere: int PyObject_Not(PyObject *o); Returns 0 if the object, o, is considered to be true, 1 if o is considered to be false and -1 on failure. This is equivalent to the Python expression: not o. */ /* Get the type of an object. On success, returns a type object corresponding to the object type of object 'o'. On failure, returns NULL. This is equivalent to the Python expression: type(o) */ PyAPI_FUNC(PyObject *) PyObject_Type(PyObject *o); /* Return the size of object 'o'. If the object 'o' provides both sequence and mapping protocols, the sequence size is returned. On error, -1 is returned. This is the equivalent to the Python expression: len(o) */ PyAPI_FUNC(Py_ssize_t) PyObject_Size(PyObject *o); /* For DLL compatibility */ #undef PyObject_Length PyAPI_FUNC(Py_ssize_t) PyObject_Length(PyObject *o); #define PyObject_Length PyObject_Size /* Return element of 'o' corresponding to the object 'key'. Return NULL on failure. This is the equivalent of the Python expression: o[key] */ PyAPI_FUNC(PyObject *) PyObject_GetItem(PyObject *o, PyObject *key); /* Map the object 'key' to the value 'v' into 'o'. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement: o[key]=v. */ PyAPI_FUNC(int) PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v); /* Remove the mapping for the string 'key' from the object 'o'. Returns -1 on failure. This is equivalent to the Python statement: del o[key]. */ PyAPI_FUNC(int) PyObject_DelItemString(PyObject *o, const char *key); /* Delete the mapping for the object 'key' from the object 'o'. Returns -1 on failure. This is the equivalent of the Python statement: del o[key]. */ PyAPI_FUNC(int) PyObject_DelItem(PyObject *o, PyObject *key); /* === Old Buffer API ============================================ */ /* FIXME: usage of these should all be replaced in Python itself but for backwards compatibility we will implement them. Their usage without a corresponding "unlock" mechanism may create issues (but they would already be there). */ /* Takes an arbitrary object which must support the (character, single segment) buffer interface and returns a pointer to a read-only memory location useable as character based input for subsequent processing. Return 0 on success. buffer and buffer_len are only set in case no error occurs. Otherwise, -1 is returned and an exception set. */ Py_DEPRECATED(3.0) PyAPI_FUNC(int) PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len); /* Checks whether an arbitrary object supports the (character, single segment) buffer interface. Returns 1 on success, 0 on failure. */ Py_DEPRECATED(3.0) PyAPI_FUNC(int) PyObject_CheckReadBuffer(PyObject *obj); /* Same as PyObject_AsCharBuffer() except that this API expects (readable, single segment) buffer interface and returns a pointer to a read-only memory location which can contain arbitrary data. 0 is returned on success. buffer and buffer_len are only set in case no error occurs. Otherwise, -1 is returned and an exception set. */ Py_DEPRECATED(3.0) PyAPI_FUNC(int) PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len); /* Takes an arbitrary object which must support the (writable, single segment) buffer interface and returns a pointer to a writable memory location in buffer of size 'buffer_len'. Return 0 on success. buffer and buffer_len are only set in case no error occurs. Otherwise, -1 is returned and an exception set. */ Py_DEPRECATED(3.0) PyAPI_FUNC(int) PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len); /* === New Buffer API ============================================ */ /* Takes an arbitrary object and returns the result of calling obj.__format__(format_spec). */ PyAPI_FUNC(PyObject *) PyObject_Format(PyObject *obj, PyObject *format_spec); /* ==== Iterators ================================================ */ /* Takes an object and returns an iterator for it. This is typically a new iterator but if the argument is an iterator, this returns itself. */ PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *); /* Returns 1 if the object 'obj' provides iterator protocols, and 0 otherwise. This function always succeeds. */ PyAPI_FUNC(int) PyIter_Check(PyObject *); /* Takes an iterator object and calls its tp_iternext slot, returning the next value. If the iterator is exhausted, this returns NULL without setting an exception. NULL with an exception means an error occurred. */ PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *); /* === Number Protocol ================================================== */ /* Returns 1 if the object 'o' provides numeric protocols, and 0 otherwise. This function always succeeds. */ PyAPI_FUNC(int) PyNumber_Check(PyObject *o); /* Returns the result of adding o1 and o2, or NULL on failure. This is the equivalent of the Python expression: o1 + o2. */ PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2); /* Returns the result of subtracting o2 from o1, or NULL on failure. This is the equivalent of the Python expression: o1 - o2. */ PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2); /* Returns the result of multiplying o1 and o2, or NULL on failure. This is the equivalent of the Python expression: o1 * o2. */ PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* This is the equivalent of the Python expression: o1 @ o2. */ PyAPI_FUNC(PyObject *) PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2); #endif /* Returns the result of dividing o1 by o2 giving an integral result, or NULL on failure. This is the equivalent of the Python expression: o1 // o2. */ PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2); /* Returns the result of dividing o1 by o2 giving a float result, or NULL on failure. This is the equivalent of the Python expression: o1 / o2. */ PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2); /* Returns the remainder of dividing o1 by o2, or NULL on failure. This is the equivalent of the Python expression: o1 % o2. */ PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2); /* See the built-in function divmod. Returns NULL on failure. This is the equivalent of the Python expression: divmod(o1, o2). */ PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2); /* See the built-in function pow. Returns NULL on failure. This is the equivalent of the Python expression: pow(o1, o2, o3), where o3 is optional. */ PyAPI_FUNC(PyObject *) PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3); /* Returns the negation of o on success, or NULL on failure. This is the equivalent of the Python expression: -o. */ PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o); /* Returns the positive of o on success, or NULL on failure. This is the equivalent of the Python expression: +o. */ PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o); /* Returns the absolute value of 'o', or NULL on failure. This is the equivalent of the Python expression: abs(o). */ PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o); /* Returns the bitwise negation of 'o' on success, or NULL on failure. This is the equivalent of the Python expression: ~o. */ PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o); /* Returns the result of left shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1 << o2. */ PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2); /* Returns the result of right shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1 >> o2. */ PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2); /* Returns the result of bitwise and of o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1 & o2. */ PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2); /* Returns the bitwise exclusive or of o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1 ^ o2. */ PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2); /* Returns the result of bitwise or on o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1 | o2. */ PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2); /* Returns 1 if obj is an index integer (has the nb_index slot of the tp_as_number structure filled in), and 0 otherwise. */ PyAPI_FUNC(int) PyIndex_Check(PyObject *); /* Returns the object 'o' converted to a Python int, or NULL with an exception raised on failure. */ PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o); /* Returns the object 'o' converted to Py_ssize_t by going through PyNumber_Index() first. If an overflow error occurs while converting the int to Py_ssize_t, then the second argument 'exc' is the error-type to return. If it is NULL, then the overflow error is cleared and the value is clipped. */ PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc); /* Returns the object 'o' converted to an integer object on success, or NULL on failure. This is the equivalent of the Python expression: int(o). */ PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o); /* Returns the object 'o' converted to a float object on success, or NULL on failure. This is the equivalent of the Python expression: float(o). */ PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o); /* --- In-place variants of (some of) the above number protocol functions -- */ /* Returns the result of adding o2 to o1, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 += o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2); /* Returns the result of subtracting o2 from o1, possibly in-place or NULL on failure. This is the equivalent of the Python expression: o1 -= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2); /* Returns the result of multiplying o1 by o2, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 *= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* This is the equivalent of the Python expression: o1 @= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2); #endif /* Returns the result of dividing o1 by o2 giving an integral result, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2); /* Returns the result of dividing o1 by o2 giving a float result, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 /= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2); /* Returns the remainder of dividing o1 by o2, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 %= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2); /* Returns the result of raising o1 to the power of o2, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 **= o2, or o1 = pow(o1, o2, o3) if o3 is present. */ PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3); /* Returns the result of left shifting o1 by o2, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 <<= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2); /* Returns the result of right shifting o1 by o2, possibly in-place or NULL on failure. This is the equivalent of the Python expression: o1 >>= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2); /* Returns the result of bitwise and of o1 and o2, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 &= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2); /* Returns the bitwise exclusive or of o1 by o2, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 ^= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2); /* Returns the result of bitwise or of o1 and o2, possibly in-place, or NULL on failure. This is the equivalent of the Python expression: o1 |= o2. */ PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2); /* Returns the integer n converted to a string with a base, with a base marker of 0b, 0o or 0x prefixed if applicable. If n is not an int object, it is converted with PyNumber_Index first. */ PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base); /* === Sequence protocol ================================================ */ /* Return 1 if the object provides sequence protocol, and zero otherwise. This function always succeeds. */ PyAPI_FUNC(int) PySequence_Check(PyObject *o); /* Return the size of sequence object o, or -1 on failure. */ PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o); /* For DLL compatibility */ #undef PySequence_Length PyAPI_FUNC(Py_ssize_t) PySequence_Length(PyObject *o); #define PySequence_Length PySequence_Size /* Return the concatenation of o1 and o2 on success, and NULL on failure. This is the equivalent of the Python expression: o1 + o2. */ PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2); /* Return the result of repeating sequence object 'o' 'count' times, or NULL on failure. This is the equivalent of the Python expression: o * count. */ PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count); /* Return the ith element of o, or NULL on failure. This is the equivalent of the Python expression: o[i]. */ PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i); /* Return the slice of sequence object o between i1 and i2, or NULL on failure. This is the equivalent of the Python expression: o[i1:i2]. */ PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* Assign object 'v' to the ith element of the sequence 'o'. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o[i] = v. */ PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v); /* Delete the 'i'-th element of the sequence 'v'. Returns -1 on failure. This is the equivalent of the Python statement: del o[i]. */ PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i); /* Assign the sequence object 'v' to the slice in sequence object 'o', from 'i1' to 'i2'. Returns -1 on failure. This is the equivalent of the Python statement: o[i1:i2] = v. */ PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v); /* Delete the slice in sequence object 'o' from 'i1' to 'i2'. Returns -1 on failure. This is the equivalent of the Python statement: del o[i1:i2]. */ PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* Returns the sequence 'o' as a tuple on success, and NULL on failure. This is equivalent to the Python expression: tuple(o). */ PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o); /* Returns the sequence 'o' as a list on success, and NULL on failure. This is equivalent to the Python expression: list(o) */ PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o); /* Return the sequence 'o' as a list, unless it's already a tuple or list. Use PySequence_Fast_GET_ITEM to access the members of this list, and PySequence_Fast_GET_SIZE to get its length. Returns NULL on failure. If the object does not support iteration, raises a TypeError exception with 'm' as the message text. */ PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m); /* Return the size of the sequence 'o', assuming that 'o' was returned by PySequence_Fast and is not NULL. */ #define PySequence_Fast_GET_SIZE(o) \ (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) /* Return the 'i'-th element of the sequence 'o', assuming that o was returned by PySequence_Fast, and that i is within bounds. */ #define PySequence_Fast_GET_ITEM(o, i)\ (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i)) /* Return a pointer to the underlying item array for an object retured by PySequence_Fast */ #define PySequence_Fast_ITEMS(sf) \ (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ : ((PyTupleObject *)(sf))->ob_item) /* Return the number of occurrences on value on 'o', that is, return the number of keys for which o[key] == value. On failure, return -1. This is equivalent to the Python expression: o.count(value). */ PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value); /* Return 1 if 'ob' is in the sequence 'seq'; 0 if 'ob' is not in the sequence 'seq'; -1 on error. Use __contains__ if possible, else _PySequence_IterSearch(). */ PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob); /* For DLL-level backwards compatibility */ #undef PySequence_In /* Determine if the sequence 'o' contains 'value'. If an item in 'o' is equal to 'value', return 1, otherwise return 0. On error, return -1. This is equivalent to the Python expression: value in o. */ PyAPI_FUNC(int) PySequence_In(PyObject *o, PyObject *value); /* For source-level backwards compatibility */ #define PySequence_In PySequence_Contains /* Return the first index for which o[i] == value. On error, return -1. This is equivalent to the Python expression: o.index(value). */ PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value); /* --- In-place versions of some of the above Sequence functions --- */ /* Append sequence 'o2' to sequence 'o1', in-place when possible. Return the resulting object, which could be 'o1', or NULL on failure. This is the equivalent of the Python expression: o1 += o2. */ PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2); /* Repeat sequence 'o' by 'count', in-place when possible. Return the resulting object, which could be 'o', or NULL on failure. This is the equivalent of the Python expression: o1 *= count. */ PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count); /* === Mapping protocol ================================================= */ /* Return 1 if the object provides mapping protocol, and 0 otherwise. This function always succeeds. */ PyAPI_FUNC(int) PyMapping_Check(PyObject *o); /* Returns the number of keys in mapping object 'o' on success, and -1 on failure. This is equivalent to the Python expression: len(o). */ PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o); /* For DLL compatibility */ #undef PyMapping_Length PyAPI_FUNC(Py_ssize_t) PyMapping_Length(PyObject *o); #define PyMapping_Length PyMapping_Size /* Implemented as a macro: int PyMapping_DelItemString(PyObject *o, const char *key); Remove the mapping for the string 'key' from the mapping 'o'. Returns -1 on failure. This is equivalent to the Python statement: del o[key]. */ #define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K)) /* Implemented as a macro: int PyMapping_DelItem(PyObject *o, PyObject *key); Remove the mapping for the object 'key' from the mapping object 'o'. Returns -1 on failure. This is equivalent to the Python statement: del o[key]. */ #define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K)) /* On success, return 1 if the mapping object 'o' has the key 'key', and 0 otherwise. This is equivalent to the Python expression: key in o. This function always succeeds. */ PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, const char *key); /* Return 1 if the mapping object has the key 'key', and 0 otherwise. This is equivalent to the Python expression: key in o. This function always succeeds. */ PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key); /* On success, return a list or tuple of the keys in mapping object 'o'. On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o); /* On success, return a list or tuple of the values in mapping object 'o'. On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o); /* On success, return a list or tuple of the items in mapping object 'o', where each item is a tuple containing a key-value pair. On failure, return NULL. */ PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o); /* Return element of 'o' corresponding to the string 'key' or NULL on failure. This is the equivalent of the Python expression: o[key]. */ PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, const char *key); /* Map the string 'key' to the value 'v' in the mapping 'o'. Returns -1 on failure. This is the equivalent of the Python statement: o[key]=v. */ PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value); /* isinstance(object, typeorclass) */ PyAPI_FUNC(int) PyObject_IsInstance(PyObject *object, PyObject *typeorclass); /* issubclass(object, typeorclass) */ PyAPI_FUNC(int) PyObject_IsSubclass(PyObject *object, PyObject *typeorclass); #ifndef Py_LIMITED_API # define Py_CPYTHON_ABSTRACTOBJECT_H # include "cpython/abstract.h" # undef Py_CPYTHON_ABSTRACTOBJECT_H #endif #ifdef __cplusplus } #endif #endif /* Py_ABSTRACTOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/asdl.h ================================================ #ifndef Py_ASDL_H #define Py_ASDL_H typedef PyObject * identifier; typedef PyObject * string; typedef PyObject * bytes; typedef PyObject * object; typedef PyObject * singleton; typedef PyObject * constant; /* It would be nice if the code generated by asdl_c.py was completely independent of Python, but it is a goal the requires too much work at this stage. So, for example, I'll represent identifiers as interned Python strings. */ /* XXX A sequence should be typed so that its use can be typechecked. */ typedef struct { Py_ssize_t size; void *elements[1]; } asdl_seq; typedef struct { Py_ssize_t size; int elements[1]; } asdl_int_seq; asdl_seq *_Py_asdl_seq_new(Py_ssize_t size, PyArena *arena); asdl_int_seq *_Py_asdl_int_seq_new(Py_ssize_t size, PyArena *arena); #define asdl_seq_GET(S, I) (S)->elements[(I)] #define asdl_seq_LEN(S) ((S) == NULL ? 0 : (S)->size) #ifdef Py_DEBUG #define asdl_seq_SET(S, I, V) \ do { \ Py_ssize_t _asdl_i = (I); \ assert((S) != NULL); \ assert(0 <= _asdl_i && _asdl_i < (S)->size); \ (S)->elements[_asdl_i] = (V); \ } while (0) #else #define asdl_seq_SET(S, I, V) (S)->elements[I] = (V) #endif #endif /* !Py_ASDL_H */ ================================================ FILE: thirdLibs/python3_8/include/ast.h ================================================ #ifndef Py_AST_H #define Py_AST_H #ifdef __cplusplus extern "C" { #endif #include "Python-ast.h" /* mod_ty */ #include "node.h" /* node */ PyAPI_FUNC(int) PyAST_Validate(mod_ty); PyAPI_FUNC(mod_ty) PyAST_FromNode( const node *n, PyCompilerFlags *flags, const char *filename, /* decoded from the filesystem encoding */ PyArena *arena); PyAPI_FUNC(mod_ty) PyAST_FromNodeObject( const node *n, PyCompilerFlags *flags, PyObject *filename, PyArena *arena); #ifndef Py_LIMITED_API /* _PyAST_ExprAsUnicode is defined in ast_unparse.c */ PyAPI_FUNC(PyObject *) _PyAST_ExprAsUnicode(expr_ty); /* Return the borrowed reference to the first literal string in the sequence of statemnts or NULL if it doesn't start from a literal string. Doesn't set exception. */ PyAPI_FUNC(PyObject *) _PyAST_GetDocString(asdl_seq *); #endif /* !Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_AST_H */ ================================================ FILE: thirdLibs/python3_8/include/bitset.h ================================================ #ifndef Py_BITSET_H #define Py_BITSET_H #ifdef __cplusplus extern "C" { #endif /* Bitset interface */ #define BYTE char typedef BYTE *bitset; #define testbit(ss, ibit) (((ss)[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0) #define BITSPERBYTE (8*sizeof(BYTE)) #define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE) #define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE) #define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit)) #ifdef __cplusplus } #endif #endif /* !Py_BITSET_H */ ================================================ FILE: thirdLibs/python3_8/include/bltinmodule.h ================================================ #ifndef Py_BLTINMODULE_H #define Py_BLTINMODULE_H #ifdef __cplusplus extern "C" { #endif PyAPI_DATA(PyTypeObject) PyFilter_Type; PyAPI_DATA(PyTypeObject) PyMap_Type; PyAPI_DATA(PyTypeObject) PyZip_Type; #ifdef __cplusplus } #endif #endif /* !Py_BLTINMODULE_H */ ================================================ FILE: thirdLibs/python3_8/include/boolobject.h ================================================ /* Boolean object interface */ #ifndef Py_BOOLOBJECT_H #define Py_BOOLOBJECT_H #ifdef __cplusplus extern "C" { #endif PyAPI_DATA(PyTypeObject) PyBool_Type; #define PyBool_Check(x) (Py_TYPE(x) == &PyBool_Type) /* Py_False and Py_True are the only two bools in existence. Don't forget to apply Py_INCREF() when returning either!!! */ /* Don't use these directly */ PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct; /* Use these macros */ #define Py_False ((PyObject *) &_Py_FalseStruct) #define Py_True ((PyObject *) &_Py_TrueStruct) /* Macros for returning Py_True or Py_False, respectively */ #define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True #define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False /* Function to return a bool from a C long */ PyAPI_FUNC(PyObject *) PyBool_FromLong(long); #ifdef __cplusplus } #endif #endif /* !Py_BOOLOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/bytearrayobject.h ================================================ /* ByteArray object interface */ #ifndef Py_BYTEARRAYOBJECT_H #define Py_BYTEARRAYOBJECT_H #ifdef __cplusplus extern "C" { #endif #include /* Type PyByteArrayObject represents a mutable array of bytes. * The Python API is that of a sequence; * the bytes are mapped to ints in [0, 256). * Bytes are not characters; they may be used to encode characters. * The only way to go between bytes and str/unicode is via encoding * and decoding. * For the convenience of C programmers, the bytes type is considered * to contain a char pointer, not an unsigned char pointer. */ /* Object layout */ #ifndef Py_LIMITED_API typedef struct { PyObject_VAR_HEAD Py_ssize_t ob_alloc; /* How many bytes allocated in ob_bytes */ char *ob_bytes; /* Physical backing buffer */ char *ob_start; /* Logical start inside ob_bytes */ /* XXX(nnorwitz): should ob_exports be Py_ssize_t? */ int ob_exports; /* How many buffer exports */ } PyByteArrayObject; #endif /* Type object */ PyAPI_DATA(PyTypeObject) PyByteArray_Type; PyAPI_DATA(PyTypeObject) PyByteArrayIter_Type; /* Type check macros */ #define PyByteArray_Check(self) PyObject_TypeCheck(self, &PyByteArray_Type) #define PyByteArray_CheckExact(self) (Py_TYPE(self) == &PyByteArray_Type) /* Direct API functions */ PyAPI_FUNC(PyObject *) PyByteArray_FromObject(PyObject *); PyAPI_FUNC(PyObject *) PyByteArray_Concat(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyByteArray_FromStringAndSize(const char *, Py_ssize_t); PyAPI_FUNC(Py_ssize_t) PyByteArray_Size(PyObject *); PyAPI_FUNC(char *) PyByteArray_AsString(PyObject *); PyAPI_FUNC(int) PyByteArray_Resize(PyObject *, Py_ssize_t); /* Macros, trading safety for speed */ #ifndef Py_LIMITED_API #define PyByteArray_AS_STRING(self) \ (assert(PyByteArray_Check(self)), \ Py_SIZE(self) ? ((PyByteArrayObject *)(self))->ob_start : _PyByteArray_empty_string) #define PyByteArray_GET_SIZE(self) (assert(PyByteArray_Check(self)), Py_SIZE(self)) PyAPI_DATA(char) _PyByteArray_empty_string[]; #endif #ifdef __cplusplus } #endif #endif /* !Py_BYTEARRAYOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/bytes_methods.h ================================================ #ifndef Py_LIMITED_API #ifndef Py_BYTES_CTYPE_H #define Py_BYTES_CTYPE_H /* * The internal implementation behind PyBytes (bytes) and PyByteArray (bytearray) * methods of the given names, they operate on ASCII byte strings. */ extern PyObject* _Py_bytes_isspace(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isalpha(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isalnum(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isascii(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isdigit(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_islower(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isupper(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_istitle(const char *cptr, Py_ssize_t len); /* These store their len sized answer in the given preallocated *result arg. */ extern void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len); extern void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len); extern void _Py_bytes_title(char *result, const char *s, Py_ssize_t len); extern void _Py_bytes_capitalize(char *result, const char *s, Py_ssize_t len); extern void _Py_bytes_swapcase(char *result, const char *s, Py_ssize_t len); extern PyObject *_Py_bytes_find(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_index(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_rfind(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_rindex(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_count(const char *str, Py_ssize_t len, PyObject *args); extern int _Py_bytes_contains(const char *str, Py_ssize_t len, PyObject *arg); extern PyObject *_Py_bytes_startswith(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_endswith(const char *str, Py_ssize_t len, PyObject *args); /* The maketrans() static method. */ extern PyObject* _Py_bytes_maketrans(Py_buffer *frm, Py_buffer *to); /* Shared __doc__ strings. */ extern const char _Py_isspace__doc__[]; extern const char _Py_isalpha__doc__[]; extern const char _Py_isalnum__doc__[]; extern const char _Py_isascii__doc__[]; extern const char _Py_isdigit__doc__[]; extern const char _Py_islower__doc__[]; extern const char _Py_isupper__doc__[]; extern const char _Py_istitle__doc__[]; extern const char _Py_lower__doc__[]; extern const char _Py_upper__doc__[]; extern const char _Py_title__doc__[]; extern const char _Py_capitalize__doc__[]; extern const char _Py_swapcase__doc__[]; extern const char _Py_count__doc__[]; extern const char _Py_find__doc__[]; extern const char _Py_index__doc__[]; extern const char _Py_rfind__doc__[]; extern const char _Py_rindex__doc__[]; extern const char _Py_startswith__doc__[]; extern const char _Py_endswith__doc__[]; extern const char _Py_maketrans__doc__[]; extern const char _Py_expandtabs__doc__[]; extern const char _Py_ljust__doc__[]; extern const char _Py_rjust__doc__[]; extern const char _Py_center__doc__[]; extern const char _Py_zfill__doc__[]; /* this is needed because some docs are shared from the .o, not static */ #define PyDoc_STRVAR_shared(name,str) const char name[] = PyDoc_STR(str) #endif /* !Py_BYTES_CTYPE_H */ #endif /* !Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/bytesobject.h ================================================ /* Bytes (String) object interface */ #ifndef Py_BYTESOBJECT_H #define Py_BYTESOBJECT_H #ifdef __cplusplus extern "C" { #endif #include /* Type PyBytesObject represents a character string. An extra zero byte is reserved at the end to ensure it is zero-terminated, but a size is present so strings with null bytes in them can be represented. This is an immutable object type. There are functions to create new string objects, to test an object for string-ness, and to get the string value. The latter function returns a null pointer if the object is not of the proper type. There is a variant that takes an explicit size as well as a variant that assumes a zero-terminated string. Note that none of the functions should be applied to nil objects. */ /* Caching the hash (ob_shash) saves recalculation of a string's hash value. This significantly speeds up dict lookups. */ #ifndef Py_LIMITED_API typedef struct { PyObject_VAR_HEAD Py_hash_t ob_shash; char ob_sval[1]; /* Invariants: * ob_sval contains space for 'ob_size+1' elements. * ob_sval[ob_size] == 0. * ob_shash is the hash of the string or -1 if not computed yet. */ } PyBytesObject; #endif PyAPI_DATA(PyTypeObject) PyBytes_Type; PyAPI_DATA(PyTypeObject) PyBytesIter_Type; #define PyBytes_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_BYTES_SUBCLASS) #define PyBytes_CheckExact(op) (Py_TYPE(op) == &PyBytes_Type) PyAPI_FUNC(PyObject *) PyBytes_FromStringAndSize(const char *, Py_ssize_t); PyAPI_FUNC(PyObject *) PyBytes_FromString(const char *); PyAPI_FUNC(PyObject *) PyBytes_FromObject(PyObject *); PyAPI_FUNC(PyObject *) PyBytes_FromFormatV(const char*, va_list) Py_GCC_ATTRIBUTE((format(printf, 1, 0))); PyAPI_FUNC(PyObject *) PyBytes_FromFormat(const char*, ...) Py_GCC_ATTRIBUTE((format(printf, 1, 2))); PyAPI_FUNC(Py_ssize_t) PyBytes_Size(PyObject *); PyAPI_FUNC(char *) PyBytes_AsString(PyObject *); PyAPI_FUNC(PyObject *) PyBytes_Repr(PyObject *, int); PyAPI_FUNC(void) PyBytes_Concat(PyObject **, PyObject *); PyAPI_FUNC(void) PyBytes_ConcatAndDel(PyObject **, PyObject *); #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyBytes_Resize(PyObject **, Py_ssize_t); PyAPI_FUNC(PyObject*) _PyBytes_FormatEx( const char *format, Py_ssize_t format_len, PyObject *args, int use_bytearray); PyAPI_FUNC(PyObject*) _PyBytes_FromHex( PyObject *string, int use_bytearray); #endif PyAPI_FUNC(PyObject *) PyBytes_DecodeEscape(const char *, Py_ssize_t, const char *, Py_ssize_t, const char *); #ifndef Py_LIMITED_API /* Helper for PyBytes_DecodeEscape that detects invalid escape chars. */ PyAPI_FUNC(PyObject *) _PyBytes_DecodeEscape(const char *, Py_ssize_t, const char *, Py_ssize_t, const char *, const char **); #endif /* Macro, trading safety for speed */ #ifndef Py_LIMITED_API #define PyBytes_AS_STRING(op) (assert(PyBytes_Check(op)), \ (((PyBytesObject *)(op))->ob_sval)) #define PyBytes_GET_SIZE(op) (assert(PyBytes_Check(op)),Py_SIZE(op)) #endif /* _PyBytes_Join(sep, x) is like sep.join(x). sep must be PyBytesObject*, x must be an iterable object. */ #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyBytes_Join(PyObject *sep, PyObject *x); #endif /* Provides access to the internal data buffer and size of a string object or the default encoded version of a Unicode object. Passing NULL as *len parameter will force the string buffer to be 0-terminated (passing a string with embedded NULL characters will cause an exception). */ PyAPI_FUNC(int) PyBytes_AsStringAndSize( PyObject *obj, /* string or Unicode object */ char **s, /* pointer to buffer variable */ Py_ssize_t *len /* pointer to length variable or NULL (only possible for 0-terminated strings) */ ); /* Using the current locale, insert the thousands grouping into the string pointed to by buffer. For the argument descriptions, see Objects/stringlib/localeutil.h */ #ifndef Py_LIMITED_API PyAPI_FUNC(Py_ssize_t) _PyBytes_InsertThousandsGroupingLocale(char *buffer, Py_ssize_t n_buffer, char *digits, Py_ssize_t n_digits, Py_ssize_t min_width); /* Using explicit passed-in values, insert the thousands grouping into the string pointed to by buffer. For the argument descriptions, see Objects/stringlib/localeutil.h */ PyAPI_FUNC(Py_ssize_t) _PyBytes_InsertThousandsGrouping(char *buffer, Py_ssize_t n_buffer, char *digits, Py_ssize_t n_digits, Py_ssize_t min_width, const char *grouping, const char *thousands_sep); #endif /* Flags used by string formatting */ #define F_LJUST (1<<0) #define F_SIGN (1<<1) #define F_BLANK (1<<2) #define F_ALT (1<<3) #define F_ZERO (1<<4) #ifndef Py_LIMITED_API /* The _PyBytesWriter structure is big: it contains an embedded "stack buffer". A _PyBytesWriter variable must be declared at the end of variables in a function to optimize the memory allocation on the stack. */ typedef struct { /* bytes, bytearray or NULL (when the small buffer is used) */ PyObject *buffer; /* Number of allocated size. */ Py_ssize_t allocated; /* Minimum number of allocated bytes, incremented by _PyBytesWriter_Prepare() */ Py_ssize_t min_size; /* If non-zero, use a bytearray instead of a bytes object for buffer. */ int use_bytearray; /* If non-zero, overallocate the buffer (default: 0). This flag must be zero if use_bytearray is non-zero. */ int overallocate; /* Stack buffer */ int use_small_buffer; char small_buffer[512]; } _PyBytesWriter; /* Initialize a bytes writer By default, the overallocation is disabled. Set the overallocate attribute to control the allocation of the buffer. */ PyAPI_FUNC(void) _PyBytesWriter_Init(_PyBytesWriter *writer); /* Get the buffer content and reset the writer. Return a bytes object, or a bytearray object if use_bytearray is non-zero. Raise an exception and return NULL on error. */ PyAPI_FUNC(PyObject *) _PyBytesWriter_Finish(_PyBytesWriter *writer, void *str); /* Deallocate memory of a writer (clear its internal buffer). */ PyAPI_FUNC(void) _PyBytesWriter_Dealloc(_PyBytesWriter *writer); /* Allocate the buffer to write size bytes. Return the pointer to the beginning of buffer data. Raise an exception and return NULL on error. */ PyAPI_FUNC(void*) _PyBytesWriter_Alloc(_PyBytesWriter *writer, Py_ssize_t size); /* Ensure that the buffer is large enough to write *size* bytes. Add size to the writer minimum size (min_size attribute). str is the current pointer inside the buffer. Return the updated current pointer inside the buffer. Raise an exception and return NULL on error. */ PyAPI_FUNC(void*) _PyBytesWriter_Prepare(_PyBytesWriter *writer, void *str, Py_ssize_t size); /* Resize the buffer to make it larger. The new buffer may be larger than size bytes because of overallocation. Return the updated current pointer inside the buffer. Raise an exception and return NULL on error. Note: size must be greater than the number of allocated bytes in the writer. This function doesn't use the writer minimum size (min_size attribute). See also _PyBytesWriter_Prepare(). */ PyAPI_FUNC(void*) _PyBytesWriter_Resize(_PyBytesWriter *writer, void *str, Py_ssize_t size); /* Write bytes. Raise an exception and return NULL on error. */ PyAPI_FUNC(void*) _PyBytesWriter_WriteBytes(_PyBytesWriter *writer, void *str, const void *bytes, Py_ssize_t size); #endif /* Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_BYTESOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/cellobject.h ================================================ /* Cell object interface */ #ifndef Py_LIMITED_API #ifndef Py_CELLOBJECT_H #define Py_CELLOBJECT_H #ifdef __cplusplus extern "C" { #endif typedef struct { PyObject_HEAD PyObject *ob_ref; /* Content of the cell or NULL when empty */ } PyCellObject; PyAPI_DATA(PyTypeObject) PyCell_Type; #define PyCell_Check(op) (Py_TYPE(op) == &PyCell_Type) PyAPI_FUNC(PyObject *) PyCell_New(PyObject *); PyAPI_FUNC(PyObject *) PyCell_Get(PyObject *); PyAPI_FUNC(int) PyCell_Set(PyObject *, PyObject *); #define PyCell_GET(op) (((PyCellObject *)(op))->ob_ref) #define PyCell_SET(op, v) (((PyCellObject *)(op))->ob_ref = v) #ifdef __cplusplus } #endif #endif /* !Py_TUPLEOBJECT_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/ceval.h ================================================ #ifndef Py_CEVAL_H #define Py_CEVAL_H #ifdef __cplusplus extern "C" { #endif /* Interface to random parts in ceval.c */ /* PyEval_CallObjectWithKeywords(), PyEval_CallObject(), PyEval_CallFunction * and PyEval_CallMethod are kept for backward compatibility: PyObject_Call(), * PyObject_CallFunction() and PyObject_CallMethod() are recommended to call * a callable object. */ PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords( PyObject *callable, PyObject *args, PyObject *kwargs); /* Inline this */ #define PyEval_CallObject(callable, arg) \ PyEval_CallObjectWithKeywords(callable, arg, (PyObject *)NULL) PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *callable, const char *format, ...); PyAPI_FUNC(PyObject *) PyEval_CallMethod(PyObject *obj, const char *name, const char *format, ...); #ifndef Py_LIMITED_API PyAPI_FUNC(void) PyEval_SetProfile(Py_tracefunc, PyObject *); PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *); PyAPI_FUNC(void) _PyEval_SetCoroutineOriginTrackingDepth(int new_depth); PyAPI_FUNC(int) _PyEval_GetCoroutineOriginTrackingDepth(void); PyAPI_FUNC(void) _PyEval_SetAsyncGenFirstiter(PyObject *); PyAPI_FUNC(PyObject *) _PyEval_GetAsyncGenFirstiter(void); PyAPI_FUNC(void) _PyEval_SetAsyncGenFinalizer(PyObject *); PyAPI_FUNC(PyObject *) _PyEval_GetAsyncGenFinalizer(void); #endif struct _frame; /* Avoid including frameobject.h */ PyAPI_FUNC(PyObject *) PyEval_GetBuiltins(void); PyAPI_FUNC(PyObject *) PyEval_GetGlobals(void); PyAPI_FUNC(PyObject *) PyEval_GetLocals(void); PyAPI_FUNC(struct _frame *) PyEval_GetFrame(void); #ifndef Py_LIMITED_API /* Helper to look up a builtin object */ PyAPI_FUNC(PyObject *) _PyEval_GetBuiltinId(_Py_Identifier *); /* Look at the current frame's (if any) code's co_flags, and turn on the corresponding compiler flags in cf->cf_flags. Return 1 if any flag was set, else return 0. */ PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf); #endif PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg); PyAPI_FUNC(int) Py_MakePendingCalls(void); /* Protection against deeply nested recursive calls In Python 3.0, this protection has two levels: * normal anti-recursion protection is triggered when the recursion level exceeds the current recursion limit. It raises a RecursionError, and sets the "overflowed" flag in the thread state structure. This flag temporarily *disables* the normal protection; this allows cleanup code to potentially outgrow the recursion limit while processing the RecursionError. * "last chance" anti-recursion protection is triggered when the recursion level exceeds "current recursion limit + 50". By construction, this protection can only be triggered when the "overflowed" flag is set. It means the cleanup code has itself gone into an infinite loop, or the RecursionError has been mistakingly ignored. When this protection is triggered, the interpreter aborts with a Fatal Error. In addition, the "overflowed" flag is automatically reset when the recursion level drops below "current recursion limit - 50". This heuristic is meant to ensure that the normal anti-recursion protection doesn't get disabled too long. Please note: this scheme has its own limitations. See: http://mail.python.org/pipermail/python-dev/2008-August/082106.html for some observations. */ PyAPI_FUNC(void) Py_SetRecursionLimit(int); PyAPI_FUNC(int) Py_GetRecursionLimit(void); #define Py_EnterRecursiveCall(where) \ (_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \ _Py_CheckRecursiveCall(where)) #define Py_LeaveRecursiveCall() \ do{ if(_Py_MakeEndRecCheck(PyThreadState_GET()->recursion_depth)) \ PyThreadState_GET()->overflowed = 0; \ } while(0) PyAPI_FUNC(int) _Py_CheckRecursiveCall(const char *where); /* Due to the macros in which it's used, _Py_CheckRecursionLimit is in the stable ABI. It should be removed therefrom when possible. */ PyAPI_DATA(int) _Py_CheckRecursionLimit; #ifdef USE_STACKCHECK /* With USE_STACKCHECK, trigger stack checks in _Py_CheckRecursiveCall() on every 64th call to Py_EnterRecursiveCall. */ # define _Py_MakeRecCheck(x) \ (++(x) > _Py_CheckRecursionLimit || \ ++(PyThreadState_GET()->stackcheck_counter) > 64) #else # define _Py_MakeRecCheck(x) (++(x) > _Py_CheckRecursionLimit) #endif /* Compute the "lower-water mark" for a recursion limit. When * Py_LeaveRecursiveCall() is called with a recursion depth below this mark, * the overflowed flag is reset to 0. */ #define _Py_RecursionLimitLowerWaterMark(limit) \ (((limit) > 200) \ ? ((limit) - 50) \ : (3 * ((limit) >> 2))) #define _Py_MakeEndRecCheck(x) \ (--(x) < _Py_RecursionLimitLowerWaterMark(_Py_CheckRecursionLimit)) #define Py_ALLOW_RECURSION \ do { unsigned char _old = PyThreadState_GET()->recursion_critical;\ PyThreadState_GET()->recursion_critical = 1; #define Py_END_ALLOW_RECURSION \ PyThreadState_GET()->recursion_critical = _old; \ } while(0); PyAPI_FUNC(const char *) PyEval_GetFuncName(PyObject *); PyAPI_FUNC(const char *) PyEval_GetFuncDesc(PyObject *); PyAPI_FUNC(PyObject *) PyEval_EvalFrame(struct _frame *); PyAPI_FUNC(PyObject *) PyEval_EvalFrameEx(struct _frame *f, int exc); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyEval_EvalFrameDefault(struct _frame *f, int exc); #endif /* Interface for threads. A module that plans to do a blocking system call (or something else that lasts a long time and doesn't touch Python data) can allow other threads to run as follows: ...preparations here... Py_BEGIN_ALLOW_THREADS ...blocking system call here... Py_END_ALLOW_THREADS ...interpret result here... The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a {}-surrounded block. To leave the block in the middle (e.g., with return), you must insert a line containing Py_BLOCK_THREADS before the return, e.g. if (...premature_exit...) { Py_BLOCK_THREADS PyErr_SetFromErrno(PyExc_OSError); return NULL; } An alternative is: Py_BLOCK_THREADS if (...premature_exit...) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } Py_UNBLOCK_THREADS For convenience, that the value of 'errno' is restored across Py_END_ALLOW_THREADS and Py_BLOCK_THREADS. WARNING: NEVER NEST CALLS TO Py_BEGIN_ALLOW_THREADS AND Py_END_ALLOW_THREADS!!! The function PyEval_InitThreads() should be called only from init_thread() in "_threadmodule.c". Note that not yet all candidates have been converted to use this mechanism! */ PyAPI_FUNC(PyThreadState *) PyEval_SaveThread(void); PyAPI_FUNC(void) PyEval_RestoreThread(PyThreadState *); PyAPI_FUNC(int) PyEval_ThreadsInitialized(void); PyAPI_FUNC(void) PyEval_InitThreads(void); Py_DEPRECATED(3.2) PyAPI_FUNC(void) PyEval_AcquireLock(void); /* Py_DEPRECATED(3.2) */ PyAPI_FUNC(void) PyEval_ReleaseLock(void); PyAPI_FUNC(void) PyEval_AcquireThread(PyThreadState *tstate); PyAPI_FUNC(void) PyEval_ReleaseThread(PyThreadState *tstate); #ifndef Py_LIMITED_API PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds); PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void); #endif #ifndef Py_LIMITED_API PyAPI_FUNC(Py_ssize_t) _PyEval_RequestCodeExtraIndex(freefunc); #endif #define Py_BEGIN_ALLOW_THREADS { \ PyThreadState *_save; \ _save = PyEval_SaveThread(); #define Py_BLOCK_THREADS PyEval_RestoreThread(_save); #define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); #define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ } #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyEval_SliceIndex(PyObject *, Py_ssize_t *); PyAPI_FUNC(int) _PyEval_SliceIndexNotNone(PyObject *, Py_ssize_t *); #endif /* Masks and values used by FORMAT_VALUE opcode. */ #define FVC_MASK 0x3 #define FVC_NONE 0x0 #define FVC_STR 0x1 #define FVC_REPR 0x2 #define FVC_ASCII 0x3 #define FVS_MASK 0x4 #define FVS_HAVE_SPEC 0x4 #ifdef __cplusplus } #endif #endif /* !Py_CEVAL_H */ ================================================ FILE: thirdLibs/python3_8/include/classobject.h ================================================ /* Former class object interface -- now only bound methods are here */ /* Revealing some structures (not for general use) */ #ifndef Py_LIMITED_API #ifndef Py_CLASSOBJECT_H #define Py_CLASSOBJECT_H #ifdef __cplusplus extern "C" { #endif typedef struct { PyObject_HEAD PyObject *im_func; /* The callable object implementing the method */ PyObject *im_self; /* The instance it is bound to */ PyObject *im_weakreflist; /* List of weak references */ vectorcallfunc vectorcall; } PyMethodObject; PyAPI_DATA(PyTypeObject) PyMethod_Type; #define PyMethod_Check(op) ((op)->ob_type == &PyMethod_Type) PyAPI_FUNC(PyObject *) PyMethod_New(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyMethod_Function(PyObject *); PyAPI_FUNC(PyObject *) PyMethod_Self(PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PyMethod_GET_FUNCTION(meth) \ (((PyMethodObject *)meth) -> im_func) #define PyMethod_GET_SELF(meth) \ (((PyMethodObject *)meth) -> im_self) PyAPI_FUNC(int) PyMethod_ClearFreeList(void); typedef struct { PyObject_HEAD PyObject *func; } PyInstanceMethodObject; PyAPI_DATA(PyTypeObject) PyInstanceMethod_Type; #define PyInstanceMethod_Check(op) ((op)->ob_type == &PyInstanceMethod_Type) PyAPI_FUNC(PyObject *) PyInstanceMethod_New(PyObject *); PyAPI_FUNC(PyObject *) PyInstanceMethod_Function(PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PyInstanceMethod_GET_FUNCTION(meth) \ (((PyInstanceMethodObject *)meth) -> func) #ifdef __cplusplus } #endif #endif /* !Py_CLASSOBJECT_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/code.h ================================================ /* Definitions for bytecode */ #ifndef Py_LIMITED_API #ifndef Py_CODE_H #define Py_CODE_H #ifdef __cplusplus extern "C" { #endif typedef uint16_t _Py_CODEUNIT; #ifdef WORDS_BIGENDIAN # define _Py_OPCODE(word) ((word) >> 8) # define _Py_OPARG(word) ((word) & 255) #else # define _Py_OPCODE(word) ((word) & 255) # define _Py_OPARG(word) ((word) >> 8) #endif typedef struct _PyOpcache _PyOpcache; /* Bytecode object */ typedef struct { PyObject_HEAD int co_argcount; /* #arguments, except *args */ int co_posonlyargcount; /* #positional only arguments */ int co_kwonlyargcount; /* #keyword only arguments */ int co_nlocals; /* #local variables */ int co_stacksize; /* #entries needed for evaluation stack */ int co_flags; /* CO_..., see below */ int co_firstlineno; /* first source line number */ PyObject *co_code; /* instruction opcodes */ PyObject *co_consts; /* list (constants used) */ PyObject *co_names; /* list of strings (names used) */ PyObject *co_varnames; /* tuple of strings (local variable names) */ PyObject *co_freevars; /* tuple of strings (free variable names) */ PyObject *co_cellvars; /* tuple of strings (cell variable names) */ /* The rest aren't used in either hash or comparisons, except for co_name, used in both. This is done to preserve the name and line number for tracebacks and debuggers; otherwise, constant de-duplication would collapse identical functions/lambdas defined on different lines. */ Py_ssize_t *co_cell2arg; /* Maps cell vars which are arguments. */ PyObject *co_filename; /* unicode (where it was loaded from) */ PyObject *co_name; /* unicode (name, for reference) */ PyObject *co_lnotab; /* string (encoding addr<->lineno mapping) See Objects/lnotab_notes.txt for details. */ void *co_zombieframe; /* for optimization only (see frameobject.c) */ PyObject *co_weakreflist; /* to support weakrefs to code objects */ /* Scratch space for extra data relating to the code object. Type is a void* to keep the format private in codeobject.c to force people to go through the proper APIs. */ void *co_extra; /* Per opcodes just-in-time cache * * To reduce cache size, we use indirect mapping from opcode index to * cache object: * cache = co_opcache[co_opcache_map[next_instr - first_instr] - 1] */ // co_opcache_map is indexed by (next_instr - first_instr). // * 0 means there is no cache for this opcode. // * n > 0 means there is cache in co_opcache[n-1]. unsigned char *co_opcache_map; _PyOpcache *co_opcache; int co_opcache_flag; // used to determine when create a cache. unsigned char co_opcache_size; // length of co_opcache. } PyCodeObject; /* Masks for co_flags above */ #define CO_OPTIMIZED 0x0001 #define CO_NEWLOCALS 0x0002 #define CO_VARARGS 0x0004 #define CO_VARKEYWORDS 0x0008 #define CO_NESTED 0x0010 #define CO_GENERATOR 0x0020 /* The CO_NOFREE flag is set if there are no free or cell variables. This information is redundant, but it allows a single flag test to determine whether there is any extra work to be done when the call frame it setup. */ #define CO_NOFREE 0x0040 /* The CO_COROUTINE flag is set for coroutine functions (defined with ``async def`` keywords) */ #define CO_COROUTINE 0x0080 #define CO_ITERABLE_COROUTINE 0x0100 #define CO_ASYNC_GENERATOR 0x0200 /* These are no longer used. */ #if 0 #define CO_GENERATOR_ALLOWED 0x1000 #endif #define CO_FUTURE_DIVISION 0x2000 #define CO_FUTURE_ABSOLUTE_IMPORT 0x4000 /* do absolute imports by default */ #define CO_FUTURE_WITH_STATEMENT 0x8000 #define CO_FUTURE_PRINT_FUNCTION 0x10000 #define CO_FUTURE_UNICODE_LITERALS 0x20000 #define CO_FUTURE_BARRY_AS_BDFL 0x40000 #define CO_FUTURE_GENERATOR_STOP 0x80000 #define CO_FUTURE_ANNOTATIONS 0x100000 /* This value is found in the co_cell2arg array when the associated cell variable does not correspond to an argument. */ #define CO_CELL_NOT_AN_ARG (-1) /* This should be defined if a future statement modifies the syntax. For example, when a keyword is added. */ #define PY_PARSER_REQUIRES_FUTURE_KEYWORD #define CO_MAXBLOCKS 20 /* Max static block nesting within a function */ PyAPI_DATA(PyTypeObject) PyCode_Type; #define PyCode_Check(op) (Py_TYPE(op) == &PyCode_Type) #define PyCode_GetNumFree(op) (PyTuple_GET_SIZE((op)->co_freevars)) /* Public interface */ PyAPI_FUNC(PyCodeObject *) PyCode_New( int, int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *); PyAPI_FUNC(PyCodeObject *) PyCode_NewWithPosOnlyArgs( int, int, int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *); /* same as struct above */ /* Creates a new empty code object with the specified source location. */ PyAPI_FUNC(PyCodeObject *) PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno); /* Return the line number associated with the specified bytecode index in this code object. If you just need the line number of a frame, use PyFrame_GetLineNumber() instead. */ PyAPI_FUNC(int) PyCode_Addr2Line(PyCodeObject *, int); /* for internal use only */ typedef struct _addr_pair { int ap_lower; int ap_upper; } PyAddrPair; #ifndef Py_LIMITED_API /* Update *bounds to describe the first and one-past-the-last instructions in the same line as lasti. Return the number of that line. */ PyAPI_FUNC(int) _PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds); /* Create a comparable key used to compare constants taking in account the * object type. It is used to make sure types are not coerced (e.g., float and * complex) _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms * * Return (type(obj), obj, ...): a tuple with variable size (at least 2 items) * depending on the type and the value. The type is the first item to not * compare bytes and str which can raise a BytesWarning exception. */ PyAPI_FUNC(PyObject*) _PyCode_ConstantKey(PyObject *obj); #endif PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names, PyObject *lnotab); #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra); PyAPI_FUNC(int) _PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra); #endif #ifdef __cplusplus } #endif #endif /* !Py_CODE_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/codecs.h ================================================ #ifndef Py_CODECREGISTRY_H #define Py_CODECREGISTRY_H #ifdef __cplusplus extern "C" { #endif /* ------------------------------------------------------------------------ Python Codec Registry and support functions Written by Marc-Andre Lemburg (mal@lemburg.com). Copyright (c) Corporation for National Research Initiatives. ------------------------------------------------------------------------ */ /* Register a new codec search function. As side effect, this tries to load the encodings package, if not yet done, to make sure that it is always first in the list of search functions. The search_function's refcount is incremented by this function. */ PyAPI_FUNC(int) PyCodec_Register( PyObject *search_function ); /* Codec registry lookup API. Looks up the given encoding and returns a CodecInfo object with function attributes which implement the different aspects of processing the encoding. The encoding string is looked up converted to all lower-case characters. This makes encodings looked up through this mechanism effectively case-insensitive. If no codec is found, a KeyError is set and NULL returned. As side effect, this tries to load the encodings package, if not yet done. This is part of the lazy load strategy for the encodings package. */ #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyCodec_Lookup( const char *encoding ); PyAPI_FUNC(int) _PyCodec_Forget( const char *encoding ); #endif /* Codec registry encoding check API. Returns 1/0 depending on whether there is a registered codec for the given encoding. */ PyAPI_FUNC(int) PyCodec_KnownEncoding( const char *encoding ); /* Generic codec based encoding API. object is passed through the encoder function found for the given encoding using the error handling method defined by errors. errors may be NULL to use the default method defined for the codec. Raises a LookupError in case no encoder can be found. */ PyAPI_FUNC(PyObject *) PyCodec_Encode( PyObject *object, const char *encoding, const char *errors ); /* Generic codec based decoding API. object is passed through the decoder function found for the given encoding using the error handling method defined by errors. errors may be NULL to use the default method defined for the codec. Raises a LookupError in case no encoder can be found. */ PyAPI_FUNC(PyObject *) PyCodec_Decode( PyObject *object, const char *encoding, const char *errors ); #ifndef Py_LIMITED_API /* Text codec specific encoding and decoding API. Checks the encoding against a list of codecs which do not implement a str<->bytes encoding before attempting the operation. Please note that these APIs are internal and should not be used in Python C extensions. XXX (ncoghlan): should we make these, or something like them, public in Python 3.5+? */ PyAPI_FUNC(PyObject *) _PyCodec_LookupTextEncoding( const char *encoding, const char *alternate_command ); PyAPI_FUNC(PyObject *) _PyCodec_EncodeText( PyObject *object, const char *encoding, const char *errors ); PyAPI_FUNC(PyObject *) _PyCodec_DecodeText( PyObject *object, const char *encoding, const char *errors ); /* These two aren't actually text encoding specific, but _io.TextIOWrapper * is the only current API consumer. */ PyAPI_FUNC(PyObject *) _PyCodecInfo_GetIncrementalDecoder( PyObject *codec_info, const char *errors ); PyAPI_FUNC(PyObject *) _PyCodecInfo_GetIncrementalEncoder( PyObject *codec_info, const char *errors ); #endif /* --- Codec Lookup APIs -------------------------------------------------- All APIs return a codec object with incremented refcount and are based on _PyCodec_Lookup(). The same comments w/r to the encoding name also apply to these APIs. */ /* Get an encoder function for the given encoding. */ PyAPI_FUNC(PyObject *) PyCodec_Encoder( const char *encoding ); /* Get a decoder function for the given encoding. */ PyAPI_FUNC(PyObject *) PyCodec_Decoder( const char *encoding ); /* Get an IncrementalEncoder object for the given encoding. */ PyAPI_FUNC(PyObject *) PyCodec_IncrementalEncoder( const char *encoding, const char *errors ); /* Get an IncrementalDecoder object function for the given encoding. */ PyAPI_FUNC(PyObject *) PyCodec_IncrementalDecoder( const char *encoding, const char *errors ); /* Get a StreamReader factory function for the given encoding. */ PyAPI_FUNC(PyObject *) PyCodec_StreamReader( const char *encoding, PyObject *stream, const char *errors ); /* Get a StreamWriter factory function for the given encoding. */ PyAPI_FUNC(PyObject *) PyCodec_StreamWriter( const char *encoding, PyObject *stream, const char *errors ); /* Unicode encoding error handling callback registry API */ /* Register the error handling callback function error under the given name. This function will be called by the codec when it encounters unencodable characters/undecodable bytes and doesn't know the callback name, when name is specified as the error parameter in the call to the encode/decode function. Return 0 on success, -1 on error */ PyAPI_FUNC(int) PyCodec_RegisterError(const char *name, PyObject *error); /* Lookup the error handling callback function registered under the given name. As a special case NULL can be passed, in which case the error handling callback for "strict" will be returned. */ PyAPI_FUNC(PyObject *) PyCodec_LookupError(const char *name); /* raise exc as an exception */ PyAPI_FUNC(PyObject *) PyCodec_StrictErrors(PyObject *exc); /* ignore the unicode error, skipping the faulty input */ PyAPI_FUNC(PyObject *) PyCodec_IgnoreErrors(PyObject *exc); /* replace the unicode encode error with ? or U+FFFD */ PyAPI_FUNC(PyObject *) PyCodec_ReplaceErrors(PyObject *exc); /* replace the unicode encode error with XML character references */ PyAPI_FUNC(PyObject *) PyCodec_XMLCharRefReplaceErrors(PyObject *exc); /* replace the unicode encode error with backslash escapes (\x, \u and \U) */ PyAPI_FUNC(PyObject *) PyCodec_BackslashReplaceErrors(PyObject *exc); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* replace the unicode encode error with backslash escapes (\N, \x, \u and \U) */ PyAPI_FUNC(PyObject *) PyCodec_NameReplaceErrors(PyObject *exc); #endif #ifndef Py_LIMITED_API PyAPI_DATA(const char *) Py_hexdigits; #endif #ifdef __cplusplus } #endif #endif /* !Py_CODECREGISTRY_H */ ================================================ FILE: thirdLibs/python3_8/include/compile.h ================================================ #ifndef Py_COMPILE_H #define Py_COMPILE_H #ifndef Py_LIMITED_API #include "code.h" #ifdef __cplusplus extern "C" { #endif /* Public interface */ struct _node; /* Declare the existence of this type */ PyAPI_FUNC(PyCodeObject *) PyNode_Compile(struct _node *, const char *); /* XXX (ncoghlan): Unprefixed type name in a public API! */ #define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | \ CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | \ CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL | \ CO_FUTURE_GENERATOR_STOP | CO_FUTURE_ANNOTATIONS) #define PyCF_MASK_OBSOLETE (CO_NESTED) #define PyCF_SOURCE_IS_UTF8 0x0100 #define PyCF_DONT_IMPLY_DEDENT 0x0200 #define PyCF_ONLY_AST 0x0400 #define PyCF_IGNORE_COOKIE 0x0800 #define PyCF_TYPE_COMMENTS 0x1000 #define PyCF_ALLOW_TOP_LEVEL_AWAIT 0x2000 #ifndef Py_LIMITED_API typedef struct { int cf_flags; /* bitmask of CO_xxx flags relevant to future */ int cf_feature_version; /* minor Python version (PyCF_ONLY_AST) */ } PyCompilerFlags; #define _PyCompilerFlags_INIT \ (PyCompilerFlags){.cf_flags = 0, .cf_feature_version = PY_MINOR_VERSION} #endif /* Future feature support */ typedef struct { int ff_features; /* flags set by future statements */ int ff_lineno; /* line number of last future statement */ } PyFutureFeatures; #define FUTURE_NESTED_SCOPES "nested_scopes" #define FUTURE_GENERATORS "generators" #define FUTURE_DIVISION "division" #define FUTURE_ABSOLUTE_IMPORT "absolute_import" #define FUTURE_WITH_STATEMENT "with_statement" #define FUTURE_PRINT_FUNCTION "print_function" #define FUTURE_UNICODE_LITERALS "unicode_literals" #define FUTURE_BARRY_AS_BDFL "barry_as_FLUFL" #define FUTURE_GENERATOR_STOP "generator_stop" #define FUTURE_ANNOTATIONS "annotations" struct _mod; /* Declare the existence of this type */ #define PyAST_Compile(mod, s, f, ar) PyAST_CompileEx(mod, s, f, -1, ar) PyAPI_FUNC(PyCodeObject *) PyAST_CompileEx( struct _mod *mod, const char *filename, /* decoded from the filesystem encoding */ PyCompilerFlags *flags, int optimize, PyArena *arena); PyAPI_FUNC(PyCodeObject *) PyAST_CompileObject( struct _mod *mod, PyObject *filename, PyCompilerFlags *flags, int optimize, PyArena *arena); PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromAST( struct _mod * mod, const char *filename /* decoded from the filesystem encoding */ ); PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromASTObject( struct _mod * mod, PyObject *filename ); /* _Py_Mangle is defined in compile.c */ PyAPI_FUNC(PyObject*) _Py_Mangle(PyObject *p, PyObject *name); #define PY_INVALID_STACK_EFFECT INT_MAX PyAPI_FUNC(int) PyCompile_OpcodeStackEffect(int opcode, int oparg); PyAPI_FUNC(int) PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump); PyAPI_FUNC(int) _PyAST_Optimize(struct _mod *, PyArena *arena, int optimize); #ifdef __cplusplus } #endif #endif /* !Py_LIMITED_API */ /* These definitions must match corresponding definitions in graminit.h. */ #define Py_single_input 256 #define Py_file_input 257 #define Py_eval_input 258 #define Py_func_type_input 345 #endif /* !Py_COMPILE_H */ ================================================ FILE: thirdLibs/python3_8/include/complexobject.h ================================================ /* Complex number structure */ #ifndef Py_COMPLEXOBJECT_H #define Py_COMPLEXOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API typedef struct { double real; double imag; } Py_complex; /* Operations on complex numbers from complexmodule.c */ PyAPI_FUNC(Py_complex) _Py_c_sum(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) _Py_c_diff(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) _Py_c_neg(Py_complex); PyAPI_FUNC(Py_complex) _Py_c_prod(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) _Py_c_quot(Py_complex, Py_complex); PyAPI_FUNC(Py_complex) _Py_c_pow(Py_complex, Py_complex); PyAPI_FUNC(double) _Py_c_abs(Py_complex); #endif /* Complex object interface */ /* PyComplexObject represents a complex number with double-precision real and imaginary parts. */ #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD Py_complex cval; } PyComplexObject; #endif PyAPI_DATA(PyTypeObject) PyComplex_Type; #define PyComplex_Check(op) PyObject_TypeCheck(op, &PyComplex_Type) #define PyComplex_CheckExact(op) (Py_TYPE(op) == &PyComplex_Type) #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) PyComplex_FromCComplex(Py_complex); #endif PyAPI_FUNC(PyObject *) PyComplex_FromDoubles(double real, double imag); PyAPI_FUNC(double) PyComplex_RealAsDouble(PyObject *op); PyAPI_FUNC(double) PyComplex_ImagAsDouble(PyObject *op); #ifndef Py_LIMITED_API PyAPI_FUNC(Py_complex) PyComplex_AsCComplex(PyObject *op); #endif /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyComplex_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); #endif #ifdef __cplusplus } #endif #endif /* !Py_COMPLEXOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/context.h ================================================ #ifndef Py_CONTEXT_H #define Py_CONTEXT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API PyAPI_DATA(PyTypeObject) PyContext_Type; typedef struct _pycontextobject PyContext; PyAPI_DATA(PyTypeObject) PyContextVar_Type; typedef struct _pycontextvarobject PyContextVar; PyAPI_DATA(PyTypeObject) PyContextToken_Type; typedef struct _pycontexttokenobject PyContextToken; #define PyContext_CheckExact(o) (Py_TYPE(o) == &PyContext_Type) #define PyContextVar_CheckExact(o) (Py_TYPE(o) == &PyContextVar_Type) #define PyContextToken_CheckExact(o) (Py_TYPE(o) == &PyContextToken_Type) PyAPI_FUNC(PyObject *) PyContext_New(void); PyAPI_FUNC(PyObject *) PyContext_Copy(PyObject *); PyAPI_FUNC(PyObject *) PyContext_CopyCurrent(void); PyAPI_FUNC(int) PyContext_Enter(PyObject *); PyAPI_FUNC(int) PyContext_Exit(PyObject *); /* Create a new context variable. default_value can be NULL. */ PyAPI_FUNC(PyObject *) PyContextVar_New( const char *name, PyObject *default_value); /* Get a value for the variable. Returns -1 if an error occurred during lookup. Returns 0 if value either was or was not found. If value was found, *value will point to it. If not, it will point to: - default_value, if not NULL; - the default value of "var", if not NULL; - NULL. '*value' will be a new ref, if not NULL. */ PyAPI_FUNC(int) PyContextVar_Get( PyObject *var, PyObject *default_value, PyObject **value); /* Set a new value for the variable. Returns NULL if an error occurs. */ PyAPI_FUNC(PyObject *) PyContextVar_Set(PyObject *var, PyObject *value); /* Reset a variable to its previous value. Returns 0 on success, -1 on error. */ PyAPI_FUNC(int) PyContextVar_Reset(PyObject *var, PyObject *token); /* This method is exposed only for CPython tests. Don not use it. */ PyAPI_FUNC(PyObject *) _PyContext_NewHamtForTests(void); PyAPI_FUNC(int) PyContext_ClearFreeList(void); #endif /* !Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_CONTEXT_H */ ================================================ FILE: thirdLibs/python3_8/include/cpython/abstract.h ================================================ #ifndef Py_CPYTHON_ABSTRACTOBJECT_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif /* === Object Protocol ================================================== */ #ifdef PY_SSIZE_T_CLEAN # define _PyObject_CallMethodId _PyObject_CallMethodId_SizeT #endif /* Convert keyword arguments from the FASTCALL (stack: C array, kwnames: tuple) format to a Python dictionary ("kwargs" dict). The type of kwnames keys is not checked. The final function getting arguments is responsible to check if all keys are strings, for example using PyArg_ParseTupleAndKeywords() or PyArg_ValidateKeywordArguments(). Duplicate keys are merged using the last value. If duplicate keys must raise an exception, the caller is responsible to implement an explicit keys on kwnames. */ PyAPI_FUNC(PyObject *) _PyStack_AsDict( PyObject *const *values, PyObject *kwnames); /* Convert (args, nargs, kwargs: dict) into a (stack, nargs, kwnames: tuple). Return 0 on success, raise an exception and return -1 on error. Write the new stack into *p_stack. If *p_stack is differen than args, it must be released by PyMem_Free(). The stack uses borrowed references. The type of keyword keys is not checked, these checks should be done later (ex: _PyArg_ParseStackAndKeywords). */ PyAPI_FUNC(int) _PyStack_UnpackDict( PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs, PyObject *const **p_stack, PyObject **p_kwnames); /* Suggested size (number of positional arguments) for arrays of PyObject* allocated on a C stack to avoid allocating memory on the heap memory. Such array is used to pass positional arguments to call functions of the _PyObject_Vectorcall() family. The size is chosen to not abuse the C stack and so limit the risk of stack overflow. The size is also chosen to allow using the small stack for most function calls of the Python standard library. On 64-bit CPU, it allocates 40 bytes on the stack. */ #define _PY_FASTCALL_SMALL_STACK 5 PyAPI_FUNC(PyObject *) _Py_CheckFunctionResult(PyObject *callable, PyObject *result, const char *where); /* === Vectorcall protocol (PEP 590) ============================= */ /* Call callable using tp_call. Arguments are like _PyObject_Vectorcall() or _PyObject_FastCallDict() (both forms are supported), except that nargs is plainly the number of arguments without flags. */ PyAPI_FUNC(PyObject *) _PyObject_MakeTpCall( PyObject *callable, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords); #define PY_VECTORCALL_ARGUMENTS_OFFSET ((size_t)1 << (8 * sizeof(size_t) - 1)) static inline Py_ssize_t PyVectorcall_NARGS(size_t n) { return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET; } static inline vectorcallfunc _PyVectorcall_Function(PyObject *callable) { PyTypeObject *tp = Py_TYPE(callable); Py_ssize_t offset = tp->tp_vectorcall_offset; vectorcallfunc *ptr; if (!PyType_HasFeature(tp, _Py_TPFLAGS_HAVE_VECTORCALL)) { return NULL; } assert(PyCallable_Check(callable)); assert(offset > 0); ptr = (vectorcallfunc*)(((char *)callable) + offset); return *ptr; } /* Call the callable object 'callable' with the "vectorcall" calling convention. args is a C array for positional arguments. nargsf is the number of positional arguments plus optionally the flag PY_VECTORCALL_ARGUMENTS_OFFSET which means that the caller is allowed to modify args[-1]. kwnames is a tuple of keyword names. The values of the keyword arguments are stored in "args" after the positional arguments (note that the number of keyword arguments does not change nargsf). kwnames can also be NULL if there are no keyword arguments. keywords must only contains str strings (no subclass), and all keys must be unique. Return the result on success. Raise an exception and return NULL on error. */ static inline PyObject * _PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames) { PyObject *res; vectorcallfunc func; assert(kwnames == NULL || PyTuple_Check(kwnames)); assert(args != NULL || PyVectorcall_NARGS(nargsf) == 0); func = _PyVectorcall_Function(callable); if (func == NULL) { Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); return _PyObject_MakeTpCall(callable, args, nargs, kwnames); } res = func(callable, args, nargsf, kwnames); return _Py_CheckFunctionResult(callable, res, NULL); } /* Same as _PyObject_Vectorcall except that keyword arguments are passed as dict, which may be NULL if there are no keyword arguments. */ PyAPI_FUNC(PyObject *) _PyObject_FastCallDict( PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwargs); /* Call "callable" (which must support vectorcall) with positional arguments "tuple" and keyword arguments "dict". "dict" may also be NULL */ PyAPI_FUNC(PyObject *) PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict); /* Same as _PyObject_Vectorcall except without keyword arguments */ static inline PyObject * _PyObject_FastCall(PyObject *func, PyObject *const *args, Py_ssize_t nargs) { return _PyObject_Vectorcall(func, args, (size_t)nargs, NULL); } /* Call a callable without any arguments */ static inline PyObject * _PyObject_CallNoArg(PyObject *func) { return _PyObject_Vectorcall(func, NULL, 0, NULL); } PyAPI_FUNC(PyObject *) _PyObject_Call_Prepend( PyObject *callable, PyObject *obj, PyObject *args, PyObject *kwargs); PyAPI_FUNC(PyObject *) _PyObject_FastCall_Prepend( PyObject *callable, PyObject *obj, PyObject *const *args, Py_ssize_t nargs); /* Like PyObject_CallMethod(), but expect a _Py_Identifier* as the method name. */ PyAPI_FUNC(PyObject *) _PyObject_CallMethodId(PyObject *obj, _Py_Identifier *name, const char *format, ...); PyAPI_FUNC(PyObject *) _PyObject_CallMethodId_SizeT(PyObject *obj, _Py_Identifier *name, const char *format, ...); PyAPI_FUNC(PyObject *) _PyObject_CallMethodIdObjArgs( PyObject *obj, struct _Py_Identifier *name, ...); PyAPI_FUNC(int) _PyObject_HasLen(PyObject *o); /* Guess the size of object 'o' using len(o) or o.__length_hint__(). If neither of those return a non-negative value, then return the default value. If one of the calls fails, this function returns -1. */ PyAPI_FUNC(Py_ssize_t) PyObject_LengthHint(PyObject *o, Py_ssize_t); /* === New Buffer API ============================================ */ /* Return 1 if the getbuffer function is available, otherwise return 0. */ #define PyObject_CheckBuffer(obj) \ (((obj)->ob_type->tp_as_buffer != NULL) && \ ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) /* This is a C-API version of the getbuffer function call. It checks to make sure object has the required function pointer and issues the call. Returns -1 and raises an error on failure and returns 0 on success. */ PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags); /* Get the memory area pointed to by the indices for the buffer given. Note that view->ndim is the assumed size of indices. */ PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices); /* Return the implied itemsize of the data-format area from a struct-style description. */ PyAPI_FUNC(int) PyBuffer_SizeFromFormat(const char *); /* Implementation in memoryobject.c */ PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char order); PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char order); /* Copy len bytes of data from the contiguous chunk of memory pointed to by buf into the buffer exported by obj. Return 0 on success and return -1 and raise a PyBuffer_Error on error (i.e. the object does not have a buffer interface or it is not working). If fort is 'F', then if the object is multi-dimensional, then the data will be copied into the array in Fortran-style (first dimension varies the fastest). If fort is 'C', then the data will be copied into the array in C-style (last dimension varies the fastest). If fort is 'A', then it does not matter and the copy will be made in whatever way is more efficient. */ PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src); /* Copy the data from the src buffer to the buffer of destination. */ PyAPI_FUNC(int) PyBuffer_IsContiguous(const Py_buffer *view, char fort); /*Fill the strides array with byte-strides of a contiguous (Fortran-style if fort is 'F' or C-style otherwise) array of the given shape with the given number of bytes per element. */ PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char fort); /* Fills in a buffer-info structure correctly for an exporter that can only share a contiguous chunk of memory of "unsigned bytes" of the given length. Returns 0 on success and -1 (with raising an error) on error. */ PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf, Py_ssize_t len, int readonly, int flags); /* Releases a Py_buffer obtained from getbuffer ParseTuple's "s*". */ PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view); /* ==== Iterators ================================================ */ #define PyIter_Check(obj) \ ((obj)->ob_type->tp_iternext != NULL && \ (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented) /* === Number Protocol ================================================== */ #define PyIndex_Check(obj) \ ((obj)->ob_type->tp_as_number != NULL && \ (obj)->ob_type->tp_as_number->nb_index != NULL) /* === Sequence protocol ================================================ */ /* Assume tp_as_sequence and sq_item exist and that 'i' does not need to be corrected for a negative index. */ #define PySequence_ITEM(o, i)\ ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) ) #define PY_ITERSEARCH_COUNT 1 #define PY_ITERSEARCH_INDEX 2 #define PY_ITERSEARCH_CONTAINS 3 /* Iterate over seq. Result depends on the operation: PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if error. PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of obj in seq; set ValueError and return -1 if none found; also return -1 on error. PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error. */ PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation); /* === Mapping protocol ================================================= */ PyAPI_FUNC(int) _PyObject_RealIsInstance(PyObject *inst, PyObject *cls); PyAPI_FUNC(int) _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls); PyAPI_FUNC(char *const *) _PySequence_BytesToCharpArray(PyObject* self); PyAPI_FUNC(void) _Py_FreeCharPArray(char *const array[]); /* For internal use by buffer API functions */ PyAPI_FUNC(void) _Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape); PyAPI_FUNC(void) _Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape); /* Convert Python int to Py_ssize_t. Do nothing if the argument is None. */ PyAPI_FUNC(int) _Py_convert_optional_to_ssize_t(PyObject *, void *); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/dictobject.h ================================================ #ifndef Py_CPYTHON_DICTOBJECT_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif typedef struct _dictkeysobject PyDictKeysObject; /* The ma_values pointer is NULL for a combined table * or points to an array of PyObject* for a split table */ typedef struct { PyObject_HEAD /* Number of items in the dictionary */ Py_ssize_t ma_used; /* Dictionary version: globally unique, value change each time the dictionary is modified */ uint64_t ma_version_tag; PyDictKeysObject *ma_keys; /* If ma_values is NULL, the table is "combined": keys and values are stored in ma_keys. If ma_values is not NULL, the table is splitted: keys are stored in ma_keys and values are stored in ma_values */ PyObject **ma_values; } PyDictObject; PyAPI_FUNC(PyObject *) _PyDict_GetItem_KnownHash(PyObject *mp, PyObject *key, Py_hash_t hash); PyAPI_FUNC(PyObject *) _PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key); PyAPI_FUNC(PyObject *) _PyDict_GetItemStringWithError(PyObject *, const char *); PyAPI_FUNC(PyObject *) PyDict_SetDefault( PyObject *mp, PyObject *key, PyObject *defaultobj); PyAPI_FUNC(int) _PyDict_SetItem_KnownHash(PyObject *mp, PyObject *key, PyObject *item, Py_hash_t hash); PyAPI_FUNC(int) _PyDict_DelItem_KnownHash(PyObject *mp, PyObject *key, Py_hash_t hash); PyAPI_FUNC(int) _PyDict_DelItemIf(PyObject *mp, PyObject *key, int (*predicate)(PyObject *value)); PyDictKeysObject *_PyDict_NewKeysForClass(void); PyAPI_FUNC(PyObject *) PyObject_GenericGetDict(PyObject *, void *); PyAPI_FUNC(int) _PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, Py_hash_t *hash); /* Get the number of items of a dictionary. */ #define PyDict_GET_SIZE(mp) (assert(PyDict_Check(mp)),((PyDictObject *)mp)->ma_used) PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, Py_hash_t hash); PyAPI_FUNC(PyObject *) _PyDict_NewPresized(Py_ssize_t minused); PyAPI_FUNC(void) _PyDict_MaybeUntrack(PyObject *mp); PyAPI_FUNC(int) _PyDict_HasOnlyStringKeys(PyObject *mp); Py_ssize_t _PyDict_KeysSize(PyDictKeysObject *keys); PyAPI_FUNC(Py_ssize_t) _PyDict_SizeOf(PyDictObject *); PyAPI_FUNC(PyObject *) _PyDict_Pop(PyObject *, PyObject *, PyObject *); PyObject *_PyDict_Pop_KnownHash(PyObject *, PyObject *, Py_hash_t, PyObject *); PyObject *_PyDict_FromKeys(PyObject *, PyObject *, PyObject *); #define _PyDict_HasSplitTable(d) ((d)->ma_values != NULL) PyAPI_FUNC(int) PyDict_ClearFreeList(void); /* Like PyDict_Merge, but override can be 0, 1 or 2. If override is 0, the first occurrence of a key wins, if override is 1, the last occurrence of a key wins, if override is 2, a KeyError with conflicting key as argument is raised. */ PyAPI_FUNC(int) _PyDict_MergeEx(PyObject *mp, PyObject *other, int override); PyAPI_FUNC(PyObject *) _PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key); PyAPI_FUNC(int) _PyDict_SetItemId(PyObject *dp, struct _Py_Identifier *key, PyObject *item); PyAPI_FUNC(int) _PyDict_DelItemId(PyObject *mp, struct _Py_Identifier *key); PyAPI_FUNC(void) _PyDict_DebugMallocStats(FILE *out); int _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr, PyObject *name, PyObject *value); PyObject *_PyDict_LoadGlobal(PyDictObject *, PyDictObject *, PyObject *); /* _PyDictView */ typedef struct { PyObject_HEAD PyDictObject *dv_dict; } _PyDictViewObject; PyAPI_FUNC(PyObject *) _PyDictView_New(PyObject *, PyTypeObject *); PyAPI_FUNC(PyObject *) _PyDictView_Intersect(PyObject* self, PyObject *other); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/fileobject.h ================================================ #ifndef Py_CPYTHON_FILEOBJECT_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(char *) Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 PyAPI_DATA(const char *) Py_FileSystemDefaultEncodeErrors; #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000 PyAPI_DATA(int) Py_UTF8Mode; #endif /* The std printer acts as a preliminary sys.stderr until the new io infrastructure is in place. */ PyAPI_FUNC(PyObject *) PyFile_NewStdPrinter(int); PyAPI_DATA(PyTypeObject) PyStdPrinter_Type; typedef PyObject * (*Py_OpenCodeHookFunction)(PyObject *, void *); PyAPI_FUNC(PyObject *) PyFile_OpenCode(const char *utf8path); PyAPI_FUNC(PyObject *) PyFile_OpenCodeObject(PyObject *path); PyAPI_FUNC(int) PyFile_SetOpenCodeHook(Py_OpenCodeHookFunction hook, void *userData); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/initconfig.h ================================================ #ifndef Py_PYCORECONFIG_H #define Py_PYCORECONFIG_H #ifndef Py_LIMITED_API #ifdef __cplusplus extern "C" { #endif /* --- PyStatus ----------------------------------------------- */ typedef struct { enum { _PyStatus_TYPE_OK=0, _PyStatus_TYPE_ERROR=1, _PyStatus_TYPE_EXIT=2 } _type; const char *func; const char *err_msg; int exitcode; } PyStatus; PyAPI_FUNC(PyStatus) PyStatus_Ok(void); PyAPI_FUNC(PyStatus) PyStatus_Error(const char *err_msg); PyAPI_FUNC(PyStatus) PyStatus_NoMemory(void); PyAPI_FUNC(PyStatus) PyStatus_Exit(int exitcode); PyAPI_FUNC(int) PyStatus_IsError(PyStatus err); PyAPI_FUNC(int) PyStatus_IsExit(PyStatus err); PyAPI_FUNC(int) PyStatus_Exception(PyStatus err); /* --- PyWideStringList ------------------------------------------------ */ typedef struct { /* If length is greater than zero, items must be non-NULL and all items strings must be non-NULL */ Py_ssize_t length; wchar_t **items; } PyWideStringList; PyAPI_FUNC(PyStatus) PyWideStringList_Append(PyWideStringList *list, const wchar_t *item); PyAPI_FUNC(PyStatus) PyWideStringList_Insert(PyWideStringList *list, Py_ssize_t index, const wchar_t *item); /* --- PyPreConfig ----------------------------------------------- */ typedef struct { int _config_init; /* _PyConfigInitEnum value */ /* Parse Py_PreInitializeFromBytesArgs() arguments? See PyConfig.parse_argv */ int parse_argv; /* If greater than 0, enable isolated mode: sys.path contains neither the script's directory nor the user's site-packages directory. Set to 1 by the -I command line option. If set to -1 (default), inherit Py_IsolatedFlag value. */ int isolated; /* If greater than 0: use environment variables. Set to 0 by -E command line option. If set to -1 (default), it is set to !Py_IgnoreEnvironmentFlag. */ int use_environment; /* Set the LC_CTYPE locale to the user preferred locale? If equals to 0, set coerce_c_locale and coerce_c_locale_warn to 0. */ int configure_locale; /* Coerce the LC_CTYPE locale if it's equal to "C"? (PEP 538) Set to 0 by PYTHONCOERCECLOCALE=0. Set to 1 by PYTHONCOERCECLOCALE=1. Set to 2 if the user preferred LC_CTYPE locale is "C". If it is equal to 1, LC_CTYPE locale is read to decide if it should be coerced or not (ex: PYTHONCOERCECLOCALE=1). Internally, it is set to 2 if the LC_CTYPE locale must be coerced. Disable by default (set to 0). Set it to -1 to let Python decide if it should be enabled or not. */ int coerce_c_locale; /* Emit a warning if the LC_CTYPE locale is coerced? Set to 1 by PYTHONCOERCECLOCALE=warn. Disable by default (set to 0). Set it to -1 to let Python decide if it should be enabled or not. */ int coerce_c_locale_warn; #ifdef MS_WINDOWS /* If greater than 1, use the "mbcs" encoding instead of the UTF-8 encoding for the filesystem encoding. Set to 1 if the PYTHONLEGACYWINDOWSFSENCODING environment variable is set to a non-empty string. If set to -1 (default), inherit Py_LegacyWindowsFSEncodingFlag value. See PEP 529 for more details. */ int legacy_windows_fs_encoding; #endif /* Enable UTF-8 mode? (PEP 540) Disabled by default (equals to 0). Set to 1 by "-X utf8" and "-X utf8=1" command line options. Set to 1 by PYTHONUTF8=1 environment variable. Set to 0 by "-X utf8=0" and PYTHONUTF8=0. If equals to -1, it is set to 1 if the LC_CTYPE locale is "C" or "POSIX", otherwise it is set to 0. Inherit Py_UTF8Mode value value. */ int utf8_mode; int dev_mode; /* Development mode. PYTHONDEVMODE, -X dev */ /* Memory allocator: PYTHONMALLOC env var. See PyMemAllocatorName for valid values. */ int allocator; } PyPreConfig; PyAPI_FUNC(void) PyPreConfig_InitPythonConfig(PyPreConfig *config); PyAPI_FUNC(void) PyPreConfig_InitIsolatedConfig(PyPreConfig *config); /* --- PyConfig ---------------------------------------------- */ typedef struct { int _config_init; /* _PyConfigInitEnum value */ int isolated; /* Isolated mode? see PyPreConfig.isolated */ int use_environment; /* Use environment variables? see PyPreConfig.use_environment */ int dev_mode; /* Development mode? See PyPreConfig.dev_mode */ /* Install signal handlers? Yes by default. */ int install_signal_handlers; int use_hash_seed; /* PYTHONHASHSEED=x */ unsigned long hash_seed; /* Enable faulthandler? Set to 1 by -X faulthandler and PYTHONFAULTHANDLER. -1 means unset. */ int faulthandler; /* Enable tracemalloc? Set by -X tracemalloc=N and PYTHONTRACEMALLOC. -1 means unset */ int tracemalloc; int import_time; /* PYTHONPROFILEIMPORTTIME, -X importtime */ int show_ref_count; /* -X showrefcount */ int show_alloc_count; /* -X showalloccount */ int dump_refs; /* PYTHONDUMPREFS */ int malloc_stats; /* PYTHONMALLOCSTATS */ /* Python filesystem encoding and error handler: sys.getfilesystemencoding() and sys.getfilesystemencodeerrors(). Default encoding and error handler: * if Py_SetStandardStreamEncoding() has been called: they have the highest priority; * PYTHONIOENCODING environment variable; * The UTF-8 Mode uses UTF-8/surrogateescape; * If Python forces the usage of the ASCII encoding (ex: C locale or POSIX locale on FreeBSD or HP-UX), use ASCII/surrogateescape; * locale encoding: ANSI code page on Windows, UTF-8 on Android and VxWorks, LC_CTYPE locale encoding on other platforms; * On Windows, "surrogateescape" error handler; * "surrogateescape" error handler if the LC_CTYPE locale is "C" or "POSIX"; * "surrogateescape" error handler if the LC_CTYPE locale has been coerced (PEP 538); * "strict" error handler. Supported error handlers: "strict", "surrogateescape" and "surrogatepass". The surrogatepass error handler is only supported if Py_DecodeLocale() and Py_EncodeLocale() use directly the UTF-8 codec; it's only used on Windows. initfsencoding() updates the encoding to the Python codec name. For example, "ANSI_X3.4-1968" is replaced with "ascii". On Windows, sys._enablelegacywindowsfsencoding() sets the encoding/errors to mbcs/replace at runtime. See Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors. */ wchar_t *filesystem_encoding; wchar_t *filesystem_errors; wchar_t *pycache_prefix; /* PYTHONPYCACHEPREFIX, -X pycache_prefix=PATH */ int parse_argv; /* Parse argv command line arguments? */ /* Command line arguments (sys.argv). Set parse_argv to 1 to parse argv as Python command line arguments and then strip Python arguments from argv. If argv is empty, an empty string is added to ensure that sys.argv always exists and is never empty. */ PyWideStringList argv; /* Program name: - If Py_SetProgramName() was called, use its value. - On macOS, use PYTHONEXECUTABLE environment variable if set. - If WITH_NEXT_FRAMEWORK macro is defined, use __PYVENV_LAUNCHER__ environment variable is set. - Use argv[0] if available and non-empty. - Use "python" on Windows, or "python3 on other platforms. */ wchar_t *program_name; PyWideStringList xoptions; /* Command line -X options */ /* Warnings options: lowest to highest priority. warnings.filters is built in the reverse order (highest to lowest priority). */ PyWideStringList warnoptions; /* If equal to zero, disable the import of the module site and the site-dependent manipulations of sys.path that it entails. Also disable these manipulations if site is explicitly imported later (call site.main() if you want them to be triggered). Set to 0 by the -S command line option. If set to -1 (default), it is set to !Py_NoSiteFlag. */ int site_import; /* Bytes warnings: * If equal to 1, issue a warning when comparing bytes or bytearray with str or bytes with int. * If equal or greater to 2, issue an error. Incremented by the -b command line option. If set to -1 (default), inherit Py_BytesWarningFlag value. */ int bytes_warning; /* If greater than 0, enable inspect: when a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. Incremented by the -i command line option. Set to 1 if the PYTHONINSPECT environment variable is non-empty. If set to -1 (default), inherit Py_InspectFlag value. */ int inspect; /* If greater than 0: enable the interactive mode (REPL). Incremented by the -i command line option. If set to -1 (default), inherit Py_InteractiveFlag value. */ int interactive; /* Optimization level. Incremented by the -O command line option. Set by the PYTHONOPTIMIZE environment variable. If set to -1 (default), inherit Py_OptimizeFlag value. */ int optimization_level; /* If greater than 0, enable the debug mode: turn on parser debugging output (for expert only, depending on compilation options). Incremented by the -d command line option. Set by the PYTHONDEBUG environment variable. If set to -1 (default), inherit Py_DebugFlag value. */ int parser_debug; /* If equal to 0, Python won't try to write ``.pyc`` files on the import of source modules. Set to 0 by the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable. If set to -1 (default), it is set to !Py_DontWriteBytecodeFlag. */ int write_bytecode; /* If greater than 0, enable the verbose mode: print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. If greater or equal to 2, print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit. Incremented by the -v option. Set by the PYTHONVERBOSE environment variable. If set to -1 (default), inherit Py_VerboseFlag value. */ int verbose; /* If greater than 0, enable the quiet mode: Don't display the copyright and version messages even in interactive mode. Incremented by the -q option. If set to -1 (default), inherit Py_QuietFlag value. */ int quiet; /* If greater than 0, don't add the user site-packages directory to sys.path. Set to 0 by the -s and -I command line options , and the PYTHONNOUSERSITE environment variable. If set to -1 (default), it is set to !Py_NoUserSiteDirectory. */ int user_site_directory; /* If non-zero, configure C standard steams (stdio, stdout, stderr): - Set O_BINARY mode on Windows. - If buffered_stdio is equal to zero, make streams unbuffered. Otherwise, enable streams buffering if interactive is non-zero. */ int configure_c_stdio; /* If equal to 0, enable unbuffered mode: force the stdout and stderr streams to be unbuffered. Set to 0 by the -u option. Set by the PYTHONUNBUFFERED environment variable. If set to -1 (default), it is set to !Py_UnbufferedStdioFlag. */ int buffered_stdio; /* Encoding of sys.stdin, sys.stdout and sys.stderr. Value set from PYTHONIOENCODING environment variable and Py_SetStandardStreamEncoding() function. See also 'stdio_errors' attribute. */ wchar_t *stdio_encoding; /* Error handler of sys.stdin and sys.stdout. Value set from PYTHONIOENCODING environment variable and Py_SetStandardStreamEncoding() function. See also 'stdio_encoding' attribute. */ wchar_t *stdio_errors; #ifdef MS_WINDOWS /* If greater than zero, use io.FileIO instead of WindowsConsoleIO for sys standard streams. Set to 1 if the PYTHONLEGACYWINDOWSSTDIO environment variable is set to a non-empty string. If set to -1 (default), inherit Py_LegacyWindowsStdioFlag value. See PEP 528 for more details. */ int legacy_windows_stdio; #endif /* Value of the --check-hash-based-pycs command line option: - "default" means the 'check_source' flag in hash-based pycs determines invalidation - "always" causes the interpreter to hash the source file for invalidation regardless of value of 'check_source' bit - "never" causes the interpreter to always assume hash-based pycs are valid The default value is "default". See PEP 552 "Deterministic pycs" for more details. */ wchar_t *check_hash_pycs_mode; /* --- Path configuration inputs ------------ */ /* If greater than 0, suppress _PyPathConfig_Calculate() warnings on Unix. The parameter has no effect on Windows. If set to -1 (default), inherit !Py_FrozenFlag value. */ int pathconfig_warnings; wchar_t *pythonpath_env; /* PYTHONPATH environment variable */ wchar_t *home; /* PYTHONHOME environment variable, see also Py_SetPythonHome(). */ /* --- Path configuration outputs ----------- */ int module_search_paths_set; /* If non-zero, use module_search_paths */ PyWideStringList module_search_paths; /* sys.path paths. Computed if module_search_paths_set is equal to zero. */ wchar_t *executable; /* sys.executable */ wchar_t *base_executable; /* sys._base_executable */ wchar_t *prefix; /* sys.prefix */ wchar_t *base_prefix; /* sys.base_prefix */ wchar_t *exec_prefix; /* sys.exec_prefix */ wchar_t *base_exec_prefix; /* sys.base_exec_prefix */ /* --- Parameter only used by Py_Main() ---------- */ /* Skip the first line of the source ('run_filename' parameter), allowing use of non-Unix forms of "#!cmd". This is intended for a DOS specific hack only. Set by the -x command line option. */ int skip_source_first_line; wchar_t *run_command; /* -c command line argument */ wchar_t *run_module; /* -m command line argument */ wchar_t *run_filename; /* Trailing command line argument without -c or -m */ /* --- Private fields ---------------------------- */ /* Install importlib? If set to 0, importlib is not initialized at all. Needed by freeze_importlib. */ int _install_importlib; /* If equal to 0, stop Python initialization before the "main" phase */ int _init_main; } PyConfig; PyAPI_FUNC(void) PyConfig_InitPythonConfig(PyConfig *config); PyAPI_FUNC(void) PyConfig_InitIsolatedConfig(PyConfig *config); PyAPI_FUNC(void) PyConfig_Clear(PyConfig *); PyAPI_FUNC(PyStatus) PyConfig_SetString( PyConfig *config, wchar_t **config_str, const wchar_t *str); PyAPI_FUNC(PyStatus) PyConfig_SetBytesString( PyConfig *config, wchar_t **config_str, const char *str); PyAPI_FUNC(PyStatus) PyConfig_Read(PyConfig *config); PyAPI_FUNC(PyStatus) PyConfig_SetBytesArgv( PyConfig *config, Py_ssize_t argc, char * const *argv); PyAPI_FUNC(PyStatus) PyConfig_SetArgv(PyConfig *config, Py_ssize_t argc, wchar_t * const *argv); PyAPI_FUNC(PyStatus) PyConfig_SetWideStringList(PyConfig *config, PyWideStringList *list, Py_ssize_t length, wchar_t **items); #ifdef __cplusplus } #endif #endif /* !Py_LIMITED_API */ #endif /* !Py_PYCORECONFIG_H */ ================================================ FILE: thirdLibs/python3_8/include/cpython/interpreteridobject.h ================================================ #ifndef Py_CPYTHON_INTERPRETERIDOBJECT_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif /* Interpreter ID Object */ PyAPI_DATA(PyTypeObject) _PyInterpreterID_Type; PyAPI_FUNC(PyObject *) _PyInterpreterID_New(int64_t); PyAPI_FUNC(PyObject *) _PyInterpreterState_GetIDObject(PyInterpreterState *); PyAPI_FUNC(PyInterpreterState *) _PyInterpreterID_LookUp(PyObject *); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/object.h ================================================ #ifndef Py_CPYTHON_OBJECT_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif /********************* String Literals ****************************************/ /* This structure helps managing static strings. The basic usage goes like this: Instead of doing r = PyObject_CallMethod(o, "foo", "args", ...); do _Py_IDENTIFIER(foo); ... r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...); PyId_foo is a static variable, either on block level or file level. On first usage, the string "foo" is interned, and the structures are linked. On interpreter shutdown, all strings are released (through _PyUnicode_ClearStaticStrings). Alternatively, _Py_static_string allows choosing the variable name. _PyUnicode_FromId returns a borrowed reference to the interned string. _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*. */ typedef struct _Py_Identifier { struct _Py_Identifier *next; const char* string; PyObject *object; } _Py_Identifier; #define _Py_static_string_init(value) { .next = NULL, .string = value, .object = NULL } #define _Py_static_string(varname, value) static _Py_Identifier varname = _Py_static_string_init(value) #define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname) /* buffer interface */ typedef struct bufferinfo { void *buf; PyObject *obj; /* owned reference */ Py_ssize_t len; Py_ssize_t itemsize; /* This is Py_ssize_t so it can be pointed to by strides in simple case.*/ int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames); /* Maximum number of dimensions */ #define PyBUF_MAX_NDIM 64 /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 /* we used to include an E, backwards compatible alias */ #define PyBUF_WRITEABLE PyBUF_WRITABLE #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE) #define PyBUF_CONTIG_RO (PyBUF_ND) #define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE) #define PyBUF_STRIDED_RO (PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT) #define PyBUF_READ 0x100 #define PyBUF_WRITE 0x200 /* End buffer interface */ typedef struct { /* Number implementations must check *both* arguments for proper type and implement the necessary conversions in the slot functions themselves. */ binaryfunc nb_add; binaryfunc nb_subtract; binaryfunc nb_multiply; binaryfunc nb_remainder; binaryfunc nb_divmod; ternaryfunc nb_power; unaryfunc nb_negative; unaryfunc nb_positive; unaryfunc nb_absolute; inquiry nb_bool; unaryfunc nb_invert; binaryfunc nb_lshift; binaryfunc nb_rshift; binaryfunc nb_and; binaryfunc nb_xor; binaryfunc nb_or; unaryfunc nb_int; void *nb_reserved; /* the slot formerly known as nb_long */ unaryfunc nb_float; binaryfunc nb_inplace_add; binaryfunc nb_inplace_subtract; binaryfunc nb_inplace_multiply; binaryfunc nb_inplace_remainder; ternaryfunc nb_inplace_power; binaryfunc nb_inplace_lshift; binaryfunc nb_inplace_rshift; binaryfunc nb_inplace_and; binaryfunc nb_inplace_xor; binaryfunc nb_inplace_or; binaryfunc nb_floor_divide; binaryfunc nb_true_divide; binaryfunc nb_inplace_floor_divide; binaryfunc nb_inplace_true_divide; unaryfunc nb_index; binaryfunc nb_matrix_multiply; binaryfunc nb_inplace_matrix_multiply; } PyNumberMethods; typedef struct { lenfunc sq_length; binaryfunc sq_concat; ssizeargfunc sq_repeat; ssizeargfunc sq_item; void *was_sq_slice; ssizeobjargproc sq_ass_item; void *was_sq_ass_slice; objobjproc sq_contains; binaryfunc sq_inplace_concat; ssizeargfunc sq_inplace_repeat; } PySequenceMethods; typedef struct { lenfunc mp_length; binaryfunc mp_subscript; objobjargproc mp_ass_subscript; } PyMappingMethods; typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } PyAsyncMethods; typedef struct { getbufferproc bf_getbuffer; releasebufferproc bf_releasebuffer; } PyBufferProcs; /* Allow printfunc in the tp_vectorcall_offset slot for * backwards-compatibility */ typedef Py_ssize_t printfunc; typedef struct _typeobject { PyObject_VAR_HEAD const char *tp_name; /* For printing, in format "." */ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ destructor tp_dealloc; Py_ssize_t tp_vectorcall_offset; getattrfunc tp_getattr; setattrfunc tp_setattr; PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2) or tp_reserved (Python 3) */ reprfunc tp_repr; /* Method suites for standard classes */ PyNumberMethods *tp_as_number; PySequenceMethods *tp_as_sequence; PyMappingMethods *tp_as_mapping; /* More standard operations (here for binary compatibility) */ hashfunc tp_hash; ternaryfunc tp_call; reprfunc tp_str; getattrofunc tp_getattro; setattrofunc tp_setattro; /* Functions to access object as input/output buffer */ PyBufferProcs *tp_as_buffer; /* Flags to define presence of optional/expanded features */ unsigned long tp_flags; const char *tp_doc; /* Documentation string */ /* Assigned meaning in release 2.0 */ /* call function for all accessible objects */ traverseproc tp_traverse; /* delete references to contained objects */ inquiry tp_clear; /* Assigned meaning in release 2.1 */ /* rich comparisons */ richcmpfunc tp_richcompare; /* weak reference enabler */ Py_ssize_t tp_weaklistoffset; /* Iterators */ getiterfunc tp_iter; iternextfunc tp_iternext; /* Attribute descriptor and subclassing stuff */ struct PyMethodDef *tp_methods; struct PyMemberDef *tp_members; struct PyGetSetDef *tp_getset; struct _typeobject *tp_base; PyObject *tp_dict; descrgetfunc tp_descr_get; descrsetfunc tp_descr_set; Py_ssize_t tp_dictoffset; initproc tp_init; allocfunc tp_alloc; newfunc tp_new; freefunc tp_free; /* Low-level free-memory routine */ inquiry tp_is_gc; /* For PyObject_IS_GC */ PyObject *tp_bases; PyObject *tp_mro; /* method resolution order */ PyObject *tp_cache; PyObject *tp_subclasses; PyObject *tp_weaklist; destructor tp_del; /* Type attribute cache version tag. Added in version 2.6 */ unsigned int tp_version_tag; destructor tp_finalize; vectorcallfunc tp_vectorcall; /* bpo-37250: kept for backwards compatibility in CPython 3.8 only */ Py_DEPRECATED(3.8) int (*tp_print)(PyObject *, FILE *, int); #ifdef COUNT_ALLOCS /* these must be last and never explicitly initialized */ Py_ssize_t tp_allocs; Py_ssize_t tp_frees; Py_ssize_t tp_maxalloc; struct _typeobject *tp_prev; struct _typeobject *tp_next; #endif } PyTypeObject; /* The *real* layout of a type object when allocated on the heap */ typedef struct _heaptypeobject { /* Note: there's a dependency on the order of these members in slotptr() in typeobject.c . */ PyTypeObject ht_type; PyAsyncMethods as_async; PyNumberMethods as_number; PyMappingMethods as_mapping; PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, so that the mapping wins when both the mapping and the sequence define a given operator (e.g. __getitem__). see add_operators() in typeobject.c . */ PyBufferProcs as_buffer; PyObject *ht_name, *ht_slots, *ht_qualname; struct _dictkeysobject *ht_cached_keys; /* here are optional user slots, followed by the members. */ } PyHeapTypeObject; /* access macro to the members which are floating "behind" the object */ #define PyHeapType_GET_MEMBERS(etype) \ ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize)) PyAPI_FUNC(const char *) _PyType_Name(PyTypeObject *); PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyType_LookupId(PyTypeObject *, _Py_Identifier *); PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, _Py_Identifier *); PyAPI_FUNC(PyTypeObject *) _PyType_CalculateMetaclass(PyTypeObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyType_GetDocFromInternalDoc(const char *, const char *); PyAPI_FUNC(PyObject *) _PyType_GetTextSignatureFromInternalDoc(const char *, const char *); struct _Py_Identifier; PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int); PyAPI_FUNC(void) _Py_BreakPoint(void); PyAPI_FUNC(void) _PyObject_Dump(PyObject *); PyAPI_FUNC(int) _PyObject_IsFreed(PyObject *); PyAPI_FUNC(int) _PyObject_IsAbstract(PyObject *); PyAPI_FUNC(PyObject *) _PyObject_GetAttrId(PyObject *, struct _Py_Identifier *); PyAPI_FUNC(int) _PyObject_SetAttrId(PyObject *, struct _Py_Identifier *, PyObject *); PyAPI_FUNC(int) _PyObject_HasAttrId(PyObject *, struct _Py_Identifier *); /* Replacements of PyObject_GetAttr() and _PyObject_GetAttrId() which don't raise AttributeError. Return 1 and set *result != NULL if an attribute is found. Return 0 and set *result == NULL if an attribute is not found; an AttributeError is silenced. Return -1 and set *result == NULL if an error other than AttributeError is raised. */ PyAPI_FUNC(int) _PyObject_LookupAttr(PyObject *, PyObject *, PyObject **); PyAPI_FUNC(int) _PyObject_LookupAttrId(PyObject *, struct _Py_Identifier *, PyObject **); PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *); PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *); PyAPI_FUNC(void) PyObject_CallFinalizer(PyObject *); PyAPI_FUNC(int) PyObject_CallFinalizerFromDealloc(PyObject *); /* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes dict as the last parameter. */ PyAPI_FUNC(PyObject *) _PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *, int); PyAPI_FUNC(int) _PyObject_GenericSetAttrWithDict(PyObject *, PyObject *, PyObject *, PyObject *); #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) static inline void _Py_Dealloc_inline(PyObject *op) { destructor dealloc = Py_TYPE(op)->tp_dealloc; #ifdef Py_TRACE_REFS _Py_ForgetReference(op); #else _Py_INC_TPFREES(op); #endif (*dealloc)(op); } #define _Py_Dealloc(op) _Py_Dealloc_inline(op) /* Safely decref `op` and set `op` to `op2`. * * As in case of Py_CLEAR "the obvious" code can be deadly: * * Py_DECREF(op); * op = op2; * * The safe way is: * * Py_SETREF(op, op2); * * That arranges to set `op` to `op2` _before_ decref'ing, so that any code * triggered as a side-effect of `op` getting torn down no longer believes * `op` points to a valid object. * * Py_XSETREF is a variant of Py_SETREF that uses Py_XDECREF instead of * Py_DECREF. */ #define Py_SETREF(op, op2) \ do { \ PyObject *_py_tmp = _PyObject_CAST(op); \ (op) = (op2); \ Py_DECREF(_py_tmp); \ } while (0) #define Py_XSETREF(op, op2) \ do { \ PyObject *_py_tmp = _PyObject_CAST(op); \ (op) = (op2); \ Py_XDECREF(_py_tmp); \ } while (0) PyAPI_DATA(PyTypeObject) _PyNone_Type; PyAPI_DATA(PyTypeObject) _PyNotImplemented_Type; /* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE. * Defined in object.c. */ PyAPI_DATA(int) _Py_SwappedOp[]; /* This is the old private API, invoked by the macros before 3.2.4. Kept for binary compatibility of extensions using the stable ABI. */ PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*); PyAPI_FUNC(void) _PyTrash_destroy_chain(void); PyAPI_FUNC(void) _PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks, size_t sizeof_block); PyAPI_FUNC(void) _PyObject_DebugTypeStats(FILE *out); /* Define a pair of assertion macros: _PyObject_ASSERT_FROM(), _PyObject_ASSERT_WITH_MSG() and _PyObject_ASSERT(). These work like the regular C assert(), in that they will abort the process with a message on stderr if the given condition fails to hold, but compile away to nothing if NDEBUG is defined. However, before aborting, Python will also try to call _PyObject_Dump() on the given object. This may be of use when investigating bugs in which a particular object is corrupt (e.g. buggy a tp_visit method in an extension module breaking the garbage collector), to help locate the broken objects. The WITH_MSG variant allows you to supply an additional message that Python will attempt to print to stderr, after the object dump. */ #ifdef NDEBUG /* No debugging: compile away the assertions: */ # define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \ ((void)0) #else /* With debugging: generate checks: */ # define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \ ((expr) \ ? (void)(0) \ : _PyObject_AssertFailed((obj), Py_STRINGIFY(expr), \ (msg), (filename), (lineno), (func))) #endif #define _PyObject_ASSERT_WITH_MSG(obj, expr, msg) \ _PyObject_ASSERT_FROM(obj, expr, msg, __FILE__, __LINE__, __func__) #define _PyObject_ASSERT(obj, expr) \ _PyObject_ASSERT_WITH_MSG(obj, expr, NULL) #define _PyObject_ASSERT_FAILED_MSG(obj, msg) \ _PyObject_AssertFailed((obj), NULL, (msg), __FILE__, __LINE__, __func__) /* Declare and define _PyObject_AssertFailed() even when NDEBUG is defined, to avoid causing compiler/linker errors when building extensions without NDEBUG against a Python built with NDEBUG defined. msg, expr and function can be NULL. */ PyAPI_FUNC(void) _PyObject_AssertFailed( PyObject *obj, const char *expr, const char *msg, const char *file, int line, const char *function); /* Check if an object is consistent. For example, ensure that the reference counter is greater than or equal to 1, and ensure that ob_type is not NULL. Call _PyObject_AssertFailed() if the object is inconsistent. If check_content is zero, only check header fields: reduce the overhead. The function always return 1. The return value is just here to be able to write: assert(_PyObject_CheckConsistency(obj, 1)); */ PyAPI_FUNC(int) _PyObject_CheckConsistency( PyObject *op, int check_content); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/objimpl.h ================================================ #ifndef Py_CPYTHON_OBJIMPL_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif /* This function returns the number of allocated memory blocks, regardless of size */ PyAPI_FUNC(Py_ssize_t) _Py_GetAllocatedBlocks(void); /* Macros */ #ifdef WITH_PYMALLOC PyAPI_FUNC(int) _PyObject_DebugMallocStats(FILE *out); #endif typedef struct { /* user context passed as the first argument to the 2 functions */ void *ctx; /* allocate an arena of size bytes */ void* (*alloc) (void *ctx, size_t size); /* free an arena */ void (*free) (void *ctx, void *ptr, size_t size); } PyObjectArenaAllocator; /* Get the arena allocator. */ PyAPI_FUNC(void) PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator); /* Set the arena allocator. */ PyAPI_FUNC(void) PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator); PyAPI_FUNC(Py_ssize_t) _PyGC_CollectNoFail(void); PyAPI_FUNC(Py_ssize_t) _PyGC_CollectIfEnabled(void); /* Test if an object has a GC head */ #define PyObject_IS_GC(o) \ (PyType_IS_GC(Py_TYPE(o)) \ && (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) /* GC information is stored BEFORE the object structure. */ typedef struct { // Pointer to next object in the list. // 0 means the object is not tracked uintptr_t _gc_next; // Pointer to previous object in the list. // Lowest two bits are used for flags documented later. uintptr_t _gc_prev; } PyGC_Head; #define _Py_AS_GC(o) ((PyGC_Head *)(o)-1) /* True if the object is currently tracked by the GC. */ #define _PyObject_GC_IS_TRACKED(o) (_Py_AS_GC(o)->_gc_next != 0) /* True if the object may be tracked by the GC in the future, or already is. This can be useful to implement some optimizations. */ #define _PyObject_GC_MAY_BE_TRACKED(obj) \ (PyObject_IS_GC(obj) && \ (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) /* Bit flags for _gc_prev */ /* Bit 0 is set when tp_finalize is called */ #define _PyGC_PREV_MASK_FINALIZED (1) /* Bit 1 is set when the object is in generation which is GCed currently. */ #define _PyGC_PREV_MASK_COLLECTING (2) /* The (N-2) most significant bits contain the real address. */ #define _PyGC_PREV_SHIFT (2) #define _PyGC_PREV_MASK (((uintptr_t) -1) << _PyGC_PREV_SHIFT) // Lowest bit of _gc_next is used for flags only in GC. // But it is always 0 for normal code. #define _PyGCHead_NEXT(g) ((PyGC_Head*)(g)->_gc_next) #define _PyGCHead_SET_NEXT(g, p) ((g)->_gc_next = (uintptr_t)(p)) // Lowest two bits of _gc_prev is used for _PyGC_PREV_MASK_* flags. #define _PyGCHead_PREV(g) ((PyGC_Head*)((g)->_gc_prev & _PyGC_PREV_MASK)) #define _PyGCHead_SET_PREV(g, p) do { \ assert(((uintptr_t)p & ~_PyGC_PREV_MASK) == 0); \ (g)->_gc_prev = ((g)->_gc_prev & ~_PyGC_PREV_MASK) \ | ((uintptr_t)(p)); \ } while (0) #define _PyGCHead_FINALIZED(g) \ (((g)->_gc_prev & _PyGC_PREV_MASK_FINALIZED) != 0) #define _PyGCHead_SET_FINALIZED(g) \ ((g)->_gc_prev |= _PyGC_PREV_MASK_FINALIZED) #define _PyGC_FINALIZED(o) \ _PyGCHead_FINALIZED(_Py_AS_GC(o)) #define _PyGC_SET_FINALIZED(o) \ _PyGCHead_SET_FINALIZED(_Py_AS_GC(o)) PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t size); PyAPI_FUNC(PyObject *) _PyObject_GC_Calloc(size_t size); /* Test if a type supports weak references */ #define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0) #define PyObject_GET_WEAKREFS_LISTPTR(o) \ ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/pyerrors.h ================================================ #ifndef Py_CPYTHON_ERRORS_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif /* Error objects */ /* PyException_HEAD defines the initial segment of every exception class. */ #define PyException_HEAD PyObject_HEAD PyObject *dict;\ PyObject *args; PyObject *traceback;\ PyObject *context; PyObject *cause;\ char suppress_context; typedef struct { PyException_HEAD } PyBaseExceptionObject; typedef struct { PyException_HEAD PyObject *msg; PyObject *filename; PyObject *lineno; PyObject *offset; PyObject *text; PyObject *print_file_and_line; } PySyntaxErrorObject; typedef struct { PyException_HEAD PyObject *msg; PyObject *name; PyObject *path; } PyImportErrorObject; typedef struct { PyException_HEAD PyObject *encoding; PyObject *object; Py_ssize_t start; Py_ssize_t end; PyObject *reason; } PyUnicodeErrorObject; typedef struct { PyException_HEAD PyObject *code; } PySystemExitObject; typedef struct { PyException_HEAD PyObject *myerrno; PyObject *strerror; PyObject *filename; PyObject *filename2; #ifdef MS_WINDOWS PyObject *winerror; #endif Py_ssize_t written; /* only for BlockingIOError, -1 otherwise */ } PyOSErrorObject; typedef struct { PyException_HEAD PyObject *value; } PyStopIterationObject; /* Compatibility typedefs */ typedef PyOSErrorObject PyEnvironmentErrorObject; #ifdef MS_WINDOWS typedef PyOSErrorObject PyWindowsErrorObject; #endif /* Error handling definitions */ PyAPI_FUNC(void) _PyErr_SetKeyError(PyObject *); _PyErr_StackItem *_PyErr_GetTopmostException(PyThreadState *tstate); /* Context manipulation (PEP 3134) */ PyAPI_FUNC(void) _PyErr_ChainExceptions(PyObject *, PyObject *, PyObject *); /* */ #define PyExceptionClass_Name(x) (((PyTypeObject*)(x))->tp_name) /* Convenience functions */ #ifdef MS_WINDOWS Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename( PyObject *, const Py_UNICODE *); #endif /* MS_WINDOWS */ /* Like PyErr_Format(), but saves current exception as __context__ and __cause__. */ PyAPI_FUNC(PyObject *) _PyErr_FormatFromCause( PyObject *exception, const char *format, /* ASCII-encoded string */ ... ); #ifdef MS_WINDOWS /* XXX redeclare to use WSTRING */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename( int, const Py_UNICODE *); Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename( PyObject *,int, const Py_UNICODE *); #endif /* In exceptions.c */ /* Helper that attempts to replace the current exception with one of the * same type but with a prefix added to the exception text. The resulting * exception description looks like: * * prefix (exc_type: original_exc_str) * * Only some exceptions can be safely replaced. If the function determines * it isn't safe to perform the replacement, it will leave the original * unmodified exception in place. * * Returns a borrowed reference to the new exception (if any), NULL if the * existing exception was left in place. */ PyAPI_FUNC(PyObject *) _PyErr_TrySetFromCause( const char *prefix_format, /* ASCII-encoded string */ ... ); /* In signalmodule.c */ int PySignal_SetWakeupFd(int fd); PyAPI_FUNC(int) _PyErr_CheckSignals(void); /* Support for adding program text to SyntaxErrors */ PyAPI_FUNC(void) PyErr_SyntaxLocationObject( PyObject *filename, int lineno, int col_offset); PyAPI_FUNC(PyObject *) PyErr_ProgramTextObject( PyObject *filename, int lineno); /* Create a UnicodeEncodeError object */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create( const char *encoding, /* UTF-8 encoded string */ const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); /* Create a UnicodeTranslateError object */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create( const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); PyAPI_FUNC(PyObject *) _PyUnicodeTranslateError_Create( PyObject *object, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); PyAPI_FUNC(void) _PyErr_WriteUnraisableMsg( const char *err_msg, PyObject *obj); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/pylifecycle.h ================================================ #ifndef Py_CPYTHON_PYLIFECYCLE_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif /* Only used by applications that embed the interpreter and need to * override the standard encoding determination mechanism */ PyAPI_FUNC(int) Py_SetStandardStreamEncoding(const char *encoding, const char *errors); /* PEP 432 Multi-phase initialization API (Private while provisional!) */ PyAPI_FUNC(PyStatus) Py_PreInitialize( const PyPreConfig *src_config); PyAPI_FUNC(PyStatus) Py_PreInitializeFromBytesArgs( const PyPreConfig *src_config, Py_ssize_t argc, char **argv); PyAPI_FUNC(PyStatus) Py_PreInitializeFromArgs( const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv); PyAPI_FUNC(int) _Py_IsCoreInitialized(void); /* Initialization and finalization */ PyAPI_FUNC(PyStatus) Py_InitializeFromConfig( const PyConfig *config); PyAPI_FUNC(PyStatus) _Py_InitializeFromArgs( const PyConfig *config, Py_ssize_t argc, char * const *argv); PyAPI_FUNC(PyStatus) _Py_InitializeFromWideArgs( const PyConfig *config, Py_ssize_t argc, wchar_t * const *argv); PyAPI_FUNC(PyStatus) _Py_InitializeMain(void); PyAPI_FUNC(int) Py_RunMain(void); PyAPI_FUNC(void) _Py_NO_RETURN Py_ExitStatusException(PyStatus err); /* Py_PyAtExit is for the atexit module, Py_AtExit is for low-level * exit functions. */ PyAPI_FUNC(void) _Py_PyAtExit(void (*func)(PyObject *), PyObject *); /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL. */ PyAPI_FUNC(void) _Py_RestoreSignals(void); PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *); PyAPI_FUNC(void) _Py_SetProgramFullPath(const wchar_t *); PyAPI_FUNC(const char *) _Py_gitidentifier(void); PyAPI_FUNC(const char *) _Py_gitversion(void); PyAPI_FUNC(int) _Py_IsFinalizing(void); /* Random */ PyAPI_FUNC(int) _PyOS_URandom(void *buffer, Py_ssize_t size); PyAPI_FUNC(int) _PyOS_URandomNonblock(void *buffer, Py_ssize_t size); /* Legacy locale support */ PyAPI_FUNC(int) _Py_CoerceLegacyLocale(int warn); PyAPI_FUNC(int) _Py_LegacyLocaleDetected(int warn); PyAPI_FUNC(char *) _Py_SetLocaleFromEnv(int category); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/pymem.h ================================================ #ifndef Py_CPYTHON_PYMEM_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(void *) PyMem_RawMalloc(size_t size); PyAPI_FUNC(void *) PyMem_RawCalloc(size_t nelem, size_t elsize); PyAPI_FUNC(void *) PyMem_RawRealloc(void *ptr, size_t new_size); PyAPI_FUNC(void) PyMem_RawFree(void *ptr); /* Try to get the allocators name set by _PyMem_SetupAllocators(). */ PyAPI_FUNC(const char*) _PyMem_GetCurrentAllocatorName(void); PyAPI_FUNC(void *) PyMem_Calloc(size_t nelem, size_t elsize); /* strdup() using PyMem_RawMalloc() */ PyAPI_FUNC(char *) _PyMem_RawStrdup(const char *str); /* strdup() using PyMem_Malloc() */ PyAPI_FUNC(char *) _PyMem_Strdup(const char *str); /* wcsdup() using PyMem_RawMalloc() */ PyAPI_FUNC(wchar_t*) _PyMem_RawWcsdup(const wchar_t *str); typedef enum { /* PyMem_RawMalloc(), PyMem_RawRealloc() and PyMem_RawFree() */ PYMEM_DOMAIN_RAW, /* PyMem_Malloc(), PyMem_Realloc() and PyMem_Free() */ PYMEM_DOMAIN_MEM, /* PyObject_Malloc(), PyObject_Realloc() and PyObject_Free() */ PYMEM_DOMAIN_OBJ } PyMemAllocatorDomain; typedef enum { PYMEM_ALLOCATOR_NOT_SET = 0, PYMEM_ALLOCATOR_DEFAULT = 1, PYMEM_ALLOCATOR_DEBUG = 2, PYMEM_ALLOCATOR_MALLOC = 3, PYMEM_ALLOCATOR_MALLOC_DEBUG = 4, #ifdef WITH_PYMALLOC PYMEM_ALLOCATOR_PYMALLOC = 5, PYMEM_ALLOCATOR_PYMALLOC_DEBUG = 6, #endif } PyMemAllocatorName; typedef struct { /* user context passed as the first argument to the 4 functions */ void *ctx; /* allocate a memory block */ void* (*malloc) (void *ctx, size_t size); /* allocate a memory block initialized by zeros */ void* (*calloc) (void *ctx, size_t nelem, size_t elsize); /* allocate or resize a memory block */ void* (*realloc) (void *ctx, void *ptr, size_t new_size); /* release a memory block */ void (*free) (void *ctx, void *ptr); } PyMemAllocatorEx; /* Get the memory block allocator of the specified domain. */ PyAPI_FUNC(void) PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator); /* Set the memory block allocator of the specified domain. The new allocator must return a distinct non-NULL pointer when requesting zero bytes. For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: the GIL is not held when the allocator is called. If the new allocator is not a hook (don't call the previous allocator), the PyMem_SetupDebugHooks() function must be called to reinstall the debug hooks on top on the new allocator. */ PyAPI_FUNC(void) PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator); /* Setup hooks to detect bugs in the following Python memory allocator functions: - PyMem_RawMalloc(), PyMem_RawRealloc(), PyMem_RawFree() - PyMem_Malloc(), PyMem_Realloc(), PyMem_Free() - PyObject_Malloc(), PyObject_Realloc() and PyObject_Free() Newly allocated memory is filled with the byte 0xCB, freed memory is filled with the byte 0xDB. Additional checks: - detect API violations, ex: PyObject_Free() called on a buffer allocated by PyMem_Malloc() - detect write before the start of the buffer (buffer underflow) - detect write after the end of the buffer (buffer overflow) The function does nothing if Python is not compiled is debug mode. */ PyAPI_FUNC(void) PyMem_SetupDebugHooks(void); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/pystate.h ================================================ #ifndef Py_CPYTHON_PYSTATE_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif #include "cpython/initconfig.h" PyAPI_FUNC(int) _PyInterpreterState_RequiresIDRef(PyInterpreterState *); PyAPI_FUNC(void) _PyInterpreterState_RequireIDRef(PyInterpreterState *, int); PyAPI_FUNC(PyObject *) _PyInterpreterState_GetMainModule(PyInterpreterState *); /* State unique per thread */ /* Py_tracefunc return -1 when raising an exception, or 0 for success. */ typedef int (*Py_tracefunc)(PyObject *, struct _frame *, int, PyObject *); /* The following values are used for 'what' for tracefunc functions * * To add a new kind of trace event, also update "trace_init" in * Python/sysmodule.c to define the Python level event name */ #define PyTrace_CALL 0 #define PyTrace_EXCEPTION 1 #define PyTrace_LINE 2 #define PyTrace_RETURN 3 #define PyTrace_C_CALL 4 #define PyTrace_C_EXCEPTION 5 #define PyTrace_C_RETURN 6 #define PyTrace_OPCODE 7 typedef struct _err_stackitem { /* This struct represents an entry on the exception stack, which is a * per-coroutine state. (Coroutine in the computer science sense, * including the thread and generators). * This ensures that the exception state is not impacted by "yields" * from an except handler. */ PyObject *exc_type, *exc_value, *exc_traceback; struct _err_stackitem *previous_item; } _PyErr_StackItem; // The PyThreadState typedef is in Include/pystate.h. struct _ts { /* See Python/ceval.c for comments explaining most fields */ struct _ts *prev; struct _ts *next; PyInterpreterState *interp; struct _frame *frame; int recursion_depth; char overflowed; /* The stack has overflowed. Allow 50 more calls to handle the runtime error. */ char recursion_critical; /* The current calls must not cause a stack overflow. */ int stackcheck_counter; /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int tracing; int use_tracing; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; /* The exception currently being raised */ PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; /* The exception currently being handled, if no coroutines/generators * are present. Always last element on the stack referred to be exc_info. */ _PyErr_StackItem exc_state; /* Pointer to the top of the stack of the exceptions currently * being handled */ _PyErr_StackItem *exc_info; PyObject *dict; /* Stores per-thread state */ int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ unsigned long thread_id; /* Thread id where this tstate was created */ int trash_delete_nesting; PyObject *trash_delete_later; /* Called when a thread state is deleted normally, but not when it * is destroyed after fork(). * Pain: to prevent rare but fatal shutdown errors (issue 18808), * Thread.join() must wait for the join'ed thread's tstate to be unlinked * from the tstate chain. That happens at the end of a thread's life, * in pystate.c. * The obvious way doesn't quite work: create a lock which the tstate * unlinking code releases, and have Thread.join() wait to acquire that * lock. The problem is that we _are_ at the end of the thread's life: * if the thread holds the last reference to the lock, decref'ing the * lock will delete the lock, and that may trigger arbitrary Python code * if there's a weakref, with a callback, to the lock. But by this time * _PyRuntime.gilstate.tstate_current is already NULL, so only the simplest * of C code can be allowed to run (in particular it must not be possible to * release the GIL). * So instead of holding the lock directly, the tstate holds a weakref to * the lock: that's the value of on_delete_data below. Decref'ing a * weakref is harmless. * on_delete points to _threadmodule.c's static release_sentinel() function. * After the tstate is unlinked, release_sentinel is called with the * weakref-to-lock (on_delete_data) argument, and release_sentinel releases * the indirectly held lock. */ void (*on_delete)(void *); void *on_delete_data; int coroutine_origin_tracking_depth; PyObject *async_gen_firstiter; PyObject *async_gen_finalizer; PyObject *context; uint64_t context_ver; /* Unique thread state id. */ uint64_t id; /* XXX signal handlers should also be here */ }; /* Get the current interpreter state. Issue a fatal error if there no current Python thread state or no current interpreter. It cannot return NULL. The caller must hold the GIL.*/ PyAPI_FUNC(PyInterpreterState *) _PyInterpreterState_Get(void); PyAPI_FUNC(int) _PyState_AddModule(PyObject*, struct PyModuleDef*); PyAPI_FUNC(void) _PyState_ClearModules(void); PyAPI_FUNC(PyThreadState *) _PyThreadState_Prealloc(PyInterpreterState *); /* Similar to PyThreadState_Get(), but don't issue a fatal error * if it is NULL. */ PyAPI_FUNC(PyThreadState *) _PyThreadState_UncheckedGet(void); /* PyGILState */ /* Helper/diagnostic function - return 1 if the current thread currently holds the GIL, 0 otherwise. The function returns 1 if _PyGILState_check_enabled is non-zero. */ PyAPI_FUNC(int) PyGILState_Check(void); /* Get the single PyInterpreterState used by this process' GILState implementation. This function doesn't check for error. Return NULL before _PyGILState_Init() is called and after _PyGILState_Fini() is called. See also _PyInterpreterState_Get() and _PyInterpreterState_GET_UNSAFE(). */ PyAPI_FUNC(PyInterpreterState *) _PyGILState_GetInterpreterStateUnsafe(void); /* The implementation of sys._current_frames() Returns a dict mapping thread id to that thread's current frame. */ PyAPI_FUNC(PyObject *) _PyThread_CurrentFrames(void); /* Routines for advanced debuggers, requested by David Beazley. Don't use unless you know what you are doing! */ PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Main(void); PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Head(void); PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Next(PyInterpreterState *); PyAPI_FUNC(PyThreadState *) PyInterpreterState_ThreadHead(PyInterpreterState *); PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *); typedef struct _frame *(*PyThreadFrameGetter)(PyThreadState *self_); /* cross-interpreter data */ struct _xid; // _PyCrossInterpreterData is similar to Py_buffer as an effectively // opaque struct that holds data outside the object machinery. This // is necessary to pass safely between interpreters in the same process. typedef struct _xid { // data is the cross-interpreter-safe derivation of a Python object // (see _PyObject_GetCrossInterpreterData). It will be NULL if the // new_object func (below) encodes the data. void *data; // obj is the Python object from which the data was derived. This // is non-NULL only if the data remains bound to the object in some // way, such that the object must be "released" (via a decref) when // the data is released. In that case the code that sets the field, // likely a registered "crossinterpdatafunc", is responsible for // ensuring it owns the reference (i.e. incref). PyObject *obj; // interp is the ID of the owning interpreter of the original // object. It corresponds to the active interpreter when // _PyObject_GetCrossInterpreterData() was called. This should only // be set by the cross-interpreter machinery. // // We use the ID rather than the PyInterpreterState to avoid issues // with deleted interpreters. Note that IDs are never re-used, so // each one will always correspond to a specific interpreter // (whether still alive or not). int64_t interp; // new_object is a function that returns a new object in the current // interpreter given the data. The resulting object (a new // reference) will be equivalent to the original object. This field // is required. PyObject *(*new_object)(struct _xid *); // free is called when the data is released. If it is NULL then // nothing will be done to free the data. For some types this is // okay (e.g. bytes) and for those types this field should be set // to NULL. However, for most the data was allocated just for // cross-interpreter use, so it must be freed when // _PyCrossInterpreterData_Release is called or the memory will // leak. In that case, at the very least this field should be set // to PyMem_RawFree (the default if not explicitly set to NULL). // The call will happen with the original interpreter activated. void (*free)(void *); } _PyCrossInterpreterData; PyAPI_FUNC(int) _PyObject_GetCrossInterpreterData(PyObject *, _PyCrossInterpreterData *); PyAPI_FUNC(PyObject *) _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *); PyAPI_FUNC(void) _PyCrossInterpreterData_Release(_PyCrossInterpreterData *); PyAPI_FUNC(int) _PyObject_CheckCrossInterpreterData(PyObject *); /* cross-interpreter data registry */ typedef int (*crossinterpdatafunc)(PyObject *, struct _xid *); PyAPI_FUNC(int) _PyCrossInterpreterData_RegisterClass(PyTypeObject *, crossinterpdatafunc); PyAPI_FUNC(crossinterpdatafunc) _PyCrossInterpreterData_Lookup(PyObject *); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/sysmodule.h ================================================ #ifndef Py_CPYTHON_SYSMODULE_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(PyObject *) _PySys_GetObjectId(_Py_Identifier *key); PyAPI_FUNC(int) _PySys_SetObjectId(_Py_Identifier *key, PyObject *); PyAPI_FUNC(size_t) _PySys_GetSizeOf(PyObject *); typedef int(*Py_AuditHookFunction)(const char *, PyObject *, void *); PyAPI_FUNC(int) PySys_Audit(const char*, const char *, ...); PyAPI_FUNC(int) PySys_AddAuditHook(Py_AuditHookFunction, void*); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/traceback.h ================================================ #ifndef Py_CPYTHON_TRACEBACK_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif typedef struct _traceback { PyObject_HEAD struct _traceback *tb_next; struct _frame *tb_frame; int tb_lasti; int tb_lineno; } PyTracebackObject; PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, PyObject *, int, int); PyAPI_FUNC(void) _PyTraceback_Add(const char *, const char *, int); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/tupleobject.h ================================================ #ifndef Py_CPYTHON_TUPLEOBJECT_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif typedef struct { PyObject_VAR_HEAD /* ob_item contains space for 'ob_size' elements. Items must normally not be NULL, except during construction when the tuple is not yet visible outside the function that builds it. */ PyObject *ob_item[1]; } PyTupleObject; PyAPI_FUNC(int) _PyTuple_Resize(PyObject **, Py_ssize_t); PyAPI_FUNC(void) _PyTuple_MaybeUntrack(PyObject *); /* Macros trading safety for speed */ /* Cast argument to PyTupleObject* type. */ #define _PyTuple_CAST(op) (assert(PyTuple_Check(op)), (PyTupleObject *)(op)) #define PyTuple_GET_SIZE(op) Py_SIZE(_PyTuple_CAST(op)) #define PyTuple_GET_ITEM(op, i) (_PyTuple_CAST(op)->ob_item[i]) /* Macro, *only* to be used to fill in brand new tuples */ #define PyTuple_SET_ITEM(op, i, v) (_PyTuple_CAST(op)->ob_item[i] = v) PyAPI_FUNC(void) _PyTuple_DebugMallocStats(FILE *out); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/cpython/unicodeobject.h ================================================ #ifndef Py_CPYTHON_UNICODEOBJECT_H # error "this header file must not be included directly" #endif #ifdef __cplusplus extern "C" { #endif /* Py_UNICODE was the native Unicode storage format (code unit) used by Python and represents a single Unicode element in the Unicode type. With PEP 393, Py_UNICODE is deprecated and replaced with a typedef to wchar_t. */ #define PY_UNICODE_TYPE wchar_t /* Py_DEPRECATED(3.3) */ typedef wchar_t Py_UNICODE; /* --- Internal Unicode Operations ---------------------------------------- */ /* Since splitting on whitespace is an important use case, and whitespace in most situations is solely ASCII whitespace, we optimize for the common case by using a quick look-up table _Py_ascii_whitespace (see below) with an inlined check. */ #define Py_UNICODE_ISSPACE(ch) \ ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) #define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch) #define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch) #define Py_UNICODE_ISTITLE(ch) _PyUnicode_IsTitlecase(ch) #define Py_UNICODE_ISLINEBREAK(ch) _PyUnicode_IsLinebreak(ch) #define Py_UNICODE_TOLOWER(ch) _PyUnicode_ToLowercase(ch) #define Py_UNICODE_TOUPPER(ch) _PyUnicode_ToUppercase(ch) #define Py_UNICODE_TOTITLE(ch) _PyUnicode_ToTitlecase(ch) #define Py_UNICODE_ISDECIMAL(ch) _PyUnicode_IsDecimalDigit(ch) #define Py_UNICODE_ISDIGIT(ch) _PyUnicode_IsDigit(ch) #define Py_UNICODE_ISNUMERIC(ch) _PyUnicode_IsNumeric(ch) #define Py_UNICODE_ISPRINTABLE(ch) _PyUnicode_IsPrintable(ch) #define Py_UNICODE_TODECIMAL(ch) _PyUnicode_ToDecimalDigit(ch) #define Py_UNICODE_TODIGIT(ch) _PyUnicode_ToDigit(ch) #define Py_UNICODE_TONUMERIC(ch) _PyUnicode_ToNumeric(ch) #define Py_UNICODE_ISALPHA(ch) _PyUnicode_IsAlpha(ch) #define Py_UNICODE_ISALNUM(ch) \ (Py_UNICODE_ISALPHA(ch) || \ Py_UNICODE_ISDECIMAL(ch) || \ Py_UNICODE_ISDIGIT(ch) || \ Py_UNICODE_ISNUMERIC(ch)) #define Py_UNICODE_COPY(target, source, length) \ memcpy((target), (source), (length)*sizeof(Py_UNICODE)) #define Py_UNICODE_FILL(target, value, length) \ do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ } while (0) /* macros to work with surrogates */ #define Py_UNICODE_IS_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDFFF) #define Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDBFF) #define Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= (ch) && (ch) <= 0xDFFF) /* Join two surrogate characters and return a single Py_UCS4 value. */ #define Py_UNICODE_JOIN_SURROGATES(high, low) \ (((((Py_UCS4)(high) & 0x03FF) << 10) | \ ((Py_UCS4)(low) & 0x03FF)) + 0x10000) /* high surrogate = top 10 bits added to D800 */ #define Py_UNICODE_HIGH_SURROGATE(ch) (0xD800 - (0x10000 >> 10) + ((ch) >> 10)) /* low surrogate = bottom 10 bits added to DC00 */ #define Py_UNICODE_LOW_SURROGATE(ch) (0xDC00 + ((ch) & 0x3FF)) /* Check if substring matches at given offset. The offset must be valid, and the substring must not be empty. */ #define Py_UNICODE_MATCH(string, offset, substring) \ ((*((string)->wstr + (offset)) == *((substring)->wstr)) && \ ((*((string)->wstr + (offset) + (substring)->wstr_length-1) == *((substring)->wstr + (substring)->wstr_length-1))) && \ !memcmp((string)->wstr + (offset), (substring)->wstr, (substring)->wstr_length*sizeof(Py_UNICODE))) /* --- Unicode Type ------------------------------------------------------- */ /* ASCII-only strings created through PyUnicode_New use the PyASCIIObject structure. state.ascii and state.compact are set, and the data immediately follow the structure. utf8_length and wstr_length can be found in the length field; the utf8 pointer is equal to the data pointer. */ typedef struct { /* There are 4 forms of Unicode strings: - compact ascii: * structure = PyASCIIObject * test: PyUnicode_IS_COMPACT_ASCII(op) * kind = PyUnicode_1BYTE_KIND * compact = 1 * ascii = 1 * ready = 1 * (length is the length of the utf8 and wstr strings) * (data starts just after the structure) * (since ASCII is decoded from UTF-8, the utf8 string are the data) - compact: * structure = PyCompactUnicodeObject * test: PyUnicode_IS_COMPACT(op) && !PyUnicode_IS_ASCII(op) * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or PyUnicode_4BYTE_KIND * compact = 1 * ready = 1 * ascii = 0 * utf8 is not shared with data * utf8_length = 0 if utf8 is NULL * wstr is shared with data and wstr_length=length if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2 or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_t)=4 * wstr_length = 0 if wstr is NULL * (data starts just after the structure) - legacy string, not ready: * structure = PyUnicodeObject * test: kind == PyUnicode_WCHAR_KIND * length = 0 (use wstr_length) * hash = -1 * kind = PyUnicode_WCHAR_KIND * compact = 0 * ascii = 0 * ready = 0 * interned = SSTATE_NOT_INTERNED * wstr is not NULL * data.any is NULL * utf8 is NULL * utf8_length = 0 - legacy string, ready: * structure = PyUnicodeObject structure * test: !PyUnicode_IS_COMPACT(op) && kind != PyUnicode_WCHAR_KIND * kind = PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND or PyUnicode_4BYTE_KIND * compact = 0 * ready = 1 * data.any is not NULL * utf8 is shared and utf8_length = length with data.any if ascii = 1 * utf8_length = 0 if utf8 is NULL * wstr is shared with data.any and wstr_length = length if kind=PyUnicode_2BYTE_KIND and sizeof(wchar_t)=2 or if kind=PyUnicode_4BYTE_KIND and sizeof(wchar_4)=4 * wstr_length = 0 if wstr is NULL Compact strings use only one memory block (structure + characters), whereas legacy strings use one block for the structure and one block for characters. Legacy strings are created by PyUnicode_FromUnicode() and PyUnicode_FromStringAndSize(NULL, size) functions. They become ready when PyUnicode_READY() is called. See also _PyUnicode_CheckConsistency(). */ PyObject_HEAD Py_ssize_t length; /* Number of code points in the string */ Py_hash_t hash; /* Hash value; -1 if not set */ struct { /* SSTATE_NOT_INTERNED (0) SSTATE_INTERNED_MORTAL (1) SSTATE_INTERNED_IMMORTAL (2) If interned != SSTATE_NOT_INTERNED, the two references from the dictionary to this object are *not* counted in ob_refcnt. */ unsigned int interned:2; /* Character size: - PyUnicode_WCHAR_KIND (0): * character type = wchar_t (16 or 32 bits, depending on the platform) - PyUnicode_1BYTE_KIND (1): * character type = Py_UCS1 (8 bits, unsigned) * all characters are in the range U+0000-U+00FF (latin1) * if ascii is set, all characters are in the range U+0000-U+007F (ASCII), otherwise at least one character is in the range U+0080-U+00FF - PyUnicode_2BYTE_KIND (2): * character type = Py_UCS2 (16 bits, unsigned) * all characters are in the range U+0000-U+FFFF (BMP) * at least one character is in the range U+0100-U+FFFF - PyUnicode_4BYTE_KIND (4): * character type = Py_UCS4 (32 bits, unsigned) * all characters are in the range U+0000-U+10FFFF * at least one character is in the range U+10000-U+10FFFF */ unsigned int kind:3; /* Compact is with respect to the allocation scheme. Compact unicode objects only require one memory block while non-compact objects use one block for the PyUnicodeObject struct and another for its data buffer. */ unsigned int compact:1; /* The string only contains characters in the range U+0000-U+007F (ASCII) and the kind is PyUnicode_1BYTE_KIND. If ascii is set and compact is set, use the PyASCIIObject structure. */ unsigned int ascii:1; /* The ready flag indicates whether the object layout is initialized completely. This means that this is either a compact object, or the data pointer is filled out. The bit is redundant, and helps to minimize the test in PyUnicode_IS_READY(). */ unsigned int ready:1; /* Padding to ensure that PyUnicode_DATA() is always aligned to 4 bytes (see issue #19537 on m68k). */ unsigned int :24; } state; wchar_t *wstr; /* wchar_t representation (null-terminated) */ } PyASCIIObject; /* Non-ASCII strings allocated through PyUnicode_New use the PyCompactUnicodeObject structure. state.compact is set, and the data immediately follow the structure. */ typedef struct { PyASCIIObject _base; Py_ssize_t utf8_length; /* Number of bytes in utf8, excluding the * terminating \0. */ char *utf8; /* UTF-8 representation (null-terminated) */ Py_ssize_t wstr_length; /* Number of code points in wstr, possible * surrogates count as two code points. */ } PyCompactUnicodeObject; /* Strings allocated through PyUnicode_FromUnicode(NULL, len) use the PyUnicodeObject structure. The actual string data is initially in the wstr block, and copied into the data block using _PyUnicode_Ready. */ typedef struct { PyCompactUnicodeObject _base; union { void *any; Py_UCS1 *latin1; Py_UCS2 *ucs2; Py_UCS4 *ucs4; } data; /* Canonical, smallest-form Unicode buffer */ } PyUnicodeObject; PyAPI_FUNC(int) _PyUnicode_CheckConsistency( PyObject *op, int check_content); /* Fast access macros */ #define PyUnicode_WSTR_LENGTH(op) \ (PyUnicode_IS_COMPACT_ASCII(op) ? \ ((PyASCIIObject*)op)->length : \ ((PyCompactUnicodeObject*)op)->wstr_length) /* Returns the deprecated Py_UNICODE representation's size in code units (this includes surrogate pairs as 2 units). If the Py_UNICODE representation is not available, it will be computed on request. Use PyUnicode_GET_LENGTH() for the length in code points. */ /* Py_DEPRECATED(3.3) */ #define PyUnicode_GET_SIZE(op) \ (assert(PyUnicode_Check(op)), \ (((PyASCIIObject *)(op))->wstr) ? \ PyUnicode_WSTR_LENGTH(op) : \ ((void)PyUnicode_AsUnicode(_PyObject_CAST(op)),\ assert(((PyASCIIObject *)(op))->wstr), \ PyUnicode_WSTR_LENGTH(op))) /* Py_DEPRECATED(3.3) */ #define PyUnicode_GET_DATA_SIZE(op) \ (PyUnicode_GET_SIZE(op) * Py_UNICODE_SIZE) /* Alias for PyUnicode_AsUnicode(). This will create a wchar_t/Py_UNICODE representation on demand. Using this macro is very inefficient now, try to port your code to use the new PyUnicode_*BYTE_DATA() macros or use PyUnicode_WRITE() and PyUnicode_READ(). */ /* Py_DEPRECATED(3.3) */ #define PyUnicode_AS_UNICODE(op) \ (assert(PyUnicode_Check(op)), \ (((PyASCIIObject *)(op))->wstr) ? (((PyASCIIObject *)(op))->wstr) : \ PyUnicode_AsUnicode(_PyObject_CAST(op))) /* Py_DEPRECATED(3.3) */ #define PyUnicode_AS_DATA(op) \ ((const char *)(PyUnicode_AS_UNICODE(op))) /* --- Flexible String Representation Helper Macros (PEP 393) -------------- */ /* Values for PyASCIIObject.state: */ /* Interning state. */ #define SSTATE_NOT_INTERNED 0 #define SSTATE_INTERNED_MORTAL 1 #define SSTATE_INTERNED_IMMORTAL 2 /* Return true if the string contains only ASCII characters, or 0 if not. The string may be compact (PyUnicode_IS_COMPACT_ASCII) or not, but must be ready. */ #define PyUnicode_IS_ASCII(op) \ (assert(PyUnicode_Check(op)), \ assert(PyUnicode_IS_READY(op)), \ ((PyASCIIObject*)op)->state.ascii) /* Return true if the string is compact or 0 if not. No type checks or Ready calls are performed. */ #define PyUnicode_IS_COMPACT(op) \ (((PyASCIIObject*)(op))->state.compact) /* Return true if the string is a compact ASCII string (use PyASCIIObject structure), or 0 if not. No type checks or Ready calls are performed. */ #define PyUnicode_IS_COMPACT_ASCII(op) \ (((PyASCIIObject*)op)->state.ascii && PyUnicode_IS_COMPACT(op)) enum PyUnicode_Kind { /* String contains only wstr byte characters. This is only possible when the string was created with a legacy API and _PyUnicode_Ready() has not been called yet. */ PyUnicode_WCHAR_KIND = 0, /* Return values of the PyUnicode_KIND() macro: */ PyUnicode_1BYTE_KIND = 1, PyUnicode_2BYTE_KIND = 2, PyUnicode_4BYTE_KIND = 4 }; /* Return pointers to the canonical representation cast to unsigned char, Py_UCS2, or Py_UCS4 for direct character access. No checks are performed, use PyUnicode_KIND() before to ensure these will work correctly. */ #define PyUnicode_1BYTE_DATA(op) ((Py_UCS1*)PyUnicode_DATA(op)) #define PyUnicode_2BYTE_DATA(op) ((Py_UCS2*)PyUnicode_DATA(op)) #define PyUnicode_4BYTE_DATA(op) ((Py_UCS4*)PyUnicode_DATA(op)) /* Return one of the PyUnicode_*_KIND values defined above. */ #define PyUnicode_KIND(op) \ (assert(PyUnicode_Check(op)), \ assert(PyUnicode_IS_READY(op)), \ ((PyASCIIObject *)(op))->state.kind) /* Return a void pointer to the raw unicode buffer. */ #define _PyUnicode_COMPACT_DATA(op) \ (PyUnicode_IS_ASCII(op) ? \ ((void*)((PyASCIIObject*)(op) + 1)) : \ ((void*)((PyCompactUnicodeObject*)(op) + 1))) #define _PyUnicode_NONCOMPACT_DATA(op) \ (assert(((PyUnicodeObject*)(op))->data.any), \ ((((PyUnicodeObject *)(op))->data.any))) #define PyUnicode_DATA(op) \ (assert(PyUnicode_Check(op)), \ PyUnicode_IS_COMPACT(op) ? _PyUnicode_COMPACT_DATA(op) : \ _PyUnicode_NONCOMPACT_DATA(op)) /* In the access macros below, "kind" may be evaluated more than once. All other macro parameters are evaluated exactly once, so it is safe to put side effects into them (such as increasing the index). */ /* Write into the canonical representation, this macro does not do any sanity checks and is intended for usage in loops. The caller should cache the kind and data pointers obtained from other macro calls. index is the index in the string (starts at 0) and value is the new code point value which should be written to that location. */ #define PyUnicode_WRITE(kind, data, index, value) \ do { \ switch ((kind)) { \ case PyUnicode_1BYTE_KIND: { \ ((Py_UCS1 *)(data))[(index)] = (Py_UCS1)(value); \ break; \ } \ case PyUnicode_2BYTE_KIND: { \ ((Py_UCS2 *)(data))[(index)] = (Py_UCS2)(value); \ break; \ } \ default: { \ assert((kind) == PyUnicode_4BYTE_KIND); \ ((Py_UCS4 *)(data))[(index)] = (Py_UCS4)(value); \ } \ } \ } while (0) /* Read a code point from the string's canonical representation. No checks or ready calls are performed. */ #define PyUnicode_READ(kind, data, index) \ ((Py_UCS4) \ ((kind) == PyUnicode_1BYTE_KIND ? \ ((const Py_UCS1 *)(data))[(index)] : \ ((kind) == PyUnicode_2BYTE_KIND ? \ ((const Py_UCS2 *)(data))[(index)] : \ ((const Py_UCS4 *)(data))[(index)] \ ) \ )) /* PyUnicode_READ_CHAR() is less efficient than PyUnicode_READ() because it calls PyUnicode_KIND() and might call it twice. For single reads, use PyUnicode_READ_CHAR, for multiple consecutive reads callers should cache kind and use PyUnicode_READ instead. */ #define PyUnicode_READ_CHAR(unicode, index) \ (assert(PyUnicode_Check(unicode)), \ assert(PyUnicode_IS_READY(unicode)), \ (Py_UCS4) \ (PyUnicode_KIND((unicode)) == PyUnicode_1BYTE_KIND ? \ ((const Py_UCS1 *)(PyUnicode_DATA((unicode))))[(index)] : \ (PyUnicode_KIND((unicode)) == PyUnicode_2BYTE_KIND ? \ ((const Py_UCS2 *)(PyUnicode_DATA((unicode))))[(index)] : \ ((const Py_UCS4 *)(PyUnicode_DATA((unicode))))[(index)] \ ) \ )) /* Returns the length of the unicode string. The caller has to make sure that the string has it's canonical representation set before calling this macro. Call PyUnicode_(FAST_)Ready to ensure that. */ #define PyUnicode_GET_LENGTH(op) \ (assert(PyUnicode_Check(op)), \ assert(PyUnicode_IS_READY(op)), \ ((PyASCIIObject *)(op))->length) /* Fast check to determine whether an object is ready. Equivalent to PyUnicode_IS_COMPACT(op) || ((PyUnicodeObject*)(op))->data.any) */ #define PyUnicode_IS_READY(op) (((PyASCIIObject*)op)->state.ready) /* PyUnicode_READY() does less work than _PyUnicode_Ready() in the best case. If the canonical representation is not yet set, it will still call _PyUnicode_Ready(). Returns 0 on success and -1 on errors. */ #define PyUnicode_READY(op) \ (assert(PyUnicode_Check(op)), \ (PyUnicode_IS_READY(op) ? \ 0 : _PyUnicode_Ready(_PyObject_CAST(op)))) /* Return a maximum character value which is suitable for creating another string based on op. This is always an approximation but more efficient than iterating over the string. */ #define PyUnicode_MAX_CHAR_VALUE(op) \ (assert(PyUnicode_IS_READY(op)), \ (PyUnicode_IS_ASCII(op) ? \ (0x7f) : \ (PyUnicode_KIND(op) == PyUnicode_1BYTE_KIND ? \ (0xffU) : \ (PyUnicode_KIND(op) == PyUnicode_2BYTE_KIND ? \ (0xffffU) : \ (0x10ffffU))))) /* === Public API ========================================================= */ /* --- Plain Py_UNICODE --------------------------------------------------- */ /* With PEP 393, this is the recommended way to allocate a new unicode object. This function will allocate the object and its buffer in a single memory block. Objects created using this function are not resizable. */ PyAPI_FUNC(PyObject*) PyUnicode_New( Py_ssize_t size, /* Number of code points in the new string */ Py_UCS4 maxchar /* maximum code point value in the string */ ); /* Initializes the canonical string representation from the deprecated wstr/Py_UNICODE representation. This function is used to convert Unicode objects which were created using the old API to the new flexible format introduced with PEP 393. Don't call this function directly, use the public PyUnicode_READY() macro instead. */ PyAPI_FUNC(int) _PyUnicode_Ready( PyObject *unicode /* Unicode object */ ); /* Get a copy of a Unicode string. */ PyAPI_FUNC(PyObject*) _PyUnicode_Copy( PyObject *unicode ); /* Copy character from one unicode object into another, this function performs character conversion when necessary and falls back to memcpy() if possible. Fail if to is too small (smaller than *how_many* or smaller than len(from)-from_start), or if kind(from[from_start:from_start+how_many]) > kind(to), or if *to* has more than 1 reference. Return the number of written character, or return -1 and raise an exception on error. Pseudo-code: how_many = min(how_many, len(from) - from_start) to[to_start:to_start+how_many] = from[from_start:from_start+how_many] return how_many Note: The function doesn't write a terminating null character. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_CopyCharacters( PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many ); /* Unsafe version of PyUnicode_CopyCharacters(): don't check arguments and so may crash if parameters are invalid (e.g. if the output string is too short). */ PyAPI_FUNC(void) _PyUnicode_FastCopyCharacters( PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many ); /* Fill a string with a character: write fill_char into unicode[start:start+length]. Fail if fill_char is bigger than the string maximum character, or if the string has more than 1 reference. Return the number of written character, or return -1 and raise an exception on error. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Fill( PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char ); /* Unsafe version of PyUnicode_Fill(): don't check arguments and so may crash if parameters are invalid (e.g. if length is longer than the string). */ PyAPI_FUNC(void) _PyUnicode_FastFill( PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char ); /* Create a Unicode Object from the Py_UNICODE buffer u of the given size. u may be NULL which causes the contents to be undefined. It is the user's responsibility to fill in the needed data afterwards. Note that modifying the Unicode object contents after construction is only allowed if u was set to NULL. The buffer is copied into the new object. */ /* Py_DEPRECATED(3.3) */ PyAPI_FUNC(PyObject*) PyUnicode_FromUnicode( const Py_UNICODE *u, /* Unicode buffer */ Py_ssize_t size /* size of buffer */ ); /* Create a new string from a buffer of Py_UCS1, Py_UCS2 or Py_UCS4 characters. Scan the string to find the maximum character. */ PyAPI_FUNC(PyObject*) PyUnicode_FromKindAndData( int kind, const void *buffer, Py_ssize_t size); /* Create a new string from a buffer of ASCII characters. WARNING: Don't check if the string contains any non-ASCII character. */ PyAPI_FUNC(PyObject*) _PyUnicode_FromASCII( const char *buffer, Py_ssize_t size); /* Compute the maximum character of the substring unicode[start:end]. Return 127 for an empty string. */ PyAPI_FUNC(Py_UCS4) _PyUnicode_FindMaxChar ( PyObject *unicode, Py_ssize_t start, Py_ssize_t end); /* Return a read-only pointer to the Unicode object's internal Py_UNICODE buffer. If the wchar_t/Py_UNICODE representation is not yet available, this function will calculate it. */ /* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( PyObject *unicode /* Unicode object */ ); /* Similar to PyUnicode_AsUnicode(), but raises a ValueError if the string contains null characters. */ PyAPI_FUNC(const Py_UNICODE *) _PyUnicode_AsUnicode( PyObject *unicode /* Unicode object */ ); /* Return a read-only pointer to the Unicode object's internal Py_UNICODE buffer and save the length at size. If the wchar_t/Py_UNICODE representation is not yet available, this function will calculate it. */ /* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicodeAndSize( PyObject *unicode, /* Unicode object */ Py_ssize_t *size /* location where to save the length */ ); /* Get the maximum ordinal for a Unicode character. */ Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE) PyUnicode_GetMax(void); /* --- _PyUnicodeWriter API ----------------------------------------------- */ typedef struct { PyObject *buffer; void *data; enum PyUnicode_Kind kind; Py_UCS4 maxchar; Py_ssize_t size; Py_ssize_t pos; /* minimum number of allocated characters (default: 0) */ Py_ssize_t min_length; /* minimum character (default: 127, ASCII) */ Py_UCS4 min_char; /* If non-zero, overallocate the buffer (default: 0). */ unsigned char overallocate; /* If readonly is 1, buffer is a shared string (cannot be modified) and size is set to 0. */ unsigned char readonly; } _PyUnicodeWriter ; /* Initialize a Unicode writer. * * By default, the minimum buffer size is 0 character and overallocation is * disabled. Set min_length, min_char and overallocate attributes to control * the allocation of the buffer. */ PyAPI_FUNC(void) _PyUnicodeWriter_Init(_PyUnicodeWriter *writer); /* Prepare the buffer to write 'length' characters with the specified maximum character. Return 0 on success, raise an exception and return -1 on error. */ #define _PyUnicodeWriter_Prepare(WRITER, LENGTH, MAXCHAR) \ (((MAXCHAR) <= (WRITER)->maxchar \ && (LENGTH) <= (WRITER)->size - (WRITER)->pos) \ ? 0 \ : (((LENGTH) == 0) \ ? 0 \ : _PyUnicodeWriter_PrepareInternal((WRITER), (LENGTH), (MAXCHAR)))) /* Don't call this function directly, use the _PyUnicodeWriter_Prepare() macro instead. */ PyAPI_FUNC(int) _PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer, Py_ssize_t length, Py_UCS4 maxchar); /* Prepare the buffer to have at least the kind KIND. For example, kind=PyUnicode_2BYTE_KIND ensures that the writer will support characters in range U+000-U+FFFF. Return 0 on success, raise an exception and return -1 on error. */ #define _PyUnicodeWriter_PrepareKind(WRITER, KIND) \ (assert((KIND) != PyUnicode_WCHAR_KIND), \ (KIND) <= (WRITER)->kind \ ? 0 \ : _PyUnicodeWriter_PrepareKindInternal((WRITER), (KIND))) /* Don't call this function directly, use the _PyUnicodeWriter_PrepareKind() macro instead. */ PyAPI_FUNC(int) _PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer, enum PyUnicode_Kind kind); /* Append a Unicode character. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch ); /* Append a Unicode string. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str /* Unicode string */ ); /* Append a substring of a Unicode string. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str, /* Unicode string */ Py_ssize_t start, Py_ssize_t end ); /* Append an ASCII-encoded byte string. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer, const char *str, /* ASCII-encoded byte string */ Py_ssize_t len /* number of bytes, or -1 if unknown */ ); /* Append a latin1-encoded byte string. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer, const char *str, /* latin1-encoded byte string */ Py_ssize_t len /* length in bytes */ ); /* Get the value of the writer as a Unicode string. Clear the buffer of the writer. Raise an exception and return NULL on error. */ PyAPI_FUNC(PyObject *) _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer); /* Deallocate memory of a writer (clear its internal buffer). */ PyAPI_FUNC(void) _PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer); /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ PyAPI_FUNC(int) _PyUnicode_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); /* --- wchar_t support for platforms which support it --------------------- */ #ifdef HAVE_WCHAR_H PyAPI_FUNC(void*) _PyUnicode_AsKind(PyObject *s, unsigned int kind); #endif /* --- Manage the default encoding ---------------------------------------- */ /* Returns a pointer to the default encoding (UTF-8) of the Unicode object unicode and the size of the encoded representation in bytes stored in *size. In case of an error, no *size is set. This function caches the UTF-8 encoded string in the unicodeobject and subsequent calls will return the same string. The memory is released when the unicodeobject is deallocated. _PyUnicode_AsStringAndSize is a #define for PyUnicode_AsUTF8AndSize to support the previous internal function with the same behaviour. *** This API is for interpreter INTERNAL USE ONLY and will likely *** be removed or changed in the future. *** If you need to access the Unicode object as UTF-8 bytes string, *** please use PyUnicode_AsUTF8String() instead. */ PyAPI_FUNC(const char *) PyUnicode_AsUTF8AndSize( PyObject *unicode, Py_ssize_t *size); #define _PyUnicode_AsStringAndSize PyUnicode_AsUTF8AndSize /* Returns a pointer to the default encoding (UTF-8) of the Unicode object unicode. Like PyUnicode_AsUTF8AndSize(), this also caches the UTF-8 representation in the unicodeobject. _PyUnicode_AsString is a #define for PyUnicode_AsUTF8 to support the previous internal function with the same behaviour. Use of this API is DEPRECATED since no size information can be extracted from the returned data. *** This API is for interpreter INTERNAL USE ONLY and will likely *** be removed or changed for Python 3.1. *** If you need to access the Unicode object as UTF-8 bytes string, *** please use PyUnicode_AsUTF8String() instead. */ PyAPI_FUNC(const char *) PyUnicode_AsUTF8(PyObject *unicode); #define _PyUnicode_AsString PyUnicode_AsUTF8 /* --- Generic Codecs ----------------------------------------------------- */ /* Encodes a Py_UNICODE buffer of the given size and returns a Python string object. */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_Encode( const Py_UNICODE *s, /* Unicode char buffer */ Py_ssize_t size, /* number of Py_UNICODE chars to encode */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* --- UTF-7 Codecs ------------------------------------------------------- */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ int base64SetO, /* Encode RFC2152 Set O characters in base64 */ int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF7( PyObject *unicode, /* Unicode object */ int base64SetO, /* Encode RFC2152 Set O characters in base64 */ int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ const char *errors /* error handling */ ); /* --- UTF-8 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) _PyUnicode_AsUTF8String( PyObject *unicode, const char *errors); Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); /* --- UTF-32 Codecs ------------------------------------------------------ */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF32( PyObject *object, /* Unicode object */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- UTF-16 Codecs ------------------------------------------------------ */ /* Returns a Python string object holding the UTF-16 encoded value of the Unicode data. If byteorder is not 0, output is written according to the following byte order: byteorder == -1: little endian byteorder == 0: native byte order (writes a BOM mark) byteorder == 1: big endian If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended. Note that Py_UNICODE data is being interpreted as UTF-16 reduced to UCS-2. This trick makes it possible to add full UTF-16 capabilities at a later point without compromising the APIs. */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); PyAPI_FUNC(PyObject*) _PyUnicode_EncodeUTF16( PyObject* unicode, /* Unicode object */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); /* --- Unicode-Escape Codecs ---------------------------------------------- */ /* Helper for PyUnicode_DecodeUnicodeEscape that detects invalid escape chars. */ PyAPI_FUNC(PyObject*) _PyUnicode_DecodeUnicodeEscape( const char *string, /* Unicode-Escape encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ const char **first_invalid_escape /* on return, points to first invalid escaped char in string. */ ); Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); /* --- Latin-1 Codecs ----------------------------------------------------- */ PyAPI_FUNC(PyObject*) _PyUnicode_AsLatin1String( PyObject* unicode, const char* errors); Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); /* --- ASCII Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) _PyUnicode_AsASCIIString( PyObject* unicode, const char* errors); Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); /* --- Character Map Codecs ----------------------------------------------- */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ PyObject *mapping, /* encoding mapping */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) _PyUnicode_EncodeCharmap( PyObject *unicode, /* Unicode object */ PyObject *mapping, /* encoding mapping */ const char *errors /* error handling */ ); /* Translate a Py_UNICODE buffer of the given length by applying a character mapping table to it and return the resulting Unicode object. The mapping table must map Unicode ordinal integers to Unicode strings, Unicode ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is. */ Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ PyObject *table, /* Translate table */ const char *errors /* error handling */ ); /* --- MBCS codecs for Windows -------------------------------------------- */ #ifdef MS_WINDOWS Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); #endif /* --- Decimal Encoder ---------------------------------------------------- */ /* Takes a Unicode string holding a decimal value and writes it into an output buffer using standard ASCII digit codes. The output buffer has to provide at least length+1 bytes of storage area. The output string is 0-terminated. The encoder converts whitespace to ' ', decimal characters to their corresponding ASCII digit and all other Latin-1 characters except \0 as-is. Characters outside this range (Unicode ordinals 1-256) are treated as errors. This includes embedded NULL bytes. Error handling is defined by the errors argument: NULL or "strict": raise a ValueError "ignore": ignore the wrong characters (these are not copied to the output buffer) "replace": replaces illegal characters with '?' Returns 0 on success, -1 on failure. */ /* Py_DEPRECATED(3.3) */ PyAPI_FUNC(int) PyUnicode_EncodeDecimal( Py_UNICODE *s, /* Unicode buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ char *output, /* Output buffer; must have size >= length */ const char *errors /* error handling */ ); /* Transforms code points that have decimal digit property to the corresponding ASCII digit code points. Returns a new Unicode string on success, NULL on failure. */ /* Py_DEPRECATED(3.3) */ PyAPI_FUNC(PyObject*) PyUnicode_TransformDecimalToASCII( Py_UNICODE *s, /* Unicode buffer */ Py_ssize_t length /* Number of Py_UNICODE chars to transform */ ); /* Coverts a Unicode object holding a decimal value to an ASCII string for using in int, float and complex parsers. Transforms code points that have decimal digit property to the corresponding ASCII digit code points. Transforms spaces to ASCII. Transforms code points starting from the first non-ASCII code point that is neither a decimal digit nor a space to the end into '?'. */ PyAPI_FUNC(PyObject*) _PyUnicode_TransformDecimalAndSpaceToASCII( PyObject *unicode /* Unicode object */ ); /* --- Methods & Slots ---------------------------------------------------- */ PyAPI_FUNC(PyObject *) _PyUnicode_JoinArray( PyObject *separator, PyObject *const *items, Py_ssize_t seqlen ); /* Test whether a unicode is equal to ASCII identifier. Return 1 if true, 0 otherwise. The right argument must be ASCII identifier. Any error occurs inside will be cleared before return. */ PyAPI_FUNC(int) _PyUnicode_EqualToASCIIId( PyObject *left, /* Left string */ _Py_Identifier *right /* Right identifier */ ); /* Test whether a unicode is equal to ASCII string. Return 1 if true, 0 otherwise. The right argument must be ASCII-encoded string. Any error occurs inside will be cleared before return. */ PyAPI_FUNC(int) _PyUnicode_EqualToASCIIString( PyObject *left, const char *right /* ASCII-encoded string */ ); /* Externally visible for str.strip(unicode) */ PyAPI_FUNC(PyObject *) _PyUnicode_XStrip( PyObject *self, int striptype, PyObject *sepobj ); /* Using explicit passed-in values, insert the thousands grouping into the string pointed to by buffer. For the argument descriptions, see Objects/stringlib/localeutil.h */ PyAPI_FUNC(Py_ssize_t) _PyUnicode_InsertThousandsGrouping( _PyUnicodeWriter *writer, Py_ssize_t n_buffer, PyObject *digits, Py_ssize_t d_pos, Py_ssize_t n_digits, Py_ssize_t min_width, const char *grouping, PyObject *thousands_sep, Py_UCS4 *maxchar); /* === Characters Type APIs =============================================== */ /* Helper array used by Py_UNICODE_ISSPACE(). */ PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[]; /* These should not be used directly. Use the Py_UNICODE_IS* and Py_UNICODE_TO* macros instead. These APIs are implemented in Objects/unicodectype.c. */ PyAPI_FUNC(int) _PyUnicode_IsLowercase( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsUppercase( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsTitlecase( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidStart( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsXidContinue( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsWhitespace( const Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsLinebreak( const Py_UCS4 ch /* Unicode character */ ); /* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UCS4) _PyUnicode_ToLowercase( Py_UCS4 ch /* Unicode character */ ); /* Py_DEPRECATED(3.3) */ PyAPI_FUNC(Py_UCS4) _PyUnicode_ToUppercase( Py_UCS4 ch /* Unicode character */ ); Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UCS4) _PyUnicode_ToTitlecase( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToLowerFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); PyAPI_FUNC(int) _PyUnicode_ToTitleFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); PyAPI_FUNC(int) _PyUnicode_ToUpperFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); PyAPI_FUNC(int) _PyUnicode_ToFoldedFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); PyAPI_FUNC(int) _PyUnicode_IsCaseIgnorable( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsCased( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDecimalDigit( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_ToDigit( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(double) _PyUnicode_ToNumeric( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDecimalDigit( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsDigit( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsNumeric( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsPrintable( Py_UCS4 ch /* Unicode character */ ); PyAPI_FUNC(int) _PyUnicode_IsAlpha( Py_UCS4 ch /* Unicode character */ ); Py_DEPRECATED(3.3) PyAPI_FUNC(size_t) Py_UNICODE_strlen( const Py_UNICODE *u ); Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strcpy( Py_UNICODE *s1, const Py_UNICODE *s2); Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strcat( Py_UNICODE *s1, const Py_UNICODE *s2); Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strncpy( Py_UNICODE *s1, const Py_UNICODE *s2, size_t n); Py_DEPRECATED(3.3) PyAPI_FUNC(int) Py_UNICODE_strcmp( const Py_UNICODE *s1, const Py_UNICODE *s2 ); Py_DEPRECATED(3.3) PyAPI_FUNC(int) Py_UNICODE_strncmp( const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n ); Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strchr( const Py_UNICODE *s, Py_UNICODE c ); Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE*) Py_UNICODE_strrchr( const Py_UNICODE *s, Py_UNICODE c ); PyAPI_FUNC(PyObject*) _PyUnicode_FormatLong(PyObject *, int, int, int); /* Create a copy of a unicode string ending with a nul character. Return NULL and raise a MemoryError exception on memory allocation failure, otherwise return a new allocated buffer (use PyMem_Free() to free the buffer). */ Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE*) PyUnicode_AsUnicodeCopy( PyObject *unicode ); /* Return an interned Unicode object for an Identifier; may fail if there is no memory.*/ PyAPI_FUNC(PyObject*) _PyUnicode_FromId(_Py_Identifier*); /* Clear all static strings. */ PyAPI_FUNC(void) _PyUnicode_ClearStaticStrings(void); /* Fast equality check when the inputs are known to be exact unicode types and where the hash values are equal (i.e. a very probable match) */ PyAPI_FUNC(int) _PyUnicode_EQ(PyObject *, PyObject *); #ifdef __cplusplus } #endif ================================================ FILE: thirdLibs/python3_8/include/datetime.h ================================================ /* datetime.h */ #ifndef Py_LIMITED_API #ifndef DATETIME_H #define DATETIME_H #ifdef __cplusplus extern "C" { #endif /* Fields are packed into successive bytes, each viewed as unsigned and * big-endian, unless otherwise noted: * * byte offset * 0 year 2 bytes, 1-9999 * 2 month 1 byte, 1-12 * 3 day 1 byte, 1-31 * 4 hour 1 byte, 0-23 * 5 minute 1 byte, 0-59 * 6 second 1 byte, 0-59 * 7 usecond 3 bytes, 0-999999 * 10 */ /* # of bytes for year, month, and day. */ #define _PyDateTime_DATE_DATASIZE 4 /* # of bytes for hour, minute, second, and usecond. */ #define _PyDateTime_TIME_DATASIZE 6 /* # of bytes for year, month, day, hour, minute, second, and usecond. */ #define _PyDateTime_DATETIME_DATASIZE 10 typedef struct { PyObject_HEAD Py_hash_t hashcode; /* -1 when unknown */ int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ int seconds; /* 0 <= seconds < 24*3600 is invariant */ int microseconds; /* 0 <= microseconds < 1000000 is invariant */ } PyDateTime_Delta; typedef struct { PyObject_HEAD /* a pure abstract base class */ } PyDateTime_TZInfo; /* The datetime and time types have hashcodes, and an optional tzinfo member, * present if and only if hastzinfo is true. */ #define _PyTZINFO_HEAD \ PyObject_HEAD \ Py_hash_t hashcode; \ char hastzinfo; /* boolean flag */ /* No _PyDateTime_BaseTZInfo is allocated; it's just to have something * convenient to cast to, when getting at the hastzinfo member of objects * starting with _PyTZINFO_HEAD. */ typedef struct { _PyTZINFO_HEAD } _PyDateTime_BaseTZInfo; /* All time objects are of PyDateTime_TimeType, but that can be allocated * in two ways, with or without a tzinfo member. Without is the same as * tzinfo == None, but consumes less memory. _PyDateTime_BaseTime is an * internal struct used to allocate the right amount of space for the * "without" case. */ #define _PyDateTime_TIMEHEAD \ _PyTZINFO_HEAD \ unsigned char data[_PyDateTime_TIME_DATASIZE]; typedef struct { _PyDateTime_TIMEHEAD } _PyDateTime_BaseTime; /* hastzinfo false */ typedef struct { _PyDateTime_TIMEHEAD unsigned char fold; PyObject *tzinfo; } PyDateTime_Time; /* hastzinfo true */ /* All datetime objects are of PyDateTime_DateTimeType, but that can be * allocated in two ways too, just like for time objects above. In addition, * the plain date type is a base class for datetime, so it must also have * a hastzinfo member (although it's unused there). */ typedef struct { _PyTZINFO_HEAD unsigned char data[_PyDateTime_DATE_DATASIZE]; } PyDateTime_Date; #define _PyDateTime_DATETIMEHEAD \ _PyTZINFO_HEAD \ unsigned char data[_PyDateTime_DATETIME_DATASIZE]; typedef struct { _PyDateTime_DATETIMEHEAD } _PyDateTime_BaseDateTime; /* hastzinfo false */ typedef struct { _PyDateTime_DATETIMEHEAD unsigned char fold; PyObject *tzinfo; } PyDateTime_DateTime; /* hastzinfo true */ /* Apply for date and datetime instances. */ #define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \ ((PyDateTime_Date*)o)->data[1]) #define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2]) #define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3]) #define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4]) #define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5]) #define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6]) #define PyDateTime_DATE_GET_MICROSECOND(o) \ ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ (((PyDateTime_DateTime*)o)->data[8] << 8) | \ ((PyDateTime_DateTime*)o)->data[9]) #define PyDateTime_DATE_GET_FOLD(o) (((PyDateTime_DateTime*)o)->fold) /* Apply for time instances. */ #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) #define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2]) #define PyDateTime_TIME_GET_MICROSECOND(o) \ ((((PyDateTime_Time*)o)->data[3] << 16) | \ (((PyDateTime_Time*)o)->data[4] << 8) | \ ((PyDateTime_Time*)o)->data[5]) #define PyDateTime_TIME_GET_FOLD(o) (((PyDateTime_Time*)o)->fold) /* Apply for time delta instances */ #define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days) #define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds) #define PyDateTime_DELTA_GET_MICROSECONDS(o) \ (((PyDateTime_Delta*)o)->microseconds) /* Define structure for C API. */ typedef struct { /* type objects */ PyTypeObject *DateType; PyTypeObject *DateTimeType; PyTypeObject *TimeType; PyTypeObject *DeltaType; PyTypeObject *TZInfoType; /* singletons */ PyObject *TimeZone_UTC; /* constructors */ PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*); PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int, PyObject*, PyTypeObject*); PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*); PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*); PyObject *(*TimeZone_FromTimeZone)(PyObject *offset, PyObject *name); /* constructors for the DB API */ PyObject *(*DateTime_FromTimestamp)(PyObject*, PyObject*, PyObject*); PyObject *(*Date_FromTimestamp)(PyObject*, PyObject*); /* PEP 495 constructors */ PyObject *(*DateTime_FromDateAndTimeAndFold)(int, int, int, int, int, int, int, PyObject*, int, PyTypeObject*); PyObject *(*Time_FromTimeAndFold)(int, int, int, int, PyObject*, int, PyTypeObject*); } PyDateTime_CAPI; #define PyDateTime_CAPSULE_NAME "datetime.datetime_CAPI" /* This block is only used as part of the public API and should not be * included in _datetimemodule.c, which does not use the C API capsule. * See bpo-35081 for more details. * */ #ifndef _PY_DATETIME_IMPL /* Define global variable for the C API and a macro for setting it. */ static PyDateTime_CAPI *PyDateTimeAPI = NULL; #define PyDateTime_IMPORT \ PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) /* Macro for access to the UTC singleton */ #define PyDateTime_TimeZone_UTC PyDateTimeAPI->TimeZone_UTC /* Macros for type checking when not building the Python core. */ #define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType) #define PyDate_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DateType) #define PyDateTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateTimeType) #define PyDateTime_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DateTimeType) #define PyTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TimeType) #define PyTime_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->TimeType) #define PyDelta_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DeltaType) #define PyDelta_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DeltaType) #define PyTZInfo_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TZInfoType) #define PyTZInfo_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->TZInfoType) /* Macros for accessing constructors in a simplified fashion. */ #define PyDate_FromDate(year, month, day) \ PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) #define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \ PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) #define PyDateTime_FromDateAndTimeAndFold(year, month, day, hour, min, sec, usec, fold) \ PyDateTimeAPI->DateTime_FromDateAndTimeAndFold(year, month, day, hour, \ min, sec, usec, Py_None, fold, PyDateTimeAPI->DateTimeType) #define PyTime_FromTime(hour, minute, second, usecond) \ PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ Py_None, PyDateTimeAPI->TimeType) #define PyTime_FromTimeAndFold(hour, minute, second, usecond, fold) \ PyDateTimeAPI->Time_FromTimeAndFold(hour, minute, second, usecond, \ Py_None, fold, PyDateTimeAPI->TimeType) #define PyDelta_FromDSU(days, seconds, useconds) \ PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ PyDateTimeAPI->DeltaType) #define PyTimeZone_FromOffset(offset) \ PyDateTimeAPI->TimeZone_FromTimeZone(offset, NULL) #define PyTimeZone_FromOffsetAndName(offset, name) \ PyDateTimeAPI->TimeZone_FromTimeZone(offset, name) /* Macros supporting the DB API. */ #define PyDateTime_FromTimestamp(args) \ PyDateTimeAPI->DateTime_FromTimestamp( \ (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) #define PyDate_FromTimestamp(args) \ PyDateTimeAPI->Date_FromTimestamp( \ (PyObject*) (PyDateTimeAPI->DateType), args) #endif /* !defined(_PY_DATETIME_IMPL) */ #ifdef __cplusplus } #endif #endif #endif /* !Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/descrobject.h ================================================ /* Descriptors */ #ifndef Py_DESCROBJECT_H #define Py_DESCROBJECT_H #ifdef __cplusplus extern "C" { #endif typedef PyObject *(*getter)(PyObject *, void *); typedef int (*setter)(PyObject *, PyObject *, void *); typedef struct PyGetSetDef { const char *name; getter get; setter set; const char *doc; void *closure; } PyGetSetDef; #ifndef Py_LIMITED_API typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args, void *wrapped); typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds); struct wrapperbase { const char *name; int offset; void *function; wrapperfunc wrapper; const char *doc; int flags; PyObject *name_strobj; }; /* Flags for above struct */ #define PyWrapperFlag_KEYWORDS 1 /* wrapper function takes keyword args */ /* Various kinds of descriptor objects */ typedef struct { PyObject_HEAD PyTypeObject *d_type; PyObject *d_name; PyObject *d_qualname; } PyDescrObject; #define PyDescr_COMMON PyDescrObject d_common #define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) typedef struct { PyDescr_COMMON; PyMethodDef *d_method; vectorcallfunc vectorcall; } PyMethodDescrObject; typedef struct { PyDescr_COMMON; struct PyMemberDef *d_member; } PyMemberDescrObject; typedef struct { PyDescr_COMMON; PyGetSetDef *d_getset; } PyGetSetDescrObject; typedef struct { PyDescr_COMMON; struct wrapperbase *d_base; void *d_wrapped; /* This can be any function pointer */ } PyWrapperDescrObject; #endif /* Py_LIMITED_API */ PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type; PyAPI_DATA(PyTypeObject) PyGetSetDescr_Type; PyAPI_DATA(PyTypeObject) PyMemberDescr_Type; PyAPI_DATA(PyTypeObject) PyMethodDescr_Type; PyAPI_DATA(PyTypeObject) PyWrapperDescr_Type; PyAPI_DATA(PyTypeObject) PyDictProxy_Type; #ifndef Py_LIMITED_API PyAPI_DATA(PyTypeObject) _PyMethodWrapper_Type; #endif /* Py_LIMITED_API */ PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *); struct PyMemberDef; /* forward declaration for following prototype */ PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *, struct PyMemberDef *); PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *, struct PyGetSetDef *); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *, struct wrapperbase *, void *); #define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL) #endif PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *); PyAPI_FUNC(PyObject *) PyWrapper_New(PyObject *, PyObject *); PyAPI_DATA(PyTypeObject) PyProperty_Type; #ifdef __cplusplus } #endif #endif /* !Py_DESCROBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/dictobject.h ================================================ #ifndef Py_DICTOBJECT_H #define Py_DICTOBJECT_H #ifdef __cplusplus extern "C" { #endif /* Dictionary object type -- mapping from hashable object to object */ /* The distribution includes a separate file, Objects/dictnotes.txt, describing explorations into dictionary design and optimization. It covers typical dictionary use patterns, the parameters for tuning dictionaries, and several ideas for possible optimizations. */ PyAPI_DATA(PyTypeObject) PyDict_Type; #define PyDict_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_DICT_SUBCLASS) #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) PyAPI_FUNC(PyObject *) PyDict_New(void); PyAPI_FUNC(PyObject *) PyDict_GetItem(PyObject *mp, PyObject *key); PyAPI_FUNC(PyObject *) PyDict_GetItemWithError(PyObject *mp, PyObject *key); PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item); PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key); PyAPI_FUNC(void) PyDict_Clear(PyObject *mp); PyAPI_FUNC(int) PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp); PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp); PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp); PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key); /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other); /* PyDict_Merge updates/merges from a mapping object (an object that supports PyMapping_Keys() and PyObject_GetItem()). If override is true, the last occurrence of a key wins, else the first. The Python dict.update(other) is equivalent to PyDict_Merge(dict, other, 1). */ PyAPI_FUNC(int) PyDict_Merge(PyObject *mp, PyObject *other, int override); /* PyDict_MergeFromSeq2 updates/merges from an iterable object producing iterable objects of length 2. If override is true, the last occurrence of a key wins, else the first. The Python dict constructor dict(seq2) is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1). */ PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override); PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key); PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item); PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key); /* Dictionary (keys, values, items) views */ PyAPI_DATA(PyTypeObject) PyDictKeys_Type; PyAPI_DATA(PyTypeObject) PyDictValues_Type; PyAPI_DATA(PyTypeObject) PyDictItems_Type; #define PyDictKeys_Check(op) PyObject_TypeCheck(op, &PyDictKeys_Type) #define PyDictValues_Check(op) PyObject_TypeCheck(op, &PyDictValues_Type) #define PyDictItems_Check(op) PyObject_TypeCheck(op, &PyDictItems_Type) /* This excludes Values, since they are not sets. */ # define PyDictViewSet_Check(op) \ (PyDictKeys_Check(op) || PyDictItems_Check(op)) /* Dictionary (key, value, items) iterators */ PyAPI_DATA(PyTypeObject) PyDictIterKey_Type; PyAPI_DATA(PyTypeObject) PyDictIterValue_Type; PyAPI_DATA(PyTypeObject) PyDictIterItem_Type; PyAPI_DATA(PyTypeObject) PyDictRevIterKey_Type; PyAPI_DATA(PyTypeObject) PyDictRevIterItem_Type; PyAPI_DATA(PyTypeObject) PyDictRevIterValue_Type; #ifndef Py_LIMITED_API # define Py_CPYTHON_DICTOBJECT_H # include "cpython/dictobject.h" # undef Py_CPYTHON_DICTOBJECT_H #endif #ifdef __cplusplus } #endif #endif /* !Py_DICTOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/dtoa.h ================================================ #ifndef Py_LIMITED_API #ifndef PY_NO_SHORT_FLOAT_REPR #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(double) _Py_dg_strtod(const char *str, char **ptr); PyAPI_FUNC(char *) _Py_dg_dtoa(double d, int mode, int ndigits, int *decpt, int *sign, char **rve); PyAPI_FUNC(void) _Py_dg_freedtoa(char *s); PyAPI_FUNC(double) _Py_dg_stdnan(int sign); PyAPI_FUNC(double) _Py_dg_infinity(int sign); #ifdef __cplusplus } #endif #endif #endif ================================================ FILE: thirdLibs/python3_8/include/dynamic_annotations.h ================================================ /* Copyright (c) 2008-2009, Google Inc. * 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. * * Neither the name of Google Inc. 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 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. * * --- * Author: Kostya Serebryany * Copied to CPython by Jeffrey Yasskin, with all macros renamed to * start with _Py_ to avoid colliding with users embedding Python, and * with deprecated macros removed. */ /* This file defines dynamic annotations for use with dynamic analysis tool such as valgrind, PIN, etc. Dynamic annotation is a source code annotation that affects the generated code (that is, the annotation is not a comment). Each such annotation is attached to a particular instruction and/or to a particular object (address) in the program. The annotations that should be used by users are macros in all upper-case (e.g., _Py_ANNOTATE_NEW_MEMORY). Actual implementation of these macros may differ depending on the dynamic analysis tool being used. See http://code.google.com/p/data-race-test/ for more information. This file supports the following dynamic analysis tools: - None (DYNAMIC_ANNOTATIONS_ENABLED is not defined or zero). Macros are defined empty. - ThreadSanitizer, Helgrind, DRD (DYNAMIC_ANNOTATIONS_ENABLED is 1). Macros are defined as calls to non-inlinable empty functions that are intercepted by Valgrind. */ #ifndef __DYNAMIC_ANNOTATIONS_H__ #define __DYNAMIC_ANNOTATIONS_H__ #ifndef DYNAMIC_ANNOTATIONS_ENABLED # define DYNAMIC_ANNOTATIONS_ENABLED 0 #endif #if DYNAMIC_ANNOTATIONS_ENABLED != 0 /* ------------------------------------------------------------- Annotations useful when implementing condition variables such as CondVar, using conditional critical sections (Await/LockWhen) and when constructing user-defined synchronization mechanisms. The annotations _Py_ANNOTATE_HAPPENS_BEFORE() and _Py_ANNOTATE_HAPPENS_AFTER() can be used to define happens-before arcs in user-defined synchronization mechanisms: the race detector will infer an arc from the former to the latter when they share the same argument pointer. Example 1 (reference counting): void Unref() { _Py_ANNOTATE_HAPPENS_BEFORE(&refcount_); if (AtomicDecrementByOne(&refcount_) == 0) { _Py_ANNOTATE_HAPPENS_AFTER(&refcount_); delete this; } } Example 2 (message queue): void MyQueue::Put(Type *e) { MutexLock lock(&mu_); _Py_ANNOTATE_HAPPENS_BEFORE(e); PutElementIntoMyQueue(e); } Type *MyQueue::Get() { MutexLock lock(&mu_); Type *e = GetElementFromMyQueue(); _Py_ANNOTATE_HAPPENS_AFTER(e); return e; } Note: when possible, please use the existing reference counting and message queue implementations instead of inventing new ones. */ /* Report that wait on the condition variable at address "cv" has succeeded and the lock at address "lock" is held. */ #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \ AnnotateCondVarWait(__FILE__, __LINE__, cv, lock) /* Report that wait on the condition variable at "cv" has succeeded. Variant w/o lock. */ #define _Py_ANNOTATE_CONDVAR_WAIT(cv) \ AnnotateCondVarWait(__FILE__, __LINE__, cv, NULL) /* Report that we are about to signal on the condition variable at address "cv". */ #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) \ AnnotateCondVarSignal(__FILE__, __LINE__, cv) /* Report that we are about to signal_all on the condition variable at "cv". */ #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \ AnnotateCondVarSignalAll(__FILE__, __LINE__, cv) /* Annotations for user-defined synchronization mechanisms. */ #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) _Py_ANNOTATE_CONDVAR_SIGNAL(obj) #define _Py_ANNOTATE_HAPPENS_AFTER(obj) _Py_ANNOTATE_CONDVAR_WAIT(obj) /* Report that the bytes in the range [pointer, pointer+size) are about to be published safely. The race checker will create a happens-before arc from the call _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) to subsequent accesses to this memory. Note: this annotation may not work properly if the race detector uses sampling, i.e. does not observe all memory accesses. */ #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \ AnnotatePublishMemoryRange(__FILE__, __LINE__, pointer, size) /* Instruct the tool to create a happens-before arc between mu->Unlock() and mu->Lock(). This annotation may slow down the race detector and hide real races. Normally it is used only when it would be difficult to annotate each of the mutex's critical sections individually using the annotations above. This annotation makes sense only for hybrid race detectors. For pure happens-before detectors this is a no-op. For more details see http://code.google.com/p/data-race-test/wiki/PureHappensBeforeVsHybrid . */ #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \ AnnotateMutexIsUsedAsCondVar(__FILE__, __LINE__, mu) /* ------------------------------------------------------------- Annotations useful when defining memory allocators, or when memory that was protected in one way starts to be protected in another. */ /* Report that a new memory at "address" of size "size" has been allocated. This might be used when the memory has been retrieved from a free list and is about to be reused, or when the locking discipline for a variable changes. */ #define _Py_ANNOTATE_NEW_MEMORY(address, size) \ AnnotateNewMemory(__FILE__, __LINE__, address, size) /* ------------------------------------------------------------- Annotations useful when defining FIFO queues that transfer data between threads. */ /* Report that the producer-consumer queue (such as ProducerConsumerQueue) at address "pcq" has been created. The _Py_ANNOTATE_PCQ_* annotations should be used only for FIFO queues. For non-FIFO queues use _Py_ANNOTATE_HAPPENS_BEFORE (for put) and _Py_ANNOTATE_HAPPENS_AFTER (for get). */ #define _Py_ANNOTATE_PCQ_CREATE(pcq) \ AnnotatePCQCreate(__FILE__, __LINE__, pcq) /* Report that the queue at address "pcq" is about to be destroyed. */ #define _Py_ANNOTATE_PCQ_DESTROY(pcq) \ AnnotatePCQDestroy(__FILE__, __LINE__, pcq) /* Report that we are about to put an element into a FIFO queue at address "pcq". */ #define _Py_ANNOTATE_PCQ_PUT(pcq) \ AnnotatePCQPut(__FILE__, __LINE__, pcq) /* Report that we've just got an element from a FIFO queue at address "pcq". */ #define _Py_ANNOTATE_PCQ_GET(pcq) \ AnnotatePCQGet(__FILE__, __LINE__, pcq) /* ------------------------------------------------------------- Annotations that suppress errors. It is usually better to express the program's synchronization using the other annotations, but these can be used when all else fails. */ /* Report that we may have a benign race at "pointer", with size "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the point where "pointer" has been allocated, preferably close to the point where the race happens. See also _Py_ANNOTATE_BENIGN_RACE_STATIC. */ #define _Py_ANNOTATE_BENIGN_RACE(pointer, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \ sizeof(*(pointer)), description) /* Same as _Py_ANNOTATE_BENIGN_RACE(address, description), but applies to the memory range [address, address+size). */ #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description) /* Request the analysis tool to ignore all reads in the current thread until _Py_ANNOTATE_IGNORE_READS_END is called. Useful to ignore intentional racey reads, while still checking other reads and all writes. See also _Py_ANNOTATE_UNPROTECTED_READ. */ #define _Py_ANNOTATE_IGNORE_READS_BEGIN() \ AnnotateIgnoreReadsBegin(__FILE__, __LINE__) /* Stop ignoring reads. */ #define _Py_ANNOTATE_IGNORE_READS_END() \ AnnotateIgnoreReadsEnd(__FILE__, __LINE__) /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. */ #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() \ AnnotateIgnoreWritesBegin(__FILE__, __LINE__) /* Stop ignoring writes. */ #define _Py_ANNOTATE_IGNORE_WRITES_END() \ AnnotateIgnoreWritesEnd(__FILE__, __LINE__) /* Start ignoring all memory accesses (reads and writes). */ #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ do {\ _Py_ANNOTATE_IGNORE_READS_BEGIN();\ _Py_ANNOTATE_IGNORE_WRITES_BEGIN();\ }while(0)\ /* Stop ignoring all memory accesses. */ #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() \ do {\ _Py_ANNOTATE_IGNORE_WRITES_END();\ _Py_ANNOTATE_IGNORE_READS_END();\ }while(0)\ /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore synchronization events: RWLOCK* and CONDVAR*. */ #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() \ AnnotateIgnoreSyncBegin(__FILE__, __LINE__) /* Stop ignoring sync events. */ #define _Py_ANNOTATE_IGNORE_SYNC_END() \ AnnotateIgnoreSyncEnd(__FILE__, __LINE__) /* Enable (enable!=0) or disable (enable==0) race detection for all threads. This annotation could be useful if you want to skip expensive race analysis during some period of program execution, e.g. during initialization. */ #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) \ AnnotateEnableRaceDetection(__FILE__, __LINE__, enable) /* ------------------------------------------------------------- Annotations useful for debugging. */ /* Request to trace every access to "address". */ #define _Py_ANNOTATE_TRACE_MEMORY(address) \ AnnotateTraceMemory(__FILE__, __LINE__, address) /* Report the current thread name to a race detector. */ #define _Py_ANNOTATE_THREAD_NAME(name) \ AnnotateThreadName(__FILE__, __LINE__, name) /* ------------------------------------------------------------- Annotations useful when implementing locks. They are not normally needed by modules that merely use locks. The "lock" argument is a pointer to the lock object. */ /* Report that a lock has been created at address "lock". */ #define _Py_ANNOTATE_RWLOCK_CREATE(lock) \ AnnotateRWLockCreate(__FILE__, __LINE__, lock) /* Report that the lock at address "lock" is about to be destroyed. */ #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) \ AnnotateRWLockDestroy(__FILE__, __LINE__, lock) /* Report that the lock at address "lock" has been acquired. is_w=1 for writer lock, is_w=0 for reader lock. */ #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w) /* Report that the lock at address "lock" is about to be released. */ #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w) /* ------------------------------------------------------------- Annotations useful when implementing barriers. They are not normally needed by modules that merely use barriers. The "barrier" argument is a pointer to the barrier object. */ /* Report that the "barrier" has been initialized with initial "count". If 'reinitialization_allowed' is true, initialization is allowed to happen multiple times w/o calling barrier_destroy() */ #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \ AnnotateBarrierInit(__FILE__, __LINE__, barrier, count, \ reinitialization_allowed) /* Report that we are about to enter barrier_wait("barrier"). */ #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \ AnnotateBarrierWaitBefore(__FILE__, __LINE__, barrier) /* Report that we just exited barrier_wait("barrier"). */ #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) \ AnnotateBarrierWaitAfter(__FILE__, __LINE__, barrier) /* Report that the "barrier" has been destroyed. */ #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) \ AnnotateBarrierDestroy(__FILE__, __LINE__, barrier) /* ------------------------------------------------------------- Annotations useful for testing race detectors. */ /* Report that we expect a race on the variable at "address". Use only in unit tests for a race detector. */ #define _Py_ANNOTATE_EXPECT_RACE(address, description) \ AnnotateExpectRace(__FILE__, __LINE__, address, description) /* A no-op. Insert where you like to test the interceptors. */ #define _Py_ANNOTATE_NO_OP(arg) \ AnnotateNoOp(__FILE__, __LINE__, arg) /* Force the race detector to flush its state. The actual effect depends on * the implementation of the detector. */ #define _Py_ANNOTATE_FLUSH_STATE() \ AnnotateFlushState(__FILE__, __LINE__) #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ #define _Py_ANNOTATE_RWLOCK_CREATE(lock) /* empty */ #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) /* empty */ #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */ #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */ #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */ #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) /* empty */ #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) /* empty */ #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) /* empty */ #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) /* empty */ #define _Py_ANNOTATE_CONDVAR_WAIT(cv) /* empty */ #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) /* empty */ #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) /* empty */ #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) /* empty */ #define _Py_ANNOTATE_HAPPENS_AFTER(obj) /* empty */ #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) /* empty */ #define _Py_ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) /* empty */ #define _Py_ANNOTATE_SWAP_MEMORY_RANGE(address, size) /* empty */ #define _Py_ANNOTATE_PCQ_CREATE(pcq) /* empty */ #define _Py_ANNOTATE_PCQ_DESTROY(pcq) /* empty */ #define _Py_ANNOTATE_PCQ_PUT(pcq) /* empty */ #define _Py_ANNOTATE_PCQ_GET(pcq) /* empty */ #define _Py_ANNOTATE_NEW_MEMORY(address, size) /* empty */ #define _Py_ANNOTATE_EXPECT_RACE(address, description) /* empty */ #define _Py_ANNOTATE_BENIGN_RACE(address, description) /* empty */ #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */ #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) /* empty */ #define _Py_ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) /* empty */ #define _Py_ANNOTATE_TRACE_MEMORY(arg) /* empty */ #define _Py_ANNOTATE_THREAD_NAME(name) /* empty */ #define _Py_ANNOTATE_IGNORE_READS_BEGIN() /* empty */ #define _Py_ANNOTATE_IGNORE_READS_END() /* empty */ #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */ #define _Py_ANNOTATE_IGNORE_WRITES_END() /* empty */ #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */ #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */ #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() /* empty */ #define _Py_ANNOTATE_IGNORE_SYNC_END() /* empty */ #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */ #define _Py_ANNOTATE_NO_OP(arg) /* empty */ #define _Py_ANNOTATE_FLUSH_STATE() /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ /* Use the macros above rather than using these functions directly. */ #ifdef __cplusplus extern "C" { #endif void AnnotateRWLockCreate(const char *file, int line, const volatile void *lock); void AnnotateRWLockDestroy(const char *file, int line, const volatile void *lock); void AnnotateRWLockAcquired(const char *file, int line, const volatile void *lock, long is_w); void AnnotateRWLockReleased(const char *file, int line, const volatile void *lock, long is_w); void AnnotateBarrierInit(const char *file, int line, const volatile void *barrier, long count, long reinitialization_allowed); void AnnotateBarrierWaitBefore(const char *file, int line, const volatile void *barrier); void AnnotateBarrierWaitAfter(const char *file, int line, const volatile void *barrier); void AnnotateBarrierDestroy(const char *file, int line, const volatile void *barrier); void AnnotateCondVarWait(const char *file, int line, const volatile void *cv, const volatile void *lock); void AnnotateCondVarSignal(const char *file, int line, const volatile void *cv); void AnnotateCondVarSignalAll(const char *file, int line, const volatile void *cv); void AnnotatePublishMemoryRange(const char *file, int line, const volatile void *address, long size); void AnnotateUnpublishMemoryRange(const char *file, int line, const volatile void *address, long size); void AnnotatePCQCreate(const char *file, int line, const volatile void *pcq); void AnnotatePCQDestroy(const char *file, int line, const volatile void *pcq); void AnnotatePCQPut(const char *file, int line, const volatile void *pcq); void AnnotatePCQGet(const char *file, int line, const volatile void *pcq); void AnnotateNewMemory(const char *file, int line, const volatile void *address, long size); void AnnotateExpectRace(const char *file, int line, const volatile void *address, const char *description); void AnnotateBenignRace(const char *file, int line, const volatile void *address, const char *description); void AnnotateBenignRaceSized(const char *file, int line, const volatile void *address, long size, const char *description); void AnnotateMutexIsUsedAsCondVar(const char *file, int line, const volatile void *mu); void AnnotateTraceMemory(const char *file, int line, const volatile void *arg); void AnnotateThreadName(const char *file, int line, const char *name); void AnnotateIgnoreReadsBegin(const char *file, int line); void AnnotateIgnoreReadsEnd(const char *file, int line); void AnnotateIgnoreWritesBegin(const char *file, int line); void AnnotateIgnoreWritesEnd(const char *file, int line); void AnnotateEnableRaceDetection(const char *file, int line, int enable); void AnnotateNoOp(const char *file, int line, const volatile void *arg); void AnnotateFlushState(const char *file, int line); /* Return non-zero value if running under valgrind. If "valgrind.h" is included into dynamic_annotations.c, the regular valgrind mechanism will be used. See http://valgrind.org/docs/manual/manual-core-adv.html about RUNNING_ON_VALGRIND and other valgrind "client requests". The file "valgrind.h" may be obtained by doing svn co svn://svn.valgrind.org/valgrind/trunk/include If for some reason you can't use "valgrind.h" or want to fake valgrind, there are two ways to make this function return non-zero: - Use environment variable: export RUNNING_ON_VALGRIND=1 - Make your tool intercept the function RunningOnValgrind() and change its return value. */ int RunningOnValgrind(void); #ifdef __cplusplus } #endif #if DYNAMIC_ANNOTATIONS_ENABLED != 0 && defined(__cplusplus) /* _Py_ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads. Instead of doing _Py_ANNOTATE_IGNORE_READS_BEGIN(); ... = x; _Py_ANNOTATE_IGNORE_READS_END(); one can use ... = _Py_ANNOTATE_UNPROTECTED_READ(x); */ template inline T _Py_ANNOTATE_UNPROTECTED_READ(const volatile T &x) { _Py_ANNOTATE_IGNORE_READS_BEGIN(); T res = x; _Py_ANNOTATE_IGNORE_READS_END(); return res; } /* Apply _Py_ANNOTATE_BENIGN_RACE_SIZED to a static variable. */ #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ namespace { \ class static_var ## _annotator { \ public: \ static_var ## _annotator() { \ _Py_ANNOTATE_BENIGN_RACE_SIZED(&static_var, \ sizeof(static_var), \ # static_var ": " description); \ } \ }; \ static static_var ## _annotator the ## static_var ## _annotator;\ } #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ #define _Py_ANNOTATE_UNPROTECTED_READ(x) (x) #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */ #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ #endif /* __DYNAMIC_ANNOTATIONS_H__ */ ================================================ FILE: thirdLibs/python3_8/include/enumobject.h ================================================ #ifndef Py_ENUMOBJECT_H #define Py_ENUMOBJECT_H /* Enumerate Object */ #ifdef __cplusplus extern "C" { #endif PyAPI_DATA(PyTypeObject) PyEnum_Type; PyAPI_DATA(PyTypeObject) PyReversed_Type; #ifdef __cplusplus } #endif #endif /* !Py_ENUMOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/errcode.h ================================================ #ifndef Py_ERRCODE_H #define Py_ERRCODE_H #ifdef __cplusplus extern "C" { #endif /* Error codes passed around between file input, tokenizer, parser and interpreter. This is necessary so we can turn them into Python exceptions at a higher level. Note that some errors have a slightly different meaning when passed from the tokenizer to the parser than when passed from the parser to the interpreter; e.g. the parser only returns E_EOF when it hits EOF immediately, and it never returns E_OK. */ #define E_OK 10 /* No error */ #define E_EOF 11 /* End Of File */ #define E_INTR 12 /* Interrupted */ #define E_TOKEN 13 /* Bad token */ #define E_SYNTAX 14 /* Syntax error */ #define E_NOMEM 15 /* Ran out of memory */ #define E_DONE 16 /* Parsing complete */ #define E_ERROR 17 /* Execution error */ #define E_TABSPACE 18 /* Inconsistent mixing of tabs and spaces */ #define E_OVERFLOW 19 /* Node had too many children */ #define E_TOODEEP 20 /* Too many indentation levels */ #define E_DEDENT 21 /* No matching outer block for dedent */ #define E_DECODE 22 /* Error in decoding into Unicode */ #define E_EOFS 23 /* EOF in triple-quoted string */ #define E_EOLS 24 /* EOL in single-quoted string */ #define E_LINECONT 25 /* Unexpected characters after a line continuation */ #define E_IDENTIFIER 26 /* Invalid characters in identifier */ #define E_BADSINGLE 27 /* Ill-formed single statement input */ #ifdef __cplusplus } #endif #endif /* !Py_ERRCODE_H */ ================================================ FILE: thirdLibs/python3_8/include/eval.h ================================================ /* Interface to execute compiled code */ #ifndef Py_EVAL_H #define Py_EVAL_H #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(PyObject *) PyEval_EvalCode(PyObject *, PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int argc, PyObject *const *kwds, int kwdc, PyObject *const *defs, int defc, PyObject *kwdefs, PyObject *closure); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyEval_EvalCodeWithName( PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, Py_ssize_t argcount, PyObject *const *kwnames, PyObject *const *kwargs, Py_ssize_t kwcount, int kwstep, PyObject *const *defs, Py_ssize_t defcount, PyObject *kwdefs, PyObject *closure, PyObject *name, PyObject *qualname); PyAPI_FUNC(PyObject *) _PyEval_CallTracing(PyObject *func, PyObject *args); #endif #ifdef __cplusplus } #endif #endif /* !Py_EVAL_H */ ================================================ FILE: thirdLibs/python3_8/include/fileobject.h ================================================ /* File object interface (what's left of it -- see io.py) */ #ifndef Py_FILEOBJECT_H #define Py_FILEOBJECT_H #ifdef __cplusplus extern "C" { #endif #define PY_STDIOTEXTMODE "b" PyAPI_FUNC(PyObject *) PyFile_FromFd(int, const char *, const char *, int, const char *, const char *, const char *, int); PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int); PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int); PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *); PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *); /* The default encoding used by the platform file system APIs If non-NULL, this is different than the default encoding for strings */ PyAPI_DATA(const char *) Py_FileSystemDefaultEncoding; PyAPI_DATA(int) Py_HasFileSystemDefaultEncoding; /* A routine to check if a file descriptor can be select()-ed. */ #ifdef _MSC_VER /* On Windows, any socket fd can be select()-ed, no matter how high */ #define _PyIsSelectable_fd(FD) (1) #else #define _PyIsSelectable_fd(FD) ((unsigned int)(FD) < (unsigned int)FD_SETSIZE) #endif #ifndef Py_LIMITED_API # define Py_CPYTHON_FILEOBJECT_H # include "cpython/fileobject.h" # undef Py_CPYTHON_FILEOBJECT_H #endif #ifdef __cplusplus } #endif #endif /* !Py_FILEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/fileutils.h ================================================ #ifndef Py_FILEUTILS_H #define Py_FILEUTILS_H #ifdef __cplusplus extern "C" { #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyAPI_FUNC(wchar_t *) Py_DecodeLocale( const char *arg, size_t *size); PyAPI_FUNC(char*) Py_EncodeLocale( const wchar_t *text, size_t *error_pos); PyAPI_FUNC(char*) _Py_EncodeLocaleRaw( const wchar_t *text, size_t *error_pos); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03080000 typedef enum { _Py_ERROR_UNKNOWN=0, _Py_ERROR_STRICT, _Py_ERROR_SURROGATEESCAPE, _Py_ERROR_REPLACE, _Py_ERROR_IGNORE, _Py_ERROR_BACKSLASHREPLACE, _Py_ERROR_SURROGATEPASS, _Py_ERROR_XMLCHARREFREPLACE, _Py_ERROR_OTHER } _Py_error_handler; PyAPI_FUNC(_Py_error_handler) _Py_GetErrorHandler(const char *errors); PyAPI_FUNC(int) _Py_DecodeLocaleEx( const char *arg, wchar_t **wstr, size_t *wlen, const char **reason, int current_locale, _Py_error_handler errors); PyAPI_FUNC(int) _Py_EncodeLocaleEx( const wchar_t *text, char **str, size_t *error_pos, const char **reason, int current_locale, _Py_error_handler errors); #endif #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _Py_device_encoding(int); #if defined(MS_WINDOWS) || defined(__APPLE__) /* On Windows, the count parameter of read() is an int (bpo-9015, bpo-9611). On macOS 10.13, read() and write() with more than INT_MAX bytes fail with EINVAL (bpo-24658). */ # define _PY_READ_MAX INT_MAX # define _PY_WRITE_MAX INT_MAX #else /* write() should truncate the input to PY_SSIZE_T_MAX bytes, but it's safer to do it ourself to have a portable behaviour */ # define _PY_READ_MAX PY_SSIZE_T_MAX # define _PY_WRITE_MAX PY_SSIZE_T_MAX #endif #ifdef MS_WINDOWS struct _Py_stat_struct { unsigned long st_dev; uint64_t st_ino; unsigned short st_mode; int st_nlink; int st_uid; int st_gid; unsigned long st_rdev; __int64 st_size; time_t st_atime; int st_atime_nsec; time_t st_mtime; int st_mtime_nsec; time_t st_ctime; int st_ctime_nsec; unsigned long st_file_attributes; unsigned long st_reparse_tag; }; #else # define _Py_stat_struct stat #endif PyAPI_FUNC(int) _Py_fstat( int fd, struct _Py_stat_struct *status); PyAPI_FUNC(int) _Py_fstat_noraise( int fd, struct _Py_stat_struct *status); PyAPI_FUNC(int) _Py_stat( PyObject *path, struct stat *status); PyAPI_FUNC(int) _Py_open( const char *pathname, int flags); PyAPI_FUNC(int) _Py_open_noraise( const char *pathname, int flags); PyAPI_FUNC(FILE *) _Py_wfopen( const wchar_t *path, const wchar_t *mode); PyAPI_FUNC(FILE*) _Py_fopen( const char *pathname, const char *mode); PyAPI_FUNC(FILE*) _Py_fopen_obj( PyObject *path, const char *mode); PyAPI_FUNC(Py_ssize_t) _Py_read( int fd, void *buf, size_t count); PyAPI_FUNC(Py_ssize_t) _Py_write( int fd, const void *buf, size_t count); PyAPI_FUNC(Py_ssize_t) _Py_write_noraise( int fd, const void *buf, size_t count); #ifdef HAVE_READLINK PyAPI_FUNC(int) _Py_wreadlink( const wchar_t *path, wchar_t *buf, /* Number of characters of 'buf' buffer including the trailing NUL character */ size_t buflen); #endif #ifdef HAVE_REALPATH PyAPI_FUNC(wchar_t*) _Py_wrealpath( const wchar_t *path, wchar_t *resolved_path, /* Number of characters of 'resolved_path' buffer including the trailing NUL character */ size_t resolved_path_len); #endif PyAPI_FUNC(wchar_t*) _Py_wgetcwd( wchar_t *buf, /* Number of characters of 'buf' buffer including the trailing NUL character */ size_t buflen); PyAPI_FUNC(int) _Py_get_inheritable(int fd); PyAPI_FUNC(int) _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works); PyAPI_FUNC(int) _Py_set_inheritable_async_safe(int fd, int inheritable, int *atomic_flag_works); PyAPI_FUNC(int) _Py_dup(int fd); #ifndef MS_WINDOWS PyAPI_FUNC(int) _Py_get_blocking(int fd); PyAPI_FUNC(int) _Py_set_blocking(int fd, int blocking); #endif /* !MS_WINDOWS */ #endif /* Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_FILEUTILS_H */ ================================================ FILE: thirdLibs/python3_8/include/floatobject.h ================================================ /* Float object interface */ /* PyFloatObject represents a (double precision) floating point number. */ #ifndef Py_FLOATOBJECT_H #define Py_FLOATOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD double ob_fval; } PyFloatObject; #endif PyAPI_DATA(PyTypeObject) PyFloat_Type; #define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type) #define PyFloat_CheckExact(op) (Py_TYPE(op) == &PyFloat_Type) #ifdef Py_NAN #define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN) #endif #define Py_RETURN_INF(sign) do \ if (copysign(1., sign) == 1.) { \ return PyFloat_FromDouble(Py_HUGE_VAL); \ } else { \ return PyFloat_FromDouble(-Py_HUGE_VAL); \ } while(0) PyAPI_FUNC(double) PyFloat_GetMax(void); PyAPI_FUNC(double) PyFloat_GetMin(void); PyAPI_FUNC(PyObject *) PyFloat_GetInfo(void); /* Return Python float from string PyObject. */ PyAPI_FUNC(PyObject *) PyFloat_FromString(PyObject*); /* Return Python float from C double. */ PyAPI_FUNC(PyObject *) PyFloat_FromDouble(double); /* Extract C double from Python float. The macro version trades safety for speed. */ PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *); #ifndef Py_LIMITED_API #define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval) #endif #ifndef Py_LIMITED_API /* _PyFloat_{Pack,Unpack}{4,8} * * The struct and pickle (at least) modules need an efficient platform- * independent way to store floating-point values as byte strings. * The Pack routines produce a string from a C double, and the Unpack * routines produce a C double from such a string. The suffix (4 or 8) * specifies the number of bytes in the string. * * On platforms that appear to use (see _PyFloat_Init()) IEEE-754 formats * these functions work by copying bits. On other platforms, the formats the * 4- byte format is identical to the IEEE-754 single precision format, and * the 8-byte format to the IEEE-754 double precision format, although the * packing of INFs and NaNs (if such things exist on the platform) isn't * handled correctly, and attempting to unpack a string containing an IEEE * INF or NaN will raise an exception. * * On non-IEEE platforms with more precision, or larger dynamic range, than * 754 supports, not all values can be packed; on non-IEEE platforms with less * precision, or smaller dynamic range, not all values can be unpacked. What * happens in such cases is partly accidental (alas). */ /* The pack routines write 2, 4 or 8 bytes, starting at p. le is a bool * argument, true if you want the string in little-endian format (exponent * last, at p+1, p+3 or p+7), false if you want big-endian format (exponent * first, at p). * Return value: 0 if all is OK, -1 if error (and an exception is * set, most likely OverflowError). * There are two problems on non-IEEE platforms: * 1): What this does is undefined if x is a NaN or infinity. * 2): -0.0 and +0.0 produce the same string. */ PyAPI_FUNC(int) _PyFloat_Pack2(double x, unsigned char *p, int le); PyAPI_FUNC(int) _PyFloat_Pack4(double x, unsigned char *p, int le); PyAPI_FUNC(int) _PyFloat_Pack8(double x, unsigned char *p, int le); /* Needed for the old way for marshal to store a floating point number. Returns the string length copied into p, -1 on error. */ PyAPI_FUNC(int) _PyFloat_Repr(double x, char *p, size_t len); /* Used to get the important decimal digits of a double */ PyAPI_FUNC(int) _PyFloat_Digits(char *buf, double v, int *signum); PyAPI_FUNC(void) _PyFloat_DigitsInit(void); /* The unpack routines read 2, 4 or 8 bytes, starting at p. le is a bool * argument, true if the string is in little-endian format (exponent * last, at p+1, p+3 or p+7), false if big-endian (exponent first, at p). * Return value: The unpacked double. On error, this is -1.0 and * PyErr_Occurred() is true (and an exception is set, most likely * OverflowError). Note that on a non-IEEE platform this will refuse * to unpack a string that represents a NaN or infinity. */ PyAPI_FUNC(double) _PyFloat_Unpack2(const unsigned char *p, int le); PyAPI_FUNC(double) _PyFloat_Unpack4(const unsigned char *p, int le); PyAPI_FUNC(double) _PyFloat_Unpack8(const unsigned char *p, int le); /* free list api */ PyAPI_FUNC(int) PyFloat_ClearFreeList(void); PyAPI_FUNC(void) _PyFloat_DebugMallocStats(FILE* out); /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ PyAPI_FUNC(int) _PyFloat_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); #endif /* Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_FLOATOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/frameobject.h ================================================ /* Frame object interface */ #ifndef Py_LIMITED_API #ifndef Py_FRAMEOBJECT_H #define Py_FRAMEOBJECT_H #ifdef __cplusplus extern "C" { #endif typedef struct { int b_type; /* what kind of block this is */ int b_handler; /* where to jump to find handler */ int b_level; /* value stack level to pop to */ } PyTryBlock; typedef struct _frame { PyObject_VAR_HEAD struct _frame *f_back; /* previous frame, or NULL */ PyCodeObject *f_code; /* code segment */ PyObject *f_builtins; /* builtin symbol table (PyDictObject) */ PyObject *f_globals; /* global symbol table (PyDictObject) */ PyObject *f_locals; /* local symbol table (any mapping) */ PyObject **f_valuestack; /* points after the last local */ /* Next free slot in f_valuestack. Frame creation sets to f_valuestack. Frame evaluation usually NULLs it, but a frame that yields sets it to the current stack top. */ PyObject **f_stacktop; PyObject *f_trace; /* Trace function */ char f_trace_lines; /* Emit per-line trace events? */ char f_trace_opcodes; /* Emit per-opcode trace events? */ /* Borrowed reference to a generator, or NULL */ PyObject *f_gen; int f_lasti; /* Last instruction if called */ /* Call PyFrame_GetLineNumber() instead of reading this field directly. As of 2.3 f_lineno is only valid when tracing is active (i.e. when f_trace is set). At other times we use PyCode_Addr2Line to calculate the line from the current bytecode index. */ int f_lineno; /* Current line number */ int f_iblock; /* index in f_blockstack */ char f_executing; /* whether the frame is still executing */ PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */ PyObject *f_localsplus[1]; /* locals+stack, dynamically sized */ } PyFrameObject; /* Standard object interface */ PyAPI_DATA(PyTypeObject) PyFrame_Type; #define PyFrame_Check(op) (Py_TYPE(op) == &PyFrame_Type) PyAPI_FUNC(PyFrameObject *) PyFrame_New(PyThreadState *, PyCodeObject *, PyObject *, PyObject *); /* only internal use */ PyFrameObject* _PyFrame_New_NoTrack(PyThreadState *, PyCodeObject *, PyObject *, PyObject *); /* The rest of the interface is specific for frame objects */ /* Block management functions */ PyAPI_FUNC(void) PyFrame_BlockSetup(PyFrameObject *, int, int, int); PyAPI_FUNC(PyTryBlock *) PyFrame_BlockPop(PyFrameObject *); /* Extend the value stack */ PyAPI_FUNC(PyObject **) PyFrame_ExtendStack(PyFrameObject *, int, int); /* Conversions between "fast locals" and locals in dictionary */ PyAPI_FUNC(void) PyFrame_LocalsToFast(PyFrameObject *, int); PyAPI_FUNC(int) PyFrame_FastToLocalsWithError(PyFrameObject *f); PyAPI_FUNC(void) PyFrame_FastToLocals(PyFrameObject *); PyAPI_FUNC(int) PyFrame_ClearFreeList(void); PyAPI_FUNC(void) _PyFrame_DebugMallocStats(FILE *out); /* Return the line of code the frame is currently executing. */ PyAPI_FUNC(int) PyFrame_GetLineNumber(PyFrameObject *); #ifdef __cplusplus } #endif #endif /* !Py_FRAMEOBJECT_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/funcobject.h ================================================ /* Function object interface */ #ifndef Py_LIMITED_API #ifndef Py_FUNCOBJECT_H #define Py_FUNCOBJECT_H #ifdef __cplusplus extern "C" { #endif /* Function objects and code objects should not be confused with each other: * * Function objects are created by the execution of the 'def' statement. * They reference a code object in their __code__ attribute, which is a * purely syntactic object, i.e. nothing more than a compiled version of some * source code lines. There is one code object per source code "fragment", * but each code object can be referenced by zero or many function objects * depending only on how many times the 'def' statement in the source was * executed so far. */ typedef struct { PyObject_HEAD PyObject *func_code; /* A code object, the __code__ attribute */ PyObject *func_globals; /* A dictionary (other mappings won't do) */ PyObject *func_defaults; /* NULL or a tuple */ PyObject *func_kwdefaults; /* NULL or a dict */ PyObject *func_closure; /* NULL or a tuple of cell objects */ PyObject *func_doc; /* The __doc__ attribute, can be anything */ PyObject *func_name; /* The __name__ attribute, a string object */ PyObject *func_dict; /* The __dict__ attribute, a dict or NULL */ PyObject *func_weakreflist; /* List of weak references */ PyObject *func_module; /* The __module__ attribute, can be anything */ PyObject *func_annotations; /* Annotations, a dict or NULL */ PyObject *func_qualname; /* The qualified name */ vectorcallfunc vectorcall; /* Invariant: * func_closure contains the bindings for func_code->co_freevars, so * PyTuple_Size(func_closure) == PyCode_GetNumFree(func_code) * (func_closure may be NULL if PyCode_GetNumFree(func_code) == 0). */ } PyFunctionObject; PyAPI_DATA(PyTypeObject) PyFunction_Type; #define PyFunction_Check(op) (Py_TYPE(op) == &PyFunction_Type) PyAPI_FUNC(PyObject *) PyFunction_New(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyFunction_NewWithQualName(PyObject *, PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetCode(PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetGlobals(PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetModule(PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetDefaults(PyObject *); PyAPI_FUNC(int) PyFunction_SetDefaults(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetKwDefaults(PyObject *); PyAPI_FUNC(int) PyFunction_SetKwDefaults(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetClosure(PyObject *); PyAPI_FUNC(int) PyFunction_SetClosure(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyFunction_GetAnnotations(PyObject *); PyAPI_FUNC(int) PyFunction_SetAnnotations(PyObject *, PyObject *); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyFunction_FastCallDict( PyObject *func, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs); PyAPI_FUNC(PyObject *) _PyFunction_Vectorcall( PyObject *func, PyObject *const *stack, size_t nargsf, PyObject *kwnames); #endif /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PyFunction_GET_CODE(func) \ (((PyFunctionObject *)func) -> func_code) #define PyFunction_GET_GLOBALS(func) \ (((PyFunctionObject *)func) -> func_globals) #define PyFunction_GET_MODULE(func) \ (((PyFunctionObject *)func) -> func_module) #define PyFunction_GET_DEFAULTS(func) \ (((PyFunctionObject *)func) -> func_defaults) #define PyFunction_GET_KW_DEFAULTS(func) \ (((PyFunctionObject *)func) -> func_kwdefaults) #define PyFunction_GET_CLOSURE(func) \ (((PyFunctionObject *)func) -> func_closure) #define PyFunction_GET_ANNOTATIONS(func) \ (((PyFunctionObject *)func) -> func_annotations) /* The classmethod and staticmethod types lives here, too */ PyAPI_DATA(PyTypeObject) PyClassMethod_Type; PyAPI_DATA(PyTypeObject) PyStaticMethod_Type; PyAPI_FUNC(PyObject *) PyClassMethod_New(PyObject *); PyAPI_FUNC(PyObject *) PyStaticMethod_New(PyObject *); #ifdef __cplusplus } #endif #endif /* !Py_FUNCOBJECT_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/genobject.h ================================================ /* Generator object interface */ #ifndef Py_LIMITED_API #ifndef Py_GENOBJECT_H #define Py_GENOBJECT_H #ifdef __cplusplus extern "C" { #endif #include "pystate.h" /* _PyErr_StackItem */ struct _frame; /* Avoid including frameobject.h */ /* _PyGenObject_HEAD defines the initial segment of generator and coroutine objects. */ #define _PyGenObject_HEAD(prefix) \ PyObject_HEAD \ /* Note: gi_frame can be NULL if the generator is "finished" */ \ struct _frame *prefix##_frame; \ /* True if generator is being executed. */ \ char prefix##_running; \ /* The code object backing the generator */ \ PyObject *prefix##_code; \ /* List of weak reference. */ \ PyObject *prefix##_weakreflist; \ /* Name of the generator. */ \ PyObject *prefix##_name; \ /* Qualified name of the generator. */ \ PyObject *prefix##_qualname; \ _PyErr_StackItem prefix##_exc_state; typedef struct { /* The gi_ prefix is intended to remind of generator-iterator. */ _PyGenObject_HEAD(gi) } PyGenObject; PyAPI_DATA(PyTypeObject) PyGen_Type; #define PyGen_Check(op) PyObject_TypeCheck(op, &PyGen_Type) #define PyGen_CheckExact(op) (Py_TYPE(op) == &PyGen_Type) PyAPI_FUNC(PyObject *) PyGen_New(struct _frame *); PyAPI_FUNC(PyObject *) PyGen_NewWithQualName(struct _frame *, PyObject *name, PyObject *qualname); PyAPI_FUNC(int) PyGen_NeedsFinalizing(PyGenObject *); PyAPI_FUNC(int) _PyGen_SetStopIterationValue(PyObject *); PyAPI_FUNC(int) _PyGen_FetchStopIterationValue(PyObject **); PyAPI_FUNC(PyObject *) _PyGen_Send(PyGenObject *, PyObject *); PyObject *_PyGen_yf(PyGenObject *); PyAPI_FUNC(void) _PyGen_Finalize(PyObject *self); #ifndef Py_LIMITED_API typedef struct { _PyGenObject_HEAD(cr) PyObject *cr_origin; } PyCoroObject; PyAPI_DATA(PyTypeObject) PyCoro_Type; PyAPI_DATA(PyTypeObject) _PyCoroWrapper_Type; PyAPI_DATA(PyTypeObject) _PyAIterWrapper_Type; #define PyCoro_CheckExact(op) (Py_TYPE(op) == &PyCoro_Type) PyObject *_PyCoro_GetAwaitableIter(PyObject *o); PyAPI_FUNC(PyObject *) PyCoro_New(struct _frame *, PyObject *name, PyObject *qualname); /* Asynchronous Generators */ typedef struct { _PyGenObject_HEAD(ag) PyObject *ag_finalizer; /* Flag is set to 1 when hooks set up by sys.set_asyncgen_hooks were called on the generator, to avoid calling them more than once. */ int ag_hooks_inited; /* Flag is set to 1 when aclose() is called for the first time, or when a StopAsyncIteration exception is raised. */ int ag_closed; int ag_running_async; } PyAsyncGenObject; PyAPI_DATA(PyTypeObject) PyAsyncGen_Type; PyAPI_DATA(PyTypeObject) _PyAsyncGenASend_Type; PyAPI_DATA(PyTypeObject) _PyAsyncGenWrappedValue_Type; PyAPI_DATA(PyTypeObject) _PyAsyncGenAThrow_Type; PyAPI_FUNC(PyObject *) PyAsyncGen_New(struct _frame *, PyObject *name, PyObject *qualname); #define PyAsyncGen_CheckExact(op) (Py_TYPE(op) == &PyAsyncGen_Type) PyObject *_PyAsyncGenValueWrapperNew(PyObject *); int PyAsyncGen_ClearFreeLists(void); #endif #undef _PyGenObject_HEAD #ifdef __cplusplus } #endif #endif /* !Py_GENOBJECT_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/graminit.h ================================================ /* Generated by Parser/pgen */ #define single_input 256 #define file_input 257 #define eval_input 258 #define decorator 259 #define decorators 260 #define decorated 261 #define async_funcdef 262 #define funcdef 263 #define parameters 264 #define typedargslist 265 #define tfpdef 266 #define varargslist 267 #define vfpdef 268 #define stmt 269 #define simple_stmt 270 #define small_stmt 271 #define expr_stmt 272 #define annassign 273 #define testlist_star_expr 274 #define augassign 275 #define del_stmt 276 #define pass_stmt 277 #define flow_stmt 278 #define break_stmt 279 #define continue_stmt 280 #define return_stmt 281 #define yield_stmt 282 #define raise_stmt 283 #define import_stmt 284 #define import_name 285 #define import_from 286 #define import_as_name 287 #define dotted_as_name 288 #define import_as_names 289 #define dotted_as_names 290 #define dotted_name 291 #define global_stmt 292 #define nonlocal_stmt 293 #define assert_stmt 294 #define compound_stmt 295 #define async_stmt 296 #define if_stmt 297 #define while_stmt 298 #define for_stmt 299 #define try_stmt 300 #define with_stmt 301 #define with_item 302 #define except_clause 303 #define suite 304 #define namedexpr_test 305 #define test 306 #define test_nocond 307 #define lambdef 308 #define lambdef_nocond 309 #define or_test 310 #define and_test 311 #define not_test 312 #define comparison 313 #define comp_op 314 #define star_expr 315 #define expr 316 #define xor_expr 317 #define and_expr 318 #define shift_expr 319 #define arith_expr 320 #define term 321 #define factor 322 #define power 323 #define atom_expr 324 #define atom 325 #define testlist_comp 326 #define trailer 327 #define subscriptlist 328 #define subscript 329 #define sliceop 330 #define exprlist 331 #define testlist 332 #define dictorsetmaker 333 #define classdef 334 #define arglist 335 #define argument 336 #define comp_iter 337 #define sync_comp_for 338 #define comp_for 339 #define comp_if 340 #define encoding_decl 341 #define yield_expr 342 #define yield_arg 343 #define func_body_suite 344 #define func_type_input 345 #define func_type 346 #define typelist 347 ================================================ FILE: thirdLibs/python3_8/include/grammar.h ================================================ /* Grammar interface */ #ifndef Py_GRAMMAR_H #define Py_GRAMMAR_H #ifdef __cplusplus extern "C" { #endif #include "bitset.h" /* Sigh... */ /* A label of an arc */ typedef struct { int lb_type; const char *lb_str; } label; #define EMPTY 0 /* Label number 0 is by definition the empty label */ /* A list of labels */ typedef struct { int ll_nlabels; const label *ll_label; } labellist; /* An arc from one state to another */ typedef struct { short a_lbl; /* Label of this arc */ short a_arrow; /* State where this arc goes to */ } arc; /* A state in a DFA */ typedef struct { int s_narcs; const arc *s_arc; /* Array of arcs */ /* Optional accelerators */ int s_lower; /* Lowest label index */ int s_upper; /* Highest label index */ int *s_accel; /* Accelerator */ int s_accept; /* Nonzero for accepting state */ } state; /* A DFA */ typedef struct { int d_type; /* Non-terminal this represents */ char *d_name; /* For printing */ int d_nstates; state *d_state; /* Array of states */ bitset d_first; } dfa; /* A grammar */ typedef struct { int g_ndfas; const dfa *g_dfa; /* Array of DFAs */ const labellist g_ll; int g_start; /* Start symbol of the grammar */ int g_accel; /* Set if accelerators present */ } grammar; /* FUNCTIONS */ const dfa *PyGrammar_FindDFA(grammar *g, int type); const char *PyGrammar_LabelRepr(label *lb); void PyGrammar_AddAccelerators(grammar *g); void PyGrammar_RemoveAccelerators(grammar *); #ifdef __cplusplus } #endif #endif /* !Py_GRAMMAR_H */ ================================================ FILE: thirdLibs/python3_8/include/import.h ================================================ /* Module definition and import interface */ #ifndef Py_IMPORT_H #define Py_IMPORT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API PyMODINIT_FUNC PyInit__imp(void); #endif /* !Py_LIMITED_API */ PyAPI_FUNC(long) PyImport_GetMagicNumber(void); PyAPI_FUNC(const char *) PyImport_GetMagicTag(void); PyAPI_FUNC(PyObject *) PyImport_ExecCodeModule( const char *name, /* UTF-8 encoded string */ PyObject *co ); PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleEx( const char *name, /* UTF-8 encoded string */ PyObject *co, const char *pathname /* decoded from the filesystem encoding */ ); PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleWithPathnames( const char *name, /* UTF-8 encoded string */ PyObject *co, const char *pathname, /* decoded from the filesystem encoding */ const char *cpathname /* decoded from the filesystem encoding */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleObject( PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname ); #endif PyAPI_FUNC(PyObject *) PyImport_GetModuleDict(void); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000 PyAPI_FUNC(PyObject *) PyImport_GetModule(PyObject *name); #endif #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyImport_IsInitialized(PyInterpreterState *); PyAPI_FUNC(PyObject *) _PyImport_GetModuleId(struct _Py_Identifier *name); PyAPI_FUNC(PyObject *) _PyImport_AddModuleObject(PyObject *name, PyObject *modules); PyAPI_FUNC(int) _PyImport_SetModule(PyObject *name, PyObject *module); PyAPI_FUNC(int) _PyImport_SetModuleString(const char *name, PyObject* module); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject *) PyImport_AddModuleObject( PyObject *name ); #endif PyAPI_FUNC(PyObject *) PyImport_AddModule( const char *name /* UTF-8 encoded string */ ); PyAPI_FUNC(PyObject *) PyImport_ImportModule( const char *name /* UTF-8 encoded string */ ); PyAPI_FUNC(PyObject *) PyImport_ImportModuleNoBlock( const char *name /* UTF-8 encoded string */ ); PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevel( const char *name, /* UTF-8 encoded string */ PyObject *globals, PyObject *locals, PyObject *fromlist, int level ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevelObject( PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level ); #endif #define PyImport_ImportModuleEx(n, g, l, f) \ PyImport_ImportModuleLevel(n, g, l, f, 0) PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path); PyAPI_FUNC(PyObject *) PyImport_Import(PyObject *name); PyAPI_FUNC(PyObject *) PyImport_ReloadModule(PyObject *m); PyAPI_FUNC(void) PyImport_Cleanup(void); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(int) PyImport_ImportFrozenModuleObject( PyObject *name ); #endif PyAPI_FUNC(int) PyImport_ImportFrozenModule( const char *name /* UTF-8 encoded string */ ); #ifndef Py_LIMITED_API PyAPI_FUNC(void) _PyImport_AcquireLock(void); PyAPI_FUNC(int) _PyImport_ReleaseLock(void); PyAPI_FUNC(void) _PyImport_ReInitLock(void); PyAPI_FUNC(PyObject *) _PyImport_FindBuiltin( const char *name, /* UTF-8 encoded string */ PyObject *modules ); PyAPI_FUNC(PyObject *) _PyImport_FindExtensionObject(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) _PyImport_FindExtensionObjectEx(PyObject *, PyObject *, PyObject *); PyAPI_FUNC(int) _PyImport_FixupBuiltin( PyObject *mod, const char *name, /* UTF-8 encoded string */ PyObject *modules ); PyAPI_FUNC(int) _PyImport_FixupExtensionObject(PyObject*, PyObject *, PyObject *, PyObject *); struct _inittab { const char *name; /* ASCII encoded string */ PyObject* (*initfunc)(void); }; PyAPI_DATA(struct _inittab *) PyImport_Inittab; PyAPI_FUNC(int) PyImport_ExtendInittab(struct _inittab *newtab); #endif /* Py_LIMITED_API */ PyAPI_DATA(PyTypeObject) PyNullImporter_Type; PyAPI_FUNC(int) PyImport_AppendInittab( const char *name, /* ASCII encoded string */ PyObject* (*initfunc)(void) ); #ifndef Py_LIMITED_API struct _frozen { const char *name; /* ASCII encoded string */ const unsigned char *code; int size; }; /* Embedding apps may change this pointer to point to their favorite collection of frozen modules: */ PyAPI_DATA(const struct _frozen *) PyImport_FrozenModules; #endif #ifdef __cplusplus } #endif #endif /* !Py_IMPORT_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_accu.h ================================================ #ifndef Py_LIMITED_API #ifndef Py_INTERNAL_ACCU_H #define Py_INTERNAL_ACCU_H #ifdef __cplusplus extern "C" { #endif /*** This is a private API for use by the interpreter and the stdlib. *** Its definition may be changed or removed at any moment. ***/ #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif /* * A two-level accumulator of unicode objects that avoids both the overhead * of keeping a huge number of small separate objects, and the quadratic * behaviour of using a naive repeated concatenation scheme. */ #undef small /* defined by some Windows headers */ typedef struct { PyObject *large; /* A list of previously accumulated large strings */ PyObject *small; /* Pending small strings */ } _PyAccu; PyAPI_FUNC(int) _PyAccu_Init(_PyAccu *acc); PyAPI_FUNC(int) _PyAccu_Accumulate(_PyAccu *acc, PyObject *unicode); PyAPI_FUNC(PyObject *) _PyAccu_FinishAsList(_PyAccu *acc); PyAPI_FUNC(PyObject *) _PyAccu_Finish(_PyAccu *acc); PyAPI_FUNC(void) _PyAccu_Destroy(_PyAccu *acc); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_ACCU_H */ #endif /* !Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_atomic.h ================================================ #ifndef Py_ATOMIC_H #define Py_ATOMIC_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "dynamic_annotations.h" #include "pyconfig.h" #if defined(HAVE_STD_ATOMIC) #include #endif #if defined(_MSC_VER) #include #if defined(_M_IX86) || defined(_M_X64) # include #endif #endif /* This is modeled after the atomics interface from C1x, according to * the draft at * http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1425.pdf. * Operations and types are named the same except with a _Py_ prefix * and have the same semantics. * * Beware, the implementations here are deep magic. */ #if defined(HAVE_STD_ATOMIC) typedef enum _Py_memory_order { _Py_memory_order_relaxed = memory_order_relaxed, _Py_memory_order_acquire = memory_order_acquire, _Py_memory_order_release = memory_order_release, _Py_memory_order_acq_rel = memory_order_acq_rel, _Py_memory_order_seq_cst = memory_order_seq_cst } _Py_memory_order; typedef struct _Py_atomic_address { atomic_uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { atomic_int _value; } _Py_atomic_int; #define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \ atomic_signal_fence(ORDER) #define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \ atomic_thread_fence(ORDER) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ atomic_store_explicit(&((ATOMIC_VAL)->_value), NEW_VAL, ORDER) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ atomic_load_explicit(&((ATOMIC_VAL)->_value), ORDER) /* Use builtin atomic operations in GCC >= 4.7 */ #elif defined(HAVE_BUILTIN_ATOMIC) typedef enum _Py_memory_order { _Py_memory_order_relaxed = __ATOMIC_RELAXED, _Py_memory_order_acquire = __ATOMIC_ACQUIRE, _Py_memory_order_release = __ATOMIC_RELEASE, _Py_memory_order_acq_rel = __ATOMIC_ACQ_REL, _Py_memory_order_seq_cst = __ATOMIC_SEQ_CST } _Py_memory_order; typedef struct _Py_atomic_address { uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { int _value; } _Py_atomic_int; #define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \ __atomic_signal_fence(ORDER) #define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \ __atomic_thread_fence(ORDER) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ (assert((ORDER) == __ATOMIC_RELAXED \ || (ORDER) == __ATOMIC_SEQ_CST \ || (ORDER) == __ATOMIC_RELEASE), \ __atomic_store_n(&((ATOMIC_VAL)->_value), NEW_VAL, ORDER)) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ (assert((ORDER) == __ATOMIC_RELAXED \ || (ORDER) == __ATOMIC_SEQ_CST \ || (ORDER) == __ATOMIC_ACQUIRE \ || (ORDER) == __ATOMIC_CONSUME), \ __atomic_load_n(&((ATOMIC_VAL)->_value), ORDER)) /* Only support GCC (for expression statements) and x86 (for simple * atomic semantics) and MSVC x86/x64/ARM */ #elif defined(__GNUC__) && (defined(__i386__) || defined(__amd64)) typedef enum _Py_memory_order { _Py_memory_order_relaxed, _Py_memory_order_acquire, _Py_memory_order_release, _Py_memory_order_acq_rel, _Py_memory_order_seq_cst } _Py_memory_order; typedef struct _Py_atomic_address { uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { int _value; } _Py_atomic_int; static __inline__ void _Py_atomic_signal_fence(_Py_memory_order order) { if (order != _Py_memory_order_relaxed) __asm__ volatile("":::"memory"); } static __inline__ void _Py_atomic_thread_fence(_Py_memory_order order) { if (order != _Py_memory_order_relaxed) __asm__ volatile("mfence":::"memory"); } /* Tell the race checker about this operation's effects. */ static __inline__ void _Py_ANNOTATE_MEMORY_ORDER(const volatile void *address, _Py_memory_order order) { (void)address; /* shut up -Wunused-parameter */ switch(order) { case _Py_memory_order_release: case _Py_memory_order_acq_rel: case _Py_memory_order_seq_cst: _Py_ANNOTATE_HAPPENS_BEFORE(address); break; case _Py_memory_order_relaxed: case _Py_memory_order_acquire: break; } switch(order) { case _Py_memory_order_acquire: case _Py_memory_order_acq_rel: case _Py_memory_order_seq_cst: _Py_ANNOTATE_HAPPENS_AFTER(address); break; case _Py_memory_order_relaxed: case _Py_memory_order_release: break; } } #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ __extension__ ({ \ __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \ __typeof__(atomic_val->_value) new_val = NEW_VAL;\ volatile __typeof__(new_val) *volatile_data = &atomic_val->_value; \ _Py_memory_order order = ORDER; \ _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \ \ /* Perform the operation. */ \ _Py_ANNOTATE_IGNORE_WRITES_BEGIN(); \ switch(order) { \ case _Py_memory_order_release: \ _Py_atomic_signal_fence(_Py_memory_order_release); \ /* fallthrough */ \ case _Py_memory_order_relaxed: \ *volatile_data = new_val; \ break; \ \ case _Py_memory_order_acquire: \ case _Py_memory_order_acq_rel: \ case _Py_memory_order_seq_cst: \ __asm__ volatile("xchg %0, %1" \ : "+r"(new_val) \ : "m"(atomic_val->_value) \ : "memory"); \ break; \ } \ _Py_ANNOTATE_IGNORE_WRITES_END(); \ }) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ __extension__ ({ \ __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \ __typeof__(atomic_val->_value) result; \ volatile __typeof__(result) *volatile_data = &atomic_val->_value; \ _Py_memory_order order = ORDER; \ _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \ \ /* Perform the operation. */ \ _Py_ANNOTATE_IGNORE_READS_BEGIN(); \ switch(order) { \ case _Py_memory_order_release: \ case _Py_memory_order_acq_rel: \ case _Py_memory_order_seq_cst: \ /* Loads on x86 are not releases by default, so need a */ \ /* thread fence. */ \ _Py_atomic_thread_fence(_Py_memory_order_release); \ break; \ default: \ /* No fence */ \ break; \ } \ result = *volatile_data; \ switch(order) { \ case _Py_memory_order_acquire: \ case _Py_memory_order_acq_rel: \ case _Py_memory_order_seq_cst: \ /* Loads on x86 are automatically acquire operations so */ \ /* can get by with just a compiler fence. */ \ _Py_atomic_signal_fence(_Py_memory_order_acquire); \ break; \ default: \ /* No fence */ \ break; \ } \ _Py_ANNOTATE_IGNORE_READS_END(); \ result; \ }) #elif defined(_MSC_VER) /* _Interlocked* functions provide a full memory barrier and are therefore enough for acq_rel and seq_cst. If the HLE variants aren't available in hardware they will fall back to a full memory barrier as well. This might affect performance but likely only in some very specific and hard to meassure scenario. */ #if defined(_M_IX86) || defined(_M_X64) typedef enum _Py_memory_order { _Py_memory_order_relaxed, _Py_memory_order_acquire, _Py_memory_order_release, _Py_memory_order_acq_rel, _Py_memory_order_seq_cst } _Py_memory_order; typedef struct _Py_atomic_address { volatile uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { volatile int _value; } _Py_atomic_int; #if defined(_M_X64) #define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) \ switch (ORDER) { \ case _Py_memory_order_acquire: \ _InterlockedExchange64_HLEAcquire((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \ break; \ case _Py_memory_order_release: \ _InterlockedExchange64_HLERelease((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \ break; \ default: \ _InterlockedExchange64((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)(NEW_VAL)); \ break; \ } #else #define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) ((void)0); #endif #define _Py_atomic_store_32bit(ATOMIC_VAL, NEW_VAL, ORDER) \ switch (ORDER) { \ case _Py_memory_order_acquire: \ _InterlockedExchange_HLEAcquire((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \ break; \ case _Py_memory_order_release: \ _InterlockedExchange_HLERelease((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \ break; \ default: \ _InterlockedExchange((volatile long*)&((ATOMIC_VAL)->_value), (int)(NEW_VAL)); \ break; \ } #if defined(_M_X64) /* This has to be an intptr_t for now. gil_created() uses -1 as a sentinel value, if this returns a uintptr_t it will do an unsigned compare and crash */ inline intptr_t _Py_atomic_load_64bit_impl(volatile uintptr_t* value, int order) { __int64 old; switch (order) { case _Py_memory_order_acquire: { do { old = *value; } while(_InterlockedCompareExchange64_HLEAcquire((volatile __int64*)value, old, old) != old); break; } case _Py_memory_order_release: { do { old = *value; } while(_InterlockedCompareExchange64_HLERelease((volatile __int64*)value, old, old) != old); break; } case _Py_memory_order_relaxed: old = *value; break; default: { do { old = *value; } while(_InterlockedCompareExchange64((volatile __int64*)value, old, old) != old); break; } } return old; } #define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) \ _Py_atomic_load_64bit_impl((volatile uintptr_t*)&((ATOMIC_VAL)->_value), (ORDER)) #else #define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) ((ATOMIC_VAL)->_value) #endif inline int _Py_atomic_load_32bit_impl(volatile int* value, int order) { long old; switch (order) { case _Py_memory_order_acquire: { do { old = *value; } while(_InterlockedCompareExchange_HLEAcquire((volatile long*)value, old, old) != old); break; } case _Py_memory_order_release: { do { old = *value; } while(_InterlockedCompareExchange_HLERelease((volatile long*)value, old, old) != old); break; } case _Py_memory_order_relaxed: old = *value; break; default: { do { old = *value; } while(_InterlockedCompareExchange((volatile long*)value, old, old) != old); break; } } return old; } #define _Py_atomic_load_32bit(ATOMIC_VAL, ORDER) \ _Py_atomic_load_32bit_impl((volatile int*)&((ATOMIC_VAL)->_value), (ORDER)) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ if (sizeof((ATOMIC_VAL)->_value) == 8) { \ _Py_atomic_store_64bit((ATOMIC_VAL), NEW_VAL, ORDER) } else { \ _Py_atomic_store_32bit((ATOMIC_VAL), NEW_VAL, ORDER) } #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ ( \ sizeof((ATOMIC_VAL)->_value) == 8 ? \ _Py_atomic_load_64bit((ATOMIC_VAL), ORDER) : \ _Py_atomic_load_32bit((ATOMIC_VAL), ORDER) \ ) #elif defined(_M_ARM) || defined(_M_ARM64) typedef enum _Py_memory_order { _Py_memory_order_relaxed, _Py_memory_order_acquire, _Py_memory_order_release, _Py_memory_order_acq_rel, _Py_memory_order_seq_cst } _Py_memory_order; typedef struct _Py_atomic_address { volatile uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { volatile int _value; } _Py_atomic_int; #if defined(_M_ARM64) #define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) \ switch (ORDER) { \ case _Py_memory_order_acquire: \ _InterlockedExchange64_acq((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \ break; \ case _Py_memory_order_release: \ _InterlockedExchange64_rel((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \ break; \ default: \ _InterlockedExchange64((__int64 volatile*)&((ATOMIC_VAL)->_value), (__int64)NEW_VAL); \ break; \ } #else #define _Py_atomic_store_64bit(ATOMIC_VAL, NEW_VAL, ORDER) ((void)0); #endif #define _Py_atomic_store_32bit(ATOMIC_VAL, NEW_VAL, ORDER) \ switch (ORDER) { \ case _Py_memory_order_acquire: \ _InterlockedExchange_acq((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \ break; \ case _Py_memory_order_release: \ _InterlockedExchange_rel((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \ break; \ default: \ _InterlockedExchange((volatile long*)&((ATOMIC_VAL)->_value), (int)NEW_VAL); \ break; \ } #if defined(_M_ARM64) /* This has to be an intptr_t for now. gil_created() uses -1 as a sentinel value, if this returns a uintptr_t it will do an unsigned compare and crash */ inline intptr_t _Py_atomic_load_64bit_impl(volatile uintptr_t* value, int order) { uintptr_t old; switch (order) { case _Py_memory_order_acquire: { do { old = *value; } while(_InterlockedCompareExchange64_acq(value, old, old) != old); break; } case _Py_memory_order_release: { do { old = *value; } while(_InterlockedCompareExchange64_rel(value, old, old) != old); break; } case _Py_memory_order_relaxed: old = *value; break; default: { do { old = *value; } while(_InterlockedCompareExchange64(value, old, old) != old); break; } } return old; } #define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) \ _Py_atomic_load_64bit_impl((volatile uintptr_t*)&((ATOMIC_VAL)->_value), (ORDER)) #else #define _Py_atomic_load_64bit(ATOMIC_VAL, ORDER) ((ATOMIC_VAL)->_value) #endif inline int _Py_atomic_load_32bit_impl(volatile int* value, int order) { int old; switch (order) { case _Py_memory_order_acquire: { do { old = *value; } while(_InterlockedCompareExchange_acq(value, old, old) != old); break; } case _Py_memory_order_release: { do { old = *value; } while(_InterlockedCompareExchange_rel(value, old, old) != old); break; } case _Py_memory_order_relaxed: old = *value; break; default: { do { old = *value; } while(_InterlockedCompareExchange(value, old, old) != old); break; } } return old; } #define _Py_atomic_load_32bit(ATOMIC_VAL, ORDER) \ _Py_atomic_load_32bit_impl((volatile int*)&((ATOMIC_VAL)->_value), (ORDER)) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ if (sizeof((ATOMIC_VAL)->_value) == 8) { \ _Py_atomic_store_64bit((ATOMIC_VAL), (NEW_VAL), (ORDER)) } else { \ _Py_atomic_store_32bit((ATOMIC_VAL), (NEW_VAL), (ORDER)) } #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ ( \ sizeof((ATOMIC_VAL)->_value) == 8 ? \ _Py_atomic_load_64bit((ATOMIC_VAL), (ORDER)) : \ _Py_atomic_load_32bit((ATOMIC_VAL), (ORDER)) \ ) #endif #else /* !gcc x86 !_msc_ver */ typedef enum _Py_memory_order { _Py_memory_order_relaxed, _Py_memory_order_acquire, _Py_memory_order_release, _Py_memory_order_acq_rel, _Py_memory_order_seq_cst } _Py_memory_order; typedef struct _Py_atomic_address { uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { int _value; } _Py_atomic_int; /* Fall back to other compilers and processors by assuming that simple volatile accesses are atomic. This is false, so people should port this. */ #define _Py_atomic_signal_fence(/*memory_order*/ ORDER) ((void)0) #define _Py_atomic_thread_fence(/*memory_order*/ ORDER) ((void)0) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ ((ATOMIC_VAL)->_value = NEW_VAL) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ ((ATOMIC_VAL)->_value) #endif /* Standardized shortcuts. */ #define _Py_atomic_store(ATOMIC_VAL, NEW_VAL) \ _Py_atomic_store_explicit((ATOMIC_VAL), (NEW_VAL), _Py_memory_order_seq_cst) #define _Py_atomic_load(ATOMIC_VAL) \ _Py_atomic_load_explicit((ATOMIC_VAL), _Py_memory_order_seq_cst) /* Python-local extensions */ #define _Py_atomic_store_relaxed(ATOMIC_VAL, NEW_VAL) \ _Py_atomic_store_explicit((ATOMIC_VAL), (NEW_VAL), _Py_memory_order_relaxed) #define _Py_atomic_load_relaxed(ATOMIC_VAL) \ _Py_atomic_load_explicit((ATOMIC_VAL), _Py_memory_order_relaxed) #ifdef __cplusplus } #endif #endif /* Py_ATOMIC_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_ceval.h ================================================ #ifndef Py_INTERNAL_CEVAL_H #define Py_INTERNAL_CEVAL_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "pycore_atomic.h" #include "pycore_pystate.h" #include "pythread.h" PyAPI_FUNC(void) _Py_FinishPendingCalls(_PyRuntimeState *runtime); PyAPI_FUNC(void) _PyEval_Initialize(struct _ceval_runtime_state *); PyAPI_FUNC(void) _PyEval_FiniThreads( struct _ceval_runtime_state *ceval); PyAPI_FUNC(void) _PyEval_SignalReceived( struct _ceval_runtime_state *ceval); PyAPI_FUNC(int) _PyEval_AddPendingCall( PyThreadState *tstate, struct _ceval_runtime_state *ceval, int (*func)(void *), void *arg); PyAPI_FUNC(void) _PyEval_SignalAsyncExc( struct _ceval_runtime_state *ceval); PyAPI_FUNC(void) _PyEval_ReInitThreads( _PyRuntimeState *runtime); /* Private function */ void _PyEval_Fini(void); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_CEVAL_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_code.h ================================================ #ifndef Py_INTERNAL_CODE_H #define Py_INTERNAL_CODE_H #ifdef __cplusplus extern "C" { #endif typedef struct { PyObject *ptr; /* Cached pointer (borrowed reference) */ uint64_t globals_ver; /* ma_version of global dict */ uint64_t builtins_ver; /* ma_version of builtin dict */ } _PyOpcache_LoadGlobal; struct _PyOpcache { union { _PyOpcache_LoadGlobal lg; } u; char optimized; }; /* Private API */ int _PyCode_InitOpcache(PyCodeObject *co); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_CODE_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_condvar.h ================================================ #ifndef Py_INTERNAL_CONDVAR_H #define Py_INTERNAL_CONDVAR_H #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #ifndef _POSIX_THREADS /* This means pthreads are not implemented in libc headers, hence the macro not present in unistd.h. But they still can be implemented as an external library (e.g. gnu pth in pthread emulation) */ # ifdef HAVE_PTHREAD_H # include /* _POSIX_THREADS */ # endif #endif #ifdef _POSIX_THREADS /* * POSIX support */ #define Py_HAVE_CONDVAR #include #define PyMUTEX_T pthread_mutex_t #define PyCOND_T pthread_cond_t #elif defined(NT_THREADS) /* * Windows (XP, 2003 server and later, as well as (hopefully) CE) support * * Emulated condition variables ones that work with XP and later, plus * example native support on VISTA and onwards. */ #define Py_HAVE_CONDVAR /* include windows if it hasn't been done before */ #define WIN32_LEAN_AND_MEAN #include /* options */ /* non-emulated condition variables are provided for those that want * to target Windows Vista. Modify this macro to enable them. */ #ifndef _PY_EMULATED_WIN_CV #define _PY_EMULATED_WIN_CV 1 /* use emulated condition variables */ #endif /* fall back to emulation if not targeting Vista */ #if !defined NTDDI_VISTA || NTDDI_VERSION < NTDDI_VISTA #undef _PY_EMULATED_WIN_CV #define _PY_EMULATED_WIN_CV 1 #endif #if _PY_EMULATED_WIN_CV typedef CRITICAL_SECTION PyMUTEX_T; /* The ConditionVariable object. From XP onwards it is easily emulated with a Semaphore. Semaphores are available on Windows XP (2003 server) and later. We use a Semaphore rather than an auto-reset event, because although an auto-resent event might appear to solve the lost-wakeup bug (race condition between releasing the outer lock and waiting) because it maintains state even though a wait hasn't happened, there is still a lost wakeup problem if more than one thread are interrupted in the critical place. A semaphore solves that, because its state is counted, not Boolean. Because it is ok to signal a condition variable with no one waiting, we need to keep track of the number of waiting threads. Otherwise, the semaphore's state could rise without bound. This also helps reduce the number of "spurious wakeups" that would otherwise happen. */ typedef struct _PyCOND_T { HANDLE sem; int waiting; /* to allow PyCOND_SIGNAL to be a no-op */ } PyCOND_T; #else /* !_PY_EMULATED_WIN_CV */ /* Use native Win7 primitives if build target is Win7 or higher */ /* SRWLOCK is faster and better than CriticalSection */ typedef SRWLOCK PyMUTEX_T; typedef CONDITION_VARIABLE PyCOND_T; #endif /* _PY_EMULATED_WIN_CV */ #endif /* _POSIX_THREADS, NT_THREADS */ #endif /* Py_INTERNAL_CONDVAR_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_context.h ================================================ #ifndef Py_INTERNAL_CONTEXT_H #define Py_INTERNAL_CONTEXT_H #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "pycore_hamt.h" struct _pycontextobject { PyObject_HEAD PyContext *ctx_prev; PyHamtObject *ctx_vars; PyObject *ctx_weakreflist; int ctx_entered; }; struct _pycontextvarobject { PyObject_HEAD PyObject *var_name; PyObject *var_default; PyObject *var_cached; uint64_t var_cached_tsid; uint64_t var_cached_tsver; Py_hash_t var_hash; }; struct _pycontexttokenobject { PyObject_HEAD PyContext *tok_ctx; PyContextVar *tok_var; PyObject *tok_oldval; int tok_used; }; int _PyContext_Init(void); void _PyContext_Fini(void); #endif /* !Py_INTERNAL_CONTEXT_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_fileutils.h ================================================ #ifndef Py_INTERNAL_FILEUTILS_H #define Py_INTERNAL_FILEUTILS_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "Py_BUILD_CORE must be defined to include this header" #endif #include /* struct lconv */ PyAPI_DATA(int) _Py_HasFileSystemDefaultEncodeErrors; PyAPI_FUNC(int) _Py_DecodeUTF8Ex( const char *arg, Py_ssize_t arglen, wchar_t **wstr, size_t *wlen, const char **reason, _Py_error_handler errors); PyAPI_FUNC(int) _Py_EncodeUTF8Ex( const wchar_t *text, char **str, size_t *error_pos, const char **reason, int raw_malloc, _Py_error_handler errors); PyAPI_FUNC(wchar_t*) _Py_DecodeUTF8_surrogateescape( const char *arg, Py_ssize_t arglen, size_t *wlen); PyAPI_FUNC(int) _Py_GetForceASCII(void); /* Reset "force ASCII" mode (if it was initialized). This function should be called when Python changes the LC_CTYPE locale, so the "force ASCII" mode can be detected again on the new locale encoding. */ PyAPI_FUNC(void) _Py_ResetForceASCII(void); PyAPI_FUNC(int) _Py_GetLocaleconvNumeric( struct lconv *lc, PyObject **decimal_point, PyObject **thousands_sep); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_FILEUTILS_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_getopt.h ================================================ #ifndef Py_INTERNAL_PYGETOPT_H #define Py_INTERNAL_PYGETOPT_H #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif extern int _PyOS_opterr; extern Py_ssize_t _PyOS_optind; extern const wchar_t *_PyOS_optarg; extern void _PyOS_ResetGetOpt(void); typedef struct { const wchar_t *name; int has_arg; int val; } _PyOS_LongOption; extern int _PyOS_GetOpt(Py_ssize_t argc, wchar_t * const *argv, int *longindex); #endif /* !Py_INTERNAL_PYGETOPT_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_gil.h ================================================ #ifndef Py_INTERNAL_GIL_H #define Py_INTERNAL_GIL_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "pycore_condvar.h" #include "pycore_atomic.h" #ifndef Py_HAVE_CONDVAR # error You need either a POSIX-compatible or a Windows system! #endif /* Enable if you want to force the switching of threads at least every `interval`. */ #undef FORCE_SWITCHING #define FORCE_SWITCHING struct _gil_runtime_state { /* microseconds (the Python API uses seconds, though) */ unsigned long interval; /* Last PyThreadState holding / having held the GIL. This helps us know whether anyone else was scheduled after we dropped the GIL. */ _Py_atomic_address last_holder; /* Whether the GIL is already taken (-1 if uninitialized). This is atomic because it can be read without any lock taken in ceval.c. */ _Py_atomic_int locked; /* Number of GIL switches since the beginning. */ unsigned long switch_number; /* This condition variable allows one or several threads to wait until the GIL is released. In addition, the mutex also protects the above variables. */ PyCOND_T cond; PyMUTEX_T mutex; #ifdef FORCE_SWITCHING /* This condition variable helps the GIL-releasing thread wait for a GIL-awaiting thread to be scheduled and take the GIL. */ PyCOND_T switch_cond; PyMUTEX_T switch_mutex; #endif }; #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_GIL_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_hamt.h ================================================ #ifndef Py_INTERNAL_HAMT_H #define Py_INTERNAL_HAMT_H #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #define _Py_HAMT_MAX_TREE_DEPTH 7 #define PyHamt_Check(o) (Py_TYPE(o) == &_PyHamt_Type) /* Abstract tree node. */ typedef struct { PyObject_HEAD } PyHamtNode; /* An HAMT immutable mapping collection. */ typedef struct { PyObject_HEAD PyHamtNode *h_root; PyObject *h_weakreflist; Py_ssize_t h_count; } PyHamtObject; /* A struct to hold the state of depth-first traverse of the tree. HAMT is an immutable collection. Iterators will hold a strong reference to it, and every node in the HAMT has strong references to its children. So for iterators, we can implement zero allocations and zero reference inc/dec depth-first iteration. - i_nodes: an array of seven pointers to tree nodes - i_level: the current node in i_nodes - i_pos: an array of positions within nodes in i_nodes. */ typedef struct { PyHamtNode *i_nodes[_Py_HAMT_MAX_TREE_DEPTH]; Py_ssize_t i_pos[_Py_HAMT_MAX_TREE_DEPTH]; int8_t i_level; } PyHamtIteratorState; /* Base iterator object. Contains the iteration state, a pointer to the HAMT tree, and a pointer to the 'yield function'. The latter is a simple function that returns a key/value tuple for the 'Items' iterator, just a key for the 'Keys' iterator, and a value for the 'Values' iterator. */ typedef struct { PyObject_HEAD PyHamtObject *hi_obj; PyHamtIteratorState hi_iter; binaryfunc hi_yield; } PyHamtIterator; PyAPI_DATA(PyTypeObject) _PyHamt_Type; PyAPI_DATA(PyTypeObject) _PyHamt_ArrayNode_Type; PyAPI_DATA(PyTypeObject) _PyHamt_BitmapNode_Type; PyAPI_DATA(PyTypeObject) _PyHamt_CollisionNode_Type; PyAPI_DATA(PyTypeObject) _PyHamtKeys_Type; PyAPI_DATA(PyTypeObject) _PyHamtValues_Type; PyAPI_DATA(PyTypeObject) _PyHamtItems_Type; /* Create a new HAMT immutable mapping. */ PyHamtObject * _PyHamt_New(void); /* Return a new collection based on "o", but with an additional key/val pair. */ PyHamtObject * _PyHamt_Assoc(PyHamtObject *o, PyObject *key, PyObject *val); /* Return a new collection based on "o", but without "key". */ PyHamtObject * _PyHamt_Without(PyHamtObject *o, PyObject *key); /* Find "key" in the "o" collection. Return: - -1: An error occurred. - 0: "key" wasn't found in "o". - 1: "key" is in "o"; "*val" is set to its value (a borrowed ref). */ int _PyHamt_Find(PyHamtObject *o, PyObject *key, PyObject **val); /* Check if "v" is equal to "w". Return: - 0: v != w - 1: v == w - -1: An error occurred. */ int _PyHamt_Eq(PyHamtObject *v, PyHamtObject *w); /* Return the size of "o"; equivalent of "len(o)". */ Py_ssize_t _PyHamt_Len(PyHamtObject *o); /* Return a Keys iterator over "o". */ PyObject * _PyHamt_NewIterKeys(PyHamtObject *o); /* Return a Values iterator over "o". */ PyObject * _PyHamt_NewIterValues(PyHamtObject *o); /* Return a Items iterator over "o". */ PyObject * _PyHamt_NewIterItems(PyHamtObject *o); int _PyHamt_Init(void); void _PyHamt_Fini(void); #endif /* !Py_INTERNAL_HAMT_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_initconfig.h ================================================ #ifndef Py_INTERNAL_CORECONFIG_H #define Py_INTERNAL_CORECONFIG_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "pycore_pystate.h" /* _PyRuntimeState */ /* --- PyStatus ----------------------------------------------- */ /* Almost all errors causing Python initialization to fail */ #ifdef _MSC_VER /* Visual Studio 2015 doesn't implement C99 __func__ in C */ # define _PyStatus_GET_FUNC() __FUNCTION__ #else # define _PyStatus_GET_FUNC() __func__ #endif #define _PyStatus_OK() \ (PyStatus){._type = _PyStatus_TYPE_OK,} /* other fields are set to 0 */ #define _PyStatus_ERR(ERR_MSG) \ (PyStatus){ \ ._type = _PyStatus_TYPE_ERROR, \ .func = _PyStatus_GET_FUNC(), \ .err_msg = (ERR_MSG)} /* other fields are set to 0 */ #define _PyStatus_NO_MEMORY() _PyStatus_ERR("memory allocation failed") #define _PyStatus_EXIT(EXITCODE) \ (PyStatus){ \ ._type = _PyStatus_TYPE_EXIT, \ .exitcode = (EXITCODE)} #define _PyStatus_IS_ERROR(err) \ (err._type == _PyStatus_TYPE_ERROR) #define _PyStatus_IS_EXIT(err) \ (err._type == _PyStatus_TYPE_EXIT) #define _PyStatus_EXCEPTION(err) \ (err._type != _PyStatus_TYPE_OK) #define _PyStatus_UPDATE_FUNC(err) \ do { err.func = _PyStatus_GET_FUNC(); } while (0) /* --- PyWideStringList ------------------------------------------------ */ #define _PyWideStringList_INIT (PyWideStringList){.length = 0, .items = NULL} #ifndef NDEBUG PyAPI_FUNC(int) _PyWideStringList_CheckConsistency(const PyWideStringList *list); #endif PyAPI_FUNC(void) _PyWideStringList_Clear(PyWideStringList *list); PyAPI_FUNC(int) _PyWideStringList_Copy(PyWideStringList *list, const PyWideStringList *list2); PyAPI_FUNC(PyStatus) _PyWideStringList_Extend(PyWideStringList *list, const PyWideStringList *list2); PyAPI_FUNC(PyObject*) _PyWideStringList_AsList(const PyWideStringList *list); /* --- _PyArgv ---------------------------------------------------- */ typedef struct { Py_ssize_t argc; int use_bytes_argv; char * const *bytes_argv; wchar_t * const *wchar_argv; } _PyArgv; PyAPI_FUNC(PyStatus) _PyArgv_AsWstrList(const _PyArgv *args, PyWideStringList *list); /* --- Helper functions ------------------------------------------- */ PyAPI_FUNC(int) _Py_str_to_int( const char *str, int *result); PyAPI_FUNC(const wchar_t*) _Py_get_xoption( const PyWideStringList *xoptions, const wchar_t *name); PyAPI_FUNC(const char*) _Py_GetEnv( int use_environment, const char *name); PyAPI_FUNC(void) _Py_get_env_flag( int use_environment, int *flag, const char *name); /* Py_GetArgcArgv() helper */ PyAPI_FUNC(void) _Py_ClearArgcArgv(void); /* --- _PyPreCmdline ------------------------------------------------- */ typedef struct { PyWideStringList argv; PyWideStringList xoptions; /* "-X value" option */ int isolated; /* -I option */ int use_environment; /* -E option */ int dev_mode; /* -X dev and PYTHONDEVMODE */ } _PyPreCmdline; #define _PyPreCmdline_INIT \ (_PyPreCmdline){ \ .use_environment = -1, \ .isolated = -1, \ .dev_mode = -1} /* Note: _PyPreCmdline_INIT sets other fields to 0/NULL */ extern void _PyPreCmdline_Clear(_PyPreCmdline *cmdline); extern PyStatus _PyPreCmdline_SetArgv(_PyPreCmdline *cmdline, const _PyArgv *args); extern PyStatus _PyPreCmdline_SetConfig( const _PyPreCmdline *cmdline, PyConfig *config); extern PyStatus _PyPreCmdline_Read(_PyPreCmdline *cmdline, const PyPreConfig *preconfig); /* --- PyPreConfig ----------------------------------------------- */ PyAPI_FUNC(void) _PyPreConfig_InitCompatConfig(PyPreConfig *preconfig); extern void _PyPreConfig_InitFromConfig( PyPreConfig *preconfig, const PyConfig *config); extern PyStatus _PyPreConfig_InitFromPreConfig( PyPreConfig *preconfig, const PyPreConfig *config2); extern PyObject* _PyPreConfig_AsDict(const PyPreConfig *preconfig); extern void _PyPreConfig_GetConfig(PyPreConfig *preconfig, const PyConfig *config); extern PyStatus _PyPreConfig_Read(PyPreConfig *preconfig, const _PyArgv *args); extern PyStatus _PyPreConfig_Write(const PyPreConfig *preconfig); /* --- PyConfig ---------------------------------------------- */ typedef enum { /* Py_Initialize() API: backward compatibility with Python 3.6 and 3.7 */ _PyConfig_INIT_COMPAT = 1, _PyConfig_INIT_PYTHON = 2, _PyConfig_INIT_ISOLATED = 3 } _PyConfigInitEnum; PyAPI_FUNC(void) _PyConfig_InitCompatConfig(PyConfig *config); extern PyStatus _PyConfig_Copy( PyConfig *config, const PyConfig *config2); extern PyStatus _PyConfig_InitPathConfig(PyConfig *config); extern void _PyConfig_Write(const PyConfig *config, _PyRuntimeState *runtime); extern PyStatus _PyConfig_SetPyArgv( PyConfig *config, const _PyArgv *args); /* --- Function used for testing ---------------------------------- */ PyAPI_FUNC(PyObject*) _Py_GetConfigsAsDict(void); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_CORECONFIG_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_object.h ================================================ #ifndef Py_INTERNAL_OBJECT_H #define Py_INTERNAL_OBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "pycore_pystate.h" /* _PyRuntime */ PyAPI_FUNC(int) _PyType_CheckConsistency(PyTypeObject *type); PyAPI_FUNC(int) _PyDict_CheckConsistency(PyObject *mp, int check_content); /* Tell the GC to track this object. * * NB: While the object is tracked by the collector, it must be safe to call the * ob_traverse method. * * Internal note: _PyRuntime.gc.generation0->_gc_prev doesn't have any bit flags * because it's not object header. So we don't use _PyGCHead_PREV() and * _PyGCHead_SET_PREV() for it to avoid unnecessary bitwise operations. * * The PyObject_GC_Track() function is the public version of this macro. */ static inline void _PyObject_GC_TRACK_impl(const char *filename, int lineno, PyObject *op) { _PyObject_ASSERT_FROM(op, !_PyObject_GC_IS_TRACKED(op), "object already tracked by the garbage collector", filename, lineno, "_PyObject_GC_TRACK"); PyGC_Head *gc = _Py_AS_GC(op); _PyObject_ASSERT_FROM(op, (gc->_gc_prev & _PyGC_PREV_MASK_COLLECTING) == 0, "object is in generation which is garbage collected", filename, lineno, "_PyObject_GC_TRACK"); PyGC_Head *last = (PyGC_Head*)(_PyRuntime.gc.generation0->_gc_prev); _PyGCHead_SET_NEXT(last, gc); _PyGCHead_SET_PREV(gc, last); _PyGCHead_SET_NEXT(gc, _PyRuntime.gc.generation0); _PyRuntime.gc.generation0->_gc_prev = (uintptr_t)gc; } #define _PyObject_GC_TRACK(op) \ _PyObject_GC_TRACK_impl(__FILE__, __LINE__, _PyObject_CAST(op)) /* Tell the GC to stop tracking this object. * * Internal note: This may be called while GC. So _PyGC_PREV_MASK_COLLECTING * must be cleared. But _PyGC_PREV_MASK_FINALIZED bit is kept. * * The object must be tracked by the GC. * * The PyObject_GC_UnTrack() function is the public version of this macro. */ static inline void _PyObject_GC_UNTRACK_impl(const char *filename, int lineno, PyObject *op) { _PyObject_ASSERT_FROM(op, _PyObject_GC_IS_TRACKED(op), "object not tracked by the garbage collector", filename, lineno, "_PyObject_GC_UNTRACK"); PyGC_Head *gc = _Py_AS_GC(op); PyGC_Head *prev = _PyGCHead_PREV(gc); PyGC_Head *next = _PyGCHead_NEXT(gc); _PyGCHead_SET_NEXT(prev, next); _PyGCHead_SET_PREV(next, prev); gc->_gc_next = 0; gc->_gc_prev &= _PyGC_PREV_MASK_FINALIZED; } #define _PyObject_GC_UNTRACK(op) \ _PyObject_GC_UNTRACK_impl(__FILE__, __LINE__, _PyObject_CAST(op)) #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_OBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_pathconfig.h ================================================ #ifndef Py_INTERNAL_PATHCONFIG_H #define Py_INTERNAL_PATHCONFIG_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif typedef struct _PyPathConfig { /* Full path to the Python program */ wchar_t *program_full_path; wchar_t *prefix; wchar_t *exec_prefix; /* Set by Py_SetPath(), or computed by _PyConfig_InitPathConfig() */ wchar_t *module_search_path; /* Python program name */ wchar_t *program_name; /* Set by Py_SetPythonHome() or PYTHONHOME environment variable */ wchar_t *home; #ifdef MS_WINDOWS /* isolated and site_import are used to set Py_IsolatedFlag and Py_NoSiteFlag flags on Windows in read_pth_file(). These fields are ignored when their value are equal to -1 (unset). */ int isolated; int site_import; /* Set when a venv is detected */ wchar_t *base_executable; #endif } _PyPathConfig; #ifdef MS_WINDOWS # define _PyPathConfig_INIT \ {.module_search_path = NULL, \ .isolated = -1, \ .site_import = -1} #else # define _PyPathConfig_INIT \ {.module_search_path = NULL} #endif /* Note: _PyPathConfig_INIT sets other fields to 0/NULL */ PyAPI_DATA(_PyPathConfig) _Py_path_config; #ifdef MS_WINDOWS PyAPI_DATA(wchar_t*) _Py_dll_path; #endif extern void _PyPathConfig_ClearGlobal(void); extern PyStatus _PyPathConfig_SetGlobal( const struct _PyPathConfig *pathconfig); extern PyStatus _PyPathConfig_Calculate( _PyPathConfig *pathconfig, const PyConfig *config); extern int _PyPathConfig_ComputeSysPath0( const PyWideStringList *argv, PyObject **path0); extern int _Py_FindEnvConfigValue( FILE *env_file, const wchar_t *key, wchar_t *value, size_t value_size); #ifdef MS_WINDOWS extern wchar_t* _Py_GetDLLPath(void); #endif extern PyStatus _PyConfig_WritePathConfig(const PyConfig *config); extern void _Py_DumpPathConfig(PyThreadState *tstate); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_PATHCONFIG_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_pyerrors.h ================================================ #ifndef Py_INTERNAL_PYERRORS_H #define Py_INTERNAL_PYERRORS_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif static inline PyObject* _PyErr_Occurred(PyThreadState *tstate) { return tstate == NULL ? NULL : tstate->curexc_type; } PyAPI_FUNC(void) _PyErr_Fetch( PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **traceback); PyAPI_FUNC(int) _PyErr_ExceptionMatches( PyThreadState *tstate, PyObject *exc); PyAPI_FUNC(void) _PyErr_Restore( PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *traceback); PyAPI_FUNC(void) _PyErr_SetObject( PyThreadState *tstate, PyObject *type, PyObject *value); PyAPI_FUNC(void) _PyErr_Clear(PyThreadState *tstate); PyAPI_FUNC(void) _PyErr_SetNone(PyThreadState *tstate, PyObject *exception); PyAPI_FUNC(void) _PyErr_SetString( PyThreadState *tstate, PyObject *exception, const char *string); PyAPI_FUNC(PyObject *) _PyErr_Format( PyThreadState *tstate, PyObject *exception, const char *format, ...); PyAPI_FUNC(void) _PyErr_NormalizeException( PyThreadState *tstate, PyObject **exc, PyObject **val, PyObject **tb); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_PYERRORS_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_pyhash.h ================================================ #ifndef Py_INTERNAL_HASH_H #define Py_INTERNAL_HASH_H #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif uint64_t _Py_KeyedHash(uint64_t, const char *, Py_ssize_t); #endif ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_pylifecycle.h ================================================ #ifndef Py_INTERNAL_LIFECYCLE_H #define Py_INTERNAL_LIFECYCLE_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "pycore_initconfig.h" /* _PyArgv */ #include "pycore_pystate.h" /* _PyRuntimeState */ /* True if the main interpreter thread exited due to an unhandled * KeyboardInterrupt exception, suggesting the user pressed ^C. */ PyAPI_DATA(int) _Py_UnhandledKeyboardInterrupt; extern int _Py_SetFileSystemEncoding( const char *encoding, const char *errors); extern void _Py_ClearFileSystemEncoding(void); extern PyStatus _PyUnicode_InitEncodings(PyThreadState *tstate); #ifdef MS_WINDOWS extern int _PyUnicode_EnableLegacyWindowsFSEncoding(void); #endif PyAPI_FUNC(void) _Py_ClearStandardStreamEncoding(void); PyAPI_FUNC(int) _Py_IsLocaleCoercionTarget(const char *ctype_loc); /* Various one-time initializers */ extern PyStatus _PyUnicode_Init(void); extern int _PyStructSequence_Init(void); extern int _PyLong_Init(void); extern PyStatus _PyFaulthandler_Init(int enable); extern int _PyTraceMalloc_Init(int enable); extern PyObject * _PyBuiltin_Init(void); extern PyStatus _PySys_Create( _PyRuntimeState *runtime, PyInterpreterState *interp, PyObject **sysmod_p); extern PyStatus _PySys_SetPreliminaryStderr(PyObject *sysdict); extern PyStatus _PySys_ReadPreinitWarnOptions(PyWideStringList *options); extern PyStatus _PySys_ReadPreinitXOptions(PyConfig *config); extern int _PySys_InitMain( _PyRuntimeState *runtime, PyInterpreterState *interp); extern PyStatus _PyImport_Init(PyInterpreterState *interp); extern PyStatus _PyExc_Init(void); extern PyStatus _PyErr_Init(void); extern PyStatus _PyBuiltins_AddExceptions(PyObject * bltinmod); extern PyStatus _PyImportHooks_Init(void); extern int _PyFloat_Init(void); extern PyStatus _Py_HashRandomization_Init(const PyConfig *); extern PyStatus _PyTypes_Init(void); extern PyStatus _PyImportZip_Init(PyInterpreterState *interp); /* Various internal finalizers */ extern void PyMethod_Fini(void); extern void PyFrame_Fini(void); extern void PyCFunction_Fini(void); extern void PyDict_Fini(void); extern void PyTuple_Fini(void); extern void PyList_Fini(void); extern void PySet_Fini(void); extern void PyBytes_Fini(void); extern void PyFloat_Fini(void); extern void PyOS_FiniInterrupts(void); extern void PySlice_Fini(void); extern void PyAsyncGen_Fini(void); extern void _PyExc_Fini(void); extern void _PyImport_Fini(void); extern void _PyImport_Fini2(void); extern void _PyGC_Fini(_PyRuntimeState *runtime); extern void _PyType_Fini(void); extern void _Py_HashRandomization_Fini(void); extern void _PyUnicode_Fini(void); extern void PyLong_Fini(void); extern void _PyFaulthandler_Fini(void); extern void _PyHash_Fini(void); extern void _PyTraceMalloc_Fini(void); extern void _PyWarnings_Fini(PyInterpreterState *interp); extern void _PyGILState_Init( _PyRuntimeState *runtime, PyInterpreterState *interp, PyThreadState *tstate); extern void _PyGILState_Fini(_PyRuntimeState *runtime); PyAPI_FUNC(void) _PyGC_DumpShutdownStats(_PyRuntimeState *runtime); PyAPI_FUNC(PyStatus) _Py_PreInitializeFromPyArgv( const PyPreConfig *src_config, const _PyArgv *args); PyAPI_FUNC(PyStatus) _Py_PreInitializeFromConfig( const PyConfig *config, const _PyArgv *args); PyAPI_FUNC(int) _Py_HandleSystemExit(int *exitcode_p); PyAPI_FUNC(PyObject*) _PyErr_WriteUnraisableDefaultHook(PyObject *unraisable); PyAPI_FUNC(void) _PyErr_Print(PyThreadState *tstate); PyAPI_FUNC(void) _PyErr_Display(PyObject *file, PyObject *exception, PyObject *value, PyObject *tb); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_LIFECYCLE_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_pymem.h ================================================ #ifndef Py_INTERNAL_PYMEM_H #define Py_INTERNAL_PYMEM_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "objimpl.h" #include "pymem.h" /* GC runtime state */ /* If we change this, we need to change the default value in the signature of gc.collect. */ #define NUM_GENERATIONS 3 /* NOTE: about the counting of long-lived objects. To limit the cost of garbage collection, there are two strategies; - make each collection faster, e.g. by scanning fewer objects - do less collections This heuristic is about the latter strategy. In addition to the various configurable thresholds, we only trigger a full collection if the ratio long_lived_pending / long_lived_total is above a given value (hardwired to 25%). The reason is that, while "non-full" collections (i.e., collections of the young and middle generations) will always examine roughly the same number of objects -- determined by the aforementioned thresholds --, the cost of a full collection is proportional to the total number of long-lived objects, which is virtually unbounded. Indeed, it has been remarked that doing a full collection every of object creations entails a dramatic performance degradation in workloads which consist in creating and storing lots of long-lived objects (e.g. building a large list of GC-tracked objects would show quadratic performance, instead of linear as expected: see issue #4074). Using the above ratio, instead, yields amortized linear performance in the total number of objects (the effect of which can be summarized thusly: "each full garbage collection is more and more costly as the number of objects grows, but we do fewer and fewer of them"). This heuristic was suggested by Martin von Löwis on python-dev in June 2008. His original analysis and proposal can be found at: http://mail.python.org/pipermail/python-dev/2008-June/080579.html */ /* NOTE: about untracking of mutable objects. Certain types of container cannot participate in a reference cycle, and so do not need to be tracked by the garbage collector. Untracking these objects reduces the cost of garbage collections. However, determining which objects may be untracked is not free, and the costs must be weighed against the benefits for garbage collection. There are two possible strategies for when to untrack a container: i) When the container is created. ii) When the container is examined by the garbage collector. Tuples containing only immutable objects (integers, strings etc, and recursively, tuples of immutable objects) do not need to be tracked. The interpreter creates a large number of tuples, many of which will not survive until garbage collection. It is therefore not worthwhile to untrack eligible tuples at creation time. Instead, all tuples except the empty tuple are tracked when created. During garbage collection it is determined whether any surviving tuples can be untracked. A tuple can be untracked if all of its contents are already not tracked. Tuples are examined for untracking in all garbage collection cycles. It may take more than one cycle to untrack a tuple. Dictionaries containing only immutable objects also do not need to be tracked. Dictionaries are untracked when created. If a tracked item is inserted into a dictionary (either as a key or value), the dictionary becomes tracked. During a full garbage collection (all generations), the collector will untrack any dictionaries whose contents are not tracked. The module provides the python function is_tracked(obj), which returns the CURRENT tracking status of the object. Subsequent garbage collections may change the tracking status of the object. Untracking of certain containers was introduced in issue #4688, and the algorithm was refined in response to issue #14775. */ struct gc_generation { PyGC_Head head; int threshold; /* collection threshold */ int count; /* count of allocations or collections of younger generations */ }; /* Running stats per generation */ struct gc_generation_stats { /* total number of collections */ Py_ssize_t collections; /* total number of collected objects */ Py_ssize_t collected; /* total number of uncollectable objects (put into gc.garbage) */ Py_ssize_t uncollectable; }; struct _gc_runtime_state { /* List of objects that still need to be cleaned up, singly linked * via their gc headers' gc_prev pointers. */ PyObject *trash_delete_later; /* Current call-stack depth of tp_dealloc calls. */ int trash_delete_nesting; int enabled; int debug; /* linked lists of container objects */ struct gc_generation generations[NUM_GENERATIONS]; PyGC_Head *generation0; /* a permanent generation which won't be collected */ struct gc_generation permanent_generation; struct gc_generation_stats generation_stats[NUM_GENERATIONS]; /* true if we are currently running the collector */ int collecting; /* list of uncollectable objects */ PyObject *garbage; /* a list of callbacks to be invoked when collection is performed */ PyObject *callbacks; /* This is the number of objects that survived the last full collection. It approximates the number of long lived objects tracked by the GC. (by "full collection", we mean a collection of the oldest generation). */ Py_ssize_t long_lived_total; /* This is the number of objects that survived all "non-full" collections, and are awaiting to undergo a full collection for the first time. */ Py_ssize_t long_lived_pending; }; PyAPI_FUNC(void) _PyGC_Initialize(struct _gc_runtime_state *); /* Set the memory allocator of the specified domain to the default. Save the old allocator into *old_alloc if it's non-NULL. Return on success, or return -1 if the domain is unknown. */ PyAPI_FUNC(int) _PyMem_SetDefaultAllocator( PyMemAllocatorDomain domain, PyMemAllocatorEx *old_alloc); /* Special bytes broadcast into debug memory blocks at appropriate times. Strings of these are unlikely to be valid addresses, floats, ints or 7-bit ASCII. - PYMEM_CLEANBYTE: clean (newly allocated) memory - PYMEM_DEADBYTE dead (newly freed) memory - PYMEM_FORBIDDENBYTE: untouchable bytes at each end of a block Byte patterns 0xCB, 0xDB and 0xFB have been replaced with 0xCD, 0xDD and 0xFD to use the same values than Windows CRT debug malloc() and free(). If modified, _PyMem_IsPtrFreed() should be updated as well. */ #define PYMEM_CLEANBYTE 0xCD #define PYMEM_DEADBYTE 0xDD #define PYMEM_FORBIDDENBYTE 0xFD /* Heuristic checking if a pointer value is newly allocated (uninitialized), newly freed or NULL (is equal to zero). The pointer is not dereferenced, only the pointer value is checked. The heuristic relies on the debug hooks on Python memory allocators which fills newly allocated memory with CLEANBYTE (0xCD) and newly freed memory with DEADBYTE (0xDD). Detect also "untouchable bytes" marked with FORBIDDENBYTE (0xFD). */ static inline int _PyMem_IsPtrFreed(void *ptr) { uintptr_t value = (uintptr_t)ptr; #if SIZEOF_VOID_P == 8 return (value == 0 || value == (uintptr_t)0xCDCDCDCDCDCDCDCD || value == (uintptr_t)0xDDDDDDDDDDDDDDDD || value == (uintptr_t)0xFDFDFDFDFDFDFDFD); #elif SIZEOF_VOID_P == 4 return (value == 0 || value == (uintptr_t)0xCDCDCDCD || value == (uintptr_t)0xDDDDDDDD || value == (uintptr_t)0xFDFDFDFD); #else # error "unknown pointer size" #endif } PyAPI_FUNC(int) _PyMem_GetAllocatorName( const char *name, PyMemAllocatorName *allocator); /* Configure the Python memory allocators. Pass PYMEM_ALLOCATOR_DEFAULT to use default allocators. PYMEM_ALLOCATOR_NOT_SET does nothing. */ PyAPI_FUNC(int) _PyMem_SetupAllocators(PyMemAllocatorName allocator); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_PYMEM_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_pystate.h ================================================ #ifndef Py_INTERNAL_PYSTATE_H #define Py_INTERNAL_PYSTATE_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "cpython/initconfig.h" #include "fileobject.h" #include "pystate.h" #include "pythread.h" #include "sysmodule.h" #include "pycore_gil.h" /* _gil_runtime_state */ #include "pycore_pathconfig.h" #include "pycore_pymem.h" #include "pycore_warnings.h" /* ceval state */ struct _pending_calls { int finishing; PyThread_type_lock lock; /* Request for running pending calls. */ _Py_atomic_int calls_to_do; /* Request for looking at the `async_exc` field of the current thread state. Guarded by the GIL. */ int async_exc; #define NPENDINGCALLS 32 struct { int (*func)(void *); void *arg; } calls[NPENDINGCALLS]; int first; int last; }; struct _ceval_runtime_state { int recursion_limit; /* Records whether tracing is on for any thread. Counts the number of threads for which tstate->c_tracefunc is non-NULL, so if the value is 0, we know we don't have to check this thread's c_tracefunc. This speeds up the if statement in PyEval_EvalFrameEx() after fast_next_opcode. */ int tracing_possible; /* This single variable consolidates all requests to break out of the fast path in the eval loop. */ _Py_atomic_int eval_breaker; /* Request for dropping the GIL */ _Py_atomic_int gil_drop_request; struct _pending_calls pending; /* Request for checking signals. */ _Py_atomic_int signals_pending; struct _gil_runtime_state gil; }; /* interpreter state */ typedef PyObject* (*_PyFrameEvalFunction)(struct _frame *, int); // The PyInterpreterState typedef is in Include/pystate.h. struct _is { struct _is *next; struct _ts *tstate_head; int64_t id; int64_t id_refcount; int requires_idref; PyThread_type_lock id_mutex; int finalizing; PyObject *modules; PyObject *modules_by_index; PyObject *sysdict; PyObject *builtins; PyObject *importlib; /* Used in Python/sysmodule.c. */ int check_interval; /* Used in Modules/_threadmodule.c. */ long num_threads; /* Support for runtime thread stack size tuning. A value of 0 means using the platform's default stack size or the size specified by the THREAD_STACK_SIZE macro. */ /* Used in Python/thread.c. */ size_t pythread_stacksize; PyObject *codec_search_path; PyObject *codec_search_cache; PyObject *codec_error_registry; int codecs_initialized; /* fs_codec.encoding is initialized to NULL. Later, it is set to a non-NULL string by _PyUnicode_InitEncodings(). */ struct { char *encoding; /* Filesystem encoding (encoded to UTF-8) */ char *errors; /* Filesystem errors (encoded to UTF-8) */ _Py_error_handler error_handler; } fs_codec; PyConfig config; #ifdef HAVE_DLOPEN int dlopenflags; #endif PyObject *dict; /* Stores per-interpreter state */ PyObject *builtins_copy; PyObject *import_func; /* Initialized to PyEval_EvalFrameDefault(). */ _PyFrameEvalFunction eval_frame; Py_ssize_t co_extra_user_count; freefunc co_extra_freefuncs[MAX_CO_EXTRA_USERS]; #ifdef HAVE_FORK PyObject *before_forkers; PyObject *after_forkers_parent; PyObject *after_forkers_child; #endif /* AtExit module */ void (*pyexitfunc)(PyObject *); PyObject *pyexitmodule; uint64_t tstate_next_unique_id; struct _warnings_runtime_state warnings; PyObject *audit_hooks; }; PyAPI_FUNC(struct _is*) _PyInterpreterState_LookUpID(PY_INT64_T); PyAPI_FUNC(int) _PyInterpreterState_IDInitref(struct _is *); PyAPI_FUNC(void) _PyInterpreterState_IDIncref(struct _is *); PyAPI_FUNC(void) _PyInterpreterState_IDDecref(struct _is *); /* cross-interpreter data registry */ /* For now we use a global registry of shareable classes. An alternative would be to add a tp_* slot for a class's crossinterpdatafunc. It would be simpler and more efficient. */ struct _xidregitem; struct _xidregitem { PyTypeObject *cls; crossinterpdatafunc getdata; struct _xidregitem *next; }; /* runtime audit hook state */ typedef struct _Py_AuditHookEntry { struct _Py_AuditHookEntry *next; Py_AuditHookFunction hookCFunction; void *userData; } _Py_AuditHookEntry; /* GIL state */ struct _gilstate_runtime_state { int check_enabled; /* Assuming the current thread holds the GIL, this is the PyThreadState for the current thread. */ _Py_atomic_address tstate_current; PyThreadFrameGetter getframe; /* The single PyInterpreterState used by this process' GILState implementation */ /* TODO: Given interp_main, it may be possible to kill this ref */ PyInterpreterState *autoInterpreterState; Py_tss_t autoTSSkey; }; /* hook for PyEval_GetFrame(), requested for Psyco */ #define _PyThreadState_GetFrame _PyRuntime.gilstate.getframe /* Issue #26558: Flag to disable PyGILState_Check(). If set to non-zero, PyGILState_Check() always return 1. */ #define _PyGILState_check_enabled _PyRuntime.gilstate.check_enabled /* Full Python runtime state */ typedef struct pyruntimestate { /* Is running Py_PreInitialize()? */ int preinitializing; /* Is Python preinitialized? Set to 1 by Py_PreInitialize() */ int preinitialized; /* Is Python core initialized? Set to 1 by _Py_InitializeCore() */ int core_initialized; /* Is Python fully initialized? Set to 1 by Py_Initialize() */ int initialized; /* Set by Py_FinalizeEx(). Only reset to NULL if Py_Initialize() is called again. */ PyThreadState *finalizing; struct pyinterpreters { PyThread_type_lock mutex; PyInterpreterState *head; PyInterpreterState *main; /* _next_interp_id is an auto-numbered sequence of small integers. It gets initialized in _PyInterpreterState_Init(), which is called in Py_Initialize(), and used in PyInterpreterState_New(). A negative interpreter ID indicates an error occurred. The main interpreter will always have an ID of 0. Overflow results in a RuntimeError. If that becomes a problem later then we can adjust, e.g. by using a Python int. */ int64_t next_id; } interpreters; // XXX Remove this field once we have a tp_* slot. struct _xidregistry { PyThread_type_lock mutex; struct _xidregitem *head; } xidregistry; unsigned long main_thread; #define NEXITFUNCS 32 void (*exitfuncs[NEXITFUNCS])(void); int nexitfuncs; struct _gc_runtime_state gc; struct _ceval_runtime_state ceval; struct _gilstate_runtime_state gilstate; PyPreConfig preconfig; Py_OpenCodeHookFunction open_code_hook; void *open_code_userdata; _Py_AuditHookEntry *audit_hook_head; // XXX Consolidate globals found via the check-c-globals script. } _PyRuntimeState; #define _PyRuntimeState_INIT \ {.preinitialized = 0, .core_initialized = 0, .initialized = 0} /* Note: _PyRuntimeState_INIT sets other fields to 0/NULL */ PyAPI_DATA(_PyRuntimeState) _PyRuntime; PyAPI_FUNC(PyStatus) _PyRuntimeState_Init(_PyRuntimeState *runtime); PyAPI_FUNC(void) _PyRuntimeState_Fini(_PyRuntimeState *runtime); PyAPI_FUNC(void) _PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime); /* Initialize _PyRuntimeState. Return NULL on success, or return an error message on failure. */ PyAPI_FUNC(PyStatus) _PyRuntime_Initialize(void); PyAPI_FUNC(void) _PyRuntime_Finalize(void); #define _Py_CURRENTLY_FINALIZING(runtime, tstate) \ (runtime->finalizing == tstate) /* Variable and macro for in-line access to current thread and interpreter state */ #define _PyRuntimeState_GetThreadState(runtime) \ ((PyThreadState*)_Py_atomic_load_relaxed(&(runtime)->gilstate.tstate_current)) /* Get the current Python thread state. Efficient macro reading directly the 'gilstate.tstate_current' atomic variable. The macro is unsafe: it does not check for error and it can return NULL. The caller must hold the GIL. See also PyThreadState_Get() and PyThreadState_GET(). */ #define _PyThreadState_GET() _PyRuntimeState_GetThreadState(&_PyRuntime) /* Redefine PyThreadState_GET() as an alias to _PyThreadState_GET() */ #undef PyThreadState_GET #define PyThreadState_GET() _PyThreadState_GET() /* Get the current interpreter state. The macro is unsafe: it does not check for error and it can return NULL. The caller must hold the GIL. See also _PyInterpreterState_Get() and _PyGILState_GetInterpreterStateUnsafe(). */ #define _PyInterpreterState_GET_UNSAFE() (_PyThreadState_GET()->interp) /* Other */ PyAPI_FUNC(void) _PyThreadState_Init( _PyRuntimeState *runtime, PyThreadState *tstate); PyAPI_FUNC(void) _PyThreadState_DeleteExcept( _PyRuntimeState *runtime, PyThreadState *tstate); PyAPI_FUNC(PyThreadState *) _PyThreadState_Swap( struct _gilstate_runtime_state *gilstate, PyThreadState *newts); PyAPI_FUNC(PyStatus) _PyInterpreterState_Enable(_PyRuntimeState *runtime); PyAPI_FUNC(void) _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime); PyAPI_FUNC(void) _PyGILState_Reinit(_PyRuntimeState *runtime); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_PYSTATE_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_traceback.h ================================================ #ifndef Py_INTERNAL_TRACEBACK_H #define Py_INTERNAL_TRACEBACK_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "pystate.h" /* PyInterpreterState */ /* Write the Python traceback into the file 'fd'. For example: Traceback (most recent call first): File "xxx", line xxx in File "xxx", line xxx in ... File "xxx", line xxx in This function is written for debug purpose only, to dump the traceback in the worst case: after a segmentation fault, at fatal error, etc. That's why, it is very limited. Strings are truncated to 100 characters and encoded to ASCII with backslashreplace. It doesn't write the source code, only the function name, filename and line number of each frame. Write only the first 100 frames: if the traceback is truncated, write the line " ...". This function is signal safe. */ PyAPI_FUNC(void) _Py_DumpTraceback( int fd, PyThreadState *tstate); /* Write the traceback of all threads into the file 'fd'. current_thread can be NULL. Return NULL on success, or an error message on error. This function is written for debug purpose only. It calls _Py_DumpTraceback() for each thread, and so has the same limitations. It only write the traceback of the first 100 threads: write "..." if there are more threads. If current_tstate is NULL, the function tries to get the Python thread state of the current thread. It is not an error if the function is unable to get the current Python thread state. If interp is NULL, the function tries to get the interpreter state from the current Python thread state, or from _PyGILState_GetInterpreterStateUnsafe() in last resort. It is better to pass NULL to interp and current_tstate, the function tries different options to retrieve these informations. This function is signal safe. */ PyAPI_FUNC(const char*) _Py_DumpTracebackThreads( int fd, PyInterpreterState *interp, PyThreadState *current_tstate); /* Write a Unicode object into the file descriptor fd. Encode the string to ASCII using the backslashreplace error handler. Do nothing if text is not a Unicode object. The function accepts Unicode string which is not ready (PyUnicode_WCHAR_KIND). This function is signal safe. */ PyAPI_FUNC(void) _Py_DumpASCII(int fd, PyObject *text); /* Format an integer as decimal into the file descriptor fd. This function is signal safe. */ PyAPI_FUNC(void) _Py_DumpDecimal( int fd, unsigned long value); /* Format an integer as hexadecimal into the file descriptor fd with at least width digits. The maximum width is sizeof(unsigned long)*2 digits. This function is signal safe. */ PyAPI_FUNC(void) _Py_DumpHexadecimal( int fd, unsigned long value, Py_ssize_t width); PyAPI_FUNC(PyObject*) _PyTraceBack_FromFrame( PyObject *tb_next, struct _frame *frame); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_TRACEBACK_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_tupleobject.h ================================================ #ifndef Py_INTERNAL_TUPLEOBJECT_H #define Py_INTERNAL_TUPLEOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "tupleobject.h" #define _PyTuple_ITEMS(op) (_PyTuple_CAST(op)->ob_item) PyAPI_FUNC(PyObject *) _PyTuple_FromArray(PyObject *const *, Py_ssize_t); #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_TUPLEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/internal/pycore_warnings.h ================================================ #ifndef Py_INTERNAL_WARNINGS_H #define Py_INTERNAL_WARNINGS_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_BUILD_CORE # error "this header requires Py_BUILD_CORE define" #endif #include "object.h" struct _warnings_runtime_state { /* Both 'filters' and 'onceregistry' can be set in warnings.py; get_warnings_attr() will reset these variables accordingly. */ PyObject *filters; /* List */ PyObject *once_registry; /* Dict */ PyObject *default_action; /* String */ long filters_version; }; #ifdef __cplusplus } #endif #endif /* !Py_INTERNAL_WARNINGS_H */ ================================================ FILE: thirdLibs/python3_8/include/interpreteridobject.h ================================================ #ifndef Py_INTERPRETERIDOBJECT_H #define Py_INTERPRETERIDOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API # define Py_CPYTHON_INTERPRETERIDOBJECT_H # include "cpython/interpreteridobject.h" # undef Py_CPYTHON_INTERPRETERIDOBJECT_H #endif #ifdef __cplusplus } #endif #endif /* !Py_INTERPRETERIDOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/intrcheck.h ================================================ #ifndef Py_INTRCHECK_H #define Py_INTRCHECK_H #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(int) PyOS_InterruptOccurred(void); PyAPI_FUNC(void) PyOS_InitInterrupts(void); #ifdef HAVE_FORK #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000 PyAPI_FUNC(void) PyOS_BeforeFork(void); PyAPI_FUNC(void) PyOS_AfterFork_Parent(void); PyAPI_FUNC(void) PyOS_AfterFork_Child(void); #endif #endif /* Deprecated, please use PyOS_AfterFork_Child() instead */ Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyOS_AfterFork(void); #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyOS_IsMainThread(void); PyAPI_FUNC(void) _PySignal_AfterFork(void); #ifdef MS_WINDOWS /* windows.h is not included by Python.h so use void* instead of HANDLE */ PyAPI_FUNC(void*) _PyOS_SigintEvent(void); #endif #endif /* !Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_INTRCHECK_H */ ================================================ FILE: thirdLibs/python3_8/include/iterobject.h ================================================ #ifndef Py_ITEROBJECT_H #define Py_ITEROBJECT_H /* Iterators (the basic kind, over a sequence) */ #ifdef __cplusplus extern "C" { #endif PyAPI_DATA(PyTypeObject) PySeqIter_Type; PyAPI_DATA(PyTypeObject) PyCallIter_Type; PyAPI_DATA(PyTypeObject) PyCmpWrapper_Type; #define PySeqIter_Check(op) (Py_TYPE(op) == &PySeqIter_Type) PyAPI_FUNC(PyObject *) PySeqIter_New(PyObject *); #define PyCallIter_Check(op) (Py_TYPE(op) == &PyCallIter_Type) PyAPI_FUNC(PyObject *) PyCallIter_New(PyObject *, PyObject *); #ifdef __cplusplus } #endif #endif /* !Py_ITEROBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/listobject.h ================================================ /* List object interface */ /* Another generally useful object type is a list of object pointers. This is a mutable type: the list items can be changed, and items can be added or removed. Out-of-range indices or non-list objects are ignored. *** WARNING *** PyList_SetItem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, if not nil. It does *decrement* the reference count if it is *not* inserted in the list. Similarly, PyList_GetItem does not increment the returned item's reference count. */ #ifndef Py_LISTOBJECT_H #define Py_LISTOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated * len(list) == ob_size * ob_item == NULL implies ob_size == allocated == 0 * list.sort() temporarily sets allocated to -1 to detect mutations. * * Items must normally not be NULL, except during construction when * the list is not yet visible outside the function that builds it. */ Py_ssize_t allocated; } PyListObject; #endif PyAPI_DATA(PyTypeObject) PyList_Type; PyAPI_DATA(PyTypeObject) PyListIter_Type; PyAPI_DATA(PyTypeObject) PyListRevIter_Type; PyAPI_DATA(PyTypeObject) PySortWrapper_Type; #define PyList_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LIST_SUBCLASS) #define PyList_CheckExact(op) (Py_TYPE(op) == &PyList_Type) PyAPI_FUNC(PyObject *) PyList_New(Py_ssize_t size); PyAPI_FUNC(Py_ssize_t) PyList_Size(PyObject *); PyAPI_FUNC(PyObject *) PyList_GetItem(PyObject *, Py_ssize_t); PyAPI_FUNC(int) PyList_SetItem(PyObject *, Py_ssize_t, PyObject *); PyAPI_FUNC(int) PyList_Insert(PyObject *, Py_ssize_t, PyObject *); PyAPI_FUNC(int) PyList_Append(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyList_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t); PyAPI_FUNC(int) PyList_SetSlice(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *); PyAPI_FUNC(int) PyList_Sort(PyObject *); PyAPI_FUNC(int) PyList_Reverse(PyObject *); PyAPI_FUNC(PyObject *) PyList_AsTuple(PyObject *); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyList_Extend(PyListObject *, PyObject *); PyAPI_FUNC(int) PyList_ClearFreeList(void); PyAPI_FUNC(void) _PyList_DebugMallocStats(FILE *out); #endif /* Macro, trading safety for speed */ #ifndef Py_LIMITED_API #define PyList_GET_ITEM(op, i) (((PyListObject *)(op))->ob_item[i]) #define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v)) #define PyList_GET_SIZE(op) (assert(PyList_Check(op)),Py_SIZE(op)) #define _PyList_ITEMS(op) (((PyListObject *)(op))->ob_item) #endif #ifdef __cplusplus } #endif #endif /* !Py_LISTOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/longintrepr.h ================================================ #ifndef Py_LIMITED_API #ifndef Py_LONGINTREPR_H #define Py_LONGINTREPR_H #ifdef __cplusplus extern "C" { #endif /* This is published for the benefit of "friends" marshal.c and _decimal.c. */ /* Parameters of the integer representation. There are two different sets of parameters: one set for 30-bit digits, stored in an unsigned 32-bit integer type, and one set for 15-bit digits with each digit stored in an unsigned short. The value of PYLONG_BITS_IN_DIGIT, defined either at configure time or in pyport.h, is used to decide which digit size to use. Type 'digit' should be able to hold 2*PyLong_BASE-1, and type 'twodigits' should be an unsigned integer type able to hold all integers up to PyLong_BASE*PyLong_BASE-1. x_sub assumes that 'digit' is an unsigned type, and that overflow is handled by taking the result modulo 2**N for some N > PyLong_SHIFT. The majority of the code doesn't care about the precise value of PyLong_SHIFT, but there are some notable exceptions: - long_pow() requires that PyLong_SHIFT be divisible by 5 - PyLong_{As,From}ByteArray require that PyLong_SHIFT be at least 8 - long_hash() requires that PyLong_SHIFT is *strictly* less than the number of bits in an unsigned long, as do the PyLong <-> long (or unsigned long) conversion functions - the Python int <-> size_t/Py_ssize_t conversion functions expect that PyLong_SHIFT is strictly less than the number of bits in a size_t - the marshal code currently expects that PyLong_SHIFT is a multiple of 15 - NSMALLNEGINTS and NSMALLPOSINTS should be small enough to fit in a single digit; with the current values this forces PyLong_SHIFT >= 9 The values 15 and 30 should fit all of the above requirements, on any platform. */ #if PYLONG_BITS_IN_DIGIT == 30 typedef uint32_t digit; typedef int32_t sdigit; /* signed variant of digit */ typedef uint64_t twodigits; typedef int64_t stwodigits; /* signed variant of twodigits */ #define PyLong_SHIFT 30 #define _PyLong_DECIMAL_SHIFT 9 /* max(e such that 10**e fits in a digit) */ #define _PyLong_DECIMAL_BASE ((digit)1000000000) /* 10 ** DECIMAL_SHIFT */ #elif PYLONG_BITS_IN_DIGIT == 15 typedef unsigned short digit; typedef short sdigit; /* signed variant of digit */ typedef unsigned long twodigits; typedef long stwodigits; /* signed variant of twodigits */ #define PyLong_SHIFT 15 #define _PyLong_DECIMAL_SHIFT 4 /* max(e such that 10**e fits in a digit) */ #define _PyLong_DECIMAL_BASE ((digit)10000) /* 10 ** DECIMAL_SHIFT */ #else #error "PYLONG_BITS_IN_DIGIT should be 15 or 30" #endif #define PyLong_BASE ((digit)1 << PyLong_SHIFT) #define PyLong_MASK ((digit)(PyLong_BASE - 1)) #if PyLong_SHIFT % 5 != 0 #error "longobject.c requires that PyLong_SHIFT be divisible by 5" #endif /* Long integer representation. The absolute value of a number is equal to SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i) Negative numbers are represented with ob_size < 0; zero is represented by ob_size == 0. In a normalized number, ob_digit[abs(ob_size)-1] (the most significant digit) is never zero. Also, in all cases, for all valid i, 0 <= ob_digit[i] <= MASK. The allocation function takes care of allocating extra memory so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available. CAUTION: Generic code manipulating subtypes of PyVarObject has to aware that ints abuse ob_size's sign bit. */ struct _longobject { PyObject_VAR_HEAD digit ob_digit[1]; }; PyAPI_FUNC(PyLongObject *) _PyLong_New(Py_ssize_t); /* Return a copy of src. */ PyAPI_FUNC(PyObject *) _PyLong_Copy(PyLongObject *src); #ifdef __cplusplus } #endif #endif /* !Py_LONGINTREPR_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/longobject.h ================================================ #ifndef Py_LONGOBJECT_H #define Py_LONGOBJECT_H #ifdef __cplusplus extern "C" { #endif /* Long (arbitrary precision) integer object interface */ typedef struct _longobject PyLongObject; /* Revealed in longintrepr.h */ PyAPI_DATA(PyTypeObject) PyLong_Type; #define PyLong_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LONG_SUBCLASS) #define PyLong_CheckExact(op) (Py_TYPE(op) == &PyLong_Type) PyAPI_FUNC(PyObject *) PyLong_FromLong(long); PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLong(unsigned long); PyAPI_FUNC(PyObject *) PyLong_FromSize_t(size_t); PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t); PyAPI_FUNC(PyObject *) PyLong_FromDouble(double); PyAPI_FUNC(long) PyLong_AsLong(PyObject *); PyAPI_FUNC(long) PyLong_AsLongAndOverflow(PyObject *, int *); PyAPI_FUNC(Py_ssize_t) PyLong_AsSsize_t(PyObject *); PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *); PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *); PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *); #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyLong_AsInt(PyObject *); #endif PyAPI_FUNC(PyObject *) PyLong_GetInfo(void); /* It may be useful in the future. I've added it in the PyInt -> PyLong cleanup to keep the extra information. [CH] */ #define PyLong_AS_LONG(op) PyLong_AsLong(op) /* Issue #1983: pid_t can be longer than a C long on some systems */ #if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT #define _Py_PARSE_PID "i" #define PyLong_FromPid PyLong_FromLong #define PyLong_AsPid PyLong_AsLong #elif SIZEOF_PID_T == SIZEOF_LONG #define _Py_PARSE_PID "l" #define PyLong_FromPid PyLong_FromLong #define PyLong_AsPid PyLong_AsLong #elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG #define _Py_PARSE_PID "L" #define PyLong_FromPid PyLong_FromLongLong #define PyLong_AsPid PyLong_AsLongLong #else #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)" #endif /* SIZEOF_PID_T */ #if SIZEOF_VOID_P == SIZEOF_INT # define _Py_PARSE_INTPTR "i" # define _Py_PARSE_UINTPTR "I" #elif SIZEOF_VOID_P == SIZEOF_LONG # define _Py_PARSE_INTPTR "l" # define _Py_PARSE_UINTPTR "k" #elif defined(SIZEOF_LONG_LONG) && SIZEOF_VOID_P == SIZEOF_LONG_LONG # define _Py_PARSE_INTPTR "L" # define _Py_PARSE_UINTPTR "K" #else # error "void* different in size from int, long and long long" #endif /* SIZEOF_VOID_P */ #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyLong_UnsignedShort_Converter(PyObject *, void *); PyAPI_FUNC(int) _PyLong_UnsignedInt_Converter(PyObject *, void *); PyAPI_FUNC(int) _PyLong_UnsignedLong_Converter(PyObject *, void *); PyAPI_FUNC(int) _PyLong_UnsignedLongLong_Converter(PyObject *, void *); PyAPI_FUNC(int) _PyLong_Size_t_Converter(PyObject *, void *); #endif /* Used by Python/mystrtoul.c, _PyBytes_FromHex(), _PyBytes_DecodeEscapeRecode(), etc. */ #ifndef Py_LIMITED_API PyAPI_DATA(unsigned char) _PyLong_DigitValue[256]; #endif /* _PyLong_Frexp returns a double x and an exponent e such that the true value is approximately equal to x * 2**e. e is >= 0. x is 0.0 if and only if the input is 0 (in which case, e and x are both zeroes); otherwise, 0.5 <= abs(x) < 1.0. On overflow, which is possible if the number of bits doesn't fit into a Py_ssize_t, sets OverflowError and returns -1.0 for x, 0 for e. */ #ifndef Py_LIMITED_API PyAPI_FUNC(double) _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e); #endif PyAPI_FUNC(double) PyLong_AsDouble(PyObject *); PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *); PyAPI_FUNC(void *) PyLong_AsVoidPtr(PyObject *); PyAPI_FUNC(PyObject *) PyLong_FromLongLong(long long); PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLongLong(unsigned long long); PyAPI_FUNC(long long) PyLong_AsLongLong(PyObject *); PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLong(PyObject *); PyAPI_FUNC(unsigned long long) PyLong_AsUnsignedLongLongMask(PyObject *); PyAPI_FUNC(long long) PyLong_AsLongLongAndOverflow(PyObject *, int *); PyAPI_FUNC(PyObject *) PyLong_FromString(const char *, char **, int); #ifndef Py_LIMITED_API Py_DEPRECATED(3.3) PyAPI_FUNC(PyObject *) PyLong_FromUnicode(Py_UNICODE*, Py_ssize_t, int); PyAPI_FUNC(PyObject *) PyLong_FromUnicodeObject(PyObject *u, int base); PyAPI_FUNC(PyObject *) _PyLong_FromBytes(const char *, Py_ssize_t, int); #endif #ifndef Py_LIMITED_API /* _PyLong_Sign. Return 0 if v is 0, -1 if v < 0, +1 if v > 0. v must not be NULL, and must be a normalized long. There are no error cases. */ PyAPI_FUNC(int) _PyLong_Sign(PyObject *v); /* _PyLong_NumBits. Return the number of bits needed to represent the absolute value of a long. For example, this returns 1 for 1 and -1, 2 for 2 and -2, and 2 for 3 and -3. It returns 0 for 0. v must not be NULL, and must be a normalized long. (size_t)-1 is returned and OverflowError set if the true result doesn't fit in a size_t. */ PyAPI_FUNC(size_t) _PyLong_NumBits(PyObject *v); /* _PyLong_DivmodNear. Given integers a and b, compute the nearest integer q to the exact quotient a / b, rounding to the nearest even integer in the case of a tie. Return (q, r), where r = a - q*b. The remainder r will satisfy abs(r) <= abs(b)/2, with equality possible only if q is even. */ PyAPI_FUNC(PyObject *) _PyLong_DivmodNear(PyObject *, PyObject *); /* _PyLong_FromByteArray: View the n unsigned bytes as a binary integer in base 256, and return a Python int with the same numeric value. If n is 0, the integer is 0. Else: If little_endian is 1/true, bytes[n-1] is the MSB and bytes[0] the LSB; else (little_endian is 0/false) bytes[0] is the MSB and bytes[n-1] the LSB. If is_signed is 0/false, view the bytes as a non-negative integer. If is_signed is 1/true, view the bytes as a 2's-complement integer, non-negative if bit 0x80 of the MSB is clear, negative if set. Error returns: + Return NULL with the appropriate exception set if there's not enough memory to create the Python int. */ PyAPI_FUNC(PyObject *) _PyLong_FromByteArray( const unsigned char* bytes, size_t n, int little_endian, int is_signed); /* _PyLong_AsByteArray: Convert the least-significant 8*n bits of long v to a base-256 integer, stored in array bytes. Normally return 0, return -1 on error. If little_endian is 1/true, store the MSB at bytes[n-1] and the LSB at bytes[0]; else (little_endian is 0/false) store the MSB at bytes[0] and the LSB at bytes[n-1]. If is_signed is 0/false, it's an error if v < 0; else (v >= 0) n bytes are filled and there's nothing special about bit 0x80 of the MSB. If is_signed is 1/true, bytes is filled with the 2's-complement representation of v's value. Bit 0x80 of the MSB is the sign bit. Error returns (-1): + is_signed is 0 and v < 0. TypeError is set in this case, and bytes isn't altered. + n isn't big enough to hold the full mathematical value of v. For example, if is_signed is 0 and there are more digits in the v than fit in n; or if is_signed is 1, v < 0, and n is just 1 bit shy of being large enough to hold a sign bit. OverflowError is set in this case, but bytes holds the least-significant n bytes of the true value. */ PyAPI_FUNC(int) _PyLong_AsByteArray(PyLongObject* v, unsigned char* bytes, size_t n, int little_endian, int is_signed); /* _PyLong_FromNbInt: Convert the given object to a PyLongObject using the nb_int slot, if available. Raise TypeError if either the nb_int slot is not available or the result of the call to nb_int returns something not of type int. */ PyAPI_FUNC(PyObject *) _PyLong_FromNbInt(PyObject *); /* Convert the given object to a PyLongObject using the nb_index or nb_int slots, if available (the latter is deprecated). Raise TypeError if either nb_index and nb_int slots are not available or the result of the call to nb_index or nb_int returns something not of type int. Should be replaced with PyNumber_Index after the end of the deprecation period. */ PyAPI_FUNC(PyObject *) _PyLong_FromNbIndexOrNbInt(PyObject *); /* _PyLong_Format: Convert the long to a string object with given base, appending a base prefix of 0[box] if base is 2, 8 or 16. */ PyAPI_FUNC(PyObject *) _PyLong_Format(PyObject *obj, int base); PyAPI_FUNC(int) _PyLong_FormatWriter( _PyUnicodeWriter *writer, PyObject *obj, int base, int alternate); PyAPI_FUNC(char*) _PyLong_FormatBytesWriter( _PyBytesWriter *writer, char *str, PyObject *obj, int base, int alternate); /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ PyAPI_FUNC(int) _PyLong_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); #endif /* Py_LIMITED_API */ /* These aren't really part of the int object, but they're handy. The functions are in Python/mystrtoul.c. */ PyAPI_FUNC(unsigned long) PyOS_strtoul(const char *, char **, int); PyAPI_FUNC(long) PyOS_strtol(const char *, char **, int); #ifndef Py_LIMITED_API /* For use by the gcd function in mathmodule.c */ PyAPI_FUNC(PyObject *) _PyLong_GCD(PyObject *, PyObject *); #endif /* !Py_LIMITED_API */ #ifndef Py_LIMITED_API PyAPI_DATA(PyObject *) _PyLong_Zero; PyAPI_DATA(PyObject *) _PyLong_One; PyAPI_FUNC(PyObject *) _PyLong_Rshift(PyObject *, size_t); PyAPI_FUNC(PyObject *) _PyLong_Lshift(PyObject *, size_t); #endif #ifdef __cplusplus } #endif #endif /* !Py_LONGOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/marshal.h ================================================ /* Interface for marshal.c */ #ifndef Py_MARSHAL_H #define Py_MARSHAL_H #ifdef __cplusplus extern "C" { #endif #define Py_MARSHAL_VERSION 4 PyAPI_FUNC(void) PyMarshal_WriteLongToFile(long, FILE *, int); PyAPI_FUNC(void) PyMarshal_WriteObjectToFile(PyObject *, FILE *, int); PyAPI_FUNC(PyObject *) PyMarshal_WriteObjectToString(PyObject *, int); #ifndef Py_LIMITED_API PyAPI_FUNC(long) PyMarshal_ReadLongFromFile(FILE *); PyAPI_FUNC(int) PyMarshal_ReadShortFromFile(FILE *); PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromFile(FILE *); PyAPI_FUNC(PyObject *) PyMarshal_ReadLastObjectFromFile(FILE *); #endif PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromString(const char *, Py_ssize_t); #ifdef __cplusplus } #endif #endif /* !Py_MARSHAL_H */ ================================================ FILE: thirdLibs/python3_8/include/memoryobject.h ================================================ /* Memory view object. In Python this is available as "memoryview". */ #ifndef Py_MEMORYOBJECT_H #define Py_MEMORYOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API PyAPI_DATA(PyTypeObject) _PyManagedBuffer_Type; #endif PyAPI_DATA(PyTypeObject) PyMemoryView_Type; #define PyMemoryView_Check(op) (Py_TYPE(op) == &PyMemoryView_Type) #ifndef Py_LIMITED_API /* Get a pointer to the memoryview's private copy of the exporter's buffer. */ #define PyMemoryView_GET_BUFFER(op) (&((PyMemoryViewObject *)(op))->view) /* Get a pointer to the exporting object (this may be NULL!). */ #define PyMemoryView_GET_BASE(op) (((PyMemoryViewObject *)(op))->view.obj) #endif PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags); #endif #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) PyMemoryView_FromBuffer(Py_buffer *info); #endif PyAPI_FUNC(PyObject *) PyMemoryView_GetContiguous(PyObject *base, int buffertype, char order); /* The structs are declared here so that macros can work, but they shouldn't be considered public. Don't access their fields directly, use the macros and functions instead! */ #ifndef Py_LIMITED_API #define _Py_MANAGED_BUFFER_RELEASED 0x001 /* access to exporter blocked */ #define _Py_MANAGED_BUFFER_FREE_FORMAT 0x002 /* free format */ typedef struct { PyObject_HEAD int flags; /* state flags */ Py_ssize_t exports; /* number of direct memoryview exports */ Py_buffer master; /* snapshot buffer obtained from the original exporter */ } _PyManagedBufferObject; /* memoryview state flags */ #define _Py_MEMORYVIEW_RELEASED 0x001 /* access to master buffer blocked */ #define _Py_MEMORYVIEW_C 0x002 /* C-contiguous layout */ #define _Py_MEMORYVIEW_FORTRAN 0x004 /* Fortran contiguous layout */ #define _Py_MEMORYVIEW_SCALAR 0x008 /* scalar: ndim = 0 */ #define _Py_MEMORYVIEW_PIL 0x010 /* PIL-style layout */ typedef struct { PyObject_VAR_HEAD _PyManagedBufferObject *mbuf; /* managed buffer */ Py_hash_t hash; /* hash value for read-only views */ int flags; /* state flags */ Py_ssize_t exports; /* number of buffer re-exports */ Py_buffer view; /* private copy of the exporter's view */ PyObject *weakreflist; Py_ssize_t ob_array[1]; /* shape, strides, suboffsets */ } PyMemoryViewObject; #endif #ifdef __cplusplus } #endif #endif /* !Py_MEMORYOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/methodobject.h ================================================ /* Method object interface */ #ifndef Py_METHODOBJECT_H #define Py_METHODOBJECT_H #ifdef __cplusplus extern "C" { #endif /* This is about the type 'builtin_function_or_method', not Python methods in user-defined classes. See classobject.h for the latter. */ PyAPI_DATA(PyTypeObject) PyCFunction_Type; #define PyCFunction_Check(op) (Py_TYPE(op) == &PyCFunction_Type) typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); typedef PyObject *(*_PyCFunctionFast) (PyObject *, PyObject *const *, Py_ssize_t); typedef PyObject *(*PyCFunctionWithKeywords)(PyObject *, PyObject *, PyObject *); typedef PyObject *(*_PyCFunctionFastWithKeywords) (PyObject *, PyObject *const *, Py_ssize_t, PyObject *); typedef PyObject *(*PyNoArgsFunction)(PyObject *); PyAPI_FUNC(PyCFunction) PyCFunction_GetFunction(PyObject *); PyAPI_FUNC(PyObject *) PyCFunction_GetSelf(PyObject *); PyAPI_FUNC(int) PyCFunction_GetFlags(PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #ifndef Py_LIMITED_API #define PyCFunction_GET_FUNCTION(func) \ (((PyCFunctionObject *)func) -> m_ml -> ml_meth) #define PyCFunction_GET_SELF(func) \ (((PyCFunctionObject *)func) -> m_ml -> ml_flags & METH_STATIC ? \ NULL : ((PyCFunctionObject *)func) -> m_self) #define PyCFunction_GET_FLAGS(func) \ (((PyCFunctionObject *)func) -> m_ml -> ml_flags) #endif PyAPI_FUNC(PyObject *) PyCFunction_Call(PyObject *, PyObject *, PyObject *); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyCFunction_FastCallDict(PyObject *func, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs); #endif struct PyMethodDef { const char *ml_name; /* The name of the built-in function/method */ PyCFunction ml_meth; /* The C function that implements it */ int ml_flags; /* Combination of METH_xxx flags, which mostly describe the args expected by the C func */ const char *ml_doc; /* The __doc__ attribute, or NULL */ }; typedef struct PyMethodDef PyMethodDef; #define PyCFunction_New(ML, SELF) PyCFunction_NewEx((ML), (SELF), NULL) PyAPI_FUNC(PyObject *) PyCFunction_NewEx(PyMethodDef *, PyObject *, PyObject *); /* Flag passed to newmethodobject */ /* #define METH_OLDARGS 0x0000 -- unsupported now */ #define METH_VARARGS 0x0001 #define METH_KEYWORDS 0x0002 /* METH_NOARGS and METH_O must not be combined with the flags above. */ #define METH_NOARGS 0x0004 #define METH_O 0x0008 /* METH_CLASS and METH_STATIC are a little different; these control the construction of methods for a class. These cannot be used for functions in modules. */ #define METH_CLASS 0x0010 #define METH_STATIC 0x0020 /* METH_COEXIST allows a method to be entered even though a slot has already filled the entry. When defined, the flag allows a separate method, "__contains__" for example, to coexist with a defined slot like sq_contains. */ #define METH_COEXIST 0x0040 #ifndef Py_LIMITED_API #define METH_FASTCALL 0x0080 #endif /* This bit is preserved for Stackless Python */ #ifdef STACKLESS #define METH_STACKLESS 0x0100 #else #define METH_STACKLESS 0x0000 #endif #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD PyMethodDef *m_ml; /* Description of the C function to call */ PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */ PyObject *m_module; /* The __module__ attribute, can be anything */ PyObject *m_weakreflist; /* List of weak references */ vectorcallfunc vectorcall; } PyCFunctionObject; PyAPI_FUNC(PyObject *) _PyMethodDef_RawFastCallDict( PyMethodDef *method, PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs); PyAPI_FUNC(PyObject *) _PyMethodDef_RawFastCallKeywords( PyMethodDef *method, PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames); #endif PyAPI_FUNC(int) PyCFunction_ClearFreeList(void); #ifndef Py_LIMITED_API PyAPI_FUNC(void) _PyCFunction_DebugMallocStats(FILE *out); PyAPI_FUNC(void) _PyMethod_DebugMallocStats(FILE *out); #endif #ifdef __cplusplus } #endif #endif /* !Py_METHODOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/modsupport.h ================================================ #ifndef Py_MODSUPPORT_H #define Py_MODSUPPORT_H #ifdef __cplusplus extern "C" { #endif /* Module support interface */ #include /* If PY_SSIZE_T_CLEAN is defined, each functions treats #-specifier to mean Py_ssize_t */ #ifdef PY_SSIZE_T_CLEAN #define PyArg_Parse _PyArg_Parse_SizeT #define PyArg_ParseTuple _PyArg_ParseTuple_SizeT #define PyArg_ParseTupleAndKeywords _PyArg_ParseTupleAndKeywords_SizeT #define PyArg_VaParse _PyArg_VaParse_SizeT #define PyArg_VaParseTupleAndKeywords _PyArg_VaParseTupleAndKeywords_SizeT #define Py_BuildValue _Py_BuildValue_SizeT #define Py_VaBuildValue _Py_VaBuildValue_SizeT #ifndef Py_LIMITED_API #define _Py_VaBuildStack _Py_VaBuildStack_SizeT #endif #else #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _Py_VaBuildValue_SizeT(const char *, va_list); PyAPI_FUNC(PyObject **) _Py_VaBuildStack_SizeT( PyObject **small_stack, Py_ssize_t small_stack_len, const char *format, va_list va, Py_ssize_t *p_nargs); #endif /* !Py_LIMITED_API */ #endif /* Due to a glitch in 3.2, the _SizeT versions weren't exported from the DLL. */ #if !defined(PY_SSIZE_T_CLEAN) || !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(int) PyArg_Parse(PyObject *, const char *, ...); PyAPI_FUNC(int) PyArg_ParseTuple(PyObject *, const char *, ...); PyAPI_FUNC(int) PyArg_ParseTupleAndKeywords(PyObject *, PyObject *, const char *, char **, ...); PyAPI_FUNC(int) PyArg_VaParse(PyObject *, const char *, va_list); PyAPI_FUNC(int) PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *, const char *, char **, va_list); #endif PyAPI_FUNC(int) PyArg_ValidateKeywordArguments(PyObject *); PyAPI_FUNC(int) PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...); PyAPI_FUNC(PyObject *) Py_BuildValue(const char *, ...); PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...); #ifndef Py_LIMITED_API PyAPI_FUNC(int) _PyArg_UnpackStack( PyObject *const *args, Py_ssize_t nargs, const char *name, Py_ssize_t min, Py_ssize_t max, ...); PyAPI_FUNC(int) _PyArg_NoKeywords(const char *funcname, PyObject *kwargs); PyAPI_FUNC(int) _PyArg_NoPositional(const char *funcname, PyObject *args); #define _PyArg_NoKeywords(funcname, kwargs) \ ((kwargs) == NULL || _PyArg_NoKeywords((funcname), (kwargs))) #define _PyArg_NoPositional(funcname, args) \ ((args) == NULL || _PyArg_NoPositional((funcname), (args))) PyAPI_FUNC(void) _PyArg_BadArgument(const char *, const char *, const char *, PyObject *); PyAPI_FUNC(int) _PyArg_CheckPositional(const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t); #define _PyArg_CheckPositional(funcname, nargs, min, max) \ (((min) <= (nargs) && (nargs) <= (max)) \ || _PyArg_CheckPositional((funcname), (nargs), (min), (max))) #endif PyAPI_FUNC(PyObject *) Py_VaBuildValue(const char *, va_list); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject **) _Py_VaBuildStack( PyObject **small_stack, Py_ssize_t small_stack_len, const char *format, va_list va, Py_ssize_t *p_nargs); #endif #ifndef Py_LIMITED_API typedef struct _PyArg_Parser { const char *format; const char * const *keywords; const char *fname; const char *custom_msg; int pos; /* number of positional-only arguments */ int min; /* minimal number of arguments */ int max; /* maximal number of positional arguments */ PyObject *kwtuple; /* tuple of keyword parameter names */ struct _PyArg_Parser *next; } _PyArg_Parser; #ifdef PY_SSIZE_T_CLEAN #define _PyArg_ParseTupleAndKeywordsFast _PyArg_ParseTupleAndKeywordsFast_SizeT #define _PyArg_ParseStack _PyArg_ParseStack_SizeT #define _PyArg_ParseStackAndKeywords _PyArg_ParseStackAndKeywords_SizeT #define _PyArg_VaParseTupleAndKeywordsFast _PyArg_VaParseTupleAndKeywordsFast_SizeT #endif PyAPI_FUNC(int) _PyArg_ParseTupleAndKeywordsFast(PyObject *, PyObject *, struct _PyArg_Parser *, ...); PyAPI_FUNC(int) _PyArg_ParseStack( PyObject *const *args, Py_ssize_t nargs, const char *format, ...); PyAPI_FUNC(int) _PyArg_ParseStackAndKeywords( PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames, struct _PyArg_Parser *, ...); PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywordsFast(PyObject *, PyObject *, struct _PyArg_Parser *, va_list); PyAPI_FUNC(PyObject * const *) _PyArg_UnpackKeywords( PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs, PyObject *kwnames, struct _PyArg_Parser *parser, int minpos, int maxpos, int minkw, PyObject **buf); #define _PyArg_UnpackKeywords(args, nargs, kwargs, kwnames, parser, minpos, maxpos, minkw, buf) \ (((minkw) == 0 && (kwargs) == NULL && (kwnames) == NULL && \ (minpos) <= (nargs) && (nargs) <= (maxpos) && args != NULL) ? (args) : \ _PyArg_UnpackKeywords((args), (nargs), (kwargs), (kwnames), (parser), \ (minpos), (maxpos), (minkw), (buf))) void _PyArg_Fini(void); #endif /* Py_LIMITED_API */ PyAPI_FUNC(int) PyModule_AddObject(PyObject *, const char *, PyObject *); PyAPI_FUNC(int) PyModule_AddIntConstant(PyObject *, const char *, long); PyAPI_FUNC(int) PyModule_AddStringConstant(PyObject *, const char *, const char *); #define PyModule_AddIntMacro(m, c) PyModule_AddIntConstant(m, #c, c) #define PyModule_AddStringMacro(m, c) PyModule_AddStringConstant(m, #c, c) #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ PyAPI_FUNC(int) PyModule_SetDocString(PyObject *, const char *); PyAPI_FUNC(int) PyModule_AddFunctions(PyObject *, PyMethodDef *); PyAPI_FUNC(int) PyModule_ExecDef(PyObject *module, PyModuleDef *def); #endif #define Py_CLEANUP_SUPPORTED 0x20000 #define PYTHON_API_VERSION 1013 #define PYTHON_API_STRING "1013" /* The API version is maintained (independently from the Python version) so we can detect mismatches between the interpreter and dynamically loaded modules. These are diagnosed by an error message but the module is still loaded (because the mismatch can only be tested after loading the module). The error message is intended to explain the core dump a few seconds later. The symbol PYTHON_API_STRING defines the same value as a string literal. *** PLEASE MAKE SURE THE DEFINITIONS MATCH. *** Please add a line or two to the top of this log for each API version change: 22-Feb-2006 MvL 1013 PEP 353 - long indices for sequence lengths 19-Aug-2002 GvR 1012 Changes to string object struct for interning changes, saving 3 bytes. 17-Jul-2001 GvR 1011 Descr-branch, just to be on the safe side 25-Jan-2001 FLD 1010 Parameters added to PyCode_New() and PyFrame_New(); Python 2.1a2 14-Mar-2000 GvR 1009 Unicode API added 3-Jan-1999 GvR 1007 Decided to change back! (Don't reuse 1008!) 3-Dec-1998 GvR 1008 Python 1.5.2b1 18-Jan-1997 GvR 1007 string interning and other speedups 11-Oct-1996 GvR renamed Py_Ellipses to Py_Ellipsis :-( 30-Jul-1996 GvR Slice and ellipses syntax added 23-Jul-1996 GvR For 1.4 -- better safe than sorry this time :-) 7-Nov-1995 GvR Keyword arguments (should've been done at 1.3 :-( ) 10-Jan-1995 GvR Renamed globals to new naming scheme 9-Jan-1995 GvR Initial version (incompatible with older API) */ /* The PYTHON_ABI_VERSION is introduced in PEP 384. For the lifetime of Python 3, it will stay at the value of 3; changes to the limited API must be performed in a strictly backwards-compatible manner. */ #define PYTHON_ABI_VERSION 3 #define PYTHON_ABI_STRING "3" #ifdef Py_TRACE_REFS /* When we are tracing reference counts, rename module creation functions so modules compiled with incompatible settings will generate a link-time error. */ #define PyModule_Create2 PyModule_Create2TraceRefs #define PyModule_FromDefAndSpec2 PyModule_FromDefAndSpec2TraceRefs #endif PyAPI_FUNC(PyObject *) PyModule_Create2(struct PyModuleDef*, int apiver); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PyModule_CreateInitialized(struct PyModuleDef*, int apiver); #endif #ifdef Py_LIMITED_API #define PyModule_Create(module) \ PyModule_Create2(module, PYTHON_ABI_VERSION) #else #define PyModule_Create(module) \ PyModule_Create2(module, PYTHON_API_VERSION) #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ PyAPI_FUNC(PyObject *) PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version); #ifdef Py_LIMITED_API #define PyModule_FromDefAndSpec(module, spec) \ PyModule_FromDefAndSpec2(module, spec, PYTHON_ABI_VERSION) #else #define PyModule_FromDefAndSpec(module, spec) \ PyModule_FromDefAndSpec2(module, spec, PYTHON_API_VERSION) #endif /* Py_LIMITED_API */ #endif /* New in 3.5 */ #ifndef Py_LIMITED_API PyAPI_DATA(const char *) _Py_PackageContext; #endif #ifdef __cplusplus } #endif #endif /* !Py_MODSUPPORT_H */ ================================================ FILE: thirdLibs/python3_8/include/moduleobject.h ================================================ /* Module object interface */ #ifndef Py_MODULEOBJECT_H #define Py_MODULEOBJECT_H #ifdef __cplusplus extern "C" { #endif PyAPI_DATA(PyTypeObject) PyModule_Type; #define PyModule_Check(op) PyObject_TypeCheck(op, &PyModule_Type) #define PyModule_CheckExact(op) (Py_TYPE(op) == &PyModule_Type) #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject *) PyModule_NewObject( PyObject *name ); #endif PyAPI_FUNC(PyObject *) PyModule_New( const char *name /* UTF-8 encoded string */ ); PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject *) PyModule_GetNameObject(PyObject *); #endif PyAPI_FUNC(const char *) PyModule_GetName(PyObject *); Py_DEPRECATED(3.2) PyAPI_FUNC(const char *) PyModule_GetFilename(PyObject *); PyAPI_FUNC(PyObject *) PyModule_GetFilenameObject(PyObject *); #ifndef Py_LIMITED_API PyAPI_FUNC(void) _PyModule_Clear(PyObject *); PyAPI_FUNC(void) _PyModule_ClearDict(PyObject *); PyAPI_FUNC(int) _PyModuleSpec_IsInitializing(PyObject *); #endif PyAPI_FUNC(struct PyModuleDef*) PyModule_GetDef(PyObject*); PyAPI_FUNC(void*) PyModule_GetState(PyObject*); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ PyAPI_FUNC(PyObject *) PyModuleDef_Init(struct PyModuleDef*); PyAPI_DATA(PyTypeObject) PyModuleDef_Type; #endif typedef struct PyModuleDef_Base { PyObject_HEAD PyObject* (*m_init)(void); Py_ssize_t m_index; PyObject* m_copy; } PyModuleDef_Base; #define PyModuleDef_HEAD_INIT { \ PyObject_HEAD_INIT(NULL) \ NULL, /* m_init */ \ 0, /* m_index */ \ NULL, /* m_copy */ \ } struct PyModuleDef_Slot; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ typedef struct PyModuleDef_Slot{ int slot; void *value; } PyModuleDef_Slot; #define Py_mod_create 1 #define Py_mod_exec 2 #ifndef Py_LIMITED_API #define _Py_mod_LAST_SLOT 2 #endif #endif /* New in 3.5 */ typedef struct PyModuleDef{ PyModuleDef_Base m_base; const char* m_name; const char* m_doc; Py_ssize_t m_size; PyMethodDef *m_methods; struct PyModuleDef_Slot* m_slots; traverseproc m_traverse; inquiry m_clear; freefunc m_free; } PyModuleDef; #ifdef __cplusplus } #endif #endif /* !Py_MODULEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/namespaceobject.h ================================================ /* simple namespace object interface */ #ifndef NAMESPACEOBJECT_H #define NAMESPACEOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API PyAPI_DATA(PyTypeObject) _PyNamespace_Type; PyAPI_FUNC(PyObject *) _PyNamespace_New(PyObject *kwds); #endif /* !Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !NAMESPACEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/node.h ================================================ /* Parse tree node interface */ #ifndef Py_NODE_H #define Py_NODE_H #ifdef __cplusplus extern "C" { #endif typedef struct _node { short n_type; char *n_str; int n_lineno; int n_col_offset; int n_nchildren; struct _node *n_child; int n_end_lineno; int n_end_col_offset; } node; PyAPI_FUNC(node *) PyNode_New(int type); PyAPI_FUNC(int) PyNode_AddChild(node *n, int type, char *str, int lineno, int col_offset, int end_lineno, int end_col_offset); PyAPI_FUNC(void) PyNode_Free(node *n); #ifndef Py_LIMITED_API PyAPI_FUNC(Py_ssize_t) _PyNode_SizeOf(node *n); #endif /* Node access functions */ #define NCH(n) ((n)->n_nchildren) #define CHILD(n, i) (&(n)->n_child[i]) #define RCHILD(n, i) (CHILD(n, NCH(n) + i)) #define TYPE(n) ((n)->n_type) #define STR(n) ((n)->n_str) #define LINENO(n) ((n)->n_lineno) /* Assert that the type of a node is what we expect */ #define REQ(n, type) assert(TYPE(n) == (type)) PyAPI_FUNC(void) PyNode_ListTree(node *); void _PyNode_FinalizeEndPos(node *n); // helper also used in parsetok.c #ifdef __cplusplus } #endif #endif /* !Py_NODE_H */ ================================================ FILE: thirdLibs/python3_8/include/object.h ================================================ #ifndef Py_OBJECT_H #define Py_OBJECT_H #include "pymem.h" /* _Py_tracemalloc_config */ #ifdef __cplusplus extern "C" { #endif /* Object and type object interface */ /* Objects are structures allocated on the heap. Special rules apply to the use of objects to ensure they are properly garbage-collected. Objects are never allocated statically or on the stack; they must be accessed through special macros and functions only. (Type objects are exceptions to the first rule; the standard types are represented by statically initialized type objects, although work on type/class unification for Python 2.2 made it possible to have heap-allocated type objects too). An object has a 'reference count' that is increased or decreased when a pointer to the object is copied or deleted; when the reference count reaches zero there are no references to the object left and it can be removed from the heap. An object has a 'type' that determines what it represents and what kind of data it contains. An object's type is fixed when it is created. Types themselves are represented as objects; an object contains a pointer to the corresponding type object. The type itself has a type pointer pointing to the object representing the type 'type', which contains a pointer to itself!). Objects do not float around in memory; once allocated an object keeps the same size and address. Objects that must hold variable-size data can contain pointers to variable-size parts of the object. Not all objects of the same type have the same size; but the size cannot change after allocation. (These restrictions are made so a reference to an object can be simply a pointer -- moving an object would require updating all the pointers, and changing an object's size would require moving it if there was another object right next to it.) Objects are always accessed through pointers of the type 'PyObject *'. The type 'PyObject' is a structure that only contains the reference count and the type pointer. The actual memory allocated for an object contains other data that can only be accessed after casting the pointer to a pointer to a longer structure type. This longer type must start with the reference count and type fields; the macro PyObject_HEAD should be used for this (to accommodate for future changes). The implementation of a particular object type can cast the object pointer to the proper type and back. A standard interface exists for objects that contain an array of items whose size is determined when the object is allocated. */ /* Py_DEBUG implies Py_REF_DEBUG. */ #if defined(Py_DEBUG) && !defined(Py_REF_DEBUG) #define Py_REF_DEBUG #endif #if defined(Py_LIMITED_API) && defined(Py_REF_DEBUG) #error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG #endif #ifdef Py_TRACE_REFS /* Define pointers to support a doubly-linked list of all live heap objects. */ #define _PyObject_HEAD_EXTRA \ struct _object *_ob_next; \ struct _object *_ob_prev; #define _PyObject_EXTRA_INIT 0, 0, #else #define _PyObject_HEAD_EXTRA #define _PyObject_EXTRA_INIT #endif /* PyObject_HEAD defines the initial segment of every PyObject. */ #define PyObject_HEAD PyObject ob_base; #define PyObject_HEAD_INIT(type) \ { _PyObject_EXTRA_INIT \ 1, type }, #define PyVarObject_HEAD_INIT(type, size) \ { PyObject_HEAD_INIT(type) size }, /* PyObject_VAR_HEAD defines the initial segment of all variable-size * container objects. These end with a declaration of an array with 1 * element, but enough space is malloc'ed so that the array actually * has room for ob_size elements. Note that ob_size is an element count, * not necessarily a byte count. */ #define PyObject_VAR_HEAD PyVarObject ob_base; #define Py_INVALID_SIZE (Py_ssize_t)-1 /* Nothing is actually declared to be a PyObject, but every pointer to * a Python object can be cast to a PyObject*. This is inheritance built * by hand. Similarly every pointer to a variable-size Python object can, * in addition, be cast to PyVarObject*. */ typedef struct _object { _PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt; struct _typeobject *ob_type; } PyObject; /* Cast argument to PyObject* type. */ #define _PyObject_CAST(op) ((PyObject*)(op)) typedef struct { PyObject ob_base; Py_ssize_t ob_size; /* Number of items in variable part */ } PyVarObject; /* Cast argument to PyVarObject* type. */ #define _PyVarObject_CAST(op) ((PyVarObject*)(op)) #define Py_REFCNT(ob) (_PyObject_CAST(ob)->ob_refcnt) #define Py_TYPE(ob) (_PyObject_CAST(ob)->ob_type) #define Py_SIZE(ob) (_PyVarObject_CAST(ob)->ob_size) /* Type objects contain a string containing the type name (to help somewhat in debugging), the allocation parameters (see PyObject_New() and PyObject_NewVar()), and methods for accessing objects of the type. Methods are optional, a nil pointer meaning that particular kind of access is not available for this type. The Py_DECREF() macro uses the tp_dealloc method without checking for a nil pointer; it should always be implemented except if the implementation can guarantee that the reference count will never reach zero (e.g., for statically allocated type objects). NB: the methods for certain type groups are now contained in separate method blocks. */ typedef PyObject * (*unaryfunc)(PyObject *); typedef PyObject * (*binaryfunc)(PyObject *, PyObject *); typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *); typedef int (*inquiry)(PyObject *); typedef Py_ssize_t (*lenfunc)(PyObject *); typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t); typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t); typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *); typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *); typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *); typedef int (*objobjproc)(PyObject *, PyObject *); typedef int (*visitproc)(PyObject *, void *); typedef int (*traverseproc)(PyObject *, visitproc, void *); typedef void (*freefunc)(void *); typedef void (*destructor)(PyObject *); typedef PyObject *(*getattrfunc)(PyObject *, char *); typedef PyObject *(*getattrofunc)(PyObject *, PyObject *); typedef int (*setattrfunc)(PyObject *, char *, PyObject *); typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *); typedef PyObject *(*reprfunc)(PyObject *); typedef Py_hash_t (*hashfunc)(PyObject *); typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int); typedef PyObject *(*getiterfunc) (PyObject *); typedef PyObject *(*iternextfunc) (PyObject *); typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *); typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *); typedef int (*initproc)(PyObject *, PyObject *, PyObject *); typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *); typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t); #ifdef Py_LIMITED_API /* In Py_LIMITED_API, PyTypeObject is an opaque structure. */ typedef struct _typeobject PyTypeObject; #else /* PyTypeObject is defined in cpython/object.h */ #endif typedef struct{ int slot; /* slot id, see below */ void *pfunc; /* function pointer */ } PyType_Slot; typedef struct{ const char* name; int basicsize; int itemsize; unsigned int flags; PyType_Slot *slots; /* terminated by slot==0. */ } PyType_Spec; PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject*) PyType_FromSpecWithBases(PyType_Spec*, PyObject*); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000 PyAPI_FUNC(void*) PyType_GetSlot(struct _typeobject*, int); #endif /* Generic type check */ PyAPI_FUNC(int) PyType_IsSubtype(struct _typeobject *, struct _typeobject *); #define PyObject_TypeCheck(ob, tp) \ (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) PyAPI_DATA(struct _typeobject) PyType_Type; /* built-in 'type' */ PyAPI_DATA(struct _typeobject) PyBaseObject_Type; /* built-in 'object' */ PyAPI_DATA(struct _typeobject) PySuper_Type; /* built-in 'super' */ PyAPI_FUNC(unsigned long) PyType_GetFlags(struct _typeobject*); #define PyType_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type) PyAPI_FUNC(int) PyType_Ready(struct _typeobject *); PyAPI_FUNC(PyObject *) PyType_GenericAlloc(struct _typeobject *, Py_ssize_t); PyAPI_FUNC(PyObject *) PyType_GenericNew(struct _typeobject *, PyObject *, PyObject *); PyAPI_FUNC(unsigned int) PyType_ClearCache(void); PyAPI_FUNC(void) PyType_Modified(struct _typeobject *); /* Generic operations on objects */ PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *); PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *); PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *); PyAPI_FUNC(PyObject *) PyObject_Bytes(PyObject *); PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int); PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int); PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *); PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *); PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *); PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *); PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *); PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(int) PyObject_GenericSetDict(PyObject *, PyObject *, void *); #endif PyAPI_FUNC(Py_hash_t) PyObject_Hash(PyObject *); PyAPI_FUNC(Py_hash_t) PyObject_HashNotImplemented(PyObject *); PyAPI_FUNC(int) PyObject_IsTrue(PyObject *); PyAPI_FUNC(int) PyObject_Not(PyObject *); PyAPI_FUNC(int) PyCallable_Check(PyObject *); PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *); /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a list of strings. PyObject_Dir(NULL) is like builtins.dir(), returning the names of the current locals. In this case, if there are no current locals, NULL is returned, and PyErr_Occurred() is false. */ PyAPI_FUNC(PyObject *) PyObject_Dir(PyObject *); /* Helpers for printing recursive container types */ PyAPI_FUNC(int) Py_ReprEnter(PyObject *); PyAPI_FUNC(void) Py_ReprLeave(PyObject *); /* Flag bits for printing: */ #define Py_PRINT_RAW 1 /* No string quotes etc. */ /* Type flags (tp_flags) These flags are used to change expected features and behavior for a particular type. Arbitration of the flag bit positions will need to be coordinated among all extension writers who publicly release their extensions (this will be fewer than you might expect!). Most flags were removed as of Python 3.0 to make room for new flags. (Some flags are not for backwards compatibility but to indicate the presence of an optional feature; these flags remain of course.) Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value. Code can use PyType_HasFeature(type_ob, flag_value) to test whether the given type object has a specified feature. */ /* Set if the type object is dynamically allocated */ #define Py_TPFLAGS_HEAPTYPE (1UL << 9) /* Set if the type allows subclassing */ #define Py_TPFLAGS_BASETYPE (1UL << 10) /* Set if the type implements the vectorcall protocol (PEP 590) */ #ifndef Py_LIMITED_API #define _Py_TPFLAGS_HAVE_VECTORCALL (1UL << 11) #endif /* Set if the type is 'ready' -- fully initialized */ #define Py_TPFLAGS_READY (1UL << 12) /* Set while the type is being 'readied', to prevent recursive ready calls */ #define Py_TPFLAGS_READYING (1UL << 13) /* Objects support garbage collection (see objimpl.h) */ #define Py_TPFLAGS_HAVE_GC (1UL << 14) /* These two bits are preserved for Stackless Python, next after this is 17 */ #ifdef STACKLESS #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15) #else #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0 #endif /* Objects behave like an unbound method */ #define Py_TPFLAGS_METHOD_DESCRIPTOR (1UL << 17) /* Objects support type attribute cache */ #define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18) #define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19) /* Type is abstract and cannot be instantiated */ #define Py_TPFLAGS_IS_ABSTRACT (1UL << 20) /* These flags are used to determine if a type is a subclass. */ #define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24) #define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25) #define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26) #define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27) #define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28) #define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29) #define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30) #define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31) #define Py_TPFLAGS_DEFAULT ( \ Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ Py_TPFLAGS_HAVE_VERSION_TAG | \ 0) /* NOTE: The following flags reuse lower bits (removed as part of the * Python 3.0 transition). */ /* The following flag is kept for compatibility. Starting with 3.8, * binary compatibility of C extensions accross feature releases of * Python is not supported anymore, except when using the stable ABI. */ /* Type structure has tp_finalize member (3.4) */ #define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0) #ifdef Py_LIMITED_API # define PyType_HasFeature(t,f) ((PyType_GetFlags(t) & (f)) != 0) #endif #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) /* The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement reference counts. Py_DECREF calls the object's deallocator function when the refcount falls to 0; for objects that don't contain references to other objects or heap memory this can be the standard function free(). Both macros can be used wherever a void expression is allowed. The argument must not be a NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead. The macro _Py_NewReference(op) initialize reference counts to 1, and in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional bookkeeping appropriate to the special build. We assume that the reference count field can never overflow; this can be proven when the size of the field is the same as the pointer size, so we ignore the possibility. Provided a C int is at least 32 bits (which is implicitly assumed in many parts of this code), that's enough for about 2**31 references to an object. XXX The following became out of date in Python 2.2, but I'm not sure XXX what the full truth is now. Certainly, heap-allocated type objects XXX can and should be deallocated. Type objects should never be deallocated; the type pointer in an object is not considered to be a reference to the type object, to save complications in the deallocation function. (This is actually a decision that's up to the implementer of each new type so if you want, you can count such references to the type object.) */ /* First define a pile of simple helper macros, one set per special * build symbol. These either expand to the obvious things, or to * nothing at all when the special mode isn't in effect. The main * macros can later be defined just once then, yet expand to different * things depending on which special build options are and aren't in effect. * Trust me : while painful, this is 20x easier to understand than, * e.g, defining _Py_NewReference five different times in a maze of nested * #ifdefs (we used to do that -- it was impenetrable). */ #ifdef Py_REF_DEBUG PyAPI_DATA(Py_ssize_t) _Py_RefTotal; PyAPI_FUNC(void) _Py_NegativeRefcount(const char *filename, int lineno, PyObject *op); PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void); #define _Py_INC_REFTOTAL _Py_RefTotal++ #define _Py_DEC_REFTOTAL _Py_RefTotal-- /* Py_REF_DEBUG also controls the display of refcounts and memory block * allocations at the interactive prompt and at interpreter shutdown */ PyAPI_FUNC(void) _PyDebug_PrintTotalRefs(void); #else #define _Py_INC_REFTOTAL #define _Py_DEC_REFTOTAL #endif /* Py_REF_DEBUG */ #ifdef COUNT_ALLOCS PyAPI_FUNC(void) _Py_inc_count(struct _typeobject *); PyAPI_FUNC(void) _Py_dec_count(struct _typeobject *); #define _Py_INC_TPALLOCS(OP) _Py_inc_count(Py_TYPE(OP)) #define _Py_INC_TPFREES(OP) _Py_dec_count(Py_TYPE(OP)) #define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- #define _Py_COUNT_ALLOCS_COMMA , #else #define _Py_INC_TPALLOCS(OP) #define _Py_INC_TPFREES(OP) #define _Py_DEC_TPFREES(OP) #define _Py_COUNT_ALLOCS_COMMA #endif /* COUNT_ALLOCS */ /* Update the Python traceback of an object. This function must be called when a memory block is reused from a free list. */ PyAPI_FUNC(int) _PyTraceMalloc_NewReference(PyObject *op); #ifdef Py_TRACE_REFS /* Py_TRACE_REFS is such major surgery that we call external routines. */ PyAPI_FUNC(void) _Py_NewReference(PyObject *); PyAPI_FUNC(void) _Py_ForgetReference(PyObject *); PyAPI_FUNC(void) _Py_PrintReferences(FILE *); PyAPI_FUNC(void) _Py_PrintReferenceAddresses(FILE *); PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force); #else /* Without Py_TRACE_REFS, there's little enough to do that we expand code inline. */ static inline void _Py_NewReference(PyObject *op) { if (_Py_tracemalloc_config.tracing) { _PyTraceMalloc_NewReference(op); } _Py_INC_TPALLOCS(op); _Py_INC_REFTOTAL; Py_REFCNT(op) = 1; } static inline void _Py_ForgetReference(PyObject *op) { (void)op; /* may be unused, shut up -Wunused-parameter */ _Py_INC_TPFREES(op); } #endif /* !Py_TRACE_REFS */ PyAPI_FUNC(void) _Py_Dealloc(PyObject *); static inline void _Py_INCREF(PyObject *op) { _Py_INC_REFTOTAL; op->ob_refcnt++; } #define Py_INCREF(op) _Py_INCREF(_PyObject_CAST(op)) static inline void _Py_DECREF(const char *filename, int lineno, PyObject *op) { (void)filename; /* may be unused, shut up -Wunused-parameter */ (void)lineno; /* may be unused, shut up -Wunused-parameter */ _Py_DEC_REFTOTAL; if (--op->ob_refcnt != 0) { #ifdef Py_REF_DEBUG if (op->ob_refcnt < 0) { _Py_NegativeRefcount(filename, lineno, op); } #endif } else { _Py_Dealloc(op); } } #define Py_DECREF(op) _Py_DECREF(__FILE__, __LINE__, _PyObject_CAST(op)) /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear * and tp_dealloc implementations. * * Note that "the obvious" code can be deadly: * * Py_XDECREF(op); * op = NULL; * * Typically, `op` is something like self->containee, and `self` is done * using its `containee` member. In the code sequence above, suppose * `containee` is non-NULL with a refcount of 1. Its refcount falls to * 0 on the first line, which can trigger an arbitrary amount of code, * possibly including finalizers (like __del__ methods or weakref callbacks) * coded in Python, which in turn can release the GIL and allow other threads * to run, etc. Such code may even invoke methods of `self` again, or cause * cyclic gc to trigger, but-- oops! --self->containee still points to the * object being torn down, and it may be in an insane state while being torn * down. This has in fact been a rich historic source of miserable (rare & * hard-to-diagnose) segfaulting (and other) bugs. * * The safe way is: * * Py_CLEAR(op); * * That arranges to set `op` to NULL _before_ decref'ing, so that any code * triggered as a side-effect of `op` getting torn down no longer believes * `op` points to a valid object. * * There are cases where it's safe to use the naive code, but they're brittle. * For example, if `op` points to a Python integer, you know that destroying * one of those can't cause problems -- but in part that relies on that * Python integers aren't currently weakly referencable. Best practice is * to use Py_CLEAR() even if you can't think of a reason for why you need to. */ #define Py_CLEAR(op) \ do { \ PyObject *_py_tmp = _PyObject_CAST(op); \ if (_py_tmp != NULL) { \ (op) = NULL; \ Py_DECREF(_py_tmp); \ } \ } while (0) /* Function to use in case the object pointer can be NULL: */ static inline void _Py_XINCREF(PyObject *op) { if (op != NULL) { Py_INCREF(op); } } #define Py_XINCREF(op) _Py_XINCREF(_PyObject_CAST(op)) static inline void _Py_XDECREF(PyObject *op) { if (op != NULL) { Py_DECREF(op); } } #define Py_XDECREF(op) _Py_XDECREF(_PyObject_CAST(op)) /* These are provided as conveniences to Python runtime embedders, so that they can have object code that is not dependent on Python compilation flags. */ PyAPI_FUNC(void) Py_IncRef(PyObject *); PyAPI_FUNC(void) Py_DecRef(PyObject *); /* _Py_NoneStruct is an object of undefined type which can be used in contexts where NULL (nil) is not suitable (since NULL often means 'error'). Don't forget to apply Py_INCREF() when returning this value!!! */ PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */ #define Py_None (&_Py_NoneStruct) /* Macro for returning Py_None from a function */ #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None /* Py_NotImplemented is a singleton used to signal that an operation is not implemented for a given type combination. */ PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */ #define Py_NotImplemented (&_Py_NotImplementedStruct) /* Macro for returning Py_NotImplemented from a function */ #define Py_RETURN_NOTIMPLEMENTED \ return Py_INCREF(Py_NotImplemented), Py_NotImplemented /* Rich comparison opcodes */ #define Py_LT 0 #define Py_LE 1 #define Py_EQ 2 #define Py_NE 3 #define Py_GT 4 #define Py_GE 5 /* * Macro for implementing rich comparisons * * Needs to be a macro because any C-comparable type can be used. */ #define Py_RETURN_RICHCOMPARE(val1, val2, op) \ do { \ switch (op) { \ case Py_EQ: if ((val1) == (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_NE: if ((val1) != (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_LT: if ((val1) < (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_GT: if ((val1) > (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_LE: if ((val1) <= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ case Py_GE: if ((val1) >= (val2)) Py_RETURN_TRUE; Py_RETURN_FALSE; \ default: \ Py_UNREACHABLE(); \ } \ } while (0) /* More conventions ================ Argument Checking ----------------- Functions that take objects as arguments normally don't check for nil arguments, but they do check the type of the argument, and return an error if the function doesn't apply to the type. Failure Modes ------------- Functions may fail for a variety of reasons, including running out of memory. This is communicated to the caller in two ways: an error string is set (see errors.h), and the function result differs: functions that normally return a pointer return NULL for failure, functions returning an integer return -1 (which could be a legal return value too!), and other functions return 0 for success and -1 for failure. Callers should always check for errors before using the result. If an error was set, the caller must either explicitly clear it, or pass the error on to its caller. Reference Counts ---------------- It takes a while to get used to the proper usage of reference counts. Functions that create an object set the reference count to 1; such new objects must be stored somewhere or destroyed again with Py_DECREF(). Some functions that 'store' objects, such as PyTuple_SetItem() and PyList_SetItem(), don't increment the reference count of the object, since the most frequent use is to store a fresh object. Functions that 'retrieve' objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also don't increment the reference count, since most frequently the object is only looked at quickly. Thus, to retrieve an object and store it again, the caller must call Py_INCREF() explicitly. NOTE: functions that 'consume' a reference count, like PyList_SetItem(), consume the reference even if the object wasn't successfully stored, to simplify error handling. It seems attractive to make other functions that take an object as argument consume a reference count; however, this may quickly get confusing (even the current practice is already confusing). Consider it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at times. */ /* Trashcan mechanism, thanks to Christian Tismer. When deallocating a container object, it's possible to trigger an unbounded chain of deallocations, as each Py_DECREF in turn drops the refcount on "the next" object in the chain to 0. This can easily lead to stack overflows, especially in threads (which typically have less stack space to work with). A container object can avoid this by bracketing the body of its tp_dealloc function with a pair of macros: static void mytype_dealloc(mytype *p) { ... declarations go here ... PyObject_GC_UnTrack(p); // must untrack first Py_TRASHCAN_BEGIN(p, mytype_dealloc) ... The body of the deallocator goes here, including all calls ... ... to Py_DECREF on contained objects. ... Py_TRASHCAN_END // there should be no code after this } CAUTION: Never return from the middle of the body! If the body needs to "get out early", put a label immediately before the Py_TRASHCAN_END call, and goto it. Else the call-depth counter (see below) will stay above 0 forever, and the trashcan will never get emptied. How it works: The BEGIN macro increments a call-depth counter. So long as this counter is small, the body of the deallocator is run directly without further ado. But if the counter gets large, it instead adds p to a list of objects to be deallocated later, skips the body of the deallocator, and resumes execution after the END macro. The tp_dealloc routine then returns without deallocating anything (and so unbounded call-stack depth is avoided). When the call stack finishes unwinding again, code generated by the END macro notices this, and calls another routine to deallocate all the objects that may have been added to the list of deferred deallocations. In effect, a chain of N deallocations is broken into (N-1)/(PyTrash_UNWIND_LEVEL-1) pieces, with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL. Since the tp_dealloc of a subclass typically calls the tp_dealloc of the base class, we need to ensure that the trashcan is only triggered on the tp_dealloc of the actual class being deallocated. Otherwise we might end up with a partially-deallocated object. To check this, the tp_dealloc function must be passed as second argument to Py_TRASHCAN_BEGIN(). */ /* The new thread-safe private API, invoked by the macros below. */ PyAPI_FUNC(void) _PyTrash_thread_deposit_object(PyObject*); PyAPI_FUNC(void) _PyTrash_thread_destroy_chain(void); #define PyTrash_UNWIND_LEVEL 50 #define Py_TRASHCAN_BEGIN_CONDITION(op, cond) \ do { \ PyThreadState *_tstate = NULL; \ /* If "cond" is false, then _tstate remains NULL and the deallocator \ * is run normally without involving the trashcan */ \ if (cond) { \ _tstate = PyThreadState_GET(); \ if (_tstate->trash_delete_nesting >= PyTrash_UNWIND_LEVEL) { \ /* Store the object (to be deallocated later) and jump past \ * Py_TRASHCAN_END, skipping the body of the deallocator */ \ _PyTrash_thread_deposit_object(_PyObject_CAST(op)); \ break; \ } \ ++_tstate->trash_delete_nesting; \ } /* The body of the deallocator is here. */ #define Py_TRASHCAN_END \ if (_tstate) { \ --_tstate->trash_delete_nesting; \ if (_tstate->trash_delete_later && _tstate->trash_delete_nesting <= 0) \ _PyTrash_thread_destroy_chain(); \ } \ } while (0); #define Py_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN_CONDITION(op, \ Py_TYPE(op)->tp_dealloc == (destructor)(dealloc)) /* For backwards compatibility, these macros enable the trashcan * unconditionally */ #define Py_TRASHCAN_SAFE_BEGIN(op) Py_TRASHCAN_BEGIN_CONDITION(op, 1) #define Py_TRASHCAN_SAFE_END(op) Py_TRASHCAN_END #ifndef Py_LIMITED_API # define Py_CPYTHON_OBJECT_H # include "cpython/object.h" # undef Py_CPYTHON_OBJECT_H #endif #ifdef __cplusplus } #endif #endif /* !Py_OBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/objimpl.h ================================================ /* The PyObject_ memory family: high-level object memory interfaces. See pymem.h for the low-level PyMem_ family. */ #ifndef Py_OBJIMPL_H #define Py_OBJIMPL_H #include "pymem.h" #ifdef __cplusplus extern "C" { #endif /* BEWARE: Each interface exports both functions and macros. Extension modules should use the functions, to ensure binary compatibility across Python versions. Because the Python implementation is free to change internal details, and the macros may (or may not) expose details for speed, if you do use the macros you must recompile your extensions with each Python release. Never mix calls to PyObject_ memory functions with calls to the platform malloc/realloc/ calloc/free, or with calls to PyMem_. */ /* Functions and macros for modules that implement new object types. - PyObject_New(type, typeobj) allocates memory for a new object of the given type, and initializes part of it. 'type' must be the C structure type used to represent the object, and 'typeobj' the address of the corresponding type object. Reference count and type pointer are filled in; the rest of the bytes of the object are *undefined*! The resulting expression type is 'type *'. The size of the object is determined by the tp_basicsize field of the type object. - PyObject_NewVar(type, typeobj, n) is similar but allocates a variable-size object with room for n items. In addition to the refcount and type pointer fields, this also fills in the ob_size field. - PyObject_Del(op) releases the memory allocated for an object. It does not run a destructor -- it only frees the memory. PyObject_Free is identical. - PyObject_Init(op, typeobj) and PyObject_InitVar(op, typeobj, n) don't allocate memory. Instead of a 'type' parameter, they take a pointer to a new object (allocated by an arbitrary allocator), and initialize its object header fields. Note that objects created with PyObject_{New, NewVar} are allocated using the specialized Python allocator (implemented in obmalloc.c), if WITH_PYMALLOC is enabled. In addition, a special debugging allocator is used if PYMALLOC_DEBUG is also #defined. In case a specific form of memory management is needed (for example, if you must use the platform malloc heap(s), or shared memory, or C++ local storage or operator new), you must first allocate the object with your custom allocator, then pass its pointer to PyObject_{Init, InitVar} for filling in its Python- specific fields: reference count, type pointer, possibly others. You should be aware that Python has no control over these objects because they don't cooperate with the Python memory manager. Such objects may not be eligible for automatic garbage collection and you have to make sure that they are released accordingly whenever their destructor gets called (cf. the specific form of memory management you're using). Unless you have specific memory management requirements, use PyObject_{New, NewVar, Del}. */ /* * Raw object memory interface * =========================== */ /* Functions to call the same malloc/realloc/free as used by Python's object allocator. If WITH_PYMALLOC is enabled, these may differ from the platform malloc/realloc/free. The Python object allocator is designed for fast, cache-conscious allocation of many "small" objects, and with low hidden memory overhead. PyObject_Malloc(0) returns a unique non-NULL pointer if possible. PyObject_Realloc(NULL, n) acts like PyObject_Malloc(n). PyObject_Realloc(p != NULL, 0) does not return NULL, or free the memory at p. Returned pointers must be checked for NULL explicitly; no action is performed on failure other than to return NULL (no warning it printed, no exception is set, etc). For allocating objects, use PyObject_{New, NewVar} instead whenever possible. The PyObject_{Malloc, Realloc, Free} family is exposed so that you can exploit Python's small-block allocator for non-object uses. If you must use these routines to allocate object memory, make sure the object gets initialized via PyObject_{Init, InitVar} after obtaining the raw memory. */ PyAPI_FUNC(void *) PyObject_Malloc(size_t size); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyAPI_FUNC(void *) PyObject_Calloc(size_t nelem, size_t elsize); #endif PyAPI_FUNC(void *) PyObject_Realloc(void *ptr, size_t new_size); PyAPI_FUNC(void) PyObject_Free(void *ptr); /* Macros */ #define PyObject_MALLOC PyObject_Malloc #define PyObject_REALLOC PyObject_Realloc #define PyObject_FREE PyObject_Free #define PyObject_Del PyObject_Free #define PyObject_DEL PyObject_Free /* * Generic object allocator interface * ================================== */ /* Functions */ PyAPI_FUNC(PyObject *) PyObject_Init(PyObject *, PyTypeObject *); PyAPI_FUNC(PyVarObject *) PyObject_InitVar(PyVarObject *, PyTypeObject *, Py_ssize_t); PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *); PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t); #define PyObject_New(type, typeobj) \ ( (type *) _PyObject_New(typeobj) ) #define PyObject_NewVar(type, typeobj, n) \ ( (type *) _PyObject_NewVar((typeobj), (n)) ) /* Inline functions trading binary compatibility for speed: PyObject_INIT() is the fast version of PyObject_Init(), and PyObject_INIT_VAR() is the fast version of PyObject_InitVar. See also pymem.h. These inline functions expect non-NULL object pointers. */ static inline PyObject* _PyObject_INIT(PyObject *op, PyTypeObject *typeobj) { assert(op != NULL); Py_TYPE(op) = typeobj; if (PyType_GetFlags(typeobj) & Py_TPFLAGS_HEAPTYPE) { Py_INCREF(typeobj); } _Py_NewReference(op); return op; } #define PyObject_INIT(op, typeobj) \ _PyObject_INIT(_PyObject_CAST(op), (typeobj)) static inline PyVarObject* _PyObject_INIT_VAR(PyVarObject *op, PyTypeObject *typeobj, Py_ssize_t size) { assert(op != NULL); Py_SIZE(op) = size; PyObject_INIT((PyObject *)op, typeobj); return op; } #define PyObject_INIT_VAR(op, typeobj, size) \ _PyObject_INIT_VAR(_PyVarObject_CAST(op), (typeobj), (size)) #define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize ) /* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a vrbl-size object with nitems items, exclusive of gc overhead (if any). The value is rounded up to the closest multiple of sizeof(void *), in order to ensure that pointer fields at the end of the object are correctly aligned for the platform (this is of special importance for subclasses of, e.g., str or int, so that pointers can be stored after the embedded data). Note that there's no memory wastage in doing this, as malloc has to return (at worst) pointer-aligned memory anyway. */ #if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0 # error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2" #endif #define _PyObject_VAR_SIZE(typeobj, nitems) \ _Py_SIZE_ROUND_UP((typeobj)->tp_basicsize + \ (nitems)*(typeobj)->tp_itemsize, \ SIZEOF_VOID_P) #define PyObject_NEW(type, typeobj) \ ( (type *) PyObject_Init( \ (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) #define PyObject_NEW_VAR(type, typeobj, n) \ ( (type *) PyObject_InitVar( \ (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE((typeobj),(n)) ),\ (typeobj), (n)) ) /* This example code implements an object constructor with a custom allocator, where PyObject_New is inlined, and shows the important distinction between two steps (at least): 1) the actual allocation of the object storage; 2) the initialization of the Python specific fields in this storage with PyObject_{Init, InitVar}. PyObject * YourObject_New(...) { PyObject *op; op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct)); if (op == NULL) return PyErr_NoMemory(); PyObject_Init(op, &YourTypeStruct); op->ob_field = value; ... return op; } Note that in C++, the use of the new operator usually implies that the 1st step is performed automatically for you, so in a C++ class constructor you would start directly with PyObject_Init/InitVar */ /* * Garbage Collection Support * ========================== */ /* C equivalent of gc.collect() which ignores the state of gc.enabled. */ PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void); /* Test if a type has a GC head */ #define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC) PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t); #define PyObject_GC_Resize(type, op, n) \ ( (type *) _PyObject_GC_Resize(_PyVarObject_CAST(op), (n)) ) PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *); PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t); /* Tell the GC to track this object. * * See also private _PyObject_GC_TRACK() macro. */ PyAPI_FUNC(void) PyObject_GC_Track(void *); /* Tell the GC to stop tracking this object. * * See also private _PyObject_GC_UNTRACK() macro. */ PyAPI_FUNC(void) PyObject_GC_UnTrack(void *); PyAPI_FUNC(void) PyObject_GC_Del(void *); #define PyObject_GC_New(type, typeobj) \ ( (type *) _PyObject_GC_New(typeobj) ) #define PyObject_GC_NewVar(type, typeobj, n) \ ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) /* Utility macro to help write tp_traverse functions. * To use this macro, the tp_traverse function must name its arguments * "visit" and "arg". This is intended to keep tp_traverse functions * looking as much alike as possible. */ #define Py_VISIT(op) \ do { \ if (op) { \ int vret = visit(_PyObject_CAST(op), arg); \ if (vret) \ return vret; \ } \ } while (0) #ifndef Py_LIMITED_API # define Py_CPYTHON_OBJIMPL_H # include "cpython/objimpl.h" # undef Py_CPYTHON_OBJIMPL_H #endif #ifdef __cplusplus } #endif #endif /* !Py_OBJIMPL_H */ ================================================ FILE: thirdLibs/python3_8/include/odictobject.h ================================================ #ifndef Py_ODICTOBJECT_H #define Py_ODICTOBJECT_H #ifdef __cplusplus extern "C" { #endif /* OrderedDict */ /* This API is optional and mostly redundant. */ #ifndef Py_LIMITED_API typedef struct _odictobject PyODictObject; PyAPI_DATA(PyTypeObject) PyODict_Type; PyAPI_DATA(PyTypeObject) PyODictIter_Type; PyAPI_DATA(PyTypeObject) PyODictKeys_Type; PyAPI_DATA(PyTypeObject) PyODictItems_Type; PyAPI_DATA(PyTypeObject) PyODictValues_Type; #define PyODict_Check(op) PyObject_TypeCheck(op, &PyODict_Type) #define PyODict_CheckExact(op) (Py_TYPE(op) == &PyODict_Type) #define PyODict_SIZE(op) PyDict_GET_SIZE((op)) PyAPI_FUNC(PyObject *) PyODict_New(void); PyAPI_FUNC(int) PyODict_SetItem(PyObject *od, PyObject *key, PyObject *item); PyAPI_FUNC(int) PyODict_DelItem(PyObject *od, PyObject *key); /* wrappers around PyDict* functions */ #define PyODict_GetItem(od, key) PyDict_GetItem(_PyObject_CAST(od), key) #define PyODict_GetItemWithError(od, key) \ PyDict_GetItemWithError(_PyObject_CAST(od), key) #define PyODict_Contains(od, key) PyDict_Contains(_PyObject_CAST(od), key) #define PyODict_Size(od) PyDict_Size(_PyObject_CAST(od)) #define PyODict_GetItemString(od, key) \ PyDict_GetItemString(_PyObject_CAST(od), key) #endif #ifdef __cplusplus } #endif #endif /* !Py_ODICTOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/opcode.h ================================================ /* Auto-generated by Tools/scripts/generate_opcode_h.py from Lib/opcode.py */ #ifndef Py_OPCODE_H #define Py_OPCODE_H #ifdef __cplusplus extern "C" { #endif /* Instruction opcodes for compiled code */ #define POP_TOP 1 #define ROT_TWO 2 #define ROT_THREE 3 #define DUP_TOP 4 #define DUP_TOP_TWO 5 #define ROT_FOUR 6 #define NOP 9 #define UNARY_POSITIVE 10 #define UNARY_NEGATIVE 11 #define UNARY_NOT 12 #define UNARY_INVERT 15 #define BINARY_MATRIX_MULTIPLY 16 #define INPLACE_MATRIX_MULTIPLY 17 #define BINARY_POWER 19 #define BINARY_MULTIPLY 20 #define BINARY_MODULO 22 #define BINARY_ADD 23 #define BINARY_SUBTRACT 24 #define BINARY_SUBSCR 25 #define BINARY_FLOOR_DIVIDE 26 #define BINARY_TRUE_DIVIDE 27 #define INPLACE_FLOOR_DIVIDE 28 #define INPLACE_TRUE_DIVIDE 29 #define GET_AITER 50 #define GET_ANEXT 51 #define BEFORE_ASYNC_WITH 52 #define BEGIN_FINALLY 53 #define END_ASYNC_FOR 54 #define INPLACE_ADD 55 #define INPLACE_SUBTRACT 56 #define INPLACE_MULTIPLY 57 #define INPLACE_MODULO 59 #define STORE_SUBSCR 60 #define DELETE_SUBSCR 61 #define BINARY_LSHIFT 62 #define BINARY_RSHIFT 63 #define BINARY_AND 64 #define BINARY_XOR 65 #define BINARY_OR 66 #define INPLACE_POWER 67 #define GET_ITER 68 #define GET_YIELD_FROM_ITER 69 #define PRINT_EXPR 70 #define LOAD_BUILD_CLASS 71 #define YIELD_FROM 72 #define GET_AWAITABLE 73 #define INPLACE_LSHIFT 75 #define INPLACE_RSHIFT 76 #define INPLACE_AND 77 #define INPLACE_XOR 78 #define INPLACE_OR 79 #define WITH_CLEANUP_START 81 #define WITH_CLEANUP_FINISH 82 #define RETURN_VALUE 83 #define IMPORT_STAR 84 #define SETUP_ANNOTATIONS 85 #define YIELD_VALUE 86 #define POP_BLOCK 87 #define END_FINALLY 88 #define POP_EXCEPT 89 #define HAVE_ARGUMENT 90 #define STORE_NAME 90 #define DELETE_NAME 91 #define UNPACK_SEQUENCE 92 #define FOR_ITER 93 #define UNPACK_EX 94 #define STORE_ATTR 95 #define DELETE_ATTR 96 #define STORE_GLOBAL 97 #define DELETE_GLOBAL 98 #define LOAD_CONST 100 #define LOAD_NAME 101 #define BUILD_TUPLE 102 #define BUILD_LIST 103 #define BUILD_SET 104 #define BUILD_MAP 105 #define LOAD_ATTR 106 #define COMPARE_OP 107 #define IMPORT_NAME 108 #define IMPORT_FROM 109 #define JUMP_FORWARD 110 #define JUMP_IF_FALSE_OR_POP 111 #define JUMP_IF_TRUE_OR_POP 112 #define JUMP_ABSOLUTE 113 #define POP_JUMP_IF_FALSE 114 #define POP_JUMP_IF_TRUE 115 #define LOAD_GLOBAL 116 #define SETUP_FINALLY 122 #define LOAD_FAST 124 #define STORE_FAST 125 #define DELETE_FAST 126 #define RAISE_VARARGS 130 #define CALL_FUNCTION 131 #define MAKE_FUNCTION 132 #define BUILD_SLICE 133 #define LOAD_CLOSURE 135 #define LOAD_DEREF 136 #define STORE_DEREF 137 #define DELETE_DEREF 138 #define CALL_FUNCTION_KW 141 #define CALL_FUNCTION_EX 142 #define SETUP_WITH 143 #define EXTENDED_ARG 144 #define LIST_APPEND 145 #define SET_ADD 146 #define MAP_ADD 147 #define LOAD_CLASSDEREF 148 #define BUILD_LIST_UNPACK 149 #define BUILD_MAP_UNPACK 150 #define BUILD_MAP_UNPACK_WITH_CALL 151 #define BUILD_TUPLE_UNPACK 152 #define BUILD_SET_UNPACK 153 #define SETUP_ASYNC_WITH 154 #define FORMAT_VALUE 155 #define BUILD_CONST_KEY_MAP 156 #define BUILD_STRING 157 #define BUILD_TUPLE_UNPACK_WITH_CALL 158 #define LOAD_METHOD 160 #define CALL_METHOD 161 #define CALL_FINALLY 162 #define POP_FINALLY 163 /* EXCEPT_HANDLER is a special, implicit block type which is created when entering an except handler. It is not an opcode but we define it here as we want it to be available to both frameobject.c and ceval.c, while remaining private.*/ #define EXCEPT_HANDLER 257 enum cmp_op {PyCmp_LT=Py_LT, PyCmp_LE=Py_LE, PyCmp_EQ=Py_EQ, PyCmp_NE=Py_NE, PyCmp_GT=Py_GT, PyCmp_GE=Py_GE, PyCmp_IN, PyCmp_NOT_IN, PyCmp_IS, PyCmp_IS_NOT, PyCmp_EXC_MATCH, PyCmp_BAD}; #define HAS_ARG(op) ((op) >= HAVE_ARGUMENT) #ifdef __cplusplus } #endif #endif /* !Py_OPCODE_H */ ================================================ FILE: thirdLibs/python3_8/include/osdefs.h ================================================ #ifndef Py_OSDEFS_H #define Py_OSDEFS_H #ifdef __cplusplus extern "C" { #endif /* Operating system dependencies */ #ifdef MS_WINDOWS #define SEP L'\\' #define ALTSEP L'/' #define MAXPATHLEN 256 #define DELIM L';' #endif #ifdef __VXWORKS__ #define DELIM L';' #endif /* Filename separator */ #ifndef SEP #define SEP L'/' #endif /* Max pathname length */ #ifdef __hpux #include #include #ifndef PATH_MAX #define PATH_MAX MAXPATHLEN #endif #endif #ifndef MAXPATHLEN #if defined(PATH_MAX) && PATH_MAX > 1024 #define MAXPATHLEN PATH_MAX #else #define MAXPATHLEN 1024 #endif #endif /* Search path entry delimiter */ #ifndef DELIM #define DELIM L':' #endif #ifdef __cplusplus } #endif #endif /* !Py_OSDEFS_H */ ================================================ FILE: thirdLibs/python3_8/include/osmodule.h ================================================ /* os module interface */ #ifndef Py_OSMODULE_H #define Py_OSMODULE_H #ifdef __cplusplus extern "C" { #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 PyAPI_FUNC(PyObject *) PyOS_FSPath(PyObject *path); #endif #ifdef __cplusplus } #endif #endif /* !Py_OSMODULE_H */ ================================================ FILE: thirdLibs/python3_8/include/parsetok.h ================================================ /* Parser-tokenizer link interface */ #ifndef Py_LIMITED_API #ifndef Py_PARSETOK_H #define Py_PARSETOK_H #ifdef __cplusplus extern "C" { #endif #include "grammar.h" /* grammar */ #include "node.h" /* node */ typedef struct { int error; PyObject *filename; int lineno; int offset; char *text; /* UTF-8-encoded string */ int token; int expected; } perrdetail; #if 0 #define PyPARSE_YIELD_IS_KEYWORD 0x0001 #endif #define PyPARSE_DONT_IMPLY_DEDENT 0x0002 #if 0 #define PyPARSE_WITH_IS_KEYWORD 0x0003 #define PyPARSE_PRINT_IS_FUNCTION 0x0004 #define PyPARSE_UNICODE_LITERALS 0x0008 #endif #define PyPARSE_IGNORE_COOKIE 0x0010 #define PyPARSE_BARRY_AS_BDFL 0x0020 #define PyPARSE_TYPE_COMMENTS 0x0040 #define PyPARSE_ASYNC_HACKS 0x0080 PyAPI_FUNC(node *) PyParser_ParseString(const char *, grammar *, int, perrdetail *); PyAPI_FUNC(node *) PyParser_ParseFile (FILE *, const char *, grammar *, int, const char *, const char *, perrdetail *); PyAPI_FUNC(node *) PyParser_ParseStringFlags(const char *, grammar *, int, perrdetail *, int); PyAPI_FUNC(node *) PyParser_ParseFileFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int flags); PyAPI_FUNC(node *) PyParser_ParseFileFlagsEx( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags); PyAPI_FUNC(node *) PyParser_ParseFileObject( FILE *fp, PyObject *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags); PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilename( const char *s, const char *filename, /* decoded from the filesystem encoding */ grammar *g, int start, perrdetail *err_ret, int flags); PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilenameEx( const char *s, const char *filename, /* decoded from the filesystem encoding */ grammar *g, int start, perrdetail *err_ret, int *flags); PyAPI_FUNC(node *) PyParser_ParseStringObject( const char *s, PyObject *filename, grammar *g, int start, perrdetail *err_ret, int *flags); /* Note that the following functions are defined in pythonrun.c, not in parsetok.c */ PyAPI_FUNC(void) PyParser_SetError(perrdetail *); PyAPI_FUNC(void) PyParser_ClearError(perrdetail *); #ifdef __cplusplus } #endif #endif /* !Py_PARSETOK_H */ #endif /* !Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/patchlevel.h ================================================ /* Python version identification scheme. When the major or minor version changes, the VERSION variable in configure.ac must also be changed. There is also (independent) API version information in modsupport.h. */ /* Values for PY_RELEASE_LEVEL */ #define PY_RELEASE_LEVEL_ALPHA 0xA #define PY_RELEASE_LEVEL_BETA 0xB #define PY_RELEASE_LEVEL_GAMMA 0xC /* For release candidates */ #define PY_RELEASE_LEVEL_FINAL 0xF /* Serial should be 0 here */ /* Higher for patch releases */ /* Version parsed out into numeric values */ /*--start constants--*/ #define PY_MAJOR_VERSION 3 #define PY_MINOR_VERSION 8 #define PY_MICRO_VERSION 2 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL #define PY_RELEASE_SERIAL 0 /* Version as a string */ #define PY_VERSION "3.8.2" /*--end constants--*/ /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */ #define PY_VERSION_HEX ((PY_MAJOR_VERSION << 24) | \ (PY_MINOR_VERSION << 16) | \ (PY_MICRO_VERSION << 8) | \ (PY_RELEASE_LEVEL << 4) | \ (PY_RELEASE_SERIAL << 0)) ================================================ FILE: thirdLibs/python3_8/include/picklebufobject.h ================================================ /* PickleBuffer object. This is built-in for ease of use from third-party * C extensions. */ #ifndef Py_PICKLEBUFOBJECT_H #define Py_PICKLEBUFOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API PyAPI_DATA(PyTypeObject) PyPickleBuffer_Type; #define PyPickleBuffer_Check(op) (Py_TYPE(op) == &PyPickleBuffer_Type) /* Create a PickleBuffer redirecting to the given buffer-enabled object */ PyAPI_FUNC(PyObject *) PyPickleBuffer_FromObject(PyObject *); /* Get the PickleBuffer's underlying view to the original object * (NULL if released) */ PyAPI_FUNC(const Py_buffer *) PyPickleBuffer_GetBuffer(PyObject *); /* Release the PickleBuffer. Returns 0 on success, -1 on error. */ PyAPI_FUNC(int) PyPickleBuffer_Release(PyObject *); #endif /* !Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_PICKLEBUFOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/py_curses.h ================================================ #ifndef Py_CURSES_H #define Py_CURSES_H #ifdef __APPLE__ /* ** On Mac OS X 10.2 [n]curses.h and stdlib.h use different guards ** against multiple definition of wchar_t. */ #ifdef _BSD_WCHAR_T_DEFINED_ #define _WCHAR_T #endif #endif /* __APPLE__ */ /* On FreeBSD, [n]curses.h and stdlib.h/wchar.h use different guards against multiple definition of wchar_t and wint_t. */ #if defined(__FreeBSD__) && defined(_XOPEN_SOURCE_EXTENDED) # ifndef __wchar_t # define __wchar_t # endif # ifndef __wint_t # define __wint_t # endif #endif #if !defined(HAVE_CURSES_IS_PAD) && defined(WINDOW_HAS_FLAGS) /* The following definition is necessary for ncurses 5.7; without it, some of [n]curses.h set NCURSES_OPAQUE to 1, and then Python can't get at the WINDOW flags field. */ #define NCURSES_OPAQUE 0 #endif #ifdef HAVE_NCURSES_H #include #else #include #endif #ifdef HAVE_NCURSES_H /* configure was checking , but we will use , which has some or all these features. */ #if !defined(WINDOW_HAS_FLAGS) && !(NCURSES_OPAQUE+0) #define WINDOW_HAS_FLAGS 1 #endif #if !defined(HAVE_CURSES_IS_PAD) && NCURSES_VERSION_PATCH+0 >= 20090906 #define HAVE_CURSES_IS_PAD 1 #endif #ifndef MVWDELCH_IS_EXPRESSION #define MVWDELCH_IS_EXPRESSION 1 #endif #endif #ifdef __cplusplus extern "C" { #endif #define PyCurses_API_pointers 4 /* Type declarations */ typedef struct { PyObject_HEAD WINDOW *win; char *encoding; } PyCursesWindowObject; #define PyCursesWindow_Check(v) (Py_TYPE(v) == &PyCursesWindow_Type) #define PyCurses_CAPSULE_NAME "_curses._C_API" #ifdef CURSES_MODULE /* This section is used when compiling _cursesmodule.c */ #else /* This section is used in modules that use the _cursesmodule API */ static void **PyCurses_API; #define PyCursesWindow_Type (*(PyTypeObject *) PyCurses_API[0]) #define PyCursesSetupTermCalled {if (! ((int (*)(void))PyCurses_API[1]) () ) return NULL;} #define PyCursesInitialised {if (! ((int (*)(void))PyCurses_API[2]) () ) return NULL;} #define PyCursesInitialisedColor {if (! ((int (*)(void))PyCurses_API[3]) () ) return NULL;} #define import_curses() \ PyCurses_API = (void **)PyCapsule_Import(PyCurses_CAPSULE_NAME, 1); #endif /* general error messages */ static const char catchall_ERR[] = "curses function returned ERR"; static const char catchall_NULL[] = "curses function returned NULL"; #ifdef __cplusplus } #endif #endif /* !defined(Py_CURSES_H) */ ================================================ FILE: thirdLibs/python3_8/include/pyarena.h ================================================ /* An arena-like memory interface for the compiler. */ #ifndef Py_LIMITED_API #ifndef Py_PYARENA_H #define Py_PYARENA_H #ifdef __cplusplus extern "C" { #endif typedef struct _arena PyArena; /* PyArena_New() and PyArena_Free() create a new arena and free it, respectively. Once an arena has been created, it can be used to allocate memory via PyArena_Malloc(). Pointers to PyObject can also be registered with the arena via PyArena_AddPyObject(), and the arena will ensure that the PyObjects stay alive at least until PyArena_Free() is called. When an arena is freed, all the memory it allocated is freed, the arena releases internal references to registered PyObject*, and none of its pointers are valid. XXX (tim) What does "none of its pointers are valid" mean? Does it XXX mean that pointers previously obtained via PyArena_Malloc() are XXX no longer valid? (That's clearly true, but not sure that's what XXX the text is trying to say.) PyArena_New() returns an arena pointer. On error, it returns a negative number and sets an exception. XXX (tim): Not true. On error, PyArena_New() actually returns NULL, XXX and looks like it may or may not set an exception (e.g., if the XXX internal PyList_New(0) returns NULL, PyArena_New() passes that on XXX and an exception is set; OTOH, if the internal XXX block_new(DEFAULT_BLOCK_SIZE) returns NULL, that's passed on but XXX an exception is not set in that case). */ PyAPI_FUNC(PyArena *) PyArena_New(void); PyAPI_FUNC(void) PyArena_Free(PyArena *); /* Mostly like malloc(), return the address of a block of memory spanning * `size` bytes, or return NULL (without setting an exception) if enough * new memory can't be obtained. Unlike malloc(0), PyArena_Malloc() with * size=0 does not guarantee to return a unique pointer (the pointer * returned may equal one or more other pointers obtained from * PyArena_Malloc()). * Note that pointers obtained via PyArena_Malloc() must never be passed to * the system free() or realloc(), or to any of Python's similar memory- * management functions. PyArena_Malloc()-obtained pointers remain valid * until PyArena_Free(ar) is called, at which point all pointers obtained * from the arena `ar` become invalid simultaneously. */ PyAPI_FUNC(void *) PyArena_Malloc(PyArena *, size_t size); /* This routine isn't a proper arena allocation routine. It takes * a PyObject* and records it so that it can be DECREFed when the * arena is freed. */ PyAPI_FUNC(int) PyArena_AddPyObject(PyArena *, PyObject *); #ifdef __cplusplus } #endif #endif /* !Py_PYARENA_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/pycapsule.h ================================================ /* Capsule objects let you wrap a C "void *" pointer in a Python object. They're a way of passing data through the Python interpreter without creating your own custom type. Capsules are used for communication between extension modules. They provide a way for an extension module to export a C interface to other extension modules, so that extension modules can use the Python import mechanism to link to one another. For more information, please see "c-api/capsule.html" in the documentation. */ #ifndef Py_CAPSULE_H #define Py_CAPSULE_H #ifdef __cplusplus extern "C" { #endif PyAPI_DATA(PyTypeObject) PyCapsule_Type; typedef void (*PyCapsule_Destructor)(PyObject *); #define PyCapsule_CheckExact(op) (Py_TYPE(op) == &PyCapsule_Type) PyAPI_FUNC(PyObject *) PyCapsule_New( void *pointer, const char *name, PyCapsule_Destructor destructor); PyAPI_FUNC(void *) PyCapsule_GetPointer(PyObject *capsule, const char *name); PyAPI_FUNC(PyCapsule_Destructor) PyCapsule_GetDestructor(PyObject *capsule); PyAPI_FUNC(const char *) PyCapsule_GetName(PyObject *capsule); PyAPI_FUNC(void *) PyCapsule_GetContext(PyObject *capsule); PyAPI_FUNC(int) PyCapsule_IsValid(PyObject *capsule, const char *name); PyAPI_FUNC(int) PyCapsule_SetPointer(PyObject *capsule, void *pointer); PyAPI_FUNC(int) PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor); PyAPI_FUNC(int) PyCapsule_SetName(PyObject *capsule, const char *name); PyAPI_FUNC(int) PyCapsule_SetContext(PyObject *capsule, void *context); PyAPI_FUNC(void *) PyCapsule_Import( const char *name, /* UTF-8 encoded string */ int no_block); #ifdef __cplusplus } #endif #endif /* !Py_CAPSULE_H */ ================================================ FILE: thirdLibs/python3_8/include/pyconfig.h ================================================ #ifndef Py_CONFIG_H #define Py_CONFIG_H /* pyconfig.h. NOT Generated automatically by configure. This is a manually maintained version used for the Watcom, Borland and Microsoft Visual C++ compilers. It is a standard part of the Python distribution. WINDOWS DEFINES: The code specific to Windows should be wrapped around one of the following #defines MS_WIN64 - Code specific to the MS Win64 API MS_WIN32 - Code specific to the MS Win32 (and Win64) API (obsolete, this covers all supported APIs) MS_WINDOWS - Code specific to Windows, but all versions. Py_ENABLE_SHARED - Code if the Python core is built as a DLL. Also note that neither "_M_IX86" or "_MSC_VER" should be used for any purpose other than "Windows Intel x86 specific" and "Microsoft compiler specific". Therefore, these should be very rare. NOTE: The following symbols are deprecated: NT, USE_DL_EXPORT, USE_DL_IMPORT, DL_EXPORT, DL_IMPORT MS_CORE_DLL. WIN32 is still required for the locale module. */ /* Deprecated USE_DL_EXPORT macro - please use Py_BUILD_CORE */ #ifdef USE_DL_EXPORT # define Py_BUILD_CORE #endif /* USE_DL_EXPORT */ /* Visual Studio 2005 introduces deprecation warnings for "insecure" and POSIX functions. The insecure functions should be replaced by *_s versions (according to Microsoft); the POSIX functions by _* versions (which, according to Microsoft, would be ISO C conforming). Neither renaming is feasible, so we just silence the warnings. */ #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif #ifndef _CRT_NONSTDC_NO_DEPRECATE #define _CRT_NONSTDC_NO_DEPRECATE 1 #endif #define HAVE_IO_H #define HAVE_SYS_UTIME_H #define HAVE_TEMPNAM #define HAVE_TMPFILE #define HAVE_TMPNAM #define HAVE_CLOCK #define HAVE_STRERROR #include #define HAVE_HYPOT #define HAVE_STRFTIME #define DONT_HAVE_SIG_ALARM #define DONT_HAVE_SIG_PAUSE #define LONG_BIT 32 #define WORD_BIT 32 #define MS_WIN32 /* only support win32 and greater. */ #define MS_WINDOWS #ifndef PYTHONPATH # define PYTHONPATH L".\\DLLs;.\\lib" #endif #define NT_THREADS #define WITH_THREAD #ifndef NETSCAPE_PI #define USE_SOCKET #endif /* Compiler specific defines */ /* ------------------------------------------------------------------------*/ /* Microsoft C defines _MSC_VER */ #ifdef _MSC_VER /* We want COMPILER to expand to a string containing _MSC_VER's *value*. * This is horridly tricky, because the stringization operator only works * on macro arguments, and doesn't evaluate macros passed *as* arguments. * Attempts simpler than the following appear doomed to produce "_MSC_VER" * literally in the string. */ #define _Py_PASTE_VERSION(SUFFIX) \ ("[MSC v." _Py_STRINGIZE(_MSC_VER) " " SUFFIX "]") /* e.g., this produces, after compile-time string catenation, * ("[MSC v.1200 32 bit (Intel)]") * * _Py_STRINGIZE(_MSC_VER) expands to * _Py_STRINGIZE1((_MSC_VER)) expands to * _Py_STRINGIZE2(_MSC_VER) but as this call is the result of token-pasting * it's scanned again for macros and so further expands to (under MSVC 6) * _Py_STRINGIZE2(1200) which then expands to * "1200" */ #define _Py_STRINGIZE(X) _Py_STRINGIZE1((X)) #define _Py_STRINGIZE1(X) _Py_STRINGIZE2 ## X #define _Py_STRINGIZE2(X) #X /* MSVC defines _WINxx to differentiate the windows platform types Note that for compatibility reasons _WIN32 is defined on Win32 *and* on Win64. For the same reasons, in Python, MS_WIN32 is defined on Win32 *and* Win64. Win32 only code must therefore be guarded as follows: #if defined(MS_WIN32) && !defined(MS_WIN64) */ #ifdef _WIN64 #define MS_WIN64 #endif /* set the COMPILER */ #ifdef MS_WIN64 #if defined(_M_X64) || defined(_M_AMD64) #if defined(__INTEL_COMPILER) #define COMPILER ("[ICC v." _Py_STRINGIZE(__INTEL_COMPILER) " 64 bit (amd64) with MSC v." _Py_STRINGIZE(_MSC_VER) " CRT]") #else #define COMPILER _Py_PASTE_VERSION("64 bit (AMD64)") #endif /* __INTEL_COMPILER */ #define PYD_PLATFORM_TAG "win_amd64" #elif defined(_M_ARM64) #define COMPILER _Py_PASTE_VERSION("64 bit (ARM64)") #define PYD_PLATFORM_TAG "win_arm64" #else #define COMPILER _Py_PASTE_VERSION("64 bit (Unknown)") #endif #endif /* MS_WIN64 */ /* set the version macros for the windows headers */ /* Python 3.5+ requires Windows Vista or greater */ #define Py_WINVER 0x0600 /* _WIN32_WINNT_VISTA */ #define Py_NTDDI NTDDI_VISTA /* We only set these values when building Python - we don't want to force these values on extensions, as that will affect the prototypes and structures exposed in the Windows headers. Even when building Python, we allow a single source file to override this - they may need access to structures etc so it can optionally use new Windows features if it determines at runtime they are available. */ #if defined(Py_BUILD_CORE) || defined(Py_BUILD_CORE_BUILTIN) || defined(Py_BUILD_CORE_MODULE) #ifndef NTDDI_VERSION #define NTDDI_VERSION Py_NTDDI #endif #ifndef WINVER #define WINVER Py_WINVER #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT Py_WINVER #endif #endif /* _W64 is not defined for VC6 or eVC4 */ #ifndef _W64 #define _W64 #endif /* Define like size_t, omitting the "unsigned" */ #ifdef MS_WIN64 typedef __int64 ssize_t; #else typedef _W64 int ssize_t; #endif #define HAVE_SSIZE_T 1 #if defined(MS_WIN32) && !defined(MS_WIN64) #if defined(_M_IX86) #if defined(__INTEL_COMPILER) #define COMPILER ("[ICC v." _Py_STRINGIZE(__INTEL_COMPILER) " 32 bit (Intel) with MSC v." _Py_STRINGIZE(_MSC_VER) " CRT]") #else #define COMPILER _Py_PASTE_VERSION("32 bit (Intel)") #endif /* __INTEL_COMPILER */ #define PYD_PLATFORM_TAG "win32" #elif defined(_M_ARM) #define COMPILER _Py_PASTE_VERSION("32 bit (ARM)") #define PYD_PLATFORM_TAG "win_arm32" #else #define COMPILER _Py_PASTE_VERSION("32 bit (Unknown)") #endif #endif /* MS_WIN32 && !MS_WIN64 */ typedef int pid_t; #include #define Py_IS_NAN _isnan #define Py_IS_INFINITY(X) (!_finite(X) && !_isnan(X)) #define Py_IS_FINITE(X) _finite(X) #define copysign _copysign /* Side by Side assemblies supported in VS 2005 and VS 2008 but not 2010*/ #if _MSC_VER >= 1400 && _MSC_VER < 1600 #define HAVE_SXS 1 #endif /* define some ANSI types that are not defined in earlier Win headers */ #if _MSC_VER >= 1200 /* This file only exists in VC 6.0 or higher */ #include #endif #endif /* _MSC_VER */ /* ------------------------------------------------------------------------*/ /* egcs/gnu-win32 defines __GNUC__ and _WIN32 */ #if defined(__GNUC__) && defined(_WIN32) /* XXX These defines are likely incomplete, but should be easy to fix. They should be complete enough to build extension modules. */ /* Suggested by Rene Liebscher to avoid a GCC 2.91.* bug that requires structure imports. More recent versions of the compiler don't exhibit this bug. */ #if (__GNUC__==2) && (__GNUC_MINOR__<=91) #warning "Please use an up-to-date version of gcc! (>2.91 recommended)" #endif #define COMPILER "[gcc]" #define PY_LONG_LONG long long #define PY_LLONG_MIN LLONG_MIN #define PY_LLONG_MAX LLONG_MAX #define PY_ULLONG_MAX ULLONG_MAX #endif /* GNUC */ /* ------------------------------------------------------------------------*/ /* lcc-win32 defines __LCC__ */ #if defined(__LCC__) /* XXX These defines are likely incomplete, but should be easy to fix. They should be complete enough to build extension modules. */ #define COMPILER "[lcc-win32]" typedef int pid_t; /* __declspec() is supported here too - do nothing to get the defaults */ #endif /* LCC */ /* ------------------------------------------------------------------------*/ /* End of compilers - finish up */ #ifndef NO_STDIO_H # include #endif /* 64 bit ints are usually spelt __int64 unless compiler has overridden */ #ifndef PY_LONG_LONG # define PY_LONG_LONG __int64 # define PY_LLONG_MAX _I64_MAX # define PY_LLONG_MIN _I64_MIN # define PY_ULLONG_MAX _UI64_MAX #endif /* For Windows the Python core is in a DLL by default. Test Py_NO_ENABLE_SHARED to find out. Also support MS_NO_COREDLL for b/w compat */ #if !defined(MS_NO_COREDLL) && !defined(Py_NO_ENABLE_SHARED) # define Py_ENABLE_SHARED 1 /* standard symbol for shared library */ # define MS_COREDLL /* deprecated old symbol */ #endif /* !MS_NO_COREDLL && ... */ /* All windows compilers that use this header support __declspec */ #define HAVE_DECLSPEC_DLL /* For an MSVC DLL, we can nominate the .lib files used by extensions */ #ifdef MS_COREDLL # if !defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_BUILTIN) /* not building the core - must be an ext */ # if defined(_MSC_VER) /* So MSVC users need not specify the .lib file in their Makefile (other compilers are generally taken care of by distutils.) */ # if defined(_DEBUG) # pragma comment(lib,"python38_d.lib") # elif defined(Py_LIMITED_API) # pragma comment(lib,"python3.lib") # else # pragma comment(lib,"python38.lib") # endif /* _DEBUG */ # endif /* _MSC_VER */ # endif /* Py_BUILD_CORE */ #endif /* MS_COREDLL */ #if defined(MS_WIN64) /* maintain "win32" sys.platform for backward compatibility of Python code, the Win64 API should be close enough to the Win32 API to make this preferable */ # define PLATFORM "win32" # define SIZEOF_VOID_P 8 # define SIZEOF_TIME_T 8 # define SIZEOF_OFF_T 4 # define SIZEOF_FPOS_T 8 # define SIZEOF_HKEY 8 # define SIZEOF_SIZE_T 8 /* configure.ac defines HAVE_LARGEFILE_SUPPORT iff sizeof(off_t) > sizeof(long), and sizeof(PY_LONG_LONG) >= sizeof(off_t). On Win64 the second condition is not true, but if fpos_t replaces off_t then this is true. The uses of HAVE_LARGEFILE_SUPPORT imply that Win64 should define this. */ # define HAVE_LARGEFILE_SUPPORT #elif defined(MS_WIN32) # define PLATFORM "win32" # define HAVE_LARGEFILE_SUPPORT # define SIZEOF_VOID_P 4 # define SIZEOF_OFF_T 4 # define SIZEOF_FPOS_T 8 # define SIZEOF_HKEY 4 # define SIZEOF_SIZE_T 4 /* MS VS2005 changes time_t to a 64-bit type on all platforms */ # if defined(_MSC_VER) && _MSC_VER >= 1400 # define SIZEOF_TIME_T 8 # else # define SIZEOF_TIME_T 4 # endif #endif #ifdef _DEBUG # define Py_DEBUG #endif #ifdef MS_WIN32 #define SIZEOF_SHORT 2 #define SIZEOF_INT 4 #define SIZEOF_LONG 4 #define SIZEOF_LONG_LONG 8 #define SIZEOF_DOUBLE 8 #define SIZEOF_FLOAT 4 /* VC 7.1 has them and VC 6.0 does not. VC 6.0 has a version number of 1200. Microsoft eMbedded Visual C++ 4.0 has a version number of 1201 and doesn't define these. If some compiler does not provide them, modify the #if appropriately. */ #if defined(_MSC_VER) #if _MSC_VER > 1300 #define HAVE_UINTPTR_T 1 #define HAVE_INTPTR_T 1 #else /* VC6, VS 2002 and eVC4 don't support the C99 LL suffix for 64-bit integer literals */ #define Py_LL(x) x##I64 #endif /* _MSC_VER > 1300 */ #endif /* _MSC_VER */ #endif /* define signed and unsigned exact-width 32-bit and 64-bit types, used in the implementation of Python integers. */ #define PY_UINT32_T uint32_t #define PY_UINT64_T uint64_t #define PY_INT32_T int32_t #define PY_INT64_T int64_t /* Fairly standard from here! */ /* Define to 1 if you have the `copysign' function. */ #define HAVE_COPYSIGN 1 /* Define to 1 if you have the `round' function. */ #if _MSC_VER >= 1800 #define HAVE_ROUND 1 #endif /* Define to 1 if you have the `isinf' macro. */ #define HAVE_DECL_ISINF 1 /* Define to 1 if you have the `isnan' function. */ #define HAVE_DECL_ISNAN 1 /* Define if on AIX 3. System headers sometimes define this. We just want to avoid a redefinition error message. */ #ifndef _ALL_SOURCE /* #undef _ALL_SOURCE */ #endif /* Define to empty if the keyword does not work. */ /* #define const */ /* Define to 1 if you have the header file. */ #define HAVE_CONIO_H 1 /* Define to 1 if you have the header file. */ #define HAVE_DIRECT_H 1 /* Define to 1 if you have the declaration of `tzname', and to 0 if you don't. */ #define HAVE_DECL_TZNAME 1 /* Define if you have dirent.h. */ /* #define DIRENT 1 */ /* Define to the type of elements in the array set by `getgroups'. Usually this is either `int' or `gid_t'. */ /* #undef GETGROUPS_T */ /* Define to `int' if doesn't define. */ /* #undef gid_t */ /* Define if your struct tm has tm_zone. */ /* #undef HAVE_TM_ZONE */ /* Define if you don't have tm_zone but do have the external array tzname. */ #define HAVE_TZNAME /* Define to `int' if doesn't define. */ /* #undef mode_t */ /* Define if you don't have dirent.h, but have ndir.h. */ /* #undef NDIR */ /* Define to `long' if doesn't define. */ /* #undef off_t */ /* Define to `int' if doesn't define. */ /* #undef pid_t */ /* Define if the system does not provide POSIX.1 features except with this defined. */ /* #undef _POSIX_1_SOURCE */ /* Define if you need to in order for stat and other things to work. */ /* #undef _POSIX_SOURCE */ /* Define as the return type of signal handlers (int or void). */ #define RETSIGTYPE void /* Define to `unsigned' if doesn't define. */ /* #undef size_t */ /* Define if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define if you don't have dirent.h, but have sys/dir.h. */ /* #undef SYSDIR */ /* Define if you don't have dirent.h, but have sys/ndir.h. */ /* #undef SYSNDIR */ /* Define if you can safely include both and . */ /* #undef TIME_WITH_SYS_TIME */ /* Define if your declares struct tm. */ /* #define TM_IN_SYS_TIME 1 */ /* Define to `int' if doesn't define. */ /* #undef uid_t */ /* Define if the closedir function returns void instead of int. */ /* #undef VOID_CLOSEDIR */ /* Define if getpgrp() must be called as getpgrp(0) and (consequently) setpgrp() as setpgrp(0, 0). */ /* #undef GETPGRP_HAVE_ARGS */ /* Define this if your time.h defines altzone */ /* #define HAVE_ALTZONE */ /* Define if you have the putenv function. */ #define HAVE_PUTENV /* Define if your compiler supports function prototypes */ #define HAVE_PROTOTYPES /* Define if you can safely include both and (which you can't on SCO ODT 3.0). */ /* #undef SYS_SELECT_WITH_SYS_TIME */ /* Define if you want documentation strings in extension modules */ #define WITH_DOC_STRINGS 1 /* Define if you want to compile in rudimentary thread support */ /* #undef WITH_THREAD */ /* Define if you want to use the GNU readline library */ /* #define WITH_READLINE 1 */ /* Use Python's own small-block memory-allocator. */ #define WITH_PYMALLOC 1 /* Define if you have clock. */ /* #define HAVE_CLOCK */ /* Define when any dynamic module loading is enabled */ #define HAVE_DYNAMIC_LOADING /* Define if you have ftime. */ #define HAVE_FTIME /* Define if you have getpeername. */ #define HAVE_GETPEERNAME /* Define if you have getpgrp. */ /* #undef HAVE_GETPGRP */ /* Define if you have getpid. */ #define HAVE_GETPID /* Define if you have gettimeofday. */ /* #undef HAVE_GETTIMEOFDAY */ /* Define if you have getwd. */ /* #undef HAVE_GETWD */ /* Define if you have lstat. */ /* #undef HAVE_LSTAT */ /* Define if you have the mktime function. */ #define HAVE_MKTIME /* Define if you have nice. */ /* #undef HAVE_NICE */ /* Define if you have readlink. */ /* #undef HAVE_READLINK */ /* Define if you have setpgid. */ /* #undef HAVE_SETPGID */ /* Define if you have setpgrp. */ /* #undef HAVE_SETPGRP */ /* Define if you have setsid. */ /* #undef HAVE_SETSID */ /* Define if you have setvbuf. */ #define HAVE_SETVBUF /* Define if you have siginterrupt. */ /* #undef HAVE_SIGINTERRUPT */ /* Define if you have symlink. */ /* #undef HAVE_SYMLINK */ /* Define if you have tcgetpgrp. */ /* #undef HAVE_TCGETPGRP */ /* Define if you have tcsetpgrp. */ /* #undef HAVE_TCSETPGRP */ /* Define if you have times. */ /* #undef HAVE_TIMES */ /* Define if you have uname. */ /* #undef HAVE_UNAME */ /* Define if you have waitpid. */ /* #undef HAVE_WAITPID */ /* Define to 1 if you have the `wcsftime' function. */ #if defined(_MSC_VER) && _MSC_VER >= 1310 #define HAVE_WCSFTIME 1 #endif /* Define to 1 if you have the `wcscoll' function. */ #define HAVE_WCSCOLL 1 /* Define to 1 if you have the `wcsxfrm' function. */ #define HAVE_WCSXFRM 1 /* Define if the zlib library has inflateCopy */ #define HAVE_ZLIB_COPY 1 /* Define if you have the header file. */ /* #undef HAVE_DLFCN_H */ /* Define to 1 if you have the header file. */ #define HAVE_ERRNO_H 1 /* Define if you have the header file. */ #define HAVE_FCNTL_H 1 /* Define to 1 if you have the header file. */ #define HAVE_PROCESS_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SIGNAL_H 1 /* Define if you have the prototypes. */ #define HAVE_STDARG_PROTOTYPES /* Define if you have the header file. */ #define HAVE_STDDEF_H 1 /* Define if you have the header file. */ /* #undef HAVE_SYS_AUDIOIO_H */ /* Define if you have the header file. */ /* #define HAVE_SYS_PARAM_H 1 */ /* Define if you have the header file. */ /* #define HAVE_SYS_SELECT_H 1 */ /* Define to 1 if you have the header file. */ #define HAVE_SYS_STAT_H 1 /* Define if you have the header file. */ /* #define HAVE_SYS_TIME_H 1 */ /* Define if you have the header file. */ /* #define HAVE_SYS_TIMES_H 1 */ /* Define to 1 if you have the header file. */ #define HAVE_SYS_TYPES_H 1 /* Define if you have the header file. */ /* #define HAVE_SYS_UN_H 1 */ /* Define if you have the header file. */ /* #define HAVE_SYS_UTIME_H 1 */ /* Define if you have the header file. */ /* #define HAVE_SYS_UTSNAME_H 1 */ /* Define if you have the header file. */ /* #define HAVE_UNISTD_H 1 */ /* Define if you have the header file. */ /* #define HAVE_UTIME_H 1 */ /* Define if the compiler provides a wchar.h header file. */ #define HAVE_WCHAR_H 1 /* The size of `wchar_t', as computed by sizeof. */ #define SIZEOF_WCHAR_T 2 /* The size of `_Bool', as computed by sizeof. */ #define SIZEOF__BOOL 1 /* The size of `pid_t', as computed by sizeof. */ #define SIZEOF_PID_T SIZEOF_INT /* Define if you have the dl library (-ldl). */ /* #undef HAVE_LIBDL */ /* Define if you have the mpc library (-lmpc). */ /* #undef HAVE_LIBMPC */ /* Define if you have the nsl library (-lnsl). */ #define HAVE_LIBNSL 1 /* Define if you have the seq library (-lseq). */ /* #undef HAVE_LIBSEQ */ /* Define if you have the socket library (-lsocket). */ #define HAVE_LIBSOCKET 1 /* Define if you have the sun library (-lsun). */ /* #undef HAVE_LIBSUN */ /* Define if you have the termcap library (-ltermcap). */ /* #undef HAVE_LIBTERMCAP */ /* Define if you have the termlib library (-ltermlib). */ /* #undef HAVE_LIBTERMLIB */ /* Define if you have the thread library (-lthread). */ /* #undef HAVE_LIBTHREAD */ /* WinSock does not use a bitmask in select, and uses socket handles greater than FD_SETSIZE */ #define Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE /* Define if C doubles are 64-bit IEEE 754 binary format, stored with the least significant byte first */ #define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1 /* Define to 1 if you have the `erf' function. */ #define HAVE_ERF 1 /* Define to 1 if you have the `erfc' function. */ #define HAVE_ERFC 1 /* Define if you have the 'inet_pton' function. */ #define HAVE_INET_PTON 1 /* framework name */ #define _PYTHONFRAMEWORK "" /* Define if libssl has X509_VERIFY_PARAM_set1_host and related function */ #define HAVE_X509_VERIFY_PARAM_SET1_HOST 1 #endif /* !Py_CONFIG_H */ ================================================ FILE: thirdLibs/python3_8/include/pyctype.h ================================================ #ifndef Py_LIMITED_API #ifndef PYCTYPE_H #define PYCTYPE_H #define PY_CTF_LOWER 0x01 #define PY_CTF_UPPER 0x02 #define PY_CTF_ALPHA (PY_CTF_LOWER|PY_CTF_UPPER) #define PY_CTF_DIGIT 0x04 #define PY_CTF_ALNUM (PY_CTF_ALPHA|PY_CTF_DIGIT) #define PY_CTF_SPACE 0x08 #define PY_CTF_XDIGIT 0x10 PyAPI_DATA(const unsigned int) _Py_ctype_table[256]; /* Unlike their C counterparts, the following macros are not meant to * handle an int with any of the values [EOF, 0-UCHAR_MAX]. The argument * must be a signed/unsigned char. */ #define Py_ISLOWER(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_LOWER) #define Py_ISUPPER(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_UPPER) #define Py_ISALPHA(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALPHA) #define Py_ISDIGIT(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_DIGIT) #define Py_ISXDIGIT(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_XDIGIT) #define Py_ISALNUM(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALNUM) #define Py_ISSPACE(c) (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_SPACE) PyAPI_DATA(const unsigned char) _Py_ctype_tolower[256]; PyAPI_DATA(const unsigned char) _Py_ctype_toupper[256]; #define Py_TOLOWER(c) (_Py_ctype_tolower[Py_CHARMASK(c)]) #define Py_TOUPPER(c) (_Py_ctype_toupper[Py_CHARMASK(c)]) #endif /* !PYCTYPE_H */ #endif /* !Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/pydebug.h ================================================ #ifndef Py_LIMITED_API #ifndef Py_PYDEBUG_H #define Py_PYDEBUG_H #ifdef __cplusplus extern "C" { #endif /* These global variable are defined in pylifecycle.c */ /* XXX (ncoghlan): move these declarations to pylifecycle.h? */ PyAPI_DATA(int) Py_DebugFlag; PyAPI_DATA(int) Py_VerboseFlag; PyAPI_DATA(int) Py_QuietFlag; PyAPI_DATA(int) Py_InteractiveFlag; PyAPI_DATA(int) Py_InspectFlag; PyAPI_DATA(int) Py_OptimizeFlag; PyAPI_DATA(int) Py_NoSiteFlag; PyAPI_DATA(int) Py_BytesWarningFlag; PyAPI_DATA(int) Py_FrozenFlag; PyAPI_DATA(int) Py_IgnoreEnvironmentFlag; PyAPI_DATA(int) Py_DontWriteBytecodeFlag; PyAPI_DATA(int) Py_NoUserSiteDirectory; PyAPI_DATA(int) Py_UnbufferedStdioFlag; PyAPI_DATA(int) Py_HashRandomizationFlag; PyAPI_DATA(int) Py_IsolatedFlag; #ifdef MS_WINDOWS PyAPI_DATA(int) Py_LegacyWindowsFSEncodingFlag; PyAPI_DATA(int) Py_LegacyWindowsStdioFlag; #endif /* this is a wrapper around getenv() that pays attention to Py_IgnoreEnvironmentFlag. It should be used for getting variables like PYTHONPATH and PYTHONHOME from the environment */ #define Py_GETENV(s) (Py_IgnoreEnvironmentFlag ? NULL : getenv(s)) #ifdef __cplusplus } #endif #endif /* !Py_PYDEBUG_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/pydtrace.h ================================================ /* Static DTrace probes interface */ #ifndef Py_DTRACE_H #define Py_DTRACE_H #ifdef __cplusplus extern "C" { #endif #ifdef WITH_DTRACE #include "pydtrace_probes.h" /* pydtrace_probes.h, on systems with DTrace, is auto-generated to include `PyDTrace_{PROBE}` and `PyDTrace_{PROBE}_ENABLED()` macros for every probe defined in pydtrace_provider.d. Calling these functions must be guarded by a `PyDTrace_{PROBE}_ENABLED()` check to minimize performance impact when probing is off. For example: if (PyDTrace_FUNCTION_ENTRY_ENABLED()) PyDTrace_FUNCTION_ENTRY(f); */ #else /* Without DTrace, compile to nothing. */ static inline void PyDTrace_LINE(const char *arg0, const char *arg1, int arg2) {} static inline void PyDTrace_FUNCTION_ENTRY(const char *arg0, const char *arg1, int arg2) {} static inline void PyDTrace_FUNCTION_RETURN(const char *arg0, const char *arg1, int arg2) {} static inline void PyDTrace_GC_START(int arg0) {} static inline void PyDTrace_GC_DONE(Py_ssize_t arg0) {} static inline void PyDTrace_INSTANCE_NEW_START(int arg0) {} static inline void PyDTrace_INSTANCE_NEW_DONE(int arg0) {} static inline void PyDTrace_INSTANCE_DELETE_START(int arg0) {} static inline void PyDTrace_INSTANCE_DELETE_DONE(int arg0) {} static inline void PyDTrace_IMPORT_FIND_LOAD_START(const char *arg0) {} static inline void PyDTrace_IMPORT_FIND_LOAD_DONE(const char *arg0, int arg1) {} static inline void PyDTrace_AUDIT(const char *arg0, void *arg1) {} static inline int PyDTrace_LINE_ENABLED(void) { return 0; } static inline int PyDTrace_FUNCTION_ENTRY_ENABLED(void) { return 0; } static inline int PyDTrace_FUNCTION_RETURN_ENABLED(void) { return 0; } static inline int PyDTrace_GC_START_ENABLED(void) { return 0; } static inline int PyDTrace_GC_DONE_ENABLED(void) { return 0; } static inline int PyDTrace_INSTANCE_NEW_START_ENABLED(void) { return 0; } static inline int PyDTrace_INSTANCE_NEW_DONE_ENABLED(void) { return 0; } static inline int PyDTrace_INSTANCE_DELETE_START_ENABLED(void) { return 0; } static inline int PyDTrace_INSTANCE_DELETE_DONE_ENABLED(void) { return 0; } static inline int PyDTrace_IMPORT_FIND_LOAD_START_ENABLED(void) { return 0; } static inline int PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED(void) { return 0; } static inline int PyDTrace_AUDIT_ENABLED(void) { return 0; } #endif /* !WITH_DTRACE */ #ifdef __cplusplus } #endif #endif /* !Py_DTRACE_H */ ================================================ FILE: thirdLibs/python3_8/include/pyerrors.h ================================================ #ifndef Py_ERRORS_H #define Py_ERRORS_H #ifdef __cplusplus extern "C" { #endif /* Error handling definitions */ PyAPI_FUNC(void) PyErr_SetNone(PyObject *); PyAPI_FUNC(void) PyErr_SetObject(PyObject *, PyObject *); PyAPI_FUNC(void) PyErr_SetString( PyObject *exception, const char *string /* decoded from utf-8 */ ); PyAPI_FUNC(PyObject *) PyErr_Occurred(void); PyAPI_FUNC(void) PyErr_Clear(void); PyAPI_FUNC(void) PyErr_Fetch(PyObject **, PyObject **, PyObject **); PyAPI_FUNC(void) PyErr_Restore(PyObject *, PyObject *, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(void) PyErr_GetExcInfo(PyObject **, PyObject **, PyObject **); PyAPI_FUNC(void) PyErr_SetExcInfo(PyObject *, PyObject *, PyObject *); #endif /* Defined in Python/pylifecycle.c */ PyAPI_FUNC(void) _Py_NO_RETURN Py_FatalError(const char *message); #if defined(Py_DEBUG) || defined(Py_LIMITED_API) #define _PyErr_OCCURRED() PyErr_Occurred() #else #define _PyErr_OCCURRED() (PyThreadState_GET()->curexc_type) #endif /* Error testing and normalization */ PyAPI_FUNC(int) PyErr_GivenExceptionMatches(PyObject *, PyObject *); PyAPI_FUNC(int) PyErr_ExceptionMatches(PyObject *); PyAPI_FUNC(void) PyErr_NormalizeException(PyObject**, PyObject**, PyObject**); /* Traceback manipulation (PEP 3134) */ PyAPI_FUNC(int) PyException_SetTraceback(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyException_GetTraceback(PyObject *); /* Cause manipulation (PEP 3134) */ PyAPI_FUNC(PyObject *) PyException_GetCause(PyObject *); PyAPI_FUNC(void) PyException_SetCause(PyObject *, PyObject *); /* Context manipulation (PEP 3134) */ PyAPI_FUNC(PyObject *) PyException_GetContext(PyObject *); PyAPI_FUNC(void) PyException_SetContext(PyObject *, PyObject *); /* */ #define PyExceptionClass_Check(x) \ (PyType_Check((x)) && \ PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) #define PyExceptionInstance_Check(x) \ PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) PyAPI_FUNC(const char *) PyExceptionClass_Name(PyObject *); #define PyExceptionInstance_Class(x) ((PyObject*)((x)->ob_type)) /* Predefined exceptions */ PyAPI_DATA(PyObject *) PyExc_BaseException; PyAPI_DATA(PyObject *) PyExc_Exception; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyAPI_DATA(PyObject *) PyExc_StopAsyncIteration; #endif PyAPI_DATA(PyObject *) PyExc_StopIteration; PyAPI_DATA(PyObject *) PyExc_GeneratorExit; PyAPI_DATA(PyObject *) PyExc_ArithmeticError; PyAPI_DATA(PyObject *) PyExc_LookupError; PyAPI_DATA(PyObject *) PyExc_AssertionError; PyAPI_DATA(PyObject *) PyExc_AttributeError; PyAPI_DATA(PyObject *) PyExc_BufferError; PyAPI_DATA(PyObject *) PyExc_EOFError; PyAPI_DATA(PyObject *) PyExc_FloatingPointError; PyAPI_DATA(PyObject *) PyExc_OSError; PyAPI_DATA(PyObject *) PyExc_ImportError; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 PyAPI_DATA(PyObject *) PyExc_ModuleNotFoundError; #endif PyAPI_DATA(PyObject *) PyExc_IndexError; PyAPI_DATA(PyObject *) PyExc_KeyError; PyAPI_DATA(PyObject *) PyExc_KeyboardInterrupt; PyAPI_DATA(PyObject *) PyExc_MemoryError; PyAPI_DATA(PyObject *) PyExc_NameError; PyAPI_DATA(PyObject *) PyExc_OverflowError; PyAPI_DATA(PyObject *) PyExc_RuntimeError; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyAPI_DATA(PyObject *) PyExc_RecursionError; #endif PyAPI_DATA(PyObject *) PyExc_NotImplementedError; PyAPI_DATA(PyObject *) PyExc_SyntaxError; PyAPI_DATA(PyObject *) PyExc_IndentationError; PyAPI_DATA(PyObject *) PyExc_TabError; PyAPI_DATA(PyObject *) PyExc_ReferenceError; PyAPI_DATA(PyObject *) PyExc_SystemError; PyAPI_DATA(PyObject *) PyExc_SystemExit; PyAPI_DATA(PyObject *) PyExc_TypeError; PyAPI_DATA(PyObject *) PyExc_UnboundLocalError; PyAPI_DATA(PyObject *) PyExc_UnicodeError; PyAPI_DATA(PyObject *) PyExc_UnicodeEncodeError; PyAPI_DATA(PyObject *) PyExc_UnicodeDecodeError; PyAPI_DATA(PyObject *) PyExc_UnicodeTranslateError; PyAPI_DATA(PyObject *) PyExc_ValueError; PyAPI_DATA(PyObject *) PyExc_ZeroDivisionError; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_DATA(PyObject *) PyExc_BlockingIOError; PyAPI_DATA(PyObject *) PyExc_BrokenPipeError; PyAPI_DATA(PyObject *) PyExc_ChildProcessError; PyAPI_DATA(PyObject *) PyExc_ConnectionError; PyAPI_DATA(PyObject *) PyExc_ConnectionAbortedError; PyAPI_DATA(PyObject *) PyExc_ConnectionRefusedError; PyAPI_DATA(PyObject *) PyExc_ConnectionResetError; PyAPI_DATA(PyObject *) PyExc_FileExistsError; PyAPI_DATA(PyObject *) PyExc_FileNotFoundError; PyAPI_DATA(PyObject *) PyExc_InterruptedError; PyAPI_DATA(PyObject *) PyExc_IsADirectoryError; PyAPI_DATA(PyObject *) PyExc_NotADirectoryError; PyAPI_DATA(PyObject *) PyExc_PermissionError; PyAPI_DATA(PyObject *) PyExc_ProcessLookupError; PyAPI_DATA(PyObject *) PyExc_TimeoutError; #endif /* Compatibility aliases */ PyAPI_DATA(PyObject *) PyExc_EnvironmentError; PyAPI_DATA(PyObject *) PyExc_IOError; #ifdef MS_WINDOWS PyAPI_DATA(PyObject *) PyExc_WindowsError; #endif /* Predefined warning categories */ PyAPI_DATA(PyObject *) PyExc_Warning; PyAPI_DATA(PyObject *) PyExc_UserWarning; PyAPI_DATA(PyObject *) PyExc_DeprecationWarning; PyAPI_DATA(PyObject *) PyExc_PendingDeprecationWarning; PyAPI_DATA(PyObject *) PyExc_SyntaxWarning; PyAPI_DATA(PyObject *) PyExc_RuntimeWarning; PyAPI_DATA(PyObject *) PyExc_FutureWarning; PyAPI_DATA(PyObject *) PyExc_ImportWarning; PyAPI_DATA(PyObject *) PyExc_UnicodeWarning; PyAPI_DATA(PyObject *) PyExc_BytesWarning; PyAPI_DATA(PyObject *) PyExc_ResourceWarning; /* Convenience functions */ PyAPI_FUNC(int) PyErr_BadArgument(void); PyAPI_FUNC(PyObject *) PyErr_NoMemory(void); PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *); PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject( PyObject *, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000 PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObjects( PyObject *, PyObject *, PyObject *); #endif PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename( PyObject *exc, const char *filename /* decoded from the filesystem encoding */ ); PyAPI_FUNC(PyObject *) PyErr_Format( PyObject *exception, const char *format, /* ASCII-encoded string */ ... ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyAPI_FUNC(PyObject *) PyErr_FormatV( PyObject *exception, const char *format, va_list vargs); #endif #ifdef MS_WINDOWS PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename( int ierr, const char *filename /* decoded from the filesystem encoding */ ); PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject( PyObject *,int, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000 PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObjects( PyObject *,int, PyObject *, PyObject *); #endif PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename( PyObject *exc, int ierr, const char *filename /* decoded from the filesystem encoding */ ); PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int); #endif /* MS_WINDOWS */ #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 PyAPI_FUNC(PyObject *) PyErr_SetImportErrorSubclass(PyObject *, PyObject *, PyObject *, PyObject *); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject *) PyErr_SetImportError(PyObject *, PyObject *, PyObject *); #endif /* Export the old function so that the existing API remains available: */ PyAPI_FUNC(void) PyErr_BadInternalCall(void); PyAPI_FUNC(void) _PyErr_BadInternalCall(const char *filename, int lineno); /* Mask the old API with a call to the new API for code compiled under Python 2.0: */ #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__) /* Function to create a new exception */ PyAPI_FUNC(PyObject *) PyErr_NewException( const char *name, PyObject *base, PyObject *dict); PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc( const char *name, const char *doc, PyObject *base, PyObject *dict); PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *); /* In signalmodule.c */ PyAPI_FUNC(int) PyErr_CheckSignals(void); PyAPI_FUNC(void) PyErr_SetInterrupt(void); /* Support for adding program text to SyntaxErrors */ PyAPI_FUNC(void) PyErr_SyntaxLocation( const char *filename, /* decoded from the filesystem encoding */ int lineno); PyAPI_FUNC(void) PyErr_SyntaxLocationEx( const char *filename, /* decoded from the filesystem encoding */ int lineno, int col_offset); PyAPI_FUNC(PyObject *) PyErr_ProgramText( const char *filename, /* decoded from the filesystem encoding */ int lineno); /* The following functions are used to create and modify unicode exceptions from C */ /* create a UnicodeDecodeError object */ PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create( const char *encoding, /* UTF-8 encoded string */ const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); /* get the encoding attribute */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *); PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetEncoding(PyObject *); /* get the object attribute */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetObject(PyObject *); PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetObject(PyObject *); PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetObject(PyObject *); /* get the value of the start attribute (the int * may not be NULL) return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_GetStart(PyObject *, Py_ssize_t *); PyAPI_FUNC(int) PyUnicodeDecodeError_GetStart(PyObject *, Py_ssize_t *); PyAPI_FUNC(int) PyUnicodeTranslateError_GetStart(PyObject *, Py_ssize_t *); /* assign a new value to the start attribute return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_SetStart(PyObject *, Py_ssize_t); PyAPI_FUNC(int) PyUnicodeDecodeError_SetStart(PyObject *, Py_ssize_t); PyAPI_FUNC(int) PyUnicodeTranslateError_SetStart(PyObject *, Py_ssize_t); /* get the value of the end attribute (the int *may not be NULL) return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_GetEnd(PyObject *, Py_ssize_t *); PyAPI_FUNC(int) PyUnicodeDecodeError_GetEnd(PyObject *, Py_ssize_t *); PyAPI_FUNC(int) PyUnicodeTranslateError_GetEnd(PyObject *, Py_ssize_t *); /* assign a new value to the end attribute return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_SetEnd(PyObject *, Py_ssize_t); PyAPI_FUNC(int) PyUnicodeDecodeError_SetEnd(PyObject *, Py_ssize_t); PyAPI_FUNC(int) PyUnicodeTranslateError_SetEnd(PyObject *, Py_ssize_t); /* get the value of the reason attribute */ PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetReason(PyObject *); PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_GetReason(PyObject *); PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetReason(PyObject *); /* assign a new value to the reason attribute return 0 on success, -1 on failure */ PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason( PyObject *exc, const char *reason /* UTF-8 encoded string */ ); PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason( PyObject *exc, const char *reason /* UTF-8 encoded string */ ); PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason( PyObject *exc, const char *reason /* UTF-8 encoded string */ ); /* These APIs aren't really part of the error implementation, but often needed to format error messages; the native C lib APIs are not available on all platforms, which is why we provide emulations for those platforms in Python/mysnprintf.c, WARNING: The return value of snprintf varies across platforms; do not rely on any particular behavior; eventually the C99 defn may be reliable. */ #if defined(MS_WIN32) && !defined(HAVE_SNPRINTF) # define HAVE_SNPRINTF # define snprintf _snprintf # define vsnprintf _vsnprintf #endif #include PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...) Py_GCC_ATTRIBUTE((format(printf, 3, 4))); PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) Py_GCC_ATTRIBUTE((format(printf, 3, 0))); #ifndef Py_LIMITED_API # define Py_CPYTHON_ERRORS_H # include "cpython/pyerrors.h" # undef Py_CPYTHON_ERRORS_H #endif #ifdef __cplusplus } #endif #endif /* !Py_ERRORS_H */ ================================================ FILE: thirdLibs/python3_8/include/pyexpat.h ================================================ /* Stuff to export relevant 'expat' entry points from pyexpat to other * parser modules, such as cElementTree. */ /* note: you must import expat.h before importing this module! */ #define PyExpat_CAPI_MAGIC "pyexpat.expat_CAPI 1.1" #define PyExpat_CAPSULE_NAME "pyexpat.expat_CAPI" struct PyExpat_CAPI { char* magic; /* set to PyExpat_CAPI_MAGIC */ int size; /* set to sizeof(struct PyExpat_CAPI) */ int MAJOR_VERSION; int MINOR_VERSION; int MICRO_VERSION; /* pointers to selected expat functions. add new functions at the end, if needed */ const XML_LChar * (*ErrorString)(enum XML_Error code); enum XML_Error (*GetErrorCode)(XML_Parser parser); XML_Size (*GetErrorColumnNumber)(XML_Parser parser); XML_Size (*GetErrorLineNumber)(XML_Parser parser); enum XML_Status (*Parse)( XML_Parser parser, const char *s, int len, int isFinal); XML_Parser (*ParserCreate_MM)( const XML_Char *encoding, const XML_Memory_Handling_Suite *memsuite, const XML_Char *namespaceSeparator); void (*ParserFree)(XML_Parser parser); void (*SetCharacterDataHandler)( XML_Parser parser, XML_CharacterDataHandler handler); void (*SetCommentHandler)( XML_Parser parser, XML_CommentHandler handler); void (*SetDefaultHandlerExpand)( XML_Parser parser, XML_DefaultHandler handler); void (*SetElementHandler)( XML_Parser parser, XML_StartElementHandler start, XML_EndElementHandler end); void (*SetNamespaceDeclHandler)( XML_Parser parser, XML_StartNamespaceDeclHandler start, XML_EndNamespaceDeclHandler end); void (*SetProcessingInstructionHandler)( XML_Parser parser, XML_ProcessingInstructionHandler handler); void (*SetUnknownEncodingHandler)( XML_Parser parser, XML_UnknownEncodingHandler handler, void *encodingHandlerData); void (*SetUserData)(XML_Parser parser, void *userData); void (*SetStartDoctypeDeclHandler)(XML_Parser parser, XML_StartDoctypeDeclHandler start); enum XML_Status (*SetEncoding)(XML_Parser parser, const XML_Char *encoding); int (*DefaultUnknownEncodingHandler)( void *encodingHandlerData, const XML_Char *name, XML_Encoding *info); /* might be none for expat < 2.1.0 */ int (*SetHashSalt)(XML_Parser parser, unsigned long hash_salt); /* always add new stuff to the end! */ }; ================================================ FILE: thirdLibs/python3_8/include/pyfpe.h ================================================ #ifndef Py_PYFPE_H #define Py_PYFPE_H /* These macros used to do something when Python was built with --with-fpectl, * but support for that was dropped in 3.7. We continue to define them though, * to avoid breaking API users. */ #define PyFPE_START_PROTECT(err_string, leave_stmt) #define PyFPE_END_PROTECT(v) #endif /* !Py_PYFPE_H */ ================================================ FILE: thirdLibs/python3_8/include/pyhash.h ================================================ #ifndef Py_HASH_H #define Py_HASH_H #ifdef __cplusplus extern "C" { #endif /* Helpers for hash functions */ #ifndef Py_LIMITED_API PyAPI_FUNC(Py_hash_t) _Py_HashDouble(double); PyAPI_FUNC(Py_hash_t) _Py_HashPointer(void*); PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void*, Py_ssize_t); #endif /* Prime multiplier used in string and various other hashes. */ #define _PyHASH_MULTIPLIER 1000003UL /* 0xf4243 */ /* Parameters used for the numeric hash implementation. See notes for _Py_HashDouble in Python/pyhash.c. Numeric hashes are based on reduction modulo the prime 2**_PyHASH_BITS - 1. */ #if SIZEOF_VOID_P >= 8 # define _PyHASH_BITS 61 #else # define _PyHASH_BITS 31 #endif #define _PyHASH_MODULUS (((size_t)1 << _PyHASH_BITS) - 1) #define _PyHASH_INF 314159 #define _PyHASH_NAN 0 #define _PyHASH_IMAG _PyHASH_MULTIPLIER /* hash secret * * memory layout on 64 bit systems * cccccccc cccccccc cccccccc uc -- unsigned char[24] * pppppppp ssssssss ........ fnv -- two Py_hash_t * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t * ........ ........ ssssssss djbx33a -- 16 bytes padding + one Py_hash_t * ........ ........ eeeeeeee pyexpat XML hash salt * * memory layout on 32 bit systems * cccccccc cccccccc cccccccc uc * ppppssss ........ ........ fnv -- two Py_hash_t * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t (*) * ........ ........ ssss.... djbx33a -- 16 bytes padding + one Py_hash_t * ........ ........ eeee.... pyexpat XML hash salt * * (*) The siphash member may not be available on 32 bit platforms without * an unsigned int64 data type. */ #ifndef Py_LIMITED_API typedef union { /* ensure 24 bytes */ unsigned char uc[24]; /* two Py_hash_t for FNV */ struct { Py_hash_t prefix; Py_hash_t suffix; } fnv; /* two uint64 for SipHash24 */ struct { uint64_t k0; uint64_t k1; } siphash; /* a different (!) Py_hash_t for small string optimization */ struct { unsigned char padding[16]; Py_hash_t suffix; } djbx33a; struct { unsigned char padding[16]; Py_hash_t hashsalt; } expat; } _Py_HashSecret_t; PyAPI_DATA(_Py_HashSecret_t) _Py_HashSecret; #endif #ifdef Py_DEBUG PyAPI_DATA(int) _Py_HashSecret_Initialized; #endif /* hash function definition */ #ifndef Py_LIMITED_API typedef struct { Py_hash_t (*const hash)(const void *, Py_ssize_t); const char *name; const int hash_bits; const int seed_bits; } PyHash_FuncDef; PyAPI_FUNC(PyHash_FuncDef*) PyHash_GetFuncDef(void); #endif /* cutoff for small string DJBX33A optimization in range [1, cutoff). * * About 50% of the strings in a typical Python application are smaller than * 6 to 7 chars. However DJBX33A is vulnerable to hash collision attacks. * NEVER use DJBX33A for long strings! * * A Py_HASH_CUTOFF of 0 disables small string optimization. 32 bit platforms * should use a smaller cutoff because it is easier to create colliding * strings. A cutoff of 7 on 64bit platforms and 5 on 32bit platforms should * provide a decent safety margin. */ #ifndef Py_HASH_CUTOFF # define Py_HASH_CUTOFF 0 #elif (Py_HASH_CUTOFF > 7 || Py_HASH_CUTOFF < 0) # error Py_HASH_CUTOFF must in range 0...7. #endif /* Py_HASH_CUTOFF */ /* hash algorithm selection * * The values for Py_HASH_SIPHASH24 and Py_HASH_FNV are hard-coded in the * configure script. * * - FNV is available on all platforms and architectures. * - SIPHASH24 only works on platforms that don't require aligned memory for integers. * - With EXTERNAL embedders can provide an alternative implementation with:: * * PyHash_FuncDef PyHash_Func = {...}; * * XXX: Figure out __declspec() for extern PyHash_FuncDef. */ #define Py_HASH_EXTERNAL 0 #define Py_HASH_SIPHASH24 1 #define Py_HASH_FNV 2 #ifndef Py_HASH_ALGORITHM # ifndef HAVE_ALIGNED_REQUIRED # define Py_HASH_ALGORITHM Py_HASH_SIPHASH24 # else # define Py_HASH_ALGORITHM Py_HASH_FNV # endif /* uint64_t && uint32_t && aligned */ #endif /* Py_HASH_ALGORITHM */ #ifdef __cplusplus } #endif #endif /* !Py_HASH_H */ ================================================ FILE: thirdLibs/python3_8/include/pylifecycle.h ================================================ /* Interfaces to configure, query, create & destroy the Python runtime */ #ifndef Py_PYLIFECYCLE_H #define Py_PYLIFECYCLE_H #ifdef __cplusplus extern "C" { #endif /* Initialization and finalization */ PyAPI_FUNC(void) Py_Initialize(void); PyAPI_FUNC(void) Py_InitializeEx(int); PyAPI_FUNC(void) Py_Finalize(void); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 PyAPI_FUNC(int) Py_FinalizeEx(void); #endif PyAPI_FUNC(int) Py_IsInitialized(void); /* Subinterpreter support */ PyAPI_FUNC(PyThreadState *) Py_NewInterpreter(void); PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *); /* Py_PyAtExit is for the atexit module, Py_AtExit is for low-level * exit functions. */ PyAPI_FUNC(int) Py_AtExit(void (*func)(void)); PyAPI_FUNC(void) _Py_NO_RETURN Py_Exit(int); /* Bootstrap __main__ (defined in Modules/main.c) */ PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv); PyAPI_FUNC(int) Py_BytesMain(int argc, char **argv); /* In pathconfig.c */ PyAPI_FUNC(void) Py_SetProgramName(const wchar_t *); PyAPI_FUNC(wchar_t *) Py_GetProgramName(void); PyAPI_FUNC(void) Py_SetPythonHome(const wchar_t *); PyAPI_FUNC(wchar_t *) Py_GetPythonHome(void); PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void); PyAPI_FUNC(wchar_t *) Py_GetPrefix(void); PyAPI_FUNC(wchar_t *) Py_GetExecPrefix(void); PyAPI_FUNC(wchar_t *) Py_GetPath(void); PyAPI_FUNC(void) Py_SetPath(const wchar_t *); #ifdef MS_WINDOWS int _Py_CheckPython3(void); #endif /* In their own files */ PyAPI_FUNC(const char *) Py_GetVersion(void); PyAPI_FUNC(const char *) Py_GetPlatform(void); PyAPI_FUNC(const char *) Py_GetCopyright(void); PyAPI_FUNC(const char *) Py_GetCompiler(void); PyAPI_FUNC(const char *) Py_GetBuildInfo(void); /* Signals */ typedef void (*PyOS_sighandler_t)(int); PyAPI_FUNC(PyOS_sighandler_t) PyOS_getsig(int); PyAPI_FUNC(PyOS_sighandler_t) PyOS_setsig(int, PyOS_sighandler_t); #ifndef Py_LIMITED_API # define Py_CPYTHON_PYLIFECYCLE_H # include "cpython/pylifecycle.h" # undef Py_CPYTHON_PYLIFECYCLE_H #endif #ifdef __cplusplus } #endif #endif /* !Py_PYLIFECYCLE_H */ ================================================ FILE: thirdLibs/python3_8/include/pymacconfig.h ================================================ #ifndef PYMACCONFIG_H #define PYMACCONFIG_H /* * This file moves some of the autoconf magic to compile-time * when building on MacOSX. This is needed for building 4-way * universal binaries and for 64-bit universal binaries because * the values redefined below aren't configure-time constant but * only compile-time constant in these scenarios. */ #if defined(__APPLE__) # undef SIZEOF_LONG # undef SIZEOF_PTHREAD_T # undef SIZEOF_SIZE_T # undef SIZEOF_TIME_T # undef SIZEOF_VOID_P # undef SIZEOF__BOOL # undef SIZEOF_UINTPTR_T # undef SIZEOF_PTHREAD_T # undef WORDS_BIGENDIAN # undef DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754 # undef DOUBLE_IS_BIG_ENDIAN_IEEE754 # undef DOUBLE_IS_LITTLE_ENDIAN_IEEE754 # undef HAVE_GCC_ASM_FOR_X87 # undef VA_LIST_IS_ARRAY # if defined(__LP64__) && defined(__x86_64__) # define VA_LIST_IS_ARRAY 1 # endif # undef HAVE_LARGEFILE_SUPPORT # ifndef __LP64__ # define HAVE_LARGEFILE_SUPPORT 1 # endif # undef SIZEOF_LONG # ifdef __LP64__ # define SIZEOF__BOOL 1 # define SIZEOF__BOOL 1 # define SIZEOF_LONG 8 # define SIZEOF_PTHREAD_T 8 # define SIZEOF_SIZE_T 8 # define SIZEOF_TIME_T 8 # define SIZEOF_VOID_P 8 # define SIZEOF_UINTPTR_T 8 # define SIZEOF_PTHREAD_T 8 # else # ifdef __ppc__ # define SIZEOF__BOOL 4 # else # define SIZEOF__BOOL 1 # endif # define SIZEOF_LONG 4 # define SIZEOF_PTHREAD_T 4 # define SIZEOF_SIZE_T 4 # define SIZEOF_TIME_T 4 # define SIZEOF_VOID_P 4 # define SIZEOF_UINTPTR_T 4 # define SIZEOF_PTHREAD_T 4 # endif # if defined(__LP64__) /* MacOSX 10.4 (the first release to support 64-bit code * at all) only supports 64-bit in the UNIX layer. * Therefore suppress the toolbox-glue in 64-bit mode. */ /* In 64-bit mode setpgrp always has no arguments, in 32-bit * mode that depends on the compilation environment */ # undef SETPGRP_HAVE_ARG # endif #ifdef __BIG_ENDIAN__ #define WORDS_BIGENDIAN 1 #define DOUBLE_IS_BIG_ENDIAN_IEEE754 #else #define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 #endif /* __BIG_ENDIAN */ #ifdef __i386__ # define HAVE_GCC_ASM_FOR_X87 #endif /* * The definition in pyconfig.h is only valid on the OS release * where configure ran on and not necessarily for all systems where * the executable can be used on. * * Specifically: OSX 10.4 has limited supported for '%zd', while * 10.5 has full support for '%zd'. A binary built on 10.5 won't * work properly on 10.4 unless we suppress the definition * of PY_FORMAT_SIZE_T */ #undef PY_FORMAT_SIZE_T #endif /* defined(_APPLE__) */ #endif /* PYMACCONFIG_H */ ================================================ FILE: thirdLibs/python3_8/include/pymacro.h ================================================ #ifndef Py_PYMACRO_H #define Py_PYMACRO_H /* Minimum value between x and y */ #define Py_MIN(x, y) (((x) > (y)) ? (y) : (x)) /* Maximum value between x and y */ #define Py_MAX(x, y) (((x) > (y)) ? (x) : (y)) /* Absolute value of the number x */ #define Py_ABS(x) ((x) < 0 ? -(x) : (x)) #define _Py_XSTRINGIFY(x) #x /* Convert the argument to a string. For example, Py_STRINGIFY(123) is replaced with "123" by the preprocessor. Defines are also replaced by their value. For example Py_STRINGIFY(__LINE__) is replaced by the line number, not by "__LINE__". */ #define Py_STRINGIFY(x) _Py_XSTRINGIFY(x) /* Get the size of a structure member in bytes */ #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) /* Argument must be a char or an int in [-128, 127] or [0, 255]. */ #define Py_CHARMASK(c) ((unsigned char)((c) & 0xff)) /* Assert a build-time dependency, as an expression. Your compile will fail if the condition isn't true, or can't be evaluated by the compiler. This can be used in an expression: its value is 0. Example: #define foo_to_char(foo) \ ((char *)(foo) \ + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0)) Written by Rusty Russell, public domain, http://ccodearchive.net/ */ #define Py_BUILD_ASSERT_EXPR(cond) \ (sizeof(char [1 - 2*!(cond)]) - 1) #define Py_BUILD_ASSERT(cond) do { \ (void)Py_BUILD_ASSERT_EXPR(cond); \ } while(0) /* Get the number of elements in a visible array This does not work on pointers, or arrays declared as [], or function parameters. With correct compiler support, such usage will cause a build error (see Py_BUILD_ASSERT_EXPR). Written by Rusty Russell, public domain, http://ccodearchive.net/ Requires at GCC 3.1+ */ #if (defined(__GNUC__) && !defined(__STRICT_ANSI__) && \ (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ >= 4))) /* Two gcc extensions. &a[0] degrades to a pointer: a different type from an array */ #define Py_ARRAY_LENGTH(array) \ (sizeof(array) / sizeof((array)[0]) \ + Py_BUILD_ASSERT_EXPR(!__builtin_types_compatible_p(typeof(array), \ typeof(&(array)[0])))) #else #define Py_ARRAY_LENGTH(array) \ (sizeof(array) / sizeof((array)[0])) #endif /* Define macros for inline documentation. */ #define PyDoc_VAR(name) static const char name[] #define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str) #ifdef WITH_DOC_STRINGS #define PyDoc_STR(str) str #else #define PyDoc_STR(str) "" #endif /* Below "a" is a power of 2. */ /* Round down size "n" to be a multiple of "a". */ #define _Py_SIZE_ROUND_DOWN(n, a) ((size_t)(n) & ~(size_t)((a) - 1)) /* Round up size "n" to be a multiple of "a". */ #define _Py_SIZE_ROUND_UP(n, a) (((size_t)(n) + \ (size_t)((a) - 1)) & ~(size_t)((a) - 1)) /* Round pointer "p" down to the closest "a"-aligned address <= "p". */ #define _Py_ALIGN_DOWN(p, a) ((void *)((uintptr_t)(p) & ~(uintptr_t)((a) - 1))) /* Round pointer "p" up to the closest "a"-aligned address >= "p". */ #define _Py_ALIGN_UP(p, a) ((void *)(((uintptr_t)(p) + \ (uintptr_t)((a) - 1)) & ~(uintptr_t)((a) - 1))) /* Check if pointer "p" is aligned to "a"-bytes boundary. */ #define _Py_IS_ALIGNED(p, a) (!((uintptr_t)(p) & (uintptr_t)((a) - 1))) /* Use this for unused arguments in a function definition to silence compiler * warnings. Example: * * int func(int a, int Py_UNUSED(b)) { return a; } */ #if defined(__GNUC__) || defined(__clang__) # define Py_UNUSED(name) _unused_ ## name __attribute__((unused)) #else # define Py_UNUSED(name) _unused_ ## name #endif #define Py_UNREACHABLE() \ Py_FatalError("Unreachable C code path reached") #endif /* Py_PYMACRO_H */ ================================================ FILE: thirdLibs/python3_8/include/pymath.h ================================================ #ifndef Py_PYMATH_H #define Py_PYMATH_H #include "pyconfig.h" /* include for defines */ /************************************************************************** Symbols and macros to supply platform-independent interfaces to mathematical functions and constants **************************************************************************/ /* Python provides implementations for copysign, round and hypot in * Python/pymath.c just in case your math library doesn't provide the * functions. * *Note: PC/pyconfig.h defines copysign as _copysign */ #ifndef HAVE_COPYSIGN extern double copysign(double, double); #endif #ifndef HAVE_ROUND extern double round(double); #endif #ifndef HAVE_HYPOT extern double hypot(double, double); #endif /* extra declarations */ #ifndef _MSC_VER #ifndef __STDC__ extern double fmod (double, double); extern double frexp (double, int *); extern double ldexp (double, int); extern double modf (double, double *); extern double pow(double, double); #endif /* __STDC__ */ #endif /* _MSC_VER */ /* High precision definition of pi and e (Euler) * The values are taken from libc6's math.h. */ #ifndef Py_MATH_PIl #define Py_MATH_PIl 3.1415926535897932384626433832795029L #endif #ifndef Py_MATH_PI #define Py_MATH_PI 3.14159265358979323846 #endif #ifndef Py_MATH_El #define Py_MATH_El 2.7182818284590452353602874713526625L #endif #ifndef Py_MATH_E #define Py_MATH_E 2.7182818284590452354 #endif /* Tau (2pi) to 40 digits, taken from tauday.com/tau-digits. */ #ifndef Py_MATH_TAU #define Py_MATH_TAU 6.2831853071795864769252867665590057683943L #endif /* On x86, Py_FORCE_DOUBLE forces a floating-point number out of an x87 FPU register and into a 64-bit memory location, rounding from extended precision to double precision in the process. On other platforms it does nothing. */ /* we take double rounding as evidence of x87 usage */ #ifndef Py_LIMITED_API #ifndef Py_FORCE_DOUBLE # ifdef X87_DOUBLE_ROUNDING PyAPI_FUNC(double) _Py_force_double(double); # define Py_FORCE_DOUBLE(X) (_Py_force_double(X)) # else # define Py_FORCE_DOUBLE(X) (X) # endif #endif #endif #ifndef Py_LIMITED_API #ifdef HAVE_GCC_ASM_FOR_X87 PyAPI_FUNC(unsigned short) _Py_get_387controlword(void); PyAPI_FUNC(void) _Py_set_387controlword(unsigned short); #endif #endif /* Py_IS_NAN(X) * Return 1 if float or double arg is a NaN, else 0. * Caution: * X is evaluated more than once. * This may not work on all platforms. Each platform has *some* * way to spell this, though -- override in pyconfig.h if you have * a platform where it doesn't work. * Note: PC/pyconfig.h defines Py_IS_NAN as _isnan */ #ifndef Py_IS_NAN #if defined HAVE_DECL_ISNAN && HAVE_DECL_ISNAN == 1 #define Py_IS_NAN(X) isnan(X) #else #define Py_IS_NAN(X) ((X) != (X)) #endif #endif /* Py_IS_INFINITY(X) * Return 1 if float or double arg is an infinity, else 0. * Caution: * X is evaluated more than once. * This implementation may set the underflow flag if |X| is very small; * it really can't be implemented correctly (& easily) before C99. * Override in pyconfig.h if you have a better spelling on your platform. * Py_FORCE_DOUBLE is used to avoid getting false negatives from a * non-infinite value v sitting in an 80-bit x87 register such that * v becomes infinite when spilled from the register to 64-bit memory. * Note: PC/pyconfig.h defines Py_IS_INFINITY as _isinf */ #ifndef Py_IS_INFINITY # if defined HAVE_DECL_ISINF && HAVE_DECL_ISINF == 1 # define Py_IS_INFINITY(X) isinf(X) # else # define Py_IS_INFINITY(X) ((X) && \ (Py_FORCE_DOUBLE(X)*0.5 == Py_FORCE_DOUBLE(X))) # endif #endif /* Py_IS_FINITE(X) * Return 1 if float or double arg is neither infinite nor NAN, else 0. * Some compilers (e.g. VisualStudio) have intrisics for this, so a special * macro for this particular test is useful * Note: PC/pyconfig.h defines Py_IS_FINITE as _finite */ #ifndef Py_IS_FINITE #if defined HAVE_DECL_ISFINITE && HAVE_DECL_ISFINITE == 1 #define Py_IS_FINITE(X) isfinite(X) #elif defined HAVE_FINITE #define Py_IS_FINITE(X) finite(X) #else #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) #endif #endif /* HUGE_VAL is supposed to expand to a positive double infinity. Python * uses Py_HUGE_VAL instead because some platforms are broken in this * respect. We used to embed code in pyport.h to try to worm around that, * but different platforms are broken in conflicting ways. If you're on * a platform where HUGE_VAL is defined incorrectly, fiddle your Python * config to #define Py_HUGE_VAL to something that works on your platform. */ #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif /* Py_NAN * A value that evaluates to a NaN. On IEEE 754 platforms INF*0 or * INF/INF works. Define Py_NO_NAN in pyconfig.h if your platform * doesn't support NaNs. */ #if !defined(Py_NAN) && !defined(Py_NO_NAN) #if !defined(__INTEL_COMPILER) #define Py_NAN (Py_HUGE_VAL * 0.) #else /* __INTEL_COMPILER */ #if defined(ICC_NAN_STRICT) #pragma float_control(push) #pragma float_control(precise, on) #pragma float_control(except, on) #if defined(_MSC_VER) __declspec(noinline) #else /* Linux */ __attribute__((noinline)) #endif /* _MSC_VER */ static double __icc_nan() { return sqrt(-1.0); } #pragma float_control (pop) #define Py_NAN __icc_nan() #else /* ICC_NAN_RELAXED as default for Intel Compiler */ static const union { unsigned char buf[8]; double __icc_nan; } __nan_store = {0,0,0,0,0,0,0xf8,0x7f}; #define Py_NAN (__nan_store.__icc_nan) #endif /* ICC_NAN_STRICT */ #endif /* __INTEL_COMPILER */ #endif /* Py_OVERFLOWED(X) * Return 1 iff a libm function overflowed. Set errno to 0 before calling * a libm function, and invoke this macro after, passing the function * result. * Caution: * This isn't reliable. C99 no longer requires libm to set errno under * any exceptional condition, but does require +- HUGE_VAL return * values on overflow. A 754 box *probably* maps HUGE_VAL to a * double infinity, and we're cool if that's so, unless the input * was an infinity and an infinity is the expected result. A C89 * system sets errno to ERANGE, so we check for that too. We're * out of luck if a C99 754 box doesn't map HUGE_VAL to +Inf, or * if the returned result is a NaN, or if a C89 box returns HUGE_VAL * in non-overflow cases. * X is evaluated more than once. * Some platforms have better way to spell this, so expect some #ifdef'ery. * * OpenBSD uses 'isinf()' because a compiler bug on that platform causes * the longer macro version to be mis-compiled. This isn't optimal, and * should be removed once a newer compiler is available on that platform. * The system that had the failure was running OpenBSD 3.2 on Intel, with * gcc 2.95.3. * * According to Tim's checkin, the FreeBSD systems use isinf() to work * around a FPE bug on that platform. */ #if defined(__FreeBSD__) || defined(__OpenBSD__) #define Py_OVERFLOWED(X) isinf(X) #else #define Py_OVERFLOWED(X) ((X) != 0.0 && (errno == ERANGE || \ (X) == Py_HUGE_VAL || \ (X) == -Py_HUGE_VAL)) #endif /* Return whether integral type *type* is signed or not. */ #define _Py_IntegralTypeSigned(type) ((type)(-1) < 0) /* Return the maximum value of integral type *type*. */ #define _Py_IntegralTypeMax(type) ((_Py_IntegralTypeSigned(type)) ? (((((type)1 << (sizeof(type)*CHAR_BIT - 2)) - 1) << 1) + 1) : ~(type)0) /* Return the minimum value of integral type *type*. */ #define _Py_IntegralTypeMin(type) ((_Py_IntegralTypeSigned(type)) ? -_Py_IntegralTypeMax(type) - 1 : 0) /* Check whether *v* is in the range of integral type *type*. This is most * useful if *v* is floating-point, since demoting a floating-point *v* to an * integral type that cannot represent *v*'s integral part is undefined * behavior. */ #define _Py_InIntegralTypeRange(type, v) (_Py_IntegralTypeMin(type) <= v && v <= _Py_IntegralTypeMax(type)) #endif /* Py_PYMATH_H */ ================================================ FILE: thirdLibs/python3_8/include/pymem.h ================================================ /* The PyMem_ family: low-level memory allocation interfaces. See objimpl.h for the PyObject_ memory family. */ #ifndef Py_PYMEM_H #define Py_PYMEM_H #include "pyport.h" #ifdef __cplusplus extern "C" { #endif /* BEWARE: Each interface exports both functions and macros. Extension modules should use the functions, to ensure binary compatibility across Python versions. Because the Python implementation is free to change internal details, and the macros may (or may not) expose details for speed, if you do use the macros you must recompile your extensions with each Python release. Never mix calls to PyMem_ with calls to the platform malloc/realloc/ calloc/free. For example, on Windows different DLLs may end up using different heaps, and if you use PyMem_Malloc you'll get the memory from the heap used by the Python DLL; it could be a disaster if you free()'ed that directly in your own extension. Using PyMem_Free instead ensures Python can return the memory to the proper heap. As another example, in PYMALLOC_DEBUG mode, Python wraps all calls to all PyMem_ and PyObject_ memory functions in special debugging wrappers that add additional debugging info to dynamic memory blocks. The system routines have no idea what to do with that stuff, and the Python wrappers have no idea what to do with raw blocks obtained directly by the system routines then. The GIL must be held when using these APIs. */ /* * Raw memory interface * ==================== */ /* Functions Functions supplying platform-independent semantics for malloc/realloc/ free. These functions make sure that allocating 0 bytes returns a distinct non-NULL pointer (whenever possible -- if we're flat out of memory, NULL may be returned), even if the platform malloc and realloc don't. Returned pointers must be checked for NULL explicitly. No action is performed on failure (no exception is set, no warning is printed, etc). */ PyAPI_FUNC(void *) PyMem_Malloc(size_t size); PyAPI_FUNC(void *) PyMem_Realloc(void *ptr, size_t new_size); PyAPI_FUNC(void) PyMem_Free(void *ptr); /* Macros. */ /* PyMem_MALLOC(0) means malloc(1). Some systems would return NULL for malloc(0), which would be treated as an error. Some platforms would return a pointer with no memory behind it, which would break pymalloc. To solve these problems, allocate an extra byte. */ /* Returns NULL to indicate error if a negative size or size larger than Py_ssize_t can represent is supplied. Helps prevents security holes. */ #define PyMem_MALLOC(n) PyMem_Malloc(n) #define PyMem_REALLOC(p, n) PyMem_Realloc(p, n) #define PyMem_FREE(p) PyMem_Free(p) /* * Type-oriented memory interface * ============================== * * Allocate memory for n objects of the given type. Returns a new pointer * or NULL if the request was too large or memory allocation failed. Use * these macros rather than doing the multiplication yourself so that proper * overflow checking is always done. */ #define PyMem_New(type, n) \ ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ ( (type *) PyMem_Malloc((n) * sizeof(type)) ) ) #define PyMem_NEW(type, n) \ ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ ( (type *) PyMem_MALLOC((n) * sizeof(type)) ) ) /* * The value of (p) is always clobbered by this macro regardless of success. * The caller MUST check if (p) is NULL afterwards and deal with the memory * error if so. This means the original value of (p) MUST be saved for the * caller's memory error handler to not lose track of it. */ #define PyMem_Resize(p, type, n) \ ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ (type *) PyMem_Realloc((p), (n) * sizeof(type)) ) #define PyMem_RESIZE(p, type, n) \ ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ (type *) PyMem_REALLOC((p), (n) * sizeof(type)) ) /* PyMem{Del,DEL} are left over from ancient days, and shouldn't be used * anymore. They're just confusing aliases for PyMem_{Free,FREE} now. */ #define PyMem_Del PyMem_Free #define PyMem_DEL PyMem_FREE /* bpo-35053: expose _Py_tracemalloc_config for performance: _Py_NewReference() needs an efficient check to test if tracemalloc is tracing. It has to be defined in pymem.h, before object.h is included. */ struct _PyTraceMalloc_Config { /* Module initialized? Variable protected by the GIL */ enum { TRACEMALLOC_NOT_INITIALIZED, TRACEMALLOC_INITIALIZED, TRACEMALLOC_FINALIZED } initialized; /* Is tracemalloc tracing memory allocations? Variable protected by the GIL */ int tracing; /* limit of the number of frames in a traceback, 1 by default. Variable protected by the GIL. */ int max_nframe; /* use domain in trace key? Variable protected by the GIL. */ int use_domain; }; PyAPI_DATA(struct _PyTraceMalloc_Config) _Py_tracemalloc_config; #define _PyTraceMalloc_Config_INIT \ {.initialized = TRACEMALLOC_NOT_INITIALIZED, \ .tracing = 0, \ .max_nframe = 1, \ .use_domain = 0} #ifndef Py_LIMITED_API # define Py_CPYTHON_PYMEM_H # include "cpython/pymem.h" # undef Py_CPYTHON_PYMEM_H #endif #ifdef __cplusplus } #endif #endif /* !Py_PYMEM_H */ ================================================ FILE: thirdLibs/python3_8/include/pyport.h ================================================ #ifndef Py_PYPORT_H #define Py_PYPORT_H #include "pyconfig.h" /* include for defines */ #include /* Defines to build Python and its standard library: * * - Py_BUILD_CORE: Build Python core. Give access to Python internals, but * should not be used by third-party modules. * - Py_BUILD_CORE_BUILTIN: Build a Python stdlib module as a built-in module. * - Py_BUILD_CORE_MODULE: Build a Python stdlib module as a dynamic library. * * Py_BUILD_CORE_BUILTIN and Py_BUILD_CORE_MODULE imply Py_BUILD_CORE. * * On Windows, Py_BUILD_CORE_MODULE exports "PyInit_xxx" symbol, whereas * Py_BUILD_CORE_BUILTIN does not. */ #if defined(Py_BUILD_CORE_BUILTIN) && !defined(Py_BUILD_CORE) # define Py_BUILD_CORE #endif #if defined(Py_BUILD_CORE_MODULE) && !defined(Py_BUILD_CORE) # define Py_BUILD_CORE #endif /************************************************************************** Symbols and macros to supply platform-independent interfaces to basic C language & library operations whose spellings vary across platforms. Please try to make documentation here as clear as possible: by definition, the stuff here is trying to illuminate C's darkest corners. Config #defines referenced here: SIGNED_RIGHT_SHIFT_ZERO_FILLS Meaning: To be defined iff i>>j does not extend the sign bit when i is a signed integral type and i < 0. Used in: Py_ARITHMETIC_RIGHT_SHIFT Py_DEBUG Meaning: Extra checks compiled in for debug mode. Used in: Py_SAFE_DOWNCAST **************************************************************************/ /* typedefs for some C9X-defined synonyms for integral types. * * The names in Python are exactly the same as the C9X names, except with a * Py_ prefix. Until C9X is universally implemented, this is the only way * to ensure that Python gets reliable names that don't conflict with names * in non-Python code that are playing their own tricks to define the C9X * names. * * NOTE: don't go nuts here! Python has no use for *most* of the C9X * integral synonyms. Only define the ones we actually need. */ /* long long is required. Ensure HAVE_LONG_LONG is defined for compatibility. */ #ifndef HAVE_LONG_LONG #define HAVE_LONG_LONG 1 #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG long long /* If LLONG_MAX is defined in limits.h, use that. */ #define PY_LLONG_MIN LLONG_MIN #define PY_LLONG_MAX LLONG_MAX #define PY_ULLONG_MAX ULLONG_MAX #endif #define PY_UINT32_T uint32_t #define PY_UINT64_T uint64_t /* Signed variants of the above */ #define PY_INT32_T int32_t #define PY_INT64_T int64_t /* If PYLONG_BITS_IN_DIGIT is not defined then we'll use 30-bit digits if all the necessary integer types are available, and we're on a 64-bit platform (as determined by SIZEOF_VOID_P); otherwise we use 15-bit digits. */ #ifndef PYLONG_BITS_IN_DIGIT #if SIZEOF_VOID_P >= 8 #define PYLONG_BITS_IN_DIGIT 30 #else #define PYLONG_BITS_IN_DIGIT 15 #endif #endif /* uintptr_t is the C9X name for an unsigned integral type such that a * legitimate void* can be cast to uintptr_t and then back to void* again * without loss of information. Similarly for intptr_t, wrt a signed * integral type. */ typedef uintptr_t Py_uintptr_t; typedef intptr_t Py_intptr_t; /* Py_ssize_t is a signed integral type such that sizeof(Py_ssize_t) == * sizeof(size_t). C99 doesn't define such a thing directly (size_t is an * unsigned integral type). See PEP 353 for details. */ #ifdef HAVE_SSIZE_T typedef ssize_t Py_ssize_t; #elif SIZEOF_VOID_P == SIZEOF_SIZE_T typedef Py_intptr_t Py_ssize_t; #else # error "Python needs a typedef for Py_ssize_t in pyport.h." #endif /* Py_hash_t is the same size as a pointer. */ #define SIZEOF_PY_HASH_T SIZEOF_SIZE_T typedef Py_ssize_t Py_hash_t; /* Py_uhash_t is the unsigned equivalent needed to calculate numeric hash. */ #define SIZEOF_PY_UHASH_T SIZEOF_SIZE_T typedef size_t Py_uhash_t; /* Only used for compatibility with code that may not be PY_SSIZE_T_CLEAN. */ #ifdef PY_SSIZE_T_CLEAN typedef Py_ssize_t Py_ssize_clean_t; #else typedef int Py_ssize_clean_t; #endif /* Largest possible value of size_t. */ #define PY_SIZE_MAX SIZE_MAX /* Largest positive value of type Py_ssize_t. */ #define PY_SSIZE_T_MAX ((Py_ssize_t)(((size_t)-1)>>1)) /* Smallest negative value of type Py_ssize_t. */ #define PY_SSIZE_T_MIN (-PY_SSIZE_T_MAX-1) /* PY_FORMAT_SIZE_T is a platform-specific modifier for use in a printf * format to convert an argument with the width of a size_t or Py_ssize_t. * C99 introduced "z" for this purpose, but not all platforms support that; * e.g., MS compilers use "I" instead. * * These "high level" Python format functions interpret "z" correctly on * all platforms (Python interprets the format string itself, and does whatever * the platform C requires to convert a size_t/Py_ssize_t argument): * * PyBytes_FromFormat * PyErr_Format * PyBytes_FromFormatV * PyUnicode_FromFormatV * * Lower-level uses require that you interpolate the correct format modifier * yourself (e.g., calling printf, fprintf, sprintf, PyOS_snprintf); for * example, * * Py_ssize_t index; * fprintf(stderr, "index %" PY_FORMAT_SIZE_T "d sucks\n", index); * * That will expand to %ld, or %Id, or to something else correct for a * Py_ssize_t on the platform. */ #ifndef PY_FORMAT_SIZE_T # if SIZEOF_SIZE_T == SIZEOF_INT && !defined(__APPLE__) # define PY_FORMAT_SIZE_T "" # elif SIZEOF_SIZE_T == SIZEOF_LONG # define PY_FORMAT_SIZE_T "l" # elif defined(MS_WINDOWS) # define PY_FORMAT_SIZE_T "I" # else # error "This platform's pyconfig.h needs to define PY_FORMAT_SIZE_T" # endif #endif /* Py_LOCAL can be used instead of static to get the fastest possible calling * convention for functions that are local to a given module. * * Py_LOCAL_INLINE does the same thing, and also explicitly requests inlining, * for platforms that support that. * * If PY_LOCAL_AGGRESSIVE is defined before python.h is included, more * "aggressive" inlining/optimization is enabled for the entire module. This * may lead to code bloat, and may slow things down for those reasons. It may * also lead to errors, if the code relies on pointer aliasing. Use with * care. * * NOTE: You can only use this for functions that are entirely local to a * module; functions that are exported via method tables, callbacks, etc, * should keep using static. */ #if defined(_MSC_VER) # if defined(PY_LOCAL_AGGRESSIVE) /* enable more aggressive optimization for visual studio */ # pragma optimize("agtw", on) #endif /* ignore warnings if the compiler decides not to inline a function */ # pragma warning(disable: 4710) /* fastest possible local call under MSVC */ # define Py_LOCAL(type) static type __fastcall # define Py_LOCAL_INLINE(type) static __inline type __fastcall #else # define Py_LOCAL(type) static type # define Py_LOCAL_INLINE(type) static inline type #endif /* Py_MEMCPY is kept for backwards compatibility, * see https://bugs.python.org/issue28126 */ #define Py_MEMCPY memcpy #include #ifdef HAVE_IEEEFP_H #include /* needed for 'finite' declaration on some platforms */ #endif #include /* Moved here from the math section, before extern "C" */ /******************************************** * WRAPPER FOR and/or * ********************************************/ #ifdef TIME_WITH_SYS_TIME #include #include #else /* !TIME_WITH_SYS_TIME */ #ifdef HAVE_SYS_TIME_H #include #else /* !HAVE_SYS_TIME_H */ #include #endif /* !HAVE_SYS_TIME_H */ #endif /* !TIME_WITH_SYS_TIME */ /****************************** * WRAPPER FOR * ******************************/ /* NB caller must include */ #ifdef HAVE_SYS_SELECT_H #include #endif /* !HAVE_SYS_SELECT_H */ /******************************* * stat() and fstat() fiddling * *******************************/ #ifdef HAVE_SYS_STAT_H #include #elif defined(HAVE_STAT_H) #include #endif #ifndef S_IFMT /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */ #define S_IFMT 0170000 #endif #ifndef S_IFLNK /* Windows doesn't define S_IFLNK but posixmodule.c maps * IO_REPARSE_TAG_SYMLINK to S_IFLNK */ # define S_IFLNK 0120000 #endif #ifndef S_ISREG #define S_ISREG(x) (((x) & S_IFMT) == S_IFREG) #endif #ifndef S_ISDIR #define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR) #endif #ifndef S_ISCHR #define S_ISCHR(x) (((x) & S_IFMT) == S_IFCHR) #endif #ifdef __cplusplus /* Move this down here since some C++ #include's don't like to be included inside an extern "C" */ extern "C" { #endif /* Py_ARITHMETIC_RIGHT_SHIFT * C doesn't define whether a right-shift of a signed integer sign-extends * or zero-fills. Here a macro to force sign extension: * Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) * Return I >> J, forcing sign extension. Arithmetically, return the * floor of I/2**J. * Requirements: * I should have signed integer type. In the terminology of C99, this can * be either one of the five standard signed integer types (signed char, * short, int, long, long long) or an extended signed integer type. * J is an integer >= 0 and strictly less than the number of bits in the * type of I (because C doesn't define what happens for J outside that * range either). * TYPE used to specify the type of I, but is now ignored. It's been left * in for backwards compatibility with versions <= 2.6 or 3.0. * Caution: * I may be evaluated more than once. */ #ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \ ((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J)) #else #define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J)) #endif /* Py_FORCE_EXPANSION(X) * "Simply" returns its argument. However, macro expansions within the * argument are evaluated. This unfortunate trickery is needed to get * token-pasting to work as desired in some cases. */ #define Py_FORCE_EXPANSION(X) X /* Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) * Cast VALUE to type NARROW from type WIDE. In Py_DEBUG mode, this * assert-fails if any information is lost. * Caution: * VALUE may be evaluated more than once. */ #ifdef Py_DEBUG #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \ (assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE)) #else #define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE) #endif /* Py_SET_ERRNO_ON_MATH_ERROR(x) * If a libm function did not set errno, but it looks like the result * overflowed or not-a-number, set errno to ERANGE or EDOM. Set errno * to 0 before calling a libm function, and invoke this macro after, * passing the function result. * Caution: * This isn't reliable. See Py_OVERFLOWED comments. * X is evaluated more than once. */ #if defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(__hpux) && defined(__ia64)) #define _Py_SET_EDOM_FOR_NAN(X) if (isnan(X)) errno = EDOM; #else #define _Py_SET_EDOM_FOR_NAN(X) ; #endif #define Py_SET_ERRNO_ON_MATH_ERROR(X) \ do { \ if (errno == 0) { \ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ errno = ERANGE; \ else _Py_SET_EDOM_FOR_NAN(X) \ } \ } while(0) /* Py_SET_ERANGE_IF_OVERFLOW(x) * An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility. */ #define Py_SET_ERANGE_IF_OVERFLOW(X) Py_SET_ERRNO_ON_MATH_ERROR(X) /* Py_ADJUST_ERANGE1(x) * Py_ADJUST_ERANGE2(x, y) * Set errno to 0 before calling a libm function, and invoke one of these * macros after, passing the function result(s) (Py_ADJUST_ERANGE2 is useful * for functions returning complex results). This makes two kinds of * adjustments to errno: (A) If it looks like the platform libm set * errno=ERANGE due to underflow, clear errno. (B) If it looks like the * platform libm overflowed but didn't set errno, force errno to ERANGE. In * effect, we're trying to force a useful implementation of C89 errno * behavior. * Caution: * This isn't reliable. See Py_OVERFLOWED comments. * X and Y may be evaluated more than once. */ #define Py_ADJUST_ERANGE1(X) \ do { \ if (errno == 0) { \ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \ errno = ERANGE; \ } \ else if (errno == ERANGE && (X) == 0.0) \ errno = 0; \ } while(0) #define Py_ADJUST_ERANGE2(X, Y) \ do { \ if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \ (Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \ if (errno == 0) \ errno = ERANGE; \ } \ else if (errno == ERANGE) \ errno = 0; \ } while(0) /* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are * required to support the short float repr introduced in Python 3.1) require * that the floating-point unit that's being used for arithmetic operations * on C doubles is set to use 53-bit precision. It also requires that the * FPU rounding mode is round-half-to-even, but that's less often an issue. * * If your FPU isn't already set to 53-bit precision/round-half-to-even, and * you want to make use of _Py_dg_strtod and _Py_dg_dtoa, then you should * * #define HAVE_PY_SET_53BIT_PRECISION 1 * * and also give appropriate definitions for the following three macros: * * _PY_SET_53BIT_PRECISION_START : store original FPU settings, and * set FPU to 53-bit precision/round-half-to-even * _PY_SET_53BIT_PRECISION_END : restore original FPU settings * _PY_SET_53BIT_PRECISION_HEADER : any variable declarations needed to * use the two macros above. * * The macros are designed to be used within a single C function: see * Python/pystrtod.c for an example of their use. */ /* get and set x87 control word for gcc/x86 */ #ifdef HAVE_GCC_ASM_FOR_X87 #define HAVE_PY_SET_53BIT_PRECISION 1 /* _Py_get/set_387controlword functions are defined in Python/pymath.c */ #define _Py_SET_53BIT_PRECISION_HEADER \ unsigned short old_387controlword, new_387controlword #define _Py_SET_53BIT_PRECISION_START \ do { \ old_387controlword = _Py_get_387controlword(); \ new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \ if (new_387controlword != old_387controlword) \ _Py_set_387controlword(new_387controlword); \ } while (0) #define _Py_SET_53BIT_PRECISION_END \ if (new_387controlword != old_387controlword) \ _Py_set_387controlword(old_387controlword) #endif /* get and set x87 control word for VisualStudio/x86 */ #if defined(_MSC_VER) && !defined(_WIN64) && !defined(_M_ARM) /* x87 not supported in 64-bit or ARM */ #define HAVE_PY_SET_53BIT_PRECISION 1 #define _Py_SET_53BIT_PRECISION_HEADER \ unsigned int old_387controlword, new_387controlword, out_387controlword /* We use the __control87_2 function to set only the x87 control word. The SSE control word is unaffected. */ #define _Py_SET_53BIT_PRECISION_START \ do { \ __control87_2(0, 0, &old_387controlword, NULL); \ new_387controlword = \ (old_387controlword & ~(_MCW_PC | _MCW_RC)) | (_PC_53 | _RC_NEAR); \ if (new_387controlword != old_387controlword) \ __control87_2(new_387controlword, _MCW_PC | _MCW_RC, \ &out_387controlword, NULL); \ } while (0) #define _Py_SET_53BIT_PRECISION_END \ do { \ if (new_387controlword != old_387controlword) \ __control87_2(old_387controlword, _MCW_PC | _MCW_RC, \ &out_387controlword, NULL); \ } while (0) #endif #ifdef HAVE_GCC_ASM_FOR_MC68881 #define HAVE_PY_SET_53BIT_PRECISION 1 #define _Py_SET_53BIT_PRECISION_HEADER \ unsigned int old_fpcr, new_fpcr #define _Py_SET_53BIT_PRECISION_START \ do { \ __asm__ ("fmove.l %%fpcr,%0" : "=g" (old_fpcr)); \ /* Set double precision / round to nearest. */ \ new_fpcr = (old_fpcr & ~0xf0) | 0x80; \ if (new_fpcr != old_fpcr) \ __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (new_fpcr)); \ } while (0) #define _Py_SET_53BIT_PRECISION_END \ do { \ if (new_fpcr != old_fpcr) \ __asm__ volatile ("fmove.l %0,%%fpcr" : : "g" (old_fpcr)); \ } while (0) #endif /* default definitions are empty */ #ifndef HAVE_PY_SET_53BIT_PRECISION #define _Py_SET_53BIT_PRECISION_HEADER #define _Py_SET_53BIT_PRECISION_START #define _Py_SET_53BIT_PRECISION_END #endif /* If we can't guarantee 53-bit precision, don't use the code in Python/dtoa.c, but fall back to standard code. This means that repr of a float will be long (17 sig digits). Realistically, there are two things that could go wrong: (1) doubles aren't IEEE 754 doubles, or (2) we're on x86 with the rounding precision set to 64-bits (extended precision), and we don't know how to change the rounding precision. */ #if !defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) && \ !defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) && \ !defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754) #define PY_NO_SHORT_FLOAT_REPR #endif /* double rounding is symptomatic of use of extended precision on x86. If we're seeing double rounding, and we don't have any mechanism available for changing the FPU rounding precision, then don't use Python/dtoa.c. */ #if defined(X87_DOUBLE_ROUNDING) && !defined(HAVE_PY_SET_53BIT_PRECISION) #define PY_NO_SHORT_FLOAT_REPR #endif /* Py_DEPRECATED(version) * Declare a variable, type, or function deprecated. * The macro must be placed before the declaration. * Usage: * Py_DEPRECATED(3.3) extern int old_var; * Py_DEPRECATED(3.4) typedef int T1; * Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void); */ #if defined(__GNUC__) \ && ((__GNUC__ >= 4) || (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__)) #elif defined(_MSC_VER) #define Py_DEPRECATED(VERSION) __declspec(deprecated( \ "deprecated in " #VERSION)) #else #define Py_DEPRECATED(VERSION_UNUSED) #endif /* _Py_HOT_FUNCTION * The hot attribute on a function is used to inform the compiler that the * function is a hot spot of the compiled program. The function is optimized * more aggressively and on many target it is placed into special subsection of * the text section so all hot functions appears close together improving * locality. * * Usage: * int _Py_HOT_FUNCTION x(void) { return 3; } * * Issue #28618: This attribute must not be abused, otherwise it can have a * negative effect on performance. Only the functions were Python spend most of * its time must use it. Use a profiler when running performance benchmark * suite to find these functions. */ #if defined(__GNUC__) \ && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) #define _Py_HOT_FUNCTION __attribute__((hot)) #else #define _Py_HOT_FUNCTION #endif /* _Py_NO_INLINE * Disable inlining on a function. For example, it helps to reduce the C stack * consumption. * * Usage: * int _Py_NO_INLINE x(void) { return 3; } */ #if defined(_MSC_VER) # define _Py_NO_INLINE __declspec(noinline) #elif defined(__GNUC__) || defined(__clang__) # define _Py_NO_INLINE __attribute__ ((noinline)) #else # define _Py_NO_INLINE #endif /************************************************************************** Prototypes that are missing from the standard include files on some systems (and possibly only some versions of such systems.) Please be conservative with adding new ones, document them and enclose them in platform-specific #ifdefs. **************************************************************************/ #ifdef SOLARIS /* Unchecked */ extern int gethostname(char *, int); #endif #ifdef HAVE__GETPTY #include /* we need to import mode_t */ extern char * _getpty(int *, int, mode_t, int); #endif /* On QNX 6, struct termio must be declared by including sys/termio.h if TCGETA, TCSETA, TCSETAW, or TCSETAF are used. sys/termio.h must be included before termios.h or it will generate an error. */ #if defined(HAVE_SYS_TERMIO_H) && !defined(__hpux) #include #endif /* On 4.4BSD-descendants, ctype functions serves the whole range of * wchar_t character set rather than single byte code points only. * This characteristic can break some operations of string object * including str.upper() and str.split() on UTF-8 locales. This * workaround was provided by Tim Robbins of FreeBSD project. */ #if defined(__APPLE__) # define _PY_PORT_CTYPE_UTF8_ISSUE #endif #ifdef _PY_PORT_CTYPE_UTF8_ISSUE #ifndef __cplusplus /* The workaround below is unsafe in C++ because * the defines these symbols as real functions, * with a slightly different signature. * See issue #10910 */ #include #include #undef isalnum #define isalnum(c) iswalnum(btowc(c)) #undef isalpha #define isalpha(c) iswalpha(btowc(c)) #undef islower #define islower(c) iswlower(btowc(c)) #undef isspace #define isspace(c) iswspace(btowc(c)) #undef isupper #define isupper(c) iswupper(btowc(c)) #undef tolower #define tolower(c) towlower(btowc(c)) #undef toupper #define toupper(c) towupper(btowc(c)) #endif #endif /* Declarations for symbol visibility. PyAPI_FUNC(type): Declares a public Python API function and return type PyAPI_DATA(type): Declares public Python data and its type PyMODINIT_FUNC: A Python module init function. If these functions are inside the Python core, they are private to the core. If in an extension module, it may be declared with external linkage depending on the platform. As a number of platforms support/require "__declspec(dllimport/dllexport)", we support a HAVE_DECLSPEC_DLL macro to save duplication. */ /* All windows ports, except cygwin, are handled in PC/pyconfig.h. Cygwin is the only other autoconf platform requiring special linkage handling and it uses __declspec(). */ #if defined(__CYGWIN__) # define HAVE_DECLSPEC_DLL #endif /* only get special linkage if built as shared or platform is Cygwin */ #if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__) # if defined(HAVE_DECLSPEC_DLL) # if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) # define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE # define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE /* module init functions inside the core need no external linkage */ /* except for Cygwin to handle embedding */ # if defined(__CYGWIN__) # define PyMODINIT_FUNC __declspec(dllexport) PyObject* # else /* __CYGWIN__ */ # define PyMODINIT_FUNC PyObject* # endif /* __CYGWIN__ */ # else /* Py_BUILD_CORE */ /* Building an extension module, or an embedded situation */ /* public Python functions and data are imported */ /* Under Cygwin, auto-import functions to prevent compilation */ /* failures similar to those described at the bottom of 4.1: */ /* http://docs.python.org/extending/windows.html#a-cookbook-approach */ # if !defined(__CYGWIN__) # define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE # endif /* !__CYGWIN__ */ # define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE /* module init functions outside the core must be exported */ # if defined(__cplusplus) # define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject* # else /* __cplusplus */ # define PyMODINIT_FUNC __declspec(dllexport) PyObject* # endif /* __cplusplus */ # endif /* Py_BUILD_CORE */ # endif /* HAVE_DECLSPEC_DLL */ #endif /* Py_ENABLE_SHARED */ /* If no external linkage macros defined by now, create defaults */ #ifndef PyAPI_FUNC # define PyAPI_FUNC(RTYPE) RTYPE #endif #ifndef PyAPI_DATA # define PyAPI_DATA(RTYPE) extern RTYPE #endif #ifndef PyMODINIT_FUNC # if defined(__cplusplus) # define PyMODINIT_FUNC extern "C" PyObject* # else /* __cplusplus */ # define PyMODINIT_FUNC PyObject* # endif /* __cplusplus */ #endif /* limits.h constants that may be missing */ #ifndef INT_MAX #define INT_MAX 2147483647 #endif #ifndef LONG_MAX #if SIZEOF_LONG == 4 #define LONG_MAX 0X7FFFFFFFL #elif SIZEOF_LONG == 8 #define LONG_MAX 0X7FFFFFFFFFFFFFFFL #else #error "could not set LONG_MAX in pyport.h" #endif #endif #ifndef LONG_MIN #define LONG_MIN (-LONG_MAX-1) #endif #ifndef LONG_BIT #define LONG_BIT (8 * SIZEOF_LONG) #endif #if LONG_BIT != 8 * SIZEOF_LONG /* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent * 32-bit platforms using gcc. We try to catch that here at compile-time * rather than waiting for integer multiplication to trigger bogus * overflows. */ #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." #endif #ifdef __cplusplus } #endif /* * Hide GCC attributes from compilers that don't support them. */ #if (!defined(__GNUC__) || __GNUC__ < 2 || \ (__GNUC__ == 2 && __GNUC_MINOR__ < 7) ) #define Py_GCC_ATTRIBUTE(x) #else #define Py_GCC_ATTRIBUTE(x) __attribute__(x) #endif /* * Specify alignment on compilers that support it. */ #if defined(__GNUC__) && __GNUC__ >= 3 #define Py_ALIGNED(x) __attribute__((aligned(x))) #else #define Py_ALIGNED(x) #endif /* Eliminate end-of-loop code not reached warnings from SunPro C * when using do{...}while(0) macros */ #ifdef __SUNPRO_C #pragma error_messages (off,E_END_OF_LOOP_CODE_NOT_REACHED) #endif #ifndef Py_LL #define Py_LL(x) x##LL #endif #ifndef Py_ULL #define Py_ULL(x) Py_LL(x##U) #endif #define Py_VA_COPY va_copy /* * Convenient macros to deal with endianness of the platform. WORDS_BIGENDIAN is * detected by configure and defined in pyconfig.h. The code in pyconfig.h * also takes care of Apple's universal builds. */ #ifdef WORDS_BIGENDIAN #define PY_BIG_ENDIAN 1 #define PY_LITTLE_ENDIAN 0 #else #define PY_BIG_ENDIAN 0 #define PY_LITTLE_ENDIAN 1 #endif #ifdef Py_BUILD_CORE /* * Macros to protect CRT calls against instant termination when passed an * invalid parameter (issue23524). */ #if defined _MSC_VER && _MSC_VER >= 1900 extern _invalid_parameter_handler _Py_silent_invalid_parameter_handler; #define _Py_BEGIN_SUPPRESS_IPH { _invalid_parameter_handler _Py_old_handler = \ _set_thread_local_invalid_parameter_handler(_Py_silent_invalid_parameter_handler); #define _Py_END_SUPPRESS_IPH _set_thread_local_invalid_parameter_handler(_Py_old_handler); } #else #define _Py_BEGIN_SUPPRESS_IPH #define _Py_END_SUPPRESS_IPH #endif /* _MSC_VER >= 1900 */ #endif /* Py_BUILD_CORE */ #ifdef __ANDROID__ /* The Android langinfo.h header is not used. */ # undef HAVE_LANGINFO_H # undef CODESET #endif /* Maximum value of the Windows DWORD type */ #define PY_DWORD_MAX 4294967295U /* This macro used to tell whether Python was built with multithreading * enabled. Now multithreading is always enabled, but keep the macro * for compatibility. */ #ifndef WITH_THREAD # define WITH_THREAD #endif /* Check that ALT_SOABI is consistent with Py_TRACE_REFS: ./configure --with-trace-refs should must be used to define Py_TRACE_REFS */ #if defined(ALT_SOABI) && defined(Py_TRACE_REFS) # error "Py_TRACE_REFS ABI is not compatible with release and debug ABI" #endif #if defined(__ANDROID__) || defined(__VXWORKS__) /* Ignore the locale encoding: force UTF-8 */ # define _Py_FORCE_UTF8_LOCALE #endif #if defined(_Py_FORCE_UTF8_LOCALE) || defined(__APPLE__) /* Use UTF-8 as filesystem encoding */ # define _Py_FORCE_UTF8_FS_ENCODING #endif /* Mark a function which cannot return. Example: PyAPI_FUNC(void) _Py_NO_RETURN PyThread_exit_thread(void); */ #if defined(__clang__) || \ (defined(__GNUC__) && \ ((__GNUC__ >= 3) || \ (__GNUC__ == 2) && (__GNUC_MINOR__ >= 5))) # define _Py_NO_RETURN __attribute__((__noreturn__)) #elif defined(_MSC_VER) # define _Py_NO_RETURN __declspec(noreturn) #else # define _Py_NO_RETURN #endif #endif /* Py_PYPORT_H */ ================================================ FILE: thirdLibs/python3_8/include/pystate.h ================================================ /* Thread and interpreter state structures and their interfaces */ #ifndef Py_PYSTATE_H #define Py_PYSTATE_H #ifdef __cplusplus extern "C" { #endif #include "pythread.h" /* This limitation is for performance and simplicity. If needed it can be removed (with effort). */ #define MAX_CO_EXTRA_USERS 255 /* Forward declarations for PyFrameObject, PyThreadState and PyInterpreterState */ struct _frame; struct _ts; struct _is; /* struct _ts is defined in cpython/pystate.h */ typedef struct _ts PyThreadState; /* struct _is is defined in internal/pycore_pystate.h */ typedef struct _is PyInterpreterState; PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_New(void); PyAPI_FUNC(void) PyInterpreterState_Clear(PyInterpreterState *); PyAPI_FUNC(void) PyInterpreterState_Delete(PyInterpreterState *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03080000 /* New in 3.8 */ PyAPI_FUNC(PyObject *) PyInterpreterState_GetDict(PyInterpreterState *); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000 /* New in 3.7 */ PyAPI_FUNC(int64_t) PyInterpreterState_GetID(PyInterpreterState *); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* State unique per thread */ /* New in 3.3 */ PyAPI_FUNC(int) PyState_AddModule(PyObject*, struct PyModuleDef*); PyAPI_FUNC(int) PyState_RemoveModule(struct PyModuleDef*); #endif PyAPI_FUNC(PyObject*) PyState_FindModule(struct PyModuleDef*); PyAPI_FUNC(PyThreadState *) PyThreadState_New(PyInterpreterState *); PyAPI_FUNC(void) PyThreadState_Clear(PyThreadState *); PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *); PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void); /* Get the current thread state. When the current thread state is NULL, this issues a fatal error (so that the caller needn't check for NULL). The caller must hold the GIL. See also PyThreadState_GET() and _PyThreadState_GET(). */ PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void); /* Get the current Python thread state. Macro using PyThreadState_Get() or _PyThreadState_GET() depending if pycore_pystate.h is included or not (this header redefines the macro). If PyThreadState_Get() is used, issue a fatal error if the current thread state is NULL. See also PyThreadState_Get() and _PyThreadState_GET(). */ #define PyThreadState_GET() PyThreadState_Get() PyAPI_FUNC(PyThreadState *) PyThreadState_Swap(PyThreadState *); PyAPI_FUNC(PyObject *) PyThreadState_GetDict(void); PyAPI_FUNC(int) PyThreadState_SetAsyncExc(unsigned long, PyObject *); typedef enum {PyGILState_LOCKED, PyGILState_UNLOCKED} PyGILState_STATE; /* Ensure that the current thread is ready to call the Python C API, regardless of the current state of Python, or of its thread lock. This may be called as many times as desired by a thread so long as each call is matched with a call to PyGILState_Release(). In general, other thread-state APIs may be used between _Ensure() and _Release() calls, so long as the thread-state is restored to its previous state before the Release(). For example, normal use of the Py_BEGIN_ALLOW_THREADS/ Py_END_ALLOW_THREADS macros are acceptable. The return value is an opaque "handle" to the thread state when PyGILState_Ensure() was called, and must be passed to PyGILState_Release() to ensure Python is left in the same state. Even though recursive calls are allowed, these handles can *not* be shared - each unique call to PyGILState_Ensure must save the handle for its call to PyGILState_Release. When the function returns, the current thread will hold the GIL. Failure is a fatal error. */ PyAPI_FUNC(PyGILState_STATE) PyGILState_Ensure(void); /* Release any resources previously acquired. After this call, Python's state will be the same as it was prior to the corresponding PyGILState_Ensure() call (but generally this state will be unknown to the caller, hence the use of the GILState API.) Every call to PyGILState_Ensure must be matched by a call to PyGILState_Release on the same thread. */ PyAPI_FUNC(void) PyGILState_Release(PyGILState_STATE); /* Helper/diagnostic function - get the current thread state for this thread. May return NULL if no GILState API has been used on the current thread. Note that the main thread always has such a thread-state, even if no auto-thread-state call has been made on the main thread. */ PyAPI_FUNC(PyThreadState *) PyGILState_GetThisThreadState(void); #ifndef Py_LIMITED_API # define Py_CPYTHON_PYSTATE_H # include "cpython/pystate.h" # undef Py_CPYTHON_PYSTATE_H #endif #ifdef __cplusplus } #endif #endif /* !Py_PYSTATE_H */ ================================================ FILE: thirdLibs/python3_8/include/pystrcmp.h ================================================ #ifndef Py_STRCMP_H #define Py_STRCMP_H #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(int) PyOS_mystrnicmp(const char *, const char *, Py_ssize_t); PyAPI_FUNC(int) PyOS_mystricmp(const char *, const char *); #ifdef MS_WINDOWS #define PyOS_strnicmp strnicmp #define PyOS_stricmp stricmp #else #define PyOS_strnicmp PyOS_mystrnicmp #define PyOS_stricmp PyOS_mystricmp #endif #ifdef __cplusplus } #endif #endif /* !Py_STRCMP_H */ ================================================ FILE: thirdLibs/python3_8/include/pystrhex.h ================================================ #ifndef Py_STRHEX_H #define Py_STRHEX_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API /* Returns a str() containing the hex representation of argbuf. */ PyAPI_FUNC(PyObject*) _Py_strhex(const char* argbuf, const Py_ssize_t arglen); /* Returns a bytes() containing the ASCII hex representation of argbuf. */ PyAPI_FUNC(PyObject*) _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen); /* These variants include support for a separator between every N bytes: */ PyAPI_FUNC(PyObject*) _Py_strhex_with_sep(const char* argbuf, const Py_ssize_t arglen, const PyObject* sep, const int bytes_per_group); PyAPI_FUNC(PyObject*) _Py_strhex_bytes_with_sep(const char* argbuf, const Py_ssize_t arglen, const PyObject* sep, const int bytes_per_group); #endif /* !Py_LIMITED_API */ #ifdef __cplusplus } #endif #endif /* !Py_STRHEX_H */ ================================================ FILE: thirdLibs/python3_8/include/pystrtod.h ================================================ #ifndef Py_STRTOD_H #define Py_STRTOD_H #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(double) PyOS_string_to_double(const char *str, char **endptr, PyObject *overflow_exception); /* The caller is responsible for calling PyMem_Free to free the buffer that's is returned. */ PyAPI_FUNC(char *) PyOS_double_to_string(double val, char format_code, int precision, int flags, int *type); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _Py_string_to_number_with_underscores( const char *str, Py_ssize_t len, const char *what, PyObject *obj, void *arg, PyObject *(*innerfunc)(const char *, Py_ssize_t, void *)); PyAPI_FUNC(double) _Py_parse_inf_or_nan(const char *p, char **endptr); #endif /* PyOS_double_to_string's "flags" parameter can be set to 0 or more of: */ #define Py_DTSF_SIGN 0x01 /* always add the sign */ #define Py_DTSF_ADD_DOT_0 0x02 /* if the result is an integer add ".0" */ #define Py_DTSF_ALT 0x04 /* "alternate" formatting. it's format_code specific */ /* PyOS_double_to_string's "type", if non-NULL, will be set to one of: */ #define Py_DTST_FINITE 0 #define Py_DTST_INFINITE 1 #define Py_DTST_NAN 2 #ifdef __cplusplus } #endif #endif /* !Py_STRTOD_H */ ================================================ FILE: thirdLibs/python3_8/include/pythonrun.h ================================================ /* Interfaces to parse and execute pieces of python code */ #ifndef Py_PYTHONRUN_H #define Py_PYTHONRUN_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API PyAPI_FUNC(int) PyRun_SimpleStringFlags(const char *, PyCompilerFlags *); PyAPI_FUNC(int) PyRun_AnyFileExFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ int closeit, PyCompilerFlags *flags); PyAPI_FUNC(int) PyRun_SimpleFileExFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ int closeit, PyCompilerFlags *flags); PyAPI_FUNC(int) PyRun_InteractiveOneFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ PyCompilerFlags *flags); PyAPI_FUNC(int) PyRun_InteractiveOneObject( FILE *fp, PyObject *filename, PyCompilerFlags *flags); PyAPI_FUNC(int) PyRun_InteractiveLoopFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ PyCompilerFlags *flags); PyAPI_FUNC(struct _mod *) PyParser_ASTFromString( const char *s, const char *filename, /* decoded from the filesystem encoding */ int start, PyCompilerFlags *flags, PyArena *arena); PyAPI_FUNC(struct _mod *) PyParser_ASTFromStringObject( const char *s, PyObject *filename, int start, PyCompilerFlags *flags, PyArena *arena); PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ const char* enc, int start, const char *ps1, const char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena); PyAPI_FUNC(struct _mod *) PyParser_ASTFromFileObject( FILE *fp, PyObject *filename, const char* enc, int start, const char *ps1, const char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena); #endif #ifndef PyParser_SimpleParseString #define PyParser_SimpleParseString(S, B) \ PyParser_SimpleParseStringFlags(S, B, 0) #define PyParser_SimpleParseFile(FP, S, B) \ PyParser_SimpleParseFileFlags(FP, S, B, 0) #endif PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, int); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlagsFilename(const char *, const char *, int, int); #endif PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *, int, int); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, PyObject *, PyCompilerFlags *); PyAPI_FUNC(PyObject *) PyRun_FileExFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags); #endif #ifdef Py_LIMITED_API PyAPI_FUNC(PyObject *) Py_CompileString(const char *, const char *, int); #else #define Py_CompileString(str, p, s) Py_CompileStringExFlags(str, p, s, NULL, -1) #define Py_CompileStringFlags(str, p, s, f) Py_CompileStringExFlags(str, p, s, f, -1) PyAPI_FUNC(PyObject *) Py_CompileStringExFlags( const char *str, const char *filename, /* decoded from the filesystem encoding */ int start, PyCompilerFlags *flags, int optimize); PyAPI_FUNC(PyObject *) Py_CompileStringObject( const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize); #endif PyAPI_FUNC(struct symtable *) Py_SymtableString( const char *str, const char *filename, /* decoded from the filesystem encoding */ int start); #ifndef Py_LIMITED_API PyAPI_FUNC(const char *) _Py_SourceAsString( PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy); PyAPI_FUNC(struct symtable *) Py_SymtableStringObject( const char *str, PyObject *filename, int start); PyAPI_FUNC(struct symtable *) _Py_SymtableStringObjectFlags( const char *str, PyObject *filename, int start, PyCompilerFlags *flags); #endif PyAPI_FUNC(void) PyErr_Print(void); PyAPI_FUNC(void) PyErr_PrintEx(int); PyAPI_FUNC(void) PyErr_Display(PyObject *, PyObject *, PyObject *); #ifndef Py_LIMITED_API /* A function flavor is also exported by libpython. It is required when libpython is accessed directly rather than using header files which defines macros below. On Windows, for example, PyAPI_FUNC() uses dllexport to export functions in pythonXX.dll. */ PyAPI_FUNC(PyObject *) PyRun_String(const char *str, int s, PyObject *g, PyObject *l); PyAPI_FUNC(int) PyRun_AnyFile(FILE *fp, const char *name); PyAPI_FUNC(int) PyRun_AnyFileEx(FILE *fp, const char *name, int closeit); PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *, const char *, PyCompilerFlags *); PyAPI_FUNC(int) PyRun_SimpleString(const char *s); PyAPI_FUNC(int) PyRun_SimpleFile(FILE *f, const char *p); PyAPI_FUNC(int) PyRun_SimpleFileEx(FILE *f, const char *p, int c); PyAPI_FUNC(int) PyRun_InteractiveOne(FILE *f, const char *p); PyAPI_FUNC(int) PyRun_InteractiveLoop(FILE *f, const char *p); PyAPI_FUNC(PyObject *) PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l); PyAPI_FUNC(PyObject *) PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c); PyAPI_FUNC(PyObject *) PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, PyCompilerFlags *flags); /* Use macros for a bunch of old variants */ #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL) #define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL) #define PyRun_AnyFileEx(fp, name, closeit) \ PyRun_AnyFileExFlags(fp, name, closeit, NULL) #define PyRun_AnyFileFlags(fp, name, flags) \ PyRun_AnyFileExFlags(fp, name, 0, flags) #define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL) #define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL) #define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL) #define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL) #define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL) #define PyRun_File(fp, p, s, g, l) \ PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) #define PyRun_FileEx(fp, p, s, g, l, c) \ PyRun_FileExFlags(fp, p, s, g, l, c, NULL) #define PyRun_FileFlags(fp, p, s, g, l, flags) \ PyRun_FileExFlags(fp, p, s, g, l, 0, flags) #endif /* Stuff with no proper home (yet) */ #ifndef Py_LIMITED_API PyAPI_FUNC(char *) PyOS_Readline(FILE *, FILE *, const char *); #endif PyAPI_DATA(int) (*PyOS_InputHook)(void); PyAPI_DATA(char) *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, const char *); #ifndef Py_LIMITED_API PyAPI_DATA(PyThreadState*) _PyOS_ReadlineTState; #endif /* Stack size, in "pointers" (so we get extra safety margins on 64-bit platforms). On a 32-bit platform, this translates to an 8k margin. */ #define PYOS_STACK_MARGIN 2048 #if defined(WIN32) && !defined(MS_WIN64) && !defined(_M_ARM) && defined(_MSC_VER) && _MSC_VER >= 1300 /* Enable stack checking under Microsoft C */ #define USE_STACKCHECK #endif #ifdef USE_STACKCHECK /* Check that we aren't overflowing our stack */ PyAPI_FUNC(int) PyOS_CheckStack(void); #endif #ifdef __cplusplus } #endif #endif /* !Py_PYTHONRUN_H */ ================================================ FILE: thirdLibs/python3_8/include/pythread.h ================================================ #ifndef Py_PYTHREAD_H #define Py_PYTHREAD_H typedef void *PyThread_type_lock; typedef void *PyThread_type_sema; #ifdef __cplusplus extern "C" { #endif /* Return status codes for Python lock acquisition. Chosen for maximum * backwards compatibility, ie failure -> 0, success -> 1. */ typedef enum PyLockStatus { PY_LOCK_FAILURE = 0, PY_LOCK_ACQUIRED = 1, PY_LOCK_INTR } PyLockStatus; #ifndef Py_LIMITED_API #define PYTHREAD_INVALID_THREAD_ID ((unsigned long)-1) #endif PyAPI_FUNC(void) PyThread_init_thread(void); PyAPI_FUNC(unsigned long) PyThread_start_new_thread(void (*)(void *), void *); PyAPI_FUNC(void) _Py_NO_RETURN PyThread_exit_thread(void); PyAPI_FUNC(unsigned long) PyThread_get_thread_ident(void); #if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(_WIN32) || defined(_AIX) #define PY_HAVE_THREAD_NATIVE_ID PyAPI_FUNC(unsigned long) PyThread_get_thread_native_id(void); #endif PyAPI_FUNC(PyThread_type_lock) PyThread_allocate_lock(void); PyAPI_FUNC(void) PyThread_free_lock(PyThread_type_lock); PyAPI_FUNC(int) PyThread_acquire_lock(PyThread_type_lock, int); #define WAIT_LOCK 1 #define NOWAIT_LOCK 0 /* PY_TIMEOUT_T is the integral type used to specify timeouts when waiting on a lock (see PyThread_acquire_lock_timed() below). PY_TIMEOUT_MAX is the highest usable value (in microseconds) of that type, and depends on the system threading API. NOTE: this isn't the same value as `_thread.TIMEOUT_MAX`. The _thread module exposes a higher-level API, with timeouts expressed in seconds and floating-point numbers allowed. */ #define PY_TIMEOUT_T long long #if defined(_POSIX_THREADS) /* PyThread_acquire_lock_timed() uses _PyTime_FromNanoseconds(us * 1000), convert microseconds to nanoseconds. */ # define PY_TIMEOUT_MAX (PY_LLONG_MAX / 1000) #elif defined (NT_THREADS) /* In the NT API, the timeout is a DWORD and is expressed in milliseconds */ # if 0xFFFFFFFFLL * 1000 < PY_LLONG_MAX # define PY_TIMEOUT_MAX (0xFFFFFFFFLL * 1000) # else # define PY_TIMEOUT_MAX PY_LLONG_MAX # endif #else # define PY_TIMEOUT_MAX PY_LLONG_MAX #endif /* If microseconds == 0, the call is non-blocking: it returns immediately even when the lock can't be acquired. If microseconds > 0, the call waits up to the specified duration. If microseconds < 0, the call waits until success (or abnormal failure) microseconds must be less than PY_TIMEOUT_MAX. Behaviour otherwise is undefined. If intr_flag is true and the acquire is interrupted by a signal, then the call will return PY_LOCK_INTR. The caller may reattempt to acquire the lock. */ PyAPI_FUNC(PyLockStatus) PyThread_acquire_lock_timed(PyThread_type_lock, PY_TIMEOUT_T microseconds, int intr_flag); PyAPI_FUNC(void) PyThread_release_lock(PyThread_type_lock); PyAPI_FUNC(size_t) PyThread_get_stacksize(void); PyAPI_FUNC(int) PyThread_set_stacksize(size_t); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject*) PyThread_GetInfo(void); #endif /* Thread Local Storage (TLS) API TLS API is DEPRECATED. Use Thread Specific Storage (TSS) API. The existing TLS API has used int to represent TLS keys across all platforms, but it is not POSIX-compliant. Therefore, the new TSS API uses opaque data type to represent TSS keys to be compatible (see PEP 539). */ Py_DEPRECATED(3.7) PyAPI_FUNC(int) PyThread_create_key(void); Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_delete_key(int key); Py_DEPRECATED(3.7) PyAPI_FUNC(int) PyThread_set_key_value(int key, void *value); Py_DEPRECATED(3.7) PyAPI_FUNC(void *) PyThread_get_key_value(int key); Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_delete_key_value(int key); /* Cleanup after a fork */ Py_DEPRECATED(3.7) PyAPI_FUNC(void) PyThread_ReInitTLS(void); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03070000 /* New in 3.7 */ /* Thread Specific Storage (TSS) API */ typedef struct _Py_tss_t Py_tss_t; /* opaque */ #ifndef Py_LIMITED_API #if defined(_POSIX_THREADS) /* Darwin needs pthread.h to know type name the pthread_key_t. */ # include # define NATIVE_TSS_KEY_T pthread_key_t #elif defined(NT_THREADS) /* In Windows, native TSS key type is DWORD, but hardcode the unsigned long to avoid errors for include directive. */ # define NATIVE_TSS_KEY_T unsigned long #else # error "Require native threads. See https://bugs.python.org/issue31370" #endif /* When Py_LIMITED_API is not defined, the type layout of Py_tss_t is exposed to allow static allocation in the API clients. Even in this case, you must handle TSS keys through API functions due to compatibility. */ struct _Py_tss_t { int _is_initialized; NATIVE_TSS_KEY_T _key; }; #undef NATIVE_TSS_KEY_T /* When static allocation, you must initialize with Py_tss_NEEDS_INIT. */ #define Py_tss_NEEDS_INIT {0} #endif /* !Py_LIMITED_API */ PyAPI_FUNC(Py_tss_t *) PyThread_tss_alloc(void); PyAPI_FUNC(void) PyThread_tss_free(Py_tss_t *key); /* The parameter key must not be NULL. */ PyAPI_FUNC(int) PyThread_tss_is_created(Py_tss_t *key); PyAPI_FUNC(int) PyThread_tss_create(Py_tss_t *key); PyAPI_FUNC(void) PyThread_tss_delete(Py_tss_t *key); PyAPI_FUNC(int) PyThread_tss_set(Py_tss_t *key, void *value); PyAPI_FUNC(void *) PyThread_tss_get(Py_tss_t *key); #endif /* New in 3.7 */ #ifdef __cplusplus } #endif #endif /* !Py_PYTHREAD_H */ ================================================ FILE: thirdLibs/python3_8/include/pytime.h ================================================ #ifndef Py_LIMITED_API #ifndef Py_PYTIME_H #define Py_PYTIME_H #include "pyconfig.h" /* include for defines */ #include "object.h" /************************************************************************** Symbols and macros to supply platform-independent interfaces to time related functions and constants **************************************************************************/ #ifdef __cplusplus extern "C" { #endif /* _PyTime_t: Python timestamp with subsecond precision. It can be used to store a duration, and so indirectly a date (related to another date, like UNIX epoch). */ typedef int64_t _PyTime_t; #define _PyTime_MIN INT64_MIN #define _PyTime_MAX INT64_MAX typedef enum { /* Round towards minus infinity (-inf). For example, used to read a clock. */ _PyTime_ROUND_FLOOR=0, /* Round towards infinity (+inf). For example, used for timeout to wait "at least" N seconds. */ _PyTime_ROUND_CEILING=1, /* Round to nearest with ties going to nearest even integer. For example, used to round from a Python float. */ _PyTime_ROUND_HALF_EVEN=2, /* Round away from zero For example, used for timeout. _PyTime_ROUND_CEILING rounds -1e-9 to 0 milliseconds which causes bpo-31786 issue. _PyTime_ROUND_UP rounds -1e-9 to -1 millisecond which keeps the timeout sign as expected. select.poll(timeout) must block for negative values." */ _PyTime_ROUND_UP=3, /* _PyTime_ROUND_TIMEOUT (an alias for _PyTime_ROUND_UP) should be used for timeouts. */ _PyTime_ROUND_TIMEOUT = _PyTime_ROUND_UP } _PyTime_round_t; /* Convert a time_t to a PyLong. */ PyAPI_FUNC(PyObject *) _PyLong_FromTime_t( time_t sec); /* Convert a PyLong to a time_t. */ PyAPI_FUNC(time_t) _PyLong_AsTime_t( PyObject *obj); /* Convert a number of seconds, int or float, to time_t. */ PyAPI_FUNC(int) _PyTime_ObjectToTime_t( PyObject *obj, time_t *sec, _PyTime_round_t); /* Convert a number of seconds, int or float, to a timeval structure. usec is in the range [0; 999999] and rounded towards zero. For example, -1.2 is converted to (-2, 800000). */ PyAPI_FUNC(int) _PyTime_ObjectToTimeval( PyObject *obj, time_t *sec, long *usec, _PyTime_round_t); /* Convert a number of seconds, int or float, to a timespec structure. nsec is in the range [0; 999999999] and rounded towards zero. For example, -1.2 is converted to (-2, 800000000). */ PyAPI_FUNC(int) _PyTime_ObjectToTimespec( PyObject *obj, time_t *sec, long *nsec, _PyTime_round_t); /* Create a timestamp from a number of seconds. */ PyAPI_FUNC(_PyTime_t) _PyTime_FromSeconds(int seconds); /* Macro to create a timestamp from a number of seconds, no integer overflow. Only use the macro for small values, prefer _PyTime_FromSeconds(). */ #define _PYTIME_FROMSECONDS(seconds) \ ((_PyTime_t)(seconds) * (1000 * 1000 * 1000)) /* Create a timestamp from a number of nanoseconds. */ PyAPI_FUNC(_PyTime_t) _PyTime_FromNanoseconds(_PyTime_t ns); /* Create a timestamp from nanoseconds (Python int). */ PyAPI_FUNC(int) _PyTime_FromNanosecondsObject(_PyTime_t *t, PyObject *obj); /* Convert a number of seconds (Python float or int) to a timetamp. Raise an exception and return -1 on error, return 0 on success. */ PyAPI_FUNC(int) _PyTime_FromSecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round); /* Convert a number of milliseconds (Python float or int, 10^-3) to a timetamp. Raise an exception and return -1 on error, return 0 on success. */ PyAPI_FUNC(int) _PyTime_FromMillisecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round); /* Convert a timestamp to a number of seconds as a C double. */ PyAPI_FUNC(double) _PyTime_AsSecondsDouble(_PyTime_t t); /* Convert timestamp to a number of milliseconds (10^-3 seconds). */ PyAPI_FUNC(_PyTime_t) _PyTime_AsMilliseconds(_PyTime_t t, _PyTime_round_t round); /* Convert timestamp to a number of microseconds (10^-6 seconds). */ PyAPI_FUNC(_PyTime_t) _PyTime_AsMicroseconds(_PyTime_t t, _PyTime_round_t round); /* Convert timestamp to a number of nanoseconds (10^-9 seconds) as a Python int object. */ PyAPI_FUNC(PyObject *) _PyTime_AsNanosecondsObject(_PyTime_t t); /* Create a timestamp from a timeval structure. Raise an exception and return -1 on overflow, return 0 on success. */ PyAPI_FUNC(int) _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv); /* Convert a timestamp to a timeval structure (microsecond resolution). tv_usec is always positive. Raise an exception and return -1 if the conversion overflowed, return 0 on success. */ PyAPI_FUNC(int) _PyTime_AsTimeval(_PyTime_t t, struct timeval *tv, _PyTime_round_t round); /* Similar to _PyTime_AsTimeval(), but don't raise an exception on error. */ PyAPI_FUNC(int) _PyTime_AsTimeval_noraise(_PyTime_t t, struct timeval *tv, _PyTime_round_t round); /* Convert a timestamp to a number of seconds (secs) and microseconds (us). us is always positive. This function is similar to _PyTime_AsTimeval() except that secs is always a time_t type, whereas the timeval structure uses a C long for tv_sec on Windows. Raise an exception and return -1 if the conversion overflowed, return 0 on success. */ PyAPI_FUNC(int) _PyTime_AsTimevalTime_t( _PyTime_t t, time_t *secs, int *us, _PyTime_round_t round); #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_KQUEUE) /* Create a timestamp from a timespec structure. Raise an exception and return -1 on overflow, return 0 on success. */ PyAPI_FUNC(int) _PyTime_FromTimespec(_PyTime_t *tp, struct timespec *ts); /* Convert a timestamp to a timespec structure (nanosecond resolution). tv_nsec is always positive. Raise an exception and return -1 on error, return 0 on success. */ PyAPI_FUNC(int) _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts); #endif /* Compute ticks * mul / div. The caller must ensure that ((div - 1) * mul) cannot overflow. */ PyAPI_FUNC(_PyTime_t) _PyTime_MulDiv(_PyTime_t ticks, _PyTime_t mul, _PyTime_t div); /* Get the current time from the system clock. The function cannot fail. _PyTime_Init() ensures that the system clock works. */ PyAPI_FUNC(_PyTime_t) _PyTime_GetSystemClock(void); /* Get the time of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid. The function cannot fail. _PyTime_Init() ensures that a monotonic clock is available and works. */ PyAPI_FUNC(_PyTime_t) _PyTime_GetMonotonicClock(void); /* Structure used by time.get_clock_info() */ typedef struct { const char *implementation; int monotonic; int adjustable; double resolution; } _Py_clock_info_t; /* Get the current time from the system clock. * Fill clock information if info is not NULL. * Raise an exception and return -1 on error, return 0 on success. */ PyAPI_FUNC(int) _PyTime_GetSystemClockWithInfo( _PyTime_t *t, _Py_clock_info_t *info); /* Get the time of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid. Fill info (if set) with information of the function used to get the time. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyTime_GetMonotonicClockWithInfo( _PyTime_t *t, _Py_clock_info_t *info); /* Initialize time. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyTime_Init(void); /* Converts a timestamp to the Gregorian time, using the local time zone. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyTime_localtime(time_t t, struct tm *tm); /* Converts a timestamp to the Gregorian time, assuming UTC. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyTime_gmtime(time_t t, struct tm *tm); /* Get the performance counter: clock with the highest available resolution to measure a short duration. The function cannot fail. _PyTime_Init() ensures that the system clock works. */ PyAPI_FUNC(_PyTime_t) _PyTime_GetPerfCounter(void); /* Get the performance counter: clock with the highest available resolution to measure a short duration. Fill info (if set) with information of the function used to get the time. Return 0 on success, raise an exception and return -1 on error. */ PyAPI_FUNC(int) _PyTime_GetPerfCounterWithInfo( _PyTime_t *t, _Py_clock_info_t *info); #ifdef __cplusplus } #endif #endif /* Py_PYTIME_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/rangeobject.h ================================================ /* Range object interface */ #ifndef Py_RANGEOBJECT_H #define Py_RANGEOBJECT_H #ifdef __cplusplus extern "C" { #endif /* A range object represents an integer range. This is an immutable object; a range cannot change its value after creation. Range objects behave like the corresponding tuple objects except that they are represented by a start, stop, and step datamembers. */ PyAPI_DATA(PyTypeObject) PyRange_Type; PyAPI_DATA(PyTypeObject) PyRangeIter_Type; PyAPI_DATA(PyTypeObject) PyLongRangeIter_Type; #define PyRange_Check(op) (Py_TYPE(op) == &PyRange_Type) #ifdef __cplusplus } #endif #endif /* !Py_RANGEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/setobject.h ================================================ /* Set object interface */ #ifndef Py_SETOBJECT_H #define Py_SETOBJECT_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API /* There are three kinds of entries in the table: 1. Unused: key == NULL and hash == 0 2. Dummy: key == dummy and hash == -1 3. Active: key != NULL and key != dummy and hash != -1 The hash field of Unused slots is always zero. The hash field of Dummy slots are set to -1 meaning that dummy entries can be detected by either entry->key==dummy or by entry->hash==-1. */ #define PySet_MINSIZE 8 typedef struct { PyObject *key; Py_hash_t hash; /* Cached hash code of the key */ } setentry; /* The SetObject data structure is shared by set and frozenset objects. Invariant for sets: - hash is -1 Invariants for frozensets: - data is immutable. - hash is the hash of the frozenset or -1 if not computed yet. */ typedef struct { PyObject_HEAD Py_ssize_t fill; /* Number active and dummy entries*/ Py_ssize_t used; /* Number active entries */ /* The table contains mask + 1 slots, and that's a power of 2. * We store the mask instead of the size because the mask is more * frequently needed. */ Py_ssize_t mask; /* The table points to a fixed-size smalltable for small tables * or to additional malloc'ed memory for bigger tables. * The table pointer is never NULL which saves us from repeated * runtime null-tests. */ setentry *table; Py_hash_t hash; /* Only used by frozenset objects */ Py_ssize_t finger; /* Search finger for pop() */ setentry smalltable[PySet_MINSIZE]; PyObject *weakreflist; /* List of weak references */ } PySetObject; #define PySet_GET_SIZE(so) (assert(PyAnySet_Check(so)),(((PySetObject *)(so))->used)) PyAPI_DATA(PyObject *) _PySet_Dummy; PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash); PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable); PyAPI_FUNC(int) PySet_ClearFreeList(void); #endif /* Section excluded by Py_LIMITED_API */ PyAPI_DATA(PyTypeObject) PySet_Type; PyAPI_DATA(PyTypeObject) PyFrozenSet_Type; PyAPI_DATA(PyTypeObject) PySetIter_Type; PyAPI_FUNC(PyObject *) PySet_New(PyObject *); PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *); PyAPI_FUNC(int) PySet_Add(PyObject *set, PyObject *key); PyAPI_FUNC(int) PySet_Clear(PyObject *set); PyAPI_FUNC(int) PySet_Contains(PyObject *anyset, PyObject *key); PyAPI_FUNC(int) PySet_Discard(PyObject *set, PyObject *key); PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set); PyAPI_FUNC(Py_ssize_t) PySet_Size(PyObject *anyset); #define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_CheckExact(ob) \ (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_Check(ob) \ (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) #define PySet_Check(ob) \ (Py_TYPE(ob) == &PySet_Type || \ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) #define PyFrozenSet_Check(ob) \ (Py_TYPE(ob) == &PyFrozenSet_Type || \ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) #ifdef __cplusplus } #endif #endif /* !Py_SETOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/sliceobject.h ================================================ #ifndef Py_SLICEOBJECT_H #define Py_SLICEOBJECT_H #ifdef __cplusplus extern "C" { #endif /* The unique ellipsis object "..." */ PyAPI_DATA(PyObject) _Py_EllipsisObject; /* Don't use this directly */ #define Py_Ellipsis (&_Py_EllipsisObject) /* Slice object interface */ /* A slice object containing start, stop, and step data members (the names are from range). After much talk with Guido, it was decided to let these be any arbitrary python type. Py_None stands for omitted values. */ #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD PyObject *start, *stop, *step; /* not NULL */ } PySliceObject; #endif PyAPI_DATA(PyTypeObject) PySlice_Type; PyAPI_DATA(PyTypeObject) PyEllipsis_Type; #define PySlice_Check(op) (Py_TYPE(op) == &PySlice_Type) PyAPI_FUNC(PyObject *) PySlice_New(PyObject* start, PyObject* stop, PyObject* step); #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject *) _PySlice_FromIndices(Py_ssize_t start, Py_ssize_t stop); PyAPI_FUNC(int) _PySlice_GetLongIndices(PySliceObject *self, PyObject *length, PyObject **start_ptr, PyObject **stop_ptr, PyObject **step_ptr); #endif PyAPI_FUNC(int) PySlice_GetIndices(PyObject *r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step); Py_DEPRECATED(3.7) PyAPI_FUNC(int) PySlice_GetIndicesEx(PyObject *r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength); #if !defined(Py_LIMITED_API) || (Py_LIMITED_API+0 >= 0x03050400 && Py_LIMITED_API+0 < 0x03060000) || Py_LIMITED_API+0 >= 0x03060100 #define PySlice_GetIndicesEx(slice, length, start, stop, step, slicelen) ( \ PySlice_Unpack((slice), (start), (stop), (step)) < 0 ? \ ((*(slicelen) = 0), -1) : \ ((*(slicelen) = PySlice_AdjustIndices((length), (start), (stop), *(step))), \ 0)) PyAPI_FUNC(int) PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step); PyAPI_FUNC(Py_ssize_t) PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step); #endif #ifdef __cplusplus } #endif #endif /* !Py_SLICEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/structmember.h ================================================ #ifndef Py_STRUCTMEMBER_H #define Py_STRUCTMEMBER_H #ifdef __cplusplus extern "C" { #endif /* Interface to map C struct members to Python object attributes */ #include /* For offsetof */ /* An array of PyMemberDef structures defines the name, type and offset of selected members of a C structure. These can be read by PyMember_GetOne() and set by PyMember_SetOne() (except if their READONLY flag is set). The array must be terminated with an entry whose name pointer is NULL. */ typedef struct PyMemberDef { const char *name; int type; Py_ssize_t offset; int flags; const char *doc; } PyMemberDef; /* Types */ #define T_SHORT 0 #define T_INT 1 #define T_LONG 2 #define T_FLOAT 3 #define T_DOUBLE 4 #define T_STRING 5 #define T_OBJECT 6 /* XXX the ordering here is weird for binary compatibility */ #define T_CHAR 7 /* 1-character string */ #define T_BYTE 8 /* 8-bit signed int */ /* unsigned variants: */ #define T_UBYTE 9 #define T_USHORT 10 #define T_UINT 11 #define T_ULONG 12 /* Added by Jack: strings contained in the structure */ #define T_STRING_INPLACE 13 /* Added by Lillo: bools contained in the structure (assumed char) */ #define T_BOOL 14 #define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError when the value is NULL, instead of converting to None. */ #define T_LONGLONG 17 #define T_ULONGLONG 18 #define T_PYSSIZET 19 /* Py_ssize_t */ #define T_NONE 20 /* Value is always None */ /* Flags */ #define READONLY 1 #define READ_RESTRICTED 2 #define PY_WRITE_RESTRICTED 4 #define RESTRICTED (READ_RESTRICTED | PY_WRITE_RESTRICTED) /* Current API, use this */ PyAPI_FUNC(PyObject *) PyMember_GetOne(const char *, struct PyMemberDef *); PyAPI_FUNC(int) PyMember_SetOne(char *, struct PyMemberDef *, PyObject *); #ifdef __cplusplus } #endif #endif /* !Py_STRUCTMEMBER_H */ ================================================ FILE: thirdLibs/python3_8/include/structseq.h ================================================ /* Named tuple object interface */ #ifndef Py_STRUCTSEQ_H #define Py_STRUCTSEQ_H #ifdef __cplusplus extern "C" { #endif typedef struct PyStructSequence_Field { const char *name; const char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { const char *name; const char *doc; struct PyStructSequence_Field *fields; int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; #ifndef Py_LIMITED_API PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc); PyAPI_FUNC(int) PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc); #endif PyAPI_FUNC(PyTypeObject*) PyStructSequence_NewType(PyStructSequence_Desc *desc); PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type); #ifndef Py_LIMITED_API typedef PyTupleObject PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) PyTuple_SET_ITEM(op, i, v) #define PyStructSequence_GET_ITEM(op, i) PyTuple_GET_ITEM(op, i) #endif PyAPI_FUNC(void) PyStructSequence_SetItem(PyObject*, Py_ssize_t, PyObject*); PyAPI_FUNC(PyObject*) PyStructSequence_GetItem(PyObject*, Py_ssize_t); #ifdef __cplusplus } #endif #endif /* !Py_STRUCTSEQ_H */ ================================================ FILE: thirdLibs/python3_8/include/symtable.h ================================================ #ifndef Py_LIMITED_API #ifndef Py_SYMTABLE_H #define Py_SYMTABLE_H #ifdef __cplusplus extern "C" { #endif #include "Python-ast.h" /* mod_ty */ /* XXX(ncoghlan): This is a weird mix of public names and interpreter internal * names. */ typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock } _Py_block_ty; struct _symtable_entry; struct symtable { PyObject *st_filename; /* name of file being compiled, decoded from the filesystem encoding */ struct _symtable_entry *st_cur; /* current symbol table entry */ struct _symtable_entry *st_top; /* symbol table entry for module */ PyObject *st_blocks; /* dict: map AST node addresses * to symbol table entries */ PyObject *st_stack; /* list: stack of namespace info */ PyObject *st_global; /* borrowed ref to st_top->ste_symbols */ int st_nblocks; /* number of blocks used. kept for consistency with the corresponding compiler structure */ PyObject *st_private; /* name of current class or NULL */ PyFutureFeatures *st_future; /* module's future features that affect the symbol table */ int recursion_depth; /* current recursion depth */ int recursion_limit; /* recursion limit */ }; typedef struct _symtable_entry { PyObject_HEAD PyObject *ste_id; /* int: key in ste_table->st_blocks */ PyObject *ste_symbols; /* dict: variable names to flags */ PyObject *ste_name; /* string: name of current block */ PyObject *ste_varnames; /* list of function parameters */ PyObject *ste_children; /* list of child blocks */ PyObject *ste_directives;/* locations of global and nonlocal statements */ _Py_block_ty ste_type; /* module, class, or function */ int ste_nested; /* true if block is nested */ unsigned ste_free : 1; /* true if block has free variables */ unsigned ste_child_free : 1; /* true if a child block has free vars, including free refs to globals */ unsigned ste_generator : 1; /* true if namespace is a generator */ unsigned ste_coroutine : 1; /* true if namespace is a coroutine */ unsigned ste_comprehension : 1; /* true if namespace is a list comprehension */ unsigned ste_varargs : 1; /* true if block has varargs */ unsigned ste_varkeywords : 1; /* true if block has varkeywords */ unsigned ste_returns_value : 1; /* true if namespace uses return with an argument */ unsigned ste_needs_class_closure : 1; /* for class scopes, true if a closure over __class__ should be created */ unsigned ste_comp_iter_target : 1; /* true if visiting comprehension target */ int ste_comp_iter_expr; /* non-zero if visiting a comprehension range expression */ int ste_lineno; /* first line of block */ int ste_col_offset; /* offset of first line of block */ int ste_opt_lineno; /* lineno of last exec or import * */ int ste_opt_col_offset; /* offset of last exec or import * */ struct symtable *ste_table; } PySTEntryObject; PyAPI_DATA(PyTypeObject) PySTEntry_Type; #define PySTEntry_Check(op) (Py_TYPE(op) == &PySTEntry_Type) PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *); PyAPI_FUNC(struct symtable *) PySymtable_Build( mod_ty mod, const char *filename, /* decoded from the filesystem encoding */ PyFutureFeatures *future); PyAPI_FUNC(struct symtable *) PySymtable_BuildObject( mod_ty mod, PyObject *filename, PyFutureFeatures *future); PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *); PyAPI_FUNC(void) PySymtable_Free(struct symtable *); /* Flags for def-use information */ #define DEF_GLOBAL 1 /* global stmt */ #define DEF_LOCAL 2 /* assignment in code block */ #define DEF_PARAM 2<<1 /* formal parameter */ #define DEF_NONLOCAL 2<<2 /* nonlocal stmt */ #define USE 2<<3 /* name is used */ #define DEF_FREE 2<<4 /* name used but not defined in nested block */ #define DEF_FREE_CLASS 2<<5 /* free variable from class's method */ #define DEF_IMPORT 2<<6 /* assignment occurred via import */ #define DEF_ANNOT 2<<7 /* this name is annotated */ #define DEF_COMP_ITER 2<<8 /* this name is a comprehension iteration variable */ #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT) /* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol table. GLOBAL is returned from PyST_GetScope() for either of them. It is stored in ste_symbols at bits 12-15. */ #define SCOPE_OFFSET 11 #define SCOPE_MASK (DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL) #define LOCAL 1 #define GLOBAL_EXPLICIT 2 #define GLOBAL_IMPLICIT 3 #define FREE 4 #define CELL 5 #define GENERATOR 1 #define GENERATOR_EXPRESSION 2 #ifdef __cplusplus } #endif #endif /* !Py_SYMTABLE_H */ #endif /* !Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/sysmodule.h ================================================ /* System module interface */ #ifndef Py_SYSMODULE_H #define Py_SYSMODULE_H #ifdef __cplusplus extern "C" { #endif PyAPI_FUNC(PyObject *) PySys_GetObject(const char *); PyAPI_FUNC(int) PySys_SetObject(const char *, PyObject *); PyAPI_FUNC(void) PySys_SetArgv(int, wchar_t **); PyAPI_FUNC(void) PySys_SetArgvEx(int, wchar_t **, int); PyAPI_FUNC(void) PySys_SetPath(const wchar_t *); PyAPI_FUNC(void) PySys_WriteStdout(const char *format, ...) Py_GCC_ATTRIBUTE((format(printf, 1, 2))); PyAPI_FUNC(void) PySys_WriteStderr(const char *format, ...) Py_GCC_ATTRIBUTE((format(printf, 1, 2))); PyAPI_FUNC(void) PySys_FormatStdout(const char *format, ...); PyAPI_FUNC(void) PySys_FormatStderr(const char *format, ...); PyAPI_FUNC(void) PySys_ResetWarnOptions(void); PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *); PyAPI_FUNC(void) PySys_AddWarnOptionUnicode(PyObject *); PyAPI_FUNC(int) PySys_HasWarnOptions(void); PyAPI_FUNC(void) PySys_AddXOption(const wchar_t *); PyAPI_FUNC(PyObject *) PySys_GetXOptions(void); #ifndef Py_LIMITED_API # define Py_CPYTHON_SYSMODULE_H # include "cpython/sysmodule.h" # undef Py_CPYTHON_SYSMODULE_H #endif #ifdef __cplusplus } #endif #endif /* !Py_SYSMODULE_H */ ================================================ FILE: thirdLibs/python3_8/include/token.h ================================================ /* Auto-generated by Tools/scripts/generate_token.py */ /* Token types */ #ifndef Py_LIMITED_API #ifndef Py_TOKEN_H #define Py_TOKEN_H #ifdef __cplusplus extern "C" { #endif #undef TILDE /* Prevent clash of our definition with system macro. Ex AIX, ioctl.h */ #define ENDMARKER 0 #define NAME 1 #define NUMBER 2 #define STRING 3 #define NEWLINE 4 #define INDENT 5 #define DEDENT 6 #define LPAR 7 #define RPAR 8 #define LSQB 9 #define RSQB 10 #define COLON 11 #define COMMA 12 #define SEMI 13 #define PLUS 14 #define MINUS 15 #define STAR 16 #define SLASH 17 #define VBAR 18 #define AMPER 19 #define LESS 20 #define GREATER 21 #define EQUAL 22 #define DOT 23 #define PERCENT 24 #define LBRACE 25 #define RBRACE 26 #define EQEQUAL 27 #define NOTEQUAL 28 #define LESSEQUAL 29 #define GREATEREQUAL 30 #define TILDE 31 #define CIRCUMFLEX 32 #define LEFTSHIFT 33 #define RIGHTSHIFT 34 #define DOUBLESTAR 35 #define PLUSEQUAL 36 #define MINEQUAL 37 #define STAREQUAL 38 #define SLASHEQUAL 39 #define PERCENTEQUAL 40 #define AMPEREQUAL 41 #define VBAREQUAL 42 #define CIRCUMFLEXEQUAL 43 #define LEFTSHIFTEQUAL 44 #define RIGHTSHIFTEQUAL 45 #define DOUBLESTAREQUAL 46 #define DOUBLESLASH 47 #define DOUBLESLASHEQUAL 48 #define AT 49 #define ATEQUAL 50 #define RARROW 51 #define ELLIPSIS 52 #define COLONEQUAL 53 #define OP 54 #define AWAIT 55 #define ASYNC 56 #define TYPE_IGNORE 57 #define TYPE_COMMENT 58 #define ERRORTOKEN 59 #define N_TOKENS 63 #define NT_OFFSET 256 /* Special definitions for cooperation with parser */ #define ISTERMINAL(x) ((x) < NT_OFFSET) #define ISNONTERMINAL(x) ((x) >= NT_OFFSET) #define ISEOF(x) ((x) == ENDMARKER) PyAPI_DATA(const char * const) _PyParser_TokenNames[]; /* Token names */ PyAPI_FUNC(int) PyToken_OneChar(int); PyAPI_FUNC(int) PyToken_TwoChars(int, int); PyAPI_FUNC(int) PyToken_ThreeChars(int, int, int); #ifdef __cplusplus } #endif #endif /* !Py_TOKEN_H */ #endif /* Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/traceback.h ================================================ #ifndef Py_TRACEBACK_H #define Py_TRACEBACK_H #ifdef __cplusplus extern "C" { #endif struct _frame; /* Traceback interface */ PyAPI_FUNC(int) PyTraceBack_Here(struct _frame *); PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *); /* Reveal traceback type so we can typecheck traceback objects */ PyAPI_DATA(PyTypeObject) PyTraceBack_Type; #define PyTraceBack_Check(v) (Py_TYPE(v) == &PyTraceBack_Type) #ifndef Py_LIMITED_API # define Py_CPYTHON_TRACEBACK_H # include "cpython/traceback.h" # undef Py_CPYTHON_TRACEBACK_H #endif #ifdef __cplusplus } #endif #endif /* !Py_TRACEBACK_H */ ================================================ FILE: thirdLibs/python3_8/include/tracemalloc.h ================================================ #ifndef Py_TRACEMALLOC_H #define Py_TRACEMALLOC_H #ifndef Py_LIMITED_API /* Track an allocated memory block in the tracemalloc module. Return 0 on success, return -1 on error (failed to allocate memory to store the trace). Return -2 if tracemalloc is disabled. If memory block is already tracked, update the existing trace. */ PyAPI_FUNC(int) PyTraceMalloc_Track( unsigned int domain, uintptr_t ptr, size_t size); /* Untrack an allocated memory block in the tracemalloc module. Do nothing if the block was not tracked. Return -2 if tracemalloc is disabled, otherwise return 0. */ PyAPI_FUNC(int) PyTraceMalloc_Untrack( unsigned int domain, uintptr_t ptr); /* Get the traceback where a memory block was allocated. Return a tuple of (filename: str, lineno: int) tuples. Return None if the tracemalloc module is disabled or if the memory block is not tracked by tracemalloc. Raise an exception and return NULL on error. */ PyAPI_FUNC(PyObject*) _PyTraceMalloc_GetTraceback( unsigned int domain, uintptr_t ptr); #endif #endif /* !Py_TRACEMALLOC_H */ ================================================ FILE: thirdLibs/python3_8/include/tupleobject.h ================================================ /* Tuple object interface */ #ifndef Py_TUPLEOBJECT_H #define Py_TUPLEOBJECT_H #ifdef __cplusplus extern "C" { #endif /* Another generally useful object type is a tuple of object pointers. For Python, this is an immutable type. C code can change the tuple items (but not their number), and even use tuples as general-purpose arrays of object references, but in general only brand new tuples should be mutated, not ones that might already have been exposed to Python code. *** WARNING *** PyTuple_SetItem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, if not nil. It does *decrement* the reference count if it is *not* inserted in the tuple. Similarly, PyTuple_GetItem does not increment the returned item's reference count. */ PyAPI_DATA(PyTypeObject) PyTuple_Type; PyAPI_DATA(PyTypeObject) PyTupleIter_Type; #define PyTuple_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TUPLE_SUBCLASS) #define PyTuple_CheckExact(op) (Py_TYPE(op) == &PyTuple_Type) PyAPI_FUNC(PyObject *) PyTuple_New(Py_ssize_t size); PyAPI_FUNC(Py_ssize_t) PyTuple_Size(PyObject *); PyAPI_FUNC(PyObject *) PyTuple_GetItem(PyObject *, Py_ssize_t); PyAPI_FUNC(int) PyTuple_SetItem(PyObject *, Py_ssize_t, PyObject *); PyAPI_FUNC(PyObject *) PyTuple_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t); PyAPI_FUNC(PyObject *) PyTuple_Pack(Py_ssize_t, ...); PyAPI_FUNC(int) PyTuple_ClearFreeList(void); #ifndef Py_LIMITED_API # define Py_CPYTHON_TUPLEOBJECT_H # include "cpython/tupleobject.h" # undef Py_CPYTHON_TUPLEOBJECT_H #endif #ifdef __cplusplus } #endif #endif /* !Py_TUPLEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/typeslots.h ================================================ /* Do not renumber the file; these numbers are part of the stable ABI. */ /* Disabled, see #10181 */ #undef Py_bf_getbuffer #undef Py_bf_releasebuffer #define Py_mp_ass_subscript 3 #define Py_mp_length 4 #define Py_mp_subscript 5 #define Py_nb_absolute 6 #define Py_nb_add 7 #define Py_nb_and 8 #define Py_nb_bool 9 #define Py_nb_divmod 10 #define Py_nb_float 11 #define Py_nb_floor_divide 12 #define Py_nb_index 13 #define Py_nb_inplace_add 14 #define Py_nb_inplace_and 15 #define Py_nb_inplace_floor_divide 16 #define Py_nb_inplace_lshift 17 #define Py_nb_inplace_multiply 18 #define Py_nb_inplace_or 19 #define Py_nb_inplace_power 20 #define Py_nb_inplace_remainder 21 #define Py_nb_inplace_rshift 22 #define Py_nb_inplace_subtract 23 #define Py_nb_inplace_true_divide 24 #define Py_nb_inplace_xor 25 #define Py_nb_int 26 #define Py_nb_invert 27 #define Py_nb_lshift 28 #define Py_nb_multiply 29 #define Py_nb_negative 30 #define Py_nb_or 31 #define Py_nb_positive 32 #define Py_nb_power 33 #define Py_nb_remainder 34 #define Py_nb_rshift 35 #define Py_nb_subtract 36 #define Py_nb_true_divide 37 #define Py_nb_xor 38 #define Py_sq_ass_item 39 #define Py_sq_concat 40 #define Py_sq_contains 41 #define Py_sq_inplace_concat 42 #define Py_sq_inplace_repeat 43 #define Py_sq_item 44 #define Py_sq_length 45 #define Py_sq_repeat 46 #define Py_tp_alloc 47 #define Py_tp_base 48 #define Py_tp_bases 49 #define Py_tp_call 50 #define Py_tp_clear 51 #define Py_tp_dealloc 52 #define Py_tp_del 53 #define Py_tp_descr_get 54 #define Py_tp_descr_set 55 #define Py_tp_doc 56 #define Py_tp_getattr 57 #define Py_tp_getattro 58 #define Py_tp_hash 59 #define Py_tp_init 60 #define Py_tp_is_gc 61 #define Py_tp_iter 62 #define Py_tp_iternext 63 #define Py_tp_methods 64 #define Py_tp_new 65 #define Py_tp_repr 66 #define Py_tp_richcompare 67 #define Py_tp_setattr 68 #define Py_tp_setattro 69 #define Py_tp_str 70 #define Py_tp_traverse 71 #define Py_tp_members 72 #define Py_tp_getset 73 #define Py_tp_free 74 #define Py_nb_matrix_multiply 75 #define Py_nb_inplace_matrix_multiply 76 #define Py_am_await 77 #define Py_am_aiter 78 #define Py_am_anext 79 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ #define Py_tp_finalize 80 #endif ================================================ FILE: thirdLibs/python3_8/include/ucnhash.h ================================================ /* Unicode name database interface */ #ifndef Py_LIMITED_API #ifndef Py_UCNHASH_H #define Py_UCNHASH_H #ifdef __cplusplus extern "C" { #endif /* revised ucnhash CAPI interface (exported through a "wrapper") */ #define PyUnicodeData_CAPSULE_NAME "unicodedata.ucnhash_CAPI" typedef struct { /* Size of this struct */ int size; /* Get name for a given character code. Returns non-zero if success, zero if not. Does not set Python exceptions. If self is NULL, data come from the default version of the database. If it is not NULL, it should be a unicodedata.ucd_X_Y_Z object */ int (*getname)(PyObject *self, Py_UCS4 code, char* buffer, int buflen, int with_alias_and_seq); /* Get character code for a given name. Same error handling as for getname. */ int (*getcode)(PyObject *self, const char* name, int namelen, Py_UCS4* code, int with_named_seq); } _PyUnicode_Name_CAPI; #ifdef __cplusplus } #endif #endif /* !Py_UCNHASH_H */ #endif /* !Py_LIMITED_API */ ================================================ FILE: thirdLibs/python3_8/include/unicodeobject.h ================================================ #ifndef Py_UNICODEOBJECT_H #define Py_UNICODEOBJECT_H #include /* Unicode implementation based on original code by Fredrik Lundh, modified by Marc-Andre Lemburg (mal@lemburg.com) according to the Unicode Integration Proposal. (See http://www.egenix.com/files/python/unicode-proposal.txt). Copyright (c) Corporation for National Research Initiatives. Original header: -------------------------------------------------------------------- * Yet another Unicode string type for Python. This type supports the * 16-bit Basic Multilingual Plane (BMP) only. * * Written by Fredrik Lundh, January 1999. * * Copyright (c) 1999 by Secret Labs AB. * Copyright (c) 1999 by Fredrik Lundh. * * fredrik@pythonware.com * http://www.pythonware.com * * -------------------------------------------------------------------- * This Unicode String Type is * * Copyright (c) 1999 by Secret Labs AB * Copyright (c) 1999 by Fredrik Lundh * * By obtaining, using, and/or copying this software and/or its * associated documentation, you agree that you have read, understood, * and will comply with the following terms and conditions: * * Permission to use, copy, modify, and distribute this software and its * associated documentation for any purpose and without fee is hereby * granted, provided that the above copyright notice appears in all * copies, and that both that copyright notice and this permission notice * appear in supporting documentation, and that the name of Secret Labs * AB or the author not be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. * * SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * -------------------------------------------------------------------- */ #include /* === Internal API ======================================================= */ /* --- Internal Unicode Format -------------------------------------------- */ /* Python 3.x requires unicode */ #define Py_USING_UNICODE #ifndef SIZEOF_WCHAR_T #error Must define SIZEOF_WCHAR_T #endif #define Py_UNICODE_SIZE SIZEOF_WCHAR_T /* If wchar_t can be used for UCS-4 storage, set Py_UNICODE_WIDE. Otherwise, Unicode strings are stored as UCS-2 (with limited support for UTF-16) */ #if Py_UNICODE_SIZE >= 4 #define Py_UNICODE_WIDE #endif /* Set these flags if the platform has "wchar.h" and the wchar_t type is a 16-bit unsigned type */ /* #define HAVE_WCHAR_H */ /* #define HAVE_USABLE_WCHAR_T */ /* If the compiler provides a wchar_t type we try to support it through the interface functions PyUnicode_FromWideChar(), PyUnicode_AsWideChar() and PyUnicode_AsWideCharString(). */ #ifdef HAVE_USABLE_WCHAR_T # ifndef HAVE_WCHAR_H # define HAVE_WCHAR_H # endif #endif #ifdef HAVE_WCHAR_H # include #endif /* Py_UCS4 and Py_UCS2 are typedefs for the respective unicode representations. */ typedef uint32_t Py_UCS4; typedef uint16_t Py_UCS2; typedef uint8_t Py_UCS1; #ifdef __cplusplus extern "C" { #endif PyAPI_DATA(PyTypeObject) PyUnicode_Type; PyAPI_DATA(PyTypeObject) PyUnicodeIter_Type; #define PyUnicode_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_UNICODE_SUBCLASS) #define PyUnicode_CheckExact(op) (Py_TYPE(op) == &PyUnicode_Type) /* --- Constants ---------------------------------------------------------- */ /* This Unicode character will be used as replacement character during decoding if the errors argument is set to "replace". Note: the Unicode character U+FFFD is the official REPLACEMENT CHARACTER in Unicode 3.0. */ #define Py_UNICODE_REPLACEMENT_CHARACTER ((Py_UCS4) 0xFFFD) /* === Public API ========================================================= */ /* Similar to PyUnicode_FromUnicode(), but u points to UTF-8 encoded bytes */ PyAPI_FUNC(PyObject*) PyUnicode_FromStringAndSize( const char *u, /* UTF-8 encoded string */ Py_ssize_t size /* size of buffer */ ); /* Similar to PyUnicode_FromUnicode(), but u points to null-terminated UTF-8 encoded bytes. The size is determined with strlen(). */ PyAPI_FUNC(PyObject*) PyUnicode_FromString( const char *u /* UTF-8 encoded string */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject*) PyUnicode_Substring( PyObject *str, Py_ssize_t start, Py_ssize_t end); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Copy the string into a UCS4 buffer including the null character if copy_null is set. Return NULL and raise an exception on error. Raise a SystemError if the buffer is smaller than the string. Return buffer on success. buflen is the length of the buffer in (Py_UCS4) characters. */ PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4( PyObject *unicode, Py_UCS4* buffer, Py_ssize_t buflen, int copy_null); /* Copy the string into a UCS4 buffer. A new buffer is allocated using * PyMem_Malloc; if this fails, NULL is returned with a memory error exception set. */ PyAPI_FUNC(Py_UCS4*) PyUnicode_AsUCS4Copy(PyObject *unicode); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Get the length of the Unicode object. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_GetLength( PyObject *unicode ); #endif /* Get the number of Py_UNICODE units in the string representation. */ Py_DEPRECATED(3.3) PyAPI_FUNC(Py_ssize_t) PyUnicode_GetSize( PyObject *unicode /* Unicode object */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Read a character from the string. */ PyAPI_FUNC(Py_UCS4) PyUnicode_ReadChar( PyObject *unicode, Py_ssize_t index ); /* Write a character to the string. The string must have been created through PyUnicode_New, must not be shared, and must not have been hashed yet. Return 0 on success, -1 on error. */ PyAPI_FUNC(int) PyUnicode_WriteChar( PyObject *unicode, Py_ssize_t index, Py_UCS4 character ); #endif /* Resize a Unicode object. The length is the number of characters, except if the kind of the string is PyUnicode_WCHAR_KIND: in this case, the length is the number of Py_UNICODE characters. *unicode is modified to point to the new (resized) object and 0 returned on success. Try to resize the string in place (which is usually faster than allocating a new string and copy characters), or create a new string. Error handling is implemented as follows: an exception is set, -1 is returned and *unicode left untouched. WARNING: The function doesn't check string content, the result may not be a string in canonical representation. */ PyAPI_FUNC(int) PyUnicode_Resize( PyObject **unicode, /* Pointer to the Unicode object */ Py_ssize_t length /* New length */ ); /* Decode obj to a Unicode object. bytes, bytearray and other bytes-like objects are decoded according to the given encoding and error handler. The encoding and error handler can be NULL to have the interface use UTF-8 and "strict". All other objects (including Unicode objects) raise an exception. The API returns NULL in case of an error. The caller is responsible for decref'ing the returned objects. */ PyAPI_FUNC(PyObject*) PyUnicode_FromEncodedObject( PyObject *obj, /* Object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Copy an instance of a Unicode subtype to a new true Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return the reference with *incremented* refcount. The API returns NULL in case of an error. The caller is responsible for decref'ing the returned objects. */ PyAPI_FUNC(PyObject*) PyUnicode_FromObject( PyObject *obj /* Object */ ); PyAPI_FUNC(PyObject *) PyUnicode_FromFormatV( const char *format, /* ASCII-encoded string */ va_list vargs ); PyAPI_FUNC(PyObject *) PyUnicode_FromFormat( const char *format, /* ASCII-encoded string */ ... ); PyAPI_FUNC(void) PyUnicode_InternInPlace(PyObject **); PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **); PyAPI_FUNC(PyObject *) PyUnicode_InternFromString( const char *u /* UTF-8 encoded string */ ); /* Use only if you know it's a string */ #define PyUnicode_CHECK_INTERNED(op) \ (((PyASCIIObject *)(op))->state.interned) /* --- wchar_t support for platforms which support it --------------------- */ #ifdef HAVE_WCHAR_H /* Create a Unicode Object from the wchar_t buffer w of the given size. The buffer is copied into the new object. */ PyAPI_FUNC(PyObject*) PyUnicode_FromWideChar( const wchar_t *w, /* wchar_t buffer */ Py_ssize_t size /* size of buffer */ ); /* Copies the Unicode Object contents into the wchar_t buffer w. At most size wchar_t characters are copied. Note that the resulting wchar_t string may or may not be 0-terminated. It is the responsibility of the caller to make sure that the wchar_t string is 0-terminated in case this is required by the application. Returns the number of wchar_t characters copied (excluding a possibly trailing 0-termination character) or -1 in case of an error. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_AsWideChar( PyObject *unicode, /* Unicode object */ wchar_t *w, /* wchar_t buffer */ Py_ssize_t size /* size of buffer */ ); /* Convert the Unicode object to a wide character string. The output string always ends with a nul character. If size is not NULL, write the number of wide characters (excluding the null character) into *size. Returns a buffer allocated by PyMem_Malloc() (use PyMem_Free() to free it) on success. On error, returns NULL, *size is undefined and raises a MemoryError. */ PyAPI_FUNC(wchar_t*) PyUnicode_AsWideCharString( PyObject *unicode, /* Unicode object */ Py_ssize_t *size /* number of characters of the result */ ); #endif /* --- Unicode ordinals --------------------------------------------------- */ /* Create a Unicode Object from the given Unicode code point ordinal. The ordinal must be in range(0x110000). A ValueError is raised in case it is not. */ PyAPI_FUNC(PyObject*) PyUnicode_FromOrdinal(int ordinal); /* --- Free-list management ----------------------------------------------- */ /* Clear the free list used by the Unicode implementation. This can be used to release memory used for objects on the free list back to the Python memory allocator. */ PyAPI_FUNC(int) PyUnicode_ClearFreeList(void); /* === Builtin Codecs ===================================================== Many of these APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones of the builtin str() API. Setting encoding to NULL causes the default encoding (UTF-8) to be used. Error handling is set by errors which may also be set to NULL meaning to use the default handling defined for the codec. Default error handling for all builtin codecs is "strict" (ValueErrors are raised). The codecs all use a similar interface. Only deviation from the generic ones are documented. */ /* --- Manage the default encoding ---------------------------------------- */ /* Returns "utf-8". */ PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void); /* --- Generic Codecs ----------------------------------------------------- */ /* Create a Unicode object by decoding the encoded string s of the given size. */ PyAPI_FUNC(PyObject*) PyUnicode_Decode( const char *s, /* encoded string */ Py_ssize_t size, /* size of buffer */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Decode a Unicode object unicode and return the result as Python object. This API is DEPRECATED. The only supported standard encoding is rot13. Use PyCodec_Decode() to decode with rot13 and non-standard codecs that decode from str. */ Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedObject( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Decode a Unicode object unicode and return the result as Unicode object. This API is DEPRECATED. The only supported standard encoding is rot13. Use PyCodec_Decode() to decode with rot13 and non-standard codecs that decode from str to str. */ Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsDecodedUnicode( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Python object. This API is DEPRECATED. It is superseded by PyUnicode_AsEncodedString() since all standard encodings (except rot13) encode str to bytes. Use PyCodec_Encode() for encoding with rot13 and non-standard codecs that encode form str to non-bytes. */ Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedObject( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Python string object. */ PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedString( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Unicode object. This API is DEPRECATED. The only supported standard encodings is rot13. Use PyCodec_Encode() to encode with rot13 and non-standard codecs that encode from str to str. */ Py_DEPRECATED(3.6) PyAPI_FUNC(PyObject*) PyUnicode_AsEncodedUnicode( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Build an encoding map. */ PyAPI_FUNC(PyObject*) PyUnicode_BuildEncodingMap( PyObject* string /* 256 character map */ ); /* --- UTF-7 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7( const char *string, /* UTF-7 encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF7Stateful( const char *string, /* UTF-7 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); /* --- UTF-8 Codecs ------------------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8( const char *string, /* UTF-8 encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF8Stateful( const char *string, /* UTF-8 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUTF8String( PyObject *unicode /* Unicode object */ ); /* --- UTF-32 Codecs ------------------------------------------------------ */ /* Decodes length bytes from a UTF-32 encoded buffer string and returns the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: *byteorder == -1: little endian *byteorder == 0: native order *byteorder == 1: big endian In native mode, the first four bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order adjusted and the BOM skipped. In the other modes, no BOM mark interpretation is done. After completion, *byteorder is set to the current byte order at the end of input data. If byteorder is NULL, the codec starts in native order mode. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32( const char *string, /* UTF-32 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF32Stateful( const char *string, /* UTF-32 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder, /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF32String( PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-32 encoded value of the Unicode data. If byteorder is not 0, output is written according to the following byte order: byteorder == -1: little endian byteorder == 0: native byte order (writes a BOM mark) byteorder == 1: big endian If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended. */ /* --- UTF-16 Codecs ------------------------------------------------------ */ /* Decodes length bytes from a UTF-16 encoded buffer string and returns the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: *byteorder == -1: little endian *byteorder == 0: native order *byteorder == 1: big endian In native mode, the first two bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order adjusted and the BOM skipped. In the other modes, no BOM mark interpretation is done. After completion, *byteorder is set to the current byte order at the end of input data. If byteorder is NULL, the codec starts in native order mode. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16( const char *string, /* UTF-16 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeUTF16Stateful( const char *string, /* UTF-16 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder, /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. */ PyAPI_FUNC(PyObject*) PyUnicode_AsUTF16String( PyObject *unicode /* Unicode object */ ); /* --- Unicode-Escape Codecs ---------------------------------------------- */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeUnicodeEscape( const char *string, /* Unicode-Escape encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsUnicodeEscapeString( PyObject *unicode /* Unicode object */ ); /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeRawUnicodeEscape( const char *string, /* Raw-Unicode-Escape encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsRawUnicodeEscapeString( PyObject *unicode /* Unicode object */ ); /* --- Latin-1 Codecs ----------------------------------------------------- Note: Latin-1 corresponds to the first 256 Unicode ordinals. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeLatin1( const char *string, /* Latin-1 encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsLatin1String( PyObject *unicode /* Unicode object */ ); /* --- ASCII Codecs ------------------------------------------------------- Only 7-bit ASCII data is excepted. All other codes generate errors. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeASCII( const char *string, /* ASCII encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsASCIIString( PyObject *unicode /* Unicode object */ ); /* --- Character Map Codecs ----------------------------------------------- This codec uses mappings to encode and decode characters. Decoding mappings must map byte ordinals (integers in the range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None. Unmapped data bytes (ones which cause a LookupError) as well as mapped to None, 0xFFFE or '\ufffe' are treated as "undefined mapping" and cause an error. Encoding mappings must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255 or None. Unmapped character ordinals (ones which cause a LookupError) as well as mapped to None are treated as "undefined mapping" and cause an error. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeCharmap( const char *string, /* Encoded string */ Py_ssize_t length, /* size of string */ PyObject *mapping, /* decoding mapping */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_AsCharmapString( PyObject *unicode, /* Unicode object */ PyObject *mapping /* encoding mapping */ ); /* --- MBCS codecs for Windows -------------------------------------------- */ #ifdef MS_WINDOWS PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCS( const char *string, /* MBCS encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyAPI_FUNC(PyObject*) PyUnicode_DecodeMBCSStateful( const char *string, /* MBCS encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject*) PyUnicode_DecodeCodePageStateful( int code_page, /* code page number */ const char *string, /* encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); #endif PyAPI_FUNC(PyObject*) PyUnicode_AsMBCSString( PyObject *unicode /* Unicode object */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyAPI_FUNC(PyObject*) PyUnicode_EncodeCodePage( int code_page, /* code page number */ PyObject *unicode, /* Unicode object */ const char *errors /* error handling */ ); #endif #endif /* MS_WINDOWS */ /* --- Locale encoding --------------------------------------------------- */ #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Decode a string from the current locale encoding. The decoder is strict if *surrogateescape* is equal to zero, otherwise it uses the 'surrogateescape' error handler (PEP 383) to escape undecodable bytes. If a byte sequence can be decoded as a surrogate character and *surrogateescape* is not equal to zero, the byte sequence is escaped using the 'surrogateescape' error handler instead of being decoded. *str* must end with a null character but cannot contain embedded null characters. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeLocaleAndSize( const char *str, Py_ssize_t len, const char *errors); /* Similar to PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen(). */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeLocale( const char *str, const char *errors); /* Encode a Unicode object to the current locale encoding. The encoder is strict is *surrogateescape* is equal to zero, otherwise the "surrogateescape" error handler is used. Return a bytes object. The string cannot contain embedded null characters. */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeLocale( PyObject *unicode, const char *errors ); #endif /* --- File system encoding ---------------------------------------------- */ /* ParseTuple converter: encode str objects to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output as-is. */ PyAPI_FUNC(int) PyUnicode_FSConverter(PyObject*, void*); /* ParseTuple converter: decode bytes objects to unicode using PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. */ PyAPI_FUNC(int) PyUnicode_FSDecoder(PyObject*, void*); /* Decode a null-terminated string using Py_FileSystemDefaultEncoding and the "surrogateescape" error handler. If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding. Use PyUnicode_DecodeFSDefaultAndSize() if the string length is known. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefault( const char *s /* encoded string */ ); /* Decode a string using Py_FileSystemDefaultEncoding and the "surrogateescape" error handler. If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding. */ PyAPI_FUNC(PyObject*) PyUnicode_DecodeFSDefaultAndSize( const char *s, /* encoded string */ Py_ssize_t size /* size */ ); /* Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding. */ PyAPI_FUNC(PyObject*) PyUnicode_EncodeFSDefault( PyObject *unicode ); /* --- Methods & Slots ---------------------------------------------------- These are capable of handling Unicode objects and strings on input (we refer to them as strings in the descriptions) and return Unicode objects or integers as appropriate. */ /* Concat two strings giving a new Unicode string. */ PyAPI_FUNC(PyObject*) PyUnicode_Concat( PyObject *left, /* Left string */ PyObject *right /* Right string */ ); /* Concat two strings and put the result in *pleft (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_Append( PyObject **pleft, /* Pointer to left string */ PyObject *right /* Right string */ ); /* Concat two strings, put the result in *pleft and drop the right object (sets *pleft to NULL on error) */ PyAPI_FUNC(void) PyUnicode_AppendAndDel( PyObject **pleft, /* Pointer to left string */ PyObject *right /* Right string */ ); /* Split a string giving a list of Unicode strings. If sep is NULL, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given separator. At most maxsplit splits will be done. If negative, no limit is set. Separators are not included in the resulting list. */ PyAPI_FUNC(PyObject*) PyUnicode_Split( PyObject *s, /* String to split */ PyObject *sep, /* String separator */ Py_ssize_t maxsplit /* Maxsplit count */ ); /* Dito, but split at line breaks. CRLF is considered to be one line break. Line breaks are not included in the resulting list. */ PyAPI_FUNC(PyObject*) PyUnicode_Splitlines( PyObject *s, /* String to split */ int keepends /* If true, line end markers are included */ ); /* Partition a string using a given separator. */ PyAPI_FUNC(PyObject*) PyUnicode_Partition( PyObject *s, /* String to partition */ PyObject *sep /* String separator */ ); /* Partition a string using a given separator, searching from the end of the string. */ PyAPI_FUNC(PyObject*) PyUnicode_RPartition( PyObject *s, /* String to partition */ PyObject *sep /* String separator */ ); /* Split a string giving a list of Unicode strings. If sep is NULL, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given separator. At most maxsplit splits will be done. But unlike PyUnicode_Split PyUnicode_RSplit splits from the end of the string. If negative, no limit is set. Separators are not included in the resulting list. */ PyAPI_FUNC(PyObject*) PyUnicode_RSplit( PyObject *s, /* String to split */ PyObject *sep, /* String separator */ Py_ssize_t maxsplit /* Maxsplit count */ ); /* Translate a string by applying a character mapping table to it and return the resulting Unicode object. The mapping table must map Unicode ordinal integers to Unicode strings, Unicode ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is. */ PyAPI_FUNC(PyObject *) PyUnicode_Translate( PyObject *str, /* String */ PyObject *table, /* Translate table */ const char *errors /* error handling */ ); /* Join a sequence of strings using the given separator and return the resulting Unicode string. */ PyAPI_FUNC(PyObject*) PyUnicode_Join( PyObject *separator, /* Separator string */ PyObject *seq /* Sequence object */ ); /* Return 1 if substr matches str[start:end] at the given tail end, 0 otherwise. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Tailmatch( PyObject *str, /* String */ PyObject *substr, /* Prefix or Suffix string */ Py_ssize_t start, /* Start index */ Py_ssize_t end, /* Stop index */ int direction /* Tail end: -1 prefix, +1 suffix */ ); /* Return the first position of substr in str[start:end] using the given search direction or -1 if not found. -2 is returned in case an error occurred and an exception is set. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Find( PyObject *str, /* String */ PyObject *substr, /* Substring to find */ Py_ssize_t start, /* Start index */ Py_ssize_t end, /* Stop index */ int direction /* Find direction: +1 forward, -1 backward */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Like PyUnicode_Find, but search for single character only. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_FindChar( PyObject *str, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction ); #endif /* Count the number of occurrences of substr in str[start:end]. */ PyAPI_FUNC(Py_ssize_t) PyUnicode_Count( PyObject *str, /* String */ PyObject *substr, /* Substring to count */ Py_ssize_t start, /* Start index */ Py_ssize_t end /* Stop index */ ); /* Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. */ PyAPI_FUNC(PyObject *) PyUnicode_Replace( PyObject *str, /* String */ PyObject *substr, /* Substring to find */ PyObject *replstr, /* Substring to replace */ Py_ssize_t maxcount /* Max. number of replacements to apply; -1 = all */ ); /* Compare two strings and return -1, 0, 1 for less than, equal, greater than resp. Raise an exception and return -1 on error. */ PyAPI_FUNC(int) PyUnicode_Compare( PyObject *left, /* Left string */ PyObject *right /* Right string */ ); /* Compare a Unicode object with C string and return -1, 0, 1 for less than, equal, and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input string as ISO-8859-1 if it contains non-ASCII characters. This function does not raise exceptions. */ PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString( PyObject *left, const char *right /* ASCII-encoded string */ ); /* Rich compare two strings and return one of the following: - NULL in case an exception was raised - Py_True or Py_False for successful comparisons - Py_NotImplemented in case the type combination is unknown Possible values for op: Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE */ PyAPI_FUNC(PyObject *) PyUnicode_RichCompare( PyObject *left, /* Left string */ PyObject *right, /* Right string */ int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ ); /* Apply an argument tuple or dictionary to a format string and return the resulting Unicode string. */ PyAPI_FUNC(PyObject *) PyUnicode_Format( PyObject *format, /* Format string */ PyObject *args /* Argument tuple or dictionary */ ); /* Checks whether element is contained in container and return 1/0 accordingly. element has to coerce to a one element Unicode string. -1 is returned in case of an error. */ PyAPI_FUNC(int) PyUnicode_Contains( PyObject *container, /* Container string */ PyObject *element /* Element string */ ); /* Checks whether argument is a valid identifier. */ PyAPI_FUNC(int) PyUnicode_IsIdentifier(PyObject *s); /* === Characters Type APIs =============================================== */ #ifndef Py_LIMITED_API # define Py_CPYTHON_UNICODEOBJECT_H # include "cpython/unicodeobject.h" # undef Py_CPYTHON_UNICODEOBJECT_H #endif #ifdef __cplusplus } #endif #endif /* !Py_UNICODEOBJECT_H */ ================================================ FILE: thirdLibs/python3_8/include/warnings.h ================================================ #ifndef Py_WARNINGS_H #define Py_WARNINGS_H #ifdef __cplusplus extern "C" { #endif #ifndef Py_LIMITED_API PyAPI_FUNC(PyObject*) _PyWarnings_Init(void); #endif PyAPI_FUNC(int) PyErr_WarnEx( PyObject *category, const char *message, /* UTF-8 encoded string */ Py_ssize_t stack_level); PyAPI_FUNC(int) PyErr_WarnFormat( PyObject *category, Py_ssize_t stack_level, const char *format, /* ASCII-encoded string */ ...); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 /* Emit a ResourceWarning warning */ PyAPI_FUNC(int) PyErr_ResourceWarning( PyObject *source, Py_ssize_t stack_level, const char *format, /* ASCII-encoded string */ ...); #endif #ifndef Py_LIMITED_API PyAPI_FUNC(int) PyErr_WarnExplicitObject( PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry); #endif PyAPI_FUNC(int) PyErr_WarnExplicit( PyObject *category, const char *message, /* UTF-8 encoded string */ const char *filename, /* decoded from the filesystem encoding */ int lineno, const char *module, /* UTF-8 encoded string */ PyObject *registry); #ifndef Py_LIMITED_API PyAPI_FUNC(int) PyErr_WarnExplicitFormat(PyObject *category, const char *filename, int lineno, const char *module, PyObject *registry, const char *format, ...); #endif /* DEPRECATED: Use PyErr_WarnEx() instead. */ #ifndef Py_LIMITED_API #define PyErr_Warn(category, msg) PyErr_WarnEx(category, msg, 1) #endif #ifndef Py_LIMITED_API void _PyErr_WarnUnawaitedCoroutine(PyObject *coro); #endif #ifdef __cplusplus } #endif #endif /* !Py_WARNINGS_H */ ================================================ FILE: thirdLibs/python3_8/include/weakrefobject.h ================================================ /* Weak references objects for Python. */ #ifndef Py_WEAKREFOBJECT_H #define Py_WEAKREFOBJECT_H #ifdef __cplusplus extern "C" { #endif typedef struct _PyWeakReference PyWeakReference; /* PyWeakReference is the base struct for the Python ReferenceType, ProxyType, * and CallableProxyType. */ #ifndef Py_LIMITED_API struct _PyWeakReference { PyObject_HEAD /* The object to which this is a weak reference, or Py_None if none. * Note that this is a stealth reference: wr_object's refcount is * not incremented to reflect this pointer. */ PyObject *wr_object; /* A callable to invoke when wr_object dies, or NULL if none. */ PyObject *wr_callback; /* A cache for wr_object's hash code. As usual for hashes, this is -1 * if the hash code isn't known yet. */ Py_hash_t hash; /* If wr_object is weakly referenced, wr_object has a doubly-linked NULL- * terminated list of weak references to it. These are the list pointers. * If wr_object goes away, wr_object is set to Py_None, and these pointers * have no meaning then. */ PyWeakReference *wr_prev; PyWeakReference *wr_next; }; #endif PyAPI_DATA(PyTypeObject) _PyWeakref_RefType; PyAPI_DATA(PyTypeObject) _PyWeakref_ProxyType; PyAPI_DATA(PyTypeObject) _PyWeakref_CallableProxyType; #define PyWeakref_CheckRef(op) PyObject_TypeCheck(op, &_PyWeakref_RefType) #define PyWeakref_CheckRefExact(op) \ (Py_TYPE(op) == &_PyWeakref_RefType) #define PyWeakref_CheckProxy(op) \ ((Py_TYPE(op) == &_PyWeakref_ProxyType) || \ (Py_TYPE(op) == &_PyWeakref_CallableProxyType)) #define PyWeakref_Check(op) \ (PyWeakref_CheckRef(op) || PyWeakref_CheckProxy(op)) PyAPI_FUNC(PyObject *) PyWeakref_NewRef(PyObject *ob, PyObject *callback); PyAPI_FUNC(PyObject *) PyWeakref_NewProxy(PyObject *ob, PyObject *callback); PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *ref); #ifndef Py_LIMITED_API PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head); PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self); #endif /* Explanation for the Py_REFCNT() check: when a weakref's target is part of a long chain of deallocations which triggers the trashcan mechanism, clearing the weakrefs can be delayed long after the target's refcount has dropped to zero. In the meantime, code accessing the weakref will be able to "see" the target object even though it is supposed to be unreachable. See issue #16602. */ #define PyWeakref_GET_OBJECT(ref) \ (Py_REFCNT(((PyWeakReference *)(ref))->wr_object) > 0 \ ? ((PyWeakReference *)(ref))->wr_object \ : Py_None) #ifdef __cplusplus } #endif #endif /* !Py_WEAKREFOBJECT_H */