79 Commits
Author SHA1 Message Date
jfmcarreira 944bc0116b fix: build errors 2024-10-03 01:31:38 +01:00
jfmcarreira 303d15cbc2 Merge remote-tracking branch 'upstream/devel' into devel 2024-10-02 23:51:57 +01:00
jfmcarreira 05be89459e refactor: modernize code 2024-10-02 23:33:21 +01:00
jfmcarreira 0cf79bf7a5 ci: update build workflow 2024-04-28 01:06:14 +01:00
jfmcarreira e0db35d087 build: remove libfmt dependency 2024-04-27 22:18:18 +01:00
jfmcarreira 0d70ab8a84 build(fmt): find missing depency to libfmt 2023-09-24 21:58:58 +01:00
jfmcarreira d1e9a1cb2d fix(lib): add missing include and replace vector with span 2023-09-24 21:05:03 +01:00
Joao Carreira 18c69b8529 build(app): remove Qt6 dependency from qcustomplot 2023-04-29 01:56:40 +01:00
Joao Carreira 2f9abe7e47 fix(qt): make Qt6 optional 2023-04-28 23:32:36 +01:00
Joao Carreira 2f1d8dbb8b ci: add coverage to build without Qt6 2023-04-28 22:38:25 +01:00
Joao Carreira a2262ca3a7 feat(tests): update catch to version 3 2023-04-02 22:29:25 +01:00
Joao Carreira acb04c2360 fix: build errors and add support for Qt6 2023-03-28 01:07:32 +01:00
Joao Carreira cbefa2be2e refactor(pixel): add nameless namespace to CalypPixel 2022-11-13 21:34:43 +00:00
Joao Carreira 7dedd2f388 refactor(modules): remove the use of a macro to create a module 2022-11-13 21:33:54 +00:00
Joao Carreira aa2725e427 Merge branch 'master' into devel 2022-03-07 00:17:00 +00:00
Joao Carreira 8358ea0a3a Fix build on mac due to FFmpeg 2022-02-18 23:35:21 +00:00
jfmcarreira 8e15de8ce5 Merge branch 'master' into devel 2022-02-05 14:06:25 +00:00
jfmcarreira da40950ebe Minor changes in code format and repo 2022-02-05 14:06:09 +00:00
jfmcarreira 3380ad18b8 Work on resources 2022-02-05 14:01:20 +00:00
jfmcarreira d3c665605e Remove ivars that keep the active subwindow 2021-12-26 12:23:08 +00:00
jfmcarreira d01a91651b Finish refactor of load and format stream 2021-12-26 12:09:18 +00:00
jfmcarreira cd547a964b Fix keeping an history of open files 2021-12-25 02:51:02 +00:00
jfmcarreira f43e6e2634 Inital refactor to use resource independent from the video windows 2021-12-24 16:43:23 +00:00
jfmcarreira 7f8be0cb0e Merge branch 'master' into devel 2021-12-19 15:25:20 +00:00
jfmcarreira 17e2a6084a Fix resouce worker stop 2021-12-19 15:25:01 +00:00
jfmcarreira c1dd45662a Code formatting 2021-12-19 14:16:07 +00:00
jfmcarreira 77617ce53a Replace atomic_flag with plain atomic 2021-12-19 01:15:39 +00:00
jfmcarreira 6789ada346 Remove spin lock from the resource handler and avoid threads on a single frame stream 2021-12-19 00:55:42 +00:00
jfmcarreira f4c69fd894 Fix module tests 2021-12-18 23:53:10 +00:00
jfmcarreira c24ddcdc59 Cast to avoid recursion std::string 2021-12-18 23:44:54 +00:00
jfmcarreira 496bb54450 Fix scroll bug 2021-12-18 23:44:22 +00:00
jfmcarreira a048d2e0df Clean constructor of SubWindowAbstract 2021-12-18 23:42:40 +00:00
jfmcarreira 9d28051f38 Use std::span to give access to RGB buffer 2021-12-18 22:24:46 +00:00
jfmcarreira 8717338bf9 Modernise CalypModules factory 2021-12-18 22:24:03 +00:00
jfmcarreira 84865a039f Version bump 2.2.0 2021-12-05 00:41:03 +00:00
jfmcarreira 96b7576a1d Fix optional opencv dependency 2021-12-03 23:08:40 +00:00
jfmcarreira b61fd9d0e0 Remove type_safe library 2021-12-03 22:36:11 +00:00
jfmcarreira 5b4cdddde4 Disable DEBUG_ASSERT 2021-11-28 23:27:33 +00:00
jfmcarreira c43cb2bd0a Version bump 2.1.0 2021-11-28 20:36:33 +00:00
jfmcarreira e6970fb953 Fix windows build 2021-11-28 20:34:41 +00:00
jfmcarreira aac02a9959 Fix missing include 2021-11-28 18:23:05 +00:00
jfmcarreira 500e0e85ba Add macro to protect against the Qt version 2021-11-28 01:46:37 +00:00
jfmcarreira d4886a7fee Fix fetch content to build main product 2021-11-27 23:28:27 +00:00
jfmcarreira f3919ac8e8 Change cmake fetch content 2021-11-27 22:51:58 +00:00
jfmcarreira 562fd915fe Add build checks 2021-11-27 01:04:51 +00:00
jfmcarreira f3df40cdf7 Code cleanup 2021-11-27 00:52:32 +00:00
jfmcarreira 1bb2773abc Add support to filter components to display 2021-11-27 00:45:56 +00:00
jfmcarreira a5e0554286 Tidy up CalypFrame 2021-10-30 20:01:20 +01:00
jfmcarreira dc56de6f30 Fix memory leak in modules tests 2021-10-30 17:53:12 +01:00
jfmcarreira 0cc89ab949 Fix problem creating opencv mat from CalypFrame 2021-10-30 17:49:24 +01:00
jfmcarreira 480a7f1d38 Refactor ClpPixelFormats enum 2021-10-27 23:17:32 +01:00
jfmcarreira bb2a1ac228 Refactor pixel formats enum 2021-10-27 23:07:46 +01:00
jfmcarreira 90a5c32bb6 Fix option errors and add dummy module 2021-10-24 22:18:25 +01:00
jfmcarreira acc9d8ea98 Fix modules errors 2021-10-24 17:55:52 +01:00
jfmcarreira 6f91b6c04f Refactor CalypOption 2021-10-24 17:26:13 +01:00
jfmcarreira b1ca7dff0b Improve safety of class methods 2021-10-24 11:25:22 +01:00
jfmcarreira f5df1b3f9d Refactor code based on lib changes 2021-10-24 00:56:39 +01:00
jfmcarreira bd1bbef22b Fix CalypStream and CalypFrame methods 2021-10-23 23:38:03 +01:00
jfmcarreira 3a9aa5e498 Fix warnings and remove warnings are erros from tests checks 2021-10-20 00:54:10 +01:00
jfmcarreira 5499312fca Fix compilation erros 2021-10-20 00:28:49 +01:00
jfmcarreira 93cf60e34a Improvements on CalypModuleIf
Add type safe flags
Replace MACRO with templates (WIP)
2021-10-19 23:42:18 +01:00
jfmcarreira 09ec5213c3 Fix compilation errors and add new tests 2021-10-15 23:40:41 +01:00
jfmcarreira 26f3dc7612 Fix wrong filename in tests 2021-10-13 00:21:22 +01:00
jfmcarreira 6ce220be82 Check if file exists before running tests 2021-10-13 00:08:33 +01:00
jfmcarreira cc84c42fd4 Checkout LFS content for tests 2021-10-12 23:57:08 +01:00
jfmcarreira 8d2a9e6100 Fix build.yml 2021-10-12 21:10:56 +01:00
jfmcarreira c05aa73e86 Fix github action 2021-10-11 23:25:03 +01:00
jfmcarreira ddc9f40329 Fix repository with test data (fix last commit) 2021-10-11 23:14:10 +01:00
jfmcarreira e87049dccf Fix repository with test data 2021-10-11 23:12:50 +01:00
jfmcarreira 1c1afa7bfc Code clean up and add initial support to run tests in CI enviroment 2021-10-11 23:07:08 +01:00
jfmcarreira 366d69b5c9 Always use RAW format if first try to open file fails 2021-10-10 23:04:39 +01:00
jfmcarreira 26a718a06a Open .raw formats as raw video 2021-10-10 22:26:31 +01:00
jfmcarreira 3b31453221 Add support to signall if the format supports user configuration 2021-10-10 22:25:32 +01:00
jfmcarreira b7ad00a4c5 Minor refactor CalypStream header and format handler 2021-10-10 19:48:14 +01:00
jfmcarreira fbbd77bfbf Merge branch 'devel' 2021-10-10 18:05:23 +01:00
jfmcarreira be06ca656d Add new window classes for modules and streams 2021-10-10 15:13:42 +01:00
jfmcarreira 665cd0bb1c Add new window classes 2021-10-09 20:02:19 +01:00
jfmcarreira 1c0321a705 Fix histogram widget 2021-10-09 20:01:02 +01:00
jfmcarreira 5b9e16a708 Make CalypPixel work on stack 2021-10-09 18:31:21 +01:00
152 changed files with 19267 additions and 18309 deletions

No files matched your search

+37 -38
View File
@@ -1,19 +1,19 @@
---
BasedOnStyle: Google
Language: Cpp
ColumnLimit: 0
BasedOnStyle: Google
Language: Cpp
ColumnLimit: 120
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands: true
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
@@ -21,17 +21,17 @@ AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterNamespace: true
AfterClass: true
AfterEnum: true
AfterFunction: true
AfterStruct: true
AfterUnion: true
AfterControlStatement: true
AfterObjCDeclaration: true
BeforeCatch: true
BeforeElse: true
IndentBraces: false
AfterNamespace: true
AfterClass: true
AfterEnum: true
AfterFunction: true
AfterStruct: true
AfterUnion: true
AfterControlStatement: true
AfterObjCDeclaration: true
BeforeCatch: true
BeforeElse: true
IndentBraces: false
BreakBeforeBraces: Custom
BreakBeforeBinaryOperators: None
BreakBeforeInheritanceComma: false
@@ -40,31 +40,31 @@ BreakConstructorInitializersBeforeComma: true
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
CommentPragmas: '^ IWYU pragma:'
CommentPragmas: "^ IWYU pragma:"
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
ForEachMacros: [foreach, Q_FOREACH, BOOST_FOREACH]
IncludeCategories:
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
- Regex: '^<.*\.h>'
Priority: 1
- Regex: "^<.*"
Priority: 2
- Regex: ".*"
Priority: 3
IncludeIsMainRegex: "([-_](test|unittest))?$"
IndentCaseLabels: false
IndentWidth: 2
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MacroBlockBegin: ""
MacroBlockEnd: ""
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
@@ -77,21 +77,20 @@ PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: false
ReflowComments: true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SortIncludes: true
SortIncludes: true
SpacesInParentheses: true
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 2
UseTab: Never
...
Standard: Auto
TabWidth: 2
UseTab: Never
---
+64 -41
View File
@@ -1,43 +1,66 @@
---
Checks: 'clang-diagnostic-*,clang-analyzer-*,cppcoreguidelines-*,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-cppcoreguidelines-pro-bounds-pointer-arithmetic'
WarningsAsErrors: ''
HeaderFilterRegex: ''
AnalyzeTemporaryDtors: false
FormatStyle: none
Checks: "*,-modernize-use-nodiscard,-llvmlibc-*,-fuchsia-trailing-return,-fuchsia*,-altera-*,-cppcoreguidelines-pro-bounds-constant-array-index,-bugprone-implicit-widening-of-multiplication-result,-readability-magic-numbers,-cppcoreguidelines-avoid-magic-numbers, -readability-identifier-length"
WarningsAsErrors: ""
HeaderFilterRegex: ""
FormatStyle: file
CheckOptions:
- key: llvm-else-after-return.WarnOnConditionVariables
value: '0'
- key: modernize-loop-convert.MinConfidence
value: reasonable
- key: modernize-replace-auto-ptr.IncludeStyle
value: llvm
- key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons
value: '0'
- key: google-readability-namespace-comments.ShortNamespaceLines
value: '10'
- key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField
value: '0'
- key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
value: '1'
- key: cert-dcl16-c.NewSuffixes
value: 'L;LL;LU;LLU'
- key: google-readability-braces-around-statements.ShortStatementLines
value: '1'
- key: modernize-pass-by-value.IncludeStyle
value: llvm
- key: google-readability-namespace-comments.SpacesBeforeComments
value: '2'
- key: modernize-loop-convert.MaxCopySize
value: '16'
- key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors
value: '1'
- key: modernize-use-nullptr.NullMacros
value: 'NULL'
- key: llvm-qualified-auto.AddConstToQualified
value: '0'
- key: modernize-loop-convert.NamingStyle
value: CamelCase
- key: llvm-else-after-return.WarnOnUnfixable
value: '0'
- key: google-readability-function-size.StatementThreshold
value: '800'
- key: readability-identifier-naming.ClassCase
value: CamelCase
- key: readability-identifier-naming.ClassMemberCase
value: camelBack
- key: readability-identifier-naming.ClassMethodCase
value: camelBack
- key: readability-identifier-naming.ParameterCase
value: camelBack
- key: readability-identifier-naming.PrivateMemberCase
value: camelBack
- key: readability-identifier-naming.PrivateMemberPrefix
value: m_
- key: readability-identifier-length.IgnoredVariableNames
value: "^(id|to)$"
- key: llvm-else-after-return.WarnOnConditionVariables
value: "0"
- key: modernize-loop-convert.MinConfidence
value: reasonable
- key: modernize-replace-auto-ptr.IncludeStyle
value: llvm
- key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons
value: "0"
- key: google-readability-namespace-comments.ShortNamespaceLines
value: "10"
- key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField
value: "0"
- key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
value: "1"
- key: cert-dcl16-c.NewSuffixes
value: "L;LL;LU;LLU"
- key: google-readability-braces-around-statements.ShortStatementLines
value: "1"
- key: modernize-pass-by-value.IncludeStyle
value: llvm
- key: google-readability-namespace-comments.SpacesBeforeComments
value: "2"
- key: modernize-loop-convert.MaxCopySize
value: "16"
- key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors
value: "1"
- key: modernize-use-nullptr.NullMacros
value: "NULL"
- key: llvm-qualified-auto.AddConstToQualified
value: "0"
- key: modernize-loop-convert.NamingStyle
value: CamelCase
- key: llvm-else-after-return.WarnOnUnfixable
value: "0"
- key: google-readability-function-size.StatementThreshold
value: "800"
- key: readability-magic-numbers.IgnorePowersOf2IntegerValues
value: "1"
- key: readability-braces-around-statements.ShortStatementLines
value: "1"
- key: google-readability-braces-around-statements.ShortStatementLines
value: "1"
- key: hicpp-braces-around-statements.ShortStatementLines
value: "1"
- key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
value: "1"
+70 -15
View File
@@ -1,4 +1,4 @@
name: Build on Linux
name: Build/Test Pipeline
on:
push:
@@ -6,32 +6,87 @@ on:
- master
- devel
pull_request:
branches: [ master ]
branches: [master]
env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Release
jobs:
build:
check-build-linux:
# The CMake configure and build commands are platform agnostic and should work equally
# well on Windows or Mac. You can convert this to a matrix build if you need
# cross-platform coverage.
# See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
name: Build (Linux)
steps:
- name: Install dependencies
run: sudo apt-get update && sudo apt-get install gcc-10 g++-10 cmake qtbase5-dev libavcodec-dev libavformat-dev libavutil-dev libopencv-dev libopencv-video-dev libopencv-contrib-dev
- name: Install dependencies
run: sudo apt-get update && sudo apt-get install cmake qtbase5-dev libavcodec-dev libavformat-dev libavutil-dev libopencv-dev libopencv-video-dev libopencv-contrib-dev
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: cmake -B ${{github.workspace}}/build -D CMAKE_C_COMPILER=gcc-10 -D CMAKE_CXX_COMPILER=g++-10 -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_WERROR=ON
- name: Build with default options
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: |
cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_WERROR=ON
cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
- name: Build
# Build your program with the given configuration
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
- name: Build without threads
run: |
cmake -B ${{github.workspace}}/build-without-thread -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_WERROR=ON -DCALYP_MANAGED_RESOURCES=OFF -DCALYP_THREADED_MODULES=OFF
cmake --build ${{github.workspace}}/build-without-thread --config ${{env.BUILD_TYPE}}
- name: Build without dependencies
run: |
cmake -B ${{github.workspace}}/build-without-deps -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_WERROR=ON -DUSE_OPENCV=OFF -DUSE_FFMPEG=OFF
cmake --build ${{github.workspace}}/build-without-deps --config ${{env.BUILD_TYPE}}
- name: Install Qt&
run: sudo apt-get install qt6-base-dev
- name: Build with Qt& (autodetect)
run: |
cmake -B ${{github.workspace}}/build-qt6 -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_WERROR=ON
cmake --build ${{github.workspace}}/build-qt6 --config ${{env.BUILD_TYPE}}
check-build-macos:
name: Build (macOS)
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: Install dependencies
run: brew install cmake qt opencv ffmpeg
- name: Build with default options
run: |
cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DUSE_WERROR=ON
cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
check-tests-linux:
name: Tests (Linux)
runs-on: ubuntu-24.04
needs: check-build-linux
steps:
- name: Install dependencies
run: sudo apt-get update && sudo apt-get install cmake qtbase5-dev qt6-base-dev libavcodec-dev libavformat-dev libavutil-dev libopencv-dev libopencv-video-dev libopencv-contrib-dev
- uses: actions/checkout@v4
- name: Check out tests data
uses: actions/checkout@master
with:
repository: "pixlra/calyp-testdata"
path: ${{github.workspace}}/tests_data
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DBUILD_TESTS=ON -DCALYP_TEST_DATA_DIR=${{github.workspace}}/tests_data
- name: Build
# Build your program with the given configuration
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
- name: CalypLib tests
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} -t test
+3 -1
View File
@@ -1,5 +1,7 @@
# Created by https://www.gitignore.io/api/c++,clion,linux
# Edit at https://www.gitignore.io/?templates=c++,clion,linux
deps/**
templates/**
### C++ ###
# Prerequisites
@@ -146,4 +148,4 @@ doc/
compile_commands.json
# Build dirs
build*
build*
+5 -5
View File
@@ -20,10 +20,10 @@ repos:
entry: cmake -B build
pass_filenames: false
language: system
- id: cmake-build
name: Cmake Build
entry: cmake --build build
pass_filenames: false
language: system
#- id: cmake-build
#name: Cmake Build
#entry: cmake --build build
#pass_filenames: false
#language: system
+21 -13
View File
@@ -18,8 +18,8 @@ SET(PROJECT_LIBRARY
)
SET(CALYP_VERSION_MAJOR "2")
SET(CALYP_VERSION_MINOR "0")
SET(CALYP_VERSION_PATCH "1")
SET(CALYP_VERSION_MINOR "2")
SET(CALYP_VERSION_PATCH "0")
SET(CALYP_VERSION
"${CALYP_VERSION_MAJOR}.${CALYP_VERSION_MINOR}.${CALYP_VERSION_PATCH}"
CACHE INTERNAL "" FORCE
@@ -47,7 +47,7 @@ OPTION(BUILD_APP "Build GUI Application" ON)
OPTION(BUILD_TOOLS "Build Command Line Application" ON)
OPTION(BUILD_EXAMPLES "Build Examples" OFF)
OPTION(BUILD_DOC "Build Documentation" OFF)
OPTION(BUILD_TESTS "Build Google Tests" OFF)
OPTION(BUILD_TESTS "Build Tests" OFF)
OPTION(BUILD_WITH_SANITIZERS "Build with sanitizers" OFF)
OPTION(BUILD_WITH_THREAD_SANITIZER "Build with thread sanitizer" OFF)
@@ -102,7 +102,11 @@ SET(UPDATE_CHANNEL
# ####################################################################################################################################################
# Dependencies
# ####################################################################################################################################################
INCLUDE(FetchContent)
SET(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/deps")
# Doxygen
IF(BUILD_DOC)
FIND_PACKAGE(Doxygen)
SET(BUILD_DOC ${Doxygen_FOUND})
@@ -114,15 +118,20 @@ SET_PACKAGE_PROPERTIES(
TYPE OPTIONAL
)
# Catch2 and Google Tests
IF(BUILD_TESTS)
INCLUDE(FetchContent)
FETCHCONTENT_DECLARE(googletest URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip)
# For Windows: Prevent overriding the parent project's compiler/linker settings
SET(gtest_force_shared_crt
ON
CACHE BOOL "" FORCE
)
FETCHCONTENT_MAKEAVAILABLE(googletest)
FETCHCONTENT_DECLARE(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.3.2
)
SET_PACKAGE_PROPERTIES(
googletest PROPERTIES
URL "https://github.com/google/googletest"
@@ -130,20 +139,17 @@ IF(BUILD_TESTS)
TYPE OPTIONAL
)
FETCHCONTENT_DECLARE(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v2.13.1
)
FETCHCONTENT_MAKEAVAILABLE(Catch2)
SET_PACKAGE_PROPERTIES(
Catch2 PROPERTIES
URL "https://github.com/catchorg/Catch2"
DESCRIPTION "Catch2 unit tests"
TYPE OPTIONAL
)
INCLUDE(${CMAKE_CURRENT_BINARY_DIR}/_deps/catch2-src/contrib/Catch.cmake)
FETCHCONTENT_MAKEAVAILABLE(googletest Catch2)
LIST(APPEND CMAKE_MODULE_PATH ${CMAKE_BINARY_DIR}/deps/catch2-src/extras)
INCLUDE(CTest)
INCLUDE(Catch)
ENABLE_TESTING()
SET(CALYP_TEST_DATA_DIR
@@ -152,6 +158,7 @@ IF(BUILD_TESTS)
)
ENDIF()
# OpenCV
OPTION(USE_OPENCV "Add OpenCV support" ON)
IF(USE_OPENCV)
@@ -177,6 +184,7 @@ SET_PACKAGE_PROPERTIES(
TYPE OPTIONAL
)
# FFmpeg
OPTION(USE_FFMPEG "Add FFMPEG support" ON)
IF(USE_FFMPEG)
FIND_PACKAGE(FFmpeg COMPONENTS AVCODEC AVFORMAT AVUTIL SWSCALE)
@@ -242,7 +250,7 @@ IF(USE_WERROR)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
ENDIF()
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -O0")
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -O0 -DCLP_DEBUG")
IF(BUILD_WITH_SANITIZERS)
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fsanitize=address -fsanitize=leak -fsanitize=undefined")
ENDIF()
+46 -23
View File
@@ -3,19 +3,33 @@
#
INCLUDE_DIRECTORIES(
${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/.. ${CMAKE_CURRENT_SOURCE_DIR}/external ${CMAKE_CURRENT_SOURCE_DIR}/dialog
${CMAKE_CURRENT_SOURCE_DIR}/docks ${CMAKE_CURRENT_SOURCE_DIR}/widgets
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/..
${CMAKE_CURRENT_SOURCE_DIR}/external
${CMAKE_CURRENT_SOURCE_DIR}/dialog
${CMAKE_CURRENT_SOURCE_DIR}/docks
${CMAKE_CURRENT_SOURCE_DIR}/widgets
${CMAKE_CURRENT_SOURCE_DIR}/models
)
OPTION(USE_QTDBUS "Build with QtDBus" ON)
OPTION(USE_QT6 "Build with Qt6" ON)
OPTION(USE_QTDBUS "Build with QtDBus" OFF)
OPTION(USE_FERVOR "Add Fervor support" OFF)
OPTION(CALYP_MANAGED_RESOURCES "Handle streams in separate threads" ON)
OPTION(CALYP_THREADED_MODULES "Use threads for modules" ON)
IF(${USE_QT6})
FIND_PACKAGE(Qt6 QUIET COMPONENTS Core Gui Widgets Concurrent)
IF (NOT Qt6_FOUND)
FIND_PACKAGE(Qt5 REQUIRED COMPONENTS Core Gui Widgets Concurrent)
ENDIF()
ELSE()
FIND_PACKAGE(Qt5 REQUIRED COMPONENTS Core Gui Widgets Concurrent)
ENDIF()
ADD_SUBDIRECTORY(external)
FIND_PACKAGE(Qt5 REQUIRED COMPONENTS Core Gui Widgets Concurrent)
LIST(APPEND QT_LINKER_LIBS Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Concurrent)
LIST(APPEND QT_LINKER_LIBS Qt::Core Qt::Gui Qt::Widgets Qt::Concurrent)
LIST(APPEND QT_MODULES Core Gui Widgets Concurrent)
IF(USE_QTDBUS)
@@ -31,11 +45,12 @@ IF(USE_QTDBUS)
${Qt5DBus_FOUND}
PARENT_SCOPE
)
LIST(APPEND QT_LINKER_LIBS Qt5::DBus)
LIST(APPEND QT_LINKER_LIBS Qt::DBus)
LIST(APPEND QT_MODULES DBus)
ENDIF()
ENDIF()
ADD_DEFINITIONS(
-DQT_NO_CAST_TO_ASCII
# -DQT_NO_CAST_FROM_ASCII
@@ -44,26 +59,30 @@ ADD_DEFINITIONS(
# -DQT_NO_SIGNALS_SLOTS_KEYWORDS -DQT_USE_QSTRINGBUILDER
)
SET(Calyp_App_SRCS
SET(Calyp_App_Module_SRCS # Module Video
models/VideostreamResource.cpp ResourceHandle.cpp
)
SET(Calyp_App_GUI_SRCS
${Calyp_App_Module_SRCS}
# Models
ModulesHandle.cpp
SubWindowHandle.cpp
VideoHandle.cpp
CalypAppModuleIf.cpp
QualityHandle.cpp
# Main
main.cpp
MainWindow.cpp
# Module SubWindow
SubWindowHandle.cpp
MdiSubWindow.cpp
SubWindowAbstract.cpp
# Module Video
ResourceHandle.cpp
VideoHandle.cpp
VideoSubWindow.cpp
VideoStreamSubWindow.cpp
ModuleSubWindow.cpp
ViewArea.cpp
GridManager.cpp
# Module Quality
QualityHandle.cpp
PlotSubWindow.cpp
# Module Plugins
ModulesHandle.cpp
CalypAppModuleIf.cpp
# Dialogs
dialog/AboutDialog.cpp
dialog/ConfigureFormatDialog.cpp
@@ -81,7 +100,7 @@ SET(Calyp_App_SRCS
)
IF(USE_QTDBUS)
LIST(APPEND Calyp_App_SRCS DBusAppAdaptor.cpp)
LIST(APPEND Calyp_App_GUI_SRCS DBusAppAdaptor.cpp)
ENDIF()
SET(Calyp_App_UI "")
@@ -105,7 +124,7 @@ IF(USE_FERVOR)
FIND_PACKAGE(Qt5 REQUIRED Network WebKit WebKitWidgets)
LIST(APPEND QT_LINKER_LIBS Qt5::Network Qt5::WebKit Qt5::WebKitWidgets)
LIST(APPEND QT_LINKER_LIBS Qt::Network Qt::WebKit Qt::WebKitWidgets)
LIST(APPEND QT_MODULES Network WebKit WebKitWidgets)
# LIST(APPEND APP_LINKER_LIBS ${FERVOR_DEPENDENCIES} )
@@ -128,8 +147,8 @@ SET_PACKAGE_PROPERTIES(
)
ADD_FEATURE_INFO(Fervor USE_FERVOR "Fervor lib includes check for updates feature.")
QT5_WRAP_UI(Calyp_App_UI_Wrap ${Calyp_App_UI})
QT5_ADD_RESOURCES(Calyp_App_RCC ${Calyp_App_RCC})
QT_WRAP_UI(Calyp_App_UI_Wrap ${Calyp_App_UI})
QT_ADD_RESOURCES(Calyp_App_RCC ${Calyp_App_RCC})
# Instruct CMake to run moc automatically when needed.
SET(CMAKE_AUTOMOC ON)
@@ -156,7 +175,7 @@ IF(WIN32)
COMMENT "Add icon on windows platform"
)
ENDIF()
ADD_EXECUTABLE(${PROJECT_NAME} ${Calyp_App_SRCS} ${HEADERS_MOC_FILES} ${Calyp_App_UI_Wrap} ${Calyp_App_RCC} ${WINDOWS_RES_FILE})
ADD_EXECUTABLE(${PROJECT_NAME} ${Calyp_App_GUI_SRCS} ${HEADERS_MOC_FILES} ${Calyp_App_UI_Wrap} ${Calyp_App_RCC} ${WINDOWS_RES_FILE})
ELSEIF(CMAKE_HOST_APPLE)
SET(CMAKE_MACOSX_BUNDLE ON)
SET(MACOSX_BUNDLE_EXECUTABLE_NAME ${PROJECT_NAME})
@@ -164,9 +183,9 @@ ELSEIF(CMAKE_HOST_APPLE)
SET(MACOSX_BUNDLE_BUNDLE_NAME Calyp)
SET(APP_ICON_MACOSX ${CMAKE_CURRENT_SOURCE_DIR}/resources/calyp.icns)
SET_SOURCE_FILES_PROPERTIES(${APP_ICON_MACOSX} PROPERTIES MACOSX_PACKAGE_LOCATION "Resources")
ADD_EXECUTABLE(${PROJECT_NAME} MACOSX_BUNDLE ${Calyp_App_SRCS} ${HEADERS_MOC_FILES} ${Calyp_App_UI_Wrap} ${Calyp_App_RCC} ${APP_ICON_MACOSX})
ADD_EXECUTABLE(${PROJECT_NAME} MACOSX_BUNDLE ${Calyp_App_GUI_SRCS} ${HEADERS_MOC_FILES} ${Calyp_App_UI_Wrap} ${Calyp_App_RCC} ${APP_ICON_MACOSX})
ELSE()
ADD_EXECUTABLE(${PROJECT_NAME} ${Calyp_App_SRCS} ${HEADERS_MOC_FILES} ${Calyp_App_UI_Wrap} ${Calyp_App_RCC})
ADD_EXECUTABLE(${PROJECT_NAME} ${Calyp_App_GUI_SRCS} ${HEADERS_MOC_FILES} ${Calyp_App_UI_Wrap} ${Calyp_App_RCC})
ENDIF()
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${PROJECT_LIBRARY} CalypModules ${APP_LINKER_LIBS} ${QT_LINKER_LIBS} QCustomPlotLib)
@@ -176,3 +195,7 @@ INSTALL(TARGETS ${PROJECT_NAME} DESTINATION bin)
INSTALL(FILES resources/calyp.desktop DESTINATION share/applications)
INSTALL(FILES resources/calyp.png DESTINATION share/pixmaps)
INSTALL(FILES resources/calyp.xml DESTINATION share/mime/packages)
IF(BUILD_TESTS)
ADD_SUBDIRECTORY(catch2)
ENDIF()
+33 -22
View File
@@ -29,6 +29,7 @@
#include <QDockWidget>
#include "ModuleHandleDock.h"
#include "ModuleSubWindow.h"
#include "VideoSubWindow.h"
#include "lib/CalypFrame.h"
#include "lib/CalypStream.h"
@@ -55,16 +56,19 @@ CalypAppModuleIf::~CalypAppModuleIf()
auto* ptr = m_pcModuleDock;
m_pcModuleDock = NULL;
ptr->close();
delete ptr;
}
if( m_pcDisplaySubWindow )
{
auto* ptr = m_pcDisplaySubWindow;
m_pcDisplaySubWindow = NULL;
ptr->closeSubWindow();
delete ptr;
}
if( m_pcDockWidget )
{
m_pcDockWidget->close();
delete m_pcDockWidget;
}
if( m_pcModule )
{
@@ -77,7 +81,7 @@ void CalypAppModuleIf::update( bool isPlaying )
{
if( m_pcDisplaySubWindow )
{
m_pcDisplaySubWindow->refreshFrame();
m_pcDisplaySubWindow->refreshSubWindow();
}
else
{
@@ -85,15 +89,15 @@ void CalypAppModuleIf::update( bool isPlaying )
}
}
void CalypAppModuleIf::setPlaying( bool isPlaying )
{
if( m_pcDisplaySubWindow )
{
m_pcDisplaySubWindow->setPlaying( isPlaying );
}
}
// void CalypAppModuleIf::setPlaying( bool isPlaying )
// {
// if( m_pcDisplaySubWindow )
// {
// m_pcDisplaySubWindow->setPlaying( isPlaying );
// }
// }
bool CalypAppModuleIf::isRunning()
bool CalypAppModuleIf::isRunning() const
{
#ifdef CALYP_THREADED_MODULES
return QThread::isRunning();
@@ -115,7 +119,7 @@ void CalypAppModuleIf::run()
bool CalypAppModuleIf::apply( bool isPlaying, bool disableThreads )
{
bool moduleExecuted = false;
if( m_pcModule->m_iModuleType == CLP_FRAME_PROCESSING_MODULE )
if( m_pcModule->m_iModuleType == ClpModuleType::FrameProcessing )
{
if( m_pcDisplaySubWindow )
{
@@ -126,7 +130,8 @@ bool CalypAppModuleIf::apply( bool isPlaying, bool disableThreads )
m_pcSubWindow[0]->setFillWindow( true );
}
}
if( !( isPlaying && ( m_pcModule->m_uiModuleRequirements & CLP_MODULE_REQUIRES_SKIP_WHILE_PLAY ) ) )
if( !( isPlaying && m_pcModule->has( ClpModuleFeature::SkipWhilePlaying ) ) )
{
m_frameList.clear();
for( unsigned int i = 0; i < m_pcModule->m_uiNumberOfFrames; i++ )
@@ -154,7 +159,6 @@ bool CalypAppModuleIf::apply( bool isPlaying, bool disableThreads )
show();
}
}
return moduleExecuted;
}
@@ -175,7 +179,7 @@ bool CalypAppModuleIf::process()
m_frameListPtr.push_back( frame.get() );
}
if( m_pcModule->m_iModuleType == CLP_FRAME_PROCESSING_MODULE )
if( m_pcModule->m_iModuleType == ClpModuleType::FrameProcessing )
{
CalypFrame* framePtr{ nullptr };
if( m_pcModule->m_iModuleAPI >= CLP_MODULE_API_2 )
@@ -189,7 +193,7 @@ bool CalypAppModuleIf::process()
assert( framePtr != nullptr );
m_pcProcessedFrame = std::shared_ptr<CalypFrame>{ framePtr, []( CalypFrame* ptr ) {} };
}
else if( m_pcModule->m_iModuleType == CLP_FRAME_MEASUREMENT_MODULE )
else if( m_pcModule->m_iModuleType == ClpModuleType::FrameMeasurement )
{
if( m_pcModule->m_iModuleAPI >= CLP_MODULE_API_2 )
{
@@ -210,27 +214,34 @@ bool CalypAppModuleIf::process()
void CalypAppModuleIf::show()
{
#ifdef CALYP_THREADED_MODULES
if( m_canceling )
return;
#endif
switch( m_pcModule->m_iModuleType )
{
case CLP_FRAME_PROCESSING_MODULE: {
auto displayWindow = m_pcDisplaySubWindow;
case ClpModuleType::FrameProcessing: {
auto displayWindow = qobject_cast<VideoSubWindow*>( m_pcDisplaySubWindow );
if( displayWindow == nullptr )
displayWindow = m_pcSubWindow[0];
#ifdef CALYP_THREADED_MODULES
if( m_Mutex.try_lock() )
{
m_pcDisplaySubWindow->setFillWindow( false );
m_pcDisplaySubWindow->setCurrFrame( m_pcProcessedFrame );
displayWindow->setFillWindow( false );
displayWindow->setCurrFrame( m_pcProcessedFrame );
m_Mutex.unlock();
}
#else
displayWindow->setFillWindow( false );
displayWindow->setCurrFrame( m_pcProcessedFrame );
#endif
m_pcDisplaySubWindow->setFillWindow( false );
m_pcDisplaySubWindow->setCurrFrame( m_pcProcessedFrame );
break;
}
case CLP_FRAME_MEASUREMENT_MODULE:
case ClpModuleType::FrameMeasurement:
m_pcModuleDock->setModuleReturnValue( m_dMeasurementResult );
break;
default:
assert( false );
}
}
@@ -238,7 +249,7 @@ void CalypAppModuleIf::disable()
{
QApplication::setOverrideCursor( Qt::WaitCursor );
#ifdef CALYP_THREADED_MODULES
QMutexLocker locker( &m_Mutex );
m_canceling = true;
m_Mutex.lock();
m_Mutex.unlock();
#endif
+7 -9
View File
@@ -49,9 +49,8 @@ class QDockWidget;
class CalypStream;
class CalypFrame;
#define CLP_MODULE_MAX_NUM_FRAMES 5
class VideoSubWindow;
class ModuleSubWindow;
class CalypAppModuleIf : std::enable_shared_from_this<CalypAppModuleIf>,
#ifdef CALYP_THREADED_MODULES
@@ -59,7 +58,6 @@ class CalypAppModuleIf : std::enable_shared_from_this<CalypAppModuleIf>,
#else
public QObject
#endif
{
friend class ModulesHandle;
friend class ModuleHandleDock;
@@ -80,16 +78,15 @@ public:
CalypAppModuleIf( QObject* parent, QAction* action, CalypModulePtr&& module );
~CalypAppModuleIf();
auto getSubWindowList() -> const std::vector<VideoSubWindow*>& { return m_pcSubWindow; }
auto getSubWindowList() const -> const std::vector<VideoSubWindow*>& { return m_pcSubWindow; }
CalypModuleIf* getModule() { return m_pcModule.get(); }
unsigned int getModuleRequirements() { return m_pcModule->m_uiModuleRequirements; }
std::string moduleInfo() { return m_pcModule->moduleInfo(); }
auto hasFeature( ClpModuleFeature feature ) const -> bool { return m_pcModule->has( feature ); }
std::string moduleInfo() const { return m_pcModule->moduleInfo(); }
void update( bool isPlaying );
bool apply( bool isPlaying = false, bool disableThreads = false );
bool process();
void setPlaying( bool isPlaying );
bool isRunning();
bool isRunning() const;
void show();
void disable();
@@ -105,7 +102,7 @@ private:
std::vector<VideoSubWindow*> m_pcSubWindow;
// The module owns the related widgets
VideoSubWindow* m_pcDisplaySubWindow{ nullptr };
ModuleSubWindow* m_pcDisplaySubWindow{ nullptr };
QDockWidget* m_pcDockWidget{ nullptr };
ModuleHandleDock* m_pcModuleDock{ nullptr };
@@ -119,6 +116,7 @@ private:
#ifdef CALYP_THREADED_MODULES
QMutex m_Mutex;
std::atomic<bool> m_canceling{ false };
#endif
};
+186 -145
View File
@@ -36,6 +36,7 @@
#include <memory>
#include "AboutDialog.h"
#include "ConfigureFormatDialog.h"
#include "ModulesHandle.h"
#include "QualityHandle.h"
#include "SubWindowAbstract.h"
@@ -44,12 +45,12 @@
#include "VideoHandle.h"
#include "VideoSubWindow.h"
#include "lib/CalypOptions.h"
#include "models/VideostreamResource.h"
#ifdef USE_FERVOR
#include "fvupdater.h"
#endif
MainWindow::MainWindow()
: m_pcCurrentSubWindow( NULL ), m_pcCurrentVideoSubWindow( NULL ), m_pcAboutDialog( NULL )
{
setWindowModality( Qt::ApplicationModal );
setWindowModality( Qt::NonModal );
@@ -79,15 +80,15 @@ MainWindow::MainWindow()
setWindowTitle( QApplication::applicationName() );
setWindowIcon( QIcon( ":logos/calyp-icon.png" ) );
setUnifiedTitleAndToolBarOnMac( true );
setCentralWidget( m_pcWindowHandle );
setCentralWidget( m_pcWindowHandle->getWidget() );
setAcceptDrops( true );
setBackgroundRole( QPalette::Window );
connect( m_pcWindowHandle, &SubWindowHandle::windowActivated, this, &MainWindow::update );
connect( m_pcWindowHandle, &SubWindowHandle::changed, this, &MainWindow::update, Qt::QueuedConnection );
connect( m_appModuleVideo, &VideoHandle::changed, this, &MainWindow::update, Qt::QueuedConnection );
connect( m_appModuleQuality, &QualityHandle::changed, this, &MainWindow::update, Qt::QueuedConnection );
connect( m_appModuleExtensions, &ModulesHandle::changed, this, &MainWindow::update, Qt::QueuedConnection );
connect( m_pcWindowHandle, &SubWindowHandle::windowActivated, this, &MainWindow::updateMainWindow );
connect( m_pcWindowHandle, &SubWindowHandle::changed, this, &MainWindow::updateMainWindow, Qt::QueuedConnection );
connect( m_appModuleVideo, &VideoHandle::changed, this, &MainWindow::updateMainWindow, Qt::QueuedConnection );
connect( m_appModuleQuality, &QualityHandle::changed, this, &MainWindow::updateMainWindow, Qt::QueuedConnection );
connect( m_appModuleExtensions, &ModulesHandle::changed, this, &MainWindow::updateMainWindow, Qt::QueuedConnection );
}
bool MainWindow::parseArgs( int argc, char* argv[] )
@@ -134,8 +135,7 @@ bool MainWindow::parseArgs( int argc, char* argv[] )
void MainWindow::about()
{
if( !m_pcAboutDialog )
m_pcAboutDialog = new AboutDialog( this );
if( !m_pcAboutDialog ) m_pcAboutDialog = new AboutDialog( this );
m_pcAboutDialog->exec();
}
@@ -185,39 +185,82 @@ void MainWindow::closeAll()
m_pcWindowHandle->removeAllSubWindow();
}
void MainWindow::loadFile( QString fileName, CalypFileInfo* pStreamInfo )
void MainWindow::loadFile( const CalypFileInfo& pStreamInfo )
{
loadFile( pStreamInfo.m_cFilename, pStreamInfo );
}
void MainWindow::loadFile( const QString& fileName, std::optional<CalypFileInfo> streamInfoOpt, bool forceDialog )
{
qDebug() << fileName;
if( !QFileInfo( fileName ).exists() )
{
printMessage( "File " + fileName + " do not exist!", CLP_LOG_ERROR );
return;
}
VideoSubWindow* videoSubWindow = MainWindow::findVideoStreamSubWindow( m_pcWindowHandle, fileName );
if( videoSubWindow )
if( auto* videoSubWindow = MainWindow::findVideoStreamSubWindow( m_pcWindowHandle, fileName ) )
{
m_pcWindowHandle->setActiveSubWindow( videoSubWindow );
return;
}
videoSubWindow = new VideoSubWindow( VideoSubWindow::VIDEO_STREAM_SUBWINDOW ); // createSubWindow();
videoSubWindow->setResourceManaget( m_appResourceHandle.get() );
if( !pStreamInfo )
if( !streamInfoOpt.has_value() )
{
int idx = findCalypStreamInfo( m_aRecentFileStreamInfo, fileName );
pStreamInfo = (CalypFileInfo*)( idx >= 0 ? &m_aRecentFileStreamInfo.at( idx ) : NULL );
auto idx = findCalypStreamInfo( m_aRecentFileStreamInfo, fileName );
if( idx >= 0 ) streamInfoOpt = m_aRecentFileStreamInfo.at( idx );
}
auto streamInfo = streamInfoOpt.has_value() ? *streamInfoOpt : CalypFileInfo{ .m_cFilename = fileName };
auto videoResource = std::make_unique<VideostreamResource>();
bool opened = false;
try
{
bool opened = false;
[[maybe_unused]] auto guessed = video_resource_guess_format(
streamInfo.m_cFilename, streamInfo.m_uiWidth, streamInfo.m_uiHeight, streamInfo.m_iPelFormat,
streamInfo.m_uiBitsPelPixel, streamInfo.m_iEndianness, streamInfo.m_uiFrameRate );
if( !pStreamInfo )
opened = videoSubWindow->loadFile( fileName );
else
opened = videoSubWindow->loadFile( pStreamInfo );
if( !forceDialog )
{
opened = videoResource->loadFile( streamInfo, false );
}
if( !opened )
{
ConfigureFormatDialog formatDialog( this );
if( streamInfo.m_uiWidth == 0 )
{
streamInfo.m_uiWidth = m_lastOpenWidth;
}
if( streamInfo.m_uiHeight == 0 )
{
streamInfo.m_uiHeight = m_lastOpenHeight;
}
if( streamInfo.m_uiBitsPelPixel == 0 )
{
streamInfo.m_uiBitsPelPixel = m_lastOpenBitPerPixel;
}
if( formatDialog.runConfigureFormatDialog( QFileInfo( streamInfo.m_cFilename ).fileName(), streamInfo.m_uiWidth,
streamInfo.m_uiHeight, streamInfo.m_iPelFormat,
streamInfo.m_uiBitsPelPixel, streamInfo.m_iEndianness,
streamInfo.m_uiFrameRate ) != QDialog::Accepted )
{
return;
}
opened = videoResource->loadFile( streamInfo, false );
}
if( opened )
{
const auto openedStreamInfo = videoResource->getStreamInfo();
auto resource_id = m_appResourceHandle->appendResource( std::move( videoResource ) );
auto* videoSubWindow = new VideoStreamSubWindow( m_appResourceHandle.get() ); // createSubWindow();
videoSubWindow->setResource( resource_id );
printMessage( "Loading file...", CLP_LOG_INFO );
m_pcWindowHandle->addSubWindow( videoSubWindow );
videoSubWindow->show();
@@ -226,19 +269,17 @@ void MainWindow::loadFile( QString fileName, CalypFileInfo* pStreamInfo )
updateZoomFactorSBox();
addStreamInfoToRecentList( videoSubWindow->getStreamInfo() );
m_lastOpenPath = QFileInfo( openedStreamInfo.m_cFilename ).path();
m_lastOpenWidth = openedStreamInfo.m_uiWidth;
m_lastOpenHeight = openedStreamInfo.m_uiHeight;
m_lastOpenBitPerPixel = openedStreamInfo.m_uiBitsPelPixel;
addStreamInfoToRecentList( std::move( openedStreamInfo ) );
printMessage( "File loaded", CLP_LOG_INFO );
m_cLastOpenPath = QFileInfo( fileName ).path();
}
else
{
videoSubWindow->close();
}
}
catch( CalypFailure& e )
{
videoSubWindow->close();
QString warningMsg =
"Cannot open file " + QFileInfo( fileName ).fileName() + " with the following error: \n" + e.what();
QMessageBox::warning( this, QApplication::applicationName(), warningMsg );
@@ -286,13 +327,12 @@ QStringList MainWindow::showFileDialog( bool bRead )
fileNameList.clear();
if( bRead )
{
fileNameList = QFileDialog::getOpenFileNames( this, tr( "Open File" ), m_cLastOpenPath, filter.join( ";;" ) );
fileNameList = QFileDialog::getOpenFileNames( this, tr( "Open File" ), m_lastOpenPath, filter.join( ";;" ) );
}
else
{
QString fileName = QFileDialog::getSaveFileName( this, tr( "Save File" ), m_cLastOpenPath, filter.join( ";;" ) );
if( !fileName.isEmpty() )
fileNameList.append( fileName );
QString fileName = QFileDialog::getSaveFileName( this, tr( "Save File" ), m_lastOpenPath, filter.join( ";;" ) );
if( !fileName.isEmpty() ) fileNameList.append( fileName );
}
return fileNameList;
}
@@ -304,7 +344,7 @@ void MainWindow::open()
{
if( !fileNameList.at( i ).isEmpty() )
{
loadFile( fileNameList.at( i ) );
loadFile( std::move( fileNameList.at( i ) ) );
}
}
}
@@ -317,25 +357,25 @@ void MainWindow::open()
void MainWindow::openRecent()
{
QAction* action = qobject_cast<QAction*>( sender() );
CalypFileInfo recentFile = action->data().value<CalypFileInfo>();
if( action )
loadFile( recentFile.m_cFilename, &recentFile );
{
loadFile( action->data().value<CalypFileInfo>() );
}
}
void MainWindow::saveFrame()
{
if( m_pcCurrentVideoSubWindow )
auto* pcVideoSubWindow = m_pcWindowHandle->activeSubWindow<VideoStreamSubWindow>();
if( pcVideoSubWindow != nullptr )
{
VideoSubWindow* saveWindow = m_pcCurrentVideoSubWindow;
QStringList fileNameList = showFileDialog( false );
if( fileNameList.size() == 1 )
{
QString fileName = fileNameList[0];
m_cLastOpenPath = QFileInfo( fileName ).path();
m_lastOpenPath = QFileInfo( fileName ).path();
try
{
saveWindow->save( fileName );
pcVideoSubWindow->save( fileName );
}
catch( CalypFailure& e )
{
@@ -352,18 +392,17 @@ void MainWindow::saveFrame()
void MainWindow::saveStream()
{
if( m_pcCurrentVideoSubWindow )
auto* pcVideoSubWindow = m_pcWindowHandle->activeSubWindow<VideoStreamSubWindow>();
if( pcVideoSubWindow != nullptr )
{
VideoSubWindow* saveWindow = m_pcCurrentVideoSubWindow;
QStringList fileNameList = showFileDialog( false );
if( fileNameList.size() == 1 )
{
QString fileName = fileNameList[0];
m_cLastOpenPath = QFileInfo( fileName ).path();
m_lastOpenPath = QFileInfo( fileName ).path();
try
{
saveWindow->save( fileName );
pcVideoSubWindow->save( fileName );
}
catch( CalypFailure& e )
{
@@ -380,15 +419,19 @@ void MainWindow::saveStream()
void MainWindow::format()
{
if( m_pcCurrentVideoSubWindow )
auto* pcVideoSubWindow = m_pcWindowHandle->activeSubWindow<VideoStreamSubWindow>();
if( pcVideoSubWindow )
{
VideoSubWindow* pcVideoSubWindow = m_pcCurrentVideoSubWindow;
try
{
if( pcVideoSubWindow->loadFile( pcVideoSubWindow->getCurrentFileName(), true ) )
{
addStreamInfoToRecentList( pcVideoSubWindow->getStreamInfo() );
}
auto resourceId = pcVideoSubWindow->getResourceId();
CalypFileInfo streamInfo;
m_appResourceHandle->executeResourceAction<VideostreamResource>( resourceId, [&streamInfo]( auto* resource ) {
streamInfo = resource->getStreamInfo();
return true;
} );
m_pcWindowHandle->removeSubWindow( pcVideoSubWindow );
loadFile( streamInfo.m_cFilename, streamInfo, true );
}
catch( CalypFailure& e )
{
@@ -397,20 +440,18 @@ void MainWindow::format()
QMessageBox::warning( this, QApplication::applicationName(), warningMsg );
printMessage( warningMsg, CLP_LOG_ERROR );
qDebug() << warningMsg;
m_pcCurrentSubWindow->close();
}
m_pcCurrentSubWindow = NULL;
update();
updateMainWindow();
}
}
void MainWindow::reload()
{
if( m_pcCurrentSubWindow )
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow<SubWindowAbstract>();
if( activeSubWindow != nullptr )
{
m_pcCurrentSubWindow->refreshSubWindow();
m_pcCurrentSubWindow = NULL;
update();
activeSubWindow->refreshSubWindow();
updateMainWindow();
}
}
@@ -430,16 +471,16 @@ void MainWindow::reloadAll()
subWindowList.at( i )->refreshSubWindow();
}
}
m_pcCurrentSubWindow = NULL;
update();
updateMainWindow();
}
void MainWindow::loadAll()
{
if( m_pcCurrentVideoSubWindow )
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow<VideoStreamSubWindow>();
if( activeSubWindow != nullptr )
{
printMessage( "Loading file into memory...", CLP_LOG_INFO );
m_pcCurrentVideoSubWindow->loadAll();
activeSubWindow->loadAll();
printMessage( "File loaded", CLP_LOG_INFO );
}
}
@@ -448,40 +489,45 @@ void MainWindow::loadAll()
void MainWindow::normalSize()
{
if( m_pcCurrentSubWindow )
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow();
if( activeSubWindow != nullptr )
{
m_pcCurrentSubWindow->normalSize();
activeSubWindow->normalSize();
updateZoomFactorSBox();
}
}
void MainWindow::zoomToFit()
{
if( m_pcCurrentSubWindow )
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow();
if( activeSubWindow != nullptr )
{
m_pcCurrentSubWindow->zoomToFit();
activeSubWindow->zoomToFit();
updateZoomFactorSBox();
}
}
void MainWindow::zoomToFitAll()
{
VideoSubWindow* videoSubWindow;
QList<SubWindowAbstract*> subWindowList = m_pcWindowHandle->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW );
for( int i = 0; i < subWindowList.size(); i++ )
{
videoSubWindow = qobject_cast<VideoSubWindow*>( subWindowList.at( i ) );
auto* videoSubWindow = qobject_cast<VideoSubWindow*>( subWindowList.at( i ) );
videoSubWindow->zoomToFit();
}
if( m_pcCurrentSubWindow )
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow();
if( activeSubWindow != nullptr )
{
updateZoomFactorSBox();
}
}
void MainWindow::scaleFrame( int ratio )
{
if( m_pcCurrentSubWindow )
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow();
if( activeSubWindow != nullptr )
{
m_pcCurrentSubWindow->scaleView( (double)( ratio ) / 100.0 );
activeSubWindow->scaleView( (double)( ratio ) / 100.0 );
updateZoomFactorSBox();
}
}
@@ -498,10 +544,10 @@ void MainWindow::zoomFromSBox( double zoom )
void MainWindow::updateZoomFactorSBox()
{
double factor;
if( m_pcCurrentSubWindow )
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow();
if( activeSubWindow != nullptr )
{
factor = m_pcCurrentSubWindow->getScaleFactor();
auto factor = activeSubWindow->getScaleFactor();
m_pcZoomFactorSBox->setValue( factor * 100 );
}
}
@@ -522,60 +568,48 @@ void MainWindow::dropEvent( QDropEvent* event )
if( urlList.size() == 1 )
{
QString fileName = urlList.at( 0 ).toLocalFile();
m_cLastOpenPath = QFileInfo( fileName ).path();
m_lastOpenPath = QFileInfo( fileName ).path();
loadFile( fileName );
}
}
// ----------------------- Sub Window Functions -----------------------
VideoSubWindow* MainWindow::findVideoStreamSubWindow( const SubWindowHandle* windowManager,
const QString& fileName )
VideoStreamSubWindow* MainWindow::findVideoStreamSubWindow( const SubWindowHandle* windowManager,
const QString& fileName )
{
QString canonicalFilePath = QFileInfo( fileName ).canonicalFilePath();
VideoSubWindow* pcSubWindow;
QList<SubWindowAbstract*> subWindowList = windowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW );
for( int i = 0; i < subWindowList.size(); i++ )
{
pcSubWindow = qobject_cast<VideoSubWindow*>( subWindowList.at( i ) );
if( pcSubWindow->getCurrentFileName() == canonicalFilePath )
return qobject_cast<VideoSubWindow*>( pcSubWindow );
auto* pcSubWindow = qobject_cast<VideoStreamSubWindow*>( subWindowList.at( i ) );
if( pcSubWindow->getCurrentFileName() == canonicalFilePath ) return pcSubWindow;
}
return 0;
return nullptr;
}
// ----------------------- Update Functions -----------------------
void MainWindow::update()
void MainWindow::updateMainWindow()
{
SubWindowAbstract* activeSubWindow = m_pcWindowHandle->activeSubWindow();
auto* activeSubWindow = m_pcWindowHandle->activeSubWindow();
auto* activeVideoSubWindow = qobject_cast<VideoSubWindow*>( activeSubWindow );
QCoreApplication::processEvents();
// if( activeSubWindow() != m_pcCurrentSubWindow )
{
m_pcCurrentSubWindow = NULL;
m_pcCurrentVideoSubWindow = NULL;
if( activeSubWindow )
{
m_pcCurrentSubWindow = activeSubWindow;
if( m_pcCurrentSubWindow->getCategory() & SubWindowAbstract::VIDEO_SUBWINDOW )
if( activeVideoSubWindow != nullptr &&
!m_pcWindowHandle->findSubWindow( activeVideoSubWindow->getRefSubWindow() ) )
{
m_pcCurrentVideoSubWindow = qobject_cast<VideoSubWindow*>( m_pcCurrentSubWindow );
}
if( m_pcCurrentVideoSubWindow )
{
if( !m_pcWindowHandle->findSubWindow( m_pcCurrentVideoSubWindow->getRefSubWindow() ) )
{
m_pcCurrentVideoSubWindow->setRefSubWindow( NULL );
}
activeVideoSubWindow->setRefSubWindow( nullptr );
}
updateZoomFactorSBox();
}
}
//! Check this - these two function should swap order
m_appModuleQuality->update( m_pcCurrentVideoSubWindow );
m_appModuleVideo->update( m_pcCurrentVideoSubWindow );
m_appModuleQuality->update( activeVideoSubWindow );
m_appModuleVideo->update( activeVideoSubWindow );
updateMenus();
}
@@ -600,10 +634,14 @@ void MainWindow::updateMenus()
{
bool hasSubWindow = ( m_pcWindowHandle->activeSubWindow() != 0 );
bool hasVideoStreamSubWindow = false;
if( m_pcCurrentSubWindow )
if( m_pcCurrentSubWindow->getCategory() & SubWindowAbstract::VIDEO_STREAM_SUBWINDOW )
hasVideoStreamSubWindow = true;
bool hasVideoStreamSubWindow{ false };
bool supportsFormat{ false };
auto* pcVideoSubWindow = m_pcWindowHandle->activeSubWindow<VideoStreamSubWindow>();
if( pcVideoSubWindow != nullptr && pcVideoSubWindow->getCategory() & SubWindowAbstract::VIDEO_STREAM_SUBWINDOW )
{
hasVideoStreamSubWindow = true;
supportsFormat = pcVideoSubWindow->supportsFormatConfiguration();
}
m_arrayMenu[RECENT_MENU]->setEnabled( m_aRecentFileStreamInfo.size() > 0 ? true : false );
@@ -613,7 +651,7 @@ void MainWindow::updateMenus()
m_arrayActions[RELOAD_ACT]->setEnabled( hasSubWindow );
m_arrayActions[RELOAD_ALL_ACT]->setEnabled( hasSubWindow );
m_arrayActions[FORMAT_ACT]->setEnabled( hasVideoStreamSubWindow );
m_arrayActions[FORMAT_ACT]->setEnabled( supportsFormat );
m_arrayActions[LOAD_ALL_ACT]->setEnabled( hasVideoStreamSubWindow );
m_arrayActions[ZOOM_IN_ACT]->setEnabled( hasSubWindow );
@@ -668,19 +706,19 @@ void MainWindow::createActions()
m_arrayActions[FORMAT_ACT] = new QAction( tr( "&Format" ), this );
m_arrayActions[FORMAT_ACT]->setIcon( QIcon::fromTheme( "transform-scale" ) );
m_arrayActions[FORMAT_ACT]->setShortcut( Qt::CTRL + Qt::Key_F );
m_arrayActions[FORMAT_ACT]->setShortcut( Qt::CTRL | Qt::Key_F );
m_arrayActions[FORMAT_ACT]->setStatusTip( tr( "Open format dialog" ) );
connect( m_arrayActions[FORMAT_ACT], SIGNAL( triggered() ), this, SLOT( format() ) );
m_arrayActions[RELOAD_ACT] = new QAction( tr( "&Reload" ), this );
m_arrayActions[RELOAD_ACT]->setIcon( style()->standardIcon( QStyle::SP_BrowserReload ) );
m_arrayActions[RELOAD_ACT]->setShortcut( Qt::CTRL + Qt::Key_R );
m_arrayActions[RELOAD_ACT]->setShortcut( Qt::CTRL | Qt::Key_R );
m_arrayActions[RELOAD_ACT]->setShortcut( Qt::Key_F5 );
m_arrayActions[RELOAD_ACT]->setStatusTip( tr( "Reload current sequence" ) );
connect( m_arrayActions[RELOAD_ACT], SIGNAL( triggered() ), this, SLOT( reload() ) );
m_arrayActions[RELOAD_ALL_ACT] = new QAction( tr( "Reload All" ), this );
m_arrayActions[RELOAD_ALL_ACT]->setShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_R );
m_arrayActions[RELOAD_ALL_ACT]->setShortcut( Qt::CTRL | Qt::SHIFT | Qt::Key_R );
m_arrayActions[RELOAD_ALL_ACT]->setStatusTip( tr( "Reload all sequences" ) );
connect( m_arrayActions[RELOAD_ALL_ACT], SIGNAL( triggered() ), this, SLOT( reloadAll() ) );
@@ -703,22 +741,17 @@ void MainWindow::createActions()
connect( m_arrayActions[EXIT_ACT], SIGNAL( triggered() ), qApp, SLOT( closeAllWindows() ) );
// ------------ View ------------
mapperZoom = new QSignalMapper( this );
connect( mapperZoom, SIGNAL( mapped( int ) ), this, SLOT( scaleFrame( int ) ) );
m_arrayActions[ZOOM_IN_ACT] = new QAction( tr( "Zoom &In (+25%)" ), this );
m_arrayActions[ZOOM_IN_ACT]->setIcon( QIcon::fromTheme( "zoom-in" ) );
m_arrayActions[ZOOM_IN_ACT]->setShortcut( tr( "Ctrl++" ) );
m_arrayActions[ZOOM_IN_ACT]->setStatusTip( tr( "Scale the image up by 25%" ) );
connect( m_arrayActions[ZOOM_IN_ACT], SIGNAL( triggered() ), mapperZoom, SLOT( map() ) );
mapperZoom->setMapping( m_arrayActions[ZOOM_IN_ACT], 125 );
connect( m_arrayActions[ZOOM_IN_ACT], &QAction::triggered, [this] { scaleFrame( 125 ); } );
m_arrayActions[ZOOM_OUT_ACT] = new QAction( tr( "Zoom &Out (-25%)" ), this );
m_arrayActions[ZOOM_OUT_ACT]->setIcon( QIcon::fromTheme( "zoom-out" ) );
m_arrayActions[ZOOM_OUT_ACT]->setShortcut( tr( "Ctrl+-" ) );
m_arrayActions[ZOOM_OUT_ACT]->setStatusTip( tr( "Scale the image down by 25%" ) );
connect( m_arrayActions[ZOOM_OUT_ACT], SIGNAL( triggered() ), mapperZoom, SLOT( map() ) );
mapperZoom->setMapping( m_arrayActions[ZOOM_OUT_ACT], 80 );
connect( m_arrayActions[ZOOM_OUT_ACT], &QAction::triggered, [this] { scaleFrame( 80 ); } );
m_arrayActions[ZOOM_NORMAL_ACT] = new QAction( tr( "&Normal Size" ), this );
m_arrayActions[ZOOM_NORMAL_ACT]->setIcon( QIcon::fromTheme( "zoom-original" ) );
@@ -807,12 +840,9 @@ void MainWindow::createMenus()
menuBar()->addMenu( m_appModuleVideo->createVideoMenu() );
menuBar()->addMenu( m_appModuleVideo->createImageMenu() );
QMenu* QualityMenu = m_appModuleQuality->createMenu();
menuBar()->addMenu( QualityMenu );
QMenu* ModuleMenu = m_appModuleExtensions->createMenu();
menuBar()->addMenu( ModuleMenu );
QMenu* windowMenu = m_pcWindowHandle->createMenu();
menuBar()->addMenu( windowMenu );
menuBar()->addMenu( m_appModuleQuality->createMenu() );
menuBar()->addMenu( m_appModuleExtensions->createMenu() );
menuBar()->addMenu( m_pcWindowHandle->createMenu() );
menuBar()->addSeparator();
@@ -827,19 +857,17 @@ void MainWindow::createMenus()
void MainWindow::createToolBars()
{
m_arrayToolBars.resize( TOTAL_TOOLBAR );
auto* fileToolbar = addToolBar( tr( "File" ) );
fileToolbar->addAction( m_arrayActions[OPEN_ACT] );
fileToolbar->addAction( m_arrayActions[SAVE_ACT] );
fileToolbar->addAction( m_arrayActions[FORMAT_ACT] );
fileToolbar->addAction( m_arrayActions[RELOAD_ACT] );
fileToolbar->addAction( m_arrayActions[CLOSE_ACT] );
fileToolbar->setMovable( false );
addToolBar( Qt::TopToolBarArea, fileToolbar );
m_arrayToolBars[FILE_TOOLBAR] = new QToolBar( tr( "File" ) );
m_arrayToolBars[FILE_TOOLBAR]->addAction( m_arrayActions[OPEN_ACT] );
m_arrayToolBars[FILE_TOOLBAR]->addAction( m_arrayActions[SAVE_ACT] );
m_arrayToolBars[FILE_TOOLBAR]->addAction( m_arrayActions[FORMAT_ACT] );
m_arrayToolBars[FILE_TOOLBAR]->addAction( m_arrayActions[RELOAD_ACT] );
m_arrayToolBars[FILE_TOOLBAR]->addAction( m_arrayActions[CLOSE_ACT] );
auto* viewToolBar = addToolBar( tr( "View" ) );
m_arrayToolBars[FILE_TOOLBAR]->setMovable( false );
addToolBar( Qt::TopToolBarArea, m_arrayToolBars[FILE_TOOLBAR] );
m_arrayToolBars[VIEW_TOOLBAR] = new QToolBar( tr( "View" ) );
m_pcZoomFactorSBox = new QDoubleSpinBox;
m_pcZoomFactorSBox->setRange( 1.0, 10000.0 );
m_pcZoomFactorSBox->setDecimals( 0 );
@@ -847,14 +875,15 @@ void MainWindow::createToolBars()
m_pcZoomFactorSBox->setValue( 100.0 );
m_pcZoomFactorSBox->setSuffix( "%" );
connect( m_pcZoomFactorSBox, SIGNAL( valueChanged( double ) ), this, SLOT( zoomFromSBox( double ) ) );
m_arrayToolBars[VIEW_TOOLBAR]->addWidget( m_pcZoomFactorSBox );
m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_IN_ACT] );
m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_OUT_ACT] );
m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_NORMAL_ACT] );
m_arrayToolBars[VIEW_TOOLBAR]->addAction( m_arrayActions[ZOOM_FIT_ACT] );
m_arrayToolBars[FILE_TOOLBAR]->setMovable( false );
addToolBar( Qt::TopToolBarArea, m_arrayToolBars[VIEW_TOOLBAR] );
viewToolBar->addWidget( m_pcZoomFactorSBox );
viewToolBar->addAction( m_arrayActions[ZOOM_IN_ACT] );
viewToolBar->addAction( m_arrayActions[ZOOM_OUT_ACT] );
viewToolBar->addAction( m_arrayActions[ZOOM_NORMAL_ACT] );
viewToolBar->addAction( m_arrayActions[ZOOM_FIT_ACT] );
viewToolBar->setMovable( false );
addToolBar( Qt::TopToolBarArea, viewToolBar );
addToolBar( Qt::TopToolBarArea, m_appModuleVideo->createToolBar() );
}
@@ -877,12 +906,17 @@ void MainWindow::createStatusBar()
void MainWindow::addStreamInfoToRecentList( CalypFileInfo streamInfo )
{
int idx = findCalypStreamInfo( m_aRecentFileStreamInfo, streamInfo.m_cFilename );
if( idx >= 0 )
m_aRecentFileStreamInfo.remove( idx );
if( idx >= 0 ) m_aRecentFileStreamInfo.remove( idx );
m_aRecentFileStreamInfo.prepend( streamInfo );
while( m_aRecentFileStreamInfo.size() > MAX_RECENT_FILES )
{
m_aRecentFileStreamInfo.remove( m_aRecentFileStreamInfo.size() - 1 );
}
updateRecentFileActions();
QSettings appSettings;
QVariant var;
var.setValue( m_aRecentFileStreamInfo );
appSettings.setValue( "MainWindow/RecentFileList", var );
}
void MainWindow::updateRecentFileActions()
@@ -922,6 +956,7 @@ void MainWindow::checkRecentFileActions()
else
{
unsigned long long int fileSize = QFileInfo( m_aRecentFileStreamInfo.at( i ).m_cFilename ).size();
std::cout << m_aRecentFileStreamInfo.at( i ).m_uiFileSize << std::endl;
if( m_aRecentFileStreamInfo.at( i ).m_uiFileSize != fileSize )
{
m_aRecentFileStreamInfo.remove( i );
@@ -941,7 +976,10 @@ void MainWindow::readSettings()
move( pos );
resize( size );
m_cLastOpenPath = appSettings.value( "MainWindow/LastOpenPath", QDir::homePath() ).toString();
m_lastOpenPath = appSettings.value( "MainWindow/LastOpenPath", QDir::homePath() ).toString();
m_lastOpenWidth = appSettings.value( "MainWindow/LastWidth" ).value<unsigned int>();
m_lastOpenHeight = appSettings.value( "MainWindow/LastHeight" ).value<unsigned int>();
m_lastOpenBitPerPixel = appSettings.value( "MainWindow/LastBitsPerPixel" ).value<unsigned int>();
QVariant value = appSettings.value( "MainWindow/RecentFileList" );
m_aRecentFileStreamInfo = value.value<CalypFileInfoVector>();
@@ -960,10 +998,13 @@ void MainWindow::writeSettings()
appSettings.setValue( "MainWindow/Position", pos() );
appSettings.setValue( "MainWindow/Size", size() );
appSettings.setValue( "MainWindow/LastOpenPath", m_cLastOpenPath );
appSettings.setValue( "MainWindow/LastOpenPath", m_lastOpenPath );
appSettings.setValue( "MainWindow/LastWidth", m_lastOpenWidth );
appSettings.setValue( "MainWindow/LastHeight", m_lastOpenHeight );
appSettings.setValue( "MainWindow/LastBitsPerPixel", m_lastOpenBitPerPixel );
QVariant var;
var.setValue<CalypFileInfoVector>( m_aRecentFileStreamInfo );
var.setValue( m_aRecentFileStreamInfo );
appSettings.setValue( "MainWindow/RecentFileList", var );
m_appModuleVideo->writeSettings();
+16 -21
View File
@@ -39,14 +39,17 @@
#include <QMainWindow>
#include <QString>
#include <QVector>
#include <optional>
#include "CommonDefs.h"
#include "VideoStreamSubWindow.h"
#include "VideoSubWindow.h"
#include "config.h"
#ifdef USE_QTDBUS
#include "DBusAppAdaptor.h"
#endif
#include "ResourceHandle.h"
#include "VideostreamResource.h"
class QCloseEvent;
class QDragEnterEvent;
@@ -59,6 +62,7 @@ class QSignalMapper;
class CalypOptions;
class CalypStream;
class SubWindowHandle;
class VideoStreamSubWindow;
class VideoHandle;
class QualityHandle;
class ModulesHandle;
@@ -74,7 +78,8 @@ class MainWindow : public QMainWindow
public:
MainWindow();
bool parseArgs( int argc, char* argv[] );
void loadFile( QString fileName, CalypFileInfo* pStreamInfo = NULL );
void loadFile( const CalypFileInfo& pStreamInfo );
void loadFile( const QString& fileName, std::optional<CalypFileInfo> streamInfoOpt = {}, bool forceDialog = false );
public Q_SLOTS:
void printMessage( const QString& msg );
@@ -115,7 +120,7 @@ private Q_SLOTS:
void dragEnterEvent( QDragEnterEvent* event );
void dropEvent( QDropEvent* event );
void update();
void updateMainWindow();
void updateZoomFactorSBox();
private:
@@ -124,14 +129,17 @@ private:
/**
* Save the current subwindow for every category
*/
SubWindowAbstract* m_pcCurrentSubWindow; //!< General always set
VideoSubWindow* m_pcCurrentVideoSubWindow;
// SubWindowAbstract* m_pcCurrentSubWindow; //!< General always set
// VideoSubWindow* m_pcCurrentVideoSubWindow;
QString m_cLastOpenPath;
QString m_lastOpenPath;
unsigned int m_lastOpenWidth;
unsigned int m_lastOpenHeight;
unsigned int m_lastOpenBitPerPixel;
QStringList showFileDialog( bool bRead );
static VideoSubWindow* findVideoStreamSubWindow( const SubWindowHandle* windowManager,
const QString& fileName );
static VideoStreamSubWindow* findVideoStreamSubWindow( const SubWindowHandle* windowManager,
const QString& fileName );
void updateMenus();
@@ -150,7 +158,6 @@ private:
QDoubleSpinBox* m_pcZoomFactorSBox;
QSignalMapper* mapperZoom;
QSignalMapper* mapperWindow;
/**
@@ -195,18 +202,6 @@ private:
};
QVector<QDockWidget*> m_arraySideBars;
/**
* Array of tool bars for the main app
*/
enum TOOLBAR_LIST
{
FILE_TOOLBAR = 0,
VIEW_TOOLBAR,
VIDEO_TOOLBAR,
TOTAL_TOOLBAR,
};
QVector<QToolBar*> m_arrayToolBars;
/**
* Array of actions for the main app
*/
@@ -239,7 +234,7 @@ private:
QVector<QAction*> m_arrayRecentFilesActions;
CalypFileInfoVector m_aRecentFileStreamInfo;
AboutDialog* m_pcAboutDialog;
AboutDialog* m_pcAboutDialog{ nullptr };
};
#endif // __MAINWINDOW_H__
+114
View File
@@ -0,0 +1,114 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file ModuleSubWindow.cpp
* \brief Video Sub windows handling
*/
#include "ModuleSubWindow.h"
#include <QSettings>
#include <QStaticText>
#include <cassert>
#include "ModulesHandle.h"
ModuleSubWindow::ModuleSubWindow( CalypAppModuleIf* module, QWidget* parent )
: VideoSubWindow( VideoSubWindow::MODULE_SUBWINDOW, parent )
{
m_pcDisplayModule = module;
}
ModuleSubWindow::~ModuleSubWindow()
{
}
void ModuleSubWindow::resetWindowName()
{
QString windowName{ "Module" };
if( auto module_ptr = m_pcDisplayModule )
{
windowName.append( " " ).append( module_ptr->getModule()->m_pchModuleLongName );
}
setWindowName( windowName );
}
void ModuleSubWindow::updateVideoWindowInfo()
{
m_cStreamInformation = "";
m_cStreamInformation = "Module";
if( auto module_ptr = m_pcDisplayModule )
{
const auto& arraySubWindows = module_ptr->getSubWindowList();
QStringList windowInfoList;
if( arraySubWindows.size() > 0 )
{
for( std::size_t i = 0; i < arraySubWindows.size(); i++ )
{
if( arraySubWindows[i]->getWindowName() != getWindowName() )
{
windowInfoList.append( QString( "Input %1 - " + arraySubWindows[i]->getWindowName() ).arg( i + 1 ) );
}
}
}
if( module_ptr->hasFeature( ClpModuleFeature::HasInfo ) )
{
QStringList list = QString::fromStdString( module_ptr->moduleInfo() ).split( '\n' );
windowInfoList.append( list );
}
if( windowInfoList.size() > 0 )
{
m_pcVideoInfo->setInformationTopLeft( windowInfoList );
}
}
if( m_pcCurrFrameAsset )
{
QString m_cPelFmtName = QString::fromStdString( m_pcCurrFrameAsset->getPelFmtName() );
m_cStreamInformation += " | " + m_cPelFmtName;
}
if( m_cStreamInformation.isEmpty() )
{
m_cStreamInformation = " ";
}
}
bool ModuleSubWindow::isPlaying()
{
if( auto module_ptr = m_pcDisplayModule )
{
for( auto window : module_ptr->getSubWindowList() )
{
if( window->isPlaying() )
return true;
}
}
return false;
}
void ModuleSubWindow::refreshSubWindow()
{
if( auto module_ptr = m_pcDisplayModule )
{
setFillWindow( true );
updateVideoWindowInfo();
module_ptr->apply( isPlaying(), false );
}
}
+64
View File
@@ -0,0 +1,64 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file ModuleSubWindow.h
* \brief Video Sub windows handling
*/
#ifndef __MODULESUBWINDOW_H__
#define __MODULESUBWINDOW_H__
#include <QDataStream>
#include <QFuture>
#include <QRect>
#include <QString>
#include <QVector>
#include "CalypAppModuleIf.h"
#include "CommonDefs.h"
#include "VideoSubWindow.h"
#include "config.h"
#include "lib/CalypStream.h"
class VideoInformation;
class ModuleSubWindow : public VideoSubWindow
{
Q_OBJECT
public:
ModuleSubWindow( CalypAppModuleIf* module, QWidget* parent = 0 );
~ModuleSubWindow();
void resetWindowName();
void updateVideoWindowInfo();
bool isPlaying();
void stop(){};
void advanceOneFrame(){};
auto getFrameNum() -> std::uint64_t { return 1; };
void refreshSubWindow();
void setCurrFrame( std::shared_ptr<CalypFrame> pcCurrFrame );
};
#endif // __MODULESUBWINDOW_H__
+64 -77
View File
@@ -27,6 +27,7 @@
#include <cstdio>
#include "MainWindow.h"
#include "ModuleSubWindow.h"
#include "ModulesHandleOptDialog.h"
#include "SubWindowHandle.h"
#include "SubWindowSelectorDialog.h"
@@ -35,7 +36,7 @@
#include "modules/CalypModulesFactory.h"
ModulesHandle::ModulesHandle( QWidget* parent, SubWindowHandle* windowManager, VideoHandle* moduleVideo )
: QWidget( parent ), m_pcParent( parent ), m_pcMainWindowManager( windowManager ), m_appModuleVideo( moduleVideo )
: m_pcParent( parent ), m_pcMainWindowManager( windowManager ), m_appModuleVideo( moduleVideo )
{
setParent( m_pcParent );
}
@@ -50,32 +51,32 @@ void ModulesHandle::createActions()
connect( m_pcActionMapper, SIGNAL( mapped( int ) ), this, SLOT( processOpt( int ) ) );
// m_arrayActions[FORCE_PLAYING_REFRESH_ACT] = new QAction( "Refresh while
// playing", parent() );
// playing", m_pcParent );
// m_arrayActions[FORCE_PLAYING_REFRESH_ACT]->setStatusTip( "Force module
// refreshing while playing" );
// m_arrayActions[FORCE_PLAYING_REFRESH_ACT]->setCheckable( true );
m_arrayActions[LOAD_EXTERNAL_ACT] = new QAction( "Load external module", parent() );
m_arrayActions[LOAD_EXTERNAL_ACT] = new QAction( "Load external module", m_pcParent );
m_arrayActions[LOAD_EXTERNAL_ACT]->setStatusTip( "Load an externally build module" );
connect( m_arrayActions[LOAD_EXTERNAL_ACT], SIGNAL( triggered() ), this, SLOT( loadExternalModule() ) );
connect( m_arrayActions[LOAD_EXTERNAL_ACT], &QAction::triggered, this, &ModulesHandle::loadExternalModule );
m_arrayActions[APPLY_ALL_ACT] = new QAction( "Apply to All", parent() );
m_arrayActions[APPLY_ALL_ACT] = new QAction( "Apply to All", m_pcParent );
m_arrayActions[APPLY_ALL_ACT]->setStatusTip( "Apply module to all frames and save the result" );
connect( m_arrayActions[APPLY_ALL_ACT], SIGNAL( triggered() ), m_pcActionMapper, SLOT( map() ) );
m_pcActionMapper->setMapping( m_arrayActions[APPLY_ALL_ACT], APPLY_ALL_ACT );
m_arrayActions[SWAP_FRAMES_ACT] = new QAction( "Swap frames", parent() );
m_arrayActions[SWAP_FRAMES_ACT] = new QAction( "Swap frames", m_pcParent );
m_arrayActions[SWAP_FRAMES_ACT]->setStatusTip( "Swap Sub Window order" );
connect( m_arrayActions[SWAP_FRAMES_ACT], SIGNAL( triggered() ), m_pcActionMapper, SLOT( map() ) );
m_pcActionMapper->setMapping( m_arrayActions[SWAP_FRAMES_ACT], SWAP_FRAMES_ACT );
m_arrayActions[DISABLE_ACT] = new QAction( "Disable Modules", parent() );
connect( m_arrayActions[DISABLE_ACT], SIGNAL( triggered() ), this, SLOT( destroyWindowModules() ) );
m_arrayActions[DISABLE_ACT] = new QAction( "Disable Modules", m_pcParent );
connect( m_arrayActions[DISABLE_ACT], &QAction::triggered, this, &ModulesHandle::destroyWindowModules );
m_arrayActions[DISABLE_ALL_ACT] = new QAction( "Disable All Modules", parent() );
connect( m_arrayActions[DISABLE_ALL_ACT], SIGNAL( triggered() ), this, SLOT( destroyAllModulesIf() ) );
m_arrayActions[DISABLE_ALL_ACT] = new QAction( "Disable All Modules", m_pcParent );
connect( m_arrayActions[DISABLE_ALL_ACT], &QAction::triggered, this, &ModulesHandle::destroyAllModulesIf );
m_arrayActions[FORCE_NEW_WINDOW_ACT] = new QAction( "Use New Window", parent() );
m_arrayActions[FORCE_NEW_WINDOW_ACT] = new QAction( "Use New Window", m_pcParent );
m_arrayActions[FORCE_NEW_WINDOW_ACT]->setStatusTip(
"Show module result in a new window. Some modules already force this "
"feature" );
@@ -84,33 +85,28 @@ void ModulesHandle::createActions()
QMenu* ModulesHandle::createMenu()
{
m_pcModulesMenu = new QMenu( "&Modules", this );
m_pcModulesMenu = new QMenu( "&Modules", m_pcParent );
buildMenu();
return m_pcModulesMenu;
}
void ModulesHandle::buildMenu()
{
QString ModuleIfinternalName;
QAction* currAction;
QMenu* currSubMenu;
for( int i = 0; i < m_arrayModulesActions.size(); i++ )
for( auto& action : m_arrayModulesActions )
{
delete m_arrayModulesActions.at( i );
delete action;
}
m_arrayModulesActions.clear();
m_pcModulesMenu->clear();
m_pcModulesSubMenuList.clear();
CalypModulesFactoryMap& moduleFactoryMap = CalypModulesFactory::Get()->getMap();
CalypModulesFactoryMap::iterator it = moduleFactoryMap.begin();
for( ; it != moduleFactoryMap.end(); ++it )
const auto& moduleFactoryMap = CalypModulesFactory::Get()->getMap();
for( auto& [name, create_fct] : moduleFactoryMap )
{
auto pcCurrModuleIf = it->second();
ModuleIfinternalName = QString::fromLocal8Bit( it->first );
auto pcCurrModuleIf = create_fct();
QString moduleIfInternalName = QString::fromStdString( name );
currSubMenu = NULL;
QMenu* currSubMenu{ nullptr };
if( pcCurrModuleIf->m_iModuleAPI <= CLP_MODULE_API_2 )
{
if( pcCurrModuleIf->m_pchModuleCategory )
@@ -131,15 +127,15 @@ void ModulesHandle::buildMenu()
}
}
currAction = new QAction( pcCurrModuleIf->getModuleLongName(), parent() );
QAction* currAction = new QAction( pcCurrModuleIf->getModuleLongName(), m_pcParent );
QString moduleTooltip = pcCurrModuleIf->m_pchModuleTooltip;
if( pcCurrModuleIf->m_uiNumberOfFrames > 1 )
moduleTooltip += QString( " | Requires %1 frames" ).arg( pcCurrModuleIf->m_uiNumberOfFrames );
currAction->setStatusTip( moduleTooltip );
currAction->setData( ModuleIfinternalName );
currAction->setData( moduleIfInternalName );
currAction->setCheckable( false );
connect( currAction, SIGNAL( triggered() ), this, SLOT( activateModule() ) );
connect( currAction, &QAction::triggered, this, &ModulesHandle::activateModule );
m_arrayModulesActions.append( currAction );
if( currSubMenu )
@@ -159,20 +155,20 @@ void ModulesHandle::buildMenu()
void ModulesHandle::updateMenus()
{
VideoSubWindow* pcSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
bool hasSubWindow = pcSubWindow ? true : false;
QAction* currModuleAction;
VideoSubWindow* pcSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
bool hasSubWindow = pcSubWindow != nullptr ? true : false;
for( int i = 0; i < m_arrayModulesActions.size(); i++ )
{
currModuleAction = m_arrayModulesActions.at( i );
//currModuleAction->setEnabled( hasSubWindow );
auto* currModuleAction = m_arrayModulesActions.at( i );
// currModuleAction->setEnabled( hasSubWindow );
currModuleAction->setChecked( false );
}
//for( int i = 0; i < m_pcModulesSubMenuList.size(); i++ )
// for( int i = 0; i < m_pcModulesSubMenuList.size(); i++ )
//{
// m_pcModulesSubMenuList.at( i )->setEnabled( hasSubWindow );
//}
// }
for( int i = 0; i < m_arrayActions.size(); i++ )
{
@@ -184,18 +180,17 @@ void ModulesHandle::updateMenus()
if( pcSubWindow )
{
auto apcCurrentModule = pcSubWindow->getModuleArray();
m_arrayActions[DISABLE_ACT]->setEnabled( apcCurrentModule.size() > 0 );
m_arrayActions[DISABLE_ACT]->setEnabled( pcSubWindow->hasModules() );
if( pcSubWindow->getDisplayModule() )
{
m_arrayActions[APPLY_ALL_ACT]->setEnabled( true );
m_arrayActions[SWAP_FRAMES_ACT]->setEnabled( true );
}
for( int i = 0; i < apcCurrentModule.size(); i++ )
{
currModuleAction = apcCurrentModule.at( i )->m_pcModuleAction;
currModuleAction->setChecked( true );
}
// for( int i = 0; i < apcCurrentModule.size(); i++ )
// {
// currModuleAction = apcCurrentModule.at( i )->m_pcModuleAction;
// currModuleAction->setChecked( true );
// }
}
}
@@ -213,22 +208,21 @@ void ModulesHandle::writeSettings()
void ModulesHandle::processOpt( int index )
{
VideoSubWindow* pcSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
if( pcSubWindow )
{
CalypAppModuleIf* pcCurrentModule = pcSubWindow->getDisplayModule();
if( pcCurrentModule )
{
CalypAppModuleIf* pcCurrModule = pcCurrentModule;
switch( index )
{
case INVALID_OPT:
break;
case SWAP_FRAMES_ACT:
swapModulesWindowsIf( pcCurrModule );
swapModulesWindowsIf( pcCurrentModule );
break;
case APPLY_ALL_ACT:
applyAllModuleIf( pcCurrModule );
applyAllModuleIf( pcCurrentModule );
break;
default:
Q_ASSERT( 0 );
@@ -263,7 +257,7 @@ void ModulesHandle::activateModule()
Qt::KeyboardModifiers keyModifiers = QApplication::keyboardModifiers();
bool bTmpForceNewWindow = false;
VideoSubWindow* pcVideoSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcVideoSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
if( !pcVideoSubWindow )
{
return;
@@ -288,7 +282,7 @@ void ModulesHandle::activateModule()
{
int minNumFrames = numberOfFrames;
int maxNumFrames = numberOfFrames;
if( pcCurrAppModuleIf->m_pcModule->m_uiModuleRequirements & CLP_MODULES_VARIABLE_NUM_FRAMES )
if( pcCurrAppModuleIf->m_pcModule->has( ClpModuleFeature::VariableNumOfFrames ) )
{
minNumFrames = numberOfFrames;
maxNumFrames = 255;
@@ -337,7 +331,7 @@ void ModulesHandle::activateModule()
{
videoSubWindowList.clear();
qobject_cast<MainWindow*>( m_pcParent )->printMessage( "Error! Incompatible frames", CLP_LOG_ERROR );
//destroyModuleIf( pcCurrAppModuleIf );
// destroyModuleIf( pcCurrAppModuleIf );
return;
}
}
@@ -352,7 +346,7 @@ void ModulesHandle::activateModule()
{
qobject_cast<MainWindow*>( m_pcParent )
->printMessage( "Error! There is no windows to apply the module", CLP_LOG_ERROR );
//destroyModuleIf( pcCurrAppModuleIf );
// destroyModuleIf( pcCurrAppModuleIf );
return;
}
@@ -361,13 +355,13 @@ void ModulesHandle::activateModule()
pcCurrAppModuleIf->m_pcSubWindow[i] = videoSubWindowList.at( i );
}
if( pcCurrAppModuleIf->m_pcModule->m_uiModuleRequirements & CLP_MODULE_REQUIRES_OPTIONS )
if( pcCurrAppModuleIf->m_pcModule->has( ClpModuleFeature::Options ) )
{
ModulesHandleOptDialog moduleOptDialog( m_pcParent, pcCurrAppModuleIf.get() );
if( moduleOptDialog.runConfiguration() == QDialog::Rejected )
{
qobject_cast<MainWindow*>( m_pcParent )->printMessage( "Module canceled by user!", CLP_LOG_WARNINGS );
//destroyModuleIf( pcCurrAppModuleIf );
// destroyModuleIf( pcCurrAppModuleIf );
return;
}
}
@@ -376,14 +370,12 @@ void ModulesHandle::activateModule()
QString windowName;
VideoSubWindow* pcModuleSubWindow = NULL;
if( pcCurrAppModuleIf->m_pcModule->m_iModuleType == CLP_FRAME_PROCESSING_MODULE )
if( pcCurrAppModuleIf->m_pcModule->m_iModuleType == ClpModuleType::FrameProcessing )
{
if( ( pcCurrAppModuleIf->m_pcModule->m_uiModuleRequirements & CLP_MODULE_REQUIRES_NEW_WINDOW ) || bShowModulesNewWindow )
if( bShowModulesNewWindow || pcCurrAppModuleIf->m_pcModule->has( ClpModuleFeature::NewWindow ) )
{
pcModuleSubWindow = new VideoSubWindow( VideoSubWindow::MODULE_SUBWINDOW, pcCurrAppModuleIf.get() );
windowName.append( QStringLiteral( "Module " ) );
windowName.append( pcCurrAppModuleIf->m_pcModule->m_pchModuleLongName );
auto pcModuleSubWindow = new ModuleSubWindow( pcCurrAppModuleIf.get() );
pcModuleSubWindow->resetWindowName();
pcCurrAppModuleIf->m_pcDisplaySubWindow = pcModuleSubWindow;
// connect( pcModuleSubWindow->getViewArea(), SIGNAL( selectionChanged( QRect ) ), m_appModuleVideo,
// SLOT( updateSelectionArea( QRect ) ) );
@@ -397,7 +389,7 @@ void ModulesHandle::activateModule()
pcCurrAppModuleIf->m_pcSubWindow[0]->setDisplayModule( pcCurrAppModuleIf.get() );
}
}
else if( pcCurrAppModuleIf->m_pcModule->m_iModuleType == CLP_FRAME_MEASUREMENT_MODULE )
else if( pcCurrAppModuleIf->m_pcModule->m_iModuleType == ClpModuleType::FrameMeasurement )
{
pcCurrAppModuleIf->m_pcDisplaySubWindow = NULL;
pcCurrAppModuleIf->m_pcModuleDock = new ModuleHandleDock( m_pcParent, pcCurrAppModuleIf.get() );
@@ -437,7 +429,7 @@ void ModulesHandle::activateModule()
if( !moduleCreated )
{
qobject_cast<MainWindow*>( m_pcParent )->printMessage( "Error! Module cannot be created", CLP_LOG_ERROR );
//destroyModuleIf( pcCurrAppModuleIf );
// destroyModuleIf( pcCurrAppModuleIf );
return;
}
@@ -445,12 +437,11 @@ void ModulesHandle::activateModule()
QCoreApplication::processEvents();
if( pcModuleSubWindow )
if( pcCurrAppModuleIf->m_pcDisplaySubWindow )
{
pcModuleSubWindow->setWindowName( windowName );
m_pcMainWindowManager->addSubWindow( pcModuleSubWindow );
pcModuleSubWindow->show();
m_appModuleVideo->addSubWindow( pcModuleSubWindow );
m_pcMainWindowManager->addSubWindow( pcCurrAppModuleIf->m_pcDisplaySubWindow );
pcCurrAppModuleIf->m_pcDisplaySubWindow->show();
m_appModuleVideo->addSubWindow( pcCurrAppModuleIf->m_pcDisplaySubWindow );
}
else
{
@@ -475,7 +466,7 @@ void ModulesHandle::activateModule()
void ModulesHandle::destroyWindowModules()
{
VideoSubWindow* pcVideoSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcVideoSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
if( pcVideoSubWindow )
{
pcVideoSubWindow->disableAllModules();
@@ -501,9 +492,6 @@ void ModulesHandle::applyAllModuleIf( CalypAppModuleIf* pcCurrModuleIf )
{
if( !pcCurrModuleIf->m_pcModuleStream )
{
unsigned int Width = 0, Height = 0, FrameRate = 30;
int BitsPixel, InputFormat = -1;
QString supported = tr( "Supported Files (" );
QStringList formatsList;
std::vector<CalypStreamFormat> supportedFmts = CalypStream::supportedWriteFormats();
@@ -536,15 +524,15 @@ void ModulesHandle::applyAllModuleIf( CalypAppModuleIf* pcCurrModuleIf )
{
return;
}
Width = pcCurrModuleIf->m_pcProcessedFrame->getWidth();
Height = pcCurrModuleIf->m_pcProcessedFrame->getHeight();
InputFormat = pcCurrModuleIf->m_pcProcessedFrame->getPelFormat();
BitsPixel = pcCurrModuleIf->m_pcProcessedFrame->getBitsPel();
FrameRate = pcCurrModuleIf->m_pcSubWindow[0]->getInputStream()->getFrameRate();
auto Width = pcCurrModuleIf->m_pcProcessedFrame->getWidth();
auto Height = pcCurrModuleIf->m_pcProcessedFrame->getHeight();
auto InputFormat = pcCurrModuleIf->m_pcProcessedFrame->getPelFormat();
auto BitsPixel = pcCurrModuleIf->m_pcProcessedFrame->getBitsPel();
auto FrameRate = 30;
pcCurrModuleIf->m_pcModuleStream = std::unique_ptr<CalypStream>();
if( !pcCurrModuleIf->m_pcModuleStream->open( fileName.toStdString(), Width, Height, InputFormat, BitsPixel,
CLP_LITTLE_ENDIAN, FrameRate, false ) )
CLP_LITTLE_ENDIAN, FrameRate, CalypStream::Type::Output ) )
{
pcCurrModuleIf->m_pcModuleStream = nullptr;
return;
@@ -558,7 +546,7 @@ void ModulesHandle::applyAllModuleIf( CalypAppModuleIf* pcCurrModuleIf )
std::uint64_t numberOfFrames = -1;
for( unsigned int i = 0; i < numberOfWindows; i++ )
{
currFrames = pcCurrModuleIf->m_pcSubWindow[i]->getInputStream()->getFrameNum();
currFrames = pcCurrModuleIf->m_pcSubWindow[i]->getFrameNum();
if( currFrames < numberOfFrames )
numberOfFrames = currFrames;
pcCurrModuleIf->m_pcSubWindow[i]->stop();
@@ -571,8 +559,7 @@ void ModulesHandle::applyAllModuleIf( CalypAppModuleIf* pcCurrModuleIf )
pcCurrModuleIf->m_pcModuleStream->writeFrame( *pcCurrModuleIf->m_pcProcessedFrame );
for( unsigned int i = 0; i < numberOfWindows; i++ )
{
pcCurrModuleIf->m_pcSubWindow[i]->play();
pcCurrModuleIf->m_pcSubWindow[i]->playEvent();
pcCurrModuleIf->m_pcSubWindow[i]->advanceOneFrame();
}
}
for( unsigned int i = 0; i < numberOfWindows; i++ )
+1 -1
View File
@@ -39,7 +39,7 @@ class SubWindowHandle;
class CalypAppModuleIf;
class SubWindowHandle;
class ModulesHandle : public QWidget
class ModulesHandle : public QObject
{
Q_OBJECT
public:
+14 -15
View File
@@ -34,7 +34,7 @@
#include "VideoSubWindow.h"
QualityHandle::QualityHandle( QWidget* parent, SubWindowHandle* windowManager )
: m_pcParet( parent ), m_pcMainWindowManager( windowManager )
: m_pcParent( parent ), m_pcMainWindowManager( windowManager )
{
}
@@ -70,7 +70,7 @@ void QualityHandle::createActions()
QMenu* QualityHandle::createMenu()
{
m_pcMenuQuality = new QMenu( "Quality", this );
m_pcMenuQuality = new QMenu( "Quality", m_pcParent );
m_pcSubMenuQualityMetrics = m_pcMenuQuality->addMenu( "Quality Metrics" );
m_pcSubMenuQualityMetrics->addActions( m_actionGroupQualityMetric->actions() );
m_pcMenuQuality->addAction( m_arrayActions[SELECT_CURR_REF_ACT] );
@@ -82,8 +82,8 @@ QMenu* QualityHandle::createMenu()
QDockWidget* QualityHandle::createDock()
{
m_pcQualityHandleSideBar = new QualityMeasurementSidebar( m_pcParet, m_pcMainWindowManager );
m_pcQualityHandleDock = new QDockWidget( tr( "Quality Measurement" ), this );
m_pcQualityHandleSideBar = new QualityMeasurementSidebar( m_pcParent, m_pcMainWindowManager );
m_pcQualityHandleDock = new QDockWidget( tr( "Quality Measurement" ), m_pcParent );
m_pcQualityHandleDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea );
m_pcQualityHandleDock->setWidget( m_pcQualityHandleSideBar );
@@ -98,7 +98,7 @@ QDockWidget* QualityHandle::createDock()
void QualityHandle::updateMenus()
{
VideoSubWindow* pcCurrentVideoSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcCurrentVideoSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
bool hasSubWindow = pcCurrentVideoSubWindow ? true : false;
bool hasReference = false;
bool isReference = false;
@@ -169,21 +169,20 @@ void QualityHandle::measureQuality( QVector<VideoSubWindow*> apcWindowList )
}
VideoSubWindow* pcReferenceWindow = apcWindowList.at( 0 )->getRefSubWindow();
numberOfFrames = pcReferenceWindow->getInputStream()->getFrameNum();
numberOfFrames = pcReferenceWindow->getFrameNum();
for( unsigned i = 0; i < numberOfWindows; i++ )
{
currFrames = apcWindowList.at( i )->getInputStream()->getFrameNum();
currFrames = apcWindowList.at( i )->getFrameNum();
if( currFrames < numberOfFrames )
numberOfFrames = currFrames;
apcWindowList.at( i )->stop();
}
pcReferenceWindow->stop();
ProgressBar* pcProgressBar = new ProgressBar( m_pcParet, numberOfFrames );
ProgressBar* pcProgressBar = new ProgressBar( m_pcParent, numberOfFrames );
QVector<double>* padQualityValues = new QVector<double>[numberOfWindows + 1];
double* padAverageQuality = new double[numberOfWindows + 1];
double dCurrentQuality;
for( unsigned i = 0; i < numberOfWindows + 1; i++ )
{
@@ -199,12 +198,12 @@ void QualityHandle::measureQuality( QVector<VideoSubWindow*> apcWindowList )
for( unsigned int i = 0; i < numberOfWindows; i++ )
{
pcCurrFrame = apcWindowList.at( i )->getCurrFrame();
dCurrentQuality = pcCurrFrame->getQuality( m_iQualityMetricIdx, pcReferenceFrame, CLP_LUMA );
double dCurrentQuality = pcCurrFrame->getQuality( m_iQualityMetricIdx, pcReferenceFrame, CLP_LUMA );
padAverageQuality[i + 1] = ( padAverageQuality[i + 1] * double( f ) + dCurrentQuality ) / double( f + 1 );
padQualityValues[i + 1].append( dCurrentQuality );
apcWindowList.at( i )->seekRelativeEvent( true );
apcWindowList.at( i )->advanceOneFrame();
}
pcReferenceWindow->seekRelativeEvent( true );
pcReferenceWindow->advanceOneFrame();
pcProgressBar->incrementProgress( 1 );
}
for( unsigned int i = 0; i < numberOfWindows; i++ )
@@ -248,7 +247,7 @@ void QualityHandle::slotQualityMetricChanged( int idx )
void QualityHandle::slotSelectCurrentAsReference()
{
VideoSubWindow* pcRefSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcRefSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
if( pcRefSubWindow )
{
VideoSubWindow* pcVideoSubWindow;
@@ -268,7 +267,7 @@ void QualityHandle::slotSelectCurrentAsReference()
void QualityHandle::slotPlotQualitySingle()
{
VideoSubWindow* pcSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
if( pcSubWindow )
{
if( pcSubWindow->getRefSubWindow() )
@@ -292,7 +291,7 @@ void QualityHandle::slotPlotQualitySingle()
void QualityHandle::slotPlotQualitySeveral()
{
VideoSubWindow* pcSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
if( pcSubWindow )
{
QVector<VideoSubWindow*> apcWindowList;
+2 -2
View File
@@ -36,7 +36,7 @@
class SubWindowHandle;
class VideoSubWindow;
class QualityHandle : public QWidget
class QualityHandle : public QObject
{
Q_OBJECT
public:
@@ -54,7 +54,7 @@ public:
void update( VideoSubWindow* currSubWindow );
private:
QWidget* m_pcParet;
QWidget* m_pcParent;
SubWindowHandle* m_pcMainWindowManager;
enum
+101 -39
View File
@@ -30,21 +30,31 @@
#include <QFileInfo>
#include <QMutex>
#include <QThread>
#include <chrono>
#include <iostream>
#include <memory>
#include <optional>
ResourceWorker::ResourceWorker( std::shared_ptr<CalypStream> stream )
auto get_new_resource_id() -> std::size_t
{
m_pcStream = stream;
static std::size_t unique_id{ 0 };
return unique_id++;
}
ResourceWorker::~ResourceWorker()
{
stop();
}
void ResourceWorker::stop()
{
while( m_bStarting )
{
}
m_bStop = true;
wake();
wait();
if( m_bStarted )
{
wake();
wait();
}
m_bStarted = false;
}
void ResourceWorker::wake()
@@ -54,41 +64,85 @@ void ResourceWorker::wake()
m_Mutex.unlock();
}
void ResourceWorker::start()
{
m_bStarting = true;
QThread::start();
}
void ResourceWorker::run()
{
m_bStop = false;
m_bStarted = true;
m_bStarting = false;
// Loop forever
while( !m_bStop )
for( ;; )
{
//auto start = std::chrono::steady_clock::now();
m_pcStream->readNextFrameFillRGBBuffer();
while( !m_bStop && !m_resource->isReady() )
{
// Wait here
m_Mutex.lock();
m_ResourceIdle.wait( &m_Mutex );
m_Mutex.unlock();
}
// auto start = std::chrono::steady_clock::now();
if( m_bStop || !m_resource->iteration() )
{
break;
}
// auto end = std::chrono::steady_clock::now();
// std::cout << "Elapsed time reading and processing a frame: "
// << std::chrono::duration_cast<std::chrono::milliseconds>( end - start ).count()
// << " ms" << std::endl;
// if( !m_pcStream->hasWritingSlot() )
// {
// m_Mutex.lock();
// m_ResourceIdle.wait( &m_Mutex );
// m_Mutex.unlock();
// }
while( !m_bStop && !m_pcStream->hasWritingSlot() )
{
// Wait here
}
}
m_bStarted = false;
m_bStop = false;
}
ResourceHandle::ResourceHandle()
class OldStreamResource : public CalypResource
{
}
public:
OldStreamResource() = default;
CalypStream m_stream;
auto getResourceName() -> std::string override { return m_stream.getFileName(); };
auto getResource() -> CalypStream* override { return &m_stream; };
auto iteration() -> bool override
{
if( m_stream.getFrameNum() < 2 )
{
return false;
}
m_stream.readNextFrameFillRGBBuffer();
return true;
}
auto isReady() -> bool override { return m_stream.hasWritingSlot(); }
};
ResourceHandle::ResourceHandle() : m_thread{ std::make_unique<QThread>() }
{
moveToThread( m_thread.get() );
m_thread->start();
};
ResourceHandle::~ResourceHandle()
{
QMetaObject::invokeMethod( this, "cleanup" );
m_thread->wait();
};
void ResourceHandle::cleanup()
{
m_thread->quit();
};
auto ResourceHandle::addResource() -> std::size_t
{
auto resource_id = unique_id;
unique_id++;
auto newStreamResource = std::make_shared<CalypStream>();
auto resource_id = get_new_resource_id();
;
auto newStreamResource = std::make_shared<OldStreamResource>();
auto newStreamResourceWorker = std::make_unique<ResourceWorker>( newStreamResource );
m_apcStreamResourcesList[resource_id] = newStreamResource;
m_apcStreamResourcesWorkersList[resource_id] = std::move( newStreamResourceWorker );
@@ -101,8 +155,10 @@ auto ResourceHandle::getResource( CalypStream* ptr ) -> std::size_t
{
for( std::size_t i = 0; i < m_apcStreamResourcesList.size(); i++ )
{
if( m_apcStreamResourcesList[i].get() == ptr )
return i;
if( auto* resource = dynamic_cast<OldStreamResource*>( m_apcStreamResourcesList[i].get() ) )
{
if( &resource->m_stream == ptr ) return i;
}
}
}
return addResource();
@@ -110,16 +166,22 @@ auto ResourceHandle::getResource( CalypStream* ptr ) -> std::size_t
auto ResourceHandle::getResourceAsset( std::size_t id ) -> CalypStream*
{
if( m_apcStreamResourcesWorkersList.count( id ) )
{
return m_apcStreamResourcesList[id].get();
}
return nullptr;
if( !m_apcStreamResourcesWorkersList.contains( id ) ) return nullptr;
return m_apcStreamResourcesList[id]->getResource();
}
auto ResourceHandle::appendResource( std::unique_ptr<CalypResource>&& resource ) -> std::size_t
{
auto resource_id = get_new_resource_id();
m_apcStreamResourcesList[resource_id] = std::move( resource );
m_apcStreamResourcesWorkersList[resource_id] =
std::make_unique<ResourceWorker>( m_apcStreamResourcesList[resource_id] );
return resource_id;
}
void ResourceHandle::removeResource( std::size_t id )
{
if( !m_apcStreamResourcesWorkersList.count( id ) )
if( !m_apcStreamResourcesList.contains( id ) )
{
assert( false );
return;
@@ -135,7 +197,7 @@ void ResourceHandle::removeResource( std::size_t id )
void ResourceHandle::stopResourceWorker( std::size_t id )
{
if( !m_apcStreamResourcesWorkersList.count( id ) )
if( !m_apcStreamResourcesWorkersList.contains( id ) )
{
assert( false );
return;
@@ -145,23 +207,23 @@ void ResourceHandle::stopResourceWorker( std::size_t id )
void ResourceHandle::startResourceWorker( std::size_t id )
{
if( !m_apcStreamResourcesWorkersList.count( id ) )
if( !m_apcStreamResourcesWorkersList.contains( id ) )
{
assert( false );
return;
}
m_apcStreamResourcesWorkersList[id]->setObjectName(
"RW-" +
QFileInfo( QString::fromStdString( m_apcStreamResourcesList[id]->getFileName() ) ).completeBaseName() );
QFileInfo( QString::fromStdString( m_apcStreamResourcesList[id]->getResourceName() ) ).completeBaseName() );
m_apcStreamResourcesWorkersList[id]->start();
}
void ResourceHandle::wakeResourceWorker( std::size_t id )
{
if( !m_apcStreamResourcesWorkersList.count( id ) )
if( !m_apcStreamResourcesWorkersList.contains( id ) )
{
assert( false );
return;
}
m_apcStreamResourcesWorkersList[id]->wake();
}
}
+51 -10
View File
@@ -26,11 +26,13 @@
#define __RESOURCEHANDLE_H__
#include <QMutex>
#include <QMutexLocker>
#include <QThread>
#include <QVector>
#include <QWaitCondition>
#include <atomic>
#include "CommonDefs.h"
#include "CalypResource.h"
#include "lib/CalypStream.h"
class ResourceWorker : public QThread
@@ -38,35 +40,74 @@ class ResourceWorker : public QThread
private:
QMutex m_Mutex;
QWaitCondition m_ResourceIdle;
std::shared_ptr<CalypStream> m_pcStream;
bool m_bStop{ false };
std::shared_ptr<CalypResource> m_resource;
std::atomic<bool> m_bStop{ false };
std::atomic<bool> m_bStarted{ false };
std::atomic<bool> m_bStarting{ false };
public:
ResourceWorker( std::shared_ptr<CalypStream> stream );
explicit ResourceWorker( std::shared_ptr<CalypResource> resource ) : m_resource{ std::move( resource ) } {}
ResourceWorker( ResourceWorker&& other ) noexcept = delete;
ResourceWorker( const ResourceWorker& other ) = delete;
auto operator=( ResourceWorker&& other ) noexcept -> ResourceWorker& = delete;
auto operator=( const ResourceWorker& other ) -> ResourceWorker& = delete;
~ResourceWorker() override;
void stop();
void wake();
void run();
void start();
void run() override;
auto mutex() -> QMutex* { return &m_Mutex; }
};
class ResourceHandle
class ResourceWorker;
class ResourceHandle : public QObject
{
Q_OBJECT
public:
ResourceHandle();
~ResourceHandle() = default;
ResourceHandle( ResourceHandle&& other ) noexcept = delete;
ResourceHandle( const ResourceHandle& other ) = delete;
auto operator=( ResourceHandle&& other ) noexcept -> ResourceHandle& = delete;
auto operator=( const ResourceHandle& other ) -> ResourceHandle& = delete;
~ResourceHandle() override;
auto getResource( CalypStream* ptr ) -> std::size_t;
auto getResourceAsset( std::size_t id ) -> CalypStream*;
auto appendResource( std::unique_ptr<CalypResource>&& resource ) -> std::size_t;
void removeResource( std::size_t id );
void stopResourceWorker( std::size_t id );
void startResourceWorker( std::size_t id );
void wakeResourceWorker( std::size_t id );
template <typename T>
auto executeResourceAction( std::size_t id, const std::function<bool( T* )>& action ) -> bool
{
static_assert( std::is_base_of<CalypResource, T>::value, "T must inherit from CalypResource" );
if( !m_apcStreamResourcesList.contains( id ) )
{
assert( false );
return false;
}
bool result{ false };
if( auto* resource = dynamic_cast<T*>( m_apcStreamResourcesList[id].get() ) )
{
QMutexLocker locker( m_apcStreamResourcesWorkersList[id]->mutex() );
result = action( resource );
}
m_apcStreamResourcesWorkersList[id]->wake();
return result;
}
void cleanup();
private:
auto addResource() -> std::size_t;
private:
std::size_t unique_id{ 0 };
std::map<std::size_t, std::shared_ptr<CalypStream>> m_apcStreamResourcesList;
private: // NOLINT
std::unique_ptr<QThread> m_thread;
std::map<std::size_t, std::shared_ptr<CalypResource>> m_apcStreamResourcesList;
std::map<std::size_t, std::unique_ptr<ResourceWorker>> m_apcStreamResourcesWorkersList;
};
+15 -8
View File
@@ -26,14 +26,16 @@
#include <QCloseEvent>
#include <QFocusEvent>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QIcon>
#include <QScreen>
#include <QScrollBar>
#include "MdiSubWindow.h"
SubWindowAbstract::SubWindowAbstract( QWidget* parent, unsigned int category )
: QWidget( parent ), m_cSubWindow( NULL )
: QWidget{ parent }, m_uiCategory{ category }, m_cWindowName{ " " }
{
setParent( parent );
setVisible( false );
@@ -44,11 +46,6 @@ SubWindowAbstract::SubWindowAbstract( QWidget* parent, unsigned int category )
setWindowIcon( QIcon( ":/logos/calyp-icon.png" ) );
// setWidgetResizable( true );
m_pcLayout = NULL;
m_uiCategory = category;
m_cWindowName = QString( " " );
connect( this, SIGNAL( destroyed() ), this, SLOT( onDestroyed() ) );
}
@@ -87,10 +84,20 @@ bool SubWindowAbstract::mayClose()
QSize SubWindowAbstract::sizeHint() const
{
return QSize();
QSize maxSize;
QWidget* p = parentWidget();
if( p )
{
maxSize = p->size();
}
else
{
maxSize = QGuiApplication::screens()[0]->availableGeometry().size();
}
return sizeHint( maxSize );
}
QSize SubWindowAbstract::sizeHint( const QSize& ) const
QSize SubWindowAbstract::sizeHint( const QSize& maxSize ) const
{
return QSize();
}
+4 -4
View File
@@ -56,11 +56,11 @@ class SubWindowAbstract : public QWidget
Q_OBJECT
private:
QHBoxLayout* m_pcLayout;
QHBoxLayout* m_pcLayout{ nullptr };
unsigned int m_uiCategory;
QString m_cWindowName;
MdiSubWindow* m_cSubWindow;
MdiSubWindow* m_cSubWindow{ nullptr };
public:
enum SubWindowCategory
@@ -90,7 +90,7 @@ public:
*/
virtual void zoomToFit() = 0;
/**
* Scale the image (zoomed in or out) to speficied absolute zoom value (1.0 =
* Scale the image (zoomed in or out) to specified absolute zoom value (1.0 =
* original size).
*/
virtual void zoomToFactor( double factor, QPoint center = QPoint() ) = 0;
@@ -107,7 +107,7 @@ public:
* Size related functions
*/
virtual QSize sizeHint() const;
virtual QSize sizeHint( const QSize& ) const;
virtual QSize sizeHint( const QSize& maxSize ) const;
/**
* Window name
+17 -18
View File
@@ -28,7 +28,6 @@
#include <QAction>
#include <QActionGroup>
#include <QApplication>
#include <QDesktopWidget>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QMdiArea>
@@ -85,7 +84,7 @@ private:
};
SubWindowHandle::SubWindowHandle( QWidget* parent )
: QWidget( parent )
: m_pcApp( qobject_cast<MainWindow*>( parent ) )
{
m_iWindowMode = -1;
m_pcWindowManagerLayout = NULL;
@@ -94,7 +93,7 @@ SubWindowHandle::SubWindowHandle( QWidget* parent )
m_apcSubWindowList.clear();
m_apcMdiSubWindowList.clear();
m_pcApp = qobject_cast<MainWindow*>( parentWidget() );
m_pcCentralWidget = new QWidget;
// setWindowMode( DETACHEDSUBWINDOWMODE );
setWindowMode( MDISUBWINDOWMODE );
}
@@ -152,8 +151,8 @@ void SubWindowHandle::setWindowMode( int iWindowMode )
m_apcSubWindowList.at( i )->resize( m_apcSubWindowList.at( i )->sizeHint() );
m_apcSubWindowList.at( i )->show();
}
setVisible( false );
parentWidget()->update();
m_pcCentralWidget->setVisible( false );
m_pcApp->update();
m_pcApp->showNormal();
qApp->processEvents();
QSize screenSize = QGuiApplication::screens()[0]->availableGeometry().size();
@@ -164,13 +163,13 @@ void SubWindowHandle::setWindowMode( int iWindowMode )
if( iWindowMode == MDISUBWINDOWMODE )
{
setVisible( true );
m_pcCentralWidget->setVisible( true );
m_pcMdiArea = new MdiArea;
m_pcMdiArea->setActivationOrder( QMdiArea::ActivationHistoryOrder );
connect( m_pcMdiArea, SIGNAL( subWindowActivated( QMdiSubWindow* ) ), this, SLOT( updateActiveSubWindow() ) );
m_pcWindowManagerLayout = new QHBoxLayout( this );
m_pcWindowManagerLayout = new QHBoxLayout( m_pcCentralWidget );
m_pcWindowManagerLayout->addWidget( m_pcMdiArea );
setLayout( m_pcWindowManagerLayout );
m_pcCentralWidget->setLayout( m_pcWindowManagerLayout );
for( int i = 0; i < m_apcSubWindowList.size(); i++ )
{
addMdiSubWindow( m_apcSubWindowList.at( i ) );
@@ -320,11 +319,6 @@ void SubWindowHandle::removeActiveSubWindow()
removeSubWindow( m_pcActiveWindow );
}
SubWindowAbstract* SubWindowHandle::activeSubWindow() const
{
return m_pcActiveWindow;
}
QList<SubWindowAbstract*> SubWindowHandle::findSubWindow( const unsigned int uiCategory ) const
{
QList<SubWindowAbstract*> apcSubWindowList;
@@ -491,12 +485,12 @@ void SubWindowHandle::createActions()
m_actionGroupWindowMode->actions().at( m_iWindowMode )->setChecked( true );
m_arrayActions[CLOSE_ACT] = new QAction( tr( "&Close" ), this );
m_arrayActions[CLOSE_ACT]->setIcon( style()->standardIcon( QStyle::SP_DialogCloseButton ) );
m_arrayActions[CLOSE_ACT]->setIcon( m_pcApp->style()->standardIcon( QStyle::SP_DialogCloseButton ) );
m_arrayActions[CLOSE_ACT]->setStatusTip( tr( "Close the active window" ) );
connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), this, SLOT( removeActiveSubWindow() ) );
m_arrayActions[CLOSE_ACT] = new QAction( tr( "&Close" ), this );
m_arrayActions[CLOSE_ACT]->setIcon( style()->standardIcon( QStyle::SP_DialogCloseButton ) );
m_arrayActions[CLOSE_ACT]->setIcon( m_pcApp->style()->standardIcon( QStyle::SP_DialogCloseButton ) );
m_arrayActions[CLOSE_ACT]->setStatusTip( tr( "Close the active window" ) );
connect( m_arrayActions[CLOSE_ACT], SIGNAL( triggered() ), this, SLOT( removeActiveSubWindow() ) );
@@ -519,14 +513,14 @@ void SubWindowHandle::createActions()
m_arrayActions[NEXT_WINDOWS_ACT] = new QAction( tr( "Ne&xt" ), this );
m_arrayActions[NEXT_WINDOWS_ACT]->setShortcuts( QKeySequence::NextChild );
m_arrayActions[NEXT_WINDOWS_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_ArrowRight ) ) );
m_arrayActions[NEXT_WINDOWS_ACT]->setIcon( QIcon( m_pcApp->style()->standardIcon( QStyle::SP_ArrowRight ) ) );
m_arrayActions[NEXT_WINDOWS_ACT]->setStatusTip( tr( "Move the focus to the next window" ) );
// connect( m_arrayActions[NEXT_WINDOWS_ACT], SIGNAL( triggered() ), this,
// SLOT( activateNextSubWindow() ) );
m_arrayActions[PREVIOUS_WINDOWS_ACT] = new QAction( tr( "Pre&vious" ), this );
m_arrayActions[PREVIOUS_WINDOWS_ACT]->setShortcuts( QKeySequence::PreviousChild );
m_arrayActions[PREVIOUS_WINDOWS_ACT]->setIcon( QIcon( style()->standardIcon( QStyle::SP_ArrowLeft ) ) );
m_arrayActions[PREVIOUS_WINDOWS_ACT]->setIcon( QIcon( m_pcApp->style()->standardIcon( QStyle::SP_ArrowLeft ) ) );
m_arrayActions[PREVIOUS_WINDOWS_ACT]->setStatusTip( tr( "Move the focus to the previous window" ) );
// connect( m_arrayActions[PREVIOUS_WINDOWS_ACT], SIGNAL( triggered() ),
// this, SLOT( activatePreviousSubWindow() ) );
@@ -537,12 +531,17 @@ void SubWindowHandle::createActions()
QMenu* SubWindowHandle::createMenu()
{
m_pcMenuWindow = new QMenu( "&Window", this );
m_pcMenuWindow = new QMenu( "&Window", m_pcApp );
updateMenu();
connect( m_pcMenuWindow, SIGNAL( aboutToShow() ), this, SLOT( updateMenu() ) );
return m_pcMenuWindow;
}
auto SubWindowHandle::getWidget() -> QWidget*
{
return m_pcCentralWidget;
}
void SubWindowHandle::updateMenu()
{
m_pcMenuWindow->clear();
+10 -2
View File
@@ -42,7 +42,7 @@ class SubWindowAbstract;
class MdiArea;
class MdiSubWindow;
class SubWindowHandle : public QWidget
class SubWindowHandle : public QObject
{
Q_OBJECT
@@ -53,7 +53,12 @@ public:
void addSubWindow( SubWindowAbstract* widget );
SubWindowAbstract* activeSubWindow() const;
template <class T = SubWindowAbstract>
T* activeSubWindow() const
{
static_assert( std::is_base_of<SubWindowAbstract, T>::value, "T must inherit from SubWindowAbstract" );
return qobject_cast<T*>( m_pcActiveWindow );
}
QList<SubWindowAbstract*> findSubWindow( const unsigned int uiCategory = 0 ) const;
QList<SubWindowAbstract*> findSubWindow( const QString& aName, const unsigned int uiCategory = 0 ) const;
@@ -62,6 +67,8 @@ public:
void createActions();
QMenu* createMenu();
auto getWidget() -> QWidget*;
void readSettings();
void writeSettings();
@@ -76,6 +83,7 @@ private:
int m_iWindowMode;
QList<SubWindowAbstract*> m_apcSubWindowList;
QWidget* m_pcCentralWidget;
QHBoxLayout* m_pcWindowManagerLayout;
MdiArea* m_pcMdiArea;
QList<MdiSubWindow*> m_apcMdiSubWindowList;
+213 -104
View File
@@ -32,6 +32,7 @@
#include <QTimer>
#include <QToolBar>
#include <QtGui>
#include <limits>
#include <memory>
#include "FrameNumberWidget.h"
@@ -40,18 +41,18 @@
#include "SeekStreamDialog.h"
#include "SubWindowHandle.h"
#include "SubWindowSelectorDialog.h"
#include "VideoStreamSubWindow.h"
#include "VideoSubWindow.h"
#include "lib/CalypFrame.h"
VideoHandle::VideoHandle( QWidget* parent, SubWindowHandle* windowManager )
: m_pcParet( parent ), m_pcMainWindowManager( windowManager )
: m_pcParent{ parent }
, m_pcMainWindowManager{ windowManager }
, m_pcPlayingTimer{ new QTimer{ this } }
, m_pcFrameRateFeedbackTimer{ std::make_unique<QElapsedTimer>() }
{
m_pcCurrentVideoSubWindow = NULL;
m_bIsPlaying = false;
m_pcPlayingTimer = new QTimer( this );
m_pcFrameRateFeedbackTimer = std::make_unique<QElapsedTimer>();
m_pcPlayingTimer->setTimerType( Qt::PreciseTimer );
connect( m_pcPlayingTimer, &QTimer::timeout,
this, &VideoHandle::playEvent );
connect( m_pcPlayingTimer, &QTimer::timeout, this, &VideoHandle::playEvent );
m_acPlayingSubWindows.clear();
}
@@ -59,16 +60,20 @@ VideoHandle::~VideoHandle() = default;
void VideoHandle::createActions()
{
if( m_pcParent == nullptr )
{
return;
}
m_arrayActions.resize( TOTAL_ACT );
m_arrayActions[PLAY_ACT] = new QAction( "Play", this );
m_arrayActions[PLAY_ACT]->setStatusTip( "Play/Pause" );
m_arrayActions[PLAY_ACT]->setIcon( QIcon( m_pcParet->style()->standardIcon( QStyle::SP_MediaPlay ) ) );
m_arrayActions[PLAY_ACT]->setIcon( QIcon( m_pcParent->style()->standardIcon( QStyle::SP_MediaPlay ) ) );
m_arrayActions[PLAY_ACT]->setShortcut( Qt::Key_Space );
connect( m_arrayActions[PLAY_ACT], SIGNAL( triggered() ), this, SLOT( play() ) );
m_arrayActions[STOP_ACT] = new QAction( "Stop", this );
m_arrayActions[STOP_ACT]->setStatusTip( "Stop" );
m_arrayActions[STOP_ACT]->setIcon( QIcon( m_pcParet->style()->standardIcon( QStyle::SP_MediaStop ) ) );
m_arrayActions[STOP_ACT]->setIcon( QIcon( m_pcParent->style()->standardIcon( QStyle::SP_MediaStop ) ) );
connect( m_arrayActions[STOP_ACT], SIGNAL( triggered() ), this, SLOT( stop() ) );
m_mapperVideoSeek = new QSignalMapper( this );
@@ -77,7 +82,7 @@ void VideoHandle::createActions()
m_arrayActions[VIDEO_BACKWARD_ACT] = new QAction( "Video Backward", this );
m_arrayActions[VIDEO_BACKWARD_ACT]->setStatusTip( "Seek backward" );
m_arrayActions[VIDEO_BACKWARD_ACT]->setIcon(
QIcon( m_pcParet->style()->standardIcon( QStyle::SP_MediaSeekBackward ) ) );
QIcon( m_pcParent->style()->standardIcon( QStyle::SP_MediaSeekBackward ) ) );
m_arrayActions[VIDEO_BACKWARD_ACT]->setShortcut( Qt::Key_Left );
connect( m_arrayActions[VIDEO_BACKWARD_ACT], SIGNAL( triggered() ), m_mapperVideoSeek, SLOT( map() ) );
m_mapperVideoSeek->setMapping( m_arrayActions[VIDEO_BACKWARD_ACT], 0 );
@@ -85,7 +90,7 @@ void VideoHandle::createActions()
m_arrayActions[VIDEO_FORWARD_ACT] = new QAction( "Video Forward", this );
m_arrayActions[VIDEO_FORWARD_ACT]->setStatusTip( "Seek forward" );
m_arrayActions[VIDEO_FORWARD_ACT]->setIcon(
QIcon( m_pcParet->style()->standardIcon( QStyle::SP_MediaSeekForward ) ) );
QIcon( m_pcParent->style()->standardIcon( QStyle::SP_MediaSeekForward ) ) );
m_arrayActions[VIDEO_FORWARD_ACT]->setShortcut( Qt::Key_Right );
connect( m_arrayActions[VIDEO_FORWARD_ACT], SIGNAL( triggered() ), m_mapperVideoSeek, SLOT( map() ) );
m_mapperVideoSeek->setMapping( m_arrayActions[VIDEO_FORWARD_ACT], 1 );
@@ -122,6 +127,24 @@ void VideoHandle::createActions()
connect( m_pcFrameSlider, SIGNAL( valueChanged( int ) ), this, SLOT( seekSliderEvent( int ) ) );
// ------------ Image ------------
m_mapperComponent = new QSignalMapper( this );
m_actionGroupComponent = new QActionGroup( this );
m_actionGroupComponent->setExclusive( true );
m_mapperComponent->setMapping( m_actionGroupComponent->addAction( "All" ), -1 );
m_mapperComponent->setMapping( m_actionGroupComponent->addAction( "Red" ), 0 );
m_mapperComponent->setMapping( m_actionGroupComponent->addAction( "Green" ), 1 );
m_mapperComponent->setMapping( m_actionGroupComponent->addAction( "Blue" ), 2 );
m_mapperComponent->setMapping( m_actionGroupComponent->addAction( "Alpha" ), 3 );
for( int i = 0; i < m_actionGroupComponent->actions().size(); i++ )
{
m_actionGroupComponent->actions().at( i )->setCheckable( true );
m_actionGroupComponent->actions().at( i )->setVisible( false );
connect( m_actionGroupComponent->actions().at( i ), SIGNAL( triggered() ), m_mapperComponent, SLOT( map() ) );
}
m_actionGroupComponent->actions().at( 0 )->setChecked( true );
m_actionGroupComponent->actions().at( 0 )->setVisible( true );
connect( m_mapperComponent, SIGNAL( mapped( int ) ), this, SLOT( setComponent( int ) ) );
m_actionGroupTools = new QActionGroup( this );
m_actionGroupTools->setExclusive( true );
@@ -133,7 +156,7 @@ void VideoHandle::createActions()
m_arrayActions[NAVIGATION_TOOL_ACT] = new QAction( tr( "Navigation Tool" ), this );
m_arrayActions[NAVIGATION_TOOL_ACT]->setCheckable( true );
m_arrayActions[NAVIGATION_TOOL_ACT]->setChecked( true );
m_arrayActions[NAVIGATION_TOOL_ACT]->setShortcut( Qt::CTRL + Qt::Key_1 );
m_arrayActions[NAVIGATION_TOOL_ACT]->setShortcut( Qt::CTRL | Qt::Key_1 );
m_actionGroupTools->addAction( m_arrayActions[NAVIGATION_TOOL_ACT] );
connect( m_arrayActions[NAVIGATION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, SLOT( map() ) );
m_mapperTools->setMapping( m_arrayActions[NAVIGATION_TOOL_ACT], ViewArea::NavigationView );
@@ -141,7 +164,7 @@ void VideoHandle::createActions()
m_arrayActions[SELECTION_TOOL_ACT] = new QAction( "Selection Tool", this );
m_arrayActions[SELECTION_TOOL_ACT]->setCheckable( true );
m_arrayActions[SELECTION_TOOL_ACT]->setChecked( false );
m_arrayActions[SELECTION_TOOL_ACT]->setShortcut( Qt::CTRL + Qt::Key_2 );
m_arrayActions[SELECTION_TOOL_ACT]->setShortcut( Qt::CTRL | Qt::Key_2 );
m_actionGroupTools->addAction( m_arrayActions[SELECTION_TOOL_ACT] );
connect( m_arrayActions[SELECTION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, SLOT( map() ) );
m_mapperTools->setMapping( m_arrayActions[SELECTION_TOOL_ACT], ViewArea::NormalSelectionView );
@@ -149,7 +172,7 @@ void VideoHandle::createActions()
m_arrayActions[BLOCK_SELECTION_TOOL_ACT] = new QAction( "Block Selection Tool", this );
m_arrayActions[BLOCK_SELECTION_TOOL_ACT]->setCheckable( true );
m_arrayActions[BLOCK_SELECTION_TOOL_ACT]->setChecked( false );
m_arrayActions[BLOCK_SELECTION_TOOL_ACT]->setShortcut( Qt::CTRL + Qt::Key_3 );
m_arrayActions[BLOCK_SELECTION_TOOL_ACT]->setShortcut( Qt::CTRL | Qt::Key_3 );
m_actionGroupTools->addAction( m_arrayActions[BLOCK_SELECTION_TOOL_ACT] );
connect( m_arrayActions[BLOCK_SELECTION_TOOL_ACT], SIGNAL( triggered() ), m_mapperTools, SLOT( map() ) );
m_mapperTools->setMapping( m_arrayActions[BLOCK_SELECTION_TOOL_ACT], ViewArea::BlockSelectionView );
@@ -157,9 +180,11 @@ void VideoHandle::createActions()
m_mapperGrid = new QSignalMapper( this );
m_actionGroupGrid = new QActionGroup( this );
m_actionGroupGrid->setExclusive( true );
m_mapperGrid->setMapping( m_actionGroupGrid->addAction( "4x4" ), 4 );
m_mapperGrid->setMapping( m_actionGroupGrid->addAction( "8x8" ), 8 );
m_mapperGrid->setMapping( m_actionGroupGrid->addAction( "16x16" ), 16 );
m_mapperGrid->setMapping( m_actionGroupGrid->addAction( "64x64" ), 64 );
m_mapperGrid->setMapping( m_actionGroupGrid->addAction( "128x128" ), 128 );
for( int i = 0; i < m_actionGroupGrid->actions().size(); i++ )
{
@@ -177,7 +202,11 @@ void VideoHandle::createActions()
QMenu* VideoHandle::createVideoMenu()
{
m_pcMenuVideo = new QMenu( "Video", m_pcParet );
if( m_pcParent == nullptr )
{
return nullptr;
}
m_pcMenuVideo = new QMenu( "Video", m_pcParent );
m_pcMenuVideo->addAction( m_arrayActions[PLAY_ACT] );
m_pcMenuVideo->addAction( m_arrayActions[STOP_ACT] );
m_pcMenuVideo->addAction( m_arrayActions[VIDEO_BACKWARD_ACT] );
@@ -192,7 +221,13 @@ QMenu* VideoHandle::createVideoMenu()
QMenu* VideoHandle::createImageMenu()
{
m_pcMenuImage = new QMenu( "Image", m_pcParet );
if( m_pcParent == nullptr )
{
return nullptr;
}
m_pcMenuImage = new QMenu( "Image", m_pcParent );
m_menuComponent = m_pcMenuImage->addMenu( "Component" );
m_menuComponent->addActions( m_actionGroupComponent->actions() );
m_pcMenuImage->addAction( m_arrayActions[NAVIGATION_TOOL_ACT] );
m_pcMenuImage->addAction( m_arrayActions[SELECTION_TOOL_ACT] );
m_pcMenuImage->addAction( m_arrayActions[BLOCK_SELECTION_TOOL_ACT] );
@@ -203,14 +238,16 @@ QMenu* VideoHandle::createImageMenu()
return m_pcMenuImage;
}
QToolBar* VideoHandle::createToolBar()
auto VideoHandle::createToolBar() -> QPointer<QToolBar>
{
m_toolbarVideo = new QToolBar( tr( "Video" ) );
if( m_pcParent == nullptr ) return nullptr;
QPointer m_toolbarVideo = new QToolBar( tr( "Video" ) );
m_toolbarVideo->setAllowedAreas( Qt::TopToolBarArea | Qt::BottomToolBarArea );
m_toolbarVideo->addAction( m_arrayActions[PLAY_ACT] );
m_toolbarVideo->addAction( m_arrayActions[STOP_ACT] );
QLabel* pcLockLabel = new QLabel( "PlayingLock" );
QPointer pcLockLabel = new QLabel( "PlayingLock" );
pcLockLabel->setAlignment( Qt::AlignCenter );
m_arrayActions[VIDEO_LOCK_ACT] = m_toolbarVideo->addWidget( pcLockLabel );
m_arrayActions[VIDEO_LOCK_ACT]->setVisible( false );
@@ -219,6 +256,7 @@ QToolBar* VideoHandle::createToolBar()
m_toolbarVideo->addWidget( m_pcFrameSlider );
m_toolbarVideo->addAction( m_arrayActions[VIDEO_FORWARD_ACT] );
m_toolbarVideo->addWidget( new QLabel );
m_pcFrameNumInfo = new FrameNumberWidget;
m_toolbarVideo->addWidget( m_pcFrameNumInfo );
@@ -227,8 +265,12 @@ QToolBar* VideoHandle::createToolBar()
QDockWidget* VideoHandle::createDock()
{
m_pcFramePropertiesSideBar = new FramePropertiesDock( m_pcParet, &m_bIsPlaying );
m_pcFramePropertiesDock = new QDockWidget( tr( "Frame Information" ), m_pcParet );
if( m_pcParent == nullptr )
{
return nullptr;
}
m_pcFramePropertiesSideBar = new FramePropertiesDock( m_pcParent, &m_bIsPlaying );
m_pcFramePropertiesDock = new QDockWidget( tr( "Frame Information" ), m_pcParent );
m_pcFramePropertiesDock->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea );
m_pcFramePropertiesDock->setWidget( m_pcFramePropertiesSideBar );
connect( m_pcFramePropertiesDock, SIGNAL( visibilityChanged( bool ) ), this, SLOT( update() ) );
@@ -238,6 +280,10 @@ QDockWidget* VideoHandle::createDock()
QWidget* VideoHandle::createStatusBarMessage()
{
if( m_pcParent == nullptr )
{
return nullptr;
}
QWidget* pcStatusBarWidget = new QWidget;
QHBoxLayout* mainlayout = new QHBoxLayout;
@@ -267,9 +313,65 @@ QWidget* VideoHandle::createStatusBarMessage()
return pcStatusBarWidget;
}
void VideoHandle::updateComponentMenu()
{
VideoSubWindow* pcSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
if( pcSubWindow == nullptr )
{
m_menuComponent->setEnabled( false );
return;
}
const auto* frame = pcSubWindow->getCurrFrame();
if( frame == nullptr )
{
m_menuComponent->setEnabled( false );
return;
}
m_menuComponent->setEnabled( true );
for( int i = 1; i < m_actionGroupComponent->actions().size(); i++ )
{
m_actionGroupComponent->actions()[i]->setChecked( false );
m_actionGroupComponent->actions()[i]->setVisible( false );
}
switch( frame->getColorSpace() )
{
case CLP_COLOR_GRAY:
m_actionGroupComponent->actions().at( 1 )->setText( QStringLiteral( "Gray" ) );
m_actionGroupComponent->actions().at( 1 )->setVisible( true );
break;
case CLP_COLOR_YUV:
m_actionGroupComponent->actions().at( 1 )->setText( QStringLiteral( "Luminance" ) );
m_actionGroupComponent->actions().at( 1 )->setVisible( true );
m_actionGroupComponent->actions().at( 2 )->setText( QStringLiteral( "Chrominance U (Cb)" ) );
m_actionGroupComponent->actions().at( 2 )->setVisible( true );
m_actionGroupComponent->actions().at( 3 )->setText( QStringLiteral( "Chrominance V (Cr)" ) );
m_actionGroupComponent->actions().at( 3 )->setVisible( true );
break;
case CLP_COLOR_RGBA:
m_actionGroupComponent->actions().at( 4 )->setText( QStringLiteral( "Alpha" ) );
m_actionGroupComponent->actions().at( 4 )->setVisible( true );
[[fallthrough]];
case CLP_COLOR_RGB:
m_actionGroupComponent->actions().at( 1 )->setText( QStringLiteral( "Red" ) );
m_actionGroupComponent->actions().at( 1 )->setVisible( true );
m_actionGroupComponent->actions().at( 2 )->setText( QStringLiteral( "Green" ) );
m_actionGroupComponent->actions().at( 2 )->setVisible( true );
m_actionGroupComponent->actions().at( 3 )->setText( QStringLiteral( "Blue" ) );
m_actionGroupComponent->actions().at( 3 )->setVisible( true );
break;
default:
Q_ASSERT( false );
}
auto component = pcSubWindow->getViewArea()->getFilteredChannel();
int idx = component.has_value() ? *component : 0;
m_actionGroupComponent->actions().at( idx )->setChecked( true );
}
void VideoHandle::updateMenus()
{
VideoSubWindow* pcSubWindow = qobject_cast<VideoSubWindow*>( m_pcMainWindowManager->activeSubWindow() );
VideoSubWindow* pcSubWindow = m_pcMainWindowManager->activeSubWindow<VideoSubWindow>();
bool hasSubWindow = pcSubWindow ? true : false;
m_arrayActions[PLAY_ACT]->setEnabled( hasSubWindow );
@@ -295,6 +397,8 @@ void VideoHandle::updateMenus()
m_arrayActions[SELECTION_TOOL_ACT]->setEnabled( hasSubWindow );
m_arrayActions[BLOCK_SELECTION_TOOL_ACT]->setEnabled( hasSubWindow );
m_arrayActions[SHOW_GRID_ACT]->setEnabled( hasSubWindow );
updateComponentMenu();
}
void VideoHandle::readSettings()
@@ -302,8 +406,7 @@ void VideoHandle::readSettings()
QSettings appSettings;
m_arrayActions[VIDEO_REPEAT_ACT]->setChecked( appSettings.value( "VideoHandle/Repeat", false ).toBool() );
m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->setChecked( appSettings.value( "VideoHandle/VideoZoomLock", false ).toBool() );
if( !appSettings.value( "VideoHandle/FrameProperties", true ).toBool() )
m_pcFramePropertiesDock->close();
if( !appSettings.value( "VideoHandle/FrameProperties", true ).toBool() ) m_pcFramePropertiesDock->close();
m_uiViewTool = appSettings.value( "VideoHandle/SelectedTool", ViewArea::NavigationView ).toUInt();
setTool( m_uiViewTool );
@@ -325,10 +428,16 @@ void VideoHandle::update()
{
if( m_pcCurrentVideoSubWindow )
{
const CalypStream* pcStream = m_pcCurrentVideoSubWindow->getInputStream();
const CalypFrame* pcFrame = m_pcCurrentVideoSubWindow->getCurrFrame();
bool isPlaying{ false };
const CalypStream* pcStream{ nullptr };
if( auto* videoStreamSubWindow = qobject_cast<VideoStreamSubWindow*>( m_pcCurrentVideoSubWindow ) )
{
pcStream = videoStreamSubWindow->getInputStream();
isPlaying = videoStreamSubWindow->isPlaying();
}
auto pcFrame = m_pcCurrentVideoSubWindow->getCurrFrameAsset();
m_pcVideoFormatLabel->setText( m_pcCurrentVideoSubWindow->getStreamInformation() );
m_pcVideoFormatLabel->setText( m_pcCurrentVideoSubWindow->getVideoInformation() );
QString resolution;
if( pcFrame )
@@ -362,7 +471,7 @@ void VideoHandle::update()
}
}
m_pcResolutionLabel->setText( resolution );
m_pcFramePropertiesSideBar->setFrame( m_pcCurrentVideoSubWindow->getCurrFrameAsset(), m_pcCurrentVideoSubWindow->isPlaying() );
m_pcFramePropertiesSideBar->setFrame( pcFrame, isPlaying );
m_pcFrameNumInfo->setTotalFrameNum( total_frame_num );
m_pcFrameNumInfo->setCurrFrameNum( frame_num );
@@ -380,12 +489,12 @@ void VideoHandle::update()
if( m_pcCurrentVideoSubWindow->isPlaying() )
{
m_arrayActions[PLAY_ACT]->setText( "Pause" );
m_arrayActions[PLAY_ACT]->setIcon( m_pcParet->style()->standardIcon( QStyle::SP_MediaPause ) );
m_arrayActions[PLAY_ACT]->setIcon( m_pcParent->style()->standardIcon( QStyle::SP_MediaPause ) );
}
else
{
m_arrayActions[PLAY_ACT]->setText( "Play" );
m_arrayActions[PLAY_ACT]->setIcon( m_pcParet->style()->standardIcon( QStyle::SP_MediaPlay ) );
m_arrayActions[PLAY_ACT]->setIcon( m_pcParent->style()->standardIcon( QStyle::SP_MediaPlay ) );
}
}
else
@@ -419,26 +528,22 @@ void VideoHandle::addSubWindow( VideoSubWindow* window )
window->getViewArea()->setTool( m_uiViewTool );
window->getViewArea()->setGridVisible( m_arrayActions[SHOW_GRID_ACT]->isChecked() );
connect( window, &SubWindowAbstract::aboutToClose,
this, &VideoHandle::closeSubWindow );
connect( window, &SubWindowAbstract::aboutToClose, this, &VideoHandle::closeSubWindow );
connect( window, &SubWindowAbstract::zoomFactorChanged,
this, &VideoHandle::zoomToFactorAll );
connect( window, &SubWindowAbstract::zoomFactorChanged, this, &VideoHandle::zoomToFactorAll );
connect( window, &SubWindowAbstract::scrollBarMoved,
this, &VideoHandle::moveAllScrollBars );
connect( window, &SubWindowAbstract::scrollBarMoved, this, &VideoHandle::moveAllScrollBars );
connect( window->getViewArea(), SIGNAL( selectionChanged( QRect ) ), this, SLOT( updateSelectionArea( QRect ) ) );
}
void VideoHandle::closeSubWindow( SubWindowAbstract* subWindow )
{
VideoSubWindow* videoSubWindow = qobject_cast<VideoSubWindow*>( subWindow );
auto* videoStreamSubWindow = qobject_cast<VideoStreamSubWindow*>( subWindow );
if( m_acPlayingSubWindows.contains( videoSubWindow ) )
if( m_acPlayingSubWindows.contains( videoStreamSubWindow ) )
{
int pos = m_acPlayingSubWindows.indexOf( videoSubWindow );
// m_acPlayingSubWindows.at( pos )->stop();
int pos = m_acPlayingSubWindows.indexOf( videoStreamSubWindow );
m_acPlayingSubWindows.remove( pos );
if( m_acPlayingSubWindows.size() < 2 )
{
@@ -453,18 +558,15 @@ void VideoHandle::closeSubWindow( SubWindowAbstract* subWindow )
void VideoHandle::zoomToFactorAll( const double scale, const QPoint center )
{
double factor;
if( m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->isChecked() )
{
factor = m_pcCurrentVideoSubWindow->getScaleFactor();
double factor = m_pcCurrentVideoSubWindow->getScaleFactor();
SubWindowAbstract* subWindow;
QList<SubWindowAbstract*> subWindowList =
m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW );
for( int i = 0; i < subWindowList.size(); i++ )
{
subWindow = subWindowList.at( i );
SubWindowAbstract* subWindow = subWindowList.at( i );
if( m_pcCurrentVideoSubWindow == subWindow )
continue;
else
@@ -518,12 +620,12 @@ void VideoHandle::moveAllScrollBars( const double& horRatio, const double& verRa
{
if( m_arrayActions[VIDEO_ZOOM_LOCK_ACT]->isChecked() && m_pcCurrentVideoSubWindow )
{
VideoSubWindow* videoSubWindow;
QList<SubWindowAbstract*> subWindowList = m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW );
QList<SubWindowAbstract*> subWindowList =
m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_SUBWINDOW );
for( int i = 0; i < subWindowList.size(); i++ )
{
videoSubWindow = qobject_cast<VideoSubWindow*>( subWindowList.at( i ) );
VideoSubWindow* videoSubWindow = qobject_cast<VideoSubWindow*>( subWindowList.at( i ) );
if( m_pcCurrentVideoSubWindow == videoSubWindow )
continue;
else
@@ -537,22 +639,20 @@ void VideoHandle::moveAllScrollBars( const double& horRatio, const double& verRa
unsigned long VideoHandle::getMaxFrameNumber()
{
unsigned long currFrames;
unsigned long maxFrames = INT_MAX;
std::uint64_t maxFrames = std::numeric_limits<std::uint64_t>::max();
if( m_pcCurrentVideoSubWindow )
{
if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) )
if( m_acPlayingSubWindows.contains( qobject_cast<VideoStreamSubWindow*>( m_pcCurrentVideoSubWindow ) ) )
{
for( int i = 0; i < m_acPlayingSubWindows.size(); i++ )
{
currFrames = m_acPlayingSubWindows.at( i )->getInputStream()->getFrameNum();
if( currFrames < maxFrames )
maxFrames = currFrames;
auto currFrames = m_acPlayingSubWindows.at( i )->getFrameNum();
if( currFrames < maxFrames ) maxFrames = currFrames;
}
}
else
{
maxFrames = m_pcCurrentVideoSubWindow->getInputStream()->getFrameNum();
maxFrames = m_pcCurrentVideoSubWindow->getFrameNum();
}
}
return maxFrames;
@@ -565,9 +665,9 @@ void VideoHandle::setTimerStatus()
{
status |= m_acPlayingSubWindows.at( i )->isPlaying();
}
if( m_pcCurrentVideoSubWindow )
if( auto* videoStreamSubWindow = qobject_cast<VideoStreamSubWindow*>( m_pcCurrentVideoSubWindow ) )
{
status |= m_pcCurrentVideoSubWindow->isPlaying();
status |= videoStreamSubWindow->isPlaying();
}
if( status )
{
@@ -596,13 +696,11 @@ void VideoHandle::configureFrameRateTimer()
void VideoHandle::play()
{
if( !m_pcCurrentVideoSubWindow )
return;
auto* videoStreamSubWindow = qobject_cast<VideoStreamSubWindow*>( m_pcCurrentVideoSubWindow );
if( !m_pcCurrentVideoSubWindow->getInputStream() )
return;
if( videoStreamSubWindow == nullptr ) return;
if( !m_pcCurrentVideoSubWindow->isPlaying() ) // Not playing
if( !videoStreamSubWindow->isPlaying() ) // Not playing
{
if( m_acPlayingSubWindows.size() < 2 )
{
@@ -611,9 +709,9 @@ void VideoHandle::play()
m_acPlayingSubWindows.at( i )->pause();
}
m_acPlayingSubWindows.clear();
m_acPlayingSubWindows.append( m_pcCurrentVideoSubWindow );
m_acPlayingSubWindows.append( videoStreamSubWindow );
}
if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) )
if( m_acPlayingSubWindows.contains( videoStreamSubWindow ) )
{
for( int i = 0; i < m_acPlayingSubWindows.size(); i++ )
{
@@ -624,7 +722,7 @@ void VideoHandle::play()
}
else
{
if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) )
if( m_acPlayingSubWindows.contains( videoStreamSubWindow ) )
{
for( int i = 0; i < m_acPlayingSubWindows.size(); i++ )
{
@@ -633,12 +731,11 @@ void VideoHandle::play()
}
else
{
m_pcCurrentVideoSubWindow->pause();
videoStreamSubWindow->pause();
}
}
setTimerStatus();
emit changed();
// update();
}
void VideoHandle::stop()
@@ -666,9 +763,13 @@ void VideoHandle::stop()
void VideoHandle::calculateRealFrameRate()
{
double average_time_between_frames_ms = m_uiNumberPlayedFrames > 0 ? 1000.0 / m_uiRealAverageFrameRate : 0;
double time_elapsed_since_last_frame_ms = m_pcFrameRateFeedbackTimer->elapsed();
average_time_between_frames_ms = double( average_time_between_frames_ms * m_uiNumberPlayedFrames + time_elapsed_since_last_frame_ms ) / double( m_uiNumberPlayedFrames + 1 );
m_uiRealAverageFrameRate = 1000.0 / average_time_between_frames_ms;
auto time_elapsed_since_last_frame_ms = static_cast<double>( m_pcFrameRateFeedbackTimer->elapsed() );
average_time_between_frames_ms =
double( average_time_between_frames_ms * m_uiNumberPlayedFrames + time_elapsed_since_last_frame_ms ) /
double( m_uiNumberPlayedFrames + 1 );
m_uiRealAverageFrameRate =
std::round<unsigned int>( static_cast<unsigned int>( 1000.0 / average_time_between_frames_ms ) );
m_uiNumberPlayedFrames++;
m_pcFrameRateFeedbackTimer->restart();
}
@@ -711,16 +812,14 @@ void VideoHandle::playEvent()
}
catch( const char* msg )
{
QString warningMsg = "Error while playing " +
QFileInfo( m_pcCurrentVideoSubWindow->getCurrentFileName() ).fileName() +
" with the following error: \n" + msg;
QMessageBox::warning( m_pcParet, QApplication::applicationName(), warningMsg );
QString warningMsg =
"Error while playing " + m_pcCurrentVideoSubWindow->getWindowName() + " with the following error: \n" + msg;
QMessageBox::warning( m_pcParent, QApplication::applicationName(), warningMsg );
qDebug() << warningMsg;
stop();
m_pcCurrentVideoSubWindow->close();
}
if( bShouldRefreshUI )
emit changed();
if( bShouldRefreshUI ) emit changed();
// auto end = std::chrono::steady_clock::now();
// std::cout << "Elapsed time going to next frame: "
@@ -730,11 +829,11 @@ void VideoHandle::playEvent()
void VideoHandle::seekEvent( int direction )
{
if( m_pcCurrentVideoSubWindow )
if( auto* videoStreamSubWindow = qobject_cast<VideoStreamSubWindow*>( m_pcCurrentVideoSubWindow ) )
{
if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) )
if( m_acPlayingSubWindows.contains( videoStreamSubWindow ) )
{
if( !( (unsigned int)( m_pcCurrentVideoSubWindow->getInputStream()->getCurrFrameNum() + 1 ) >= getMaxFrameNumber() &&
if( !( (unsigned int)( videoStreamSubWindow->getInputStream()->getCurrFrameNum() + 1 ) >= getMaxFrameNumber() &&
direction > 0 ) )
{
for( auto playingSubWindow : m_acPlayingSubWindows )
@@ -745,7 +844,7 @@ void VideoHandle::seekEvent( int direction )
}
else
{
m_pcCurrentVideoSubWindow->seekRelativeEvent( direction > 0 ? true : false );
videoStreamSubWindow->seekRelativeEvent( direction > 0 ? true : false );
}
emit changed();
}
@@ -753,37 +852,36 @@ void VideoHandle::seekEvent( int direction )
void VideoHandle::seekVideo()
{
if( m_pcCurrentVideoSubWindow )
if( auto* videoStreamSubWindow = qobject_cast<VideoStreamSubWindow*>( m_pcCurrentVideoSubWindow ) )
{
if( m_pcCurrentVideoSubWindow->getInputStream() )
SeekStreamDialog* dialogSeekVideo = new SeekStreamDialog( videoStreamSubWindow->getInputStream(), m_pcParent );
int newFrameNum = dialogSeekVideo->runDialog();
if( newFrameNum >= 0 )
{
SeekStreamDialog* dialogSeekVideo =
new SeekStreamDialog( m_pcCurrentVideoSubWindow->getInputStream(), m_pcParet );
int newFrameNum = dialogSeekVideo->runDialog();
if( newFrameNum >= 0 )
if( m_acPlayingSubWindows.contains( videoStreamSubWindow ) )
{
if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) )
for( auto playingSubWindow : m_acPlayingSubWindows )
{
for( auto playingSubWindow : m_acPlayingSubWindows )
{
playingSubWindow->seekAbsoluteEvent( (unsigned int)newFrameNum );
}
playingSubWindow->seekAbsoluteEvent( (unsigned int)newFrameNum );
}
else
{
m_pcCurrentVideoSubWindow->seekAbsoluteEvent( (unsigned int)newFrameNum );
}
emit changed();
}
else
{
videoStreamSubWindow->seekAbsoluteEvent( (unsigned int)newFrameNum );
}
emit changed();
}
}
}
void VideoHandle::seekSliderEvent( int new_frame_num )
{
if( m_pcCurrentVideoSubWindow && !m_bIsPlaying ) // TODO: Fix this slot
// TODO: Fix this slot
if( m_bIsPlaying ) return;
if( auto* videoStreamSubWindow = qobject_cast<VideoStreamSubWindow*>( m_pcCurrentVideoSubWindow ) )
{
if( m_acPlayingSubWindows.contains( m_pcCurrentVideoSubWindow ) )
if( m_acPlayingSubWindows.contains( videoStreamSubWindow ) )
{
for( auto playingSubWindow : m_acPlayingSubWindows )
{
@@ -792,7 +890,7 @@ void VideoHandle::seekSliderEvent( int new_frame_num )
}
else
{
m_pcCurrentVideoSubWindow->seekAbsoluteEvent( (unsigned int)new_frame_num );
videoStreamSubWindow->seekAbsoluteEvent( (unsigned int)new_frame_num );
}
emit changed();
}
@@ -800,8 +898,6 @@ void VideoHandle::seekSliderEvent( int new_frame_num )
void VideoHandle::videoSelectionButtonEvent()
{
VideoSubWindow* videoSubWindow;
Qt::KeyboardModifiers keyModifiers = QApplication::keyboardModifiers();
if( keyModifiers & Qt::ControlModifier )
{
@@ -809,13 +905,13 @@ void VideoHandle::videoSelectionButtonEvent()
m_pcMainWindowManager->findSubWindow( SubWindowAbstract::VIDEO_STREAM_SUBWINDOW );
for( auto subWindow : subWindowList )
{
videoSubWindow = qobject_cast<VideoSubWindow*>( subWindow );
auto* videoSubWindow = qobject_cast<VideoStreamSubWindow*>( subWindow );
m_acPlayingSubWindows.append( videoSubWindow );
}
}
else
{
SubWindowSelectorDialog dialogWindowsSelection( m_pcParet, m_pcMainWindowManager,
SubWindowSelectorDialog dialogWindowsSelection( m_pcParent, m_pcMainWindowManager,
SubWindowAbstract::VIDEO_STREAM_SUBWINDOW );
QStringList cWindowListNames;
for( auto playingSubWindow : m_acPlayingSubWindows )
@@ -829,7 +925,7 @@ void VideoHandle::videoSelectionButtonEvent()
QList<SubWindowAbstract*> selectedSubWindowList = dialogWindowsSelection.getSelectedWindows();
for( auto window : selectedSubWindowList )
{
videoSubWindow = qobject_cast<VideoSubWindow*>( window );
auto* videoSubWindow = qobject_cast<VideoStreamSubWindow*>( window );
m_acPlayingSubWindows.append( videoSubWindow );
}
}
@@ -860,6 +956,19 @@ void VideoHandle::videoSelectionButtonEvent()
}
}
void VideoHandle::setComponent( int component )
{
if( m_pcCurrentVideoSubWindow == nullptr ) return;
if( component < 0 )
{
m_pcCurrentVideoSubWindow->getViewArea()->clearFilteredChannel();
}
else
{
m_pcCurrentVideoSubWindow->getViewArea()->setFilteredChannel( static_cast<std::size_t>( component ) );
}
}
void VideoHandle::setTool( int tool )
{
m_uiViewTool = tool;
+15 -7
View File
@@ -33,6 +33,7 @@
#include <QWidget>
#include "CommonDefs.h"
#include "VideoSubWindow.h"
#include "config.h"
class QToolBar;
@@ -43,7 +44,7 @@ class QSlider;
class SubWindowHandle;
class SubWindowAbstract;
class VideoSubWindow;
class VideoStreamSubWindow;
class FramePropertiesDock;
class FrameNumberWidget;
class QTimer;
@@ -58,7 +59,7 @@ public:
void createActions();
QMenu* createVideoMenu();
QMenu* createImageMenu();
QToolBar* createToolBar();
QPointer<QToolBar> createToolBar();
QDockWidget* createDock();
QWidget* createStatusBarMessage();
void updateMenus();
@@ -71,7 +72,7 @@ public:
void addSubWindow( VideoSubWindow* subWindow );
private:
QWidget* m_pcParet;
QWidget* m_pcParent;
SubWindowHandle* m_pcMainWindowManager;
enum
{
@@ -96,6 +97,11 @@ private:
QSlider* m_pcFrameSlider;
FrameNumberWidget* m_pcFrameNumInfo;
// Filter component actions
QMenu* m_menuComponent;
QActionGroup* m_actionGroupComponent;
QSignalMapper* m_mapperComponent;
// Tools Actions
QActionGroup* m_actionGroupTools;
QSignalMapper* m_mapperTools;
@@ -107,7 +113,7 @@ private:
QMenu* m_pcMenuVideo;
QMenu* m_pcMenuImage;
QToolBar* m_toolbarVideo;
// QToolBar* m_toolbarVideo;
QDockWidget* m_pcFramePropertiesDock;
FramePropertiesDock* m_pcFramePropertiesSideBar;
@@ -116,11 +122,11 @@ private:
QLabel* m_pcVideoFormatLabel;
QLabel* m_pcResolutionLabel;
VideoSubWindow* m_pcCurrentVideoSubWindow;
QVector<VideoSubWindow*> m_acPlayingSubWindows;
QPointer<VideoSubWindow> m_pcCurrentVideoSubWindow{ nullptr };
QVector<VideoStreamSubWindow*> m_acPlayingSubWindows;
QTimer* m_pcPlayingTimer;
bool m_bIsPlaying;
bool m_bIsPlaying{ false };
unsigned int m_uiNumberPlayedFrames{ 0 };
unsigned int m_uiRealAverageFrameRate{ 0 };
@@ -130,6 +136,7 @@ private:
void calculateRealFrameRate();
unsigned long getMaxFrameNumber();
void setTimerStatus();
void updateComponentMenu();
Q_SIGNALS:
void changed();
@@ -149,6 +156,7 @@ private Q_SLOTS:
void seekEvent( int direction );
void seekVideo();
void videoSelectionButtonEvent();
void setComponent( int component );
void setTool( int tool );
void toggleGrid( bool checked );
void setGridSize( int size );
+423
View File
@@ -0,0 +1,423 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file VideoStreamSubWindow.cpp
* \brief Video Sub windows handling
*/
#include "VideoStreamSubWindow.h"
#include <QScrollArea>
#include <QSettings>
#include <QStaticText>
#include <cassert>
#include "ConfigureFormatDialog.h"
#include "ModulesHandle.h"
#include "QtConcurrent/qtconcurrentrun.h"
#include "ResourceHandle.h"
#include "SubWindowAbstract.h"
#define QT_NO_CONCURRENT
VideoStreamSubWindow::VideoStreamSubWindow( ResourceHandle* resourceManager, QWidget* parent )
: VideoSubWindow( VideoSubWindow::VIDEO_STREAM_SUBWINDOW, parent )
, m_pcResourceManager{ resourceManager }
, m_pCurrStream{ NULL }
, m_bIsPlaying{ false }
{
}
VideoStreamSubWindow::~VideoStreamSubWindow()
{
if( m_pcResourceManager ) m_pcResourceManager->removeResource( m_uiResourceId );
}
void VideoStreamSubWindow::resetWindowName()
{
setWindowName( QFileInfo( m_cFilename ).fileName() );
}
void VideoStreamSubWindow::updateVideoWindowInfo()
{
m_cStreamInformation = "";
if( m_pcDisplayModule )
{
m_cStreamInformation = "Module";
const auto& arraySubWindows = m_pcDisplayModule->getSubWindowList();
QStringList windowInfoList;
if( arraySubWindows.size() > 0 )
{
for( std::size_t i = 0; i < arraySubWindows.size(); i++ )
{
if( arraySubWindows[i]->getWindowName() != getWindowName() )
{
windowInfoList.append( QString( "Input %1 - " + arraySubWindows[i]->getWindowName() ).arg( i + 1 ) );
}
}
}
if( m_pcDisplayModule->hasFeature( ClpModuleFeature::HasInfo ) )
{
QStringList list = QString::fromStdString( m_pcDisplayModule->moduleInfo() ).split( '\n' );
windowInfoList.append( list );
}
if( windowInfoList.size() > 0 )
{
m_pcVideoInfo->setInformationTopLeft( windowInfoList );
}
}
else if( m_pCurrStream )
{
QString m_cFormatName = QString::fromStdString( m_pCurrStream->getFormatName() );
QString m_cCodedName = QString::fromStdString( m_pCurrStream->getCodecName() );
m_cStreamInformation = m_cFormatName + " | " + m_cCodedName;
}
if( m_pcCurrFrameAsset )
{
QString m_cPelFmtName = QString::fromStdString( m_pcCurrFrameAsset->getPelFmtName() );
if( m_pCurrStream )
if( !m_pCurrStream->isNative() ) m_cPelFmtName += "*";
m_cStreamInformation += " | " + m_cPelFmtName;
}
if( m_cStreamInformation.isEmpty() )
{
m_cStreamInformation = " ";
}
}
void VideoStreamSubWindow::loadAll()
{
QApplication::setOverrideCursor( Qt::WaitCursor );
m_pCurrStream->loadAll();
refreshFrame();
QApplication::restoreOverrideCursor();
}
void VideoStreamSubWindow::setResource( std::size_t id )
{
m_uiResourceId = id;
m_pCurrStream = m_pcResourceManager->getResourceAsset( m_uiResourceId );
#ifdef CALYP_MANAGED_RESOURCES
m_pcResourceManager->startResourceWorker( m_uiResourceId );
#endif
QApplication::restoreOverrideCursor();
refreshFrame();
m_cFilename = QString::fromStdString( m_pCurrStream->getFileName() );
updateVideoWindowInfo();
setWindowName( QFileInfo( m_cFilename ).fileName() );
}
// bool VideoStreamSubWindow::loadFile( QString cFilename, bool bForceDialog )
// {
// assert( m_pcResourceManager != nullptr );
// ConfigureFormatDialog formatDialog( this );
// unsigned int Width = 0, Height = 0, BitsPel = 8, FrameRate = 30;
// int Endianness = CLP_LITTLE_ENDIAN;
// auto InputFormat = ClpPixelFormats::YUV420p;
// QSettings appSettings;
// if( m_pCurrStream )
// m_pCurrStream->getFormat( Width, Height, InputFormat, BitsPel, Endianness, FrameRate );
// else
// m_uiResourceId = m_pcResourceManager->getResource( nullptr );
// m_pCurrStream = m_pcResourceManager->getResourceAsset( m_uiResourceId );
// bool bConfig = true;
// if( !bForceDialog )
// {
// bConfig = guessFormat( cFilename, Width, Height, InputFormat, BitsPel, Endianness, FrameRate );
// if( bConfig )
// {
// // Pre-load values with last opened file
// Width = appSettings.value( "VideoStreamSubWindow/LastWidth" ).value<unsigned int>();
// Height = appSettings.value( "VideoStreamSubWindow/LastHeight" ).value<unsigned int>();
// BitsPel = appSettings.value( "VideoStreamSubWindow/LastBitsPerPixel" ).value<unsigned int>();
// }
// }
// bool bRet{ false };
// bool forceRaw{ false };
// for( int iPass = 0; iPass < 2 && !bRet; iPass++ )
// {
// if( iPass || bConfig )
// {
// if( formatDialog.runConfigureFormatDialog( QFileInfo( cFilename ).fileName(), Width, Height, InputFormat,
// BitsPel,
// Endianness, FrameRate ) == QDialog::Rejected )
// {
// return false;
// }
// }
// try
// {
// bRet = m_pCurrStream->open( cFilename.toStdString(), Width, Height, InputFormat, BitsPel, Endianness,
// FrameRate,
// iPass == 1, CalypStream::Type::Input );
// forceRaw = iPass > 0;
// }
// catch( CalypFailure& e )
// {
// if( iPass > 0 )
// throw( e );
// }
// }
// if( !bRet )
// {
// return false;
// }
// m_sStreamInfo.m_cFilename = cFilename;
// m_sStreamInfo.m_uiWidth = Width;
// m_sStreamInfo.m_uiHeight = Height;
// m_sStreamInfo.m_iPelFormat = InputFormat;
// m_sStreamInfo.m_uiBitsPelPixel = BitsPel;
// m_sStreamInfo.m_iEndianness = Endianness;
// m_sStreamInfo.m_uiFrameRate = FrameRate;
// m_sStreamInfo.m_uiFileSize = QFileInfo( cFilename ).size();
// m_sStreamInfo.m_bForceRaw = forceRaw;
// QVariant var;
// var.setValue<unsigned int>( Width );
// appSettings.setValue( "VideoStreamSubWindow/LastWidth", var );
// var.setValue<unsigned int>( Height );
// appSettings.setValue( "VideoStreamSubWindow/LastHeight", var );
// var.setValue<unsigned int>( BitsPel );
// appSettings.setValue( "VideoStreamSubWindow/LastBitsPerPixel", var );
// #ifdef CALYP_MANAGED_RESOURCES
// m_pcResourceManager->startResourceWorker( m_uiResourceId );
// #endif
// QApplication::restoreOverrideCursor();
// refreshFrame();
// m_cFilename = cFilename;
// updateVideoWindowInfo();
// setWindowName( QFileInfo( m_cFilename ).fileName() );
// return true;
// }
// bool VideoStreamSubWindow::loadFile( CalypFileInfo streamInfo )
// {
// assert( m_pcResourceManager != nullptr );
// m_uiResourceId = m_pcResourceManager->getResource( m_pCurrStream );
// m_pCurrStream = m_pcResourceManager->getResourceAsset( m_uiResourceId );
// if( !m_pCurrStream->open( streamInfo.m_cFilename.toStdString(), streamInfo.m_uiWidth, streamInfo.m_uiHeight,
// static_cast<ClpPixelFormats>( streamInfo.m_iPelFormat ), streamInfo.m_uiBitsPelPixel,
// streamInfo.m_iEndianness, streamInfo.m_uiFrameRate, streamInfo.m_bForceRaw,
// CalypStream::Type::Input ) )
// {
// return false;
// }
// m_cFilename = streamInfo.m_cFilename;
// m_sStreamInfo = std::move( streamInfo );
// #ifdef CALYP_MANAGED_RESOURCES
// m_pcResourceManager->startResourceWorker( m_uiResourceId );
// #endif
// QApplication::restoreOverrideCursor();
// refreshFrame();
// updateVideoWindowInfo();
// setWindowName( QFileInfo( m_cFilename ).fileName() );
// return true;
// }
void VideoStreamSubWindow::refreshSubWindow()
{
#ifdef CALYP_MANAGED_RESOURCES
m_pcResourceManager->stopResourceWorker( m_uiResourceId );
#endif
if( !m_pCurrStream->reload() )
{
close();
return;
}
#ifdef CALYP_MANAGED_RESOURCES
m_pcResourceManager->startResourceWorker( m_uiResourceId );
#endif
updateVideoWindowInfo();
refreshFrame();
}
void VideoStreamSubWindow::refreshFrame()
{
bool bSetFrame = true;
m_pcCurrFrameAsset = m_pCurrStream->getCurrFrameAsset();
if( m_pcDisplayModule )
{
// bool disableThreads = !m_bIsPlaying && hasAssociatedModule();
m_pcDisplayModule->apply( m_bIsPlaying, true );
bSetFrame = false;
}
if( bSetFrame ) VideoSubWindow::refreshFrame();
}
void VideoStreamSubWindow::refreshFrame( bool bThreaded )
{
#ifndef QT_NO_CONCURRENT
m_cRefreshResult.waitForFinished();
if( bThreaded )
{
m_cRefreshResult = QtConcurrent::run( this, &VideoSubWindow::refreshFrame );
}
else
#endif
{
refreshFrame();
}
}
bool VideoStreamSubWindow::goToNextFrame( bool bThreaded )
{
#ifndef QT_NO_CONCURRENT
m_cRefreshResult.waitForFinished();
m_cReadResult.waitForFinished();
#endif
#ifdef CALYP_MANAGED_RESOURCES
while( !m_pCurrStream->hasNextFrame() && !m_pCurrStream->isEof() )
{
}
#endif
bool bEndOfSeq = m_pCurrStream->setNextFrame();
#ifdef CALYP_MANAGED_RESOURCES
bThreaded = false;
m_pcResourceManager->wakeResourceWorker( m_uiResourceId );
#endif
if( !bEndOfSeq )
{
#ifndef QT_NO_CONCURRENT
m_cRefreshResult.waitForFinished();
if( bThreaded )
{
m_cReadResult = QtConcurrent::run( m_pCurrStream, &CalypStream::readNextFrameFillRGBBuffer );
refreshFrame( bThreaded );
}
else
#endif
{
refreshFrame( bThreaded );
#ifndef CALYP_MANAGED_RESOURCES
m_pCurrStream->readNextFrameFillRGBBuffer();
#endif
}
}
return bEndOfSeq;
}
bool VideoStreamSubWindow::saveStream( const QString& filename )
{
bool iRet = false;
QApplication::setOverrideCursor( Qt::WaitCursor );
// TODO: implement this
QApplication::restoreOverrideCursor();
return iRet;
}
bool VideoStreamSubWindow::isPlaying()
{
return m_bIsPlaying;
}
bool VideoStreamSubWindow::play()
{
bool isPlaying = false;
if( m_pCurrStream && m_pCurrStream->getFrameNum() > 1 )
{
isPlaying = true;
}
m_bIsPlaying = isPlaying;
return m_bIsPlaying;
}
bool VideoStreamSubWindow::playEvent()
{
bool bEndOfSeq = false;
if( m_pCurrStream && m_bIsPlaying )
{
bEndOfSeq = goToNextFrame( true );
}
return bEndOfSeq;
}
void VideoStreamSubWindow::pause()
{
m_bIsPlaying = false;
refreshFrame();
}
void VideoStreamSubWindow::seekAbsoluteEvent( unsigned int new_frame_num )
{
if( m_pCurrStream )
{
if( m_pCurrStream->seekInput( new_frame_num ) ) refreshFrame();
#ifdef CALYP_MANAGED_RESOURCES
m_pcResourceManager->wakeResourceWorker( m_uiResourceId );
#endif
}
}
void VideoStreamSubWindow::seekRelativeEvent( bool bIsForward )
{
if( m_pCurrStream )
{
if( bIsForward )
{
goToNextFrame( true );
}
else
{
m_pCurrStream->seekInputRelative( bIsForward );
#ifdef CALYP_MANAGED_RESOURCES
m_pcResourceManager->wakeResourceWorker( m_uiResourceId );
#endif
refreshFrame();
}
}
}
void VideoStreamSubWindow::stop()
{
#ifndef QT_NO_CONCURRENT
m_cRefreshResult.waitForFinished();
m_cReadResult.waitForFinished();
#endif
m_bIsPlaying = false;
seekAbsoluteEvent( 0 );
return;
}
+112
View File
@@ -0,0 +1,112 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file VideoStreamSubWindow.h
* \brief Video Sub windows handling
*/
#ifndef __VIDEOSTREAMSUBWINDOW_H__
#define __VIDEOSTREAMSUBWINDOW_H__
#include <QDataStream>
#include <QFuture>
#include <QRect>
#include <QString>
#include <QVector>
#include <cstdint>
#include "CommonDefs.h"
#include "VideoSubWindow.h"
#include "config.h"
#include "lib/CalypStream.h"
#include "models/VideostreamResource.h"
class QScrollArea;
class VideoInformation;
class VideoStreamSubWindow;
class ResourceHandle;
class CalypAppModuleIf;
class VideoStreamSubWindow : public VideoSubWindow
{
Q_OBJECT
public:
VideoStreamSubWindow( ResourceHandle* resourceManager, QWidget* parent = 0 );
~VideoStreamSubWindow();
void resetWindowName() override;
void updateVideoWindowInfo() override;
bool isPlaying() override;
void stop() override;
void advanceOneFrame() override { goToNextFrame( true ); }
auto getFrameNum() -> std::uint64_t override { return m_pCurrStream->getFrameNum(); }
bool supportsFormatConfiguration() const { return m_pCurrStream->supportsFormatConfiguration(); };
void setResource( std::size_t id );
auto getResourceId() const -> std::size_t { return m_uiResourceId; };
// bool loadFile( QString cFilename, bool bForceDialog = false );
// bool loadFile( CalypFileInfo streamInfo );
void loadAll();
bool saveStream( const QString& filename );
bool play();
void pause();
bool playEvent();
void seekAbsoluteEvent( unsigned int new_frame_num );
void seekRelativeEvent( bool bIsFoward );
CalypFileInfo getStreamInfo() { return m_sStreamInfo; }
const CalypStream* getInputStream() { return m_pCurrStream; }
const CalypStream* getCurrStream() { return m_pCurrStream; }
QString getCurrentFileName() { return m_cFilename; }
void refreshSubWindow() override;
void refreshFrame();
void refreshFrame( bool bThreaded );
private:
bool goToNextFrame( bool bThreaded );
private: // NO_LINT
ResourceHandle* m_pcResourceManager;
std::size_t m_uiResourceId;
QString m_cFilename;
CalypFileInfo m_sStreamInfo;
CalypStream* m_pCurrStream;
QString m_cCurrFileName;
bool m_bIsPlaying;
/**
* Threads variables
* QtConcurrent
*/
QFuture<void> m_cRefreshResult;
QFuture<void> m_cReadResult;
};
#endif // __VIDEOSTREAMSUBWINDOW_H__
+111 -760
View File
File diff suppressed because it is too large. Load diff
+65 -118
View File
@@ -28,6 +28,7 @@
#include <QDataStream>
#include <QFuture>
#include <QRect>
#include <QStaticText>
#include <QString>
#include <QVector>
@@ -45,69 +46,32 @@ class VideoSubWindow;
class ResourceHandle;
class CalypAppModuleIf;
typedef struct
/**
* \class VideoInformation
* \brief Shows information about video sub window
*/
class VideoInformation : public QWidget
{
QString m_cFilename;
unsigned int m_uiWidth;
unsigned int m_uiHeight;
int m_iPelFormat;
unsigned int m_uiBitsPelPixel;
unsigned int m_iEndianness;
unsigned int m_uiFrameRate;
unsigned long long int m_uiFileSize;
} CalypFileInfo;
typedef QVector<CalypFileInfo> CalypFileInfoVector;
public:
VideoInformation( QWidget* parent );
void setInformationTopLeft( const QStringList& textLines );
void setBusyWindow( bool bFlag );
QDataStream& operator<<( QDataStream& out, const CalypFileInfoVector& d );
QDataStream& operator>>( QDataStream& in, CalypFileInfoVector& d );
int findCalypStreamInfo( CalypFileInfoVector array, QString filename );
protected:
void paintEvent( QPaintEvent* event ) override;
private:
QTimer* m_pcRefreshTimer;
QList<QStaticText> m_cTopLeftTextList;
QFont m_cTopLeftTextFont;
QFont m_cCenterTextFont;
bool m_bBusyWindow;
};
class VideoSubWindow : public SubWindowAbstract
{
Q_OBJECT
private:
ResourceHandle* m_pcResourceManager;
bool m_bWindowBusy;
QScrollArea* m_pcScrollArea;
QPoint m_cCurrScroll;
double m_dHorScroll;
double m_dVerScroll;
ViewArea* m_cViewArea;
VideoInformation* m_pcVideoInfo;
QString m_cFilename;
QString m_cStreamInformation;
CalypFileInfo m_sStreamInfo;
std::size_t m_uiResourceId;
CalypStream* m_pCurrStream;
std::shared_ptr<CalypFrame> m_pcCurrFrameAsset;
//CalypFrame* m_pcCurrFrame;
QRect m_cSelectedArea;
CalypAppModuleIf* m_pcCurrentDisplayModule{ nullptr };
std::vector<std::shared_ptr<CalypAppModuleIf>> m_associatedModules;
bool m_hasAssociatedModules;
VideoSubWindow* m_pcReferenceSubWindow;
// QString m_cWindowShortName;
QString m_cCurrFileName;
bool m_bIsPlaying;
QTimer* m_pcUpdateTimer;
/**
* Threads variables
* QtConcurrent
*/
QFuture<void> m_cRefreshResult;
QFuture<void> m_cReadResult;
public:
enum VideoSubWindowCategories
{
@@ -115,41 +79,26 @@ public:
MODULE_SUBWINDOW = SubWindowAbstract::MODULE_SUBWINDOW,
};
VideoSubWindow( enum VideoSubWindowCategories category, QWidget* parent = 0 );
VideoSubWindow( enum VideoSubWindowCategories category, CalypAppModuleIf* displayModule, QWidget* parent = 0 );
~VideoSubWindow();
void setResourceManaget( ResourceHandle* resourceManager ) { m_pcResourceManager = resourceManager; }
virtual void resetWindowName() = 0;
virtual void updateVideoWindowInfo() = 0;
void updateVideoWindowInfo();
virtual bool isPlaying() = 0;
virtual void stop() = 0;
virtual void advanceOneFrame() = 0;
virtual auto getFrameNum() -> std::uint64_t { return 1; };
bool loadFile( QString cFilename, bool bForceDialog = false );
bool loadFile( CalypFileInfo* streamInfo );
void loadAll();
bool save( QString filename );
bool saveStream( QString filename );
void refreshSubWindow();
void refreshFrame( bool bThreaded = false );
bool play();
void pause();
bool playEvent();
void stop();
void setPlaying( bool isPlaying );
bool isPlaying();
void seekAbsoluteEvent( unsigned int new_frame_num );
void seekRelativeEvent( bool bIsFoward );
QString getVideoInformation() { return m_cStreamInformation; }
bool save( const QString& filename );
void setCurrFrame( std::shared_ptr<CalypFrame> pcCurrFrame );
CalypFileInfo getStreamInfo() { return m_sStreamInfo; }
QString getStreamInformation() { return m_cStreamInformation; }
const CalypStream* getInputStream() { return m_pCurrStream; }
const CalypStream* getCurrStream() { return m_pCurrStream; }
CalypFrame* getCurrFrame() { return m_pcCurrFrameAsset.get(); }
std::shared_ptr<CalypFrame> getCurrFrameAsset();
ViewArea* getViewArea() { return m_cViewArea; }
auto getCurrFrame() -> CalypFrame* { return m_pcCurrFrameAsset.get(); }
auto getCurrFrameAsset() -> std::shared_ptr<CalypFrame> { return m_pcCurrFrameAsset; };
auto getViewArea() -> ViewArea* { return m_cViewArea; }
VideoSubWindow* getRefSubWindow() { return m_pcReferenceSubWindow; }
void setRefSubWindow( VideoSubWindow* subWindow )
{
m_pcReferenceSubWindow = NULL;
@@ -158,59 +107,37 @@ public:
m_pcReferenceSubWindow = subWindow;
}
VideoSubWindow* getRefSubWindow() { return m_pcReferenceSubWindow; }
/**
* Functions to enable a module in the
* current SubWindow
*/
//void enableModule( std::shared_ptr<CalypAppModuleIf> pcModule );
auto hasModules() -> bool { return m_associatedModules.size() > 0; }
bool hasAssociatedModule();
void setDisplayModule( CalypAppModuleIf* pcModule );
void associateModule( std::shared_ptr<CalypAppModuleIf> pcModule );
void disableModule( CalypAppModuleIf* pcModule );
bool disableAllModules();
CalypAppModuleIf* getDisplayModule() { return m_pcCurrentDisplayModule; }
QVector<CalypAppModuleIf*> getModuleArray()
{
QVector<CalypAppModuleIf*> apcModulesArray;
if( m_pcCurrentDisplayModule )
apcModulesArray.append( m_pcCurrentDisplayModule );
for( const auto& module : m_associatedModules )
{
apcModulesArray.append( module.get() );
}
return apcModulesArray;
}
CalypAppModuleIf* getDisplayModule() { return m_pcDisplayModule; }
/**
* Virtual functions from SubWindowAbstract
*/
void normalSize();
void zoomToFit();
void scaleView( double scale, QPoint center = QPoint() );
void zoomToFactor( double factor, QPoint center = QPoint() );
void normalSize() override;
void zoomToFit() override;
void scaleView( double scale, QPoint center = QPoint() ) override;
void zoomToFactor( double factor, QPoint center = QPoint() ) override;
double getScaleFactor() { return m_cViewArea->getZoomFactor(); }
double getScaleFactor() override { return m_cViewArea->getZoomFactor(); }
/**
* Size related functions
*/
QSize sizeHint() const;
QSize sizeHint( const QSize& ) const;
QSize sizeHint( const QSize& ) const override;
QString getCurrentFileName() { return m_cFilename; }
void clearWindowBusy() { m_bWindowBusy = false; }
void setFillWindow( bool bFlag );
void adjustScrollBarToRatio( const double& horRatio, const double& verRatio );
void adjustScrollBarToRatio( const double horRatio, const double verRatio );
private:
void refreshFrameOperation();
bool goToNextFrame( bool bThreaded = false );
static bool guessFormat( QString filename, unsigned int& rWidth, unsigned int& rHeight, int& rInputFormat, unsigned int& rBitsPerPixel,
int& rEndianness, unsigned int& rFrameRate );
bool hasRunningModule();
/**
@@ -222,6 +149,8 @@ private:
QSize getScrollSize();
protected:
void refreshFrame();
void keyPressEvent( QKeyEvent* event ) override;
void resizeEvent( QResizeEvent* event ) override;
void closeEvent( QCloseEvent* event ) override;
@@ -233,9 +162,27 @@ public Q_SLOTS:
void updateScrollValues();
void updateSelectedArea( QRect area );
void updatePixelValueStatusBar( const QPoint& pos );
protected:
VideoInformation* m_pcVideoInfo;
QString m_cStreamInformation;
std::shared_ptr<CalypFrame> m_pcCurrFrameAsset;
// bool m_bWindowBusy;
// bool m_bIsPlaying;
std::vector<std::shared_ptr<CalypAppModuleIf>> m_associatedModules;
CalypAppModuleIf* m_pcDisplayModule{ nullptr };
// bool m_hasAssociatedModules;
private:
QScrollArea* m_pcScrollArea;
QPoint m_cCurrScroll;
double m_dHorScroll{ 0 };
double m_dVerScroll{ 0 };
ViewArea* m_cViewArea;
QRect m_cSelectedArea;
VideoSubWindow* m_pcReferenceSubWindow;
QTimer* m_pcUpdateTimer;
};
Q_DECLARE_METATYPE( CalypFileInfo ) // NOLINT
Q_DECLARE_METATYPE( CalypFileInfoVector ) // NOLINT
#endif // __VIDEOSUBWINDOW_H__
+98 -54
View File
@@ -25,6 +25,7 @@
#include "ViewArea.h"
#include <qcolor.h>
#include <qnamespace.h>
#include <QColor>
@@ -42,9 +43,17 @@
#include "GridManager.h"
static const QColor selectionColor = Qt::cyan;
static const QColor imageMaskColor = Qt::green;
static const QColor eraserColor = Qt::red;
#if QT_VERSION >= QT_VERSION_CHECK( 5, 14, 0 )
constexpr auto kSelectionColor = QColorConstants::Cyan;
constexpr auto kImageMaskColor = QColorConstants::Green;
constexpr auto kEraserColor = QColorConstants::Red;
#else
static const QColor kSelectionColor = Qt::cyan;
static const QColor kImageMaskColor = Qt::green;
static const QColor kEraserColor = Qt::red;
#endif
constexpr double kMaxZoom = 100.0;
constexpr double kMinZoom = 0.01;
ViewArea::ViewArea( QWidget* parent )
: QWidget( parent )
@@ -53,15 +62,6 @@ ViewArea::ViewArea( QWidget* parent )
m_grid = GridManager();
m_mask = QBitmap();
m_selectedArea = QRect();
m_dZoomFactor = 1;
m_xOffset = 0;
m_yOffset = 0;
m_mode = NormalMode;
m_eTool = NavigationTool;
m_bGridVisible = false;
m_snapToGrid = false;
m_blockTrackEnable = false;
m_visibleZoomRect = true;
m_zoomWinTimer.setSingleShot( true );
m_zoomWinTimer.setInterval( 2000 );
@@ -72,8 +72,17 @@ void ViewArea::setImage( std::shared_ptr<CalypFrame> frame )
{
m_nextFrame = frame;
m_uiPixelHalfScale = 1 << ( m_nextFrame->getBitsPel() - 1 );
m_nextFrame->fillRGBBuffer();
m_image = QImage( m_nextFrame->getRGBBuffer(),
if( m_filterSingleChannel.has_value() )
{
m_nextFrame->fillRGBBuffer( m_filterSingleChannel );
}
else
{
m_nextFrame->fillRGBBuffer();
}
auto rgb_buffer = *m_nextFrame->getRGBBuffer();
m_image = QImage( rgb_buffer.data(),
m_nextFrame->getWidth(),
m_nextFrame->getHeight(),
QImage::Format_ARGB32 );
@@ -86,14 +95,49 @@ void ViewArea::setImage( std::shared_ptr<CalypFrame> frame )
initZoomWinRect();
}
void ViewArea::clear()
// void ViewArea::clear()
// {
// m_image = QImage();
// m_mask = QBitmap();
// m_mode = NormalMode;
// updateSize();
// update();
// updateGeometry();
// }
auto ViewArea::getFilteredChannel() -> std::optional<std::size_t>
{
m_image = QImage();
m_mask = QBitmap();
m_mode = NormalMode;
updateSize();
return m_filterSingleChannel;
}
void ViewArea::setFilteredChannel( std::size_t channel )
{
m_filterSingleChannel = channel;
if( m_nextFrame != nullptr )
{
m_nextFrame->fillRGBBuffer( m_filterSingleChannel );
auto rgb_buffer = *m_nextFrame->getRGBBuffer();
m_image = QImage( rgb_buffer.data(),
m_nextFrame->getWidth(),
m_nextFrame->getHeight(),
QImage::Format_ARGB32 );
}
update();
}
void ViewArea::clearFilteredChannel()
{
m_filterSingleChannel = {};
if( m_nextFrame != nullptr )
{
m_nextFrame->fillRGBBuffer( m_filterSingleChannel );
auto rgb_buffer = *m_nextFrame->getRGBBuffer();
m_image = QImage( rgb_buffer.data(),
m_nextFrame->getWidth(),
m_nextFrame->getHeight(),
QImage::Format_ARGB32 );
}
update();
updateGeometry();
}
void ViewArea::setTool( unsigned int view )
@@ -161,14 +205,14 @@ void ViewArea::setZoomFactor( double f )
double ViewArea::scaleZoomFactor( double scale, QPoint center, QSize minimumSize )
{
double maxZoom = 100.0;
double minZoom = 0.01; //( 1.0 / m_image.width() );
Q_ASSERT( !m_image.isNull() );
double new_scale = 1.0;
if( ( m_dZoomFactor == minZoom ) && ( scale < 1 ) )
if( ( m_dZoomFactor == kMinZoom ) && ( scale < 1 ) )
return new_scale;
if( ( m_dZoomFactor == maxZoom ) && ( scale > 1 ) )
if( ( m_dZoomFactor == kMaxZoom ) && ( scale > 1 ) )
return new_scale;
double newZoomFactor = m_dZoomFactor * scale * 100.0;
@@ -209,16 +253,16 @@ double ViewArea::scaleZoomFactor( double scale, QPoint center, QSize minimumSize
new_scale = scale;
if( newZoomFactor < minZoom )
if( newZoomFactor < kMinZoom )
{
newZoomFactor = minZoom;
newZoomFactor = kMinZoom;
new_scale = newZoomFactor / m_dZoomFactor;
}
else
{
if( newZoomFactor > maxZoom )
if( newZoomFactor > kMaxZoom )
{
newZoomFactor = maxZoom;
newZoomFactor = kMaxZoom;
new_scale = newZoomFactor / m_dZoomFactor;
}
}
@@ -474,12 +518,12 @@ void ViewArea::paintEvent( QPaintEvent* event )
// Draw a border around the image.
/* if( m_xOffset || m_yOffset )
{
painter.setPen( Qt::black );
painter.drawRect( m_xOffset - 1, m_yOffset - 1, m_image.width() *
m_dZoomFactor + 1, m_image.height() *
m_dZoomFactor + 1 );
}*/
{
painter.setPen( Qt::black );
painter.drawRect( m_xOffset - 1, m_yOffset - 1, m_image.width() *
m_dZoomFactor + 1, m_image.height() *
m_dZoomFactor + 1 );
}*/
int frFormat = m_currFrame->getColorSpace();
@@ -567,16 +611,16 @@ void ViewArea::paintEvent( QPaintEvent* event )
QRect vr = windowToView( winRect );
QRect cVisibleImg = vr & cImg;
//cVisibleImg.moveTopLeft(vr.topLeft());
// cVisibleImg.moveTopLeft(vr.topLeft());
QRect cVisibleWinRect;
cVisibleWinRect.setLeft( floor( (double)cVisibleImg.x() / dRatio ) );
cVisibleWinRect.setTop( floor( (double)cVisibleImg.y() / dRatio ) );
cVisibleWinRect.setRight( round( (double)cVisibleImg.right() / dRatio ) );
cVisibleWinRect.setBottom( round( (double)cVisibleImg.bottom() / dRatio ) );
//painter.fillRect( cImgWinRect, QBrush( QColor( 128, 128, 128, 128 ) ) );
// painter.fillRect( cImgWinRect, QBrush( QColor( 128, 128, 128, 128 ) ) );
painter.setPen( QColor( 50, 50, 50, 128 ) );
//painter.drawRect( cImgWinRect );
// painter.drawRect( cImgWinRect );
painter.setOpacity( 0.7 );
painter.drawImage( cImgWinRect, m_image );
painter.setOpacity( 1 );
@@ -599,7 +643,7 @@ void ViewArea::paintEvent( QPaintEvent* event )
painter.setPen( QColor( 255, 255, 255, 128 ) );
painter.drawRect( cVisibleWinRect );
//qDebug() << "Debug VisibleZoomRect: " << winRect << vr << cImgWinRect << cVisibleWinRect << cVisibleImg << dRatio;
// qDebug() << "Debug VisibleZoomRect: " << winRect << vr << cImgWinRect << cVisibleWinRect << cVisibleImg << dRatio;
}
QRect sr = viewToWindow( m_selectedArea );
@@ -610,7 +654,7 @@ void ViewArea::paintEvent( QPaintEvent* event )
if( m_newShape || m_blockTrackEnable )
{
// Set the tool color
QColor selectColor = selectionColor;
QColor selectColor = kSelectionColor;
selectColor.setAlpha( 120 );
@@ -664,7 +708,7 @@ void ViewArea::paintEvent( QPaintEvent* event )
if( m_maskColor.isValid() )
color = m_maskColor;
else
color = imageMaskColor;
color = kImageMaskColor;
color.setAlpha( 120 );
painter.setPen( color );
@@ -684,16 +728,16 @@ void ViewArea::paintEvent( QPaintEvent* event )
if( m_maskColor.isValid() )
color = m_maskColor;
else
color = imageMaskColor;
color = kImageMaskColor;
break;
}
case EraserTool: {
color = eraserColor;
color = kEraserColor;
break;
}
default:
color = selectionColor; // ?Problems!
color = kSelectionColor; // ?Problems!
}
color.setAlpha( 120 );
@@ -898,18 +942,18 @@ void ViewArea::mouseMoveEvent( QMouseEvent* event )
}
}
/* else // if tool() == BlockSelectionTool || MaskTool || EraserTool
{
m_blockTrackEnable = false;
// If cursor is inside the selected area, we most redraw
// the selection rect because it may be smaller.
if( m_selectedArea.contains( actualPos ) )
{
m_selectedArea = m_grid.rectContains( m_lastPos );
}
{
m_blockTrackEnable = false;
// If cursor is inside the selected area, we most redraw
// the selection rect because it may be smaller.
if( m_selectedArea.contains( actualPos ) )
{
m_selectedArea = m_grid.rectContains( m_lastPos );
}
m_selectedArea = m_selectedArea.united( m_grid.rectContains( actualPos ) );
}
*/
m_selectedArea = m_selectedArea.united( m_grid.rectContains( actualPos ) );
}
*/
if( tool() == SelectionTool )
{
// intercept the selected area with the image area to limit the
+22 -23
View File
@@ -56,17 +56,15 @@ public:
ViewArea( QWidget* parent = 0 );
QImage& image() { return m_image; };
void setImage( std::shared_ptr<CalypFrame> frame );
auto getFilteredChannel() -> std::optional<std::size_t>;
void setFilteredChannel( std::size_t channel );
void clearFilteredChannel();
void setMode( int mode );
void setMaskColor( const QColor& color = QColor() );
/**
* Clears any contents.
*/
void clear();
/**
* Select tool from the menu
*/
@@ -108,12 +106,12 @@ public Q_SLOTS:
// void setSelectedArea( QRect &rect );
protected:
void paintEvent( QPaintEvent* event );
void resizeEvent( QResizeEvent* event );
void mousePressEvent( QMouseEvent* event );
void mouseMoveEvent( QMouseEvent* event );
void mouseReleaseEvent( QMouseEvent* event );
void wheelEvent( QWheelEvent* event );
void paintEvent( QPaintEvent* event ) override;
void resizeEvent( QResizeEvent* event ) override;
void mousePressEvent( QMouseEvent* event ) override;
void mouseMoveEvent( QMouseEvent* event ) override;
void mouseReleaseEvent( QMouseEvent* event ) override;
void wheelEvent( QWheelEvent* event ) override;
void updateSize();
void updateOffset();
@@ -149,34 +147,35 @@ private:
QRect viewToWindow( const QRect& rc ) const;
std::shared_ptr<CalypFrame> m_currFrame;
QImage m_image;
std::shared_ptr<CalypFrame> m_nextFrame;
std::optional<std::size_t> m_filterSingleChannel;
ClpPel m_uiPixelHalfScale;
Tool m_eTool;
bool m_bGridVisible;
Tool m_eTool{ NavigationTool };
bool m_bGridVisible{ false };
QTimer m_zoomWinTimer;
double m_dZoomWinRatio;
double m_dZoomFactor;
double m_dZoomFactor{ 1.0 };
QImage m_image;
//QPixmap m_pixmap;
// QPixmap m_pixmap;
QBitmap m_mask;
QRect m_selectedArea;
QPoint m_lastPos;
QPoint m_lastWindowPos;
GridManager m_grid;
ViewMode m_mode;
ViewMode m_mode{ NormalMode };
QColor m_maskColor;
int m_xOffset;
int m_yOffset;
bool m_blockTrackEnable;
int m_xOffset{ 0 };
int m_yOffset{ 0 };
bool m_blockTrackEnable{ false };
bool m_newShape;
bool m_snapToGrid;
bool m_snapToGrid{ false };
bool m_cursorInGrid;
bool m_visibleZoomRect;
bool m_visibleZoomRect{ true };
};
#endif // __VIEWAREA_H__
+21
View File
@@ -0,0 +1,21 @@
#
# CMakeLists for Calyp lis tests using catch2
#
FETCHCONTENT_MAKEAVAILABLE(Catch2)
SET(Calyp_App_Catch2_Tests_SRCS CalypAppTests.cpp CalypResourcesTests.cpp)
ADD_DEFINITIONS(-DCALYP_TEST_DATA_DIR=\"${CALYP_TEST_DATA_DIR}\")
ADD_EXECUTABLE(CalypAppCatch2Tests ${Calyp_App_Catch2_Tests_SRCS})
TARGET_LINK_LIBRARIES(
CalypAppCatch2Tests
${PROJECT_LIBRARY}
CalypModules
${APP_LINKER_LIBS}
${QT_LINKER_LIBS}
QCustomPlotLib
Catch2::Catch2WithMain
)
CATCH_DISCOVER_TESTS(CalypAppCatch2Tests)
+26
View File
@@ -0,0 +1,26 @@
/* This file is a part of plaYUVer project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file CalypLibTests.cpp
* \brief CalypLib main test file
*/
#define CATCH_CONFIG_MAIN
#include <catch2/catch_test_macros.hpp>
+285
View File
@@ -0,0 +1,285 @@
/* This file is a part of plaYUVer project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file CalypResourcesTests.cpp
* \brief Resouce handling tests
*/
#include <QString>
#include <catch2/catch_all.hpp>
#include <filesystem>
#include <iostream>
#include <variant>
#include "ResourceHandle.h"
#include "lib/CalypFrame.h"
#include "lib/CalypStream.h"
#include "models/VideostreamResource.h"
using namespace std::chrono_literals;
constexpr int kFrameRate{ 30 };
constexpr auto kStreamType = CalypStream::Type::Input;
auto getFileTestFilename( const char* test_sequence ) -> std::string
{
return std::string( CALYP_TEST_DATA_DIR ) + std::string( "/" ) + std::string( test_sequence );
}
TEST_CASE( "Can construct and destruct a resource", "VideoResource" )
{
auto videoResource = std::make_unique<VideostreamResource>();
CHECK( videoResource != nullptr );
}
TEST_CASE( "Can load a YUV file", "VideoResource" )
{
constexpr unsigned int kWidth{ 352 };
constexpr unsigned int kHeight{ 288 };
constexpr auto kInputFormat{ ClpPixelFormats::YUV420p };
constexpr unsigned int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_LITTLE_ENDIAN };
const auto kFilename = getFileTestFilename( "Foreman.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
auto resourceHandle = std::make_unique<ResourceHandle>();
auto videoResource = std::make_unique<VideostreamResource>();
CalypFileInfo streamInfo{ .m_cFilename = QString::fromStdString( kFilename ) };
CHECK_FALSE( videoResource->loadFile( streamInfo, false ) );
SECTION( "Now use a valid config" )
{
streamInfo = CalypFileInfo{ .m_cFilename = QString::fromStdString( kFilename ),
.m_uiWidth = kWidth,
.m_uiHeight = kHeight,
.m_iPelFormat = kInputFormat,
.m_uiBitsPelPixel = kBitsPel,
.m_iEndianness = KEndianness,
.m_uiFrameRate = kFrameRate };
REQUIRE( videoResource->loadFile( streamInfo ) );
const auto& test_stream = videoResource->getStream();
CHECK( test_stream.getWidth() == kWidth );
CHECK( test_stream.getHeight() == kHeight );
CHECK( test_stream.getBitsPerPixel() == kBitsPel );
CHECK( test_stream.getFormatName() == "YUV" );
CHECK( test_stream.getCodecName() == "Raw Video" );
CHECK( test_stream.getEndianess() == CLP_BIG_ENDIAN );
auto frame = videoResource->getCurrFrame();
CHECK( frame->getPixel( 2, 0 ) == CalypPixel{ CLP_COLOR_YUV, 201, 129, 125 } );
CHECK( frame->getPixel( 336, 278 ) == CalypPixel{ CLP_COLOR_YUV, 99, 111, 142 } );
}
}
TEST_CASE( "Can load a MKV file", "VideoResource" )
{
constexpr unsigned int kWidth{ 352 };
constexpr unsigned int kHeight{ 288 };
constexpr unsigned int kBitsPel{ 8 };
const auto kFilename = getFileTestFilename( "Foreman.mkv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
auto resourceHandle = std::make_unique<ResourceHandle>();
auto videoResource = std::make_unique<VideostreamResource>( nullptr );
CalypFileInfo streamInfo{ .m_cFilename = QString::fromStdString( kFilename ) };
REQUIRE( videoResource->loadFile( streamInfo ) );
const auto& test_stream = videoResource->getStream();
CHECK( test_stream.getWidth() == kWidth );
CHECK( test_stream.getHeight() == kHeight );
CHECK( test_stream.getBitsPerPixel() == kBitsPel );
CHECK( test_stream.getFormatName() == "MKV" );
CHECK( test_stream.getCodecName() == "h264" );
CHECK( test_stream.getEndianess() == CLP_BIG_ENDIAN );
auto frame = videoResource->getCurrFrame();
CHECK( frame->getPixel( 311, 255 ) == CalypPixel{ CLP_COLOR_YUV, 83, 120, 132 } );
}
TEST_CASE( "Can load a PNG file", "VideoResource" )
{
constexpr unsigned int kWidth{ 352 };
constexpr unsigned int kHeight{ 288 };
constexpr unsigned int kBitsPel{ 8 };
const auto kFilename = getFileTestFilename( "Foreman.png" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
auto resourceHandle = std::make_unique<ResourceHandle>();
auto videoResource = std::make_unique<VideostreamResource>( nullptr );
CalypFileInfo streamInfo{ .m_cFilename = QString::fromStdString( kFilename ) };
REQUIRE( videoResource->loadFile( streamInfo ) );
const auto& test_stream = videoResource->getStream();
CHECK( test_stream.getWidth() == kWidth );
CHECK( test_stream.getHeight() == kHeight );
CHECK( test_stream.getBitsPerPixel() == kBitsPel );
CHECK( test_stream.getFormatName() == "PNG" );
CHECK( test_stream.getCodecName() == "png" );
CHECK( test_stream.getEndianess() == CLP_BIG_ENDIAN );
auto frame = videoResource->getCurrFrame();
CHECK( frame->getPixel( 292, 263 ) == CalypPixel{ CLP_COLOR_RGB, 92, 83, 54 } );
}
TEST_CASE( "Resource handle can store a video resource", "VideoResource" )
{
constexpr unsigned int kWidth{ 352 };
constexpr unsigned int kHeight{ 288 };
constexpr auto kInputFormat{ ClpPixelFormats::YUV420p };
constexpr unsigned int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_LITTLE_ENDIAN };
const auto kFilename = getFileTestFilename( "Foreman.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
auto resourceHandle = std::make_unique<ResourceHandle>();
CalypFileInfo streamInfo{ .m_cFilename = QString::fromStdString( kFilename ),
.m_uiWidth = kWidth,
.m_uiHeight = kHeight,
.m_iPelFormat = kInputFormat,
.m_uiBitsPelPixel = kBitsPel,
.m_iEndianness = KEndianness,
.m_uiFrameRate = kFrameRate };
{
auto videoResource = std::make_unique<VideostreamResource>( nullptr );
REQUIRE( videoResource != nullptr );
CHECK( videoResource->loadFile( streamInfo ) );
CHECK( resourceHandle->appendResource( std::move( videoResource ) ) == 0 );
}
auto videoResource = std::make_unique<VideostreamResource>( nullptr );
REQUIRE( videoResource != nullptr );
CHECK( videoResource->loadFile( streamInfo ) );
auto resource_id = resourceHandle->appendResource( std::move( videoResource ) );
CHECK( resource_id == 1 );
SECTION( "Can start and stop resource" )
{
resourceHandle->startResourceWorker( resource_id );
std::this_thread::sleep_for( 20ms );
resourceHandle->stopResourceWorker( resource_id );
CHECK( true );
}
SECTION( "Can start without stopping (RAII will clear resource)" )
{
resourceHandle->startResourceWorker( resource_id );
CHECK( true );
}
resourceHandle->removeResource( resource_id );
}
TEST_CASE( "Resource handle can play a video resource", "VideoResource" )
{
constexpr unsigned int kWidth{ 352 };
constexpr unsigned int kHeight{ 288 };
constexpr auto kInputFormat{ ClpPixelFormats::YUV420p };
constexpr unsigned int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_LITTLE_ENDIAN };
const auto kFilename = getFileTestFilename( "Foreman.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
auto resourceHandle = std::make_unique<ResourceHandle>();
CalypFileInfo streamInfo{ .m_cFilename = QString::fromStdString( kFilename ),
.m_uiWidth = kWidth,
.m_uiHeight = kHeight,
.m_iPelFormat = kInputFormat,
.m_uiBitsPelPixel = kBitsPel,
.m_iEndianness = KEndianness,
.m_uiFrameRate = kFrameRate };
auto videoResource = std::make_unique<VideostreamResource>( nullptr );
REQUIRE( videoResource != nullptr );
CHECK( videoResource->loadFile( streamInfo ) );
auto frame = videoResource->getCurrFrame();
CHECK( frame->getPixel( 2, 0 ) == CalypPixel{ CLP_COLOR_YUV, 201, 129, 125 } );
CHECK( frame->getPixel( 336, 278 ) == CalypPixel{ CLP_COLOR_YUV, 99, 111, 142 } );
auto resource_id = resourceHandle->appendResource( std::move( videoResource ) );
resourceHandle->executeResourceAction<VideostreamResource>( resource_id, []( auto* resource ) {
resource->play();
return true;
} );
resourceHandle->startResourceWorker( resource_id );
resourceHandle->executeResourceAction<VideostreamResource>( resource_id, [&frame]( auto* resource ) {
resource->playEvent();
frame = resource->getCurrFrame();
return true;
} );
CHECK( frame->getPixel( 298, 237 ) == CalypPixel{ CLP_COLOR_YUV, 82, 115, 134 } );
resourceHandle->executeResourceAction<VideostreamResource>( resource_id, [&frame]( auto* resource ) {
resource->playEvent();
frame = resource->getCurrFrame();
return true;
} );
CHECK_FALSE( frame->getPixel( 298, 237 ) == CalypPixel{ CLP_COLOR_YUV, 82, 115, 134 } );
SECTION( "Can Stop" )
{
resourceHandle->executeResourceAction<VideostreamResource>( resource_id, [&frame]( auto* resource ) {
resource->playEvent();
frame = resource->getCurrFrame();
return true;
} );
resourceHandle->executeResourceAction<VideostreamResource>( resource_id, [&frame]( auto* resource ) {
resource->stop();
frame = resource->getCurrFrame();
return true;
} );
CHECK( frame->getPixel( 2, 0 ) == CalypPixel{ CLP_COLOR_YUV, 201, 129, 125 } );
CHECK( frame->getPixel( 336, 278 ) == CalypPixel{ CLP_COLOR_YUV, 99, 111, 142 } );
}
resourceHandle->stopResourceWorker( resource_id );
}
+43 -41
View File
@@ -73,8 +73,7 @@ QDataStream& operator>>( QDataStream& in, CalypStandardResolutionVector& array )
class AddCustomFormat : public QDialog
{
public:
AddCustomFormat( QWidget* parent = NULL )
: QDialog( parent, Qt::Dialog | Qt::WindowTitleHint )
AddCustomFormat( QWidget* parent = NULL ) : QDialog( parent, Qt::Dialog | Qt::WindowTitleHint )
{
setWindowModality( Qt::ApplicationModal );
setWindowTitle( "Add custom resolution" );
@@ -137,8 +136,7 @@ private:
QSpinBox* m_spinHeight;
};
ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent )
: QDialog( parent )
ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent ) : QDialog( parent )
{
QString Name;
unsigned int uiWidth, uiHeight;
@@ -175,12 +173,18 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent )
QFont titleFont, menusFont, normalFont;
#if QT_VERSION > QT_VERSION_CHECK( 6, 0, 0 )
auto fontWeight = QFont::Weight::Bold;
#else
auto fontWeight = 75;
#endif
titleFont.setPointSize( 12 );
titleFont.setBold( true );
titleFont.setWeight( 75 );
titleFont.setWeight( fontWeight );
menusFont.setBold( true );
titleFont.setWeight( 75 );
titleFont.setWeight( fontWeight );
normalFont.setBold( false );
// menusFont.setPointSize( 12 );
@@ -382,8 +386,30 @@ ConfigureFormatDialog::ConfigureFormatDialog( QWidget* parent )
setFixedSize( MainLayout->sizeHint() );
}
int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, unsigned int& rWidth, unsigned int& rHeight,
int& rInputFormat, unsigned int& rBits, int& rEndianess, unsigned int& rFrameRate )
auto findPelFormatColorSpace( ClpPixelFormats rInputFormat ) -> std::pair<int, std::int64_t>
{
if( rInputFormat != ClpPixelFormats::Invalid )
{
auto pelFmtName = CalypFrame::pixelFormatName( rInputFormat );
for( unsigned int j = 0; j < CalypFrame::supportedColorSpacesListNames().size(); j++ )
{
const auto& formats_list = CalypFrame::supportedPixelFormatListNames( j );
for( const auto& [key, name] : formats_list )
{
if( pelFmtName == name )
{
return std::make_pair( j, static_cast<int>( key ) );
}
}
}
}
return std::make_pair( 0, 0 );
}
auto ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, unsigned int& rWidth,
unsigned int& rHeight, ClpPixelFormats& rInputFormat,
unsigned int& rBits, int& rEndianess,
unsigned int& rFrameRate ) -> QDialog::DialogCode
{
// Set default values
// setWindowTitle( "Configure resolution for " + Filename );
@@ -391,24 +417,8 @@ int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, un
m_spinBoxWidth->setValue( rWidth );
m_spinBoxheight->setValue( rHeight );
int colorSpace = 0;
int sampling = 0;
if( rInputFormat >= 0 )
{
std::string pelFmtName = CalypFrame::supportedPixelFormatListNames()[rInputFormat];
for( unsigned int j = 0; j < CalypFrame::supportedColorSpacesListNames().size(); j++ )
{
for( unsigned int i = 0; i < CalypFrame::supportedPixelFormatListNames( j ).size(); i++ )
{
if( pelFmtName == CalypFrame::supportedPixelFormatListNames( j )[i] )
{
colorSpace = j;
sampling = i;
break;
}
}
}
}
auto [colorSpace, sampling] = findPelFormatColorSpace( rInputFormat );
m_comboBoxColorSpace->setCurrentIndex( colorSpace );
m_comboBoxPixelFormat->setCurrentIndex( sampling );
m_spinBoxBits->setValue( rBits );
@@ -441,16 +451,8 @@ int ConfigureFormatDialog::runConfigureFormatDialog( const QString& Filename, un
rWidth = m_spinBoxWidth->value();
rHeight = m_spinBoxheight->value();
colorSpace = m_comboBoxColorSpace->currentIndex();
sampling = m_comboBoxPixelFormat->currentIndex();
std::string pelFmtName = CalypFrame::supportedPixelFormatListNames( colorSpace )[sampling];
for( unsigned int i = 0; i < CalypFrame::supportedPixelFormatListNames().size(); i++ )
{
if( pelFmtName == CalypFrame::supportedPixelFormatListNames()[i] )
{
rInputFormat = i;
break;
}
}
sampling = m_comboBoxPixelFormat->currentData().toInt();
rInputFormat = static_cast<ClpPixelFormats>( sampling );
rBits = m_spinBoxBits->value();
rEndianess = m_comboBoxEndianness->currentIndex();
rFrameRate = m_spinBoxFrameRate->value();
@@ -508,13 +510,13 @@ void ConfigureFormatDialog::slotResolutionChange()
void ConfigureFormatDialog::slotColorSpaceChange( int idx )
{
if( idx == -1 )
return;
if( idx == -1 ) return;
m_comboBoxPixelFormat->clear();
for( unsigned int i = 0; i < CalypFrame::supportedPixelFormatListNames( idx ).size(); i++ )
const auto& formats_list = CalypFrame::supportedPixelFormatListNames( idx );
for( const auto& [key, name] : formats_list )
{
m_comboBoxPixelFormat->insertItem( i, CalypFrame::supportedPixelFormatListNames( idx )[i].c_str() );
m_comboBoxPixelFormat->addItem( QString::fromStdString( std::string( name ) ), static_cast<int>( key ) );
}
m_comboBoxPixelFormat->setCurrentIndex( 0 );
}
@@ -542,6 +544,6 @@ void ConfigureFormatDialog::writeSettings()
{
QSettings appSettings;
QVariant var;
var.setValue<CalypStandardResolutionVector>( aRCustomFileFormats );
var.setValue( aRCustomFileFormats );
appSettings.setValue( "ConfigureFormatDialog/CustomFormats", var );
}
+4 -3
View File
@@ -38,7 +38,7 @@ class QSpinBox;
class QString;
class QWidget;
typedef QVector<CalypStandardResolution> CalypStandardResolutionVector;
using CalypStandardResolutionVector = QVector<CalypStandardResolution>;
QDataStream& operator<<( QDataStream& out, const CalypStandardResolutionVector& array );
QDataStream& operator>>( QDataStream& in, CalypStandardResolutionVector& array );
@@ -51,8 +51,9 @@ class ConfigureFormatDialog : public QDialog
public:
ConfigureFormatDialog( QWidget* parent = 0 );
int runConfigureFormatDialog( const QString& Filename, unsigned int& rWidth, unsigned int& rHeight, int& rInputFormat, unsigned int& rBits,
int& rEndianess, unsigned int& rFrameRate );
auto runConfigureFormatDialog( const QString& Filename, unsigned int& rWidth, unsigned int& rHeight,
ClpPixelFormats& rInputFormat, unsigned int& rBits, int& rEndianess,
unsigned int& rFrameRate ) -> QDialog::DialogCode;
void readSettings();
void writeSettings();
+16 -19
View File
@@ -36,18 +36,17 @@
class QLineEdit;
class OpionConfiguration : public QWidget
class OptionConfiguration : public QWidget
{
public:
OpionConfiguration( OptionBase* option )
OptionConfiguration( CalypOptions::OptionBase* option )
: m_cName{ option->opt_string }
{
m_pcChecked = NULL;
m_cName = option->opt_string;
m_pcDescription = new QLabel;
auto* pcDescription = new QLabel;
QString desc = QString::fromStdString( option->opt_desc );
m_pcDescription->setText( desc );
pcDescription->setText( desc );
QHBoxLayout* layout = new QHBoxLayout;
layout->addWidget( m_pcDescription, 0, Qt::AlignLeft );
layout->addWidget( pcDescription, 0, Qt::AlignLeft );
if( !option->isBinary() )
{
m_pcValue = new QLineEdit;
@@ -64,7 +63,7 @@ public:
layout->setContentsMargins( 1, 1, 1, 1 );
setLayout( layout );
}
const QString getValue() const
auto getValue() const -> QString
{
if( m_pcChecked )
{
@@ -72,12 +71,11 @@ public:
}
return m_pcValue->text();
}
const std::string& getName() { return m_cName; }
auto getName() const -> std::string { return m_cName; }
private:
QLineEdit* m_pcValue;
QCheckBox* m_pcChecked;
QLabel* m_pcDescription;
QLineEdit* m_pcValue{ nullptr };
QCheckBox* m_pcChecked{ nullptr };
std::string m_cName;
};
@@ -87,13 +85,12 @@ ModulesHandleOptDialog::ModulesHandleOptDialog( QWidget* parent, CalypAppModuleI
resize( 400, 10 );
setWindowTitle( "Select module parameters" );
const CalypOptions::OptionsList& moduleOptions = m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.getOptionList();
auto& moduleOptions = m_pcCurrModuleIf->m_pcModule->m_cModuleOptions.getOptionList();
QVBoxLayout* optionsLayout = new QVBoxLayout;
OpionConfiguration* pcOption;
for( CalypOptions::OptionsList::const_iterator it = moduleOptions.begin(); it != moduleOptions.end(); ++it )
for( auto& option : moduleOptions )
{
pcOption = new OpionConfiguration( ( *it )->opt );
auto pcOption = new OptionConfiguration( option->base_opt.get() );
m_apcOptionList.append( pcOption );
optionsLayout->addWidget( pcOption );
}
@@ -125,13 +122,13 @@ int ModulesHandleOptDialog::runConfiguration()
std::string optionString;
QString valueString( "" );
for( int i = 0; i < m_apcOptionList.size(); i++ )
for( const auto& option : m_apcOptionList )
{
valueString = m_apcOptionList.at( i )->getValue();
valueString = option->getValue();
if( !valueString.isEmpty() )
{
optionString.append( "--" );
optionString.append( m_apcOptionList.at( i )->getName() );
optionString.append( option->getName() );
if( !( valueString == "true" ) )
{
optionString.append( "=" );
+2 -2
View File
@@ -32,7 +32,7 @@
#include "CommonDefs.h"
#include "config.h"
class OpionConfiguration;
class OptionConfiguration;
/**
*
@@ -47,7 +47,7 @@ public:
private:
CalypAppModuleIf* m_pcCurrModuleIf;
QVector<OpionConfiguration*> m_apcOptionList;
QVector<OptionConfiguration*> m_apcOptionList;
};
#endif // __MODULEHANDLEOPTDIALOG_H__
-1
View File
@@ -25,7 +25,6 @@
#include "ProgressBar.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QLabel>
#include <QProgressBar>
#include <QVBoxLayout>
+10 -2
View File
@@ -2,7 +2,15 @@
# CMakeLists for qcustomplot
#
FIND_PACKAGE(Qt5 REQUIRED COMPONENTS Core Gui Widgets PrintSupport)
IF(${USE_QT6})
FIND_PACKAGE(Qt6 QUIET COMPONENTS Core Gui Widgets PrintSupport)
IF (NOT Qt6_FOUND)
FIND_PACKAGE(Qt5 REQUIRED COMPONENTS Core Gui Widgets PrintSupport)
ENDIF()
ELSE()
FIND_PACKAGE(Qt5 REQUIRED COMPONENTS Core Gui Widgets PrintSupport)
ENDIF()
SET(qcustomplot_SRCS qcustomplot.cpp qcustomplot.h)
@@ -13,5 +21,5 @@ IF(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
ENDIF()
ADD_LIBRARY(QCustomPlotLib STATIC ${qcustomplot_SRCS})
TARGET_LINK_LIBRARIES(QCustomPlotLib Qt5::Core Qt5::Gui Qt5::Widgets Qt5::PrintSupport)
TARGET_LINK_LIBRARIES(QCustomPlotLib Qt::Core Qt::Gui Qt::Widgets Qt::PrintSupport)
TARGET_INCLUDE_DIRECTORIES(QCustomPlotLib PUBLIC .)
Vendored Regular → Executable
+18
View File
@@ -1,3 +1,21 @@
#### Version 2.1.1 released on 06.11.22 ####
Added features:
- Qt6.4 Compatibility
Bugfixes:
- dynamically changing device pixel ratios (e.g. when moving between different DPI screens) is handled properly
- bugfix Colormap autoscaling: recalculateDataBounds() if (0, 0) data point is NaN.
- minor bugfix in getMantissa for certain values due to rounding errors
- Graphs with line style lsImpulse properly ignore NaN data points
- fixed issue where QCP wasn't greyed out together with the rest of the UI on embedded systems when a modal dialog is shown
(QCustomPlot no longer has the Qt::WA_OpaquePaintEvent attribute enabled by default)
Other:
- in QCPAxisPainterPrivate::getTickLabelData, don't use fixed 'e', but locale aware character of parent plot locale
- Axis rescaling now ignores +/- Inf in data values
- slight performance improvements of QCPColorMap colorization and fills.
#### Version 2.1.0 released on 29.03.21 ####
Added features:
+10309 -10898
View File
File diff suppressed because it is too large. Load diff
+3453 -3706
View File
File diff suppressed because it is too large. Load diff
+9 -4
View File
@@ -22,6 +22,10 @@
* \brief main file
*/
#include <QApplication>
#include <QMetaType>
#include <QStyleFactory>
#include "CommonDefs.h"
#include "ConfigureFormatDialog.h"
#include "MainWindow.h"
@@ -30,8 +34,7 @@
#ifdef USE_QTDBUS
#include "DBusAppAdaptor.h"
#endif
#include <QApplication>
#include <QStyleFactory>
#ifdef USE_FERVOR
#include "fvupdater.h"
#endif
@@ -43,10 +46,12 @@
int main( int argc, char* argv[] )
{
qRegisterMetaType<CalypFileInfoVector>();
qRegisterMetaTypeStreamOperators<CalypFileInfoVector>();
qRegisterMetaType<CalypStandardResolutionVector>();
#if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
qRegisterMetaTypeStreamOperators<CalypFileInfoVector>();
qRegisterMetaTypeStreamOperators<CalypStandardResolutionVector>();
#endif
QApplication::setStyle( "macOS" );
QApplication application( argc, argv );
QApplication::setApplicationName( QStringLiteral( "Calyp" ) );
QApplication::setApplicationVersion( QStringLiteral( CALYP_VERSION_STRING ) );
+52
View File
@@ -0,0 +1,52 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file CalypResource.h
* \brief Abstract calyp resource
*/
#ifndef __CALYPRESOURCE_H__
#define __CALYPRESOURCE_H__
#include <QObject>
#include "lib/CalypStream.h"
class CalypResource
{
public:
virtual ~CalypResource() = default;
virtual auto iteration() -> bool = 0;
virtual auto isReady() -> bool = 0;
virtual auto getResourceName() -> std::string = 0;
// TODO(JC) [[deprecated( "Do not directly access the resource" )]] after refactoring
virtual auto getResource() -> CalypStream* = 0;
protected:
CalypResource() = default;
CalypResource( CalypResource&& other ) noexcept = default;
CalypResource( const CalypResource& other ) = default;
auto operator=( CalypResource&& other ) noexcept -> CalypResource& = default;
auto operator=( const CalypResource& other ) -> CalypResource& = default;
};
#endif // __CALYPRESOURCE_H__
+351
View File
@@ -0,0 +1,351 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file VideostreamResource.h
* \brief Class to control video playback
*/
#include "VideostreamResource.h"
#include <qfileinfo.h>
#include <QDataStream>
#include <QElapsedTimer>
#include <QFileInfo>
#include <QRegularExpression>
#include <memory>
#include "lib/CalypFrame.h"
/**
* \brief Functions to control data stream from stream information
*/
auto operator<<( QDataStream& out, const CalypFileInfoVector& infos ) -> QDataStream&
{
out << infos.size();
for( const auto& info : infos )
{
out << info.m_cFilename << info.m_uiWidth << info.m_uiHeight << static_cast<int>( info.m_iPelFormat )
<< info.m_uiBitsPelPixel << info.m_iEndianness << info.m_uiFrameRate << info.m_uiFileSize << info.m_bForceRaw;
}
return out;
}
auto operator>>( QDataStream& in, CalypFileInfoVector& infos ) -> QDataStream&
{
auto array_size = infos.size();
in >> array_size;
for( int i = 0; i < array_size; i++ )
{
CalypFileInfo d;
int pelFormat{ 0 };
in >> d.m_cFilename;
in >> d.m_uiWidth;
in >> d.m_uiHeight;
in >> pelFormat;
in >> d.m_uiBitsPelPixel;
in >> d.m_iEndianness;
in >> d.m_uiFrameRate;
in >> d.m_uiFileSize;
in >> d.m_bForceRaw;
d.m_iPelFormat = static_cast<ClpPixelFormats>( pelFormat );
infos.append( d );
}
return in;
}
auto findCalypStreamInfo( const CalypFileInfoVector& array, const QString& filename ) -> int
{
for( int i = 0; i < array.size(); i++ )
{
if( array.at( i ).m_cFilename == filename ) return i;
}
return -1;
}
VideostreamResource::VideostreamResource( QObject* parent ) : QObject{ parent } {}
VideostreamResource::~VideostreamResource() = default;
auto VideostreamResource::iteration() -> bool
{
m_currStream.readNextFrameFillRGBBuffer();
return true;
}
auto VideostreamResource::isReady() -> bool
{
return m_currStream.hasWritingSlot();
}
bool VideostreamResource::loadFile( const CalypFileInfo& streamInfo, bool optimistic )
{
m_sStreamInfo = streamInfo;
ClpPixelFormats inputFormat = static_cast<ClpPixelFormats>( m_sStreamInfo.m_iPelFormat );
try
{
if( !m_currStream.open( streamInfo.m_cFilename.toStdString(), streamInfo.m_uiWidth, streamInfo.m_uiHeight,
inputFormat, streamInfo.m_uiBitsPelPixel, streamInfo.m_iEndianness,
streamInfo.m_uiFrameRate, streamInfo.m_bForceRaw, CalypStream::Type::Input ) )
{
return false;
}
}
catch( CalypFailure& e )
{
if( !optimistic )
{
return false;
}
throw( e );
}
m_currStream.getFormat( m_sStreamInfo.m_uiWidth, m_sStreamInfo.m_uiHeight, m_sStreamInfo.m_iPelFormat,
m_sStreamInfo.m_uiBitsPelPixel, m_sStreamInfo.m_iEndianness, m_sStreamInfo.m_uiFrameRate );
m_sStreamInfo.m_uiFileSize = QFileInfo{ streamInfo.m_cFilename }.size();
return true;
}
auto VideostreamResource::getCurrFrame() -> std::shared_ptr<CalypFrame>
{
return m_currStream.getCurrFrameAsset();
}
bool VideostreamResource::play()
{
bool isPlaying = false;
if( m_currStream.getFrameNum() > 1 )
{
isPlaying = true;
}
m_bIsPlaying = isPlaying;
return m_bIsPlaying;
}
bool VideostreamResource::playEvent()
{
bool bEndOfSeq = false;
if( m_bIsPlaying )
{
bEndOfSeq = goToNextFrame( true );
}
return bEndOfSeq;
}
void VideostreamResource::pause()
{
m_bIsPlaying = false;
triggerRefresh();
}
void VideostreamResource::seekAbsoluteEvent( unsigned int new_frame_num )
{
if( m_currStream.seekInput( new_frame_num ) ) triggerRefresh();
}
void VideostreamResource::seekRelativeEvent( bool bIsForward )
{
if( bIsForward )
{
goToNextFrame( true );
}
else
{
m_currStream.seekInputRelative( bIsForward );
triggerRefresh();
}
}
void VideostreamResource::stop()
{
m_bIsPlaying = false;
seekAbsoluteEvent( 0 );
return;
}
auto VideostreamResource::goToNextFrame( bool bThreaded ) -> bool
{
while( !m_currStream.hasNextFrame() && !m_currStream.isEof() )
{
}
bool bEndOfSeq = m_currStream.setNextFrame();
if( !bEndOfSeq )
{
triggerRefresh();
}
return bEndOfSeq;
}
void VideostreamResource::triggerRefresh() {}
auto video_resource_guess_format( const QString& filename, unsigned int& rWidth, unsigned int& rHeight,
ClpPixelFormats& rInputFormat, unsigned int& rBitsPerPixel, int& rEndianness,
unsigned int& rFrameRate ) -> bool
{
std::vector<CalypStandardResolution> stdResList = CalypStream::stdResolutionSizes();
bool bGuessed = true;
bool bGuessedByFilesize = false;
QString FilenameShort = QFileInfo( filename ).fileName();
QString fileExtension = QFileInfo( filename ).suffix();
if( filename.startsWith( "/dev/" ) )
{
return true;
}
if( !fileExtension.compare( "yuv", Qt::CaseInsensitive ) || !fileExtension.compare( "rgb", Qt::CaseInsensitive ) ||
!fileExtension.compare( "gray", Qt::CaseInsensitive ) )
{
bGuessed = false;
// Guess pixel format
const auto& formats_list = CalypFrame::supportedPixelFormatListNames();
for( const auto& [key, name] : formats_list )
{
if( FilenameShort.contains( QString::fromStdString( std::string( name ) ), Qt::CaseInsensitive ) )
{
rInputFormat = key;
break;
}
}
if( rWidth == 0 || rHeight == 0 )
{
// Guess resolution - match resolution name
int iMatch = -1;
for( unsigned int i = 0; i < stdResList.size(); i++ )
{
if( FilenameShort.contains( QString::fromStdString( stdResList[i].shortName ) ) )
{
iMatch = i;
}
}
if( iMatch >= 0 )
{
rWidth = stdResList[iMatch].uiWidth;
rHeight = stdResList[iMatch].uiHeight;
}
// Guess resolution - match %dx%d
// QRegularExpressionMatch resolutionMatch = QRegularExpression( "_\\d*x\\d*" ).match( FilenameShort );
QRegularExpressionMatch resolutionMatch = QRegularExpression( "_[0-9]+x[0-9]+" ).match( FilenameShort );
if( resolutionMatch.hasMatch() )
{
QString resolutionString = resolutionMatch.captured( resolutionMatch.lastCapturedIndex() );
if( resolutionString.startsWith( "_" ) || resolutionString.endsWith( "_" ) )
{
resolutionString.remove( "_" );
QStringList resolutionArgs = resolutionString.split( "x" );
if( resolutionArgs.size() == 2 )
{
rWidth = resolutionArgs.at( 0 ).toUInt();
rHeight = resolutionArgs.at( 1 ).toUInt();
}
}
}
}
// Guess resolution by file size
if( rWidth == 0 && rHeight == 0 )
{
FILE* pF = fopen( filename.toStdString().c_str(), "rb" );
if( pF )
{
fseek( pF, 0, SEEK_END );
unsigned long long int uiFileSize = ftell( pF );
fclose( pF );
int count = 0;
int match = -1;
for( unsigned int i = 0; i < stdResList.size(); i++ )
{
auto frame_bytes =
CalypFrame::getBytesPerFrame( stdResList[i].uiWidth, stdResList[i].uiHeight, rInputFormat, 8 );
auto module = uiFileSize % frame_bytes;
if( module == 0 )
{
match = i;
count++;
}
}
if( count == 1 )
{
rWidth = stdResList[match].uiWidth;
rHeight = stdResList[match].uiHeight;
bGuessedByFilesize = true;
}
}
}
// [.|_]
// Guess bits per pixel - match %dbpp
QRegularExpressionMatch BppMatch = QRegularExpression( "_[0-9]+bpp" ).match( FilenameShort );
if( BppMatch.hasMatch() )
{
QString matchString = BppMatch.captured( BppMatch.lastCapturedIndex() );
matchString.remove( "_" );
matchString.remove( "bpp" );
rBitsPerPixel = matchString.toUInt();
if( !( rBitsPerPixel > 0 && rBitsPerPixel < 16 ) )
{
rBitsPerPixel = -1;
}
}
QRegularExpressionMatch BppOnlyMatch = QRegularExpression( "_[0-9]+b" ).match( FilenameShort );
if( BppOnlyMatch.hasMatch() )
{
QString matchString = BppOnlyMatch.captured( BppOnlyMatch.lastCapturedIndex() );
matchString.remove( "_" );
matchString.remove( "b" );
rBitsPerPixel = matchString.toUInt();
if( !( rBitsPerPixel > 0 && rBitsPerPixel < 16 ) )
{
rBitsPerPixel = -1;
}
}
// Guess frame rate - match %dbpp
QRegularExpressionMatch FpsMatch = QRegularExpression( "_[0-9]+fps" ).match( FilenameShort );
if( FpsMatch.hasMatch() )
{
QString matchString = FpsMatch.captured( FpsMatch.lastCapturedIndex() );
matchString.remove( "_" );
matchString.remove( "fps" );
rFrameRate = matchString.toUInt();
if( rFrameRate < 0 )
{
rFrameRate = 30;
}
}
// Guess Endianness
if( FilenameShort.contains( QStringLiteral( "be" ), Qt::CaseInsensitive ) )
{
rEndianness = CLP_BIG_ENDIAN;
}
if( FilenameShort.contains( QStringLiteral( "le" ), Qt::CaseInsensitive ) )
{
rEndianness = CLP_LITTLE_ENDIAN;
}
if( rWidth > 0 && rHeight > 0 && rInputFormat != ClpPixelFormats::Invalid ) bGuessed = true && !bGuessedByFilesize;
}
return bGuessed;
}
+106
View File
@@ -0,0 +1,106 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file VideostreamResource.h
* \brief Class to control video playback
*/
#ifndef __VIDEOSTREAMRESOURCE_H__
#define __VIDEOSTREAMRESOURCE_H__
#include <QElapsedTimer>
#include <QWidget>
#include "CalypResource.h"
#include "CommonDefs.h"
#include "config.h"
#include "lib/CalypStream.h"
struct CalypFileInfo
{
QString m_cFilename;
unsigned int m_uiWidth;
unsigned int m_uiHeight;
ClpPixelFormats m_iPelFormat;
unsigned int m_uiBitsPelPixel{ 8 };
int m_iEndianness{ CLP_LITTLE_ENDIAN };
unsigned int m_uiFrameRate{ 30 };
unsigned long long int m_uiFileSize;
bool m_bForceRaw{ false };
};
using CalypFileInfoVector = QVector<CalypFileInfo>;
auto operator<<( QDataStream& out, const CalypFileInfoVector& infos ) -> QDataStream&;
auto operator>>( QDataStream& in, CalypFileInfoVector& infos ) -> QDataStream&;
auto findCalypStreamInfo( const CalypFileInfoVector& array, const QString& filename ) -> int;
class VideostreamResource : public QObject, public CalypResource
{
Q_OBJECT
public:
VideostreamResource( QObject* parent = nullptr );
VideostreamResource( VideostreamResource&& other ) noexcept = delete;
VideostreamResource& operator=( VideostreamResource&& other ) noexcept = delete;
VideostreamResource( const VideostreamResource& other ) = delete;
VideostreamResource& operator=( const VideostreamResource& other ) = delete;
~VideostreamResource();
auto getResourceName() -> std::string override { return m_currStream.getFileName(); };
auto iteration() -> bool override;
auto isReady() -> bool override;
auto loadFile( const CalypFileInfo& streamInfo, bool optimistic = true ) -> bool;
auto getStreamInfo() const -> CalypFileInfo { return m_sStreamInfo; }
auto getResource() -> CalypStream* override { return &m_currStream; };
auto getStream() const -> const CalypStream& { return m_currStream; };
auto getCurrFrame() -> std::shared_ptr<CalypFrame>;
bool play();
void pause();
void stop();
bool playEvent();
void seekAbsoluteEvent( unsigned int new_frame_num );
void seekRelativeEvent( bool bIsForward );
private:
auto goToNextFrame( bool bThreaded ) -> bool;
void triggerRefresh();
// Q_SIGNALS:
// private Q_SLOTS:
private: // NOLINT
CalypStream m_currStream;
CalypFileInfo m_sStreamInfo;
bool m_bIsPlaying;
};
auto video_resource_guess_format( const QString& filename, unsigned int& rWidth, unsigned int& rHeight,
ClpPixelFormats& rInputFormat, unsigned int& rBitsPerPixel, int& rEndianness,
unsigned int& rFrameRate ) -> bool;
Q_DECLARE_METATYPE( CalypFileInfo ) // NOLINT
Q_DECLARE_METATYPE( CalypFileInfoVector ) // NOLINT
#endif // __VIDEOSTREAMRESOURCE_H__
+1 -1
View File
@@ -35,7 +35,7 @@ class QLabel;
class FrameNumberWidget : public QWidget
{
public:
FrameNumberWidget( QWidget* parent = 0 );
explicit FrameNumberWidget( QWidget* parent = 0 );
void setCurrFrameNum( int number );
void setTotalFrameNum( int number );
void clear();
+10 -9
View File
@@ -41,7 +41,7 @@ class HistogramWorker : public QThread
{
private:
QObject* m_parent;
std::shared_ptr<CalypFrame> m_pcFrame;
std::shared_ptr<CalypFrame> m_pcFrame{ nullptr };
public:
HistogramWorker( QObject* parent )
@@ -52,27 +52,28 @@ public:
void setup( std::shared_ptr<CalypFrame> frame )
{
m_pcFrame = std::move( frame );
EventData* eventData = new EventData( m_pcFrame.get() ); // NOLINT
EventData* eventData = new EventData(); // NOLINT
eventData->starting = true;
// QCoreApplication::postEvent( m_parent, eventData );
start();
QCoreApplication::postEvent( m_parent, eventData );
}
void run() override
{
if( m_pcFrame != nullptr && m_parent != nullptr )
EventData* eventData = new EventData(); // NOLINT
if( m_pcFrame != nullptr )
{
EventData* eventData = new EventData( m_pcFrame.get() ); // NOLINT
m_pcFrame->calcHistogram();
eventData->success = true;
QCoreApplication::postEvent( m_parent, eventData );
eventData->frame = m_pcFrame.get();
}
eventData->success = true;
QCoreApplication::postEvent( m_parent, eventData );
}
class EventData : public QEvent
{
public:
EventData( CalypFrame* f )
: QEvent( QEvent::User ), frame{ f } {}
EventData()
: QEvent( QEvent::User ), frame{ nullptr } {}
CalypFrame* frame{ nullptr };
bool starting{ false };
bool success{ false };
@@ -33,15 +33,15 @@ AbsoluteFrameDifferenceExample::AbsoluteFrameDifferenceExample()
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2; // Use API version 2 (recommended).
// See this example for details on the functions prototype
m_iModuleType = CLP_FRAME_PROCESSING_MODULE; // Apply module to the frames or to the whole sequence.
m_iModuleType = ClpModuleType::FrameProcessing; // Apply module to the frames or to the whole sequence.
m_pchModuleCategory = "Measurements"; // Category (sub-menu)
m_pchModuleName = "AbsoluteDifferenceExample"; // Name
m_pchModuleLongName = "Absolute Difference Example"; // Name
m_pchModuleTooltip = "Measure the absolute difference " // Description
"between two images (Y plane), e. g., abs( Y1 - Y2 )";
m_uiNumberOfFrames = 2; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES)
m_uiModuleRequirements = CLP_MODULE_REQUIRES_NEW_WINDOW; // Module requirements (check CalypModulesIf.h).
// Several requirements should be "or" between each others.
m_uiNumberOfFrames = 2; // Number of Frames required (ONE_FRAME, TWO_FRAMES, THREE_FRAMES)
m_uiModuleRequirements = ClpModuleFeature::NewWindow; // Module requirements (check CalypModulesIf.h).
// Several requirements should be "or" between each others.
m_pcFrameDifference = NULL;
}
@@ -56,7 +56,7 @@ bool AbsoluteFrameDifferenceExample::create( std::vector<CalypFrame*> apcFrameLi
return false;
m_pcFrameDifference =
new CalypFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), CLP_GRAY );
new CalypFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), ClpPixelFormats::Gray );
return true;
}
@@ -29,10 +29,8 @@
#include "CalypModuleIf.h"
class AbsoluteFrameDifferenceExample : public CalypModuleIf
class AbsoluteFrameDifferenceExample : public CalypModuleIf, public CalypModuleInstance<AbsoluteFrameDifferenceExample>
{
REGISTER_CLASS_FACTORY( AbsoluteFrameDifferenceExample )
private:
CalypFrame* m_pcFrameDifference;
+3 -3
View File
@@ -29,13 +29,13 @@ REGISTER_CLASS_MAKER( FrameBinarizationAPIv1 )
FrameBinarizationAPIv1::FrameBinarizationAPIv1()
{
/* Module Definition */
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Utilities";
m_pchModuleName = "FrameBinarizationAPIv1";
m_pchModuleLongName = "Frame Binarization API v1";
m_pchModuleTooltip = "Binarize frame";
m_uiNumberOfFrames = 1;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_OPTIONS;
m_uiModuleRequirements = ClpModuleFeature::Options;
m_cModuleOptions.addOptions() /**/
( "threshold", m_uiThreshold, "Threshold level for binarization (0-255) [128]" );
@@ -47,7 +47,7 @@ FrameBinarizationAPIv1::FrameBinarizationAPIv1()
void FrameBinarizationAPIv1::create( CalypFrame* frame )
{
m_pcBinFrame = NULL;
m_pcBinFrame = new CalypFrame( frame->getWidth(), frame->getHeight(), CLP_GRAY, 8 );
m_pcBinFrame = new CalypFrame( frame->getWidth(), frame->getHeight(), ClpPixelFormats::Gray, 8 );
}
CalypFrame* FrameBinarizationAPIv1::process( CalypFrame* frame )
+1 -3
View File
@@ -27,10 +27,8 @@
#include "CalypModuleIf.h"
class FrameBinarizationAPIv1 : public CalypModuleIf
class FrameBinarizationAPIv1 : public CalypModuleIf, public CalypModuleInstance<FrameBinarizationAPIv1>
{
REGISTER_CLASS_FACTORY( FrameBinarizationAPIv1 )
private:
CalypFrame* m_pcBinFrame;
unsigned int m_uiThreshold;
+3 -3
View File
@@ -8,6 +8,8 @@ EXPORT(PACKAGE MyLib)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/..)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations")
SET(Calyp_Lib_Frame_SRCS CalypPixel.cpp PixelFormats.h PixelFormats.cpp CalypFrame.h CalypFrame.cpp)
SET(Calyp_Lib_Stream_SRCS
@@ -22,7 +24,7 @@ SET(Calyp_Lib_Stream_SRCS
SET(Calyp_Lib_OptionParser_SRCS CalypOptions.h CalypOptions.cpp)
SET(Calyp_Lib_Modules_SRCS CalypOptions.h CalypOptions.cpp)
SET(Calyp_Lib_Modules_SRCS CalypModuleIf.h CalypModuleIf.cpp)
SET(Calyp_Lib_SRCS CalypLib.h CalypDefs.h ${Calyp_Lib_Frame_SRCS} ${Calyp_Lib_Stream_SRCS} ${Calyp_Lib_OptionParser_SRCS} ${Calyp_Lib_Modules_SRCS})
@@ -44,8 +46,6 @@ IF(USE_OPENCV)
LIST(APPEND Calyp_Lib_SRCS StreamHandlerOpenCV.h)
LIST(APPEND Calyp_Lib_SRCS StreamHandlerOpenCV.cpp)
LIST(APPEND Calyp_Lib_SRCS CalypOpenCVModuleIf.cpp)
LIST(APPEND CMAKE_CFG_LINKER_LIBSS ${OpenCV_LIBRARIES})
LIST(APPEND CMAKE_CFG_INCLUDE_DIRS ${OpenCV_INCLUDE_DIRS})
+8 -11
View File
@@ -20,13 +20,14 @@
/**
* \file CalypDefs.h
* \ingroup CalypLibGrp
* \brief Define basic types, new types and enumerations
* \brief Define basic types, new types and enumerations (private use only)
*/
#ifndef __CALYPDEFS_H__
#define __CALYPDEFS_H__
#include <algorithm>
#include <format>
#include <iterator>
#include <memory>
#include <string>
@@ -58,20 +59,16 @@ inline std::string clpUppercase( const std::string& in )
struct CalypFailure : public std::exception
{
std::string m_class_name;
std::string m_error_msg;
CalypFailure( std::string error_msg ) throw()
: m_error_msg( error_msg ) {}
CalypFailure( std::string error_msg ) throw() : m_error_msg{ std::move( error_msg ) } {}
CalypFailure( std::string class_name, std::string error_msg ) throw()
: m_class_name( class_name ), m_error_msg( error_msg )
: m_error_msg{ std::format( "[%s] %s", class_name, error_msg ) }
{
}
~CalypFailure() throw() {}
const char* what() const throw()
{
std::string* msg = new std::string( "[" + m_class_name + "] " + m_error_msg );
return msg->c_str();
}
auto what() const throw() -> const char* { return m_error_msg.c_str(); }
private:
std::string m_error_msg;
};
#endif // __CALYPDEFS_H__
+594 -596
View File
File diff suppressed because it is too large. Load diff
+259 -234
View File
@@ -26,8 +26,11 @@
#ifndef __CALYPFRAME_H__
#define __CALYPFRAME_H__
#include <array>
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <vector>
@@ -35,7 +38,7 @@
namespace cv
{
class Mat;
}
} // namespace cv
using ClpPel = std::uint16_t;
using ClpByte = std::uint8_t;
@@ -56,24 +59,23 @@ enum CalypColorSpace
};
/**
* \enum CalypPixelFormats
* \enum ClpPixelFormats
* \brief List of supported pixel formats
* \ingroup CalypLibGrp
*/
enum CalypPixelFormats
enum class ClpPixelFormats : int
{
CLP_INVALID_FMT = -1, //!< Invalid
CLP_YUV420P = 0, //!< YUV 420 progressive
CLP_YUV422P, //!< YUV 422 progressive
CLP_YUV444P, //!< YUV 444 progressive
CLP_YUYV422, //!< YUV 422 interleaved
CLP_GRAY, //!< Grayscale
CLP_RGB24P, //!< RGB 32 bpp progressive
CLP_RGB24, //!< RGB 32 bpp
CLP_BGR24, //!< BGR 32 bpp
CLP_RGBA32, //!< RGBA 32 bpp
CLP_BGRA32, //!< BGRA 32 bpp
CLP_MAX_FMT = 255, //!< Account for future formats
Invalid = -1, //!< Invalid
YUV420p = 0, //!< YUV 420 progressive
YUV422p, //!< YUV 422 progressive
YUV444p, //!< YUV 444 progressive
YUYV422, //!< YUV 422 interleaved
Gray, //!< Grayscale
RGB24p, //!< RGB 32 bpp progressive
RGB24, //!< RGB 32 bpp
BGR24, //!< BGR 32 bpp
RGBA32, //!< RGBA 32 bpp
BGRA32, //!< BGRA 32 bpp
};
enum CLP_YUV_Components
@@ -93,11 +95,15 @@ enum CLP_RGB_Components
enum CLP_Endianness
{
CLP_INVALID_ENDIANESS = -1,
CLP_BIG_ENDIAN = 0,
CLP_LITTLE_ENDIAN = 1,
};
#define CHROMASHIFT( SIZE, SHIFT ) (unsigned int)( -( ( -( (int)( SIZE ) ) ) >> ( SHIFT ) ) )
constexpr auto CHROMASHIFT( unsigned int size, unsigned int shift ) -> unsigned int
{
return -( ( -( static_cast<int>( size ) ) ) >> ( shift ) ); // NOLINT
}
/**
* \class CalypPixel
@@ -106,41 +112,55 @@ enum CLP_Endianness
*/
class CalypPixel
{
private:
static constexpr std::size_t kMaxNumberOfComponents{ 4 };
int m_colorSpace{ CLP_COLOR_INVALID };
std::array<ClpPel, kMaxNumberOfComponents> m_pelComp{ 0, 0, 0, 0 };
public:
static int getMaxNumberOfComponents();
static constexpr std::size_t getMaxNumberOfComponents() { return kMaxNumberOfComponents; }
CalypPixel( const int& CalypColorSpace = CLP_COLOR_INVALID );
CalypPixel( const int& CalypColorSpace, const ClpPel& c0 );
CalypPixel( const int& CalypColorSpace, const ClpPel& c0, const ClpPel& c1, const ClpPel& c2 );
CalypPixel( const int& CalypColorSpace, const ClpPel& c0, const ClpPel& c1, const ClpPel& c2, const ClpPel& c3 );
CalypPixel( const CalypPixel& other );
~CalypPixel();
CalypPixel() = default;
explicit CalypPixel( int calypColorSpace, ClpPel c0 = 0 );
CalypPixel( int calypColorSpace, ClpPel c0, ClpPel c1, ClpPel c2 );
CalypPixel( int calypColorSpace, ClpPel c0, ClpPel c1, ClpPel c2, ClpPel c3 );
CalypPixel( const CalypPixel& other ) noexcept = default;
CalypPixel( CalypPixel&& other ) noexcept = default;
auto operator=( const CalypPixel& other ) -> CalypPixel& = default;
auto operator=( CalypPixel&& other ) noexcept -> CalypPixel& = default;
~CalypPixel() = default;
int colorSpace() const;
int colorSpace() const { return m_colorSpace; };
ClpPel operator[]( const int& channel ) const;
ClpPel& operator[]( const int& channel );
auto components() const -> const std::array<ClpPel, kMaxNumberOfComponents>& { return m_pelComp; };
auto components() -> std::array<ClpPel, kMaxNumberOfComponents>& { return m_pelComp; };
CalypPixel operator=( const CalypPixel& );
CalypPixel operator+( const CalypPixel& );
CalypPixel operator+=( const CalypPixel& );
CalypPixel operator-( const CalypPixel& );
CalypPixel operator-=( const CalypPixel& );
CalypPixel operator*( const double& );
auto operator[]( const std::size_t channel ) const -> ClpPel { return m_pelComp[channel]; }
auto operator[]( const std::size_t channel ) -> ClpPel& { return m_pelComp[channel]; }
auto operator+=( const CalypPixel& ) -> CalypPixel&;
auto operator-=( const CalypPixel& ) -> CalypPixel&;
auto operator*=( double ) -> CalypPixel&;
auto operator+( const CalypPixel& ) const -> CalypPixel;
auto operator-( const CalypPixel& ) const -> CalypPixel;
auto operator*( double ) const -> CalypPixel;
auto operator==( const CalypPixel& other ) const -> bool;
friend auto operator<<( std::ostream& os, const CalypPixel& p ) -> std::ostream&;
/**
* Convert a Pixel to a new color space
* @param inputPixel input pixel (CalypPixel)
* @param eOutputSpace output color space
* @return converted pixel
*/
CalypPixel convertPixel( CalypColorSpace eOutputSpace );
private:
class CalypPixelPrivate;
std::unique_ptr<CalypPixelPrivate> d;
* Convert a Pixel to a new color space
* @param inputPixel input pixel (CalypPixel)
* @param eOutputSpace output color space
* @return converted pixel
*/
auto convertPixel( CalypColorSpace eOutputSpace ) const -> CalypPixel;
};
auto operator<<( std::ostream& stream, const CalypPixel& pixel ) -> std::ostream&;
/**
* \class CalypPlane
* \ingroup CalypLibGrp CalypPlaneGrp
@@ -192,33 +212,24 @@ class CalypFrame
{
public:
/**
* Function that handles the supported color space
* of CalypFrame
* @return vector of strings with pixel formats names
*/
* Function that handles the supported color space
* of CalypFrame
* @return vector of strings with pixel formats names
*/
static std::vector<std::string> supportedColorSpacesListNames();
/**
* Function that handles the supported pixel formats
* of CalypFrame
* @return vector of strings with pixel formats names
*/
static std::vector<std::string> supportedPixelFormatListNames();
static std::vector<std::string> supportedPixelFormatListNames( int colorSpace );
static int numberOfFormats();
static int findPixelFormat( const std::string& name );
static int pelformatColorSpace( const int idx );
/**
* Creates a new frame using the following configuration
*
* @param width width of the frame
* @param height height of the frame
* @param pel_format pixel format index (always use PixelFormats enum)
*
* @note this function might misbehave if the pixel format enum is not correct
*/
CalypFrame( unsigned int width, unsigned int height, int pelFormat, unsigned bitsPixel = 8 );
* Function that handles the supported pixel formats
* of CalypFrame
* @return vector of strings with pixel formats names
*/
static constexpr auto numberOfFormats() -> std::size_t;
static auto findPixelFormat( const std::string& name ) -> std::optional<ClpPixelFormats>;
static auto findPixelFormat( std::string_view name ) -> std::optional<ClpPixelFormats>;
static auto pelFormatColorSpace( ClpPixelFormats idx ) -> int;
static auto supportedPixelFormatListNames() -> std::map<ClpPixelFormats, std::string_view>;
static auto supportedPixelFormatListNames( int colorSpace ) -> std::map<ClpPixelFormats, std::string_view>;
static auto pixelFormatName( ClpPixelFormats idx ) -> std::string_view;
/**
* Creates a new frame using the following configuration
@@ -229,27 +240,39 @@ public:
*
* @note this function might misbehave if the pixel format enum is not correct
*/
CalypFrame( unsigned int width, unsigned int height, int pelFormat, unsigned bitsPixel, bool has_negative_values );
CalypFrame( unsigned int width, unsigned int height, ClpPixelFormats pelFormat, unsigned bitsPixel = 8 );
/**
* Creates a new frame using the following configuration
*
* @param width width of the frame
* @param height height of the frame
* @param pel_format pixel format index (always use PixelFormats enum)
*
* @note this function might misbehave if the pixel format enum is not correct
*/
CalypFrame( unsigned int width, unsigned int height, ClpPixelFormats pelFormat, unsigned bitsPixel,
bool hasNegativeValues );
/**
* Move contructor
*
* @param other existing frame to copy from
*/
CalypFrame( CalypFrame&& other ) noexcept;
CalypFrame( CalypFrame&& other ) noexcept = default;
/**
* Move assignement contructor
*
* @param other existing frame to copy from
*/
CalypFrame& operator=( CalypFrame&& other ) noexcept;
auto operator=( CalypFrame&& other ) noexcept -> CalypFrame& = default;
/**
* Copy contructor
*
* @param other existing frame to copy from
*/
* Copy contructor
*
* @param other existing frame to copy from
*/
CalypFrame( const CalypFrame& other );
/**
@@ -257,26 +280,26 @@ public:
*
* @param other existing frame to copy from
*/
CalypFrame& operator=( const CalypFrame& other );
auto operator=( const CalypFrame& other ) -> CalypFrame&;
/**
* Creates and new frame with the configuration of an existing one and copy
* its contents. This function only copies a specific region from the existing
* frame
*
* @param other existing frame to copy from
* @param posX position X to crop from
* @param posY position Y to crop from
* @param areaWidth crop width
* @param areaHeight crop height
*/
* Creates and new frame with the configuration of an existing one and copy
* its contents. This function only copies a specific region from the existing
* frame
*
* @param other existing frame to copy from
* @param posX position X to crop from
* @param posY position Y to crop from
* @param areaWidth crop width
* @param areaHeight crop height
*/
CalypFrame( const CalypFrame& other, unsigned int x, unsigned int y, unsigned int width, unsigned int height );
CalypFrame( const CalypFrame* other, unsigned int x, unsigned int y, unsigned int width, unsigned int height );
~CalypFrame();
/** Format match opts
*/
*/
enum FormatMatching
{
MATCH_COLOR_SPACE = 1,
@@ -289,196 +312,198 @@ public:
};
/**
* Check if two CalypFrames have the same fmt
* @param other frame to compare with
* @param match matching conditions (use enum FormatMatching)
* @return true if format matches
*/
bool haveSameFmt( const CalypFrame& other, unsigned int match = MATCH_ALL ) const;
bool haveSameFmt( const CalypFrame* other, unsigned int match = MATCH_ALL ) const;
* Check if two CalypFrames have the same fmt
* @param other frame to compare with
* @param match matching conditions (use enum FormatMatching)
* @return true if format matches
*/
auto haveSameFmt( const CalypFrame& other, unsigned int match = MATCH_ALL ) const -> bool;
auto haveSameFmt( const CalypFrame* other, unsigned int match = MATCH_ALL ) const -> bool;
/**
* Get pixel format information
* @return pixel format index
*/
int getPelFormat() const;
* Get pixel format information
* @return pixel format index
*/
auto getPelFormat() const -> ClpPixelFormats;
/**
* Get pixel format information
* @return pixel format name
*/
std::string getPelFmtName();
* Get pixel format information
* @return pixel format name
*/
auto getPelFmtName() const -> std::string;
/**
* Get color space information
* @return get color space index
*/
int getColorSpace() const;
* Get color space information
* @return get color space index
*/
auto getColorSpace() const -> int;
/**
* Get the number of channels
* @return number of channels
*/
unsigned getNumberChannels() const;
* Get the number of channels
* @return number of channels
*/
auto getNumberChannels() const -> unsigned;
/**
* Get width of the frame
* @param channel/component
* @return number of pixels
*/
unsigned int getWidth( unsigned channel = 0 ) const;
* Get width of the frame
* @param channel/component
* @return number of pixels
*/
auto getWidth( unsigned channel = 0 ) const -> unsigned int;
/**
* Get height of the frame
* @param channel/component
* @return number of pixels
*/
unsigned int getHeight( unsigned channel = 0 ) const;
* Get height of the frame
* @param channel/component
* @return number of pixels
*/
auto getHeight( unsigned channel = 0 ) const -> unsigned int;
/**
* Check if frame has negative values
* @return Boolean with the flag value
*/
bool getHasNegativeValues() const;
auto getHasNegativeValues() const -> bool;
/**
* Get number of pixels of the frame
* @param channel/component
* @return number of pixels
*/
std::uint64_t getPixels( unsigned channel = 0 ) const;
* Get number of pixels of the frame
* @param channel/component
* @return number of pixels
*/
auto getPixels( unsigned channel = 0 ) const -> std::uint64_t;
/**
* Get the total number of pixels of the frame
* @return number of pixels
*/
std::uint64_t getTotalNumberOfPixels() const;
auto getTotalNumberOfPixels() const -> std::uint64_t;
/**
* Get chroma width ratio
* @return ratio multiple of 2
*/
unsigned getChromaWidthRatio() const;
* Get chroma width ratio
* @return ratio multiple of 2
*/
auto getChromaWidthRatio() const -> unsigned;
/**
* Get chroma height ratio
* @return ratio multiple of 2
*/
unsigned getChromaHeightRatio() const;
* Get chroma height ratio
* @return ratio multiple of 2
*/
auto getChromaHeightRatio() const -> unsigned;
/**
* Get number of pixels in each chroma channel
* @return number of pixels
*/
std::uint64_t getChromaLength() const;
* Get number of pixels in each chroma channel
* @return number of pixels
*/
auto getChromaLength() const -> std::uint64_t;
/**
* Get number of bits per pixel
* @return number of bits
*/
unsigned int getBitsPel() const;
* Get number of bits per pixel
* @return number of bits
*/
auto getBitsPel() const -> unsigned int;
/**
* Get number of bytes per frame of an existing frame
* @return number of bytes per frame
*/
std::uint64_t getBytesPerFrame() const;
* Get number of bytes per frame of an existing frame
* @return number of bytes per frame
*/
auto getBytesPerFrame() const -> std::uint64_t;
/**
* Get number of bytes per frame of a specific pixel format
* @return number of bytes per frame
*/
static std::uint64_t getBytesPerFrame( unsigned int uiWidth, unsigned int uiHeight, int iPixelFormat, unsigned int bitsPixel );
* Get number of bytes per frame of a specific pixel format
* @return number of bytes per frame
*/
static auto getBytesPerFrame( unsigned int uiWidth, unsigned int uiHeight, ClpPixelFormats pelFormat,
unsigned int bitsPixel ) -> std::uint64_t;
/**
* Reset frame pixels to zero
*/
* Reset frame pixels to zero
*/
void reset();
ClpPel*** getPelBufferYUV() const;
ClpPel*** getPelBufferYUV();
auto getPelBufferYUV() const -> ClpPel***;
auto getPelBufferYUV() -> ClpPel***;
auto getRGBBuffer() const -> const unsigned char*;
auto getRGBBuffer() const -> std::optional<std::span<const std::uint8_t>>;
/**
* Get pixel value at coordinates
* @param ch frame channel
* @param xPos position in X axis
* @param yPos position in Y axis
* @param ch frame channel
* @param xPos position in X axis
* @param yPos position in Y axis
* @param absolute whether it should return positive/negative values
* @return pixel value
*/
ClpPel operator()( unsigned int ch, unsigned int xPos, unsigned int yPos, bool absolute = true ) const;
* @return pixel value
*/
auto operator()( unsigned int ch, unsigned int xPos, unsigned int yPos, bool absolute = true ) const -> ClpPel;
/**
* Get pixel value at coordinates
* @param xPos position in X axis
* @param yPos position in Y axis
* @return pixel value
*/
CalypPixel operator()( unsigned int xPos, unsigned int yPos ) const;
* Get pixel value at coordinates
* @param xPos position in X axis
* @param yPos position in Y axis
* @return pixel value
*/
auto operator()( unsigned int xPos, unsigned int yPos ) const -> CalypPixel;
/**
* Get pixel value at coordinates
* @param xPos position in X axis
* @param yPos position in Y axis
* @return pixel value
*/
CalypPixel getPixel( unsigned int xPos, unsigned int yPos ) const;
* Get pixel value at coordinates
* @param xPos position in X axis
* @param yPos position in Y axis
* @return pixel value
*/
auto getPixel( unsigned int xPos, unsigned int yPos ) const -> CalypPixel;
/**
* Get pixel value at coordinates
* in the desired color space
* @param xPos position in X axis
* @param yPos position in Y axis
* @param eColorSpace desired color space
* @return pixel value
*/
CalypPixel getPixel( unsigned int xPos, unsigned int yPos, CalypColorSpace eColorSpace );
* Get pixel value at coordinates
* in the desired color space
* @param xPos position in X axis
* @param yPos position in Y axis
* @param eColorSpace desired color space
* @return pixel value
*/
auto getPixel( unsigned int xPos, unsigned int yPos, CalypColorSpace eColorSpace ) const -> CalypPixel;
/**
* Set pixel value at coordinates to a given value
* @param xPos position in X axis
* @param yPos position in Y axis
*/
* Set pixel value at coordinates to a given value
* @param xPos position in X axis
* @param yPos position in Y axis
*/
void setPixel( unsigned int xPos, unsigned int yPos, CalypPixel pixel );
/**
* Copy a frame into the current buffer
* @param other frame to be copied
*/
* Copy a frame into the current buffer
* @param other frame to be copied
*/
void copyFrom( const CalypFrame& other );
void copyFrom( const CalypFrame* other );
/**
* Copy a region from a reference corresponding to the size
* of the size of the current frame
* @param other frame to be copied
* @param x x position on the reference frame
* @param y y position on the reference frame
*/
* Copy a region from a reference corresponding to the size
* of the size of the current frame
* @param other frame to be copied
* @param x x position on the reference frame
* @param y y position on the reference frame
*/
void copyFrom( const CalypFrame& other, unsigned x, unsigned y );
void copyFrom( const CalypFrame* other, unsigned x, unsigned y );
/**
* Copy a reference frame to a specific location on the current frame
* The whole reference frame is copied
* @param other frame to be copied
* @param x x position on the current frame
* @param y y position on the current frame
*/
* Copy a reference frame to a specific location on the current frame
* The whole reference frame is copied
* @param other frame to be copied
* @param x x position on the current frame
* @param y y position on the current frame
*/
void copyTo( const CalypFrame& other, unsigned x, unsigned y ) const;
void copyTo( const CalypFrame* other, unsigned x, unsigned y ) const;
void frameFromBuffer( const std::vector<ClpByte>&, int, unsigned long );
void frameFromBuffer( const std::vector<ClpByte>&, int );
void frameToBuffer( std::vector<ClpByte>&, int ) const;
void frameFromBuffer( std::span<const ClpByte>, int iEndianness, std::uint64_t uiBuffSize );
void frameFromBuffer( std::span<const ClpByte>, int iEndianness );
void frameToBuffer( std::span<ClpByte>, int iEndianness ) const;
void fillRGBBuffer( std::optional<std::size_t> channel ) const;
void fillRGBBuffer() const;
/**
* Histogram
*/
* Histogram
*/
enum HistogramChannels
{
HIST_CHAN_ONE = 0,
@@ -497,32 +522,32 @@ public:
};
void calcHistogram();
unsigned int getMinimumPelValue( unsigned channel );
unsigned int getMaximumPelValue( unsigned channel );
auto getMinimumPelValue( unsigned channel ) const -> unsigned int;
auto getMaximumPelValue( unsigned channel ) const -> unsigned int;
unsigned int getMaximum( unsigned channel );
unsigned int getNumPixelsRange( unsigned channel, unsigned int start, unsigned int end );
double getMean( unsigned channel, unsigned int start, unsigned int end );
int getMedian( unsigned channel, unsigned int start, unsigned int end );
double getStdDev( unsigned channel, unsigned int start, unsigned int end );
double getHistogramValue( unsigned channel, unsigned int bin );
unsigned int getNEBins( unsigned channel );
int getNumHistogramSegment();
double getEntropy( unsigned channel, unsigned int start, unsigned int end );
auto getMaximum( unsigned channel ) const -> unsigned int;
auto getNumPixelsRange( unsigned channel, unsigned int start, unsigned int end ) const -> unsigned int;
auto getMean( unsigned channel, unsigned int start, unsigned int end ) const -> double;
auto getMedian( unsigned channel, unsigned int start, unsigned int end ) const -> int;
auto getStdDev( unsigned channel, unsigned int start, unsigned int end ) const -> double;
auto getHistogramValue( unsigned channel, unsigned int bin ) const -> double;
auto getNEBins( unsigned channel ) const -> unsigned int;
auto getNumHistogramSegment() const -> int;
auto getEntropy( unsigned channel, unsigned int start, unsigned int end ) const -> double;
/**
* interface with OpenCV lib
*/
bool toMat( cv::Mat& cvMat, bool convertToGray = false, bool scale = true, unsigned channel = 0 ) const;
bool fromMat( cv::Mat& cvMat, int iChannel = -1 );
* interface with OpenCV lib
*/
auto toMat( cv::Mat& cvMat, bool convertToGray = false, bool scale = true, unsigned channel = 0 ) const -> bool;
auto fromMat( cv::Mat& cvMat, int iChannel = -1 ) -> bool;
/**
* \ingroup CalypFrameGrp
* @defgroup CalypFrameQualityMetricsGrp Calyp Frame Quality Metrics interface
* @{
* Quality metrics interface
*
*/
* \ingroup CalypFrameGrp
* @defgroup CalypFrameQualityMetricsGrp Calyp Frame Quality Metrics interface
* @{
* Quality metrics interface
*
*/
enum QualityMetrics
{
@@ -534,18 +559,18 @@ public:
NUMBER_METRICS,
};
static std::vector<std::string> supportedQualityMetricsList();
static std::vector<std::string> supportedQualityMetricsUnitsList();
double getQuality( int Metric, CalypFrame* Org, unsigned int component );
double getMSE( CalypFrame* Org, unsigned int component );
double getPSNR( CalypFrame* Org, unsigned int component );
double getSSIM( CalypFrame* Org, unsigned int component );
double getWSPNR( CalypFrame* Org, unsigned int component );
static auto supportedQualityMetricsList() -> std::vector<std::string>;
static auto supportedQualityMetricsUnitsList() -> std::vector<std::string>;
auto getQuality( int metric, CalypFrame* org, unsigned int component ) -> double;
auto getMSE( CalypFrame* org, unsigned int component ) -> double;
auto getPSNR( CalypFrame* org, unsigned int component ) -> double;
auto getSSIM( CalypFrame* org, unsigned int component ) -> double;
auto getWSPNR( CalypFrame* org, unsigned int component ) -> double;
/** @} */
private:
class CalypFramePrivate;
std::unique_ptr<CalypFramePrivate> d;
struct CalypFramePrivate;
std::unique_ptr<CalypFramePrivate> m_d;
};
#endif // __CALYPFRAME_H__
@@ -24,11 +24,17 @@
#include "CalypModuleIf.h"
// OpenCV
#include "CalypFrame.h"
#include "PixelFormats.h"
#include "config.h"
#ifdef USE_OPENCV
#include <opencv2/opencv.hpp>
#endif
bool CalypOpenCVModuleIf::create( std::vector<CalypFrame*> apcFrameList )
{
#ifdef USE_OPENCV
_BASIC_MODULE_API_2_CHECK_
bool bRet = false;
std::vector<Mat> acMatList( apcFrameList.size() );
@@ -39,7 +45,7 @@ bool CalypOpenCVModuleIf::create( std::vector<CalypFrame*> apcFrameList )
Mat* outputMat = create_using_opencv( acMatList );
if( outputMat )
{
unsigned pelFormat = m_bConvertToGray ? CalypFrame::findPixelFormat( "GRAY" ) : apcFrameList[0]->getPelFormat();
auto pelFormat = m_bConvertToGray ? ClpPixelFormats::Gray : apcFrameList[0]->getPelFormat();
m_pcOutputFrame = std::make_unique<CalypFrame>( outputMat->cols, outputMat->rows, pelFormat, apcFrameList[0]->getBitsPel() );
bRet = true;
}
@@ -48,10 +54,14 @@ bool CalypOpenCVModuleIf::create( std::vector<CalypFrame*> apcFrameList )
return false;
}
return bRet;
#else
return false;
#endif
}
CalypFrame* CalypOpenCVModuleIf::process( std::vector<CalypFrame*> apcFrameList )
{
#ifdef USE_OPENCV
m_pcOutputFrame->reset();
std::vector<Mat> acMatList( apcFrameList.size() );
for( unsigned i = 0; i < apcFrameList.size(); i++ )
@@ -61,8 +71,35 @@ CalypFrame* CalypOpenCVModuleIf::process( std::vector<CalypFrame*> apcFrameList
Mat* cvOutput = process_using_opencv( acMatList );
m_pcOutputFrame->fromMat( *cvOutput );
return m_pcOutputFrame.get();
#else
return nullptr;
#endif
}
void CalypOpenCVModuleIf::destroy()
{
}
ClpModuleFeature operator|( ClpModuleFeature lhs, ClpModuleFeature rhs )
{
return static_cast<ClpModuleFeature>(
static_cast<std::underlying_type_t<ClpModuleFeature>>( lhs ) |
static_cast<std::underlying_type_t<ClpModuleFeature>>( rhs ) );
}
ClpModuleFeature operator&( ClpModuleFeature lhs, ClpModuleFeature rhs )
{
return static_cast<ClpModuleFeature>(
static_cast<std::underlying_type_t<ClpModuleFeature>>( lhs ) &
static_cast<std::underlying_type_t<ClpModuleFeature>>( rhs ) );
}
auto CalypModuleIf::getModuleLongName() -> const char*
{
return m_pchModuleLongName ? m_pchModuleLongName : m_pchModuleName;
}
auto CalypModuleIf::has( ClpModuleFeature feature ) -> bool
{
return ( m_uiModuleRequirements & feature ) != ClpModuleFeature::None;
}
+58 -60
View File
@@ -40,18 +40,6 @@
#include "CalypFrame.h"
#include "CalypOptions.h"
#define REGISTER_CLASS_MAKER( X ) \
extern "C" CalypModulePtr Maker() { return std::make_unique<X>(); }
#define REGISTER_CLASS_FACTORY( X ) \
public: \
X( const X& buffer ) \
noexcept = delete; \
X( X&& buffer ) \
noexcept = delete; \
auto operator=( const X& buffer )->X& = delete; \
auto operator=( X&& buffer ) noexcept->X& = delete; \
static CalypModulePtr Create() { return std::make_unique<X>(); }
#define _BASIC_MODULE_API_2_CHECK_ \
if( apcFrameList.size() != m_uiNumberOfFrames ) \
return false; \
@@ -71,8 +59,9 @@ public: \
*/
enum Module_API_Version
{
CLP_MODULE_API_1,
CLP_MODULE_API_2,
CLP_MODULE_API_INVALID = -1,
CLP_MODULE_API_1 = 0,
CLP_MODULE_API_2 = 1,
CLP_MODULE_API_3,
};
@@ -81,12 +70,11 @@ enum Module_API_Version
* Type of module
* @see m_iModuleType
*/
enum Module_Type
enum class ClpModuleType : std::uint8_t
{
CLP_INVALID_MODULE = -1,
CLP_FRAME_PROCESSING_MODULE = 0,
CLP_FRAME_MEASUREMENT_MODULE = 1,
CLP_MODULE_TYPE_MAX = 255,
Invalid,
FrameProcessing,
FrameMeasurement,
};
/** Module_Features Enum
@@ -94,18 +82,19 @@ enum Module_Type
* Features/Requirements of a module
* @see m_uiModuleRequirements
*/
enum Module_Features
enum class ClpModuleFeature : std::uint64_t
{
CLP_MODULE_REQUIRES_NOTHING = 0,
CLP_MODULE_REQUIRES_SKIP_WHILE_PLAY = 1,
CLP_MODULE_REQUIRES_OPTIONS = 2,
CLP_MODULE_REQUIRES_NEW_WINDOW = 4,
CLP_MODULE_USES_KEYS = 8,
CLP_MODULES_VARIABLE_NUM_FRAMES = 16,
CLP_MODULES_HAS_INFO = 32,
CLP_MODULE_REQURES_MAX = 1024,
None = 0,
SkipWhilePlaying = 1,
Options = 2,
NewWindow = 4,
KeysShortcuts = 8,
VariableNumOfFrames = 16,
HasInfo = 32,
};
auto operator|( ClpModuleFeature lhs, ClpModuleFeature rhs ) -> ClpModuleFeature;
enum Module_Key_Supported
{
MODULE_KEY_LEFT,
@@ -114,6 +103,8 @@ enum Module_Key_Supported
MODULE_KEY_DOWN,
};
class CalypFrame;
/**
* \class CalypModuleIf
* \ingroup CalypLib Calyp_Modules
@@ -122,31 +113,17 @@ enum Module_Key_Supported
class CalypModuleIf
{
public:
int m_iModuleAPI{ CLP_MODULE_API_1 };
int m_iModuleType{ CLP_INVALID_MODULE };
const char* m_pchModuleCategory{ "" };
const char* m_pchModuleName{ "" };
const char* m_pchModuleTooltip{ "" };
const char* m_pchModuleLongName{ "" };
//! Number of frames
unsigned int m_uiNumberOfFrames{ 1 };
//! Features/Requirements
unsigned int m_uiModuleRequirements{ CLP_MODULE_REQUIRES_NOTHING };
unsigned int m_iFrameBufferCount{ 0 };
//CalypFrame* m_pcOutputFrame;
CalypOptions m_cModuleOptions;
CalypModuleIf() = default;
virtual ~CalypModuleIf() {}
virtual void destroy() = 0;
CalypModuleIf( const CalypModuleIf& buffer ) noexcept = delete;
CalypModuleIf( CalypModuleIf&& buffer ) noexcept = delete;
auto operator=( const CalypModuleIf& buffer ) -> CalypModuleIf& = delete;
auto operator=( CalypModuleIf&& buffer ) noexcept -> CalypModuleIf& = delete;
const char* getModuleLongName()
{
return m_pchModuleLongName ? m_pchModuleLongName : m_pchModuleName;
}
virtual ~CalypModuleIf() = default;
virtual void destroy(){};
auto getModuleLongName() -> const char*;
auto has( ClpModuleFeature feature ) -> bool;
/**
* Module API version 1
@@ -172,6 +149,23 @@ public:
m_iFrameBufferCount = 0;
return true;
};
public:
int m_iModuleAPI{ CLP_MODULE_API_1 };
ClpModuleType m_iModuleType{ ClpModuleType::Invalid };
const char* m_pchModuleCategory{ "" };
const char* m_pchModuleName{ "" };
const char* m_pchModuleTooltip{ "" };
const char* m_pchModuleLongName{ nullptr };
//! Number of frames
unsigned int m_uiNumberOfFrames{ 1 };
//! Features/Requirements
ClpModuleFeature m_uiModuleRequirements{ ClpModuleFeature::None };
unsigned int m_iFrameBufferCount{ 0 };
CalypOptions m_cModuleOptions;
};
namespace cv
@@ -188,16 +182,8 @@ class CalypOpenCVModuleIf : public CalypModuleIf
{
using Mat = cv::Mat;
protected:
//const char* m_pchPythonFunctionName;
std::unique_ptr<CalypFrame> m_pcOutputFrame;
bool m_bConvertToGray;
public:
CalypOpenCVModuleIf()
{
m_bConvertToGray = false;
};
CalypOpenCVModuleIf() = default;
virtual ~CalypOpenCVModuleIf() {}
// Common API
@@ -209,8 +195,20 @@ public:
virtual cv::Mat* create_using_opencv( const std::vector<Mat>& apcFrameList ) { return nullptr; };
virtual Mat* process_using_opencv( const std::vector<Mat>& apcFrameList ) = 0;
virtual void destroy_using_opencv(){};
protected:
// const char* m_pchPythonFunctionName;
std::unique_ptr<CalypFrame> m_pcOutputFrame;
bool m_bConvertToGray{ false };
};
using CalypModulePtr = std::unique_ptr<CalypModuleIf>;
template <typename T>
class CalypModuleInstance
{
public:
static CalypModulePtr Create() { return std::make_unique<T>(); }
};
#endif // __CALYPMODULESIF_H__
+127 -133
View File
@@ -38,46 +38,47 @@
#include "CalypOptions.h"
#include <cstring>
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>
#include "config.h"
#include "lib/CalypFrame.h"
#include "lib/CalypModuleIf.h"
using namespace std;
struct ParseFailure : public std::exception
{
std::string arg;
std::string val;
ParseFailure( std::string arg0, std::string val0 ) throw()
: arg( arg0 ), val( val0 ) {}
: arg{ std::move( arg0 ) }, val{ std::move( val0 ) } {}
ParseFailure( ParseFailure&& other ) noexcept = delete;
ParseFailure& operator=( ParseFailure&& other ) noexcept = delete;
ParseFailure( const ParseFailure& other ) = delete;
ParseFailure& operator=( const ParseFailure& other ) = delete;
~ParseFailure() throw() {}
const char* what() const throw() { return "Option Parse Failure"; }
const char* what() const throw() override { return "Option Parse Failure"; }
};
/** Type specific option storage */
class boolOption : public OptionBase
class boolOption : public CalypOptions::OptionBase
{
public:
boolOption( const std::string& name, const std::string& desc )
: OptionBase( name, desc, "(1-0)" ) { is_binary = true; }
void parse( const std::string& arg ) { arg_count++; }
: CalypOptions::OptionBase( name, desc, "(1-0)" ) { is_binary = true; }
void parse( const std::string& arg ) override { arg_count++; }
};
/** Type specific option storage */
template <typename T>
class StandardOption : public OptionBase
class StandardOption : public CalypOptions::OptionBase
{
public:
StandardOption( const std::string& name, T& storage, const std::string& desc, const std::string& def )
: OptionBase( name, desc, def ), opt_storage( storage )
{
is_binary = false;
}
: CalypOptions::OptionBase( name, desc, def ), opt_storage( storage ) {}
void parse( const std::string& arg );
void parse( const std::string& arg ) override;
T& opt_storage;
std::vector<T> opt_storage_array;
};
@@ -105,7 +106,7 @@ inline void StandardOption<T>::parse( const std::string& arg )
template <>
inline void StandardOption<std::vector<unsigned int>>::parse( const std::string& arg )
{
unsigned int aux_opt_storage;
unsigned int aux_opt_storage{ 0 };
std::istringstream arg_ss( arg, std::istringstream::in );
arg_ss.exceptions( std::ios::failbit );
try
@@ -123,7 +124,7 @@ inline void StandardOption<std::vector<unsigned int>>::parse( const std::string&
template <>
inline void StandardOption<std::vector<int>>::parse( const std::string& arg )
{
int aux_opt_storage;
int aux_opt_storage{ 0 };
std::istringstream arg_ss( arg, std::istringstream::in );
arg_ss.exceptions( std::ios::failbit );
try
@@ -155,26 +156,26 @@ inline void StandardOption<std::vector<std::string>>::parse( const std::string&
}
/** Option class for argument handling using a user provided function */
struct FunctionOption : public OptionBase
struct FunctionOption : public CalypOptions::OptionBase
{
public:
typedef void( Func )( CalypOptions&, const std::string& );
using OptFunc = std::function<void( CalypOptions&, const std::string& )>;
FunctionOption( const std::string& name, CalypOptions& parent_, Func* func_, const std::string& desc, const std::string& def )
: OptionBase( name, desc, def ), parent( parent_ ), func( func_ )
public:
FunctionOption( const std::string& name, CalypOptions& parent, OptFunc func, const std::string& desc, const std::string& def )
: CalypOptions::OptionBase( name, desc, def ), m_parent( parent ), m_func( func )
{
is_binary = false;
}
void parse( const std::string& arg )
void parse( const std::string& arg ) override
{
func( parent, arg );
m_func( m_parent, arg );
arg_count++;
}
private:
CalypOptions& parent;
void ( *func )( CalypOptions&, const std::string& );
CalypOptions& m_parent;
OptFunc m_func;
};
/* Helper method to initiate adding options to Options */
@@ -187,7 +188,13 @@ private:
*/
CalypOptions& CalypOptions::operator()( const std::string& name, const std::string& desc )
{
addOption( new boolOption( name, desc ) );
addOptionInternal( std::make_unique<boolOption>( name, desc ) );
return *this;
}
CalypOptions& CalypOptions::addOption( const std::string& name, const std::string& desc )
{
addOptionInternal( std::make_unique<boolOption>( name, desc ) );
return *this;
}
@@ -199,14 +206,27 @@ CalypOptions& CalypOptions::operator()( const std::string& name, const std::stri
template <typename T>
CalypOptions& CalypOptions::operator()( const std::string& name, T& storage, const std::string& desc )
{
addOption( new StandardOption<T>( name, storage, desc, std::string( "" ) ) );
addOptionInternal( std::make_unique<StandardOption<T>>( name, storage, desc, std::string( "" ) ) );
return *this;
}
template <typename T>
CalypOptions& CalypOptions::addOption( const std::string& name, T& storage, const std::string& desc )
{
addOptionInternal( std::make_unique<StandardOption<T>>( name, storage, desc, std::string( "" ) ) );
return *this;
}
template <typename T>
CalypOptions& CalypOptions::operator()( const std::string& name, T& storage, const std::string& desc, const std::string& defaults )
{
addOption( new StandardOption<T>( name, storage, desc ) );
addOptionInternal( std::make_unique<StandardOption<T>>( name, storage, desc ) );
return *this;
}
template <typename T>
CalypOptions& CalypOptions::addOption( const std::string& name, T& storage, const std::string& desc, const std::string& defaults )
{
addOptionInternal( std::make_unique<StandardOption<T>>( name, storage, desc ) );
return *this;
}
@@ -223,53 +243,35 @@ template CalypOptions& CalypOptions::operator()( const std::string& name, std::v
template CalypOptions& CalypOptions::operator()( const std::string& name, std::vector<std::string>& storage,
const std::string& desc );
CalypOptions::Option::Option()
: opt( 0 ) {}
CalypOptions::Option::~Option()
CalypOptions::CalypOptions( std::string name )
: m_cOptionGroupName{ std::move( name ) }
{
if( opt )
delete opt;
}
CalypOptions::CalypOptions( const std::string& name )
{
m_cOptionGroupName = name;
m_bAllowUnkonw = true;
}
CalypOptions::~CalypOptions()
{
for( CalypOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ )
{
delete *it;
}
}
OptionBase* CalypOptions::operator[]( const std::string& optName )
CalypOptions::OptionBase* CalypOptions::operator[]( const std::string& optName )
{
return getOption( optName );
}
OptionBase* CalypOptions::getOption( const std::string& optName )
CalypOptions::OptionBase* CalypOptions::getOption( const std::string& optName )
{
CalypOptions::OptionMap::iterator opt_it;
std::map<std::string, std::list<Option*>>::iterator opt_it;
opt_it = opt_short_map.find( optName );
if( opt_it != opt_short_map.end() )
{
OptionsList opt_list = ( *opt_it ).second;
for( CalypOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it )
auto opt_list = ( *opt_it ).second;
for( auto& option : opt_list )
{
return ( *it )->opt;
return option->base_opt.get();
}
}
opt_it = opt_long_map.find( optName );
if( opt_it != opt_long_map.end() )
{
OptionsList opt_list = ( *opt_it ).second;
for( CalypOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it )
auto opt_list = ( *opt_it ).second;
for( auto& option : opt_list )
{
return ( *it )->opt;
return option->base_opt.get();
}
}
return NULL;
@@ -281,30 +283,20 @@ bool CalypOptions::hasOpt( const std::string& optName )
return opt ? opt->count() > 0 ? true : false : false;
}
void CalypOptions::addDefaultOptions()
{
addOptions() /**/
( "help", "produce help message" ) /**/
( "version", "show version and exit" ) /**/
( "pel_fmts", "list pixel formats" ) /**/
( "quality_metrics", "list supported quality metrics" ) /**/
( "module_list", "list supported modules" ) /**/
( "module_list_full", "detailed list supported modules" );
}
CalypOptions& CalypOptions::addOptions()
{
return *this;
}
void CalypOptions::addOption( OptionBase* opt )
void CalypOptions::addOptionInternal( std::unique_ptr<OptionBase> opt )
{
Option* names = new Option();
names->opt = opt;
string& opt_string = opt->opt_string;
auto names = std::make_unique<Option>();
names->base_opt = std::move( opt );
opt = nullptr;
const std::string& opt_string = names->base_opt->opt_string;
size_t opt_start = 0;
for( size_t opt_end = 0; opt_end != string::npos; )
for( size_t opt_end = 0; opt_end != std::string::npos; )
{
opt_end = opt_string.find_first_of( ',', opt_start );
bool force_short = 0;
@@ -313,36 +305,37 @@ void CalypOptions::addOption( OptionBase* opt )
opt_start++;
force_short = 1;
}
string opt_name = opt_string.substr( opt_start, opt_end - opt_start );
std::string opt_name = opt_string.substr( opt_start, opt_end - opt_start );
if( force_short || opt_name.size() == 1 )
{
names->opt_short.push_back( opt_name );
opt_short_map[opt_name].push_back( names );
opt_short_map[opt_name].push_back( names.get() );
}
else
{
names->opt_long.push_back( opt_name );
opt_long_map[opt_name].push_back( names );
opt_long_map[opt_name].push_back( names.get() );
}
opt_start += opt_end + 1;
}
opt_list.push_back( names );
opt_list.push_back( std::move( names ) );
}
static void setOptions( CalypOptions::OptionsList& opt_list, const string& value )
static void setOptions( std::list<CalypOptions::Option*>& opt_list, const std::string& value )
{
/* multiple options may be registered for the same name:
* allow each to parse value */
for( CalypOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); ++it )
* allow each to parse value
*/
for( auto& option : opt_list )
{
( *it )->opt->parse( value );
option->base_opt->parse( value );
}
}
bool CalypOptions::storePair( bool allow_long, bool allow_short, const string& name, const string& value )
bool CalypOptions::storePair( bool allow_long, bool allow_short, const std::string& name, const std::string& value )
{
bool found = false;
CalypOptions::OptionMap::iterator opt_it;
std::map<std::string, std::list<Option*>>::iterator opt_it;
if( allow_long )
{
opt_it = opt_long_map.find( name );
@@ -367,7 +360,7 @@ bool CalypOptions::storePair( bool allow_long, bool allow_short, const string& n
if( !m_bAllowUnkonw )
{
/* not found */
cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << endl;
std::cerr << "Unknown option: `" << name << "' (value:`" << value << "')" << std::endl;
}
return false;
}
@@ -376,7 +369,7 @@ bool CalypOptions::storePair( bool allow_long, bool allow_short, const string& n
return true;
}
bool CalypOptions::storePair( const string& name, const string& value )
bool CalypOptions::storePair( const std::string& name, const std::string& value )
{
return storePair( true, true, name, value );
}
@@ -384,19 +377,19 @@ bool CalypOptions::storePair( const string& name, const string& value )
/**
* returns number of extra arguments consumed
*/
unsigned int CalypOptions::parseLONG( unsigned int argc, char* argv[] )
unsigned int CalypOptions::parseLONG( unsigned int argc, char* argv[] ) // NOLINT
{
/* gnu style long options can take the forms:
* --option=arg
* --option arg
*/
string arg( argv[0] );
size_t arg_opt_start = arg.find_first_not_of( '-' );
size_t arg_opt_sep = arg.find_first_of( '=' );
string option = arg.substr( arg_opt_start, arg_opt_sep - arg_opt_start );
std::string arg( argv[0] );
std::size_t arg_opt_start = arg.find_first_not_of( '-' );
std::size_t arg_opt_sep = arg.find_first_of( '=' );
std::string option = arg.substr( arg_opt_start, arg_opt_sep - arg_opt_start );
unsigned int extra_argc_consumed = 0;
if( arg_opt_sep == string::npos )
if( arg_opt_sep == std::string::npos )
{
/* no argument found => argument in argv[1] (maybe) */
/* xxx, need to handle case where option isn't required */
@@ -416,7 +409,7 @@ unsigned int CalypOptions::parseLONG( unsigned int argc, char* argv[] )
else
{
/* argument occurs after option_sep */
string val = arg.substr( arg_opt_sep + 1 );
std::string val = arg.substr( arg_opt_sep + 1 );
storePair( true, false, option, val );
}
return extra_argc_consumed;
@@ -425,7 +418,7 @@ unsigned int CalypOptions::parseLONG( unsigned int argc, char* argv[] )
/**
* returns number of extra arguments consumed
*/
unsigned int CalypOptions::parseLONG( string arg )
unsigned int CalypOptions::parseLONG( const std::string& arg )
{
/* gnu style long options can take the forms:
* --option=arg
@@ -433,10 +426,10 @@ unsigned int CalypOptions::parseLONG( string arg )
*/
size_t arg_opt_start = arg.find_first_not_of( '-' );
size_t arg_opt_sep = arg.find_first_of( '=' );
string option = arg.substr( arg_opt_start, arg_opt_sep - arg_opt_start );
std::string option = arg.substr( arg_opt_start, arg_opt_sep - arg_opt_start );
unsigned int extra_argc_consumed = 0;
if( arg_opt_sep == string::npos )
if( arg_opt_sep == std::string::npos )
{
/* no argument found => argument in argv[1] (maybe) */
/* xxx, need to handle case where option isn't required */
@@ -448,36 +441,36 @@ unsigned int CalypOptions::parseLONG( string arg )
else
{
/* argument occurs after option_sep */
string val = arg.substr( arg_opt_sep + 1 );
std::string val = arg.substr( arg_opt_sep + 1 );
storePair( true, false, option, val );
}
return extra_argc_consumed;
}
unsigned int CalypOptions::parseSHORT( unsigned int argc, char* argv[] )
unsigned int CalypOptions::parseSHORT( unsigned int argc, char* argv[] ) // NOLINT
{
/* short options can take the forms:
* --option arg
* -option arg
*/
string arg( argv[0] );
size_t arg_opt_start = arg.find_first_not_of( '-' );
string option = arg.substr( arg_opt_start );
std::string arg( argv[0] );
std::size_t arg_opt_start = arg.find_first_not_of( '-' );
std::string option = arg.substr( arg_opt_start );
/* lookup option */
/* argument in argv[1] */
/* xxx, need to handle case where option isn't required */
if( argc == 1 )
{
cerr << "Not processing option without argument `" << option << "'" << endl;
std::cerr << "Not processing option without argument `" << option << "'" << std::endl;
return 0; /* run out of argv for argument */
}
storePair( false, true, option, string( argv[1] ) );
storePair( false, true, option, std::string( argv[1] ) );
return 1;
}
int CalypOptions::parse( unsigned int argc, char* argv[] )
int CalypOptions::parse( unsigned int argc, char* argv[] ) // NOLINT
{
try
{
@@ -499,10 +492,11 @@ int CalypOptions::parse( unsigned int argc, char* argv[] )
return 0;
}
list<const char*> CalypOptions::scanArgv( unsigned int argc, char* argv[] )
// NOLINTNEXTLINE(*-avoid-c-arrays)
std::list<const char*> CalypOptions::scanArgv( unsigned int argc, char* argv[] )
{
/* a list for anything that didn't get handled as an option */
list<const char*> non_option_arguments;
std::list<const char*> non_option_arguments;
for( unsigned int i = 1; i < argc; i++ )
{
@@ -560,13 +554,13 @@ static const char spaces[41] = " ";
* using the formatting: "-x, --long",
* if a short/long option isn't specified, it is not printed
*/
static void doHelpOpt( ostream& out, const CalypOptions::Option& entry, unsigned int pad_short = 0 )
static void doHelpOpt( std::ostream& out, const CalypOptions::Option& entry, unsigned int pad_short = 0 )
{
pad_short = min( pad_short, 8u );
pad_short = std::min( pad_short, 8u );
if( !entry.opt_short.empty() )
{
unsigned int pad = max( (int)pad_short - (int)entry.opt_short.front().size(), 0 );
unsigned int pad = std::max( (int)pad_short - (int)entry.opt_short.front().size(), 0 );
out << "-" << entry.opt_short.front();
if( !entry.opt_long.empty() )
{
@@ -587,19 +581,19 @@ static void doHelpOpt( ostream& out, const CalypOptions::Option& entry, unsigned
}
/* format the help text */
void CalypOptions::doHelp( ostream& out, unsigned int columns )
void CalypOptions::doHelp( std::ostream& out, unsigned int columns )
{
const unsigned int pad_short = 3;
/* first pass: work out the longest option name */
unsigned int max_width = 0;
for( CalypOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ )
for( auto& opt : opt_list )
{
ostringstream line( ios_base::out );
doHelpOpt( line, **it, pad_short );
max_width = max( max_width, (unsigned int)line.tellp() );
std::ostringstream line( std::ios_base::out );
doHelpOpt( line, *opt, pad_short );
max_width = std::max( max_width, (unsigned int)line.tellp() );
}
unsigned int opt_width = min( max_width + 2, 28u + pad_short ) + 2;
unsigned int opt_width = std::min( max_width + 2, 28u + pad_short ) + 2;
unsigned int desc_width = columns - opt_width;
/* second pass: write out formatted option and help text.
@@ -607,17 +601,17 @@ void CalypOptions::doHelp( ostream& out, unsigned int columns )
* - if the option text is longer than opt_width, place the help
* text at opt_width on the next line.
*/
for( CalypOptions::OptionsList::iterator it = opt_list.begin(); it != opt_list.end(); it++ )
for( auto& opt : opt_list )
{
ostringstream line( ios_base::out );
std::ostringstream line( std::ios_base::out );
line << " ";
doHelpOpt( line, **it, pad_short );
doHelpOpt( line, *opt, pad_short );
const string& opt_desc = ( *it )->opt->opt_desc;
const std::string& opt_desc = opt->base_opt->opt_desc;
if( opt_desc.empty() )
{
/* no help text: output option, skip further processing */
cout << line.str() << endl;
std::cout << line.str() << std::endl;
continue;
}
size_t currlength = size_t( line.tellp() );
@@ -625,17 +619,17 @@ void CalypOptions::doHelp( ostream& out, unsigned int columns )
{
/* if option text is too long (and would collide with the
* help text, split onto next line */
line << endl;
line << std::endl;
currlength = 0;
}
/* split up the help text, taking into account new lines,
* (add opt_width of padding to each new line) */
for( size_t newline_pos = 0, cur_pos = 0; cur_pos != string::npos; currlength = 0 )
for( std::size_t newline_pos = 0, cur_pos = 0; cur_pos != std::string::npos; currlength = 0 )
{
/* print any required padding space for vertical alignment */
line << &( spaces[40 - opt_width + currlength] );
newline_pos = opt_desc.find_first_of( '\n', newline_pos );
if( newline_pos != string::npos )
if( newline_pos != std::string::npos )
{
/* newline found, print substring (newline needn't be stripped) */
newline_pos++;
@@ -652,14 +646,14 @@ void CalypOptions::doHelp( ostream& out, unsigned int columns )
/* find a suitable point to split text (avoid spliting in middle of word)
*/
size_t split_pos = opt_desc.find_last_of( ' ', cur_pos + desc_width );
if( split_pos != string::npos )
if( split_pos != std::string::npos )
{
/* eat up multiple space characters */
split_pos = opt_desc.find_last_not_of( ' ', split_pos ) + 1;
}
/* bad split if no suitable space to split at. fall back to width */
bool bad_split = split_pos == string::npos || split_pos <= cur_pos;
bool bad_split = split_pos == std::string::npos || split_pos <= cur_pos;
if( bad_split )
{
split_pos = cur_pos + desc_width;
@@ -677,10 +671,9 @@ void CalypOptions::doHelp( ostream& out, unsigned int columns )
{
break;
}
line << endl;
line << std::endl;
}
cout << line.str() << endl;
std::cout << line.str() << std::endl;
}
}
@@ -690,24 +683,25 @@ bool CalypOptions::checkListingOpts()
if( hasOpt( "version" ) )
{
std::cout << "Calyp version " << CALYP_VERSION_STRING << "\n";
std::cout << "Calyp version" << CALYP_VERSION_STRING << std::endl;
bRet |= true;
}
if( hasOpt( "pel_fmts" ) )
{
printf( "Calyp supported pixel formats: \n" );
for( unsigned int i = 0; i < CalypFrame::supportedPixelFormatListNames().size(); i++ )
std::cout << "Calyp supported pixel formats:" << std::endl;
const auto& fmt_list = CalypFrame::supportedPixelFormatListNames();
for( const auto& [key, name] : fmt_list )
{
printf( " %s\n", CalypFrame::supportedPixelFormatListNames()[i].c_str() );
std::cout << " " << name << std::endl;
}
bRet |= true;
}
if( hasOpt( "quality_metrics" ) )
{
printf( "Calyp supported quality metrics: \n" );
std::cout << "Calyp supported quality metrics:" << std::endl;
for( unsigned int i = 0; i < CalypFrame::supportedQualityMetricsList().size(); i++ )
{
printf( " %s\n", CalypFrame::supportedQualityMetricsList()[i].c_str() );
std::cout << " " << CalypFrame::supportedQualityMetricsList()[i] << std::endl;
}
bRet |= true;
}
+53 -48
View File
@@ -42,34 +42,10 @@
#include <list>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "CalypDefs.h"
/**
* \class OptionBase
* \ingroup CalypLibGrp
* \brief Virtual base class for storing information relating to a
* specific option This base class describes common elements.
* Type specific information should be stored in a derived class.
*/
class OptionBase
{
public:
OptionBase( const std::string& name, const std::string& desc, const std::string& def )
: arg_count( 0 ), opt_string( name ), opt_desc( desc ), opt_defaults( def ) {}
virtual ~OptionBase() {}
/* parse argument arg, to obtain a value for the option */
virtual void parse( const std::string& arg ) = 0;
int count() { return arg_count; }
bool isBinary() { return is_binary; }
int arg_count;
std::string opt_string;
std::string opt_desc;
std::string opt_defaults;
bool is_binary;
};
/**
* \class CalypOptions
* \ingroup CalypLibGrp
@@ -78,34 +54,56 @@ public:
class CalypOptions
{
public:
/**
* Virtual base class for storing information relating to a
* specific option This base class describes common elements.
* Type specific information should be stored in a derived class.
*/
class OptionBase
{
public:
OptionBase( std::string name, std::string desc, std::string def )
: opt_string{ std::move( name ) }, opt_desc{ std::move( desc ) }, opt_defaults{ std::move( def ) } {}
OptionBase( OptionBase&& other ) noexcept = delete;
OptionBase& operator=( OptionBase&& other ) noexcept = delete;
OptionBase( const OptionBase& other ) = delete;
OptionBase& operator=( const OptionBase& other ) = delete;
virtual ~OptionBase() = default;
/* parse argument arg, to obtain a value for the option */
virtual void parse( const std::string& arg ) = 0;
auto count() const -> std::size_t { return arg_count; }
auto isBinary() const -> bool { return is_binary; }
std::string opt_string;
std::string opt_desc;
std::string opt_defaults;
protected:
std::size_t arg_count{ 0 };
bool is_binary{ false };
};
struct Option
{
Option();
~Option();
std::list<std::string> opt_long;
std::list<std::string> opt_short;
OptionBase* opt;
std::unique_ptr<OptionBase> base_opt{ nullptr };
};
typedef std::list<Option*> OptionsList;
CalypOptions( const std::string& name = "" );
~CalypOptions();
CalypOptions() = default;
CalypOptions( std::string name );
int parse( unsigned int argc, char* argv[] );
int parse( unsigned int argc, char* argv[] ); // NOLINT
void parse( std::vector<std::string> args_array );
std::list<const char*>& getUnhandledArgs() { return m_aUnhandledArgs; }
void doHelp( std::ostream& out, unsigned columns = 80 );
OptionBase* operator[]( const std::string& optName );
OptionBase* getOption( const std::string& optName );
CalypOptions::OptionBase* operator[]( const std::string& optName );
CalypOptions::OptionBase* getOption( const std::string& optName );
bool hasOpt( const std::string& optName );
OptionsList getOptionList() { return opt_list; }
void addDefaultOptions();
auto getOptionList() -> const std::list<std::unique_ptr<Option>>& { return opt_list; }
CalypOptions& addOptions();
void addOption( OptionBase* opt );
/**
* Add option described by name to the parent Options list,
@@ -114,6 +112,7 @@ public:
* with desc as an optional help description
*/
CalypOptions& operator()( const std::string& name, const std::string& desc );
CalypOptions& addOption( const std::string& name, const std::string& desc );
/**
* Add option described by name to the parent Options list,
@@ -123,29 +122,35 @@ public:
*/
template <typename T>
CalypOptions& operator()( const std::string& name, T& storage, const std::string& desc );
template <typename T>
CalypOptions& addOption( const std::string& name, T& storage, const std::string& desc );
template <typename T>
CalypOptions& operator()( const std::string& name, T& storage, const std::string& desc, const std::string& defaults );
template <typename T>
CalypOptions& addOption( const std::string& name, T& storage, const std::string& desc, const std::string& defaults );
bool checkListingOpts();
private:
typedef std::map<std::string, OptionsList> OptionMap;
OptionMap opt_long_map;
OptionMap opt_short_map;
void addOptionInternal( std::unique_ptr<OptionBase> opt );
OptionsList opt_list;
private:
std::map<std::string, std::list<Option*>> opt_long_map;
std::map<std::string, std::list<Option*>> opt_short_map;
std::string m_cOptionGroupName;
bool m_bAllowUnkonw;
std::list<std::unique_ptr<Option>> opt_list;
std::string m_cOptionGroupName{ "" };
bool m_bAllowUnkonw{ true };
std::list<const char*> m_aUnhandledArgs;
bool storePair( bool allow_long, bool allow_short, const std::string& name, const std::string& value );
bool storePair( const std::string& name, const std::string& value );
unsigned int parseLONG( unsigned int argc, char* argv[] );
unsigned int parseLONG( std::string arg );
unsigned int parseSHORT( unsigned int argc, char* argv[] );
std::list<const char*> scanArgv( unsigned int argc, char* argv[] );
unsigned int parseLONG( unsigned int argc, char* argv[] ); // NOLINT
unsigned int parseLONG( const std::string& arg );
unsigned int parseSHORT( unsigned int argc, char* argv[] ); // NOLINT
std::list<const char*> scanArgv( unsigned int argc, char* argv[] ); // NOLINT
};
#endif // __CALYPOPTIONS_H__
+101 -145
View File
@@ -22,208 +22,164 @@
* \brief Video Frame handling
*/
#include <memory>
#include <algorithm>
#include <cassert>
#include "CalypFrame.h"
#include "PixelFormats.h"
#include "config.h"
#define MAX_NUMBER_COMPONENTS 4
class CalypPixel::CalypPixelPrivate
namespace
{
public:
CalypPixelPrivate( const int& ColorSpace )
{
iColorSpace = ColorSpace == CLP_COLOR_GRAY ?
CLP_COLOR_YUV :
ColorSpace;
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
PelComp[i] = 0;
}
}
constexpr auto kMinPixelValue{ 0 };
constexpr auto kMaxPixelValue{ 255 };
int iColorSpace;
ClpPel PelComp[MAX_NUMBER_COMPONENTS];
};
static inline void yuvToRgb( const int& iY, const int& iU, const int& iV, int& iR, int& iG, int& iB )
constexpr void yuvToRgb( int iY, int iU, int iV, int& iR, int& iG, int& iB )
{
iR = iY + ( ( 1436 * ( iV - 128 ) ) >> 10 );
iG = iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 );
iB = iY + ( ( 1812 * ( iU - 128 ) ) >> 10 );
iR = iR < 0 ? 0 : iR > 255 ? 255 :
iR;
iG = iG < 0 ? 0 : iG > 255 ? 255 :
iG;
iB = iB < 0 ? 0 : iB > 255 ? 255 :
iB;
iR = std::clamp( iY + ( ( 1436 * ( iV - 128 ) ) >> 10 ), kMinPixelValue, kMaxPixelValue ); // NOLINT
iG = std::clamp( iY - ( ( 352 * ( iU - 128 ) + 731 * ( iV - 128 ) ) >> 10 ), kMinPixelValue,
kMaxPixelValue ); // NOLINT
iB = std::clamp( iY + ( ( 1812 * ( iU - 128 ) ) >> 10 ), kMinPixelValue, kMaxPixelValue ); // NOLINT
}
static inline void rgbToYuv( const int& iR, const int& iG, const int& iB, int& iY, int& iU, int& iV )
constexpr void rgbToYuv( int iR, int iG, int iB, int& iY, int& iU, int& iV )
{
iY = ( 299 * iR + 587 * iG + 114 * iB + 500 ) / 1000;
iU = ( 1000 * ( iB - iY ) + 226816 ) / 1772;
iV = ( 1000 * ( iR - iY ) + 179456 ) / 1402;
iY = ( 299 * iR + 587 * iG + 114 * iB + 500 ) / 1000; // NOLINT
iU = ( 1000 * ( iB - iY ) + 226816 ) / 1772; // NOLINT
iV = ( 1000 * ( iR - iY ) + 179456 ) / 1402; // NOLINT
}
} // namespace
CalypPixel::CalypPixel( int colorSpace, const ClpPel c0 ) : m_colorSpace( colorSpace )
{
m_pelComp[0] = c0;
}
int CalypPixel::getMaxNumberOfComponents()
CalypPixel::CalypPixel( int colorSpace, const ClpPel c0, const ClpPel c1, const ClpPel c2 ) : m_colorSpace( colorSpace )
{
return MAX_NUMBER_COMPONENTS;
m_pelComp[0] = c0;
m_pelComp[1] = c1;
m_pelComp[2] = c2;
}
CalypPixel::CalypPixel( const int& ColorSpace )
: d{ std::make_unique<CalypPixelPrivate>( ColorSpace ) }
CalypPixel::CalypPixel( int colorSpace, const ClpPel c0, const ClpPel c1, const ClpPel c2, const ClpPel c3 )
: m_colorSpace( colorSpace )
{
m_pelComp[0] = c0;
m_pelComp[1] = c1;
m_pelComp[2] = c2;
m_pelComp[3] = c3;
}
CalypPixel::CalypPixel( const int& ColorSpace, const ClpPel& c0 )
: d{ std::make_unique<CalypPixelPrivate>( ColorSpace ) }
auto CalypPixel::operator+=( const CalypPixel& in ) -> CalypPixel&
{
d->PelComp[0] = c0;
}
CalypPixel::CalypPixel( const int& ColorSpace, const ClpPel& c0, const ClpPel& c1, const ClpPel& c2 )
: d{ std::make_unique<CalypPixelPrivate>( ColorSpace ) }
{
d->PelComp[0] = c0;
d->PelComp[1] = c1;
d->PelComp[2] = c2;
}
CalypPixel::CalypPixel( const int& ColorSpace, const ClpPel& c0, const ClpPel& c1, const ClpPel& c2, const ClpPel& c3 )
: d{ std::make_unique<CalypPixelPrivate>( ColorSpace ) }
{
d->PelComp[0] = c0;
d->PelComp[1] = c1;
d->PelComp[2] = c2;
d->PelComp[3] = c3;
}
CalypPixel::CalypPixel( const CalypPixel& other )
: d{ std::make_unique<CalypPixelPrivate>( other.colorSpace() ) }
{
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
d->PelComp[i] = other[i];
}
}
CalypPixel::~CalypPixel() = default;
int CalypPixel::colorSpace() const
{
return d->iColorSpace;
}
ClpPel CalypPixel::operator[]( const int& channel ) const
{
return d->PelComp[channel];
}
ClpPel& CalypPixel::operator[]( const int& channel )
{
return d->PelComp[channel];
}
CalypPixel CalypPixel::operator=( const CalypPixel& other )
{
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
d->PelComp[i] = other[i];
}
assert( in.colorSpace() == m_colorSpace );
const auto& other_comp = in.components();
std::ranges::transform( other_comp, m_pelComp, m_pelComp.begin(), []( auto& lhs, auto& rhs ) { return lhs + rhs; } );
return *this;
}
CalypPixel CalypPixel::operator+( const CalypPixel& in )
auto CalypPixel::operator-=( const CalypPixel& in ) -> CalypPixel&
{
CalypPixel result;
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
result[i] = d->PelComp[i] + in[i];
}
return result;
}
CalypPixel CalypPixel::operator+=( const CalypPixel& in )
{
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
d->PelComp[i] += in[i];
}
assert( in.colorSpace() == m_colorSpace );
const auto& other_comp = in.components();
std::ranges::transform( other_comp, m_pelComp, m_pelComp.begin(), []( auto& lhs, auto& rhs ) { return lhs - rhs; } );
return *this;
}
CalypPixel CalypPixel::operator-( const CalypPixel& in )
auto CalypPixel::operator*=( double op ) -> CalypPixel&
{
CalypPixel result;
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
result[i] = d->PelComp[i] - in[i];
}
return result;
}
CalypPixel CalypPixel::operator-=( const CalypPixel& in )
{
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
d->PelComp[i] -= in[i];
}
std::ranges::transform( m_pelComp, m_pelComp.begin(), [&op]( auto& p1 ) { return p1 * op; } );
return *this;
}
CalypPixel CalypPixel::operator*( const double& op )
auto CalypPixel::operator+( const CalypPixel& in ) const -> CalypPixel
{
CalypPixel result;
for( int i = 0; i < MAX_NUMBER_COMPONENTS; i++ )
{
result[i] = d->PelComp[i] * op;
}
assert( in.colorSpace() == m_colorSpace );
const auto& other_comp = in.components();
CalypPixel result{ m_colorSpace };
std::ranges::transform( other_comp, m_pelComp, result.components().begin(),
[]( auto& lhs, auto& rhs ) { return lhs + rhs; } );
return result;
}
CalypPixel CalypPixel::convertPixel( CalypColorSpace eOutputSpace )
auto CalypPixel::operator-( const CalypPixel& input ) const -> CalypPixel
{
if( d->iColorSpace == eOutputSpace )
return *this;
assert( input.colorSpace() == m_colorSpace );
const auto& other_comp = input.components();
CalypPixel result{ m_colorSpace };
std::ranges::transform( other_comp, m_pelComp, result.components().begin(),
[]( auto& lhs, auto& rhs ) { return lhs - rhs; } );
return result;
}
int outA = 0;
int outB = 0;
int outC = 0;
int outD = 0;
if( d->iColorSpace == CLP_COLOR_YUV )
auto CalypPixel::operator*( double op ) const -> CalypPixel
{
CalypPixel result{ m_colorSpace };
auto& comp = result.components();
std::ranges::transform( comp, comp.begin(), [&op]( auto& p1 ) { return p1 * op; } );
return result;
}
auto CalypPixel::operator==( const CalypPixel& other ) const -> bool
{
return colorSpace() == other.colorSpace() && std::ranges::equal( m_pelComp, other.components() );
}
auto operator<<( std::ostream& stream, const CalypPixel& pixel ) -> std::ostream&
{
// #ifdef CLP_DEBUG
// if( p.colorSpace() == CLP_COLOR_RGB || p.colorSpace() == CLP_COLOR_YUV )
// {
// os << "(" << p[0] << ", " << p[1] << ", " << p[2] << ")";
// }
// else
// {
// os << "(" << p[0] << ", " << p[1] << ", " << p[2] << ", " << p[3] << ")";
// }
// #endif
return stream;
}
auto CalypPixel::convertPixel( CalypColorSpace eOutputSpace ) const -> CalypPixel
{
if( m_colorSpace == eOutputSpace ) return *this;
int outA{ 0 };
int outB{ 0 };
int outC{ 0 };
int outD{ 0 };
if( m_colorSpace == CLP_COLOR_YUV )
{
switch( eOutputSpace )
{
case CLP_COLOR_GRAY:
outA = d->PelComp[0];
outA = m_pelComp[0];
break;
case CLP_COLOR_RGBA:
outD = 255;
outD = kMaxPixelValue;
case CLP_COLOR_RGB:
yuvToRgb( d->PelComp[0], d->PelComp[1], d->PelComp[2], outA, outB, outC );
yuvToRgb( m_pelComp[0], m_pelComp[1], m_pelComp[2], outA, outB, outC );
break;
default:
break;
}
}
if( d->iColorSpace == CLP_COLOR_RGB )
if( m_colorSpace == CLP_COLOR_RGB )
{
switch( eOutputSpace )
{
case CLP_COLOR_GRAY:
rgbToYuv( d->PelComp[0], d->PelComp[1], d->PelComp[2], outA, outB, outC );
rgbToYuv( m_pelComp[0], m_pelComp[1], m_pelComp[2], outA, outB, outC );
case CLP_COLOR_YUV:
rgbToYuv( d->PelComp[0], d->PelComp[1], d->PelComp[2], outA, outB, outC );
rgbToYuv( m_pelComp[0], m_pelComp[1], m_pelComp[2], outA, outB, outC );
break;
case CLP_COLOR_RGBA:
outD = 255;
outD = kMaxPixelValue;
break;
default:
break;
}
}
return CalypPixel( eOutputSpace, outA, outB, outC, outD );
return { eOutputSpace, static_cast<ClpPel>( outA ), static_cast<ClpPel>( outB ), static_cast<ClpPel>( outC ),
static_cast<ClpPel>( outD ) };
}
+221 -197
View File
@@ -30,6 +30,7 @@
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include "CalypFrame.h"
#include "CalypStreamHandlerIf.h"
@@ -48,6 +49,8 @@
constexpr auto kDefaultBitsPerPixel = 8;
constexpr auto kDefaultFrameRate = 30;
auto find_stream_handler( const std::string& strFilename, bool bRead ) -> CalypStreamFormat::CreateStreamHandlerFn;
std::vector<CalypStreamFormat> CalypStream::supportedReadFormats()
{
INI_REGIST_CALYP_SUPPORTED_FMT;
@@ -110,7 +113,8 @@ struct CalypStreamFrameBuffer : std::enable_shared_from_this<CalypStreamFrameBuf
std::vector<std::unique_ptr<CalypFrame>> framePool;
std::size_t bufferIdx{ 0 };
CalypStreamFrameBuffer( std::size_t size, unsigned int width, unsigned int height, int pelFormat, unsigned int bitsPixel, bool hasNegative )
CalypStreamFrameBuffer( std::size_t size, unsigned int width, unsigned int height, ClpPixelFormats pelFormat,
unsigned int bitsPixel, bool hasNegative )
{
framePool.reserve( size );
for( std::size_t i = 0; i < size; i++ )
@@ -133,10 +137,8 @@ struct CalypStreamFrameBuffer : std::enable_shared_from_this<CalypStreamFrameBuf
auto oldSize = framePool.size();
for( std::size_t i = oldSize; i < newSize; i++ )
{
framePool.push_back( std::make_unique<CalypFrame>( framePool[0]->getWidth(),
framePool[0]->getHeight(),
framePool[0]->getPelFormat(),
framePool[0]->getBitsPel(),
framePool.push_back( std::make_unique<CalypFrame>( framePool[0]->getWidth(), framePool[0]->getHeight(),
framePool[0]->getPelFormat(), framePool[0]->getBitsPel(),
framePool[0]->getHasNegativeValues() ) );
}
bufferIdx += newSize - oldSize;
@@ -163,19 +165,14 @@ class CalypStream::CalypStreamPrivate
{
public:
std::recursive_mutex stream_mutex;
CalypStream::Type streamType;
bool isInit;
bool isInput;
CalypStreamHandlerIf* handler;
CreateStreamHandlerFn pfctCreateHandler;
std::unique_ptr<CalypStreamHandlerIf> handler;
std::shared_ptr<CalypStreamFrameBuffer> frameBuffer;
std::deque<std::shared_ptr<CalypFrame>> frameFifo;
// std::vector<std::unique_ptr<CalypFrame>> framePool;
// std::deque<std::shared_ptr<CalypFrame>> frameFifo;
// std::size_t bufferIdx{ 0 };
std::string cFilename;
long long int iCurrFrameNum;
bool bLoadAll;
@@ -187,17 +184,114 @@ public:
CalypStreamPrivate()
{
handler = nullptr;
pfctCreateHandler = nullptr;
isInput = true;
streamType = CalypStream::Type::Input;
isInit = false;
bLoadAll = false;
iCurrFrameNum = -1;
cFilename = "";
}
~CalypStreamPrivate()
~CalypStreamPrivate() { close(); }
bool open( std::string filename, unsigned int width, unsigned int height, ClpPixelFormats input_format,
unsigned int bitsPel, int endianness, bool hasNegative, unsigned int frame_rate, bool forceRaw,
CalypStream::Type type )
{
close();
if( isInit )
{
close();
}
isInit = false;
streamType = type;
bool isInput = streamType == CalypStream::Type::Input;
if( forceRaw )
{
handler = StreamHandlerRaw::Create();
}
else
{
auto createHandlerFct = find_stream_handler( filename, isInput );
if( !createHandlerFct )
{
throw CalypFailure( "CalypStream", "Invalid handler" );
}
handler = createHandlerFct();
}
if( !handler )
{
throw CalypFailure( "CalypStream", "Cannot create handler" );
}
cFilename = std::move( filename );
handler->m_uiWidth = width;
handler->m_uiHeight = height;
handler->m_iPixelFormat = input_format;
handler->m_uiBitsPerPixel = bitsPel;
handler->m_iEndianness = bitsPel > 8 ? endianness : CLP_BIG_ENDIAN;
handler->m_dFrameRate = frame_rate;
if( !handler->openHandler( cFilename, isInput ) )
{
close();
throw CalypFailure( "CalypStream", "Cannot create the stream handler" );
return isInit;
}
if( handler->m_uiWidth <= 0 || handler->m_uiHeight <= 0 || handler->m_iPixelFormat == ClpPixelFormats::Invalid )
{
close();
throw CalypFailure( "CalypStream", "Incorrect configuration: width, height or pixel format" );
return isInit;
}
frameFifo.clear();
// Keep past, current and future frames
std::size_t bufferSize = isInput ? 6 : 1;
try
{
frameBuffer =
std::make_shared<CalypStreamFrameBuffer>( bufferSize, handler->m_uiWidth, handler->m_uiHeight,
handler->m_iPixelFormat, handler->m_uiBitsPerPixel, hasNegative );
}
catch( CalypFailure& e )
{
close();
throw CalypFailure( "CalypStream", "Cannot allocated frame buffer" );
return isInit;
}
const CalypFrame* refFrame = frameBuffer->ref();
handler->m_uiNBytesPerFrame = refFrame->getBytesPerFrame();
// Some handlers need to know how long is a frame to get frame number
handler->calculateFrameNumber();
if( isInput && handler->m_uiTotalNumberFrames == 0 )
{
close();
throw CalypFailure( "CalypStream", "Incorrect configuration: less than one frame" );
return isInit;
}
if( !handler->configureBuffer( *refFrame ) )
{
close();
throw CalypFailure( "CalypStream", "Cannot allocated buffers" );
return isInit;
}
iCurrFrameNum = -1;
isInit = true;
seekInput( 0 );
isInit = true;
return isInit;
}
void close()
@@ -205,18 +299,42 @@ public:
if( handler )
{
handler->closeHandler();
handler->Delete();
}
bLoadAll = false;
isInit = false;
}
bool seekInput( unsigned long new_frame_num )
{
const std::lock_guard<std::recursive_mutex> lock( stream_mutex );
if( !isInit || new_frame_num >= handler->m_uiTotalNumberFrames || long( new_frame_num ) == iCurrFrameNum )
return false;
iCurrFrameNum = new_frame_num;
if( bLoadAll )
return true;
frameFifo.clear();
if( !handler->seek( iCurrFrameNum ) )
{
throw CalypFailure( "CalypStream", "Cannot seek file into desired position" );
}
readNextFrame();
if( handler->m_uiTotalNumberFrames > 1 )
readNextFrame();
return true;
}
bool readNextFrame( bool fillRgbBuffer = false )
{
const std::lock_guard<std::recursive_mutex> lock( stream_mutex );
if( !isInit || !isInput || handler->m_uiCurrFrameFileIdx >= handler->m_uiTotalNumberFrames )
if( !isInit || streamType != CalypStream::Type::Input ||
handler->m_uiCurrFrameFileIdx >= handler->m_uiTotalNumberFrames )
return false;
if( bLoadAll )
@@ -253,47 +371,7 @@ std::vector<std::string> CalypStreamFormat::getExts()
return arrayExt;
}
CreateStreamHandlerFn CalypStream::findStreamHandler( std::string strFilename, bool bRead )
{
std::string currExt = strFilename.substr( strFilename.find_last_of( "." ) + 1 );
currExt = clpLowercase( currExt );
std::vector<CalypStreamFormat> supportedFmts;
if( bRead )
{
supportedFmts = CalypStream::supportedReadFormats();
}
else
{
supportedFmts = CalypStream::supportedWriteFormats();
}
for( unsigned int i = 0; i < supportedFmts.size(); i++ )
{
std::vector<std::string> arrayExt = supportedFmts[i].getExts();
for( std::vector<std::string>::iterator e = arrayExt.begin(); e != arrayExt.end(); ++e )
{
if( currExt != "" && currExt == *e )
{
return supportedFmts[i].formatFct;
}
else if( strFilename.find( *e ) != std::string::npos )
{
return supportedFmts[i].formatFct;
}
}
}
#ifdef USE_FFMPEG
return &StreamHandlerLibav::Create;
#else
return &StreamHandlerRaw::Create;
#endif
}
CalypStream::CalypStream()
: d{ std::make_unique<CalypStreamPrivate>() }
{
}
CalypStream::CalypStream() : d{ std::make_unique<CalypStreamPrivate>() } {}
CalypStream::~CalypStream() = default;
@@ -306,12 +384,12 @@ std::string CalypStream::getCodecName() const
return !d->handler ? "" : d->handler->getCodecName();
}
bool CalypStream::open( std::string filename, std::string resolution, std::string input_format_name, unsigned int bitsPel, int endianness, bool hasNegative,
unsigned int frame_rate, bool bInput )
bool CalypStream::open( std::string filename, std::string resolution, std::string input_format_name,
unsigned int bitsPel, int endianness, bool hasNegative, unsigned int frame_rate,
CalypStream::Type type )
{
unsigned int width = 0;
unsigned int height = 0;
int input_format = -1;
if( resolution.size() > 0 )
{
@@ -321,124 +399,51 @@ bool CalypStream::open( std::string filename, std::string resolution, std::strin
return false;
}
}
for( unsigned int i = 0; i < CalypFrame::supportedPixelFormatListNames().size(); i++ )
const auto input_format = CalypFrame::findPixelFormat( input_format_name );
if( !input_format.has_value() )
{
if( clpLowercase( CalypFrame::supportedPixelFormatListNames()[i] ) == clpLowercase( input_format_name ) )
{
input_format = i;
break;
}
return false;
}
return open( filename, width, height, input_format, bitsPel, endianness, hasNegative, frame_rate, bInput );
return d->open( std::move( filename ), width, height, *input_format, bitsPel, endianness, hasNegative, frame_rate,
false, type );
}
bool CalypStream::open( std::string filename, unsigned int width, unsigned int height, int input_format, unsigned int bitsPel, int endianness,
unsigned int frame_rate, bool bInput )
bool CalypStream::open( std::string filename, unsigned int width, unsigned int height, ClpPixelFormats input_format,
unsigned int bitsPel, int endianness, unsigned int frame_rate, CalypStream::Type type )
{
return open( filename, width, height, input_format, bitsPel, endianness, false, frame_rate, bInput );
return d->open( std::move( filename ), width, height, input_format, bitsPel, endianness, false, frame_rate, false,
type );
}
bool CalypStream::open( std::string filename, unsigned int width, unsigned int height, int input_format, unsigned int bitsPel, int endianness, bool hasNegative,
unsigned int frame_rate, bool bInput )
bool CalypStream::open( std::string filename, unsigned int width, unsigned int height, ClpPixelFormats input_format,
unsigned int bitsPel, int endianness, bool hasNegative, unsigned int frame_rate,
CalypStream::Type type )
{
if( d->isInit )
{
d->close();
}
d->isInit = false;
d->isInput = bInput;
return d->open( std::move( filename ), width, height, input_format, bitsPel, endianness, hasNegative, frame_rate,
false, type );
}
d->pfctCreateHandler = CalypStream::findStreamHandler( filename, d->isInput );
if( !d->pfctCreateHandler )
{
throw CalypFailure( "CalypStream", "Invalid handler" );
}
bool CalypStream::open( std::string filename, unsigned int width, unsigned int height, ClpPixelFormats input_format,
unsigned int bitsPel, int endianness, unsigned int frame_rate, bool forceRaw,
CalypStream::Type type )
{
return d->open( std::move( filename ), width, height, input_format, bitsPel, endianness, false, frame_rate, forceRaw,
type );
}
d->handler = d->pfctCreateHandler();
if( !d->handler )
{
throw CalypFailure( "CalypStream", "Cannot create handler" );
}
d->cFilename = filename;
d->handler->m_cFilename = filename;
d->handler->m_uiWidth = width;
d->handler->m_uiHeight = height;
d->handler->m_iPixelFormat = input_format;
d->handler->m_uiBitsPerPixel = bitsPel;
d->handler->m_iEndianness = endianness;
d->handler->m_dFrameRate = frame_rate;
if( !d->handler->openHandler( d->cFilename, d->isInput ) )
{
d->close();
return d->isInit;
}
if( d->handler->m_uiWidth <= 0 || d->handler->m_uiHeight <= 0 || d->handler->m_iPixelFormat < 0 )
{
d->close();
//throw CalypFailure( "CalypStream", "Incorrect configuration: width, height or pixel format" );
return d->isInit;
}
d->frameFifo.clear();
// Keep past, current and future frames
std::size_t bufferSize = d->isInput ? 6 : 1;
try
{
d->frameBuffer = std::make_shared<CalypStreamFrameBuffer>( bufferSize,
d->handler->m_uiWidth,
d->handler->m_uiHeight,
d->handler->m_iPixelFormat,
d->handler->m_uiBitsPerPixel,
hasNegative );
}
catch( CalypFailure& e )
{
d->close();
throw CalypFailure( "CalypStream", "Cannot allocated frame buffer" );
return d->isInit;
}
const CalypFrame* refFrame = d->frameBuffer->ref();
d->handler->m_uiNBytesPerFrame = refFrame->getBytesPerFrame();
// Some handlers need to know how long is a frame to get frame number
d->handler->calculateFrameNumber();
if( d->isInput && d->handler->m_uiTotalNumberFrames == 0 )
{
d->close();
throw CalypFailure( "CalypStream", "Incorrect configuration: less than one frame" );
return d->isInit;
}
if( !d->handler->configureBuffer( *refFrame ) )
{
d->close();
throw CalypFailure( "CalypStream", "Cannot allocated buffers" );
return d->isInit;
}
d->iCurrFrameNum = -1;
d->isInit = true;
seekInput( 0 );
d->isInit = true;
return d->isInit;
bool CalypStream::supportsFormatConfiguration()
{
if( d->handler == nullptr )
return false;
return d->handler->m_bSupportsFormat;
}
bool CalypStream::reload()
{
d->frameFifo.clear();
d->handler->closeHandler();
if( !d->handler->openHandler( d->cFilename, d->isInput ) )
if( !d->handler->openHandler( d->cFilename, d->streamType == CalypStream::Type::Input ) )
{
throw CalypFailure( "CalypStream", "Cannot open stream " + d->cFilename + " with the " +
std::string( d->handler->m_pchHandlerName ) + " handler" );
@@ -448,8 +453,9 @@ bool CalypStream::reload()
d->handler->calculateFrameNumber();
d->handler->configureBuffer( *refFrame );
if( d->handler->m_uiWidth <= 0 || d->handler->m_uiHeight <= 0 || d->handler->m_iPixelFormat < 0 ||
d->handler->m_uiBitsPerPixel == 0 || d->handler->m_uiTotalNumberFrames == 0 )
if( d->handler->m_uiWidth <= 0 || d->handler->m_uiHeight <= 0 ||
d->handler->m_iPixelFormat == ClpPixelFormats::Invalid || d->handler->m_uiBitsPerPixel == 0 ||
d->handler->m_uiTotalNumberFrames == 0 )
{
return false;
}
@@ -503,8 +509,8 @@ long CalypStream::getCurrFrameNum() const
return d->iCurrFrameNum;
}
void CalypStream::getFormat( unsigned int& rWidth, unsigned int& rHeight, int& rInputFormat, unsigned int& rBitsPerPel, int& rEndianness,
unsigned int& rFrameRate ) const
void CalypStream::getFormat( unsigned int& rWidth, unsigned int& rHeight, ClpPixelFormats& rInputFormat,
unsigned int& rBitsPerPel, int& rEndianness, unsigned int& rFrameRate ) const
{
if( d->isInit )
{
@@ -519,7 +525,7 @@ void CalypStream::getFormat( unsigned int& rWidth, unsigned int& rHeight, int& r
{
rWidth = 0;
rHeight = 0;
rInputFormat = CLP_YUV420P;
rInputFormat = ClpPixelFormats::YUV420p;
rBitsPerPel = kDefaultBitsPerPixel;
rEndianness = 0;
rFrameRate = kDefaultFrameRate;
@@ -543,7 +549,7 @@ auto CalypStream::hasWritingSlot() -> bool
void CalypStream::loadAll()
{
const std::lock_guard<std::recursive_mutex> lock( d->stream_mutex );
if( d->bLoadAll || !d->isInput )
if( d->bLoadAll || d->streamType != CalypStream::Type::Input )
return;
try
@@ -564,7 +570,14 @@ void CalypStream::loadAll()
d->iCurrFrameNum = 0;
}
std::unique_ptr<CalypFrame> CalypStream::getCurrFrame( std::unique_ptr<CalypFrame> buffer )
auto CalypStream::getCurrFrameAsset() -> std::shared_ptr<CalypFrame>
{
if( d->bLoadAll )
return d->frameFifo[d->iCurrFrameNum];
return d->frameFifo.front();
}
auto CalypStream::getCurrFrame( std::unique_ptr<CalypFrame> buffer ) const -> std::unique_ptr<CalypFrame>
{
if( buffer == nullptr )
buffer = std::make_unique<CalypFrame>( *d->frameFifo.front() );
@@ -573,13 +586,6 @@ std::unique_ptr<CalypFrame> CalypStream::getCurrFrame( std::unique_ptr<CalypFram
return buffer;
}
auto CalypStream::getCurrFrameAsset() -> std::shared_ptr<CalypFrame>
{
if( d->bLoadAll )
return d->frameFifo[d->iCurrFrameNum];
return d->frameFifo.front();
}
auto CalypStream::getCurrFrame() -> CalypFrame*
{
if( d->bLoadAll )
@@ -642,7 +648,7 @@ bool CalypStream::saveFrame( const std::string& filename, const CalypFrame& save
{
CalypStream auxSaveStream;
if( !auxSaveStream.open( filename, saveFrame.getWidth(), saveFrame.getHeight(), saveFrame.getPelFormat(),
saveFrame.getBitsPel(), CLP_LITTLE_ENDIAN, 1, false ) )
saveFrame.getBitsPel(), CLP_LITTLE_ENDIAN, 1, Type::Output ) )
{
return false;
}
@@ -655,7 +661,7 @@ bool CalypStream::saveFrame( const std::string& filename, const CalypFrame& save
*/
bool CalypStream::seekInputRelative( bool bIsFoward )
{
if( !d->isInit || !d->isInput )
if( !d->isInit || d->streamType != Type::Input )
return false;
bool bRet = false;
@@ -674,24 +680,42 @@ bool CalypStream::seekInputRelative( bool bIsFoward )
bool CalypStream::seekInput( unsigned long new_frame_num )
{
const std::lock_guard<std::recursive_mutex> lock( d->stream_mutex );
return d->seekInput( new_frame_num );
}
if( !d->isInit || new_frame_num >= d->handler->m_uiTotalNumberFrames || long( new_frame_num ) == d->iCurrFrameNum )
return false;
auto find_stream_handler( const std::string& strFilename, bool bRead ) -> CalypStreamFormat::CreateStreamHandlerFn
{
std::string currExt = strFilename.substr( strFilename.find_last_of( "." ) + 1 );
currExt = clpLowercase( currExt );
d->iCurrFrameNum = new_frame_num;
if( d->bLoadAll )
return true;
d->frameFifo.clear();
if( !d->handler->seek( d->iCurrFrameNum ) )
std::vector<CalypStreamFormat> supportedFmts;
if( bRead )
{
throw CalypFailure( "CalypStream", "Cannot seek file into desired position" );
supportedFmts = CalypStream::supportedReadFormats();
}
else
{
supportedFmts = CalypStream::supportedWriteFormats();
}
for( unsigned int i = 0; i < supportedFmts.size(); i++ )
{
std::vector<std::string> arrayExt = supportedFmts[i].getExts();
for( std::vector<std::string>::iterator e = arrayExt.begin(); e != arrayExt.end(); ++e )
{
if( currExt != "" && currExt == *e )
{
return supportedFmts[i].formatFct;
}
else if( strFilename.find( *e ) != std::string::npos )
{
return supportedFmts[i].formatFct;
}
}
}
d->readNextFrame();
if( d->handler->m_uiTotalNumberFrames > 1 )
d->readNextFrame();
return true;
}
#ifdef USE_FFMPEG
return &StreamHandlerLibav::Create;
#else
return &StreamHandlerRaw::Create;
#endif
}
+38 -24
View File
@@ -29,22 +29,10 @@
#include <memory>
#include <vector>
#include "CalypDefs.h"
#include "CalypFrame.h"
class CalypStreamHandlerIf;
typedef CalypStreamHandlerIf* ( *CreateStreamHandlerFn )( void );
struct CalypStreamFormat
{
std::string formatName;
std::string formatExt;
std::vector<std::string> getExts();
std::string formatPattern;
CreateStreamHandlerFn formatFct;
};
struct CalypStandardResolution
{
std::string shortName;
@@ -52,6 +40,26 @@ struct CalypStandardResolution
unsigned int uiHeight;
};
/**
* \class CalypStreamFormat
* \ingroup CalypLibGrp CalypStreamGrp
* \brief Stream format handling class
*/
class CalypStreamFormat
{
public:
using CreateStreamHandlerFn = auto ( * )( void ) -> std::unique_ptr<CalypStreamHandlerIf>;
CalypStreamFormat() = default;
std::vector<std::string> getExts();
std::string formatName;
std::string formatExt;
std::string formatPattern;
CreateStreamHandlerFn formatFct;
};
/**
* \class CalypStream
* \ingroup CalypLibGrp CalypStreamGrp
@@ -60,11 +68,14 @@ struct CalypStandardResolution
class CalypStream
{
public:
enum class Type
{
Input,
Output
};
static std::vector<CalypStreamFormat> supportedReadFormats();
static std::vector<CalypStreamFormat> supportedWriteFormats();
static CreateStreamHandlerFn findStreamHandler( std::string strFilename, bool bRead );
static std::vector<CalypStandardResolution> stdResolutionSizes();
CalypStream();
@@ -77,13 +88,16 @@ public:
std::string getFormatName() const;
std::string getCodecName() const;
bool open( std::string filename, std::string resolution, std::string input_format, unsigned int bitsPel, int endianness, bool hasNegative, unsigned int frame_rate,
bool bInput );
bool open( std::string filename, unsigned int width, unsigned int height, int input_format, unsigned int bitsPel, int endianness, unsigned int frame_rate,
bool bInput );
bool open( std::string filename, unsigned int width, unsigned int height, int input_format, unsigned int bitsPel, int endianness, bool hasNegative, unsigned int frame_rate,
bool bInput );
bool open( std::string filename, std::string resolution, std::string input_format, unsigned int bitsPel,
int endianness, bool hasNegative, unsigned int frame_rate, Type type );
bool open( std::string filename, unsigned int width, unsigned int height, ClpPixelFormats input_format,
unsigned int bitsPel, int endianness, unsigned int frame_rate, CalypStream::Type type );
bool open( std::string filename, unsigned int width, unsigned int height, ClpPixelFormats input_format,
unsigned int bitsPel, int endianness, bool hasNegative, unsigned int frame_rate, Type type );
bool open( std::string filename, unsigned int width, unsigned int height, ClpPixelFormats input_format,
unsigned int bitsPel, int endianness, unsigned int frame_rate, bool forceRaw, Type type );
bool supportsFormatConfiguration();
bool reload();
bool isNative() const;
@@ -95,15 +109,15 @@ public:
int getEndianess() const;
long getCurrFrameNum() const;
double getFrameRate() const;
void getFormat( unsigned int& rWidth, unsigned int& rHeight, int& rInputFormat, unsigned int& rBitsPerPel, int& rEndianness,
unsigned int& rFrameRate ) const;
void getFormat( unsigned int& rWidth, unsigned int& rHeight, ClpPixelFormats& rInputFormat, unsigned int& rBitsPerPel,
int& rEndianness, unsigned int& rFrameRate ) const;
auto hasNextFrame() -> bool;
auto hasWritingSlot() -> bool;
void loadAll();
std::unique_ptr<CalypFrame> getCurrFrame( std::unique_ptr<CalypFrame> buffer );
auto getCurrFrameAsset() -> std::shared_ptr<CalypFrame>;
auto getCurrFrame( std::unique_ptr<CalypFrame> buffer ) const -> std::unique_ptr<CalypFrame>;
auto getCurrFrame() -> CalypFrame*;
bool isEof();
bool setNextFrame();
+34 -38
View File
@@ -27,6 +27,7 @@
#include <vector>
#include "CalypDefs.h"
#include "CalypStream.h"
#define INI_REGIST_CALYP_SUPPORTED_FMT \
@@ -51,12 +52,11 @@
formatsList.insert( formatsList.end(), new_fmts.begin(), new_fmts.end() ); \
}
#define REGISTER_CALYP_STREAM_HANDLER( X ) \
public: \
static CalypStreamHandlerIf* Create() { return new X(); } \
void Delete() { delete this; } \
static std::vector<CalypStreamFormat> supportedReadFormats(); \
static std::vector<CalypStreamFormat> supportedWriteFormats(); \
#define REGISTER_CALYP_STREAM_HANDLER( X ) \
public: \
static std::unique_ptr<CalypStreamHandlerIf> Create() { return std::make_unique<X>(); } \
static std::vector<CalypStreamFormat> supportedReadFormats(); \
static std::vector<CalypStreamFormat> supportedWriteFormats(); \
// static int checkforSupportedFile( String, bool );
/**
@@ -69,23 +69,7 @@ class CalypStreamHandlerIf
friend class CalypStream;
public:
CalypStreamHandlerIf()
: m_bIsInput( true )
, m_bNative( true )
, m_uiWidth( 0 )
, m_uiHeight( 0 )
, m_iPixelFormat( -1 )
, m_uiBitsPerPixel( 8 )
, m_iEndianness( -1 )
, m_dFrameRate( 30 )
, m_uiCurrFrameFileIdx( 0 )
, m_uiTotalNumberFrames( 0 )
, m_uiNBytesPerFrame( 0 )
, m_isEOF( false )
{
}
virtual ~CalypStreamHandlerIf() {}
virtual void Delete() = 0;
virtual bool openHandler( std::string strFilename, bool bInput ) = 0;
virtual void closeHandler() = 0;
@@ -96,28 +80,40 @@ public:
virtual void calculateFrameNumber(){};
std::string getFormatName() { return m_strFormatName; }
std::string getCodecName() { return m_strCodecName; }
std::string getFormatName()
{
return m_strFormatName;
}
std::string getCodecName()
{
return m_strCodecName;
}
protected:
const char* m_pchHandlerName;
CalypStreamHandlerIf() = default;
CalypStreamHandlerIf( bool supportsFormats )
: m_bSupportsFormat{ supportsFormats }
{
}
const char* m_pchHandlerName{ "" };
const bool m_bSupportsFormat{ false };
std::string m_strFormatName;
std::string m_strCodecName;
bool m_bIsInput;
bool m_bNative;
std::string m_cFilename;
unsigned int m_uiWidth;
unsigned int m_uiHeight;
int m_iPixelFormat;
unsigned int m_uiBitsPerPixel;
int m_iEndianness;
double m_dFrameRate;
std::uint64_t m_uiCurrFrameFileIdx;
std::uint64_t m_uiTotalNumberFrames;
bool m_bIsInput{ true };
bool m_bNative{ true };
unsigned int m_uiWidth{ 0 };
unsigned int m_uiHeight{ 0 };
ClpPixelFormats m_iPixelFormat{ ClpPixelFormats::Invalid };
unsigned int m_uiBitsPerPixel{ 8 };
int m_iEndianness{ CLP_INVALID_ENDIANESS };
double m_dFrameRate{ 30 };
std::uint64_t m_uiCurrFrameFileIdx{ 0 };
std::uint64_t m_uiTotalNumberFrames{ 0 };
std::vector<ClpByte> m_pStreamBuffer;
std::uint64_t m_uiNBytesPerFrame;
bool m_isEOF;
std::uint64_t m_uiNBytesPerFrame{ 0 };
bool m_isEOF{ false };
};
#endif // __CALYPSTREAMHANDLERIF_H__
+21 -21
View File
@@ -43,11 +43,11 @@
#define ADD_FFMPEG_PEL_FMT( fmt ) 0
#endif
const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
const std::map<ClpPixelFormats, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
{
CLP_YUV420P,
ClpPixelFormats::YUV420p,
{
"YUV420p",
"YUV420p"sv,
CLP_COLOR_YUV,
3,
3,
@@ -62,9 +62,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_YUV422P,
ClpPixelFormats::YUV422p,
{
"YUV422p",
"YUV422p"sv,
CLP_COLOR_YUV,
3,
3,
@@ -79,9 +79,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_YUV444P,
ClpPixelFormats::YUV444p,
{
"YUV444p",
"YUV444p"sv,
CLP_COLOR_YUV,
3,
3,
@@ -96,9 +96,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_YUYV422,
ClpPixelFormats::YUYV422,
{
"YUYV422",
"YUYV422"sv,
CLP_COLOR_YUV,
3,
1,
@@ -113,9 +113,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_GRAY,
ClpPixelFormats::Gray,
{
"GRAY",
"GRAY"sv,
CLP_COLOR_GRAY,
1,
1,
@@ -126,9 +126,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_RGB24P,
ClpPixelFormats::RGB24p,
{
"RGBp",
"RGBp"sv,
CLP_COLOR_RGB,
3,
3,
@@ -143,9 +143,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_RGB24,
ClpPixelFormats::RGB24,
{
"RGB",
"RGB"sv,
CLP_COLOR_RGB,
3,
1,
@@ -160,9 +160,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_BGR24,
ClpPixelFormats::BGR24,
{
"BGR",
"BGR"sv,
CLP_COLOR_RGB,
3,
1,
@@ -177,9 +177,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_RGBA32,
ClpPixelFormats::RGBA32,
{
"RGBA",
"RGBA"sv,
CLP_COLOR_RGBA,
4,
1,
@@ -195,9 +195,9 @@ const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap = {
},
},
{
CLP_BGRA32,
ClpPixelFormats::BGRA32,
{
"BGRA",
"BGRA"sv,
CLP_COLOR_RGBA,
4,
1,
+19 -12
View File
@@ -29,11 +29,21 @@
#include "CalypFrame.h"
#define CHROMA_RESAMPLING( X ) ( ( ( X + 1 ) >> 1 ) << 1 )
using namespace std::string_view_literals;
#define CHROMARATIO( SIZE, RATIO ) ( RATIO > 1 ? ( ( SIZE + 1 ) / RATIO ) : SIZE )
template <typename T>
inline constexpr T CHROMA_RESAMPLING( T in )
{
return ( ( ( in + 1 ) >> 1 ) << 1 );
}
typedef struct CalypComponentDescriptor
template <typename T, typename R>
inline constexpr T CHROMARATIO( T size, R ratio )
{
return ( ratio > 1 ? ( ( size + 1 ) / ratio ) : size );
}
struct CalypComponentDescriptor
{
/**
* Which of the 4 planes contains the component.
@@ -51,8 +61,7 @@ typedef struct CalypComponentDescriptor
* Elements are bits for bitstream formats, bytes otherwise.
*/
unsigned short offset_plus1;
} CalypComponentDescriptor;
};
/**
* Descriptor that unambiguously describes how the bits of a pixel are
@@ -63,9 +72,9 @@ typedef struct CalypComponentDescriptor
* and all the YUV variants) AVPixFmtDescriptor just stores how values
* are stored not what these values represent.
*/
typedef struct CalypPixelFormatDescriptor
struct CalypPixelFormatDescriptor
{
const char* name;
std::string_view name;
int colorSpace;
@@ -102,11 +111,9 @@ typedef struct CalypPixelFormatDescriptor
* otherwise 0 is luma, 1 is chroma-U and 2 is chroma-V.
*/
CalypComponentDescriptor comp[4];
};
} CalypPixelFormatDescriptor;
#define MAX_NUMBER_PLANES 3
extern const std::map<int, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap;
static constexpr std::size_t kNumberOfPixelFormats{ 10 };
extern const std::map<ClpPixelFormats, CalypPixelFormatDescriptor> g_CalypPixFmtDescriptorsMap;
#endif // __PIXELFORMATS_H__
+46 -47
View File
@@ -35,6 +35,10 @@
#define FF_USER_CODEC_PARAM
#endif
#if( LIBAVCODEC_VERSION_MAJOR >= 59 && LIBAVFORMAT_VERSION_MAJOR >= 59 )
#define FF_API_LAVF_AVCTX
#endif
std::vector<CalypStreamFormat> StreamHandlerLibav::supportedReadFormats()
{
INI_REGIST_CALYP_SUPPORTED_FMT;
@@ -90,7 +94,7 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
// }
// Register all components of FFmpeg
//av_register_all();
// av_register_all();
/* open input file, and allocate format context */
if( avformat_open_input( &m_cFmtCtx, filename, NULL, NULL ) < 0 )
@@ -123,7 +127,7 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
#else
int codecId = m_cStream->codec->codec_id;
#endif
AVCodec* dec = avcodec_find_decoder( AVCodecID( codecId ) );
auto* dec = avcodec_find_decoder( AVCodecID( codecId ) );
if( !dec )
{
std::cout << "Failed to find video coded" << std::endl;
@@ -150,7 +154,7 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
if( avcodec_open2( m_cCodedCtx, dec, NULL ) < 0 )
{
std::cout << "Failed to open video coded" << std::endl;
std::cout << "Failed to open video codec" << std::endl;
return false;
}
@@ -172,8 +176,8 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
m_uiBitsPerPixel = 8;
/**
* Auxiliar conversation to re-use similar pixfmt
*/
* Auxiliar conversation to re-use similar pixfmt
*/
int auxPixFmt = m_ffPixFmt;
switch( m_ffPixFmt )
{
@@ -197,20 +201,14 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
auxPixFmt = AV_PIX_FMT_GRAY8;
}
m_iPixelFormat = CLP_INVALID_FMT;
for( int i = 0; i < CalypFrame::numberOfFormats(); i++ )
m_iPixelFormat = ClpPixelFormats::Invalid;
m_bNative = false;
auto found_fmt = std::find_if( g_CalypPixFmtDescriptorsMap.begin(), g_CalypPixFmtDescriptorsMap.end(),
[auxPixFmt]( const auto& fmt ) { return fmt.second.ffmpegPelFormat == auxPixFmt; } );
if( found_fmt != g_CalypPixFmtDescriptorsMap.end() )
{
if( g_CalypPixFmtDescriptorsMap.at( i ).ffmpegPelFormat == auxPixFmt )
{
m_iPixelFormat = i;
break;
}
}
if( m_iPixelFormat == CLP_INVALID_FMT )
{
m_bNative = false;
//throw CalypFailure( "StreamHandlerLibav", "Cannot open file using FFmpeg libs - unsupported pixel format" );
//return false;
m_bNative = true;
m_iPixelFormat = found_fmt->first;
}
double fr = 30;
@@ -249,35 +247,34 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
if( !m_bNative )
{
int newPelFmt = -1;
ClpPixelFormats newPelFmt{ ClpPixelFormats::Invalid };
const AVPixFmtDescriptor* ffPelDesc = av_pix_fmt_desc_get( AVPixelFormat( m_ffPixFmt ) );
if( ffPelDesc->flags & AV_PIX_FMT_FLAG_PAL )
{
newPelFmt = CLP_RGB24;
newPelFmt = ClpPixelFormats::RGB24;
}
else if( ffPelDesc->flags & AV_PIX_FMT_FLAG_ALPHA )
{
newPelFmt = CLP_RGBA32;
newPelFmt = ClpPixelFormats::RGBA32;
}
else if( ffPelDesc->flags & AV_PIX_FMT_FLAG_RGB )
{
newPelFmt = CLP_RGB24;
newPelFmt = ClpPixelFormats::RGB24;
}
else if( ffPelDesc->nb_components == 1 )
{
newPelFmt = CLP_GRAY;
newPelFmt = ClpPixelFormats::Gray;
}
else
{
newPelFmt = CLP_YUV444P;
newPelFmt = ClpPixelFormats::YUV444p;
}
m_iPixelFormat = newPelFmt;
AVPixelFormat newAvFmt = AVPixelFormat( g_CalypPixFmtDescriptorsMap.at( m_iPixelFormat ).ffmpegPelFormat );
/* create scaling context */
m_ScalerCtx = sws_getContext( m_uiWidth, m_uiHeight, AVPixelFormat( m_ffPixFmt ),
m_uiWidth, m_uiHeight, newAvFmt,
m_ScalerCtx = sws_getContext( m_uiWidth, m_uiHeight, AVPixelFormat( m_ffPixFmt ), m_uiWidth, m_uiHeight, newAvFmt,
SWS_BILINEAR, NULL, NULL, NULL );
m_cConvertedFrame = av_frame_alloc();
@@ -287,8 +284,9 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
return false;
}
if( av_image_alloc( m_cConvertedFrame->data, m_cConvertedFrame->linesize,
m_uiWidth, m_uiHeight, newAvFmt, 16 ) < 0 )
auto alloc_error =
av_image_alloc( m_cConvertedFrame->data, m_cConvertedFrame->linesize, m_uiWidth, m_uiHeight, newAvFmt, 16 );
if( alloc_error < 0 )
{
closeHandler();
return false;
@@ -300,10 +298,10 @@ bool StreamHandlerLibav::openHandler( std::string strFilename, bool bInput )
m_uiFrameBufferSize = av_image_get_buffer_size( AVPixelFormat( m_ffPixFmt ), m_uiWidth, m_uiHeight, 1 );
/* initialize packet, set data to NULL, let the demuxer fill it */
av_init_packet( &m_cPacket );
m_cPacket.data = NULL;
m_cPacket.size = 0;
m_cOrgPacket = m_cPacket;
m_cPacket = av_packet_alloc();
m_cPacket->data = NULL;
m_cPacket->size = 0;
m_cOrgPacket = *m_cPacket;
m_bHasStream = true;
return true;
@@ -320,6 +318,7 @@ void StreamHandlerLibav::closeHandler()
avformat_close_input( &m_cFmtCtx );
av_free( m_cFrame );
av_packet_free( &m_cPacket );
}
m_bHasStream = false;
}
@@ -369,21 +368,21 @@ bool StreamHandlerLibav::read( CalypFrame& pcFrame )
bReadPkt = true;
else
return false;
//if( iRet == AVERROR_EOF )
// m_isEOF = true;
// if( iRet == AVERROR_EOF )
// m_isEOF = true;
}
else
{
bGotFrame = 1;
}
#else
if( m_cPacket.stream_index == m_iStreamIdx )
if( m_cPacket->stream_index == m_iStreamIdx )
{
if( ( iRet = avcodec_decode_video2( m_cCodedCtx, m_cFrame, &bGotFrame, &m_cPacket ) ) < 0 )
if( ( iRet = avcodec_decode_video2( m_cCodedCtx, m_cFrame, &bGotFrame, m_cPacket ) ) < 0 )
return false;
m_cPacket.data += iRet;
m_cPacket.size -= iRet;
if( m_cPacket.size <= 0 )
m_cPacket->data += iRet;
m_cPacket->size -= iRet;
if( m_cPacket->size <= 0 )
{
bReadPkt = true;
av_packet_unref( &m_cOrgPacket );
@@ -396,7 +395,7 @@ bool StreamHandlerLibav::read( CalypFrame& pcFrame )
{
bReadPkt = false;
av_packet_unref( &m_cOrgPacket );
if( ( iRet = av_read_frame( m_cFmtCtx, &m_cPacket ) ) < 0 )
if( ( iRet = av_read_frame( m_cFmtCtx, m_cPacket ) ) < 0 )
{
if( iRet == AVERROR_EOF )
{
@@ -405,10 +404,10 @@ bool StreamHandlerLibav::read( CalypFrame& pcFrame )
}
return false;
}
m_cOrgPacket = m_cPacket;
m_cOrgPacket = *m_cPacket;
#ifdef FF_SEND_RECEIVE_API
if( m_cPacket.stream_index == m_iStreamIdx )
if( ( iRet = avcodec_send_packet( m_cCodedCtx, &m_cPacket ) ) < 0 )
if( m_cPacket->stream_index == m_iStreamIdx )
if( ( iRet = avcodec_send_packet( m_cCodedCtx, m_cPacket ) ) < 0 )
return false;
#endif
}
@@ -419,13 +418,13 @@ bool StreamHandlerLibav::read( CalypFrame& pcFrame )
AVFrame* decFrame = m_cFrame;
if( !m_bNative )
{
sws_scale( m_ScalerCtx, (const uint8_t* const*)decFrame->data, decFrame->linesize, 0,
decFrame->height, (uint8_t* const*)m_cConvertedFrame->data, m_cConvertedFrame->linesize );
sws_scale( m_ScalerCtx, (const uint8_t* const*)decFrame->data, decFrame->linesize, 0, decFrame->height,
(uint8_t* const*)m_cConvertedFrame->data, m_cConvertedFrame->linesize );
decFrame = m_cConvertedFrame;
}
av_image_copy_to_buffer( m_pStreamBuffer.data(), m_uiFrameBufferSize, decFrame->data,
decFrame->linesize, AVPixelFormat( m_ffPixFmt ), m_uiWidth, m_uiHeight, 1 );
av_image_copy_to_buffer( m_pStreamBuffer.data(), m_uiFrameBufferSize, decFrame->data, decFrame->linesize,
AVPixelFormat( m_ffPixFmt ), m_uiWidth, m_uiHeight, 1 );
pcFrame.frameFromBuffer( m_pStreamBuffer, m_iEndianness );
m_uiCurrFrameFileIdx++;
+2 -1
View File
@@ -40,6 +40,7 @@
#endif
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
@@ -87,7 +88,7 @@ private:
int m_ffPixFmt;
AVFrame* m_cFrame;
AVPacket m_cOrgPacket;
AVPacket m_cPacket;
AVPacket* m_cPacket;
bool m_bHasStream;
+15 -13
View File
@@ -28,6 +28,8 @@
#include <opencv2/opencv.hpp>
#include "CalypFrame.h"
#include "PixelFormats.h"
#if CV_MAJOR_VERSION >= 3
#include <opencv2/videoio.hpp>
#endif
@@ -60,12 +62,12 @@ std::vector<CalypStreamFormat> StreamHandlerOpenCV::supportedWriteFormats()
StreamHandlerOpenCV::StreamHandlerOpenCV()
{
m_pchHandlerName = "OpenCV";
pcVideoCapture = NULL;
m_pcVideoCapture = NULL;
}
bool StreamHandlerOpenCV::openHandler( std::string strFilename, bool bInput )
{
m_cFilename = strFilename;
m_cFilename = std::move( strFilename );
if( bInput )
{
#if( CV_VERSION_MAJOR >= 3 )
@@ -82,10 +84,10 @@ bool StreamHandlerOpenCV::openHandler( std::string strFilename, bool bInput )
m_strFormatName = "DEV";
m_strCodecName = "Raw Video";
pcVideoCapture = new VideoCapture( iDeviceId );
m_pcVideoCapture = new VideoCapture( iDeviceId );
#if CV_MAJOR_VERSION >= 4
m_uiWidth = pcVideoCapture->get( cv::CAP_PROP_FRAME_WIDTH );
m_uiHeight = pcVideoCapture->get( cv::CAP_PROP_FRAME_HEIGHT );
m_uiWidth = m_pcVideoCapture->get( cv::CAP_PROP_FRAME_WIDTH );
m_uiHeight = m_pcVideoCapture->get( cv::CAP_PROP_FRAME_HEIGHT );
#else
m_uiWidth = pcVideoCapture->get( CV_CAP_PROP_FRAME_WIDTH );
m_uiHeight = pcVideoCapture->get( CV_CAP_PROP_FRAME_HEIGHT );
@@ -103,10 +105,10 @@ bool StreamHandlerOpenCV::openHandler( std::string strFilename, bool bInput )
m_dFrameRate = 1;
}
m_uiBitsPerPixel = 8;
m_iPixelFormat = CalypFrame::findPixelFormat( "BGR" );
m_iPixelFormat = ClpPixelFormats::BGR24;
m_uiTotalNumberFrames = 1;
if( pcVideoCapture )
if( m_pcVideoCapture )
{
m_uiTotalNumberFrames = 2;
}
@@ -117,11 +119,11 @@ bool StreamHandlerOpenCV::openHandler( std::string strFilename, bool bInput )
void StreamHandlerOpenCV::closeHandler()
{
if( pcVideoCapture )
if( m_pcVideoCapture )
{
pcVideoCapture->release();
delete pcVideoCapture;
pcVideoCapture = NULL;
m_pcVideoCapture->release();
delete m_pcVideoCapture;
m_pcVideoCapture = NULL;
}
}
@@ -139,10 +141,10 @@ bool StreamHandlerOpenCV::seek( std::uint64_t iFrameNum )
bool StreamHandlerOpenCV::read( CalypFrame& pcFrame )
{
bool bRet = false;
if( pcVideoCapture )
if( m_pcVideoCapture )
{
Mat cvMat;
bRet = pcVideoCapture->read( cvMat );
bRet = m_pcVideoCapture->read( cvMat );
if( bRet )
bRet = pcFrame.fromMat( cvMat );
}
+2 -1
View File
@@ -48,7 +48,8 @@ public:
bool write( const CalypFrame& pcFrame );
private:
cv::VideoCapture* pcVideoCapture;
std::string m_cFilename;
cv::VideoCapture* m_pcVideoCapture;
};
#endif // __STREAMHANDLEROPENCV_H__
+6 -5
View File
@@ -28,6 +28,7 @@
#include <cstdio>
#include "CalypFrame.h"
#include "PixelFormats.h"
std::vector<CalypStreamFormat> StreamHandlerPortableMap::supportedReadFormats()
{
@@ -79,26 +80,26 @@ bool StreamHandlerPortableMap::openHandler( std::string strFilename, bool bInput
}
}
m_uiBitsPerPixel = log( m_iMaxValue + 1 ) / log( 2 );
m_iPixelFormat = m_iMagicNumber == 1 || m_iMagicNumber == 2 || m_iMagicNumber == 5 ? CLP_GRAY : CLP_RGB24;
m_iPixelFormat = m_iMagicNumber == 1 || m_iMagicNumber == 2 || m_iMagicNumber == 5 ? ClpPixelFormats::Gray : ClpPixelFormats::RGB24;
}
else
{
int colorSpace = CalypFrame::pelformatColorSpace( m_iPixelFormat );
int colorSpace = CalypFrame::pelFormatColorSpace( m_iPixelFormat );
m_iMaxValue = ( 1 << m_uiBitsPerPixel ) - 1;
if( m_uiBitsPerPixel == 1 )
{
m_iMagicNumber = 1;
m_iPixelFormat = CalypFrame::findPixelFormat( "GRAY" );
m_iPixelFormat = ClpPixelFormats::Gray;
}
else if( colorSpace == CLP_COLOR_GRAY )
{
m_iMagicNumber = 5;
m_iPixelFormat = CalypFrame::findPixelFormat( "GRAY" );
m_iPixelFormat = ClpPixelFormats::Gray;
}
else if( colorSpace == CLP_COLOR_RGB )
{
m_iMagicNumber = 6;
m_iPixelFormat = CalypFrame::findPixelFormat( "RGB" );
m_iPixelFormat = ClpPixelFormats::RGB24;
}
else
{
+17 -5
View File
@@ -25,6 +25,7 @@
#include "StreamHandlerRaw.h"
#include <cstdio>
#include <filesystem>
#include "CalypFrame.h"
@@ -34,6 +35,7 @@ std::vector<CalypStreamFormat> StreamHandlerRaw::supportedReadFormats()
REGIST_CALYP_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw YUV Video", "yuv" );
REGIST_CALYP_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Gray Video", "gray" );
REGIST_CALYP_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw RGB Video", "rgb" );
REGIST_CALYP_SUPPORTED_FMT( &StreamHandlerRaw::Create, "Raw Video", "raw" );
END_REGIST_CALYP_SUPPORTED_FMT;
}
@@ -44,17 +46,24 @@ std::vector<CalypStreamFormat> StreamHandlerRaw::supportedWriteFormats()
END_REGIST_CALYP_SUPPORTED_FMT;
}
StreamHandlerRaw::StreamHandlerRaw() : CalypStreamHandlerIf{ true }
{
m_pchHandlerName = "RawVideo";
}
bool StreamHandlerRaw::openHandler( std::string strFilename, bool bInput )
{
m_bIsInput = bInput;
m_pFile = NULL;
m_pFile = nullptr;
m_pFile = fopen( strFilename.c_str(), bInput ? "rb" : "wb" );
if( m_pFile == NULL )
if( m_pFile == nullptr )
{
return false;
}
calculateFrameNumber();
m_strFormatName = "YUV";
std::string fileExtension = std::filesystem::path{ strFilename }.extension().string();
fileExtension.erase( fileExtension.begin() );
m_strFormatName = clpUppercase( fileExtension );
m_strCodecName = "Raw Video";
return true;
}
@@ -63,6 +72,7 @@ void StreamHandlerRaw::closeHandler()
{
if( m_pFile )
fclose( m_pFile );
m_pFile = nullptr;
}
bool StreamHandlerRaw::configureBuffer( const CalypFrame& pcFrame )
@@ -97,7 +107,8 @@ bool StreamHandlerRaw::read( CalypFrame& pcFrame )
{
if( !m_pFile || m_pStreamBuffer.empty() || m_uiNBytesPerFrame == 0 )
return false;
unsigned long long int processed_bytes = fread( m_pStreamBuffer.data(), sizeof( ClpByte ), m_uiNBytesPerFrame, m_pFile );
unsigned long long int processed_bytes =
fread( m_pStreamBuffer.data(), sizeof( ClpByte ), m_uiNBytesPerFrame, m_pFile );
if( processed_bytes != m_uiNBytesPerFrame )
return false;
m_uiCurrFrameFileIdx++;
@@ -108,7 +119,8 @@ bool StreamHandlerRaw::read( CalypFrame& pcFrame )
bool StreamHandlerRaw::write( const CalypFrame& pcFrame )
{
pcFrame.frameToBuffer( m_pStreamBuffer, m_iEndianness );
unsigned long long int processed_bytes = fwrite( m_pStreamBuffer.data(), sizeof( ClpByte ), m_uiNBytesPerFrame, m_pFile );
unsigned long long int processed_bytes =
fwrite( m_pStreamBuffer.data(), sizeof( ClpByte ), m_uiNBytesPerFrame, m_pFile );
if( processed_bytes != m_uiNBytesPerFrame )
return false;
return true;
+1 -1
View File
@@ -40,7 +40,7 @@ private:
FILE* m_pFile; /**< The input file pointer >*/
public:
StreamHandlerRaw() { m_pchHandlerName = "RawVideo"; }
StreamHandlerRaw();
~StreamHandlerRaw() {}
bool openHandler( std::string strFilename, bool bInput );
void closeHandler();
+10 -3
View File
@@ -2,10 +2,17 @@
# CMakeLists for Calyp lis tests using catch2
#
# ADD_DEFINITIONS(-DCALYP_TEST_DATA_DIR=\"${CALYP_TEST_DATA_DIR}\")
FETCHCONTENT_MAKEAVAILABLE(Catch2)
SET(Calyp_Lib_Catch2_Tests_SRCS CalypFrameTests.cpp)
SET(Calyp_Lib_Catch2_Tests_SRCS
CalypLibTests.cpp
CalypStreamTests.cpp
CalypFrameTests.cpp
)
ADD_DEFINITIONS(-DCALYP_TEST_DATA_DIR=\"${CALYP_TEST_DATA_DIR}\")
ADD_EXECUTABLE(CalypLibCatch2Tests ${Calyp_Lib_Catch2_Tests_SRCS})
TARGET_LINK_LIBRARIES(CalypLibCatch2Tests ${PROJECT_LIBRARY} Catch2::Catch2)
TARGET_LINK_LIBRARIES(CalypLibCatch2Tests ${PROJECT_LIBRARY} Catch2::Catch2WithMain)
CATCH_DISCOVER_TESTS(CalypLibCatch2Tests)
+16 -17
View File
@@ -22,40 +22,39 @@
* \brief CalypFrame general tests
*/
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <catch2/catch_all.hpp>
#include "CalypFrame.h"
TEST_CASE( "create a 256x128 frame with 8 bits in YUV420 format", "CalypFrame" )
{
// Constructor: CalypFrame( unsigned int width, unsigned int height, int pelFormat, unsigned bitsPixel = 8 );
CalypFrame testFrame( 256, 128, CLP_YUV420P, 8 );
CalypFrame testFrame( 256, 128, ClpPixelFormats::YUV420p, 8 );
REQUIRE( testFrame.getWidth() == 256 );
REQUIRE( testFrame.getHeight() == 128 );
REQUIRE( testFrame.getPelFormat() == CLP_YUV420P );
REQUIRE( testFrame.getBitsPel() == 8 );
CHECK( testFrame.getWidth() == 256 );
CHECK( testFrame.getHeight() == 128 );
CHECK( testFrame.getPelFormat() == ClpPixelFormats::YUV420p );
CHECK( testFrame.getBitsPel() == 8 );
}
TEST_CASE( "create a 256x128 frame with 10 bits in YUV420 format", "CalypFrame" )
{
// Constructor: CalypFrame( unsigned int width, unsigned int height, int pelFormat, unsigned bitsPixel = 8 );
CalypFrame testFrame( 256, 128, CLP_YUV420P, 10 );
CalypFrame testFrame( 256, 128, ClpPixelFormats::YUV420p, 10 );
REQUIRE( testFrame.getWidth() == 256 );
REQUIRE( testFrame.getHeight() == 128 );
REQUIRE( testFrame.getPelFormat() == CLP_YUV420P );
REQUIRE( testFrame.getBitsPel() == 10 );
CHECK( testFrame.getWidth() == 256 );
CHECK( testFrame.getHeight() == 128 );
CHECK( testFrame.getPelFormat() == ClpPixelFormats::YUV420p );
CHECK( testFrame.getBitsPel() == 10 );
}
TEST_CASE( "create a 256x128 frame with 16 bits in YUV420 format", "CalypFrame" )
{
// Constructor: CalypFrame( unsigned int width, unsigned int height, int pelFormat, unsigned bitsPixel = 8 );
CalypFrame testFrame( 256, 128, CLP_YUV420P, 16 );
CalypFrame testFrame( 256, 128, ClpPixelFormats::YUV420p, 16 );
REQUIRE( testFrame.getWidth() == 256 );
REQUIRE( testFrame.getHeight() == 128 );
REQUIRE( testFrame.getPelFormat() == CLP_YUV420P );
REQUIRE( testFrame.getBitsPel() == 16 );
CHECK( testFrame.getWidth() == 256 );
CHECK( testFrame.getHeight() == 128 );
CHECK( testFrame.getPelFormat() == ClpPixelFormats::YUV420p );
CHECK( testFrame.getBitsPel() == 16 );
}
+26
View File
@@ -0,0 +1,26 @@
/* This file is a part of plaYUVer project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file CalypLibTests.cpp
* \brief CalypLib main test file
*/
#define CATCH_CONFIG_MAIN
#include <catch2/catch_test_macros.hpp>
+280
View File
@@ -0,0 +1,280 @@
/* This file is a part of plaYUVer project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file CalypStreamTests.cpp
* \brief CalypStream general tests
*/
#include <catch2/catch_all.hpp>
#include <filesystem>
#include <iostream>
#include <variant>
#include "CalypFrame.h"
#include "CalypStream.h"
constexpr int kFrameRate{ 30 };
constexpr auto kStreamType = CalypStream::Type::Input;
auto getFileTestFilename( const char* test_sequence ) -> std::string
{
return std::string( CALYP_TEST_DATA_DIR ) + std::string( "/" ) + std::string( test_sequence );
}
TEST_CASE( "Can open a YUV 420p file", "CalypStream" )
{
constexpr int kWidth{ 352 };
constexpr int kHeight{ 288 };
constexpr auto kInputFormat{ ClpPixelFormats::YUV420p };
constexpr int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_INVALID_ENDIANESS };
const auto kFilename = getFileTestFilename( "Foreman.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( test_stream.getWidth() == kWidth );
CHECK( test_stream.getHeight() == kHeight );
CHECK( test_stream.getBitsPerPixel() == kBitsPel );
CHECK( test_stream.getFormatName() == "YUV" );
CHECK( test_stream.getCodecName() == "Raw Video" );
CHECK( test_stream.getEndianess() == CLP_BIG_ENDIAN );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getPixel( 2, 0 ) == CalypPixel{ CLP_COLOR_YUV, 201, 129, 125 } );
CHECK( frame->getPixel( 336, 278 ) == CalypPixel{ CLP_COLOR_YUV, 99, 111, 142 } );
}
TEST_CASE( "Can open a YUV file", "CalypStream" )
{
constexpr int kWidth{ 352 };
constexpr int kHeight{ 288 };
constexpr int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_INVALID_ENDIANESS };
auto common_checks = []( auto& stream ) {
return stream.getWidth() == kWidth && stream.getHeight() == kHeight && stream.getBitsPerPixel() == kBitsPel &&
stream.getFormatName() == "YUV" && stream.getCodecName() == "Raw Video" &&
stream.getEndianess() == CLP_BIG_ENDIAN;
};
SECTION( "YUV420p" )
{
constexpr auto kInputFormat{ ClpPixelFormats::YUV420p };
const auto kFilename = getFileTestFilename( "Foreman.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( common_checks( test_stream ) );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getColorSpace() == CLP_COLOR_YUV );
CHECK( frame->getPelFmtName() == "YUV420p" );
CHECK( frame->getPelFormat() == kInputFormat );
}
SECTION( "YUV422p" )
{
constexpr auto kInputFormat{ ClpPixelFormats::YUV422p };
const auto kFilename = getFileTestFilename( "Foreman_352x288_yuv422p.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( common_checks( test_stream ) );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getColorSpace() == CLP_COLOR_YUV );
CHECK( frame->getPelFmtName() == "YUV422p" );
CHECK( frame->getPelFormat() == kInputFormat );
}
SECTION( "YUV444p" )
{
constexpr auto kInputFormat{ ClpPixelFormats::YUV444p };
const auto kFilename = getFileTestFilename( "Foreman_352x288_yuv444p.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( common_checks( test_stream ) );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getColorSpace() == CLP_COLOR_YUV );
CHECK( frame->getPelFmtName() == "YUV444p" );
CHECK( frame->getPelFormat() == kInputFormat );
}
SECTION( "YUYV422" )
{
constexpr auto kInputFormat{ ClpPixelFormats::YUYV422 };
const auto kFilename = getFileTestFilename( "Foreman_352x288_yuyv422.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( common_checks( test_stream ) );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getColorSpace() == CLP_COLOR_YUV );
CHECK( frame->getPelFmtName() == "YUYV422" );
CHECK( frame->getPelFormat() == kInputFormat );
}
}
TEST_CASE( "Can open a RGB file", "CalypStream" )
{
constexpr int kWidth{ 352 };
constexpr int kHeight{ 288 };
constexpr int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_INVALID_ENDIANESS };
auto common_checks = []( auto& stream ) {
return stream.getWidth() == kWidth && stream.getHeight() == kHeight && stream.getBitsPerPixel() == kBitsPel &&
stream.getFormatName() == "YUV" && stream.getCodecName() == "Raw Video" &&
stream.getEndianess() == CLP_BIG_ENDIAN;
};
SECTION( "RGB24" )
{
constexpr auto kInputFormat{ ClpPixelFormats::RGB24 };
const auto kFilename = getFileTestFilename( "Foreman_352x288_rgb24.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( common_checks( test_stream ) );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getColorSpace() == CLP_COLOR_RGB );
CHECK( frame->getPelFmtName() == "RGB" );
CHECK( frame->getPelFormat() == kInputFormat );
std::cout << test_stream.getFormatName();
}
SECTION( "BGR24" )
{
constexpr auto kInputFormat{ ClpPixelFormats::BGR24 };
const auto kFilename = getFileTestFilename( "Foreman_352x288_bgr24.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( common_checks( test_stream ) );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getColorSpace() == CLP_COLOR_RGB );
CHECK( frame->getPelFmtName() == "BGR" );
CHECK( frame->getPelFormat() == kInputFormat );
}
}
TEST_CASE( "Can open a GRAY file", "CalypStream" )
{
constexpr int kWidth{ 352 };
constexpr int kHeight{ 288 };
constexpr int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_INVALID_ENDIANESS };
auto common_checks = []( auto& stream ) {
return stream.getWidth() == kWidth && stream.getHeight() == kHeight && stream.getBitsPerPixel() == kBitsPel &&
stream.getFormatName() == "YUV" && stream.getCodecName() == "Raw Video" &&
stream.getEndianess() == CLP_BIG_ENDIAN;
};
constexpr auto kInputFormat{ ClpPixelFormats::Gray };
const auto kFilename = getFileTestFilename( "Foreman_352x288_gray.yuv" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
CalypStream test_stream;
auto result =
test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, kStreamType );
REQUIRE( result );
CHECK( common_checks( test_stream ) );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getColorSpace() == CLP_COLOR_GRAY );
CHECK( frame->getPelFmtName() == "GRAY" );
CHECK( frame->getPelFormat() == kInputFormat );
}
TEST_CASE( "Can open .batatas file as RAW video", "CalypStream" )
{
constexpr int kWidth{ 352 };
constexpr int kHeight{ 288 };
constexpr auto kInputFormat{ ClpPixelFormats::YUV420p };
constexpr int kBitsPel{ 8 };
constexpr auto KEndianness{ CLP_INVALID_ENDIANESS };
const auto kFilename = getFileTestFilename( "Foreman.batatas" );
REQUIRE( std::filesystem::exists( std::filesystem::path( kFilename ) ) );
bool force_raw{ false };
SECTION( "Without forcing raw video" )
{
CalypStream test_stream;
bool result{ false };
try
{
result = test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate, force_raw,
kStreamType );
}
catch( ... )
{
// NOLINT
}
CHECK( !result );
}
SECTION( "Forcing raw video" )
{
force_raw = true;
CalypStream test_stream;
auto result = test_stream.open( kFilename, kWidth, kHeight, kInputFormat, kBitsPel, KEndianness, kFrameRate,
force_raw, kStreamType );
REQUIRE( result );
CHECK( test_stream.getWidth() == kWidth );
CHECK( test_stream.getHeight() == kHeight );
CHECK( test_stream.getBitsPerPixel() == kBitsPel );
CHECK( test_stream.getFormatName() == "BATATAS" );
CHECK( test_stream.getCodecName() == "Raw Video" );
CHECK( test_stream.getEndianess() == CLP_BIG_ENDIAN );
const auto* frame = test_stream.getCurrFrame();
CHECK( frame->getPixel( 2, 0 ) == CalypPixel{ CLP_COLOR_YUV, 201, 129, 125 } );
CHECK( frame->getPixel( 336, 278 ) == CalypPixel{ CLP_COLOR_YUV, 99, 111, 142 } );
}
}
+4 -4
View File
@@ -35,13 +35,13 @@ protected:
static void SetUpTestCase()
{
pcStreamPast = std::make_unique<CalypStream>();
pcStreamPast->open( std::string( CALYP_TEST_DATA_DIR ) + std::string( "/BasketballDrill_F10_832x480_yuv420p.yuv" ), 832, 480, 0, 8,
CLP_BIG_ENDIAN, 1, true );
pcStreamPast->open( std::string( CALYP_TEST_DATA_DIR ) + std::string( "/BasketballDrill_F10_832x480_yuv420p.yuv" ), 832, 480, ClpPixelFormats::YUV420p, 8,
CLP_BIG_ENDIAN, 1, CalypStream::Type::Input );
pcFramePast = pcStreamPast->getCurrFrame();
pcStreamFuture = std::make_unique<CalypStream>();
pcStreamFuture->open( std::string( CALYP_TEST_DATA_DIR ) + std::string( "/BasketballDrill_F15_832x480_yuv420p.yuv" ), 832, 480, 0, 8,
CLP_BIG_ENDIAN, 1, true );
pcStreamFuture->open( std::string( CALYP_TEST_DATA_DIR ) + std::string( "/BasketballDrill_F15_832x480_yuv420p.yuv" ), 832, 480, ClpPixelFormats::YUV420p, 8,
CLP_BIG_ENDIAN, 1, CalypStream::Type::Input );
pcFrameFuture = pcStreamFuture->getCurrFrame();
}
+8 -15
View File
@@ -29,19 +29,19 @@ AbsoluteFrameDifference::AbsoluteFrameDifference()
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2; // Use API version 2 (recommended).
// See this example for details on the functions prototype
m_iModuleType = CLP_FRAME_PROCESSING_MODULE; // Apply module to the frames or to
m_iModuleType = ClpModuleType::FrameProcessing; // Apply module to the frames or to
// the whole sequence.
m_pchModuleCategory = "Measurements"; // Category (sub-menu)
m_pchModuleName = "AbsoluteFrameDifference"; // Name (no spaces)
m_pchModuleLongName = "Absolute Difference"; // Long Name
m_pchModuleTooltip = "Measure the absolute difference " // Description
"between two images (Y plane), e. g., abs( Y1 - Y2 )";
m_uiNumberOfFrames = 2; // Number of frames required
m_uiModuleRequirements = CLP_MODULE_REQUIRES_NEW_WINDOW; // Module requirements
// (check
// CalypModulesIf.h).
m_uiNumberOfFrames = 2; // Number of frames required
m_uiModuleRequirements = ClpModuleFeature::NewWindow; // Module requirements
// (check
// CalypModulesIf.h).
// Several requirements should be "or" between each others.
m_pcFrameDifference = NULL;
m_pcFrameDifference = nullptr;
}
bool AbsoluteFrameDifference::create( std::vector<CalypFrame*> apcFrameList )
@@ -52,7 +52,7 @@ bool AbsoluteFrameDifference::create( std::vector<CalypFrame*> apcFrameList )
if( !apcFrameList[i]->haveSameFmt( apcFrameList[0], CalypFrame::MATCH_COLOR_SPACE_IGNORE_GRAY | CalypFrame::MATCH_COLOR_SPACE | CalypFrame::MATCH_RESOLUTION | CalypFrame::MATCH_BITS ) )
return false;
m_pcFrameDifference = new CalypFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), CLP_GRAY, apcFrameList[0]->getBitsPel() );
m_pcFrameDifference = std::make_unique<CalypFrame>( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), ClpPixelFormats::Gray, apcFrameList[0]->getBitsPel() );
return true;
}
@@ -77,12 +77,5 @@ CalypFrame* AbsoluteFrameDifference::process( std::vector<CalypFrame*> apcFrameL
}
}
}
return m_pcFrameDifference;
}
void AbsoluteFrameDifference::destroy()
{
if( m_pcFrameDifference )
delete m_pcFrameDifference;
m_pcFrameDifference = NULL;
return m_pcFrameDifference.get();
}
+3 -7
View File
@@ -28,19 +28,15 @@
// CalypLib
#include "lib/CalypModuleIf.h"
class AbsoluteFrameDifference : public CalypModuleIf
class AbsoluteFrameDifference : public CalypModuleIf, public CalypModuleInstance<AbsoluteFrameDifference>
{
REGISTER_CLASS_FACTORY( AbsoluteFrameDifference )
private:
CalypFrame* m_pcFrameDifference;
std::unique_ptr<CalypFrame> m_pcFrameDifference;
public:
AbsoluteFrameDifference();
virtual ~AbsoluteFrameDifference() {}
bool create( std::vector<CalypFrame*> apcFrameList );
CalypFrame* process( std::vector<CalypFrame*> apcFrameList );
void destroy();
};
#endif // __FRAMEDIFFERENCE_H__
#endif // __ABSOLUTEFRAMEDIFFERENCE_H__
+6 -10
View File
@@ -13,7 +13,9 @@ SET(Calyp_Mod_SRCS CalypModulesFactory.cpp)
#
# Modules List
#
# SET( MODULE_LOCATION "")
IF(CMAKE_BUILD_TYPE STREQUAL "Debug")
ADD_MODULE_USE_OPENCV(DummyOpencvModule "DummyOpencvModule" VERSION 3.1.0 MODULES core)
ENDIF()
ADD_MODULE(FilterComponentLuma "FilterComponent")
ADD_MODULE(FilterComponentChromaU "FilterComponent")
@@ -34,6 +36,8 @@ ADD_MODULE(WeightedPSNR "WeightedPSNR")
ADD_MODULE(HEVCIntraPrediction "HEVCIntraPrediction")
ADD_MODULE(OptimiseDisplay "OptimiseDisplay")
ADD_MODULE_USE_OPENCV(ShapeDetection "ShapeDetection" VERSION 3.1.0 MODULES core)
ADD_MODULE_USE_OPENCV(
MeasureOpticalFlowDualTVL1
"MeasureOpticalFlowDualTVL1"
@@ -85,15 +89,7 @@ ADD_MODULE_USE_OPENCV(
imgproc
photo
)
ADD_MODULE_USE_OPENCV(
ThreeSixtyDynamicDownsampling
"ThreeSixtyDynamicDownsampling"
VERSION
3.1.0
MODULES
core
imgproc
)
# ADD_MODULE_USE_OPENCV( ThreeSixtyDynamicDownsampling "ThreeSixtyDynamicDownsampling" VERSION 3.1.0 MODULES core imgproc )
ADD_MODULE_USE_OPENCV(
ThreeSixtyNxN
"ThreeSixtyNxN"
+35 -33
View File
@@ -24,9 +24,6 @@
#include "CalypModulesFactory.h"
#include <cstring>
#include <functional>
#include "config.h"
#ifdef USE_DYNLOAD
#include <dlfcn.h>
@@ -37,45 +34,50 @@
// Generated by cmake
#include "ModulesListHeader.h"
CalypModulesFactory::CalypModulesFactory(){ REGISTER_ALL_MODULES }
CalypModulesFactory::CalypModulesFactory()
{
REGISTER_ALL_MODULES
}
void CalypModulesFactory::Register( const char* moduleName, CreateModuleFn pfnCreate )
void CalypModulesFactory::Register( const std::string& moduleName, std::function<CalypModulePtr( void )> pfnCreate )
{
m_FactoryMap[moduleName] = pfnCreate;
}
bool CalypModulesFactory::RegisterDl( const char* dlName )
void CalypModulesFactory::Register( const char* moduleName, std::function<CalypModulePtr( void )> pfnCreate )
{
#ifdef USE_DYNLOAD
void* pHndl = dlopen( dlName, RTLD_NOW );
if( pHndl == NULL )
{
std::cerr << dlerror() << std::endl;
return false;
}
CreateModuleFn pfnCreate = (CreateModuleFn)dlsym( pHndl, "Maker" );
if( pfnCreate == NULL )
{
return false;
}
Register( dlName, pfnCreate );
return true;
#else
return false;
#endif
Register( std::string{ moduleName }, pfnCreate );
}
CalypModulePtr CalypModulesFactory::CreateModule( const char* moduleName )
bool CalypModulesFactory::RegisterDl( const char* dlName )
{
CalypModulesFactoryMap& moduleFactoryMap = CalypModulesFactory::Get()->getMap();
CalypModulesFactoryMap::iterator it = moduleFactoryMap.begin();
for( ; it != moduleFactoryMap.end(); ++it )
// #ifdef USE_DYNLOAD
// void* pHndl = dlopen( dlName, RTLD_NOW );
// if( pHndl == NULL )
// {
// std::cerr << dlerror() << std::endl;
// return false;
// }
// CreateModuleFn pfnCreate = (CreateModuleFn)dlsym( pHndl, "Maker" );
// if( pfnCreate == NULL )
// {
// return false;
// }
// Register( dlName, pfnCreate );
// return true;
// #else
return false;
// #endif
}
CalypModulePtr CalypModulesFactory::CreateModule( const std::string& moduleName ) const
{
const auto& moduleFactoryMap = CalypModulesFactory::Get()->getMap();
if( moduleFactoryMap.contains( moduleName ) )
{
if( !strcmp( it->first, moduleName ) )
{
return it->second();
}
auto createFct = moduleFactoryMap.at( moduleName );
return createFct();
}
return nullptr;
}
}
+6 -10
View File
@@ -25,37 +25,33 @@
#ifndef __CALYPMODULESFACTORY_H__
#define __CALYPMODULESFACTORY_H__
#include <functional>
#include <map>
// CalypLib
#include "lib/CalypModuleIf.h"
#define REGISTER_MODULE( X ) Register( "X", &( X::Create ) );
typedef CalypModulePtr ( *CreateModuleFn )( void );
typedef std::map<const char*, CreateModuleFn> CalypModulesFactoryMap;
// Factory for creating instances of CalypModuleIf
class CalypModulesFactory
{
using CalypModulesFactoryMap = std::map<std::string, std::function<CalypModulePtr( void )>>;
private:
CalypModulesFactory();
CalypModulesFactory& operator=( const CalypModulesFactory& ) { return *this; }
CalypModulesFactoryMap m_FactoryMap;
public:
~CalypModulesFactory() = default;
static CalypModulesFactory* Get()
{
static CalypModulesFactory instance;
return &instance;
}
void Register( const char* moduleName, CreateModuleFn pfnCreate );
void Register( const std::string& moduleName, std::function<CalypModulePtr( void )> pfnCreate );
void Register( const char* moduleName, std::function<CalypModulePtr( void )> pfnCreate );
bool RegisterDl( const char* dlName );
CalypModulePtr CreateModule( const char* moduleName );
CalypModulePtr CreateModule( const std::string& moduleName ) const;
CalypModulesFactoryMap& getMap() { return m_FactoryMap; }
};
+5 -3
View File
@@ -25,18 +25,20 @@
#include "DisparityStereoBM.h"
#include "lib/CalypFrame.h"
DisparityStereoBM::DisparityStereoBM()
{
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2;
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Stereo";
m_pchModuleName = "Disparity-BM";
m_pchModuleLongName = "Block macth based disparity";
m_pchModuleTooltip = "Measure the disparity between two images using the "
"Stereo BM method (OpenCV)";
m_uiNumberOfFrames = 2;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_SKIP_WHILE_PLAY | CLP_MODULE_REQUIRES_NEW_WINDOW | CLP_MODULE_REQUIRES_OPTIONS;
m_uiModuleRequirements = ClpModuleFeature::SkipWhilePlaying | ClpModuleFeature::NewWindow | ClpModuleFeature::Options;
m_cModuleOptions.addOptions() /**/
( "block_size", m_uiBlockSize, "Block Size (positive odd number) [9]" );
@@ -49,7 +51,7 @@ bool DisparityStereoBM::create( std::vector<CalypFrame*> apcFrameList )
{
_BASIC_MODULE_API_2_CHECK_
m_pcDisparityFrame =
new CalypFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), CLP_GRAY );
new CalypFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), ClpPixelFormats::Gray );
if( ( m_uiBlockSize % 2 ) == 0 )
{
m_uiBlockSize++;
+1 -3
View File
@@ -32,10 +32,8 @@
// CalypLib
#include "lib/CalypModuleIf.h"
class DisparityStereoBM : public CalypModuleIf
class DisparityStereoBM : public CalypModuleIf, public CalypModuleInstance<DisparityStereoBM>
{
REGISTER_CLASS_FACTORY( DisparityStereoBM )
private:
CalypFrame* m_pcDisparityFrame;
int m_uiNumberOfDisparities;
+4 -4
View File
@@ -29,14 +29,14 @@ DisparityStereoSGBM::DisparityStereoSGBM()
{
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2;
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Stereo";
m_pchModuleName = "Disparity-SGBM";
m_pchModuleName = "SGBM based disparity";
m_pchModuleLongName = "SGBM based disparity";
m_pchModuleTooltip = "Measure the disparity between two images using the "
"Stereo SGBM method (OpenCV)";
m_uiNumberOfFrames = 2;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_SKIP_WHILE_PLAY | CLP_MODULE_REQUIRES_NEW_WINDOW | CLP_MODULE_REQUIRES_OPTIONS;
m_uiModuleRequirements = ClpModuleFeature::SkipWhilePlaying | ClpModuleFeature::NewWindow | ClpModuleFeature::Options;
m_cModuleOptions.addOptions() /**/
( "block_size", m_uiBlockSize, "Block Size (positive odd number) [3]" )( "HHAlgorithm", m_bUseHH,
@@ -51,7 +51,7 @@ bool DisparityStereoSGBM::create( std::vector<CalypFrame*> apcFrameList )
{
_BASIC_MODULE_API_2_CHECK_
m_pcDisparityFrame =
new CalypFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), CLP_GRAY );
new CalypFrame( apcFrameList[0]->getWidth(), apcFrameList[0]->getHeight(), ClpPixelFormats::Gray );
if( ( m_uiBlockSize % 2 ) == 0 )
{
m_uiBlockSize++;
+1 -3
View File
@@ -51,10 +51,8 @@
// CalypLib
#include "lib/CalypModuleIf.h"
class DisparityStereoSGBM : public CalypModuleIf
class DisparityStereoSGBM : public CalypModuleIf, public CalypModuleInstance<DisparityStereoSGBM>
{
REGISTER_CLASS_FACTORY( DisparityStereoSGBM )
private:
CalypFrame* m_pcDisparityFrame;
bool m_bUseHH;
+1 -3
View File
@@ -32,10 +32,8 @@
// CalypLib
#include "CalypModuleIf.h"
class DisparityStereoVar : public CalypModuleIf
class DisparityStereoVar : public CalypModuleIf, public CalypModuleInstance<DisparityStereoVar>
{
REGISTER_CLASS_FACTORY( DisparityStereoVar )
private:
CalypFrame* m_pcDisparityFrame;
cv::StereoVar m_cStereoVar;
+60
View File
@@ -0,0 +1,60 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file DummyOpencvModule.cpp
*/
#include "DummyOpencvModule.h"
#include <cstdlib>
//#include <opencv2/video/video.hpp>
using cv::Mat;
using cv::Ptr;
using namespace cv::saliency;
DummyOpencvModule::DummyOpencvModule()
{
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Dummy";
m_pchModuleName = "DummyOpencvModule";
m_pchModuleLongName = "Shape detection";
m_pchModuleTooltip = "Detect shapes in images";
m_uiNumberOfFrames = 1;
m_uiModuleRequirements = ClpModuleFeature::NewWindow | ClpModuleFeature::Options;
m_bConvertToGray = false;
m_cModuleOptions.addOptions()( "Convert to Gray", m_bConvertToGray, "Measure a binary saliency map [false]" );
}
cv::Mat* DummyOpencvModule::create_using_opencv( const std::vector<Mat>& apcMatList )
{
m_resultImage = std::make_unique<Mat>( apcMatList[0].rows, apcMatList[0].cols, CV_8UC1 );
return m_resultImage.get();
}
Mat* DummyOpencvModule::process_using_opencv( const std::vector<Mat>& apcMatList )
{
apcMatList[0].copyTo( *m_resultImage );
return m_resultImage.get();
}
+49
View File
@@ -0,0 +1,49 @@
/* This file is a part of Calyp project
* Copyright (C) 2014-2021 by Joao Carreira (jfmcarreira@gmail.com)
* Luis Lucas (luisfrlucas@gmail.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* \file DummyOpencvModule.h
* \brief Modules to detect curves shape
*/
#ifndef __DUMMYOPENCVMODULE_H__
#define __DUMMYOPENCVMODULE_H__
// CalypLib
#include "lib/CalypModuleIf.h"
// OpenCV
#include <opencv2/core/core.hpp>
#include <opencv2/saliency.hpp>
class DummyOpencvModule : public CalypOpenCVModuleIf, public CalypModuleInstance<DummyOpencvModule>
{
using Mat = cv::Mat;
private:
std::unique_ptr<Mat> m_resultImage;
public:
DummyOpencvModule();
virtual ~DummyOpencvModule() = default;
Mat* create_using_opencv( const std::vector<Mat>& apcMatList ) override;
Mat* process_using_opencv( const std::vector<Mat>& apcMatList ) override;
};
#endif // __DUMMYOPENCVMODULE_H__
+2 -2
View File
@@ -28,13 +28,13 @@ EightBitsSampling::EightBitsSampling()
{
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2;
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Conversions";
m_pchModuleName = "BitsResampling";
m_pchModuleLongName = "Re-sampling frame (bpp)";
m_pchModuleTooltip = "Re-sampling frame to a different value of bits per pixel";
m_uiNumberOfFrames = 1;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_OPTIONS;
m_uiModuleRequirements = ClpModuleFeature::Options;
m_cModuleOptions.addOptions() /**/
( "num_bits", m_iNumberOfBits, "Number of bits/pixel (8-16) [8]" );
+1 -3
View File
@@ -28,10 +28,8 @@
// CalypLib
#include "lib/CalypModuleIf.h"
class EightBitsSampling : public CalypModuleIf
class EightBitsSampling : public CalypModuleIf, public CalypModuleInstance<EightBitsSampling>
{
REGISTER_CLASS_FACTORY( EightBitsSampling )
private:
int m_iNumberOfBits;
int m_iBitSifting;
+5 -15
View File
@@ -30,19 +30,16 @@ FilterComponentModule::FilterComponentModule()
{
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2;
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_uiNumberOfFrames = 1;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_NOTHING;
m_uiModuleRequirements = ClpModuleFeature::None;
m_pchModuleCategory = "Filtering";
m_pcFilteredFrame = NULL;
}
bool FilterComponentModule::createFilter( unsigned int uiWidth, unsigned int uiHeight, unsigned int bitsPixel )
{
m_pcFilteredFrame = NULL;
m_pcFilteredFrame = new CalypFrame( uiWidth, uiHeight, CLP_GRAY, bitsPixel );
return true;
m_pcFilteredFrame = std::make_unique<CalypFrame>( uiWidth, uiHeight, ClpPixelFormats::Gray, bitsPixel );
return m_pcFilteredFrame != nullptr;
}
CalypFrame* FilterComponentModule::filterComponent( CalypFrame* InputFrame, int Component )
@@ -51,14 +48,7 @@ CalypFrame* FilterComponentModule::filterComponent( CalypFrame* InputFrame, int
ClpPel*** pppInputPelYUV = InputFrame->getPelBufferYUV();
memcpy( pppOutputPelYUV[CLP_LUMA][0], pppInputPelYUV[Component][0],
m_pcFilteredFrame->getWidth() * m_pcFilteredFrame->getHeight() * sizeof( ClpPel ) );
return m_pcFilteredFrame;
}
void FilterComponentModule::destroy()
{
if( m_pcFilteredFrame )
delete m_pcFilteredFrame;
m_pcFilteredFrame = NULL;
return m_pcFilteredFrame.get();
}
FilterComponentLuma::FilterComponentLuma()
+5 -8
View File
@@ -26,27 +26,26 @@
#define __FILTERCOMPONENT_H__
// CalypLib
#include "lib/CalypFrame.h"
#include "lib/CalypModuleIf.h"
class FilterComponentModule : public CalypModuleIf
{
private:
CalypFrame* m_pcFilteredFrame;
std::unique_ptr<CalypFrame> m_pcFilteredFrame{ nullptr };
public:
FilterComponentModule();
virtual ~FilterComponentModule() {}
bool create( std::vector<CalypFrame*> apcFrameList ) = 0;
CalypFrame* process( std::vector<CalypFrame*> apcFrameList ) = 0;
void destroy();
bool createFilter( unsigned int uiWidth, unsigned int uiHeight, unsigned int bitsPixel );
CalypFrame* filterComponent( CalypFrame* InputFrame, int Component );
};
class FilterComponentLuma : public FilterComponentModule
class FilterComponentLuma : public FilterComponentModule, public CalypModuleInstance<FilterComponentLuma>
{
REGISTER_CLASS_FACTORY( FilterComponentLuma )
public:
FilterComponentLuma();
virtual ~FilterComponentLuma() {}
@@ -54,9 +53,8 @@ public:
CalypFrame* process( std::vector<CalypFrame*> apcFrameList );
};
class FilterComponentChromaU : public FilterComponentModule
class FilterComponentChromaU : public FilterComponentModule, public CalypModuleInstance<FilterComponentChromaU>
{
REGISTER_CLASS_FACTORY( FilterComponentChromaU )
public:
FilterComponentChromaU();
virtual ~FilterComponentChromaU() {}
@@ -64,9 +62,8 @@ public:
CalypFrame* process( std::vector<CalypFrame*> apcFrameList );
};
class FilterComponentChromaV : public FilterComponentModule
class FilterComponentChromaV : public FilterComponentModule, public CalypModuleInstance<FilterComponentChromaV>
{
REGISTER_CLASS_FACTORY( FilterComponentChromaV )
public:
FilterComponentChromaV();
virtual ~FilterComponentChromaV() {}
+3 -3
View File
@@ -27,13 +27,13 @@
FrameBinarization::FrameBinarization()
{
/* Module Definition */
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Utilities";
m_pchModuleLongName = "Binarization";
m_pchModuleName = "FrameBinarization";
m_pchModuleTooltip = "Binarize frame";
m_uiNumberOfFrames = 1;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_OPTIONS;
m_uiModuleRequirements = ClpModuleFeature::Options;
m_cModuleOptions.addOptions() /**/
( "threshold", m_uiThreshold, "Threshold level for binarization (0-255) [128]" );
@@ -45,7 +45,7 @@ FrameBinarization::FrameBinarization()
void FrameBinarization::create( CalypFrame* frame )
{
m_pcBinFrame = NULL;
m_pcBinFrame = new CalypFrame( frame->getWidth(), frame->getHeight(), CLP_GRAY, 8 );
m_pcBinFrame = new CalypFrame( frame->getWidth(), frame->getHeight(), ClpPixelFormats::Gray, 8 );
}
CalypFrame* FrameBinarization::process( CalypFrame* frame )
+1 -3
View File
@@ -28,10 +28,8 @@
// CalypLib
#include "lib/CalypModuleIf.h"
class FrameBinarization : public CalypModuleIf
class FrameBinarization : public CalypModuleIf, public CalypModuleInstance<FrameBinarization>
{
REGISTER_CLASS_FACTORY( FrameBinarization )
private:
CalypFrame* m_pcBinFrame;
unsigned int m_uiThreshold;
+2 -2
View File
@@ -28,13 +28,13 @@ FrameConcatenation::FrameConcatenation()
{
/* Module Definition */
m_iModuleAPI = CLP_MODULE_API_2;
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Utilities";
m_pchModuleLongName = "Frame Concatenation";
m_pchModuleName = "FrameConc";
m_pchModuleTooltip = "Concatenate frames side-by-side";
m_uiNumberOfFrames = 2;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_OPTIONS | CLP_MODULE_REQUIRES_NEW_WINDOW;
m_uiModuleRequirements = ClpModuleFeature::Options | ClpModuleFeature::NewWindow;
m_cModuleOptions.addOptions() /**/
( "ShiftHorizontal", m_iShiftHor, "Amount of pixels to shift in horizontal direction" );
+1 -3
View File
@@ -28,10 +28,8 @@
// CalypLib
#include "lib/CalypModuleIf.h"
class FrameConcatenation : public CalypModuleIf
class FrameConcatenation : public CalypModuleIf, public CalypModuleInstance<FrameConcatenation>
{
REGISTER_CLASS_FACTORY( FrameConcatenation )
private:
CalypFrame* m_pcProcessedFrame;
int m_iShiftHor;
+2 -2
View File
@@ -27,13 +27,13 @@
FrameCrop::FrameCrop()
{
/* Module Definition */
m_iModuleType = CLP_FRAME_PROCESSING_MODULE;
m_iModuleType = ClpModuleType::FrameProcessing;
m_pchModuleCategory = "Utilities";
m_pchModuleLongName = "Crop";
m_pchModuleName = "FrameCrop";
m_pchModuleTooltip = "Crop a region of a frame";
m_uiNumberOfFrames = 1;
m_uiModuleRequirements = CLP_MODULE_REQUIRES_OPTIONS;
m_uiModuleRequirements = ClpModuleFeature::Options;
m_cModuleOptions.addOptions() /**/
( "xPosition", m_uiXPosition, "X cordinate of the left-top corner of the crop region [0]" ) /**/
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more