├── .gitattributes ├── display ├── config-libs.png ├── config-linker.png └── config-include.png ├── MpegCoder ├── MpegCoder.vcxproj.user ├── stdafx.cpp ├── targetver.h ├── stdafx.h ├── MpegCoder.vcxproj.filters ├── snprintf.cpp ├── dllmain.cpp ├── MpegBase.cpp ├── MpegBase.h ├── MpegCoder.h ├── MpegCoder.vcxproj ├── MpegStreamer.h └── MpegPyd.h ├── .gitignore ├── .github ├── PULL_REQUEST_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE │ ├── pull_request_template.md │ └── pull_request_template.yml └── ISSUE_TEMPLATE │ ├── docs_request.yml │ ├── feature_request.yml │ └── bug_report.yml ├── MpegCoder.sln ├── CONTRIBUTING.md ├── README.md ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── webtools.py └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /display/config-libs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/HEAD/display/config-libs.png -------------------------------------------------------------------------------- /display/config-linker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/HEAD/display/config-linker.png -------------------------------------------------------------------------------- /display/config-include.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/HEAD/display/config-include.png -------------------------------------------------------------------------------- /MpegCoder/MpegCoder.vcxproj.user: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /MpegCoder/stdafx.cpp: -------------------------------------------------------------------------------- 1 | // stdafx.cpp : 只包括标准包含文件的源文件 2 | // $safeprojectname$.pch 将作为预编译标头 3 | // stdafx.obj 将包含预编译类型信息 4 | 5 | #include "stdafx.h" 6 | 7 | // TODO: 在 STDAFX.H 中引用任何所需的附加头文件, 8 | //而不是在此文件中引用 9 | -------------------------------------------------------------------------------- /MpegCoder/targetver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。 4 | 5 | // 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将 6 | // 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。 7 | 8 | #include 9 | -------------------------------------------------------------------------------- /MpegCoder/stdafx.h: -------------------------------------------------------------------------------- 1 | // stdafx.h : 标准系统包含文件的包含文件, 2 | // 或是经常使用但不常更改的 3 | // 特定于项目的包含文件 4 | // 5 | 6 | #pragma once 7 | 8 | #include "targetver.h" 9 | 10 | #define WIN32_LEAN_AND_MEAN // 从 Windows 头中排除极少使用的资料 11 | // Numpy header: 12 | #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 13 | // Windows header: 14 | #define _CRT_SECURE_NO_WARNINGS 15 | #include 16 | 17 | 18 | 19 | // TODO: 在此处引用程序需要的其他头文件 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Others 2 | include/* 3 | lib/* 4 | .vs/* 5 | *.pdb 6 | *.pyd 7 | *.ipdb 8 | *.iobj 9 | *.exp 10 | *.log 11 | *.tlog 12 | *.lastbuildstate 13 | unsuccessfulbuild 14 | /MpegCoder/x64/ 15 | 16 | # Compressed files 17 | *.tar.xz 18 | *.tar.gz 19 | *.tar.bz2 20 | *.7z 21 | *.zip 22 | *.rar 23 | 24 | # Prerequisites 25 | *.d 26 | 27 | # Compiled Object files 28 | *.slo 29 | *.lo 30 | *.o 31 | *.obj 32 | 33 | # Precompiled Headers 34 | *.gch 35 | *.pch 36 | 37 | # Compiled Dynamic libraries 38 | *.so 39 | *.dylib 40 | *.dll 41 | 42 | # Fortran module files 43 | *.mod 44 | *.smod 45 | 46 | # Compiled Static libraries 47 | *.lai 48 | *.la 49 | *.a 50 | *.lib 51 | 52 | # Executables 53 | *.exe 54 | *.out 55 | *.app 56 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | # Pull request 2 | 3 | ## Get started 4 | 5 | - [ ] I have read [Contributing guidelines](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CONTRIBUTING.md). 6 | - [ ] I agree to follow the [Code of Conduct](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CODE_OF_CONDUCT.md). 7 | - [ ] I have confirmed that my pull request (PR) is not duplicated with an existing PR. 8 | - [ ] I have confirmed that my pull request (PR) passes the testing workflow of the project. 9 | 10 | ## Description 11 | 12 | Describe what you have done with this PR. List any dependencies that are required for this change. 13 | 14 | If your PR is designed for an issue, please refer to the issue by the following example: 15 | 16 | Fixes # (issue) 17 | 18 | ## Updated report 19 | 20 | Please summarize your modifications as an itemized report. 21 | 22 | 1. Update ... 23 | 2. Add ... 24 | 25 | ## Information 26 | 27 | Please provide the following information about your PR: 28 | 29 | - `mpegCoder` version: 30 | 31 | ## Additional context 32 | 33 | Add any other context about the problem here. 34 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/pull_request_template.md: -------------------------------------------------------------------------------- 1 | # Pull request 2 | 3 | ## Get started 4 | 5 | - [ ] I have read [Contributing guidelines](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CONTRIBUTING.md). 6 | - [ ] I agree to follow the [Code of Conduct](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CODE_OF_CONDUCT.md). 7 | - [ ] I have confirmed that my pull request (PR) is not duplicated with an existing PR. 8 | - [ ] I have confirmed that my pull request (PR) passes the testing workflow of the project. 9 | 10 | ## Description 11 | 12 | Describe what you have done with this PR. List any dependencies that are required for this change. 13 | 14 | If your PR is designed for an issue, please refer to the issue by the following example: 15 | 16 | Fixes # (issue) 17 | 18 | ## Updated report 19 | 20 | Please summarize your modifications as an itemized report. 21 | 22 | 1. Update ... 23 | 2. Add ... 24 | 25 | ## Information 26 | 27 | Please provide the following information about your PR: 28 | 29 | - `mpegCoder` version: 30 | 31 | ## Additional context 32 | 33 | Add any other context about the problem here. 34 | -------------------------------------------------------------------------------- /MpegCoder.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31410.357 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MpegCoder", "MpegCoder\MpegCoder.vcxproj", "{57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Debug|x64.ActiveCfg = Debug|x64 17 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Debug|x64.Build.0 = Debug|x64 18 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Debug|x86.ActiveCfg = Debug|Win32 19 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Debug|x86.Build.0 = Debug|Win32 20 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Release|x64.ActiveCfg = Release|x64 21 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Release|x64.Build.0 = Release|x64 22 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Release|x86.ActiveCfg = Release|Win32 23 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {C950261D-8B64-4B1B-8275-B7B3F8F58C6E} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/docs_request.yml: -------------------------------------------------------------------------------- 1 | name: Docs request 2 | description: Report a problem or a request for the docs. 3 | title: "[Docs]" 4 | labels: documentation, to be solved 5 | 6 | body: 7 | - type: checkboxes 8 | attributes: 9 | label: Get started 10 | options: 11 | - label: >- 12 | I have read [Contributing guidelines](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CONTRIBUTING.md). 13 | required: true 14 | - label: >- 15 | I agree to follow the [Code of Conduct](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CODE_OF_CONDUCT.md). 16 | required: true 17 | - label: >- 18 | I have confirmed that my issue is not duplicated with an existing issue. 19 | required: true 20 | 21 | - type: textarea 22 | attributes: 23 | label: Problem 24 | description: >- 25 | If you meet any problems with the documentation, please describe your problems here. 26 | 27 | - type: textarea 28 | attributes: 29 | label: Required feature 30 | description: >- 31 | If you need more explanations in the documentation, please describe your needs here. 32 | 33 | - type: input 34 | attributes: 35 | label: mpegCoder version 36 | description: >- 37 | e.g. 3.1.0 38 | validations: 39 | required: true 40 | 41 | - type: textarea 42 | attributes: 43 | label: Additional context 44 | description: >- 45 | Add any other context about the problem here. 46 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/pull_request_template.yml: -------------------------------------------------------------------------------- 1 | name: Pull request 2 | description: Send a pull request (PR) for this project. 3 | title: "[PR]" 4 | 5 | body: 6 | - type: checkboxes 7 | attributes: 8 | label: Get started 9 | options: 10 | - label: >- 11 | I have read [Contributing guidelines](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CONTRIBUTING.md). 12 | required: true 13 | - label: >- 14 | I agree to follow the [Code of Conduct](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CODE_OF_CONDUCT.md). 15 | required: true 16 | - label: >- 17 | I have confirmed that my pull request (PR) is not duplicated with an existing PR. 18 | required: true 19 | - label: >- 20 | I have confirmed that my pull request (PR) passes the testing workflow of the project. 21 | required: true 22 | 23 | - type: textarea 24 | attributes: 25 | label: Description 26 | description: >- 27 | Describe what you have done with this PR. 28 | 29 | - type: textarea 30 | attributes: 31 | label: Updated report 32 | description: >- 33 | Summarize your modifications as itemized report. 34 | value: | 35 | 1. Update ... 36 | 2. Add ... 37 | 38 | - type: input 39 | attributes: 40 | label: mpegCoder version 41 | description: >- 42 | e.g. 3.1.0 43 | validations: 44 | required: true 45 | 46 | - type: textarea 47 | attributes: 48 | label: Additional context 49 | description: >- 50 | Add any other context about the problem here. 51 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for this project 3 | title: "[Feature]" 4 | labels: enhancement, to be solved 5 | 6 | body: 7 | - type: checkboxes 8 | attributes: 9 | label: Get started 10 | options: 11 | - label: >- 12 | I have read [Contributing guidelines](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CONTRIBUTING.md). 13 | required: true 14 | - label: >- 15 | I agree to follow the [Code of Conduct](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CODE_OF_CONDUCT.md). 16 | required: true 17 | - label: >- 18 | I have confirmed that my issue is not duplicated with an existing issue. 19 | required: true 20 | 21 | - type: textarea 22 | attributes: 23 | label: Problem 24 | description: >- 25 | If your feature request is related to a problem, please describe the problem clearly and concisely. 26 | 27 | - type: textarea 28 | attributes: 29 | label: Required feature 30 | description: >- 31 | A clear and concise description of what you want to happen. 32 | validations: 33 | required: true 34 | 35 | - type: textarea 36 | attributes: 37 | label: Alternative solution 38 | description: >- 39 | A clear and concise description of any alternative solutions or features you've considered. 40 | 41 | - type: input 42 | attributes: 43 | label: mpegCoder version 44 | description: >- 45 | e.g. 3.1.0 46 | validations: 47 | required: true 48 | 49 | - type: textarea 50 | attributes: 51 | label: Additional context 52 | description: >- 53 | Add any other context about the problem here. 54 | -------------------------------------------------------------------------------- /MpegCoder/MpegCoder.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | 头文件 20 | 21 | 22 | 头文件 23 | 24 | 25 | 头文件 26 | 27 | 28 | 头文件 29 | 30 | 31 | 头文件 32 | 33 | 34 | 头文件 35 | 36 | 37 | 38 | 39 | 源文件 40 | 41 | 42 | 源文件 43 | 44 | 45 | 源文件 46 | 47 | 48 | 源文件 49 | 50 | 51 | 源文件 52 | 53 | 54 | 源文件 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to mpegCoder 2 | 3 | Thank you for your interest in contributing to `mpegCoder`! We are accepting pull 4 | requests in any time. 5 | 6 | As a reminder, all contributors are expected to follow our [Code of Conduct][coc]. 7 | 8 | [coc]: https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CODE_OF_CONDUCT.md 9 | 10 | ## Contributing to the package 11 | 12 | ### Installation 13 | 14 | Please [fork] this project as your own repository, and create a sub-branch based on any branch in this project. The new branch name could be a short description of the implemented new feature. 15 | 16 | After that, clone your repository by 17 | 18 | ```shell 19 | git clone -b --single-branch https://github.com//FFmpeg-Encoder-Decoder-for-Python.git mpegCoder 20 | ``` 21 | 22 | In some cases, you may need to install some dependencies. Please follow the specific instructions for compling `mpegCoder`. 23 | 24 | ### Debugging 25 | 26 | We have not provided any testing scripts now. I am glad to accept the help from anyone who is willing to writing the testing scripts for this project. 27 | 28 | ### Sending pull requests 29 | 30 | After you finish your works, please send a new request, and compare your branch with the target branch in `mpegCoder`. You could explain your works concisely in the pull request description. You are not required to add the updating reports in the repository, or add the documentation. I could take over these works based on your description. 31 | 32 | ## Contributing to docs 33 | 34 | If you want to contribute to docs, please fork the [`docs`](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/tree/docs) branch, and clone it 35 | 36 | ```shell 37 | git clone -b docs --single-branch https://github.com//FFmpeg-Encoder-Decoder-for-Python.git mpegCoder-docs 38 | ``` 39 | 40 | You need to install `nodejs` and `yarn` first. We suggest to create an isolated conda environment: 41 | 42 | ```shell 43 | conda create -n docs -c conda-forge git python=3.9 nodejs=15.14.0 yarn=1.22.10 44 | ``` 45 | 46 | Then you could initialize the docs project by 47 | 48 | ```shell 49 | cd mpegCoder-docs 50 | yarn install 51 | ``` 52 | 53 | You could start the local debugging by 54 | 55 | ```shell 56 | yarn start 57 | ``` 58 | 59 | After you finish your works, you could also send a pull request. 60 | -------------------------------------------------------------------------------- /MpegCoder/snprintf.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * C99-compatible snprintf() and vsnprintf() implementations 3 | * Copyright (c) 2012 Ronald S. Bultje 4 | * 5 | * This file is part of FFmpeg. 6 | * 7 | * FFmpeg is free software; you can redistribute it and/or 8 | * modify it under the terms of the GNU Lesser General Public 9 | * License as published by the Free Software Foundation; either 10 | * version 2.1 of the License, or (at your option) any later version. 11 | * 12 | * FFmpeg is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | * Lesser General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Lesser General Public 18 | * License along with FFmpeg; if not, write to the Free Software 19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 20 | */ 21 | 22 | 23 | #include "stdafx.h" 24 | 25 | extern "C" 26 | { 27 | #include 28 | #include 29 | #include 30 | #include 31 | } 32 | 33 | #include "compat/va_copy.h" 34 | #include "libavutil/error.h" 35 | #include "compat/msvcrt/snprintf.h" 36 | 37 | #if defined(__MINGW32__) 38 | #define EOVERFLOW EFBIG 39 | #endif 40 | 41 | extern "C" 42 | { 43 | int avpriv_snprintf(char *s, size_t n, const char *fmt, ...) { 44 | va_list ap; 45 | int ret; 46 | 47 | va_start(ap, fmt); 48 | ret = avpriv_vsnprintf(s, n, fmt, ap); 49 | va_end(ap); 50 | 51 | return ret; 52 | } 53 | 54 | int avpriv_vsnprintf(char *s, size_t n, const char *fmt, va_list ap) { 55 | int ret; 56 | va_list ap_copy; 57 | 58 | if (n == 0) 59 | return _vscprintf(fmt, ap); 60 | else if (n > INT_MAX) 61 | return AVERROR(EOVERFLOW); 62 | 63 | /* we use n - 1 here because if the buffer is not big enough, the MS 64 | * runtime libraries don't add a terminating zero at the end. MSDN 65 | * recommends to provide _snprintf/_vsnprintf() a buffer size that 66 | * is one less than the actual buffer, and zero it before calling 67 | * _snprintf/_vsnprintf() to workaround this problem. 68 | * See http://msdn.microsoft.com/en-us/library/1kt27hek(v=vs.80).aspx */ 69 | memset(s, 0, n); 70 | va_copy(ap_copy, ap); 71 | ret = _vsnprintf_s(s, n - 1, INT_MAX, fmt, ap_copy); 72 | va_end(ap_copy); 73 | if (ret == -1) 74 | ret = _vscprintf(fmt, ap); 75 | 76 | return ret; 77 | } 78 | } -------------------------------------------------------------------------------- /MpegCoder/dllmain.cpp: -------------------------------------------------------------------------------- 1 | // dllmain.cpp : The entry of the dll program. 2 | #include "stdafx.h" 3 | #include "MpegPyd.h" 4 | 5 | /***************************************************************************** 6 | * The initialization of the module. Would be invoked when using import. 7 | *****************************************************************************/ 8 | PyMODINIT_FUNC // == __decslpec(dllexport) PyObject*, Define the exported main function. 9 | PyInit_mpegCoder(void) { // The external module name is: --CppClass 10 | import_array(); 11 | /* Initialize libavcodec, and register all codecs and formats. */ 12 | // Register everything 13 | #ifndef FFMPG3_4 14 | av_register_all(); 15 | #endif 16 | #ifndef FFMPG4_0 17 | avformat_network_init(); 18 | #endif 19 | 20 | PyObject* pReturn = 0; 21 | // Configure the __new__ method as the default method. This method is used for building the instances. 22 | C_MPDC_ClassInfo.tp_new = PyType_GenericNew; 23 | C_MPEC_ClassInfo.tp_new = PyType_GenericNew; 24 | C_MPCT_ClassInfo.tp_new = PyType_GenericNew; 25 | C_MPSV_ClassInfo.tp_new = PyType_GenericNew; 26 | 27 | /* Finish the initialization, including the derivations. 28 | * When success, return 0; Otherwise, return -1 and throw errors. */ 29 | if (PyType_Ready(&C_MPDC_ClassInfo) < 0) 30 | return nullptr; 31 | if (PyType_Ready(&C_MPEC_ClassInfo) < 0) 32 | return nullptr; 33 | if (PyType_Ready(&C_MPCT_ClassInfo) < 0) 34 | return nullptr; 35 | if (PyType_Ready(&C_MPSV_ClassInfo) < 0) 36 | return nullptr; 37 | 38 | pReturn = PyModule_Create(&ModuleInfo); // Create the module according to the module info. 39 | if (pReturn == 0) 40 | return nullptr; 41 | 42 | Py_INCREF(&ModuleInfo); // Because the module is not registered to the python counter, Py_INCREF is required to be invoked. 43 | PyModule_AddFunctions(pReturn, C_MPC_MethodMembers); // Add the global method members. 44 | PyModule_AddObject(pReturn, "MpegDecoder", (PyObject*)&C_MPDC_ClassInfo); // Add the class as one module member. 45 | PyModule_AddObject(pReturn, "MpegEncoder", (PyObject*)&C_MPEC_ClassInfo); 46 | PyModule_AddObject(pReturn, "MpegClient", (PyObject*)&C_MPCT_ClassInfo); 47 | PyModule_AddObject(pReturn, "MpegServer", (PyObject*)&C_MPSV_ClassInfo); 48 | return pReturn; 49 | } 50 | 51 | /* 52 | BOOL APIENTRY DllMain( HMODULE hModule, 53 | DWORD ul_reason_for_call, 54 | LPVOID lpReserved 55 | ) 56 | { 57 | switch (ul_reason_for_call) 58 | { 59 | case DLL_PROCESS_ATTACH: 60 | case DLL_THREAD_ATTACH: 61 | case DLL_THREAD_DETACH: 62 | case DLL_PROCESS_DETACH: 63 | break; 64 | } 65 | return TRUE; 66 | } 67 | */ 68 | -------------------------------------------------------------------------------- /MpegCoder/MpegBase.cpp: -------------------------------------------------------------------------------- 1 | #include "stdafx.h" 2 | #include "MpegBase.h" 3 | 4 | // Global functions. 5 | const string cmpc::av_make_error_string2_cpp(int errnum) { 6 | char errbuf[AV_ERROR_MAX_STRING_SIZE]; 7 | av_strerror(errnum, errbuf, AV_ERROR_MAX_STRING_SIZE); 8 | string strerrbuf = errbuf; 9 | return strerrbuf; 10 | } 11 | 12 | const string cmpc::av_ts_make_string_cpp(int64_t ts) { 13 | char tsstrbuf[AV_TS_MAX_STRING_SIZE]; 14 | av_ts_make_string(tsstrbuf, ts); 15 | string strtsstrbuf = tsstrbuf; 16 | return strtsstrbuf; 17 | } 18 | 19 | const string cmpc::av_ts_make_time_string_cpp(int64_t ts, AVRational* tb) { 20 | char tsstrbuf[AV_TS_MAX_STRING_SIZE]; 21 | av_ts_make_time_string(tsstrbuf, ts, tb); 22 | string strtsstrbuf = tsstrbuf; 23 | return strtsstrbuf; 24 | } 25 | 26 | // CharList implementation. 27 | cmpc::CharList::CharList(void) : data() { 28 | } 29 | 30 | cmpc::CharList::CharList(const std::vector& args) : data() { 31 | set(args); 32 | } 33 | 34 | cmpc::CharList::CharList(const std::vector&& args) noexcept : 35 | data(args) { 36 | } 37 | 38 | cmpc::CharList::~CharList(void) { 39 | clear(); 40 | } 41 | 42 | cmpc::CharList::CharList(const CharList& ref) : data() { 43 | set(ref.data); 44 | } 45 | 46 | cmpc::CharList& cmpc::CharList::operator=(const CharList& ref) { 47 | if (this != &ref) { 48 | set(ref.data); 49 | } 50 | return *this; 51 | } 52 | 53 | cmpc::CharList::CharList(CharList&& ref) noexcept : 54 | data(std::move(ref.data)) { 55 | } 56 | 57 | cmpc::CharList& cmpc::CharList::operator=(CharList&& ref) noexcept { 58 | if (this != &ref) { 59 | set(std::move(ref.data)); 60 | } 61 | return *this; 62 | } 63 | 64 | cmpc::CharList& cmpc::CharList::operator=(const std::vector& args) { 65 | set(args); 66 | return *this; 67 | } 68 | 69 | cmpc::CharList& cmpc::CharList::operator=(std::vector&& args) noexcept { 70 | set(args); 71 | return *this; 72 | } 73 | 74 | void cmpc::CharList::set(const std::vector& args) { 75 | data.clear(); 76 | for (auto it = args.begin(); it != args.end(); ++it) { 77 | string new_str(*it); 78 | data.push_back(new_str); 79 | } 80 | } 81 | 82 | void cmpc::CharList::set(std::vector&& args) noexcept { 83 | data = args; 84 | } 85 | 86 | void cmpc::CharList::clear() { 87 | data.clear(); 88 | } 89 | 90 | std::shared_ptr cmpc::CharList::c_str() { 91 | std::shared_ptr pointer(new const char* [data.size() + 1], std::default_delete()); 92 | auto p_cur = pointer.get(); 93 | for (auto it = data.begin(); it != data.end(); ++it) { 94 | *p_cur = it->c_str(); 95 | p_cur++; 96 | } 97 | *p_cur = nullptr; 98 | return pointer; 99 | } 100 | 101 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug report 2 | description: Something is not working correctly. 3 | title: "[BUG]" 4 | labels: "bug, to be solved" 5 | 6 | body: 7 | - type: checkboxes 8 | attributes: 9 | label: Get started 10 | options: 11 | - label: >- 12 | I have read [Contributing guidelines](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CONTRIBUTING.md). 13 | required: true 14 | - label: >- 15 | I have confirmed that my problem could not be solved by the [troubleshooting](https://cainmagi.github.io/FFmpeg-Encoder-Decoder-for-Python/docs/troubleshooting/installation) section in the documentation. 16 | required: true 17 | - label: >- 18 | I agree to follow the [Code of Conduct](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/blob/master/CODE_OF_CONDUCT.md). 19 | required: true 20 | - label: >- 21 | I have confirmed that my issue is not duplicated with an existing issue. 22 | required: true 23 | 24 | - type: textarea 25 | attributes: 26 | label: Description 27 | description: >- 28 | A clear and concise description of what the bug is. 29 | validations: 30 | required: true 31 | 32 | - type: textarea 33 | attributes: 34 | label: To Reproduce 35 | description: >- 36 | Steps to reproduce the behavior. Instead of describing the steps, you could also provide your codes related to the error here. 37 | value: | 38 | 1. Get package from '...' 39 | 2. Then run '...' 40 | 3. An error occurs. 41 | 42 | - type: textarea 43 | attributes: 44 | label: Traceback 45 | description: >- 46 | The python trackback of the bug. If there is no traceback, please describe (1) The expected behaviors. (2) The actual behaviors. 47 | render: sh-session 48 | 49 | - type: textarea 50 | attributes: 51 | label: Behaviors 52 | description: >- 53 | If there is no traceback, please describe (1) The expected behaviors. (2) The actual behaviors. 54 | value: | 55 | 1. The expected behaviors: 56 | 2. The actual behaviors: 57 | 58 | - type: textarea 59 | attributes: 60 | label: Screenshots 61 | description: >- 62 | If applicable, add screenshots to help explain your problem. 63 | 64 | - type: input 65 | attributes: 66 | label: OS 67 | description: >- 68 | e.g. Ubuntu 20.04, Debian 10, Windows 10 21H1 69 | validations: 70 | required: true 71 | - type: input 72 | attributes: 73 | label: Python version 74 | description: >- 75 | e.g. 3.8 76 | validations: 77 | required: true 78 | - type: input 79 | attributes: 80 | label: numpy version 81 | description: >- 82 | e.g. 1.21.1 83 | validations: 84 | required: true 85 | - type: input 86 | attributes: 87 | label: mpegCoder version 88 | description: >- 89 | e.g. 3.1.0 90 | validations: 91 | required: true 92 | 93 | - type: textarea 94 | attributes: 95 | label: Additional context 96 | description: >- 97 | Add any other context about the problem here. 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FFmpeg-Encoder-Decoder-for-Python 2 | 3 | This is a mpegCoder adapted from FFmpeg & Python-c-api. Using it you could get access to processing video easily. Just use it as a common module in python like this. 4 | 5 | ```python 6 | import mpegCoder 7 | ``` 8 | 9 | | Branch | Description | 10 | | :-------------: | :-----------: | 11 | | `master` :link: | The source project of `mpegCoder`, Windows version. | 12 | | [`master-linux` :link:][git-linux] | The source project of `mpegCoder`, Linux version. | 13 | | [`example-client-check` :link:][exp1] | A testing project of the online video stream demuxing. | 14 | | [`example-client-player` :link:][exp2] | A testing project of the simple online video stream player. | 15 | 16 | ## Source project of `mpegCoder` (Windows) 17 | 18 | The following instructions are used for building the project on Windows with Visual Studio 2019. 19 | 20 | 1. Clone the `master` branch which only contains the codes of `mpegCoder`: 21 | 22 | ```bash 23 | git clone --single-branch -b master https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python.git 24 | ``` 25 | 26 | 2. Download the FFMpeg dependencies, including `include` and `lib`. Users could download dependencies manually by checking [the release page :link:](https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/releases/tag/deps-3.0.0). However, we recommend users to use the following script to get the dependencies quickly: 27 | 28 | ```bash 29 | python webtools.py 30 | ``` 31 | 32 | This script requires users to install `urllib3`. The `tqdm` is also recommended to be installed. 33 | 34 | 3. The following configurations should be set for `All` (both debug and release) and `x64`. Open the project by `MpegCoder.sln`. Then configure the following paths of the include directories and the library directories. In both configurations, the first item is required to be modified according to your python path, the second item is required to be modified according to your numpy path. 35 | 36 | | Path | Screenshot | 37 | | :----- | :----------: | 38 | | `includes` | ![Configure includes](./display/config-include.png) | 39 | | `libs` | ![Configure libs](./display/config-include.png) | 40 | 41 | 4. Modify the linker configs. We only need to change the item `python3x.lib` according to the python version you have. 42 | ![Configure linker](./display/config-linker.png) 43 | 44 | 5. Run the `Release`, `x64` build. The built file should be saved as `x64\Release\mpegCoder.pyd`. 45 | 46 | 6. The `mpegCoder.pyd` should be used together with the FFMpeg shared libraries, including: 47 | 48 | ```shell 49 | avcodec-59.dll 50 | avformat-59.dll 51 | avutil-57.dll 52 | swresample-4.dll 53 | swscale-6.dll 54 | ``` 55 | 56 | ## Update reports 57 | 58 | Has been moved to [:bookmark_tabs: CHANGELOG.md](./CHANGELOG.md) 59 | 60 | ## Version of currently used FFmpeg library 61 | 62 | Current FFMpeg version is `5.0`. 63 | 64 | | Dependency | Version | 65 | | :-------------: | :------------: | 66 | | `libavcodec` | `59.18.100.0` | 67 | | `libavformat` | `59.16.100.0` | 68 | | `libavutil` | `57.17.100.0` | 69 | | `libswresample` | `4.3.100.0` | 70 | | `libswscale` | `6.4.100.0` | 71 | 72 | [git-linux]:https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/tree/master-linux "master (Linux)" 73 | [exp1]:https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/tree/example-client-check "check the client" 74 | [exp2]:https://github.com/cainmagi/FFmpeg-Encoder-Decoder-for-Python/tree/example-client-player "client with player" 75 | -------------------------------------------------------------------------------- /MpegCoder/MpegBase.h: -------------------------------------------------------------------------------- 1 | #ifndef MPEGBASE_H_INCLUDED 2 | #define MPEGBASE_H_INCLUDED 3 | 4 | #define MPEGCODER_EXPORTS 5 | #ifdef MPEGCODER_EXPORTS 6 | #define MPEGCODER_API __declspec(dllexport) 7 | #else 8 | #define MPEGCODER_API __declspec(dllimport) 9 | #endif 10 | 11 | #define FFMPG3_4 12 | #define FFMPG4_0 13 | #define FFMPG4_4 14 | #define FFMPG5_0 15 | 16 | #define MPEGCODER_CURRENT_VERSION "3.2.0" 17 | 18 | #define STREAM_PIX_FMT AVPixelFormat::AV_PIX_FMT_YUV420P /* default pix_fmt */ 19 | 20 | #define SCALE_FLAGS SWS_BICUBIC 21 | //SWS_BILINEAR 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | using std::string; 36 | using std::cerr; 37 | using std::cout; 38 | using std::endl; 39 | using std::ostream; 40 | 41 | namespace cmpc { 42 | extern "C" 43 | { 44 | #include "libavcodec/avcodec.h" 45 | #include "libavformat/avformat.h" 46 | #include "libswscale/swscale.h" 47 | #include "libavutil/imgutils.h" 48 | #include "libavutil/samplefmt.h" 49 | #include "libavutil/timestamp.h" 50 | #include "libavutil/opt.h" 51 | #include "libavutil/avassert.h" 52 | #include "libavutil/channel_layout.h" 53 | #include "libavutil/mathematics.h" 54 | #include "libavutil/time.h" 55 | #include "libswresample/swresample.h" 56 | } 57 | } 58 | 59 | #ifdef __cplusplus 60 | namespace cmpc { 61 | const string av_make_error_string2_cpp(int errnum); 62 | #undef av_err2str 63 | #define av_err2str(errnum) av_make_error_string2_cpp(errnum) 64 | const string av_ts_make_string_cpp(int64_t ts); 65 | #undef av_ts2str 66 | #define av_ts2str(ts) av_ts_make_string_cpp(ts) 67 | const string av_ts_make_time_string_cpp(int64_t ts, AVRational* tb); 68 | #undef av_ts2timestr 69 | #define av_ts2timestr(ts, tb) av_ts_make_time_string_cpp(ts, tb) 70 | } 71 | #endif // __cplusplus 72 | 73 | namespace cmpc { 74 | // a wrapper around a single output AVStream 75 | typedef struct _OutputStream { 76 | AVStream* st; 77 | AVCodecContext* enc; 78 | 79 | /* pts of the next frame that will be generated */ 80 | int64_t next_frame; 81 | 82 | AVFrame* frame; 83 | AVFrame* tmp_frame; 84 | 85 | struct SwsContext* sws_ctx; 86 | } OutputStream; 87 | 88 | // A wrapper of the char *[] 89 | class CharList { 90 | public: 91 | CharList(void); // Constructor. 92 | CharList(const std::vector& args); // Copy constructor (string ver). 93 | CharList(const std::vector&& args) noexcept; // Move constructor (string ver). 94 | ~CharList(void); // 3-5 law. Destructor. 95 | CharList(const CharList& ref); // Copy constructor. 96 | CharList& operator=(const CharList& ref); // Copy assignment operator. 97 | CharList(CharList&& ref) noexcept; // Move constructor. 98 | CharList& operator=(CharList&& ref) noexcept; // Move assignment operator. 99 | CharList& operator=(const std::vector& args); // Copy assignment operator (string ver). 100 | CharList& operator=(std::vector&& args) noexcept; // Move assignment operator (string ver). 101 | void set(const std::vector& args); // Set strings as data. 102 | void set(std::vector&& args) noexcept; // Set strings as data (move). 103 | void clear(); // clear all data. 104 | std::shared_ptr c_str(); // Equivalent conversion for char ** 105 | private: 106 | std::vector data; 107 | }; 108 | } 109 | 110 | // compatibility with newer API 111 | #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1) 112 | #define av_frame_alloc avcodec_alloc_frame 113 | #define av_frame_free avcodec_free_frame 114 | #endif 115 | 116 | #endif 117 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # FFmpeg-Encoder-Decoder-for-Python 2 | 3 | ## Update Report 4 | 5 | ### V3.2.0 update report: 6 | 7 | 1. Upgrade to `FFMpeg 5.0` Version. 8 | 9 | 2. Fix the const assignment bug caused by the codec configuration method. 10 | 11 | ### V3.1.0 update report: 12 | 13 | 1. Support `str()` type for all string arguments. 14 | 15 | 2. Support `http`, `ftp`, `sftp` streams for `MpegServer`. 16 | 17 | 3. Support `nthread` option for `MpegDecoder`, `MpegEncoder`, `MpegClient` and `MpegServer`. 18 | 19 | 4. Fix a bug caused by the constructor `MpegServer()`. 20 | 21 | 5. Clean up all `gcc` warnings of the source codes. 22 | 23 | 6. Fix typos in docstrings. 24 | 25 | ### V3.0.0 update report: 26 | 27 | 1. Fix a severe memory leaking bugs when using `AVPacket`. 28 | 29 | 2. Fix a bug caused by using `MpegClient.terminate()` when a video is closed by the server. 30 | 31 | 3. Support the `MpegServer`. This class is used for serving the online video streams. 32 | 33 | 4. Refactor the implementation of the loggings. 34 | 35 | 5. Add `getParameter()` and `setParameter(configDict)` APIs to `MpegEncoder` and `MpegServer`. 36 | 37 | 6. Move `FFMpeg` depedencies and the `OutputStream` class to the `cmpc` space. 38 | 39 | 7. Fix dependency issues and cpp standard issues. 40 | 41 | 8. Upgrade to `FFMpeg 4.4` Version. 42 | 43 | 9. Add a quick script for fetching the `FFMpeg` dependencies. 44 | 45 | ### V2.05 update report: 46 | 47 | 1. Fix a severe bug that causes the memory leak when using `MpegClient`.This bug also exists in `MpegDecoder`, but it seems that the bug would not cause memory leak in that case. (Although we have also fixed it now.) 48 | 49 | 2. Upgrade to `FFMpeg 4.0` Version. 50 | 51 | ### V2.01 update report: 52 | 53 | 1. Fix a bug that occurs when the first received frame may has a PTS larger than zero. 54 | 55 | 2. Enable the project produce the newest `FFMpeg 3.4.2` version and use `Python 3.6.4`, `numpy 1.14`. 56 | 57 | ### V2.0 update report: 58 | 59 | 1. Revise the bug of the encoder which may cause the stream duration is shorter than the real duration of the video in some not advanced media players. 60 | 61 | 2. Improve the structure of the code and remove some unnecessary codes. 62 | 63 | 3. Provide a complete version of client, which could demux the video stream from a server in any network protocol. 64 | 65 | ### V1.8 update report: 66 | 67 | 1. Provide options `(widthDst, heightDst)` to let `MpegDecoder` could control the output size manually. To ensure the option is valid, we must use the method `setParameter` before `FFmpegSetup`. Now you could use this options to get a rescaled output directly: 68 | 69 | ```python 70 | d = mpegCoder.MpegDecoder() # initialize 71 | d.setParameter(widthDst=400, heightDst=300) # noted that these options must be set before 'FFmpegSetup'! 72 | d.FFmpegSetup(b'i.avi') # the original video size would not influence the output 73 | print(d) # examine the parameters. You could also get the original video size by 'getParameter' 74 | d.ExtractFrame(0, 100) # get 100 frames with 400x300 75 | ``` 76 | 77 | In another example, the set optional parameters could be inherited by encoder, too: 78 | 79 | ```python 80 | d.setParameter(widthDst=400, heightDst=300) # set optional parameters 81 | ... 82 | e.setParameter(decoder=d) # the width/height would inherit from widthDst/heightDst rather than original width/height of the decoder. 83 | ``` 84 | 85 | Noted that we do not provide `widthDst`/`heightDst` in `getParameter`, because these 2 options are all set by users. There is no need to get them from the video metadata. 86 | 87 | 2. Optimize some realization of Decoder so that its efficiency could be improved. 88 | 89 | ### V1.7-linux update report: 90 | 91 | Thanks to God, we succeed in this work! 92 | 93 | A new version is avaliable for Linux. To implement this tool, you need to install some libraries firstly: 94 | 95 | * python3.5 96 | 97 | * numpy 1.13 98 | 99 | If you want, you could install `ffmpeg` on Linux: Here are some instructions 100 | 101 | 1. Check every pack which ffmpeg needs here: [Dependency of FFmpeg](https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu "Dependency of FFmpeg") 102 | 103 | 2. Use these steps to install ffmpeg instead of provided commands on the above site. 104 | 105 | ```Bash 106 | $ git clone https://git.ffmpeg.org/ffmpeg.git 107 | $ cd ffmpeg 108 | $ ./configure --prefix=host --enable-gpl --enable-libx264 --enable-libx265 --enable-shared --disable-static --disable-doc 109 | $ make 110 | $ make install 111 | ``` 112 | 113 | ### V1.7 update report: 114 | 115 | 1. Realize the encoder totally. 116 | 117 | 2. Provide a global option `dumpLevel` to control the log shown in the screen. 118 | 119 | 3. Fix bugs in initialize functions. 120 | 121 | ### V1.5 update report: 122 | 123 | 1. Provide an incomplete version of encoder, which could encode frames as a video stream that could not be played by player. 124 | 125 | ### V1.4 update report: 126 | 127 | 1. Fix a severe bug of the decoder, which causes the memory collapsed if decoding a lot of frames. 128 | 129 | ### V1.2 update report: 130 | 131 | 1. Use numpy array to replace the native pyList, which improves the speed significantly. 132 | 133 | ### V1.0 update report: 134 | 135 | 1. Provide the decoder which could decode videos in arbitrary formats and arbitrary coding. 136 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | cainmagi@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /MpegCoder/MpegCoder.h: -------------------------------------------------------------------------------- 1 | // 下列 ifdef 块是创建使从 DLL 导出更简单的 2 | // 宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 MPEGCODER_EXPORT 3 | // 符号编译的。在使用此 DLL 的 4 | // 任何其他项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将 5 | // MPEGCODER_API 函数视为自 DLL 导入,而此 DLL 则将用此宏定义的 6 | // 符号视为是被导出的。 7 | #ifndef MPEGCODER_H_INCLUDED 8 | #define MPEGCODER_H_INCLUDED 9 | 10 | #include "MpegBase.h" 11 | 12 | #define MPEGCODER_DEBUG 13 | 14 | // Exported from MpegCoder.dll 15 | namespace cmpc { 16 | 17 | extern int8_t __dumpControl; 18 | class CMpegClient; 19 | class CMpegServer; 20 | 21 | class CMpegDecoder { 22 | public: 23 | CMpegDecoder(void); // Constructor. 24 | ~CMpegDecoder(void); // 3-5 law. Destructor. 25 | CMpegDecoder(const CMpegDecoder& ref); // Copy constructor. 26 | CMpegDecoder& operator=(const CMpegDecoder& ref); // Copy assignment operator. 27 | CMpegDecoder(CMpegDecoder&& ref) noexcept; // Move constructor. 28 | CMpegDecoder& operator=(CMpegDecoder&& ref) noexcept; // Move assignment operator. 29 | friend class CMpegEncoder; // Let the encoder be able to access the member of this class. 30 | friend class CMpegServer; // Let the server be able to access the member of this class. 31 | friend ostream& operator<<(ostream& out, CMpegDecoder& self_class); // Show the results. 32 | void clear(void); // Clear all configurations and resources. 33 | void meta_protected_clear(void); // Clear the resources, but the configurations are remained. 34 | void dumpFormat(); // Show the av_format results. 35 | void setParameter(string keyword, void* ptr); // Set arguments. 36 | PyObject* getParameter(string keyword); // Get the current arguments. 37 | PyObject* getParameter(); // Get all key arguments. 38 | void resetPath(string inVideoPath); // Reset the path (encoded) of the online video stream. 39 | bool FFmpegSetup(); // Configure the decoder, and extract the basic meta-data. This method is also equipped in the constructor. 40 | bool FFmpegSetup(string inVideoPath); // Configure the decoder with extra arguments. 41 | bool ExtractFrame(PyObject* PyFrameList, int64_t framePos, int64_t frameNum, double timePos, int mode); // Extract n frames as PyFrame, where n is given by frameNum, and the starting postion is given by framePos. 42 | bool ExtractGOP(PyObject* PyFrameList); // Extract a GOP as PyFrames. 43 | void setGOPPosition(int64_t inpos); // Set the current GOP poistion by the index of frames. 44 | void setGOPPosition(double inpos); // Set the cuurent GOP position by the time. 45 | private: 46 | string videoPath; // The path of video stream to be decoded. 47 | int width, height; // Width, height of the video. 48 | int widthDst, heightDst; // Target width, height of ExtractFrame(). 49 | enum AVPixelFormat PPixelFormat; // Enum object of the pixel format. 50 | AVFormatContext* PFormatCtx; // Format context of the video. 51 | AVCodecContext* PCodecCtx; // Codec context of the video. 52 | AVStream* PVideoStream; // Video stream. 53 | 54 | int PVideoStreamIDX; // The index of the video stream. 55 | int PVideoFrameCount; // The counter of the decoded frames. 56 | uint8_t* RGBbuffer; // The buffer of the RGB formatted images. 57 | struct SwsContext* PswsCtx; // The context of the scale transformator. 58 | 59 | string _str_codec; // Show the name of the current codec. 60 | double _duration; // Show the time of the video play. 61 | int64_t _predictFrameNum; // The prediction of the total number of frames. 62 | 63 | int64_t currentGOPTSM; // The timestamp where the GOP cursor is pointinng to. 64 | bool EndofGOP; // A flag of reading GOP. This value need to be reset to be false by the reset methods. 65 | int nthread; // The number of threads; 66 | 67 | /* Enable or disable frame reference counting. You are not supposed to support 68 | * both paths in your application but pick the one most appropriate to your 69 | * needs. Look for the use of refcount in this example to see what are the 70 | * differences of API usage between them. */ 71 | int refcount; // Reference count of the video frame. 72 | int _open_codec_context(int& stream_idx, AVCodecContext*& dec_ctx, AVFormatContext* PFormatCtx, enum AVMediaType type); 73 | int _SaveFrame(PyObject* PyFrameList, AVFrame*& frame, AVFrame*& frameRGB, AVPacket*& pkt, bool& got_frame, int64_t minPTS, bool& processed, int cached); 74 | int _SaveFrameForGOP(PyObject* PyFrameList, AVFrame*& frame, AVFrame*& frameRGB, AVPacket*& pkt, bool& got_frame, int& GOPstate, bool& processed, int cached); 75 | PyObject* _SaveFrame_castToPyFrameArray(uint8_t* data[], int fWidth, int fHeight); 76 | PyObject* _SaveFrame_castToPyFrameArrayOld(uint8_t* data[], int fWidth, int fHeight); 77 | int __avcodec_decode_video2(AVCodecContext* avctx, AVFrame* frame, bool& got_frame, AVPacket* pkt); 78 | int64_t __FrameToPts(int64_t seekFrame) const; 79 | int64_t __TimeToPts(double seekTime) const; 80 | }; 81 | 82 | class CMpegEncoder { 83 | public: 84 | CMpegEncoder(void); // Constructor. 85 | ~CMpegEncoder(void); // 3-5 law. Destructor. 86 | CMpegEncoder(const CMpegEncoder& ref); // Copy constructor. 87 | CMpegEncoder& operator=(const CMpegEncoder& ref); // Copy assignment operator. 88 | CMpegEncoder(CMpegEncoder&& ref) noexcept; // Move constructor. 89 | CMpegEncoder& operator=(CMpegEncoder&& ref) noexcept; // Move assignment operator. 90 | friend ostream& operator<<(ostream& out, CMpegEncoder& self_class); // Show the results. 91 | void clear(void); // Clear all configurations and resources. 92 | void resetPath(string inVideoPath); // Reset the path of the output video stream. 93 | void dumpFormat(); // Show the av_format results. 94 | bool FFmpegSetup(); // Configure the encoder, and create the file handle. This method is also equipped in the constructor. 95 | bool FFmpegSetup(string inVideoPath); // Configure the encoder with extra arguments. 96 | void FFmpegClose(); // Close the encoder, and finalize the written of the encoded video. 97 | int EncodeFrame(PyArrayObject* PyFrame); // Encode one frame. 98 | void setParameter(string keyword, void* ptr); // Set arguments. 99 | PyObject* getParameter(string keyword); // Get the current arguments. 100 | PyObject* getParameter(); // Get all key arguments. 101 | private: 102 | string videoPath; // The path of the output video stream. 103 | string codecName; // The name of the codec 104 | int64_t bitRate; // The bit rate of the output video. 105 | int width, height; // The size of the frames in the output video. 106 | int widthSrc, heightSrc; // The size of the input data (frames). 107 | AVRational timeBase, frameRate; // The time base and the frame rate. 108 | int GOPSize, MaxBFrame; // The size of GOPs, and the maximal number of B frames. 109 | OutputStream PStreamContex; // The context of the current video parser. 110 | AVFormatContext* PFormatCtx; // Format context of the video. 111 | AVPacket* Ppacket; // AV Packet used for writing frames. 112 | struct SwsContext* PswsCtx; // The context of the scale transformator. 113 | AVFrame* __frameRGB; // A temp AV frame object. Used for converting the data format. 114 | uint8_t* RGBbuffer; // Data buffer. 115 | bool __have_video, __enable_header; 116 | 117 | int nthread; // The number of threads; 118 | 119 | AVRational _setAVRational(int num, int den); 120 | int64_t __FrameToPts(int64_t seekFrame) const; 121 | int64_t __TimeToPts(double seekTime) const; 122 | bool _LoadFrame_castFromPyFrameArray(AVFrame* frame, PyArrayObject* PyFrame); 123 | void __log_packet(); 124 | int __write_frame(); 125 | const AVCodec* __add_stream(); 126 | AVFrame* __alloc_picture(enum AVPixelFormat pix_fmt, int width, int height); 127 | bool __open_video(const AVCodec* codec, const AVDictionary* opt_arg); 128 | AVFrame* __get_video_frame(PyArrayObject* PyFrame); 129 | int __avcodec_encode_video2(AVCodecContext* enc_ctx, AVPacket* pkt, AVFrame* frame); 130 | int __avcodec_encode_video2_flush(AVCodecContext* enc_ctx, AVPacket* pkt); 131 | }; 132 | 133 | ostream& operator<<(ostream& out, CMpegDecoder& self_class); 134 | ostream& operator<<(ostream& out, CMpegEncoder& self_class); 135 | } 136 | 137 | #endif 138 | -------------------------------------------------------------------------------- /MpegCoder/MpegCoder.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 15.0 23 | {57C5DB39-2AA7-40DD-B7E1-162B3E7F7044} 24 | Win32Proj 25 | MpegCoder 26 | 10.0 27 | 28 | 29 | 30 | DynamicLibrary 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | DynamicLibrary 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | DynamicLibrary 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | DynamicLibrary 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | true 75 | C:\Program Files\Python37\include;../include;$(IncludePath) 76 | C:\Program Files\Python37\libs;../lib;$(LibraryPath) 77 | 78 | 79 | true 80 | C:\Users\cainm\.conda\envs\py310\include;C:\Users\cainm\.conda\envs\py310\lib\site-packages\numpy\core\include;..\include;$(IncludePath) 81 | C:\Users\cainm\.conda\envs\py310\libs;C:\Users\cainm\.conda\envs\py310\lib\site-packages\numpy\core\lib;..\lib;$(LibraryPath) 82 | 83 | 84 | false 85 | C:\Program Files\Python37\include;../include;$(IncludePath) 86 | C:\Program Files\Python37\libs;../lib;$(LibraryPath) 87 | 88 | 89 | false 90 | C:\Users\cainm\.conda\envs\py310\include;C:\Users\cainm\.conda\envs\py310\lib\site-packages\numpy\core\include;..\include;$(IncludePath) 91 | C:\Users\cainm\.conda\envs\py310\libs;C:\Users\cainm\.conda\envs\py310\lib\site-packages\numpy\core\lib;..\lib;$(LibraryPath) 92 | 93 | 94 | 95 | Use 96 | Level3 97 | Disabled 98 | WIN32;_DEBUG;MpegCoder_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 99 | true 100 | 101 | 102 | Windows 103 | true 104 | avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;postproc.lib;swresample.lib;swscale.lib;%(AdditionalDependencies) 105 | 106 | 107 | 108 | 109 | Use 110 | Level3 111 | Disabled 112 | _DEBUG;MpegCoder_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 113 | true 114 | true 115 | 116 | 117 | Windows 118 | true 119 | python310.lib;python3.lib;npymath.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;%(AdditionalDependencies) 120 | 121 | 122 | echo F | xcopy /y /i "$(OutDir)$(TargetName)$(TargetExt)" "$(OutDir)mpegCoder.pyd" 123 | 124 | 125 | 126 | 127 | Use 128 | Level3 129 | MaxSpeed 130 | true 131 | true 132 | WIN32;NDEBUG;MpegCoder_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 133 | true 134 | 135 | 136 | Windows 137 | true 138 | true 139 | true 140 | avcodec.lib;avdevice.lib;avfilter.lib;avformat.lib;avutil.lib;postproc.lib;swresample.lib;swscale.lib;%(AdditionalDependencies) 141 | 142 | 143 | 144 | 145 | Use 146 | Level3 147 | MaxSpeed 148 | true 149 | true 150 | NDEBUG;MpegCoder_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 151 | true 152 | true 153 | 154 | 155 | Windows 156 | true 157 | true 158 | true 159 | python310.lib;python3.lib;npymath.lib;avcodec.lib;avformat.lib;avutil.lib;swresample.lib;swscale.lib;%(AdditionalDependencies) 160 | 161 | 162 | echo F | xcopy /y /i "$(OutDir)$(TargetName)$(TargetExt)" "$(OutDir)mpegCoder.pyd" 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | Create 181 | Create 182 | Create 183 | Create 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | -------------------------------------------------------------------------------- /MpegCoder/MpegStreamer.h: -------------------------------------------------------------------------------- 1 | // 下列 ifdef 块是创建使从 DLL 导出更简单的 2 | // 宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 MPEGCODER_EXPORT 3 | // 符号编译的。在使用此 DLL 的 4 | // 任何其他项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将 5 | // MPEGCODER_API 函数视为自 DLL 导入,而此 DLL 则将用此宏定义的 6 | // 符号视为是被导出的。 7 | #ifndef MPEGSTREAMER_H_INCLUDED 8 | #define MPEGSTREAMER_H_INCLUDED 9 | 10 | #include "MpegBase.h" 11 | 12 | // Exported from MpegCoder.dll 13 | namespace cmpc { 14 | 15 | extern int8_t __dumpControl; 16 | class CMpegDecoder; 17 | class CMpegEncoder; 18 | 19 | class BufferList { // A buffer holder of several frames 20 | public: 21 | BufferList(void); 22 | ~BufferList(void); 23 | BufferList(const BufferList& ref); 24 | BufferList& operator=(const BufferList& ref); 25 | BufferList(BufferList&& ref) noexcept; 26 | BufferList& operator=(BufferList&& ref) noexcept; 27 | void clear(void); 28 | const int64_t size() const; 29 | void set(int64_t set_size, int width, int height, int widthDst = 0, int heightDst = 0); 30 | void set_timer(AVRational targetFrameRate, AVRational timeBase); 31 | bool reset_memory(); 32 | void freeze_write(int64_t read_size); 33 | bool write(SwsContext* PswsCtx, AVFrame* frame); 34 | PyObject* read(); 35 | private: 36 | int64_t _Buffer_pos; // Writring cursor of the source buffer,pointing to the index of the currently written frame. 37 | int64_t _Buffer_rpos; // Reading cursor of the source buffer,pointing to the index of the currently read frame. 38 | int64_t _Buffer_size; // Size of the source buffer, it should be determined by the numeber of required frames. 39 | int64_t __Read_size; // A temporary variable used for showing the size of the data to be read. 40 | int64_t next_pts; 41 | int64_t interval_pts; 42 | int dst_width, dst_height; 43 | int src_width, src_height; 44 | int _Buffer_capacity; 45 | AVFrame* frameRGB; 46 | uint8_t** _Buffer_List; // Source buffer, the size of this buffer is determined by the number of required frames. 47 | }; 48 | 49 | class CMpegClient { 50 | public: 51 | CMpegClient(void); // Constructor. 52 | ~CMpegClient(void); // 3-5 law. Destructor. 53 | CMpegClient(const CMpegClient& ref) = delete; // Delete the copy constructor. 54 | CMpegClient& operator=(const CMpegClient& ref) = delete; // Delete the copy assignment operator. 55 | CMpegClient(CMpegClient&& ref) noexcept; // Move constructor. 56 | CMpegClient& operator=(CMpegClient&& ref) noexcept; // Move assignment operator. 57 | friend class CMpegEncoder; // Let the encoder be able to access the member of this class. 58 | friend class CMpegServer; // Let the server be able to access the member of this class. 59 | friend ostream& operator<<(ostream& out, CMpegClient& self_class); // Show the results. 60 | void clear(void); // Clear all configurations and resources. 61 | void meta_protected_clear(void); // Clear the resources, but the configurations are remained. 62 | void dumpFormat(); // Show the av_format results. 63 | void setParameter(string keyword, void* ptr); // Set arguments. 64 | PyObject* getParameter(string keyword); // Get the current arguments. 65 | PyObject* getParameter(); // Get all key arguments. 66 | void resetPath(string inVideoPath); // Reset the path (URL) of the online video stream. 67 | bool FFmpegSetup(); // Configure the decoder, and extract the basic meta-data. This method is also equipped in the constructor. 68 | bool FFmpegSetup(string inVideoPath); // Configure the decoder with extra arguments. 69 | bool start(); // Start the listening to the online stream. 70 | void terminate(); // Terminate the listener. 71 | PyObject* ExtractFrame(int64_t readsize); // Extract frames with the given number. 72 | PyObject* ExtractFrame(); // Extract frames. The number is configured in the class properties. 73 | private: 74 | string videoPath; // The path (URL) of the online video stream. 75 | int width, height; // Width, height of the video. 76 | int widthDst, heightDst; // Target width, height of ExtractFrame(). 77 | enum AVPixelFormat PPixelFormat; // Enum object of the pixel format. 78 | AVFormatContext* PFormatCtx; // Format context of the video. 79 | AVCodecContext* PCodecCtx; // Codec context of the video. 80 | AVStream* PVideoStream; // Video stream. 81 | 82 | AVFrame* frame; 83 | 84 | int PVideoStreamIDX; // The index of the video stream. 85 | int PVideoFrameCount; // The counter of the decoded frames. 86 | BufferList buffer; // The buffer of the RGB formatted images. 87 | struct SwsContext* PswsCtx; // The context of the scale transformator. 88 | int64_t cache_size, read_size; 89 | AVRational frameRate; 90 | 91 | std::thread read_handle; // The thread of the circular frame reader. 92 | std::mutex read_check; // Lock for reading the status. 93 | std::mutex info_lock; // Lock for reading the info. 94 | bool reading; 95 | 96 | string _str_codec; // The name of the current codec. 97 | double _duration; // The duration of the current video. 98 | int64_t _predictFrameNum; // The prediction of the total number of frames. 99 | int nthread; // The number of threads; 100 | 101 | /* Enable or disable frame reference counting. You are not supposed to support 102 | * both paths in your application but pick the one most appropriate to your 103 | * needs. Look for the use of refcount in this example to see what are the 104 | * differences of API usage between them. */ 105 | int refcount; // Reference count of the video frame. 106 | bool __setup_check() const; 107 | int _open_codec_context(int& stream_idx, AVCodecContext*& dec_ctx, AVFormatContext* PFormatCtx, enum AVMediaType type); 108 | void __client_holder(); 109 | AVRational _setAVRational(int num, int den); 110 | int __save_frame(AVFrame*& frame, AVPacket*& pkt, bool& got_frame, int cached); 111 | int __avcodec_decode_video2(AVCodecContext* avctx, AVFrame* frame, bool& got_frame, AVPacket* pkt); 112 | }; 113 | 114 | class CMpegServer { 115 | public: 116 | CMpegServer(void); // Constructor. 117 | ~CMpegServer(void); // 3-5 law. Destructor. 118 | CMpegServer(const CMpegServer& ref); // Delete the copy constructor. 119 | CMpegServer& operator=(const CMpegServer& ref); // Delete the copy assignment operator. 120 | CMpegServer(CMpegServer&& ref) noexcept; // Move constructor. 121 | CMpegServer& operator=(CMpegServer&& ref) noexcept; // Move assignment operator. 122 | //friend class CMpegEncoder; // Let the server be able to access the member of this class. 123 | friend ostream& operator<<(ostream& out, CMpegServer& self_class); // Show the results. 124 | void clear(void); // Clear all configurations and resources. 125 | void meta_protected_clear(void); // Clear the resources, but the configurations are remained. 126 | void resetPath(string inVideoPath); // Reset the path of the output video stream. 127 | void dumpFormat(); // Show the av_format results. 128 | bool FFmpegSetup(); // Configure the encoder, and create the file handle. This method is also equipped in the constructor. 129 | bool FFmpegSetup(string inVideoPath); // Configure the encoder with extra arguments. 130 | void FFmpegClose(); // Close the encoder, and finalize the written of the encoded video. 131 | void setParameter(string keyword, void* ptr); // Set arguments. 132 | PyObject* getParameter(string keyword); // Get the current arguments. 133 | PyObject* getParameter(); // Get all key arguments. 134 | int ServeFrameBlock(PyArrayObject* PyFrame); // Encode the frame into the output stream (block mode). 135 | int ServeFrame(PyArrayObject* PyFrame); // Encode the frame into the output stream. 136 | private: 137 | string videoPath; // The path of the output video stream. 138 | string __formatName; // The format name of the stream. Could be "rtsp" or "rtmp". This value is detected from the videoPath. 139 | string codecName; // The name of the codec 140 | int64_t bitRate; // The bit rate of the output video. 141 | int64_t __pts_ahead; // The ahead pts. 142 | int64_t __start_time; // The start time stamp. This value is used for controlling the writing of the frames. 143 | int64_t __cur_time; // The current time stamp. This value is restricted by __pts_ahead. 144 | int width, height; // The size of the frames in the output video. 145 | int widthSrc, heightSrc; // The size of the input data (frames). 146 | AVRational timeBase, frameRate; // The time base and the frame rate. 147 | AVRational time_base_q; // The time base used for calculating the absolute time. 148 | int GOPSize, MaxBFrame; // The size of GOPs, and the maximal number of B frames. 149 | OutputStream PStreamContex; // The context of the current video parser. 150 | AVFormatContext* PFormatCtx; // Format context of the video. 151 | AVPacket* Ppacket; // AV Packet used for writing frames. 152 | struct SwsContext* PswsCtx; // The context of the scale transformator. 153 | AVFrame* __frameRGB; // A temp AV frame object. Used for converting the data format. 154 | uint8_t* RGBbuffer; // Data buffer. 155 | bool __have_video, __enable_header; 156 | 157 | int nthread; // The number of threads; 158 | 159 | AVRational _setAVRational(int num, int den); 160 | int64_t __FrameToPts(int64_t seekFrame) const; 161 | int64_t __TimeToPts(double seekTime) const; 162 | bool __setup_check() const; 163 | bool _LoadFrame_castFromPyFrameArray(AVFrame* frame, PyArrayObject* PyFrame); 164 | void __log_packet(); 165 | int __write_frame(); 166 | const AVCodec* __add_stream(); 167 | AVFrame* __alloc_picture(enum AVPixelFormat pix_fmt, int width, int height); 168 | bool __open_video(const AVCodec* codec, const AVDictionary* opt_arg); 169 | AVFrame* __get_video_frame(PyArrayObject* PyFrame); 170 | int __avcodec_encode_video2(AVCodecContext* enc_ctx, AVPacket* pkt, AVFrame* frame); 171 | int __avcodec_encode_video2_flush(AVCodecContext* enc_ctx, AVPacket* pkt); 172 | }; 173 | 174 | ostream& operator<<(ostream& out, CMpegClient& self_class); 175 | ostream& operator<<(ostream& out, CMpegServer& self_class); 176 | } 177 | 178 | #endif 179 | -------------------------------------------------------------------------------- /webtools.py: -------------------------------------------------------------------------------- 1 | #!python 2 | # -*- coding: UTF-8 -*- 3 | ''' 4 | ################################################################ 5 | # WebTools 6 | # @ FFMpeg encoder and decoder. 7 | # Yuchen Jin @ cainmagi@gmail.com 8 | # Requirements: (Pay attention to version) 9 | # python 3.3+ 10 | # urllib3 1.26.2+ 11 | # Tools used for checking and downloading datasets. 12 | # Inspired by: 13 | # https://gist.github.com/devhero/8ae2229d9ea1a59003ced4587c9cb236 14 | # and https://gist.github.com/maxim/6e15aa45ba010ab030c4 15 | # This tool is picked from the other project, MDNC, see: 16 | # https://github.com/cainmagi/MDNC 17 | ################################################################ 18 | ''' 19 | 20 | import os 21 | import json 22 | import tarfile 23 | import urllib3 24 | 25 | try: 26 | from tqdm import tqdm 27 | wrapattr=tqdm.wrapattr 28 | except ImportError: 29 | import contextlib 30 | 31 | @contextlib.contextmanager 32 | def wrapattr(req, mode=None, total=0, desc=None): 33 | yield req 34 | 35 | __all__ = [ 36 | 'get_token', 37 | 'download_tarball_link', 'download_tarball_public', 'download_tarball_private', 'download_tarball' 38 | ] 39 | 40 | 41 | class _SafePoolManager(urllib3.PoolManager): 42 | '''A wrapped urllib3.PoolManager with context supported. 43 | This is a private class. Should not be used by users. 44 | ''' 45 | def __enter__(self): 46 | return self 47 | 48 | def __exit__(self, exc_type, exc_value, exc_traceback): 49 | self.clear() 50 | 51 | 52 | def get_token(token='', silent=False): 53 | '''Automatically get the token, if the token is missing. 54 | Arguments: 55 | token: the given OAuth token. Only when this argument is unset, 56 | the program will try to find a token from env. 57 | silent: a flag. If set true, this tool would not ask for a token 58 | when the token could not be found. 59 | ''' 60 | if not token: 61 | token = os.environ.get('GITTOKEN', None) 62 | if token is None: 63 | token = os.environ.get('GITHUB_API_TOKEN', None) 64 | if isinstance(token, str) and token != '': 65 | token = token.split(':')[-1] 66 | else: 67 | if not silent: 68 | print('data.webtools: A Github OAuth token is required for downloading the data in private repository. Please provide your OAuth token:') 69 | token = input('Token:') 70 | if not token: 71 | print('data.webtools: Provide blank token. Try to download the tarball without token.') 72 | print('data.webtools: Tips: specify the environment variable $GITTOKEN or $GITHUB_API_TOKEN could help you skip this step.') 73 | else: 74 | return '' 75 | return token 76 | 77 | 78 | def __get_tarball_mode(name, mode='auto'): 79 | '''Detect the tarball compression mode by file name. 80 | Arguments: 81 | name: the file name with a file name extension. 82 | mode: the mode name, should be '', 'gz, ''bz2', or 'xz'. If specified, 83 | the compression mode would not be detected by file name. 84 | ''' 85 | name = os.path.split(name)[-1] 86 | pos = name.find('?') 87 | if pos > 0: 88 | name = name[:name.find('?')] # Remove the HTML args. 89 | if mode == 'auto': 90 | if name.endswith('tar'): 91 | mode = '' 92 | elif name.endswith('tar.gz') or name.endswith('tar.gzip'): 93 | mode = 'gz' 94 | elif name.endswith('tar.bz2') or name.endswith('tar.bzip2'): 95 | mode = 'bz2' 96 | elif name.endswith('tar.xz'): 97 | mode = 'xz' 98 | if mode not in ('', 'gz', 'bz2', 'xz'): 99 | raise TypeError('data.webtools: The file name to be downloaded should end with supported format. Now we supports: tar, tar.gz/tar.gzip, tar.bz2/tar.bzip2, tar.xz.') 100 | return mode 101 | 102 | 103 | def download_tarball_link(link, path='.', mode='auto', verbose=False): 104 | '''Download an online tarball and extract it automatically. 105 | The tarball is directed by the link. This tool would not work on 106 | private github repository. 107 | The tarball would be sent to pipeline and not get stored. 108 | Now supports gz, bz2 or xz format. 109 | Arguments: 110 | link: the web link. 111 | path: the extracted data root path. Should be a folder path. 112 | mode: the mode of extraction. Could be 'gz', 'bz2', 'xz' or 113 | 'auto'. 114 | verbose: a flag, whether to show the downloaded size during 115 | the web request. 116 | ''' 117 | mode = __get_tarball_mode(name=link, mode=mode) 118 | os.makedirs(path, exist_ok=True) 119 | # Initialize urllib3 120 | with _SafePoolManager(retries=urllib3.util.Retry(connect=5, read=2, redirect=5), 121 | timeout=urllib3.util.Timeout(connect=5.0)) as http: 122 | # Get the data. 123 | git_header = { 124 | 'User-Agent': 'cainmagi/webtools' 125 | } 126 | req = http.request(url=link, headers=git_header, method='GET', preload_content=False) 127 | if req.status < 400: 128 | if verbose: 129 | file_name = os.path.split(link)[-1] 130 | with wrapattr(req, 'read', total=0, desc='Get {0}'.format(file_name)) as req: 131 | with tarfile.open(fileobj=req, mode='r|{0}'.format(mode)) as tar: 132 | tar.extractall(path) 133 | else: 134 | with tarfile.open(fileobj=req, mode='r|{0}'.format(mode)) as tar: 135 | tar.extractall(path) 136 | else: 137 | raise FileNotFoundError('data.webtools: Fail to get access to the tarball. Maybe the repo or the tag is not correct, or the repo is private, or the network is not available. The error message is: {0}'.format(req.read().decode('utf-8'))) 138 | req.release_conn() 139 | 140 | 141 | def __download_tarball_from_repo(user, repo, tag, asset, path='.', mode='auto', token=None, verbose=False): 142 | '''Download an online tarball and extract it automatically. 143 | A base tool. Should not used by users. Please use 144 | download_tarball, or 145 | download_tarball_public, or 146 | download_tarball_private 147 | for instead. 148 | ''' 149 | # Initialize the urllib3 150 | with _SafePoolManager(retries=urllib3.util.Retry(connect=5, read=2, redirect=5), 151 | timeout=urllib3.util.Timeout(connect=5.0)) as http: 152 | # Get the release info. 153 | link_full = 'https://api.github.com/repos/{user}/{repo}/releases/tags/{tag}'.format(user=user, repo=repo, tag=tag) 154 | git_header = { 155 | 'Accept': 'application/vnd.github.v3+json', 156 | 'User-Agent': 'cainmagi/webtools' 157 | } 158 | if token: 159 | git_header['Authorization'] = 'token {token}'.format(token=token) 160 | req = http.request(url=link_full, headers=git_header, method='GET', preload_content=False) 161 | if req.status < 400: 162 | info = json.loads(req.read().decode()) 163 | link_assets = info['assets_url'] 164 | else: 165 | raise FileNotFoundError('data.webtools: Fail to get access to the release. Maybe the repo or the tag is not correct, or the authentication fails, or the network is not available. The error message is: {0}'.format(req.read().decode('utf-8'))) 166 | req.release_conn() 167 | # Get the assets info. 168 | req = http.request(url=link_assets, headers=git_header, method='GET', preload_content=False) 169 | if req.status < 400: 170 | info = json.loads(req.read().decode()) 171 | asset_info = next(filter(lambda aitem: aitem['name'] == asset, info), None) 172 | if asset_info is None: 173 | raise FileNotFoundError('data.webtools: Fail to locate the asset "{asset}" in the given release.'.format(asset=asset)) 174 | link_asset = asset_info['url'] 175 | else: 176 | raise FileNotFoundError('data.webtools: Fail to get access to the release. Maybe the asset address is not correct. The error message is: {0}'.format(req.read().decode('utf-8'))) 177 | req.release_conn() 178 | # Download the data. 179 | git_header = { 180 | 'Accept': 'application/octet-stream', 181 | 'User-Agent': 'cainmagi/webtools' 182 | } 183 | if token: 184 | git_header['Authorization'] = 'token {token}'.format(token=token) 185 | # req = http.request(method='GET', url=link_asset, headers=git_header) 186 | req = http.request(url=link_asset, headers=git_header, method='GET', preload_content=False) 187 | if req.status < 400: 188 | if verbose: 189 | with wrapattr(req, 'read', total=0, desc='Get {0}'.format(asset)) as req: 190 | with tarfile.open(fileobj=req, mode='r|{0}'.format(mode)) as tar: 191 | tar.extractall(path) 192 | else: 193 | with tarfile.open(fileobj=req, mode='r|{0}'.format(mode)) as tar: 194 | tar.extractall(path) 195 | else: 196 | raise FileNotFoundError('data.webtools: Fail to get access to the asset. The error message is: {0}'.format(req.read().decode('utf-8'))) 197 | req.release_conn() 198 | 199 | 200 | def download_tarball_public(user, repo, tag, asset, path='.', mode='auto', verbose=False): 201 | '''Download an online tarball and extract it automatically 202 | (public). 203 | This tool only supports public github repositories. This method 204 | could be replaced by download_tarball_link(), but we do not 205 | recommend to do that. 206 | The tarball would be sent to pipeline and not get stored. 207 | Now supports gz or xz format. 208 | Arguments: 209 | user: the github user name. 210 | repo: the github repository name. 211 | tag: the github release tag. 212 | asset: the github asset (tarball) to be downloaded. 213 | path: the extracted data root path. Should be a folder path. 214 | mode: the mode of extraction. Could be 'gz', 'bz2', 'xz' or 215 | 'auto'. 216 | verbose: a flag, whether to show the downloaded size during 217 | the web request. 218 | ''' 219 | mode = __get_tarball_mode(name=asset, mode=mode) 220 | os.makedirs(path, exist_ok=True) 221 | __download_tarball_from_repo(user=user, repo=repo, tag=tag, asset=asset, 222 | path=path, mode=mode, token=None, verbose=verbose) 223 | 224 | 225 | def download_tarball_private(user, repo, tag, asset, path='.', mode='auto', token=None, verbose=False): 226 | '''Download an online tarball and extract it automatically 227 | (private). 228 | This tool should only be used for downloading assets from 229 | private repositories. Although it could be also used for 230 | public repositories, we do not recommend to use it in those 231 | cases, because it would still require a token. 232 | The tarball would be sent to pipeline and not get stored. 233 | Now supports gz or xz format. 234 | Arguments: 235 | user: the github user name. 236 | repo: the github repository name. 237 | tag: the github release tag. 238 | asset: the github asset (tarball) to be downloaded. 239 | path: the extracted data root path. Should be a folder path. 240 | mode: the mode of extraction. Could be 'gz', 'bz2', 'xz' or 241 | 'auto'. 242 | token: the token required for downloading the private asset. 243 | verbose: a flag, whether to show the downloaded size during 244 | the web request. 245 | ''' 246 | mode = __get_tarball_mode(name=asset, mode=mode) 247 | os.makedirs(path, exist_ok=True) 248 | token = get_token(token) 249 | __download_tarball_from_repo(user=user, repo=repo, tag=tag, asset=asset, 250 | path=path, mode=mode, token=token, verbose=verbose) 251 | 252 | 253 | def download_tarball(user, repo, tag, asset, path='.', mode='auto', token=None, verbose=False): 254 | '''Download an online tarball and extract it automatically. 255 | This tool is used for downloading the assets from github 256 | repositories. It would try to detect the data info in public 257 | mode, and switch to private downloading mode when the Github 258 | repository could not be accessed. 259 | The tarball would be sent to pipeline and not get stored. 260 | Now supports gz or xz format. 261 | Arguments: 262 | user: the github user name. 263 | repo: the github repository name. 264 | tag: the github release tag. 265 | asset: the github asset (tarball) to be downloaded. 266 | path: the extracted data root path. Should be a folder path. 267 | mode: the mode of extraction. Could be 'gz', 'bz2', 'xz' or 268 | 'auto'. 269 | token: the token required for downloading the private asset, 270 | when downloading public asses, this value would not 271 | be used. 272 | verbose: a flag, whether to show the downloaded size during 273 | the web request. 274 | ''' 275 | mode = __get_tarball_mode(name=asset, mode=mode) 276 | os.makedirs(path, exist_ok=True) 277 | # Detect the repository infomation first. 278 | is_public_mode = True 279 | with _SafePoolManager(retries=urllib3.util.Retry(connect=5, read=2, redirect=5), 280 | timeout=urllib3.util.Timeout(connect=5.0)) as http: 281 | link_full = 'https://api.github.com/repos/{user}/{repo}/releases/tags/{tag}'.format(user=user, repo=repo, tag=tag) 282 | git_header = { 283 | 'Accept': 'application/vnd.github.v3+json', 284 | 'User-Agent': 'cainmagi/webtools' 285 | } 286 | req = http.request(url=link_full, headers=git_header, method='GET', preload_content=False) 287 | if req.status < 400: 288 | is_public_mode = is_public_mode 289 | else: 290 | is_public_mode = False 291 | req.release_conn() 292 | if is_public_mode: 293 | __download_tarball_from_repo(user=user, repo=repo, tag=tag, asset=asset, 294 | path=path, mode=mode, token=None, verbose=verbose) 295 | else: 296 | token = get_token(token) 297 | __download_tarball_from_repo(user=user, repo=repo, tag=tag, asset=asset, 298 | path=path, mode=mode, token=token, verbose=verbose) 299 | 300 | 301 | if __name__ == '__main__': 302 | 303 | # token = get_token(token='') 304 | print('Get ffmpeg dependencies...') 305 | download_tarball('cainmagi', 'FFmpeg-Encoder-Decoder-for-Python', 'deps-3.2.0', 'dep-win-ffmpeg_5_0.tar.xz', path='.', mode='auto', verbose=True, token='') 306 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MpegCoder/MpegPyd.h: -------------------------------------------------------------------------------- 1 | #ifndef MPEGPYD_H_INCLUDED 2 | #define MPEGPYD_H_INCLUDED 3 | 4 | #define PY_ARRAY_UNIQUE_SYMBOL MPEGARRAY_API 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "MpegCoder.h" 15 | #include "MpegStreamer.h" 16 | using std::string; 17 | using std::ostringstream; 18 | 19 | PyObject *str2PyStr(string Str) { // Convert the output string to the widechar unicode string. 20 | int wlen = MultiByteToWideChar(CP_ACP, NULL, Str.c_str(), int(Str.size()), NULL, 0); 21 | wchar_t* wszString = new wchar_t[static_cast(wlen) + 1]; 22 | MultiByteToWideChar(CP_ACP, NULL, Str.c_str(), int(Str.size()), wszString, wlen); 23 | wszString[wlen] = 0; 24 | PyObject* res = PyUnicode_FromWideChar(wszString, wlen); 25 | delete[] wszString; 26 | return res; 27 | } 28 | 29 | bool PyStr2str(PyObject* py_str, string& s_str) { // Convert a python str to std::string. 30 | if (!py_str) { 31 | return false; 32 | } 33 | if (PyUnicode_Check(py_str)) { 34 | auto py_bytes = PyUnicode_EncodeFSDefault(py_str); 35 | if (!py_bytes) { 36 | PyErr_SetString(PyExc_TypeError, "Error.PyStr2str: fail to encode the unicode str.'"); 37 | return false; 38 | } 39 | auto c_str = PyBytes_AsString(py_bytes); 40 | if (!c_str) { 41 | PyErr_SetString(PyExc_TypeError, "Error.PyStr2str: fail to parse data from the encoded str.'"); 42 | return false; 43 | } 44 | s_str.assign(c_str); 45 | Py_DECREF(py_bytes); 46 | } 47 | else { 48 | if (PyBytes_Check(py_str)) { 49 | auto c_str = PyBytes_AsString(py_str); 50 | if (!c_str) { 51 | PyErr_SetString(PyExc_TypeError, "Error.PyStr2str: fail to parse data from the bytes object.'"); 52 | return false; 53 | } 54 | s_str.assign(c_str); 55 | } 56 | else { 57 | PyErr_SetString(PyExc_TypeError, "Error.PyStr2str: fail to convert the object to string, maybe the object is not str or bytes.'"); 58 | return false; 59 | } 60 | } 61 | return true; 62 | } 63 | 64 | /***************************************************************************** 65 | * C style definition of Python classes. 66 | * Each class would ref the C implemented class directly. 67 | * No extra python data member is added to these classes, 68 | * because the data members have been already packed as private members of the 69 | * C classes. 70 | *****************************************************************************/ 71 | typedef struct _C_MpegDecoder 72 | { 73 | PyObject_HEAD // == PyObject ob_base; Define the PyObject header. 74 | cmpc::CMpegDecoder* _in_Handle; // Define the implementation of the C Object. 75 | } C_MpegDecoder; 76 | 77 | typedef struct _C_MpegEncoder 78 | { 79 | PyObject_HEAD // == PyObject ob_base; Define the PyObject header. 80 | cmpc::CMpegEncoder* _in_Handle; // Define the implementation of the C Object. 81 | } C_MpegEncoder; 82 | 83 | typedef struct _C_MpegClient 84 | { 85 | PyObject_HEAD // == PyObject ob_base; Define the PyObject header. 86 | cmpc::CMpegClient* _in_Handle; // Define the implementation of the C Object. 87 | } C_MpegClient; 88 | 89 | typedef struct _C_MpegServer 90 | { 91 | PyObject_HEAD // == PyObject ob_base; Define the PyObject header. 92 | cmpc::CMpegServer* _in_Handle; // Define the implementation of the C Object. 93 | } C_MpegServer; 94 | 95 | static PyMemberDef C_MPDC_DataMembers[] = // Register the members of the python class. 96 | { // Do not register any data, because all data of this class is private. 97 | //{"m_dEnglish", T_FLOAT, offsetof(CScore, m_dEnglish), 0, "The English score of instance."}, 98 | { "hAddress", T_ULONGLONG, offsetof(C_MpegDecoder, _in_Handle), READONLY, "The address of the handle in memory." }, 99 | { nullptr, 0, 0, 0, nullptr } 100 | }; 101 | 102 | static PyMemberDef C_MPEC_DataMembers[] = // Register the members of the python class. 103 | { // Do not register any data, because all data of this class is private. 104 | //{"m_dEnglish", T_FLOAT, offsetof(CScore, m_dEnglish), 0, "The English score of instance."}, 105 | { "hAddress", T_ULONGLONG, offsetof(C_MpegEncoder, _in_Handle), READONLY, "The address of the handle in memory." }, 106 | { nullptr, 0, 0, 0, nullptr } 107 | }; 108 | 109 | static PyMemberDef C_MPCT_DataMembers[] = // Register the members of the python class. 110 | { // Do not register any data, because all data of this class is private. 111 | //{"m_dEnglish", T_FLOAT, offsetof(CScore, m_dEnglish), 0, "The English score of instance."}, 112 | { "hAddress", T_ULONGLONG, offsetof(C_MpegClient, _in_Handle), READONLY, "The address of the handle in memory." }, 113 | { nullptr, 0, 0, 0, nullptr } 114 | }; 115 | 116 | static PyMemberDef C_MPSV_DataMembers[] = // Register the members of the python class. 117 | { // Do not register any data, because all data of this class is private. 118 | //{"m_dEnglish", T_FLOAT, offsetof(CScore, m_dEnglish), 0, "The English score of instance."}, 119 | { "hAddress", T_ULONGLONG, offsetof(C_MpegServer, _in_Handle), READONLY, "The address of the handle in memory." }, 120 | { nullptr, 0, 0, 0, nullptr } 121 | }; 122 | 123 | /***************************************************************************** 124 | * Delearaction of all methods and functions. 125 | * Prepare the function objects for the registeration of the classes and 126 | * functions. 127 | *****************************************************************************/ 128 | /*static void Example(ClassName* Self, PyObject* pArgs); 129 | PyMODINIT_FUNC PyFunc_Example(void);*/ 130 | 131 | static PyObject* C_MPC_Global(PyObject* Self, PyObject* args, PyObject* kwargs) { 132 | char dumpLevel = -1; 133 | cmpc::CharList kwlist_str({ "dumpLevel" }); 134 | auto kwlist_ptr = kwlist_str.c_str(); 135 | auto kwlist = (char**)(kwlist_ptr.get()); 136 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|B", kwlist, &dumpLevel)) { 137 | PyErr_SetString(PyExc_TypeError, "Error.GlobalSettings: invalid keyword'"); 138 | return nullptr; 139 | } 140 | if (dumpLevel != -1) { 141 | cmpc::__dumpControl = static_cast(dumpLevel); 142 | switch (dumpLevel) { 143 | case 0: 144 | cmpc::av_log_set_level(AV_LOG_ERROR); 145 | break; 146 | case 1: 147 | cmpc::av_log_set_level(AV_LOG_INFO); 148 | break; 149 | case 2: 150 | default: 151 | cmpc::av_log_set_level(AV_LOG_DEBUG); 152 | break; 153 | } 154 | } 155 | Py_RETURN_NONE; 156 | } 157 | 158 | static PyObject* C_MPC_Help(PyObject* Self) { 159 | cout << R"(================================================================================ 160 | __ _ _ _ _ ,___ 161 | ( / / / o ( / ) ) / / / 162 | (__/ , , _, /_ _ _ _' ( / / / ,_ _ _, / __ __/ _ _ 163 | _/_(_/_(__/ /_(/_/ / /_/_)_ / / (__/|_)_(/_(_)_(___/(_)(_/_(/_/ (_ 164 | // /| /| 165 | (/ (/ (/ 166 | ================================================================================ 167 | Yuchen's Mpeg Coder - Readme 168 | This is a mpegcoder adapted from FFmpeg & Python-c-api.Using it you could 169 | get access to processing video easily. Just use it as a common module in 170 | python like this. 171 | >>> import mpegCoder 172 | Noted that this API need you to install numpy. 173 | An example of decoding a video in an arbitrary format: 174 | >>> d = mpegCoder.MpegDecoder() 175 | >>> d.FFmpegSetup(b'inputVideo.mp4') 176 | >>> p = d.ExtractGOP(10) # Get a gop of current video by setting the 177 | start position of 10th frame. 178 | >>> p = d.ExtractGOP() # Get a gop of current video, using the current 179 | position after the last ExtractGOP. 180 | >>> d.ExtractFrame(100, 100) # Extract 100 frames from the begining of 181 | 100th frame. 182 | An example of transfer the coding of a video with an assigned codec: 183 | >>> d = mpegCoder.MpegDecoder() 184 | >>> d.FFmpegSetup(b'i.avi') 185 | >>> e = mpegCoder.MpegEncoder() 186 | >>> e.setParameter(decoder=d, codecName=b'libx264', videoPath=b'o.mp4') 187 | # inherit most of parameters from the decoder. 188 | >>> opened = e.FFmpegSetup() # Load the encoder. 189 | >>> if opened: # If encoder is not loaded successfully, do not continue. 190 | ... p = True 191 | ... while p: 192 | ... p = d.ExtractGOP() # Extract current GOP. 193 | ... if p is not None: 194 | ... for i in p: # Select every frame. 195 | ... e.EncodeFrame(i) # Encode current frame. 196 | ... e.FFmpegClose() # End encoding, and flush all frames in cache. 197 | >>> d.clear() # Close the input video. 198 | An example of demuxing the video streamer from a server: 199 | >>> d = mpegCoder.MpegClient() # create the handle 200 | >>> d.setParameter(dstFrameRate=(5,1), readSize=5, cacheSize=12) 201 | # normalize the frame rate to 5 FPS, and use a cache which size is 202 | # 12 frames. Read 5 frames each time. 203 | >>> success = d.FFmpegSetup(b'rtsp://localhost:8554/video') 204 | >>> if not success: # exit if fail to connect with the server 205 | ... exit() 206 | >>> d.start() # start the sub-thread for demuxing the stream. 207 | >>> for i in range(10): # processing loop 208 | ... time.sleep(5) 209 | ... p = d.ExtractFrame() # every 5 seconds, read 5 frames (1 sec.) 210 | ... # do some processing 211 | >>> d.terminate() # shut down the current thread. You could call start() 212 | # and let it restart. 213 | >>> d.clear() # Disconnect with the stream. 214 | For more instructions, you could tap help(mpegCoder). 215 | ================================================================================ 216 | V3.2.0 update report: 217 | 1. Upgrade FFMpeg to 5.0. 218 | 2. Fix the const assignment bug caused by the codec configuration method. 219 | V3.1.0 update report: 220 | 1. Support str() type for all string arguments. 221 | 2. Support http, ftp, sftp streams for MpegServer. 222 | 3. Support "nthread" option for MpegDecoder, MpegEncoder, MpegClient and 223 | MpegServer. 224 | 4. Fix a bug caused by the constructor MpegServer(). 225 | 5. Clean up all gcc warnings of the source codes. 226 | 6. Fix typos in docstrings. 227 | V3.0.0 update report: 228 | 1. Fix a severe memory leaking bugs when using AVPacket. 229 | 2. Fix a bug caused by using MpegClient.terminate() when a video is closed 230 | by the server. 231 | 3. Support the MpegServer. This class is used for serving the online video 232 | streams. 233 | 4. Refactor the implementation of the loggings. 234 | 5. Add getParameter() and setParameter(configDict) APIs to MpegEncoder and 235 | MpegServer. 236 | 6. Move FFMpeg depedencies and the OutputStream class to the cmpc space. 237 | 7. Fix dependency issues and cpp standard issues. 238 | 8. Upgrade to `FFMpeg 4.4` Version. 239 | 9. Add a quick script for fetching the `FFMpeg` dependencies. 240 | V2.05 update report: 241 | 1. Fix a severe bug that causes the memory leak when using MpegClient. 242 | This bug also exists in MpegDecoder, but it seems that the bug would not cause 243 | memory leak in that case. (Although we have also fixed it now.) 244 | 2. Upgrade to FFMpeg 4.0 Version. 245 | V2.01 update report: 246 | Fix a bug that occurs when the first received frame may has a PTS larger than 247 | zero. 248 | V2.0 update report: 249 | 1. Revise the bug of the encoder which may cause the stream duration is shorter 250 | than the real duration of the video in some not advanced media players. 251 | 2. Improve the structure of the code and remove some unnecessary codes. 252 | 3. Provide a complete version of client, which could demux the video stream 253 | from a server in any network protocol. 254 | V1.8 update report: 255 | 1. Provide options (widthDst, heightDst) to let MpegDecoder could control the 256 | output size manually. To ensure the option is valid, we must use the method 257 | 'setParameter' before 'FFmpegSetup'. 258 | 2. Optimize some realization of Decoder so that its efficiency could be 259 | improved. 260 | V1.7 update report: 261 | 1. Realize the encoder totally. 262 | 2. Provide a global option 'dumpLevel' to control the log shown in the screen. 263 | 3. Fix bugs in initalize functions. 264 | V1.5 update report: 265 | 1. Provide an incomplete version of encoder, which could encode frames as a 266 | video stream that could not be played by player. 267 | V1.4 update report: 268 | 1. Fix a severe bug of the decoder, which causes the memory collapsed if 269 | decoding a lot of frames. 270 | V1.2 update report: 271 | 1. Use numpy array to replace the native pyList, which improves the speed 272 | significantlly. 273 | V1.0 update report: 274 | 1. Provide the decoder which could decode videos in arbitrary formats and 275 | arbitrary coding. 276 | )"; 277 | Py_RETURN_NONE; 278 | } 279 | 280 | /***************************************************************************** 281 | * Declare the core methods of the classes. 282 | *****************************************************************************/ 283 | static int C_MPDC_init(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { // Construct 284 | PyObject* vpath = nullptr; 285 | cmpc::CharList kwlist_str({ "videoPath" }); 286 | auto kwlist_ptr = kwlist_str.c_str(); 287 | auto kwlist = (char**)(kwlist_ptr.get()); 288 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 289 | PyErr_SetString(PyExc_TypeError, "Error.Initialize: need 'videoPath(str)'"); 290 | return -1; 291 | } 292 | string in_vpath; 293 | if (!vpath) { 294 | in_vpath.clear(); 295 | } 296 | else if (!PyStr2str(vpath, in_vpath)) { 297 | return -1; 298 | } 299 | Self->_in_Handle = new cmpc::CMpegDecoder; 300 | if (!in_vpath.empty()) { 301 | Self->_in_Handle->FFmpegSetup(in_vpath); 302 | } 303 | 304 | in_vpath.clear(); 305 | //cout << sizeof(Self->_in_Handle) << " - " << sizeof(unsigned long long) << endl; 306 | return 0; 307 | } 308 | 309 | static int C_MPEC_init(C_MpegEncoder* Self) { // Construct 310 | Self->_in_Handle = new cmpc::CMpegEncoder; 311 | return 0; 312 | } 313 | 314 | static int C_MPCT_init(C_MpegClient* Self) { // Construct 315 | Self->_in_Handle = new cmpc::CMpegClient; 316 | return 0; 317 | } 318 | 319 | static int C_MPSV_init(C_MpegServer* Self) { // Construct 320 | Self->_in_Handle = new cmpc::CMpegServer; 321 | return 0; 322 | } 323 | 324 | static void C_MPDC_Destruct(C_MpegDecoder* Self) { // Destructor 325 | delete Self->_in_Handle; // Delete the allocated class implementation. 326 | /* If there are still other members, also need to deallocate them, 327 | * for example, Py_XDECREF(Self->Member); */ 328 | Py_TYPE(Self)->tp_free((PyObject*)Self); // Destruct the PyObject. 329 | } 330 | 331 | static void C_MPEC_Destruct(C_MpegEncoder* Self) { // Destructor 332 | delete Self->_in_Handle; // Delete the allocated class implementation. 333 | /* If there are still other members, also need to deallocate them, 334 | * for example, Py_XDECREF(Self->Member); */ 335 | Py_TYPE(Self)->tp_free((PyObject*)Self); // Destruct the PyObject. 336 | } 337 | 338 | static void C_MPCT_Destruct(C_MpegClient* Self) { // Destructor 339 | delete Self->_in_Handle; // Delete the allocated class implementation. 340 | /* If there are still other members, also need to deallocate them, 341 | * for example, Py_XDECREF(Self->Member); */ 342 | Py_TYPE(Self)->tp_free((PyObject*)Self); // Destruct the PyObject. 343 | } 344 | 345 | static void C_MPSV_Destruct(C_MpegServer* Self) { // Destructor 346 | delete Self->_in_Handle; // Delete the allocated class implementation. 347 | /* If there are still other members, also need to deallocate them, 348 | * for example, Py_XDECREF(Self->Member); */ 349 | Py_TYPE(Self)->tp_free((PyObject*)Self); // Destruct the PyObject. 350 | } 351 | 352 | static PyObject* C_MPDC_Str(C_MpegDecoder* Self) { // The __str__ (print) operator. 353 | ostringstream OStr; 354 | OStr << *(Self->_in_Handle); 355 | string Str = OStr.str(); 356 | return str2PyStr(Str); // Convert the string to unicode wide char. 357 | } 358 | 359 | static PyObject* C_MPEC_Str(C_MpegEncoder* Self) { // The __str__ (print) operator. 360 | ostringstream OStr; 361 | OStr << *(Self->_in_Handle); 362 | string Str = OStr.str(); 363 | return str2PyStr(Str); // Convert the string to unicode wide char. 364 | } 365 | 366 | static PyObject* C_MPCT_Str(C_MpegClient* Self) { // The __str__ (print) operator. 367 | ostringstream OStr; 368 | OStr << *(Self->_in_Handle); 369 | string Str = OStr.str(); 370 | return str2PyStr(Str); // Convert the string to unicode wide char. 371 | } 372 | 373 | static PyObject* C_MPSV_Str(C_MpegServer* Self) { // The __str__ (print) operator. 374 | ostringstream OStr; 375 | OStr << *(Self->_in_Handle); 376 | string Str = OStr.str(); 377 | return str2PyStr(Str); // Convert the string to unicode wide char. 378 | } 379 | 380 | static PyObject* C_MPDC_Repr(C_MpegDecoder* Self) { // The __repr__ operator. 381 | return C_MPDC_Str(Self); 382 | } 383 | 384 | static PyObject* C_MPEC_Repr(C_MpegEncoder* Self) { // The __repr__ operator. 385 | return C_MPEC_Str(Self); 386 | } 387 | 388 | static PyObject* C_MPCT_Repr(C_MpegClient* Self) { // The __repr__ operator. 389 | return C_MPCT_Str(Self); 390 | } 391 | 392 | static PyObject* C_MPSV_Repr(C_MpegServer* Self) { // The __repr__ operator. 393 | return C_MPSV_Str(Self); 394 | } 395 | 396 | /***************************************************************************** 397 | * Define the Python-C-APIs for . 398 | * C_MPDC_Setup: Configure the decoder by the video. 399 | * C_MPDC_ExtractFrame Extract serveral frames. 400 | *****************************************************************************/ 401 | static PyObject* C_MPDC_Setup(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 402 | /* Wrapped (bool)C_MPDC_Setup method, the inputs are: 403 | * videoPath [str/bytes->str]: the video path to be decoded. 404 | */ 405 | PyObject* vpath = nullptr; 406 | cmpc::CharList kwlist_str({ "videoPath" }); 407 | auto kwlist_ptr = kwlist_str.c_str(); 408 | auto kwlist = (char**)(kwlist_ptr.get()); 409 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 410 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoPath(str)'"); 411 | return nullptr; 412 | } 413 | string in_vpath; 414 | if (!vpath) { 415 | in_vpath.clear(); 416 | } 417 | else if (!PyStr2str(vpath, in_vpath)) { 418 | return nullptr; 419 | } 420 | bool res; 421 | if (!in_vpath.empty()) 422 | res = Self->_in_Handle->FFmpegSetup(in_vpath); 423 | else 424 | res = Self->_in_Handle->FFmpegSetup(); 425 | 426 | in_vpath.clear(); 427 | if (res) 428 | Py_RETURN_TRUE; 429 | else 430 | Py_RETURN_FALSE; 431 | } 432 | 433 | static PyObject* C_MPEC_Setup(C_MpegEncoder* Self, PyObject* args, PyObject* kwargs) { 434 | /* Wrapped (bool)C_MPEC_Setup method, the inputs are: 435 | * videoPath [str/bytes->str]: the video path to be encoded. 436 | */ 437 | PyObject* vpath = nullptr; 438 | cmpc::CharList kwlist_str({ "videoPath" }); 439 | auto kwlist_ptr = kwlist_str.c_str(); 440 | auto kwlist = (char**)(kwlist_ptr.get()); 441 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 442 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoPath(str)'"); 443 | return nullptr; 444 | } 445 | string in_vpath; 446 | if (!vpath) { 447 | in_vpath.clear(); 448 | } 449 | else if (!PyStr2str(vpath, in_vpath)) { 450 | return nullptr; 451 | } 452 | bool res; 453 | if (!in_vpath.empty()) 454 | res = Self->_in_Handle->FFmpegSetup(in_vpath); 455 | else 456 | res = Self->_in_Handle->FFmpegSetup(); 457 | 458 | in_vpath.clear(); 459 | if (res) 460 | Py_RETURN_TRUE; 461 | else 462 | Py_RETURN_FALSE; 463 | } 464 | 465 | static PyObject* C_MPCT_Setup(C_MpegClient* Self, PyObject* args, PyObject* kwargs) { 466 | /* Wrapped (bool)C_MPCT_Setup method, the inputs are: 467 | * videoAddress [str/bytes->str]: the video path to be demuxed. 468 | */ 469 | PyObject* vpath = nullptr; 470 | cmpc::CharList kwlist_str({ "videoAddress" }); 471 | auto kwlist_ptr = kwlist_str.c_str(); 472 | auto kwlist = (char**)(kwlist_ptr.get()); 473 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 474 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoAddress(str)'"); 475 | return nullptr; 476 | } 477 | string in_vpath; 478 | if (!vpath) { 479 | in_vpath.clear(); 480 | } 481 | else if (!PyStr2str(vpath, in_vpath)) { 482 | return nullptr; 483 | } 484 | bool res; 485 | if (!in_vpath.empty()) 486 | res = Self->_in_Handle->FFmpegSetup(in_vpath); 487 | else 488 | res = Self->_in_Handle->FFmpegSetup(); 489 | 490 | in_vpath.clear(); 491 | if (res) 492 | Py_RETURN_TRUE; 493 | else 494 | Py_RETURN_FALSE; 495 | } 496 | 497 | static PyObject* C_MPSV_Setup(C_MpegServer* Self, PyObject* args, PyObject* kwargs) { 498 | /* Wrapped (bool)C_MPSV_Setup method, the inputs are: 499 | * videoAddress [str/bytes->str]: the video address to be served. 500 | */ 501 | PyObject* vpath = nullptr; 502 | cmpc::CharList kwlist_str({ "videoAddress" }); 503 | auto kwlist_ptr = kwlist_str.c_str(); 504 | auto kwlist = (char**)(kwlist_ptr.get()); 505 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 506 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoAddress(str)'"); 507 | return nullptr; 508 | } 509 | string in_vpath; 510 | if (!vpath) { 511 | in_vpath.clear(); 512 | } 513 | else if (!PyStr2str(vpath, in_vpath)) { 514 | return nullptr; 515 | } 516 | bool res; 517 | if (!in_vpath.empty()) 518 | res = Self->_in_Handle->FFmpegSetup(in_vpath); 519 | else 520 | res = Self->_in_Handle->FFmpegSetup(); 521 | 522 | in_vpath.clear(); 523 | if (res) 524 | Py_RETURN_TRUE; 525 | else 526 | Py_RETURN_FALSE; 527 | } 528 | 529 | static PyObject* C_MPDC_resetPath(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 530 | /* Wrapped (bool)C_MPDC_resetPath method, the inputs are: 531 | * videoPath [str/bytes->str]: the video path to be decoded. 532 | */ 533 | PyObject* vpath = nullptr; 534 | cmpc::CharList kwlist_str({ "videoPath" }); 535 | auto kwlist_ptr = kwlist_str.c_str(); 536 | auto kwlist = (char**)(kwlist_ptr.get()); 537 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 538 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoPath(str)'"); 539 | return nullptr; 540 | } 541 | string in_vpath; 542 | if (!PyStr2str(vpath, in_vpath)) { 543 | return nullptr; 544 | } 545 | Self->_in_Handle->resetPath(in_vpath); 546 | 547 | in_vpath.clear(); 548 | Py_RETURN_NONE; 549 | } 550 | 551 | static PyObject* C_MPEC_resetPath(C_MpegEncoder* Self, PyObject* args, PyObject* kwargs) { 552 | /* Wrapped (bool)C_MPEC_resetPath method, the inputs are: 553 | * videoPath [str/bytes->str]: the video path to be encoded. 554 | */ 555 | PyObject* vpath = nullptr; 556 | cmpc::CharList kwlist_str({ "videoPath" }); 557 | auto kwlist_ptr = kwlist_str.c_str(); 558 | auto kwlist = (char**)(kwlist_ptr.get()); 559 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 560 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoPath(str)'"); 561 | return nullptr; 562 | } 563 | string in_vpath; 564 | if (!PyStr2str(vpath, in_vpath)) { 565 | return nullptr; 566 | } 567 | Self->_in_Handle->resetPath(in_vpath); 568 | 569 | in_vpath.clear(); 570 | Py_RETURN_NONE; 571 | } 572 | 573 | static PyObject* C_MPCT_resetPath(C_MpegClient* Self, PyObject* args, PyObject* kwargs) { 574 | /* Wrapped (bool)C_MPCT_resetPath method, the inputs are: 575 | * videoAddress [str/bytes->str]: the video path to be demuxed. 576 | */ 577 | PyObject* vpath = nullptr; 578 | cmpc::CharList kwlist_str({ "videoAddress" }); 579 | auto kwlist_ptr = kwlist_str.c_str(); 580 | auto kwlist = (char**)(kwlist_ptr.get()); 581 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 582 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoAddress(str)'"); 583 | return nullptr; 584 | } 585 | string in_vpath; 586 | if (!PyStr2str(vpath, in_vpath)) { 587 | return nullptr; 588 | } 589 | Self->_in_Handle->resetPath(in_vpath); 590 | 591 | in_vpath.clear(); 592 | Py_RETURN_NONE; 593 | } 594 | 595 | static PyObject* C_MPSV_resetPath(C_MpegServer* Self, PyObject* args, PyObject* kwargs) { 596 | /* Wrapped (bool)C_MPSV_resetPath method, the inputs are: 597 | * videoAddress [str/bytes->str]: the video address to be served. 598 | */ 599 | PyObject* vpath = nullptr; 600 | cmpc::CharList kwlist_str({ "videoAddress" }); 601 | auto kwlist_ptr = kwlist_str.c_str(); 602 | auto kwlist = (char**)(kwlist_ptr.get()); 603 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &vpath)) { 604 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'videoAddress(str)'"); 605 | return nullptr; 606 | } 607 | string in_vpath; 608 | if (!PyStr2str(vpath, in_vpath)) { 609 | return nullptr; 610 | } 611 | Self->_in_Handle->resetPath(in_vpath); 612 | 613 | in_vpath.clear(); 614 | Py_RETURN_NONE; 615 | } 616 | 617 | static PyObject* C_MPCT_Start(C_MpegClient* Self) { 618 | /* Wrapped (void)Start method, the input is required to be empty. */ 619 | auto success = Self->_in_Handle->start(); 620 | if (!success) { 621 | PyErr_SetString(PyExc_ConnectionError, "Error.Start: before call this method, need to call FFmpegSetup() successfully, and also you should not call it when the decoding thread is running.'"); 622 | return nullptr; 623 | } 624 | Py_RETURN_NONE; 625 | } 626 | 627 | static PyObject* C_MPCT_Terminate(C_MpegClient* Self) { 628 | /* Wrapped (void)Terminate method, the input is required to be empty. */ 629 | Self->_in_Handle->terminate(); 630 | Py_RETURN_NONE; 631 | } 632 | 633 | /* Pay attention to the following two methods : 634 | * Why do we remove the Py_IN/DECREF? 635 | * Because no temp variables are created, so we do not need to manage them, 636 | * but just use None as the returned value. */ 637 | static PyObject* FreePyArray(PyArrayObject* PyArray) { 638 | uint8_t* out_dataptr = (uint8_t*)PyArray_DATA(PyArray); 639 | delete[] out_dataptr; 640 | return nullptr; 641 | } 642 | void FreePyList(PyObject* PyList) { 643 | Py_ssize_t getlen = PyList_Size(PyList); 644 | for (Py_ssize_t i = 0; i < getlen; i++) { 645 | PyObject* Item = PyList_GetItem(PyList, i); 646 | FreePyArray((PyArrayObject*)Item); 647 | } 648 | Py_DECREF(PyList); 649 | PyGC_Collect(); 650 | } 651 | 652 | static PyObject* C_MPDC_ExtractFrame(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 653 | /* Wrapped (int)ExtractFrame method, the inputs are: 654 | * framePos [int->int64_t]: the start position of the extracted frames. 655 | * frameNum [int->int64_t]: the number of extracted frames. 656 | */ 657 | int64_t framePos = 0, frameNum = 1; 658 | cmpc::CharList kwlist_str({ "framePos", "frameNum" }); 659 | auto kwlist_ptr = kwlist_str.c_str(); 660 | auto kwlist = (char**)(kwlist_ptr.get()); 661 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|LL", kwlist, &framePos, &frameNum)) { 662 | PyErr_SetString(PyExc_TypeError, "Error.ExtractFrame: need 'framePos(int)/frameNum(int)'"); 663 | return nullptr; 664 | } 665 | PyObject* PyFrameList = PyList_New(static_cast(0)); 666 | //cout << framePos << " - " << frameNum << endl; 667 | bool res = Self->_in_Handle->ExtractFrame(PyFrameList, framePos, frameNum, 0, 0); 668 | Py_ssize_t getlen = PyList_Size(PyFrameList); 669 | res = res && (getlen > 0); 670 | if (res) { 671 | PyObject* PyFrameArray = PyArray_FromObject(PyFrameList, NPY_UINT8, 4, 4); 672 | FreePyList(PyFrameList); 673 | return PyFrameArray; 674 | } 675 | else { 676 | Py_DECREF(PyFrameList); 677 | PyGC_Collect(); 678 | Py_RETURN_NONE; 679 | } 680 | } 681 | 682 | static PyObject* C_MPDC_ExtractFrame_Time(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 683 | /* Wrapped (int)ExtractFrame method, the inputs are: 684 | * timePos [float->double]: the start position (time unit) of the extracted frames. 685 | * frameNum [int->int64_t]: the number of extracted frames. 686 | */ 687 | double timePos = 0; 688 | int64_t frameNum = 1; 689 | cmpc::CharList kwlist_str({ "timePos", "frameNum" }); 690 | auto kwlist_ptr = kwlist_str.c_str(); 691 | auto kwlist = (char**)(kwlist_ptr.get()); 692 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|dL", kwlist, &timePos, &frameNum)) { 693 | PyErr_SetString(PyExc_TypeError, "Error.ExtractFrame_Time: need 'timePos(float)/frameNum(int)'"); 694 | return nullptr; 695 | } 696 | PyObject* PyFrameList = PyList_New(static_cast(0)); 697 | //cout << framePos << " - " << frameNum << endl; 698 | bool res = Self->_in_Handle->ExtractFrame(PyFrameList, 0, frameNum, timePos, 1); 699 | Py_ssize_t getlen = PyList_Size(PyFrameList); 700 | res = res && (getlen > 0); 701 | if (res) { 702 | PyObject* PyFrameArray = PyArray_FromObject(PyFrameList, NPY_UINT8, 4, 4); 703 | FreePyList(PyFrameList); 704 | return PyFrameArray; 705 | } 706 | else { 707 | Py_DECREF(PyFrameList); 708 | PyGC_Collect(); 709 | Py_RETURN_NONE; 710 | } 711 | } 712 | 713 | static PyObject* C_MPEC_EncodeFrame(C_MpegEncoder* Self, PyObject* args, PyObject* kwargs) { 714 | /* Wrapped (bool)EncodeFrame method, the inputs are: 715 | * PyArrayFrame [ndarray->PyArrayObject]: the frame to be encoded. 716 | */ 717 | PyObject* PyArrayFrame = nullptr; 718 | cmpc::CharList kwlist_str({ "PyArrayFrame" }); 719 | auto kwlist_ptr = kwlist_str.c_str(); 720 | auto kwlist = (char**)(kwlist_ptr.get()); 721 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &PyArrayFrame)) { 722 | PyErr_SetString(PyExc_TypeError, "Error.EncodeFrame: need 'PyArrayFrame(ndarray)'"); 723 | return nullptr; 724 | } 725 | int res = Self->_in_Handle->EncodeFrame(reinterpret_cast(PyArrayFrame)); 726 | if (res >= 0) 727 | Py_RETURN_TRUE; 728 | else 729 | Py_RETURN_FALSE; 730 | } 731 | 732 | static PyObject* C_MPSV_ServeFrame(C_MpegServer* Self, PyObject* args, PyObject* kwargs) { 733 | /* Wrapped (bool)ServeFrame method, the inputs are: 734 | * PyArrayFrame [ndarray->PyArrayObject]: the frame to be encoded and served. 735 | */ 736 | PyObject* PyArrayFrame = nullptr; 737 | cmpc::CharList kwlist_str({ "PyArrayFrame" }); 738 | auto kwlist_ptr = kwlist_str.c_str(); 739 | auto kwlist = (char**)(kwlist_ptr.get()); 740 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &PyArrayFrame)) { 741 | PyErr_SetString(PyExc_TypeError, "Error.EncodeFrame: need 'PyArrayFrame(ndarray)'"); 742 | return nullptr; 743 | } 744 | int res = Self->_in_Handle->ServeFrame(reinterpret_cast(PyArrayFrame)); 745 | if (res >= 0) 746 | Py_RETURN_TRUE; 747 | else 748 | Py_RETURN_FALSE; 749 | } 750 | 751 | static PyObject* C_MPSV_ServeFrameBlock(C_MpegServer* Self, PyObject* args, PyObject* kwargs) { 752 | /* Wrapped (bool)ServeFrameBlock method, the inputs are: 753 | * PyArrayFrame [ndarray->PyArrayObject]: the frame to be encoded and served. 754 | */ 755 | PyObject* PyArrayFrame = nullptr; 756 | cmpc::CharList kwlist_str({ "PyArrayFrame" }); 757 | auto kwlist_ptr = kwlist_str.c_str(); 758 | auto kwlist = (char**)(kwlist_ptr.get()); 759 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &PyArrayFrame)) { 760 | PyErr_SetString(PyExc_TypeError, "Error.EncodeFrame: need 'PyArrayFrame(ndarray)'"); 761 | return nullptr; 762 | } 763 | int res = Self->_in_Handle->ServeFrameBlock(reinterpret_cast(PyArrayFrame)); 764 | if (res >= 0) 765 | Py_RETURN_TRUE; 766 | else 767 | Py_RETURN_FALSE; 768 | } 769 | 770 | static PyObject* C_MPCT_ExtractFrame(C_MpegClient* Self, PyObject* args, PyObject* kwargs) { 771 | /* Wrapped (int)ExtractFrame method, the inputs are: 772 | * readSize [int->int64_t]: the number of frames to be readed. This value could not 773 | * exceeded the size of the frame buffer. 774 | */ 775 | int64_t readSize = 0; 776 | cmpc::CharList kwlist_str({ "readSize" }); 777 | auto kwlist_ptr = kwlist_str.c_str(); 778 | auto kwlist = (char**)(kwlist_ptr.get()); 779 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|L", kwlist, &readSize)) { 780 | PyErr_SetString(PyExc_TypeError, "Error.ExtractFrame: need 'readSize(int)'"); 781 | return nullptr; 782 | } 783 | PyObject* res = nullptr; 784 | if (readSize > 0) 785 | res = Self->_in_Handle->ExtractFrame(readSize); 786 | else 787 | res = Self->_in_Handle->ExtractFrame(); 788 | if (res) { 789 | return res; 790 | } 791 | else { 792 | Py_RETURN_NONE; 793 | } 794 | } 795 | 796 | static PyObject* C_MPDC_ExtractGOP(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 797 | /* Wrapped (int)ExtractGOP method, the inputs are: 798 | * framePos [int->int64_t]: the start position of the GOP to be extracted. 799 | */ 800 | int64_t framePos = -1; 801 | cmpc::CharList kwlist_str({ "framePos" }); 802 | auto kwlist_ptr = kwlist_str.c_str(); 803 | auto kwlist = (char**)(kwlist_ptr.get()); 804 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|L", kwlist, &framePos)) { 805 | PyErr_SetString(PyExc_TypeError, "Error.ExtractGOP: need 'framePos(int)'"); 806 | return nullptr; 807 | } 808 | PyObject* PyFrameList = PyList_New(static_cast(0)); 809 | //cout << framePos << " - " << frameNum << endl; 810 | if (!(framePos < 0)) 811 | Self->_in_Handle->setGOPPosition(framePos); 812 | bool res = Self->_in_Handle->ExtractGOP(PyFrameList); 813 | Py_ssize_t getlen = PyList_Size(PyFrameList); 814 | res = res && (getlen > 0); 815 | if (res) { 816 | PyObject* PyFrameArray = PyArray_FromObject(PyFrameList, NPY_UINT8, 4, 4); 817 | FreePyList(PyFrameList); 818 | return PyFrameArray; 819 | } 820 | else { 821 | Py_DECREF(PyFrameList); 822 | PyGC_Collect(); 823 | Py_RETURN_NONE; 824 | } 825 | } 826 | 827 | static PyObject* C_MPDC_ExtractGOP_Time(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 828 | /* Wrapped (int)ExtractGOP_Time method, the inputs are: 829 | * timePos [float->double]: the start position (time unit) of the GOP to be extracted. 830 | */ 831 | double timePos = -1; 832 | cmpc::CharList kwlist_str({ "timePos" }); 833 | auto kwlist_ptr = kwlist_str.c_str(); 834 | auto kwlist = (char**)(kwlist_ptr.get()); 835 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|d", kwlist, &timePos)) { 836 | PyErr_SetString(PyExc_TypeError, "Error.ExtractGOP_Time: need 'timePos(float)'"); 837 | return nullptr; 838 | } 839 | PyObject* PyFrameList = PyList_New(static_cast(0)); 840 | //cout << framePos << " - " << frameNum << endl; 841 | if (!(timePos < 0)) 842 | Self->_in_Handle->setGOPPosition(timePos); 843 | bool res = Self->_in_Handle->ExtractGOP(PyFrameList); 844 | Py_ssize_t getlen = PyList_Size(PyFrameList); 845 | res = res && (getlen > 0); 846 | if (res) { 847 | PyObject* PyFrameArray = PyArray_FromObject(PyFrameList, NPY_UINT8, 4, 4); 848 | FreePyList(PyFrameList); 849 | return PyFrameArray; 850 | } 851 | else { 852 | Py_DECREF(PyFrameList); 853 | PyGC_Collect(); 854 | Py_RETURN_NONE; 855 | } 856 | } 857 | 858 | static PyObject* C_MPDC_setGOPPosition(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 859 | /* Wrapped (void)setGOPPosition method, the inputs are: 860 | * framePos [int->int64_t]: the start position of the GOP to be extracted. 861 | * timePos [float->double]: the start position (time unit) of the GOP to be extracted. 862 | */ 863 | int64_t framePos = -1; 864 | double timePos = -1; 865 | cmpc::CharList kwlist_str({ "framePos", "timePos" }); 866 | auto kwlist_ptr = kwlist_str.c_str(); 867 | auto kwlist = (char**)(kwlist_ptr.get()); 868 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Ld", kwlist, &framePos, &timePos)) { 869 | PyErr_SetString(PyExc_TypeError, "Error.setGOPPosition: need 'framePos(int)'/'timePos(float)'"); 870 | return nullptr; 871 | } 872 | if (!(framePos < 0)) 873 | Self->_in_Handle->setGOPPosition(framePos); 874 | else if (!(timePos < 0)) 875 | Self->_in_Handle->setGOPPosition(timePos); 876 | Py_RETURN_NONE; 877 | } 878 | 879 | static PyObject* C_MPDC_getParam(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 880 | /* Wrapped (bool)C_MPDC_getParam function, the inputs are: 881 | * paramName [str/bytes->str]: The name of the parameter to be gotten, could be. 882 | * videoPath: [str] Path of the current video. 883 | * width/height: [int] The width / height of the frame. 884 | * frameCount: [int] The count of frames of the current decoding work. 885 | * coderName: [str] The name of the decoder. 886 | * nthread: [int] The number of decoder threads. 887 | * duration: [float] The duration of the video. 888 | * estFrameNum: [int] The estimated total frame number. 889 | * avgFrameRate [float] The average frame rate. 890 | */ 891 | PyObject* param = nullptr; 892 | cmpc::CharList kwlist_str({ "paramName" }); 893 | auto kwlist_ptr = kwlist_str.c_str(); 894 | auto kwlist = (char**)(kwlist_ptr.get()); 895 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, ¶m)) { 896 | PyErr_SetString(PyExc_TypeError, "Error.getParameter: need 'paramName(str)'"); 897 | return nullptr; 898 | } 899 | string in_param; 900 | if (!param) { 901 | in_param.clear(); 902 | } 903 | else if (!PyStr2str(param, in_param)) { 904 | return nullptr; 905 | } 906 | PyObject* res = nullptr; 907 | if (in_param.empty()) { 908 | res = Self->_in_Handle->getParameter(); 909 | } 910 | else { 911 | res = Self->_in_Handle->getParameter(in_param); 912 | } 913 | in_param.clear(); 914 | return res; 915 | } 916 | 917 | static PyObject* C_MPEC_getParam(C_MpegEncoder* Self, PyObject* args, PyObject* kwargs) { 918 | /* Wrapped (bool)C_MPEC_getParam function, the inputs are: 919 | * paramName [str/bytes->str]: The name of the parameter to be gotten, could be. 920 | * videoPath: [str] Path of the current video. 921 | * codecName: [str] The name of the codec. 922 | * nthread: [int] The number of encoder threads. 923 | * bitRate: [int] The target bit rate. 924 | * width/height: [int] The width / height of the encoded frame. 925 | * widthSrc/heightSrc: [int] The width / height of the input frame. 926 | * GOPSize: [int] The size of one GOP. 927 | * maxBframe: [int] The maximal number of continuous B frames. 928 | * frameRate: [float] The target frame rate. 929 | */ 930 | PyObject* param = nullptr; 931 | cmpc::CharList kwlist_str({ "paramName" }); 932 | auto kwlist_ptr = kwlist_str.c_str(); 933 | auto kwlist = (char**)(kwlist_ptr.get()); 934 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, ¶m)) { 935 | PyErr_SetString(PyExc_TypeError, "Error.getParameter: need 'paramName(str)'"); 936 | return nullptr; 937 | } 938 | string in_param; 939 | if (!param) { 940 | in_param.clear(); 941 | } 942 | else if (!PyStr2str(param, in_param)) { 943 | return nullptr; 944 | } 945 | PyObject* res = nullptr; 946 | if (in_param.empty()) { 947 | res = Self->_in_Handle->getParameter(); 948 | } 949 | else { 950 | res = Self->_in_Handle->getParameter(in_param); 951 | } 952 | in_param.clear(); 953 | return res; 954 | } 955 | 956 | static PyObject* C_MPCT_getParam(C_MpegClient* Self, PyObject* args, PyObject* kwargs) { 957 | /* Wrapped (bool)C_MPCT_getParam method, the inputs are: 958 | * parameter [str/bytes->str]: The name of the parameter to be gotten, could be. 959 | * videoAddress: [str] The address of the current video. 960 | * width/height: [int] The width / height of the received frame. 961 | * frameCount: [int] The count of frames of the current decoding work. 962 | * coderName: [str] The name of the decoder. 963 | * nthread: [int] The number of decoder threads. 964 | * duration: [float] The duration of the video. 965 | * estFrameNum: [int] The estimated total frame number. 966 | * avgFrameRate [float] The average frame rate. 967 | */ 968 | PyObject* param = nullptr; 969 | cmpc::CharList kwlist_str({ "paramName" }); 970 | auto kwlist_ptr = kwlist_str.c_str(); 971 | auto kwlist = (char**)(kwlist_ptr.get()); 972 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, ¶m)) { 973 | PyErr_SetString(PyExc_TypeError, "Error.getParameter: need 'paramName(str)'"); 974 | return nullptr; 975 | } 976 | string in_param; 977 | if (!param) { 978 | in_param.clear(); 979 | } 980 | else if (!PyStr2str(param, in_param)) { 981 | return nullptr; 982 | } 983 | PyObject* res = nullptr; 984 | if (in_param.empty()) { 985 | res = Self->_in_Handle->getParameter(); 986 | } 987 | else { 988 | res = Self->_in_Handle->getParameter(in_param); 989 | } 990 | in_param.clear(); 991 | return res; 992 | } 993 | 994 | static PyObject* C_MPSV_getParam(C_MpegServer* Self, PyObject* args, PyObject* kwargs) { 995 | /* Wrapped (bool)C_MPSV_getParam function, the inputs are: 996 | * paramName [str/bytes->str]: The name of the parameter to be gotten, could be. 997 | * videoAddress: [str] The address of the current video. 998 | * codecName: [str] The name of the codec. 999 | * formatName: [str] The name of the stream format. 1000 | * nthread: [int] The number of encoder threads. 1001 | * bitRate: [int] The target bit rate. 1002 | * width/height: [int] The width / height of the encoded frame. 1003 | * widthSrc/heightSrc: [int] The width / height of the input frame. 1004 | * GOPSize: [int] The size of one GOP. 1005 | * maxBframe: [int] The maximal number of continuous B frames. 1006 | * frameRate: [float] The target frame rate. 1007 | * waitRef [float] The reference used for sync. waiting. 1008 | * ptsAhead [int] The ahead time duration in the uit of time stamp. 1009 | */ 1010 | PyObject* param = nullptr; 1011 | cmpc::CharList kwlist_str({ "paramName" }); 1012 | auto kwlist_ptr = kwlist_str.c_str(); 1013 | auto kwlist = (char**)(kwlist_ptr.get()); 1014 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, ¶m)) { 1015 | PyErr_SetString(PyExc_TypeError, "Error.getParameter: need 'paramName(str)'"); 1016 | return nullptr; 1017 | } 1018 | string in_param; 1019 | if (!param) { 1020 | in_param.clear(); 1021 | } 1022 | else if (!PyStr2str(param, in_param)) { 1023 | return nullptr; 1024 | } 1025 | PyObject* res = nullptr; 1026 | if (in_param.empty()) { 1027 | res = Self->_in_Handle->getParameter(); 1028 | } 1029 | else { 1030 | res = Self->_in_Handle->getParameter(in_param); 1031 | } 1032 | in_param.clear(); 1033 | return res; 1034 | } 1035 | 1036 | static PyObject* C_MPDC_setParam(C_MpegDecoder* Self, PyObject* args, PyObject* kwargs) { 1037 | /* Wrapped (void)C_MPDC_setParam method, the inputs are: 1038 | * widthDst/heightDst: [int] The width / height of the decoded frames. 1039 | * nthread: [int] The number of decoder threads. 1040 | */ 1041 | int widthDst = 0; 1042 | int heightDst = 0; 1043 | int nthread = 0; 1044 | cmpc::CharList kwlist_str({ "widthDst", "heightDst", "nthread" }); 1045 | auto kwlist_ptr = kwlist_str.c_str(); 1046 | auto kwlist = (char**)(kwlist_ptr.get()); 1047 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iii", kwlist, &widthDst, &heightDst, &nthread)) { 1048 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'params'"); 1049 | return nullptr; 1050 | } 1051 | if (widthDst > 0) { 1052 | Self->_in_Handle->setParameter("widthDst", &widthDst); 1053 | } 1054 | if (heightDst > 0) { 1055 | Self->_in_Handle->setParameter("heightDst", &heightDst); 1056 | } 1057 | if (nthread > 0) { 1058 | Self->_in_Handle->setParameter("nthread", &nthread); 1059 | } 1060 | Py_RETURN_NONE; 1061 | } 1062 | 1063 | static PyObject* C_MPEC_setParam(C_MpegEncoder* Self, PyObject* args, PyObject* kwargs) { 1064 | /* Wrapped (bool)C_MPEC_setParam method, the inputs are: 1065 | * decoder: [MpegDecoder / MpegClient]: The parameters to be configured. 1066 | * configDict: [dict] A collection of key params. 1067 | * videoPath: [str/bytes] Path of the current video. 1068 | * codecName: [str/bytes] The name of the codec. 1069 | * nthread: [int] The number of encoder threads. 1070 | * bitRate: [double] The target bit rate. 1071 | * width/height: [int] The width / height of the encoded frame. 1072 | * widthSrc/heightSrc: [int] The width / height of the input frame. 1073 | * GOPSize: [int] The size of one GOP. 1074 | * maxBframe: [int] The maximal number of continuous B frames. 1075 | * frameRate: [tuple] The target frame rate. 1076 | */ 1077 | PyObject* decoder = nullptr; 1078 | PyObject* configDict = nullptr; 1079 | PyObject* videoPath = nullptr; 1080 | PyObject* codecName = nullptr; 1081 | double bitRate = -1; 1082 | int nthread = 0; 1083 | int width = 0; 1084 | int height = 0; 1085 | int widthSrc = 0; 1086 | int heightSrc = 0; 1087 | int GOPSize = 0; 1088 | int MaxBframe = -1; 1089 | PyObject* frameRate = nullptr; 1090 | cmpc::CharList kwlist_str({ "decoder", "configDict", "videoPath", "codecName", "nthread", "bitRate", "width", "height", "widthSrc", "heightSrc", "GOPSize", "maxBframe", "frameRate" }); 1091 | auto kwlist_ptr = kwlist_str.c_str(); 1092 | auto kwlist = (char**)(kwlist_ptr.get()); 1093 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOOOidiiiiiiO", kwlist, &decoder, &configDict, &videoPath, &codecName, &nthread, &bitRate, &width, &height, &widthSrc, &heightSrc, &GOPSize, &MaxBframe, &frameRate)) { 1094 | PyErr_SetString(PyExc_TypeError, "Error.setParameter: need 'params'"); 1095 | return nullptr; 1096 | } 1097 | string temp_str; 1098 | if (decoder) { 1099 | temp_str.assign(decoder->ob_type->tp_name); 1100 | if (temp_str.compare("mpegCoder.MpegDecoder") == 0) { 1101 | auto decoderPtr = reinterpret_cast(decoder); 1102 | Self->_in_Handle->setParameter("decoder", decoderPtr->_in_Handle); 1103 | } 1104 | else if (temp_str.compare("mpegCoder.MpegClient") == 0) { 1105 | auto decoderPtr = reinterpret_cast(decoder); 1106 | Self->_in_Handle->setParameter("client", decoderPtr->_in_Handle); 1107 | } 1108 | else { 1109 | cerr << "Warning.setParameter: Not intended decoder type, no valid update in this step." << endl; 1110 | } 1111 | } 1112 | else if (configDict) { 1113 | if (PyDict_Check(configDict)) { 1114 | Self->_in_Handle->setParameter("configDict", configDict); 1115 | } 1116 | else { 1117 | cerr << "Warning.setParameter: Not intended configDict type (require to be a dict), no valid update in this step." << endl; 1118 | } 1119 | } 1120 | if (videoPath) { 1121 | if (PyStr2str(videoPath, temp_str)) { 1122 | Self->_in_Handle->setParameter("videoPath", &temp_str); 1123 | } 1124 | else { 1125 | return nullptr; 1126 | } 1127 | } 1128 | if (codecName) { 1129 | if (PyStr2str(codecName, temp_str)) { 1130 | Self->_in_Handle->setParameter("codecName", &temp_str); 1131 | } 1132 | else { 1133 | return nullptr; 1134 | } 1135 | } 1136 | if (nthread > 0) { 1137 | Self->_in_Handle->setParameter("nthread", &nthread); 1138 | } 1139 | if (bitRate > 0) { 1140 | Self->_in_Handle->setParameter("bitRate", &bitRate); 1141 | } 1142 | if (width > 0) { 1143 | Self->_in_Handle->setParameter("width", &width); 1144 | } 1145 | if (height > 0) { 1146 | Self->_in_Handle->setParameter("height", &height); 1147 | } 1148 | if (widthSrc > 0) { 1149 | Self->_in_Handle->setParameter("widthSrc", &widthSrc); 1150 | } 1151 | if (heightSrc > 0) { 1152 | Self->_in_Handle->setParameter("heightSrc", &heightSrc); 1153 | } 1154 | if (GOPSize > 0) { 1155 | Self->_in_Handle->setParameter("GOPSize", &GOPSize); 1156 | } 1157 | if (MaxBframe >= 0) { 1158 | Self->_in_Handle->setParameter("maxBframe", &MaxBframe); 1159 | } 1160 | if (frameRate) { 1161 | if (PyTuple_Check(frameRate) && PyTuple_Size(frameRate) == 2) { 1162 | Self->_in_Handle->setParameter("frameRate", frameRate); 1163 | } 1164 | else { 1165 | cerr << "Warning.setParameter: {frameRate} must be a 2-dim tuple, so there is no valid update in this step." << endl; 1166 | } 1167 | } 1168 | temp_str.clear(); 1169 | Py_RETURN_NONE; 1170 | } 1171 | 1172 | static PyObject* C_MPCT_setParam(C_MpegClient* Self, PyObject* args, PyObject* kwargs) { 1173 | /* Wrapped (void)C_MPCT_setParam method, the inputs are: 1174 | * widthDst/heightDst: [int] The width / height of the decoded frames. 1175 | * cacheSize/readSize: [int] The size of the cache, and the reading size. 1176 | * dstFrameRate: [tuple] The target frame rate of the client. 1177 | * nthread: [int] The number of decoder threads. 1178 | */ 1179 | int widthDst = 0; 1180 | int heightDst = 0; 1181 | int nthread = 0; 1182 | int64_t cacheSize = 0; 1183 | int64_t readSize = 0; 1184 | PyObject* frameRate = nullptr; 1185 | cmpc::CharList kwlist_str({ "widthDst", "heightDst", "cacheSize", "readSize", "dstFrameRate", "nthread" }); 1186 | auto kwlist_ptr = kwlist_str.c_str(); 1187 | auto kwlist = (char**)(kwlist_ptr.get()); 1188 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iiLLOi", kwlist, &widthDst, &heightDst, &cacheSize, &readSize, &frameRate, &nthread)) { 1189 | PyErr_SetString(PyExc_TypeError, "Error.FFmpegSetup: need 'params'"); 1190 | return nullptr; 1191 | } 1192 | if (widthDst > 0) { 1193 | Self->_in_Handle->setParameter("widthDst", &widthDst); 1194 | } 1195 | if (heightDst > 0) { 1196 | Self->_in_Handle->setParameter("heightDst", &heightDst); 1197 | } 1198 | if (cacheSize > 0) { 1199 | Self->_in_Handle->setParameter("cacheSize", &cacheSize); 1200 | } 1201 | if (readSize > 0) { 1202 | Self->_in_Handle->setParameter("readSize", &readSize); 1203 | } 1204 | if (frameRate) { 1205 | if (PyTuple_Check(frameRate) && PyTuple_Size(frameRate) == 2) { 1206 | Self->_in_Handle->setParameter("dstFrameRate", frameRate); 1207 | } 1208 | else { 1209 | cerr << "Warning.setParameter: {dstFrameRate} must be a 2-dim tuple, so there is no valid update in this step." << endl; 1210 | } 1211 | } 1212 | if (nthread > 0) { 1213 | Self->_in_Handle->setParameter("nthread", &nthread); 1214 | } 1215 | Py_RETURN_NONE; 1216 | } 1217 | 1218 | static PyObject* C_MPSV_setParam(C_MpegServer* Self, PyObject* args, PyObject* kwargs) { 1219 | /* Wrapped (bool)C_MPSV_setParam method, the inputs are: 1220 | * decoder [MpegDecoder / MpegClient]: The parameters to be configured. 1221 | * videoAddress: [str/bytes] The address of the current video. 1222 | * codecName: [str/bytes] The name of the codec. 1223 | * nthread: [int] The number of encoder threads. 1224 | * bitRate: [double] The target bit rate. 1225 | * width/height: [int] The width / height of the encoded frame. 1226 | * widthSrc/heightSrc: [int] The width / height of the input frame. 1227 | * GOPSize: [int] The size of one GOP. 1228 | * maxBframe: [int] The maximal number of continuous B frames. 1229 | * frameRate: [tuple] The target frame rate. 1230 | * frameAhead [int] The number of ahead frames. This value is suggested 1231 | * to be larger than the GOPSize. 1232 | */ 1233 | PyObject* decoder = nullptr; 1234 | PyObject* configDict = nullptr; 1235 | PyObject* videoAddress = nullptr; 1236 | PyObject* codecName = nullptr; 1237 | double bitRate = -1; 1238 | int nthread = 0; 1239 | int width = 0; 1240 | int height = 0; 1241 | int widthSrc = 0; 1242 | int heightSrc = 0; 1243 | int GOPSize = 0; 1244 | int MaxBframe = -1; 1245 | int frameAhead = 0; 1246 | PyObject* frameRate = nullptr; 1247 | cmpc::CharList kwlist_str({ "decoder", "configDict", "videoAddress", "codecName", "nthread", "bitRate", "width", "height", "widthSrc", "heightSrc", "GOPSize", "maxBframe", "frameRate", "frameAhead" }); 1248 | auto kwlist_ptr = kwlist_str.c_str(); 1249 | auto kwlist = (char**)(kwlist_ptr.get()); 1250 | if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOOOidiiiiiiOi", kwlist, &decoder, &configDict, &videoAddress, &codecName, &nthread, &bitRate, &width, &height, &widthSrc, &heightSrc, &GOPSize, &MaxBframe, &frameRate, &frameAhead)) { 1251 | PyErr_SetString(PyExc_TypeError, "Error.setParameter: need 'params'"); 1252 | return nullptr; 1253 | } 1254 | string temp_str; 1255 | if (decoder) { 1256 | temp_str.assign(decoder->ob_type->tp_name); 1257 | if (temp_str.compare("mpegCoder.MpegDecoder") == 0) { 1258 | auto decoderPtr = reinterpret_cast(decoder); 1259 | Self->_in_Handle->setParameter("decoder", decoderPtr->_in_Handle); 1260 | } 1261 | else if (temp_str.compare("mpegCoder.MpegClient") == 0) { 1262 | auto decoderPtr = reinterpret_cast(decoder); 1263 | Self->_in_Handle->setParameter("client", decoderPtr->_in_Handle); 1264 | } 1265 | else { 1266 | cerr << "Warning.setParameter: Not intended decoder type, no valid update in this step." << endl; 1267 | } 1268 | } 1269 | else if (configDict) { 1270 | if (PyDict_Check(configDict)) { 1271 | Self->_in_Handle->setParameter("configDict", configDict); 1272 | } 1273 | else { 1274 | cerr << "Warning.setParameter: Not intended configDict type (require to be a dict), no valid update in this step." << endl; 1275 | } 1276 | } 1277 | if (videoAddress) { 1278 | if (PyStr2str(videoAddress, temp_str)) { 1279 | Self->_in_Handle->setParameter("videoAddress", &temp_str); 1280 | } 1281 | else { 1282 | return nullptr; 1283 | } 1284 | } 1285 | if (codecName) { 1286 | if (PyStr2str(codecName, temp_str)) { 1287 | Self->_in_Handle->setParameter("codecName", &temp_str); 1288 | } 1289 | else { 1290 | return nullptr; 1291 | } 1292 | } 1293 | if (nthread > 0) { 1294 | Self->_in_Handle->setParameter("nthread", &nthread); 1295 | } 1296 | if (bitRate > 0) { 1297 | Self->_in_Handle->setParameter("bitRate", &bitRate); 1298 | } 1299 | if (width > 0) { 1300 | Self->_in_Handle->setParameter("width", &width); 1301 | } 1302 | if (height > 0) { 1303 | Self->_in_Handle->setParameter("height", &height); 1304 | } 1305 | if (widthSrc > 0) { 1306 | Self->_in_Handle->setParameter("widthSrc", &widthSrc); 1307 | } 1308 | if (heightSrc > 0) { 1309 | Self->_in_Handle->setParameter("heightSrc", &heightSrc); 1310 | } 1311 | if (GOPSize > 0) { 1312 | Self->_in_Handle->setParameter("GOPSize", &GOPSize); 1313 | } 1314 | if (MaxBframe >= 0) { 1315 | Self->_in_Handle->setParameter("maxBframe", &MaxBframe); 1316 | } 1317 | if (frameRate) { 1318 | if (PyTuple_Check(frameRate) && PyTuple_Size(frameRate) == 2) { 1319 | Self->_in_Handle->setParameter("frameRate", frameRate); 1320 | } 1321 | else { 1322 | cerr << "Warning.setParameter: {frameRate} must be a 2-dim tuple, so there is no valid update in this step." << endl; 1323 | } 1324 | } 1325 | if (frameAhead > 0) { 1326 | Self->_in_Handle->setParameter("frameAhead", &frameAhead); 1327 | } 1328 | temp_str.clear(); 1329 | Py_RETURN_NONE; 1330 | } 1331 | 1332 | static PyObject* C_MPDC_DumpFile(C_MpegDecoder* Self) { 1333 | /* Wrapped (void)dumpFormat method, the input is required to be empty. */ 1334 | Self->_in_Handle->dumpFormat(); 1335 | Py_RETURN_NONE; 1336 | } 1337 | 1338 | static PyObject* C_MPEC_DumpFile(C_MpegEncoder* Self) { 1339 | /* Wrapped (void)dumpFormat method, the input is required to be empty. */ 1340 | Self->_in_Handle->dumpFormat(); 1341 | Py_RETURN_NONE; 1342 | } 1343 | 1344 | static PyObject* C_MPCT_DumpFile(C_MpegClient* Self) { 1345 | /* Wrapped (void)dumpFormat method, the input is required to be empty. */ 1346 | Self->_in_Handle->dumpFormat(); 1347 | Py_RETURN_NONE; 1348 | } 1349 | 1350 | static PyObject* C_MPSV_DumpFile(C_MpegServer* Self) { 1351 | /* Wrapped (void)dumpFormat method, the input is required to be empty. */ 1352 | Self->_in_Handle->dumpFormat(); 1353 | Py_RETURN_NONE; 1354 | } 1355 | 1356 | static PyObject* C_MPDC_Clear(C_MpegDecoder* Self) { 1357 | /* Wrapped (void)clear method, the input is required to be empty. */ 1358 | Self->_in_Handle->clear(); 1359 | Py_RETURN_NONE; 1360 | } 1361 | 1362 | static PyObject* C_MPEC_Clear(C_MpegEncoder* Self) { 1363 | /* Wrapped (void)clear method, the input is required to be empty. */ 1364 | Self->_in_Handle->clear(); 1365 | Py_RETURN_NONE; 1366 | } 1367 | 1368 | static PyObject* C_MPCT_Clear(C_MpegClient* Self) { 1369 | /* Wrapped (void)clear method, the input is required to be empty. */ 1370 | Self->_in_Handle->clear(); 1371 | Py_RETURN_NONE; 1372 | } 1373 | 1374 | static PyObject* C_MPSV_Clear(C_MpegServer* Self) { 1375 | /* Wrapped (void)clear method, the input is required to be empty. */ 1376 | Self->_in_Handle->clear(); 1377 | Py_RETURN_NONE; 1378 | } 1379 | 1380 | static PyObject* C_MPEC_Close(C_MpegEncoder* Self) { 1381 | /* Wrapped (void)close method, the input is required to be empty. */ 1382 | Self->_in_Handle->FFmpegClose(); 1383 | Py_RETURN_NONE; 1384 | } 1385 | 1386 | static PyObject* C_MPSV_Close(C_MpegServer* Self) { 1387 | /* Wrapped (void)close method, the input is required to be empty. */ 1388 | Self->_in_Handle->FFmpegClose(); 1389 | Py_RETURN_NONE; 1390 | } 1391 | 1392 | /***************************************************************************** 1393 | * Register the methods of each class. 1394 | *****************************************************************************/ 1395 | static PyMethodDef C_MPC_MethodMembers[] = // Register the global method list. 1396 | { 1397 | { "setGlobal", (PyCFunction)C_MPC_Global, METH_VARARGS | METH_KEYWORDS, \ 1398 | "Set global setting parameters.\n - dumpLevel: [int] the level of dumped log.\n -|- 0: silent executing.\n -|- 1: [default] dump basic informations.\n -|- 2: dump all informations." }, 1399 | { "readme", (PyCFunction)C_MPC_Help, METH_NOARGS, \ 1400 | "Use it to see readme and some useful instructions." }, 1401 | { nullptr, nullptr, 0, nullptr } 1402 | }; 1403 | 1404 | static PyMethodDef C_MPDC_MethodMembers[] = // Register the member methods of Decoder. 1405 | { // This step add the methods to the C-API of the class. 1406 | { "FFmpegSetup", (PyCFunction)C_MPDC_Setup, METH_VARARGS | METH_KEYWORDS, \ 1407 | "Reset the decoder and the video format.\n - videoPath: [str/bytes] the path of decoded video file." }, 1408 | { "resetPath", (PyCFunction)C_MPDC_resetPath, METH_VARARGS | METH_KEYWORDS, \ 1409 | "Reset the path of decoded video.\n - videoPath: [str/bytes] the path of decoded video file." }, 1410 | { "ExtractFrame", (PyCFunction)C_MPDC_ExtractFrame, METH_VARARGS | METH_KEYWORDS, \ 1411 | "Extract a series of continius frames at the specific position.\n - framePos: [int] the start position of the decoder.\n - frameNum: [int] the expected number of extracted frames." }, 1412 | { "ExtractFrameByTime", (PyCFunction)C_MPDC_ExtractFrame_Time, METH_VARARGS | METH_KEYWORDS, \ 1413 | "Extract a series of continius frames at the specific position (time based).\n - timePos: [double] the start position (second) of the decoder.\n - frameNum: [int] the expected number of extracted frames." }, 1414 | { "ExtractGOP", (PyCFunction)C_MPDC_ExtractGOP, METH_VARARGS | METH_KEYWORDS, \ 1415 | "Extract a series of continius frames as a GOP at the specific position.\n - framePos: [int] the start position of the decoder." }, 1416 | { "ExtractGOPByTime", (PyCFunction)C_MPDC_ExtractGOP_Time, METH_VARARGS | METH_KEYWORDS, \ 1417 | "Extract a series of continius frames as a GOP at the specific position (time based).\n - timePos: [double] the start position (second) of the decoder." }, 1418 | { "ResetGOPPosition", (PyCFunction)C_MPDC_setGOPPosition, METH_VARARGS | METH_KEYWORDS, \ 1419 | "Reset the start position of GOP flow.\n - framePos: [int] the start position of the decoder.\n - timePos: [double] the start position (second) of the decoder." }, 1420 | { "clear", (PyCFunction)C_MPDC_Clear, METH_NOARGS, \ 1421 | "Clear all states (except the videoPath)." }, 1422 | { "dumpFile", (PyCFunction)C_MPDC_DumpFile, METH_NOARGS, \ 1423 | "Show current state of formatContex." }, 1424 | { "setParameter", (PyCFunction)C_MPDC_setParam, METH_VARARGS | METH_KEYWORDS, \ 1425 | "Set the optional parameters of 'Setup' & 'Extract' functions via different methods.\n - widthDst: [int] the width of destination (frame), if <=0 (default), it would take no effect.\n - heightDst: [int] the height of destination (frame), if <=0 (default), it would take no effect.\n - nthread: [int] number of decoder threads." }, 1426 | { "getParameter", (PyCFunction)C_MPDC_getParam, METH_VARARGS | METH_KEYWORDS, \ 1427 | "Input a parameter's name to get it.\n - paramName: [str/bytes] the name of needed parameter. If set empty, would return all key params.\n -|- videoPath: [str] the current path of the read video.\n -|- width/height: [int] the size of one frame.\n -|- frameCount: [int] the number of returned frames in the last ExtractFrame().\n -|- coderName: [str] the name of the decoder.\n -|- nthread: [int] number of decoder threads.\n -|- duration: [double] the total seconds of this video.\n -|- estFrameNum: [int] the estimated total frame number(may be not accurate).\n -|- avgFrameRate: [double] the average of FPS." }, 1428 | { nullptr, nullptr, 0, nullptr } 1429 | }; 1430 | 1431 | static PyMethodDef C_MPEC_MethodMembers[] = // Register the member methods of Encoder. 1432 | { // This step add the methods to the C-API of the class. 1433 | { "FFmpegSetup", (PyCFunction)C_MPEC_Setup, METH_VARARGS | METH_KEYWORDS, \ 1434 | "Open the encoded video and reset the encoder.\n - videoPath: [str/bytes] the path of encoded(written) video file." }, 1435 | { "resetPath", (PyCFunction)C_MPEC_resetPath, METH_VARARGS | METH_KEYWORDS, \ 1436 | "Reset the output path of encoded video.\n - videoPath: [str/bytes] the path of encoded video file." }, 1437 | { "EncodeFrame", (PyCFunction)C_MPEC_EncodeFrame, METH_VARARGS | METH_KEYWORDS, \ 1438 | "Encode one frame.\n - PyArrayFrame: [ndarray] the frame that needs to be encoded." }, 1439 | { "setParameter", (PyCFunction)C_MPEC_setParam, METH_VARARGS | METH_KEYWORDS, \ 1440 | "Set the necessary parameters of 'Setup' & 'Encode' functions via different methods.\n - decoder: [MpegDecoder / MpegClient] copy metadata from a known decoder.\n - configDict: [dict] a config dict returned by getParameter().\n - videoPath: [str/bytes] the current path of the encoded video.\n - codecName: [str/bytes] the name of the encoder.\n - nthread: [int] number of encoder threads.\n - bitRate: [float] the indended bit rate (Kb/s).\n - width/height: [int] the size of one encoded (scaled) frame.\n - widthSrc/heightSrc: [int] the size of one input frame, if set <=0, these parameters would not be enabled.\n - GOPSize: [int] the number of frames in a GOP.\n - maxBframe: [int] the maximal number of B frames in a GOP.\n - frameRate: [tuple] a 2-dim tuple indicating the FPS(num, den) of the stream." }, 1441 | { "getParameter", (PyCFunction)C_MPEC_getParam, METH_VARARGS | METH_KEYWORDS, \ 1442 | "Input a parameter's name to get it.\n - paramName: [str/bytes] the name of needed parameter. If set empty, would return all key params.\n -|- videoPath: [str] the current path of the encoded video.\n -|- codecName: [str] the name of the encoder.\n -|- nthread: [int] number of encoder threads.\n -|- bitRate: [float] the indended bit rate (Kb/s).\n -|- width/height: [int] the size of one encoded (scaled) frame.\n -|- widthSrc/heightSrc: [int] the size of one input frame, if set <=0, these parameters would not be enabled.\n -|- GOPSize: [int] the number of frames in a GOP.\n -|- maxBframe: [int] the maximal number of B frames in a GOP.\n -|- frameRate: [tuple] a 2-dim tuple indicating the FPS(num, den) of the stream." }, 1443 | { "clear", (PyCFunction)C_MPEC_Clear, METH_NOARGS, \ 1444 | "Clear all states." }, 1445 | { "dumpFile", (PyCFunction)C_MPEC_DumpFile, METH_NOARGS, \ 1446 | "Show current state of formatContex." }, 1447 | { "FFmpegClose", (PyCFunction)C_MPEC_Close, METH_NOARGS, \ 1448 | "Close currently encoded video and write the end code of a MPEG file." }, 1449 | { nullptr, nullptr, 0, nullptr } 1450 | }; 1451 | 1452 | static PyMethodDef C_MPCT_MethodMembers[] = // Register the member methods of Encoder. 1453 | { // This step add the methods to the C-API of the class. 1454 | { "FFmpegSetup", (PyCFunction)C_MPCT_Setup, METH_VARARGS | METH_KEYWORDS, \ 1455 | "Reset the decoder and the video format.\n - videoAddress: [str/bytes] the path of decoded video file." }, 1456 | { "resetPath", (PyCFunction)C_MPCT_resetPath, METH_VARARGS | METH_KEYWORDS, \ 1457 | "Reset the address of decoded video.\n - videoAddress: [str/bytes] the path of decoded video file." }, 1458 | { "start", (PyCFunction)C_MPCT_Start, METH_NOARGS, \ 1459 | "Start the demuxing thread, must be called after FFmpegSetup()." }, 1460 | { "terminate", (PyCFunction)C_MPCT_Terminate, METH_NOARGS, \ 1461 | "Terminate all current demuxing threads, usually used when there is only one thread." }, 1462 | { "ExtractFrame", (PyCFunction)C_MPCT_ExtractFrame, METH_VARARGS | METH_KEYWORDS, \ 1463 | "Extract frames from the current buffer.\n - readSize: [int] the number of extracted frames, should not be larger than cache number. \nIf not set, will be used as the default value." }, 1464 | { "clear", (PyCFunction)C_MPCT_Clear, METH_NOARGS, \ 1465 | "Clear all states (except the videoAddress)." }, 1466 | { "dumpFile", (PyCFunction)C_MPCT_DumpFile, METH_NOARGS, \ 1467 | "Show current state of formatContex." }, 1468 | { "setParameter", (PyCFunction)C_MPCT_setParam, METH_VARARGS | METH_KEYWORDS, \ 1469 | "Set the optional parameters of 'Setup' & 'Extract' functions and the demuxing thread via different methods.\n - widthDst: [int] the width of destination (frame), if <=0 (default), it would take no effect.\n - heightDst: [int] the height of destination (frame), if <=0 (default), it would take no effect.\n - cacheSize: [int] the number of allocated avaliable frames in the cache.\n - readSize: [int] the default value of ExtractFrame().\n - dstFrameRate: [tuple] a 2-dim tuple indicating the destination FPS(num, den) of the stream.\n - nthread: [int] number of decoder threads." }, 1470 | { "getParameter", (PyCFunction)C_MPCT_getParam, METH_VARARGS | METH_KEYWORDS, \ 1471 | "Input a parameter's name to get it.\n - paramName: [str/bytes] the name of needed parameter. If set empty, would return all key params.\n -|- videoAddress: [str] the current path of the read video.\n -|- width/height: [int] the size of one frame.\n -|- frameCount: [int] the number of returned frames in the last ExtractFrame().\n -|- coderName: [str] the name of the decoder.\n -|- nthread: [int] number of decoder threads.\n -|- duration: [double] the total seconds of this video.\n -|- estFrameNum: [int] the estimated total frame number(may be not accurate).\n -|- srcFrameRate: [double] the average of FPS of the source video." }, 1472 | { nullptr, nullptr, 0, nullptr } 1473 | }; 1474 | 1475 | static PyMethodDef C_MPSV_MethodMembers[] = // Register the member methods of Server. 1476 | { // This step add the methods to the C-API of the class. 1477 | { "FFmpegSetup", (PyCFunction)C_MPSV_Setup, METH_VARARGS | METH_KEYWORDS, \ 1478 | "Open the encoded video and reset the encoder.\n - videoAddress: [str/bytes] the path of encoded(written) video file." }, 1479 | { "resetPath", (PyCFunction)C_MPSV_resetPath, METH_VARARGS | METH_KEYWORDS, \ 1480 | "Reset the output path of encoded video.\n - videoAddress: [str/bytes] the path of encoded video file." }, 1481 | { "ServeFrame", (PyCFunction)C_MPSV_ServeFrame, METH_VARARGS | METH_KEYWORDS, \ 1482 | "Encode one frame and send the frame non-blockly.\n - PyArrayFrame: [ndarray] the frame that needs to be encoded." }, 1483 | { "ServeFrameBlock", (PyCFunction)C_MPSV_ServeFrameBlock, METH_VARARGS | METH_KEYWORDS, \ 1484 | "Encode one frame and send the frame blockly. This method is suggested to be used in sub-processes.\n - PyArrayFrame: [ndarray] the frame that needs to be encoded." }, 1485 | { "setParameter", (PyCFunction)C_MPSV_setParam, METH_VARARGS | METH_KEYWORDS, \ 1486 | "Set the necessary parameters of 'Setup' & 'Serve' functions via different methods.\n - decoder: [MpegDecoder / MpegClient] copy metadata from a known decoder.\n - configDict: [dict] a config dict returned by getParameter().\n - videoAddress: [str/bytes] the current path of the encoded video.\n - codecName: [str/bytes] the name of the encoder.\n - nthread: [int] number of encoder threads.\n - bitRate: [float] the indended bit rate (Kb/s).\n - width/height: [int] the size of one encoded (scaled) frame.\n - widthSrc/heightSrc: [int] the size of one input frame, if set <=0, these parameters would not be enabled.\n - GOPSize: [int] the number of frames in a GOP.\n - maxBframe: [int] the maximal number of B frames in a GOP.\n - frameRate: [tuple] a 2-dim tuple indicating the FPS(num, den) of the stream.\n - frameAhead: [int] The number of ahead frames. This value is suggested to be larger than the GOPSize.." }, 1487 | { "getParameter", (PyCFunction)C_MPSV_getParam, METH_VARARGS | METH_KEYWORDS, \ 1488 | "Input a parameter's name to get it.\n - paramName: [str/bytes] the name of needed parameter. If set empty, would return all key params.\n -|- videoAddress: [str] the current path of the encoded video.\n -|- codecName: [str] the name of the encoder.\n -|- formatName: [str] the format name of the stream.\n -|- nthread: [int] number of encoder threads.\n -|- bitRate: [float] the indended bit rate (Kb/s).\n -|- width/height: [int] the size of one encoded (scaled) frame.\n -|- widthSrc/heightSrc: [int] the size of one input frame, if set <=0, these parameters would not be enabled.\n -|- GOPSize: [int] the number of frames in a GOP.\n -|- maxBframe: [int] the maximal number of B frames in a GOP.\n -|- frameRate: [tuple] a 2-dim tuple indicating the FPS(num, den) of the stream.\n -|- waitRef: [float] The reference used for sync. waiting.\n -|- ptsAhead: [int] The ahead time duration in the uit of time stamp." }, 1489 | { "clear", (PyCFunction)C_MPSV_Clear, METH_NOARGS, \ 1490 | "Clear all states." }, 1491 | { "dumpFile", (PyCFunction)C_MPSV_DumpFile, METH_NOARGS, \ 1492 | "Show current state of formatContex." }, 1493 | { "FFmpegClose", (PyCFunction)C_MPSV_Close, METH_NOARGS, \ 1494 | "Close currently encoded video and write the end code of a MPEG file." }, 1495 | { nullptr, nullptr, 0, nullptr } 1496 | }; 1497 | 1498 | /***************************************************************************** 1499 | * Declaration of the class, including the name, information and the members. 1500 | * This is the top-level packing of the class APIs. 1501 | *****************************************************************************/ 1502 | static PyTypeObject C_MPDC_ClassInfo = 1503 | { 1504 | PyVarObject_HEAD_INIT(nullptr, 0)"mpegCoder.MpegDecoder", // The implementation of the __class__.__name__. 1505 | sizeof(C_MpegDecoder), // The memory length of the class. This value is required for PyObject_New. 1506 | 0, 1507 | (destructor)C_MPDC_Destruct, // Destructor. 1508 | 0, 1509 | 0, 1510 | 0, 1511 | 0, 1512 | (reprfunc)C_MPDC_Repr, // __repr__ method. 1513 | 0, 1514 | 0, 1515 | 0, 1516 | 0, 1517 | 0, 1518 | (reprfunc)C_MPDC_Str, // __str__ method. 1519 | 0, 1520 | 0, 1521 | 0, 1522 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // If no methods are provided, this value is Py_TPFLAGS_DEFAULE. 1523 | "This class has wrapped the C-API of FFmpeg decoder so that users could call its methods\n to decode the frame data in python quickly.", // __doc__, the docstring of the class. 1524 | 0, 1525 | 0, 1526 | 0, 1527 | 0, 1528 | 0, 1529 | 0, 1530 | C_MPDC_MethodMembers, // The collection of all method members. 1531 | C_MPDC_DataMembers, // THe collection of all data members. 1532 | 0, 1533 | 0, 1534 | 0, 1535 | 0, 1536 | 0, 1537 | 0, 1538 | (initproc)C_MPDC_init, // Constructor. 1539 | 0, 1540 | }; 1541 | 1542 | static PyTypeObject C_MPEC_ClassInfo = 1543 | { 1544 | PyVarObject_HEAD_INIT(nullptr, 0)"mpegCoder.MpegEncoder", // The implementation of the __class__.__name__. 1545 | sizeof(C_MpegEncoder), // The memory length of the class. This value is required for PyObject_New. 1546 | 0, 1547 | (destructor)C_MPEC_Destruct, // Destructor. 1548 | 0, 1549 | 0, 1550 | 0, 1551 | 0, 1552 | (reprfunc)C_MPEC_Repr, // __repr__ method. 1553 | 0, 1554 | 0, 1555 | 0, 1556 | 0, 1557 | 0, 1558 | (reprfunc)C_MPEC_Str, // __str__ method. 1559 | 0, 1560 | 0, 1561 | 0, 1562 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // If no methods are provided, this value is Py_TPFLAGS_DEFAULE. 1563 | "This class has wrapped the C-API of FFmpeg encoder so that users could call its methods\n to encode frames by using numpy-data quickly.", // __doc__, the docstring of the class. 1564 | 0, 1565 | 0, 1566 | 0, 1567 | 0, 1568 | 0, 1569 | 0, 1570 | C_MPEC_MethodMembers, // The collection of all method members. 1571 | C_MPEC_DataMembers, // THe collection of all data members. 1572 | 0, 1573 | 0, 1574 | 0, 1575 | 0, 1576 | 0, 1577 | 0, 1578 | (initproc)C_MPEC_init, // Constructor. 1579 | 0, 1580 | }; 1581 | 1582 | static PyTypeObject C_MPCT_ClassInfo = 1583 | { 1584 | PyVarObject_HEAD_INIT(nullptr, 0)"mpegCoder.MpegClient", // The implementation of the __class__.__name__. 1585 | sizeof(C_MpegClient), // The memory length of the class. This value is required for PyObject_New. 1586 | 0, 1587 | (destructor)C_MPCT_Destruct, // Destructor. 1588 | 0, 1589 | 0, 1590 | 0, 1591 | 0, 1592 | (reprfunc)C_MPCT_Repr, // __repr__ method. 1593 | 0, 1594 | 0, 1595 | 0, 1596 | 0, 1597 | 0, 1598 | (reprfunc)C_MPCT_Str, // __str__ method. 1599 | 0, 1600 | 0, 1601 | 0, 1602 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // If no methods are provided, this value is Py_TPFLAGS_DEFAULE. 1603 | "This class has wrapped the C-API of FFmpeg demuxer so that users could call its methods\n to demux the network stream in python quickly.", // __doc__, the docstring of the class. 1604 | 0, 1605 | 0, 1606 | 0, 1607 | 0, 1608 | 0, 1609 | 0, 1610 | C_MPCT_MethodMembers, // The collection of all method members. 1611 | C_MPCT_DataMembers, // THe collection of all data members. 1612 | 0, 1613 | 0, 1614 | 0, 1615 | 0, 1616 | 0, 1617 | 0, 1618 | (initproc)C_MPCT_init, // Constructor. 1619 | 0, 1620 | }; 1621 | 1622 | static PyTypeObject C_MPSV_ClassInfo = 1623 | { 1624 | PyVarObject_HEAD_INIT(nullptr, 0)"mpegCoder.MpegServer", // The implementation of the __class__.__name__. 1625 | sizeof(C_MpegServer), // The memory length of the class. This value is required for PyObject_New. 1626 | 0, 1627 | (destructor)C_MPSV_Destruct, // Destructor. 1628 | 0, 1629 | 0, 1630 | 0, 1631 | 0, 1632 | (reprfunc)C_MPSV_Repr, // __repr__ method. 1633 | 0, 1634 | 0, 1635 | 0, 1636 | 0, 1637 | 0, 1638 | (reprfunc)C_MPSV_Str, // __str__ method. 1639 | 0, 1640 | 0, 1641 | 0, 1642 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // If no methods are provided, this value is Py_TPFLAGS_DEFAULE. 1643 | "This class has wrapped the C-API of FFmpeg stream server so that users could call its methods\n to server streamed frames by using numpy-data quickly.", // __doc__, the docstring of the class. 1644 | 0, 1645 | 0, 1646 | 0, 1647 | 0, 1648 | 0, 1649 | 0, 1650 | C_MPSV_MethodMembers, // The collection of all method members. 1651 | C_MPSV_DataMembers, // THe collection of all data members. 1652 | 0, 1653 | 0, 1654 | 0, 1655 | 0, 1656 | 0, 1657 | 0, 1658 | (initproc)C_MPSV_init, // Constructor. 1659 | 0, 1660 | }; 1661 | 1662 | /***************************************************************************** 1663 | * Decleartion of the module. 1664 | * This is the top-level packing of the module APIs. 1665 | *****************************************************************************/ 1666 | static PyModuleDef ModuleInfo = 1667 | { 1668 | PyModuleDef_HEAD_INIT, 1669 | "mpegCoder", // The __name__ of the module. 1670 | "A FFmpeg module which could provide a class for encode/decode a video in any format.", // __doc__; The docstring of the module. 1671 | -1, 1672 | nullptr, nullptr, nullptr, nullptr, nullptr 1673 | }; 1674 | 1675 | #endif 1676 | --------------------------------------------------------------------------------