Arpan Tripathi commited on
Commit
231e998
·
unverified ·
1 Parent(s): 46d811c

VMAF & color/chroma validation with ffmpeg (#127)

Browse files
.gitignore CHANGED
@@ -24,6 +24,7 @@ IQA-PyTorch/
24
  MDTVSFA/
25
  output/
26
  ignore/
 
27
  MANIQA/
28
  frames/
29
  tmp/
 
24
  MDTVSFA/
25
  output/
26
  ignore/
27
+ scoring.md
28
  MANIQA/
29
  frames/
30
  tmp/
bootstrap.sh ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+
4
+ # run this script using `sudo -E ./bootstrap.sh`, otherwise it won't work
5
+ #
6
+ # If you're seeing issues with `dpkg` on platforms like tensordock, wait 15
7
+ # minutes and try running the script again.
8
+ #
9
+ # Once installed to see the autoupdater logs, run
10
+ # `sudo journalctl -fu vision-autoupdater`
11
+ ################################################################################
12
+
13
+ # external vars the user may override
14
+ ################################################################################
15
+ WITH_AUTOUPDATES=${WITH_AUTOUPDATES:-1}
16
+ NVIDIA_DRIVER_VERSION=${NVIDIA_DRIVER_VERSION:-535}
17
+ NO_LAUNCH=${NO_LAUNCH:-0}
18
+
19
+ # internal vars
20
+ ################################################################################
21
+ REBOOT_REQUIRED=0
22
+ export DEBIAN_FRONTEND=noninteractive
23
+
24
+ function echo_() {
25
+ echo "# $@"
26
+ echo "################################################################################"
27
+ }
28
+
29
+ # check for root and setup exit trap
30
+ ################################################################################
31
+ if [[ $(id -u) -ne 0 ]]; then
32
+ echo_ "Please run this script as root."
33
+ exit 1
34
+ fi
35
+
36
+ function on_exit_ {
37
+ echo_ cleaning up...
38
+ apt-mark unhold openssh-server
39
+ }
40
+ trap on_exit_ INT TERM EXIT
41
+
42
+ # setup base files/folders
43
+ ################################################################################
44
+ echo_ setting up base files and folders
45
+ touch $HOME/.bashrc
46
+ chown $SUDO_USER:$SUDO_USER $HOME/.bashrc
47
+ chmod 644 $HOME/.bashrc
48
+
49
+ mkdir -p $HOME/.local/bin
50
+ if ! [[ $(echo $PATH | grep "$HOME/.local/bin") ]]; then
51
+ echo '' >> $HOME/.bashrc
52
+ echo 'export PATH=$HOME/.local/bin:$PATH' >> $HOME/.bashrc
53
+ fi
54
+ chown -R $SUDO_USER:$SUDO_USER $HOME/.local
55
+
56
+ # do not upgrade openssh server whilst installing
57
+ ################################################################################
58
+ apt-mark hold openssh-server
59
+
60
+ # fix anything broken, update stuff, and install base software
61
+ ################################################################################
62
+ echo_ setting up base packages
63
+ apt update -qq
64
+ apt install -y vim git curl wget cron net-tools dnsutils software-properties-common
65
+
66
+ # docker
67
+ ################################################################################
68
+ echo_ checking for docker
69
+ if ! [[ $(which docker) ]]; then
70
+ echo_ docker was not found, installing...
71
+ apt update -qq
72
+ apt install -y docker.io
73
+ systemctl enable --now docker
74
+ fi
75
+
76
+ groupadd docker || true
77
+ usermod -aG docker $SUDO_USER || true
78
+
79
+ # nvidia drivers
80
+ ################################################################################
81
+ echo_ checking for nvidia drivers
82
+ if ! [[ $(which nvidia-smi) ]]; then
83
+ echo_ nvidia drivers were not found, installing...
84
+
85
+ apt purge nvidia-*
86
+ add-apt-repository -y ppa:graphics-drivers/ppa
87
+ apt update -qq
88
+ apt-mark unhold nvidia* libnvidia*
89
+ apt install -y libnvidia-common-$NVIDIA_DRIVER_VERSION libnvidia-gl-$NVIDIA_DRIVER_VERSION nvidia-driver-$NVIDIA_DRIVER_VERSION
90
+ dpkg-query -W --showformat='${Package} ${Status}\n' | grep -v deinstall | awk '{ print $1 }' | grep -E 'nvidia.*-[0-9]+$' | xargs -r -L 1 apt-mark hold
91
+
92
+ # signal to the script that it _should_ reboot the server once done.
93
+ REBOOT_REQUIRED=1
94
+ fi
95
+
96
+ # nvidia/cuda/container-toolkit
97
+ ################################################################################
98
+ echo_ checking for the nvidia container toolkit
99
+ if ! [[ $(command nvidia-ctk) ]]; then
100
+ echo_ the nvidia container toolkit was not found, installing...
101
+ wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-keyring_1.1-1_all.deb
102
+ dpkg -i cuda-keyring_1.1-1_all.deb
103
+ rm cuda-keyring_1.1-1_all.deb
104
+
105
+ apt update -qq
106
+ apt-mark unhold nvidia* libnvidia*
107
+ apt install -y nvidia-container-toolkit
108
+ dpkg-query -W --showformat='${Package} ${Status}\n' | grep -v deinstall | awk '{ print $1 }' | grep -E 'nvidia.*-[0-9]+$' | xargs -r -L 1 apt-mark hold
109
+ fi
110
+
111
+ nvidia-ctk runtime configure --runtime=docker
112
+ systemctl restart docker
113
+
114
+ # python 3.11
115
+ ################################################################################
116
+ echo_ checking for python3.11
117
+ if ! [[ $(which python3.11) ]]; then
118
+ echo_ python3.11 was not found, installing...
119
+ add-apt-repository -y ppa:deadsnakes/ppa
120
+ apt install -y python3.11-full
121
+ python3.11 -m ensurepip
122
+ fi
123
+
124
+ # ensure `python` and `pip` point to the right place
125
+ rm /usr/bin/pip || true
126
+ echo '#!/bin/bash' >> /usr/bin/pip
127
+ echo 'python3.11 -m pip $@' >> /usr/bin/pip
128
+ chmod a+x /usr/bin/pip
129
+
130
+ rm /usr/bin/python || true
131
+ ln -s $(which python3.11) /usr/bin/python
132
+
133
+ # finally, reboot if needed
134
+ ################################################################################
135
+ if [[ REBOOT_REQUIRED -eq 1 ]]; then
136
+ echo_ "bootstrap.sh modified something that requires a reboot. Please SSH back in to this machine after a short while :)"
137
+ shutdown now -r
138
+ else
139
+ echo_ "bootstrap.sh is all done :)"
140
+ fi
docs/validator_setup.md CHANGED
@@ -12,6 +12,33 @@ To achieve optimal results, we recommend the following setup:
12
 
13
  ---
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  ## Install PM2 (Process Manager)
16
 
17
  **PM2** is used to manage and monitor the validator process. If you haven’t installed PM2 yet, follow these steps:
@@ -124,104 +151,19 @@ To enable video quality validation, install **VMAF** by following the steps belo
124
 
125
  ---
126
 
127
- Clone the VMAF repository into the working root directory of your `vidaio-subnet` package. If the `vidaio-subnet` virtual environment is currently active, deactivate it first:
128
 
129
  ```bash
130
  git clone https://github.com/vidAio-subnet/vmaf.git
 
 
131
  cd vmaf
 
 
 
132
  ```
133
 
134
  ---
135
-
136
- ### Step 1: Set Up a Virtual Environment in VMAF directory
137
-
138
- 1. Install `venv` if it’s not already installed:
139
- ```bash
140
- python3 -m venv vmaf-venv
141
- ```
142
-
143
- 2. Activate the virtual environment:
144
- ```bash
145
- source vmaf-venv/bin/activate
146
- ```
147
-
148
- ---
149
-
150
- ### Step 2: Install Dependencies
151
-
152
- 1. Install `meson`:
153
- ```bash
154
- pip install meson
155
- ```
156
-
157
- 2. Install system dependencies:
158
- ```bash
159
- sudo apt-get update
160
- sudo apt-get install nasm ninja-build doxygen xxd
161
- ```
162
- For Ninja, verify whether the package name is `ninja` or `ninja-build` before running the install command.
163
-
164
- ---
165
-
166
- ### Step 3: Compile VMAF
167
-
168
-
169
- 1. Set up the build environment:
170
- ```bash
171
- cd libvmaf
172
- meson setup build --buildtype release -Denable_avx512=true
173
- ```
174
-
175
- 2. Optional flags:
176
- - Use `-Denable_float=true` to enable floating-point feature extractors.
177
- - Use `-Denable_avx512=true` to enable AVX-512 SIMD instructions for faster processing on supported CPUs.
178
- - Use `-Denable_cuda=true` to build with CUDA support (requires `nvcc` and CUDA >= 11).
179
- **Note:** To enable CUDA successfully, ensure `nvcc` and the CUDA driver are installed. Refer to the [CUDA and NVCC setup guide](miner_setup.md#step-2-install-cuda-and-nvcc).
180
- - Use `-Denable_nvtx=true` to enable NVTX marker support for profiling with Nsight Systems.
181
- - **Recommendation:**
182
- We recommend adding `-Denable_avx512=true` to enhance validation speed. If CUDA is available, include the flag `-Denable_cuda=true` But At present, VMAF does not include support for CUDA integration.
183
-
184
- 3. Build the project:
185
- ```bash
186
- ninja -vC build
187
- ```
188
-
189
- ---
190
-
191
- ### Step 4: Test the Build
192
-
193
- Run tests to verify the build:
194
- ```bash
195
- ninja -vC build test
196
- ```
197
-
198
- ---
199
-
200
- ### Step 5: Install VMAF
201
-
202
- Install the library, headers, and the command-line tool:
203
- ```bash
204
- ninja -vC build install
205
- ```
206
-
207
- ---
208
-
209
- ### Step 6: Generate Documentation
210
-
211
- Generate HTML documentation:
212
- ```bash
213
- ninja -vC build doc/html
214
- ```
215
-
216
- ### Step 7: Deactivate vmaf-venv, activate project venv
217
-
218
- ```bash
219
- deactivate
220
- cd ..
221
- cd ..
222
- source venv/bin/activate
223
- ```
224
-
225
  ## Running the Validator with PM2
226
 
227
  To run the validator, use the following command:
 
12
 
13
  ---
14
 
15
+ ## Bootstrap System Dependencies
16
+
17
+ The `bootstrap.sh` script at the repository root automates the installation of core system-level dependencies:
18
+
19
+ - **NVIDIA GPU drivers** (default version 535)
20
+ - **Docker** and the **NVIDIA Container Toolkit**
21
+ - **Python 3.11**
22
+ - Base utilities (git, curl, wget, etc.)
23
+
24
+ Run the script **as root** with the `-E` flag to preserve environment variables:
25
+
26
+ ```bash
27
+ sudo -E ./bootstrap.sh
28
+ ```
29
+
30
+ > **Note:** If you encounter `dpkg` lock issues (common on platforms like TensorDock), wait ~15 minutes and re-run the script. The script will **automatically reboot** the machine if a new NVIDIA driver was installed.
31
+
32
+ #### Optional environment variables
33
+
34
+ | Variable | Default | Description |
35
+ |---|---|---|
36
+ | `NVIDIA_DRIVER_VERSION` | `535` | NVIDIA driver version to install |
37
+
38
+ Once the bootstrap completes (and any reboot finishes), proceed with the rest of this guide.
39
+
40
+ ---
41
+
42
  ## Install PM2 (Process Manager)
43
 
44
  **PM2** is used to manage and monitor the validator process. If you haven’t installed PM2 yet, follow these steps:
 
151
 
152
  ---
153
 
154
+ Clone the VMAF repository into the working root directory of your `vidaio-subnet` package:
155
 
156
  ```bash
157
  git clone https://github.com/vidAio-subnet/vmaf.git
158
+ cp vmaf_utils/Dockerfile vmaf/Dockerfile
159
+ cp vmaf_utils/Dockerfile.ffmpeg vmaf/Dockerfile.ffmpeg
160
  cd vmaf
161
+ git stash && git reset --hard 332dde62838d91d8b5216e9822de58851f2fd64f && git stash apply
162
+ docker build -t vmaf .
163
+ docker build -t vmaf_ffmpeg:latest -f Dockerfile.ffmpeg .
164
  ```
165
 
166
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  ## Running the Validator with PM2
168
 
169
  To run the validator, use the following command:
neurons/validator.py CHANGED
@@ -589,15 +589,16 @@ class Validator(base.BaseValidator):
589
  logger.warning(f"⚠️ Reference video file missing for video_id {video_id}: {reference_video_path}")
590
  reference_video_paths.append(reference_video_path)
591
 
592
- asyncio.create_task(self.score_compressions(uids, responses, payload_urls, reference_video_paths, timestamp, video_ids, uploaded_object_names, vmaf_thresholds, target_codec, codec_mode, target_bitrate, round_id))
593
-
 
594
  batch_processed_time = time.time() - batch_start_time
595
- sleep_time = random.uniform(SLEEP_TIME_LOW, SLEEP_TIME_HIGH) - batch_processed_time
596
 
597
  logger.info(f"Completed compression batch within {batch_processed_time:.2f} seconds")
598
- logger.info(f"Sleeping for 5-6 minutes before next compression batch")
599
 
600
- await asyncio.sleep(sleep_time)
601
 
602
 
603
  async def start_organic_loop(self):
 
589
  logger.warning(f"⚠️ Reference video file missing for video_id {video_id}: {reference_video_path}")
590
  reference_video_paths.append(reference_video_path)
591
 
592
+ # asyncio.create_task(self.score_compressions(uids, responses, payload_urls, reference_video_paths, timestamp, video_ids, uploaded_object_names, vmaf_thresholds, target_codec, codec_mode, target_bitrate, round_id))
593
+ await self.score_compressions(uids, responses, payload_urls, reference_video_paths, timestamp, video_ids, uploaded_object_names, vmaf_thresholds, target_codec, codec_mode, target_bitrate, round_id)
594
+
595
  batch_processed_time = time.time() - batch_start_time
596
+ # sleep_time = random.uniform(SLEEP_TIME_LOW, SLEEP_TIME_HIGH) - batch_processed_time
597
 
598
  logger.info(f"Completed compression batch within {batch_processed_time:.2f} seconds")
599
+ # logger.info(f"Sleeping for 5-6 minutes before next compression batch")
600
 
601
+ # await asyncio.sleep(sleep_time)
602
 
603
 
604
  async def start_organic_loop(self):
services/scoring/server.py CHANGED
@@ -21,7 +21,7 @@ from fastapi import FastAPI, HTTPException
21
  import torchvision.transforms as transforms
22
  from pieapp_metric import calculate_pieapp_score
23
  from vidaio_subnet_core.utilities.storage_client import storage_client
24
- from vmaf_metric import calculate_vmaf, convert_mp4_to_y4m, trim_video
25
  from services.video_scheduler.video_utils import get_trim_video_path, delete_videos_with_fileid
26
  from scoring_function import calculate_compression_score
27
 
@@ -41,6 +41,9 @@ PIEAPP_SAMPLE_COUNT = CONFIG.score.pieapp_sample_count
41
  PIEAPP_THRESHOLD = CONFIG.score.pieapp_threshold
42
  VMAF_SAMPLE_COUNT = CONFIG.score.vmaf_sample_count
43
 
 
 
 
44
  class UpscalingScoringRequest(BaseModel):
45
  """
46
  Request model for upscaling scoring. Contains URLs for distorted videos and the reference video path.
@@ -540,6 +543,275 @@ def validate_chroma_quality_on_frames(ref_frames, dist_frames, threshold=0.7):
540
  logger.error(f"Error validating chroma quality: {e}")
541
  return False, f"Error validating chroma: {str(e)}"
542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
  # Calculate ClipIQA+ inspired score
544
  def calculate_clipiqa_plus_score(frames):
545
  """Calculate ClipIQA+ inspired score for given frames"""
@@ -1517,16 +1789,6 @@ async def score_upscaling_synthetics(request: UpscalingScoringRequest) -> Upscal
1517
  step_time = time.time() - uid_start_time
1518
  logger.info(f"♎️ 5. Validated encoding settings ({encoding_msg}) in {step_time:.2f} seconds.")
1519
 
1520
- random_frames = sorted(random.sample(range(ref_total_frames), min(ref_total_frames, VMAF_SAMPLE_COUNT)))
1521
- logger.info(f"Randomly selected {VMAF_SAMPLE_COUNT} frames for VMAF score: frame list: {random_frames}")
1522
- step_time = time.time() - uid_start_time
1523
- logger.info(f"♎️ 6. Selected random frames for VMAF in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1524
-
1525
- ref_y4m_path = convert_mp4_to_y4m(ref_path, random_frames)
1526
- logger.info("The reference video has been successfully converted to Y4M format.")
1527
- step_time = time.time() - uid_start_time
1528
- logger.info(f"♎️ 7. Converted reference video to Y4M in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1529
-
1530
  if len(dist_url) < 10:
1531
  logger.info(f"Wrong dist download URL: {dist_url}. Assigning score of 0.")
1532
  vmaf_scores.append(0.0)
@@ -1538,14 +1800,14 @@ async def score_upscaling_synthetics(request: UpscalingScoringRequest) -> Upscal
1538
  continue
1539
 
1540
  step_time = time.time() - uid_start_time
1541
- logger.info(f"♎️ 8. Validated distorted video in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1542
 
1543
  # Get frame count using ffprobe (no AV1 warnings)
1544
  dist_total_frames = get_frame_count(dist_path)
1545
 
1546
  logger.info(f"Distorted video has {dist_total_frames} frames.")
1547
  step_time = time.time() - uid_start_time
1548
- logger.info(f"♎️ 9. Retrieved distorted video frame count in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1549
 
1550
  if abs(dist_total_frames - ref_total_frames) > FRAME_TOLERANCE:
1551
  logger.info(
@@ -1561,15 +1823,48 @@ async def score_upscaling_synthetics(request: UpscalingScoringRequest) -> Upscal
1561
  os.unlink(dist_path)
1562
  continue
1563
 
1564
- # Calculate VMAF
 
 
1565
  try:
1566
  vmaf_start = time.time()
1567
- vmaf_score = calculate_vmaf(ref_y4m_path, dist_path, random_frames, neg_model=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1568
  vmaf_calc_time = time.time() - vmaf_start
1569
  logger.info(f"☣️☣️ VMAF calculation took {vmaf_calc_time:.2f} seconds.")
1570
 
1571
  step_time = time.time() - uid_start_time
1572
- logger.info(f"♎️ 10. Completed VMAF calculation in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1573
 
1574
  if vmaf_score is not None:
1575
  vmaf_scores.append(vmaf_score)
@@ -1586,6 +1881,13 @@ async def score_upscaling_synthetics(request: UpscalingScoringRequest) -> Upscal
1586
  reasons.append("failed to calculate VMAF score due to video dimension mismatch")
1587
  logger.error(f"Error calculating VMAF score: {e}")
1588
  continue
 
 
 
 
 
 
 
1589
 
1590
  if vmaf_score / 100 < VMAF_THRESHOLD:
1591
  logger.info(f"VMAF score is too low, giving zero score, current VMAF score: {vmaf_score}")
@@ -1863,22 +2165,51 @@ async def score_compression_synthetics(request: CompressionScoringRequest) -> Co
1863
  compression_rate = 1.0
1864
  logger.info("Reference file size is 0 or distorted file size >= reference, setting compression rate to 1.0")
1865
 
1866
- # Sample frames for VMAF calculation
1867
- random_frames = sorted(random.sample(range(ref_total_frames), min(ref_total_frames, VMAF_SAMPLE_COUNT)))
1868
- logger.info(f"Randomly selected {VMAF_SAMPLE_COUNT} frames for VMAF score: frame list: {random_frames}")
1869
- step_time = time.time() - uid_start_time
1870
- logger.info(f"♎️ 6. Selected random frames for VMAF in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1871
-
1872
- ref_y4m_path = convert_mp4_to_y4m(ref_path, random_frames)
1873
- logger.info("The reference video has been successfully converted to Y4M format.")
1874
- step_time = time.time() - uid_start_time
1875
- logger.info(f"♎️ 7. Converted reference video to Y4M in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1876
-
1877
- # Calculate VMAF and get Y4M paths for validation
1878
  dist_y4m_path = None
 
1879
  try:
1880
  vmaf_start = time.time()
1881
- vmaf_score, dist_y4m_path = calculate_vmaf(ref_y4m_path, dist_path, random_frames, neg_model=True, return_y4m_path=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1882
  vmaf_calc_time = time.time() - vmaf_start
1883
  logger.info(f"☣️☣️ VMAF calculation took {vmaf_calc_time:.2f} seconds.")
1884
 
@@ -1900,52 +2231,95 @@ async def score_compression_synthetics(request: CompressionScoringRequest) -> Co
1900
  if dist_y4m_path and os.path.exists(dist_y4m_path):
1901
  os.unlink(dist_y4m_path)
1902
  continue
1903
-
1904
- # Now reuse the Y4M files for color validation (no redundant conversion!)
1905
- # Extract frames for color validation from Y4M files
1906
- logger.info(f"Extracting frames from Y4M for color validation (reusing VMAF Y4M files)")
1907
- dist_frames = extract_frames_from_y4m(dist_y4m_path)
1908
- step_time = time.time() - uid_start_time
1909
- logger.info(f"♎️ 8.5. Extracted {len(dist_frames)} frames from Y4M for color validation in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1910
-
1911
- # Extract reference frames from Y4M for chroma quality comparison
1912
- ref_frames = extract_frames_from_y4m(ref_y4m_path)
1913
-
1914
- # Validate color channels (grayscale check)
1915
- color_valid, color_reason = validate_color_channels_on_frames(ref_frames, dist_frames)
1916
- if not color_valid:
1917
- logger.error(f"UID {uid}: {color_reason}")
1918
- compression_rates.append(0.9999)
1919
- final_scores.append(0.0)
1920
- reasons.append(f"Color validation failed: {color_reason}")
1921
- if dist_path and os.path.exists(dist_path):
1922
- os.unlink(dist_path)
1923
- if dist_y4m_path and os.path.exists(dist_y4m_path):
1924
- os.unlink(dist_y4m_path)
1925
- continue
1926
-
1927
- logger.info(f"✅ UID {uid}: Color channels validated - {color_reason}")
1928
- step_time = time.time() - uid_start_time
1929
- logger.info(f"♎️ 8.6. Validated color channels in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1930
 
1931
- # Validate chroma quality (prevents partial UV reduction)
1932
- chroma_valid, chroma_reason = validate_chroma_quality_on_frames(
1933
- ref_frames, dist_frames, threshold=0.7
1934
- )
1935
- if not chroma_valid:
1936
- logger.error(f"UID {uid}: {chroma_reason}")
1937
- compression_rates.append(0.9999)
1938
- final_scores.append(0.0)
1939
- reasons.append(f"Chroma validation failed: {chroma_reason}")
1940
- if dist_path and os.path.exists(dist_path):
1941
- os.unlink(dist_path)
1942
- if dist_y4m_path and os.path.exists(dist_y4m_path):
1943
- os.unlink(dist_y4m_path)
1944
- continue
1945
-
1946
- logger.info(f"✅ UID {uid}: Chroma quality validated - {chroma_reason}")
1947
- step_time = time.time() - uid_start_time
1948
- logger.info(f"♎️ 8.7. Validated chroma quality in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1949
 
1950
  # Calculate compression score using the proper formula
1951
  # Check scoring function for details
@@ -2231,22 +2605,18 @@ async def score_organics_upscaling(request: OrganicsUpscalingScoringRequest) ->
2231
 
2232
  # === MAIN SCORING LOGIC ===
2233
  try:
2234
- # Calculate 0.5 second clip duration
2235
- clip_duration = 0.25 # seconds
2236
-
2237
- # Calculate maximum start time to ensure we don't exceed video length
2238
- ref_duration = ref_total_frames / ref_fps
2239
- max_start_time = max(0, ref_duration - clip_duration)
2240
- start_time = random.uniform(0, max_start_time)
2241
-
2242
- logger.info(f"Creating 0.5-second clips starting from {start_time:.2f} seconds")
2243
-
2244
- # Create 0.5-second reference clip
2245
- ref_clip_path = trim_video(ref_path, start_time, clip_duration)
2246
  logger.info(f"Created reference clip: {ref_clip_path}")
2247
-
2248
- # Create 0.5-second distorted clip
2249
- dist_clip_path = trim_video(dist_path, start_time, clip_duration)
2250
  logger.info(f"Created distorted clip: {dist_clip_path}")
2251
 
2252
  # Upscale the reference clip
@@ -2263,18 +2633,31 @@ async def score_organics_upscaling(request: OrganicsUpscalingScoringRequest) ->
2263
  logger.info(f"Distorted ClipIQ score: {dist_clipiqa_score:.4f}")
2264
  logger.info(f"Upscaled reference ClipIQ score: {ref_upscaled_clipiqa_score:.4f}")
2265
 
2266
- # Create Y4M files for VMAF calculation
2267
- logger.info("Creating Y4M files for VMAF calculation...")
2268
- # Get the number of frames in the clips for Y4M conversion using ffprobe
2269
- ref_clip_frames = get_frame_count(ref_upscaled_clip_path)
2270
-
2271
- random_frames = sorted(random.sample(range(ref_clip_frames), min(ref_clip_frames, VMAF_SAMPLE_COUNT)))
2272
-
2273
- ref_y4m_path = convert_mp4_to_y4m(ref_upscaled_clip_path, random_frames)
2274
-
2275
- # Calculate VMAF score
2276
  logger.info("Calculating VMAF score...")
2277
- vmaf_score = calculate_vmaf(ref_y4m_path, dist_clip_path, random_frames, neg_model=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2278
 
2279
  if vmaf_score is None:
2280
  vmaf_score = 0.0
@@ -2518,55 +2901,67 @@ async def score_organics_compression(request: OrganicsCompressionScoringRequest)
2518
  compression_rate = 1.0
2519
  logger.info("Reference file size is 0 or distorted file size >= reference, setting compression rate to 1.0")
2520
 
2521
- # Calculate 0.5 second clip duration for VMAF calculation
2522
- clip_duration = 0.5 # seconds
2523
-
2524
- # Get video FPS to calculate frame-based timing using ffprobe (no AV1 warnings)
2525
  ref_fps = get_video_fps(ref_path)
2526
  logger.info(f"Reference video FPS: {ref_fps}")
2527
-
2528
- # Calculate maximum start time to ensure we don't exceed video length
2529
- ref_duration = ref_total_frames / ref_fps
2530
- max_start_time = max(0, ref_duration - clip_duration)
2531
- start_time = random.uniform(0, max_start_time)
2532
-
2533
- logger.info(f"Creating 0.5-second clips starting from {start_time:.2f} seconds")
2534
  step_time = time.time() - uid_start_time
2535
- logger.info(f"♎️ 6. Selected random start time for video chunks in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2536
 
2537
- # Create 0.5-second reference clip
2538
- # ref_clip_path = trim_video(ref_path, start_time, clip_duration)
2539
- ref_clip_path = ref_path
2540
  logger.info(f"Created reference clip: {ref_clip_path}")
2541
  step_time = time.time() - uid_start_time
2542
  logger.info(f"♎️ 7. Created reference video clip in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2543
 
2544
- # Create 0.5-second distorted clip
2545
- # dist_clip_path = trim_video(dist_path, start_time, clip_duration)
2546
- dist_clip_path = dist_path
2547
  logger.info(f"Created distorted clip: {dist_clip_path}")
2548
  step_time = time.time() - uid_start_time
2549
  logger.info(f"♎️ 8. Created distorted video clip in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2550
 
2551
- # Get the number of frames in the clips for Y4M conversion
2552
-
2553
- # ref_clip_frames = get_frame_count(ref_clip_path)
2554
- ref_clip_frames = ref_total_frames
2555
- logger.info(f"Reference clip has {ref_clip_frames} frames.")
2556
-
2557
-
2558
- # Ensure we don't sample more frames than available
2559
- random_frames = sorted(random.sample(range(ref_clip_frames), min(VMAF_SAMPLE_COUNT, ref_clip_frames)))
2560
- ref_y4m_path = convert_mp4_to_y4m(ref_clip_path, random_frames)
2561
- logger.info("The reference video clip has been successfully converted to Y4M format.")
2562
- step_time = time.time() - uid_start_time
2563
- logger.info(f"♎️ 9. Converted reference video clip to Y4M in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2564
-
2565
- # Calculate VMAF on chunked videos and get Y4M paths for validation
2566
  dist_y4m_path = None
 
2567
  try:
2568
  vmaf_start = time.time()
2569
- vmaf_score, dist_y4m_path = calculate_vmaf(ref_y4m_path, dist_clip_path, random_frames, neg_model=True, return_y4m_path=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2570
  vmaf_calc_time = time.time() - vmaf_start
2571
  logger.info(f"☣️☣️ VMAF calculation took {vmaf_calc_time:.2f} seconds.")
2572
 
@@ -2588,64 +2983,108 @@ async def score_organics_compression(request: OrganicsCompressionScoringRequest)
2588
  if dist_y4m_path and os.path.exists(dist_y4m_path):
2589
  os.unlink(dist_y4m_path)
2590
  continue
2591
-
2592
- # Now reuse the Y4M files for color validation (no redundant conversion!)
2593
- # Extract frames for color validation from Y4M files
2594
- logger.info(f"Extracting frames from Y4M for color validation from clip (reusing VMAF Y4M files)")
2595
- dist_clip_frames = extract_frames_from_y4m(dist_y4m_path)
2596
- step_time = time.time() - uid_start_time
2597
- logger.info(f"♎️ 10.5. Extracted {len(dist_clip_frames)} frames from Y4M for color validation in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2598
 
2599
- # Extract reference frames from Y4M for chroma quality comparison
2600
- ref_clip_frames_data = extract_frames_from_y4m(ref_y4m_path)
2601
-
2602
- # Validate color channels (grayscale check)
2603
- color_valid, color_reason = validate_color_channels_on_frames(ref_clip_frames_data, dist_clip_frames)
2604
- if not color_valid:
2605
- logger.error(f"UID {uid}: {color_reason}")
2606
- # vmaf_scores.append(0.0)
2607
- compression_rates.append(0.9999)
2608
- final_scores.append(0.0)
2609
- reasons.append(f"Color validation failed: {color_reason}")
2610
- if dist_path and os.path.exists(dist_path):
2611
- os.unlink(dist_path)
2612
- if ref_clip_path and os.path.exists(ref_clip_path):
2613
- os.unlink(ref_clip_path)
2614
- if dist_clip_path and os.path.exists(dist_clip_path):
2615
- os.unlink(dist_clip_path)
2616
- if dist_y4m_path and os.path.exists(dist_y4m_path):
2617
- os.unlink(dist_y4m_path)
2618
- continue
2619
-
2620
- logger.info(f"✅ UID {uid}: Color channels validated - {color_reason}")
2621
- step_time = time.time() - uid_start_time
2622
- logger.info(f"♎️ 10.6. Validated color channels in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2623
 
2624
-
2625
-
2626
- # Validate chroma quality (prevents partial UV reduction)
2627
- chroma_valid, chroma_reason = validate_chroma_quality_on_frames(
2628
- ref_clip_frames_data, dist_clip_frames, threshold=0.7
2629
- )
2630
- if not chroma_valid:
2631
- logger.error(f"UID {uid}: {chroma_reason}")
2632
- # vmaf_scores.append(0.0)
2633
- compression_rates.append(0.9999)
2634
- final_scores.append(0.0)
2635
- reasons.append(f"Chroma validation failed: {chroma_reason}")
2636
- if dist_path and os.path.exists(dist_path):
2637
- os.unlink(dist_path)
2638
- if ref_clip_path and os.path.exists(ref_clip_path):
2639
- os.unlink(ref_clip_path)
2640
- if dist_clip_path and os.path.exists(dist_clip_path):
2641
- os.unlink(dist_clip_path)
2642
- if dist_y4m_path and os.path.exists(dist_y4m_path):
2643
- os.unlink(dist_y4m_path)
2644
- continue
2645
-
2646
- logger.info(f"✅ UID {uid}: Chroma quality validated - {chroma_reason}")
2647
- step_time = time.time() - uid_start_time
2648
- logger.info(f"♎️ 10.7. Validated chroma quality in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2649
 
2650
  # Calculate compression score using the proper formula
2651
  # Check scoring function for details
 
21
  import torchvision.transforms as transforms
22
  from pieapp_metric import calculate_pieapp_score
23
  from vidaio_subnet_core.utilities.storage_client import storage_client
24
+ from vmaf_metric import calculate_vmaf, convert_mp4_to_y4m, trim_video, trim_video_select, vmaf_metric_ffmpeg, is_vmaf_ffmpeg_available
25
  from services.video_scheduler.video_utils import get_trim_video_path, delete_videos_with_fileid
26
  from scoring_function import calculate_compression_score
27
 
 
41
  PIEAPP_THRESHOLD = CONFIG.score.pieapp_threshold
42
  VMAF_SAMPLE_COUNT = CONFIG.score.vmaf_sample_count
43
 
44
+ # Check if vmaf_ffmpeg Docker image with libvmaf_cuda is available
45
+ VMAF_FFMPEG_AVAILABLE = is_vmaf_ffmpeg_available()
46
+
47
  class UpscalingScoringRequest(BaseModel):
48
  """
49
  Request model for upscaling scoring. Contains URLs for distorted videos and the reference video path.
 
543
  logger.error(f"Error validating chroma quality: {e}")
544
  return False, f"Error validating chroma: {str(e)}"
545
 
546
+
547
+ def _get_signalstats(video_path, n_subsample=1, start_time=None, duration=None, max_frames=30):
548
+ """
549
+ Run ffmpeg signalstats filter on a video and return per-frame statistics.
550
+ Extracts YAVG (luma average) and SATAVG (saturation average) per frame
551
+ directly from the MP4 — no Y4M conversion needed.
552
+
553
+ Uses CUDA hardware-accelerated decoding when available, falling back to
554
+ CPU if GPU decode fails. Uses metadata=mode=print to ensure stats are
555
+ printed to stderr.
556
+
557
+ FFmpeg processing is bounded by max_frames — FFmpeg stops decoding after
558
+ max_frames frames, so even hour-long videos are fast.
559
+
560
+ Args:
561
+ video_path: Path to input video
562
+ n_subsample: Analyze every Nth frame (1 = all frames, 5 = every 5th frame)
563
+ start_time: Optional start time in seconds (analyze from this point)
564
+ duration: Optional duration in seconds (analyze this many seconds)
565
+ max_frames: Maximum number of frames FFmpeg will decode (default 30).
566
+ FFmpeg stops after this many frames via -frames:v.
567
+
568
+ Returns:
569
+ list of dicts, each with at least 'YAVG' and 'SATAVG' keys.
570
+ """
571
+ # Build filter chain
572
+ if n_subsample > 1:
573
+ vf = f"select='not(mod(n\\,{n_subsample}))',signalstats,metadata=mode=print"
574
+ else:
575
+ vf = "signalstats,metadata=mode=print"
576
+
577
+ # Build seek/duration args (placed before -i for fast input seeking)
578
+ seek_args = []
579
+ if start_time is not None:
580
+ seek_args += ["-ss", str(start_time)]
581
+ if duration is not None:
582
+ seek_args += ["-t", str(duration)]
583
+
584
+ # -frames:v tells FFmpeg to stop after processing this many frames
585
+ frame_limit_args = ["-frames:v", str(max_frames)] if max_frames else []
586
+
587
+ # Try GPU-accelerated decoding first (NVDEC)
588
+ cmd_gpu = [
589
+ "ffmpeg",
590
+ "-hwaccel", "cuda",
591
+ ] + seek_args + [
592
+ "-i", video_path,
593
+ "-vf", vf,
594
+ ] + frame_limit_args + [
595
+ "-f", "null", "-",
596
+ "-hide_banner", "-loglevel", "info",
597
+ ]
598
+
599
+ result = subprocess.run(cmd_gpu, capture_output=True, text=True, timeout=120)
600
+
601
+ # If GPU decode failed, fall back to CPU
602
+ if result.returncode != 0:
603
+ logger.info(f"GPU decode failed for signalstats, falling back to CPU decode")
604
+ cmd_cpu = [
605
+ "ffmpeg",
606
+ ] + seek_args + [
607
+ "-i", video_path,
608
+ "-vf", vf,
609
+ ] + frame_limit_args + [
610
+ "-f", "null", "-",
611
+ "-hide_banner", "-loglevel", "info",
612
+ ]
613
+ result = subprocess.run(cmd_cpu, capture_output=True, text=True, timeout=120)
614
+
615
+ frames = []
616
+ current_frame = {}
617
+
618
+ for line in result.stderr.split('\n'):
619
+ line = line.strip()
620
+
621
+ # New frame boundary: "[Parsed_metadata_1 @ 0x...] frame:N pts:M ..."
622
+ # Lines are prefixed by FFmpeg, so we can't use startswith('frame:')
623
+ if 'frame:' in line and 'pts:' in line:
624
+ # Save the previous frame if it has the keys we need
625
+ if current_frame and 'SATAVG' in current_frame and 'YAVG' in current_frame:
626
+ frames.append(current_frame)
627
+ current_frame = {}
628
+ elif 'lavfi.signalstats.' in line:
629
+ # Parse: "lavfi.signalstats.SATAVG=29.800000"
630
+ parts = line.split('lavfi.signalstats.', 1)
631
+ if len(parts) == 2:
632
+ key_val = parts[1]
633
+ if '=' in key_val:
634
+ key, val = key_val.split('=', 1)
635
+ try:
636
+ current_frame[key] = float(val)
637
+ except ValueError:
638
+ pass
639
+
640
+ # Don't forget the last frame
641
+ if current_frame and 'SATAVG' in current_frame and 'YAVG' in current_frame:
642
+ frames.append(current_frame)
643
+
644
+ if not frames:
645
+ logger.warning(
646
+ f"signalstats returned 0 frames for {video_path}. "
647
+ f"FFmpeg returncode={result.returncode}, stderr length={len(result.stderr)}"
648
+ )
649
+ else:
650
+ logger.info(f"signalstats collected {len(frames)} frames for {os.path.basename(video_path)}")
651
+
652
+ return frames
653
+
654
+
655
+ def validate_color_channels_ffmpeg(
656
+ ref_stats,
657
+ dist_stats,
658
+ max_gray_ratio=0.50,
659
+ brightness_threshold=20.0,
660
+ ref_sat_threshold=6.0,
661
+ dist_sat_threshold=4.0,
662
+ min_checked_frames=3,
663
+ ):
664
+ """
665
+ FFmpeg-based color validation using pre-computed signalstats.
666
+ Detects grayscale conversion by comparing per-frame saturation.
667
+
668
+ Uses the same logic as validate_color_channels_on_frames:
669
+ - Skip dark reference frames (YAVG < brightness_threshold)
670
+ - Skip naturally grayscale reference frames (SATAVG < ref_sat_threshold)
671
+ - Count distorted frames with low saturation (SATAVG < dist_sat_threshold)
672
+ - Fail if too many distorted frames lost color
673
+
674
+ Args:
675
+ ref_stats: Pre-computed signalstats for reference video (from _get_signalstats)
676
+ dist_stats: Pre-computed signalstats for distorted video (from _get_signalstats)
677
+ max_gray_ratio: Max fraction of frames allowed with reduced color
678
+ brightness_threshold: Min YAVG to consider a ref frame
679
+ ref_sat_threshold: Min ref SATAVG to consider frame as colorful
680
+ dist_sat_threshold: Max dist SATAVG to classify as gray
681
+ min_checked_frames: Min evaluated frames for strict ratio validation
682
+
683
+ Returns:
684
+ tuple: (is_valid, reason)
685
+ """
686
+ try:
687
+
688
+ if not ref_stats or not dist_stats:
689
+ return False, "No frames available for color validation (signalstats)"
690
+
691
+ checked_frames = 0
692
+ low_color_frames = 0
693
+
694
+ for i, (ref_s, dist_s) in enumerate(zip(ref_stats, dist_stats)):
695
+ ref_yavg = ref_s.get('YAVG', 0)
696
+ ref_satavg = ref_s.get('SATAVG', 0)
697
+ dist_satavg = dist_s.get('SATAVG', 0)
698
+
699
+ # Skip very dark reference frames
700
+ if ref_yavg < brightness_threshold:
701
+ continue
702
+
703
+ # Skip naturally grayscale reference frames
704
+ if ref_satavg < ref_sat_threshold:
705
+ continue
706
+
707
+ checked_frames += 1
708
+
709
+ # Count distorted frames with very low saturation
710
+ if dist_satavg < dist_sat_threshold:
711
+ low_color_frames += 1
712
+ logger.debug(
713
+ f"Frame {i}: reduced saturation detected "
714
+ f"(ref_sat={ref_satavg:.2f}, dist_sat={dist_satavg:.2f})"
715
+ )
716
+
717
+ if checked_frames == 0:
718
+ return True, (
719
+ "No reference frames with sufficient color information were found; "
720
+ "color validation was skipped"
721
+ )
722
+
723
+ low_color_ratio = low_color_frames / checked_frames
724
+
725
+ logger.info(
726
+ "Color validation (ffmpeg) summary: "
727
+ f"{low_color_frames}/{checked_frames} frames with reduced saturation "
728
+ f"({low_color_ratio:.2%}); allowed maximum {max_gray_ratio:.2%}"
729
+ )
730
+
731
+ if low_color_ratio > max_gray_ratio:
732
+ return False, (
733
+ f"Color preservation failed: {low_color_ratio:.1%} of evaluated frames "
734
+ f"exhibit reduced saturation (>{max_gray_ratio:.0%} allowed)"
735
+ )
736
+
737
+ return True, (
738
+ f"Color preservation validated: {low_color_ratio:.1%} of evaluated frames "
739
+ f"exhibit reduced saturation (≤{max_gray_ratio:.0%} allowed)"
740
+ )
741
+
742
+ except Exception as e:
743
+ logger.error(f"Error during ffmpeg color validation: {e}")
744
+ return False, f"Error during color validation: {str(e)}"
745
+
746
+
747
+ def validate_chroma_quality_ffmpeg(ref_stats, dist_stats, threshold=0.7):
748
+ """
749
+ FFmpeg-based chroma validation using pre-computed signalstats.
750
+ Detects partial UV channel reduction by comparing saturation energy.
751
+
752
+ Uses SATAVG² as a proxy for chroma energy (var(U) + var(V)),
753
+ then computes the ratio: dist_energy / ref_energy per frame.
754
+
755
+ Corner cases handled:
756
+ - Ref frames with near-zero saturation (naturally B&W) are skipped
757
+ - If all frames are low-energy, validation passes (content is valid B&W)
758
+
759
+ Args:
760
+ ref_stats: Pre-computed signalstats for reference video (from _get_signalstats)
761
+ dist_stats: Pre-computed signalstats for distorted video (from _get_signalstats)
762
+ threshold: Minimum acceptable chroma energy ratio (0.0-1.0)
763
+
764
+ Returns:
765
+ tuple: (is_valid, reason)
766
+ """
767
+ try:
768
+ if not ref_stats or not dist_stats:
769
+ return False, "No frames available for chroma validation (signalstats)"
770
+
771
+ if abs(len(ref_stats) - len(dist_stats)) > FRAME_TOLERANCE:
772
+ return False, (
773
+ f"Frame count mismatch between reference and distorted: "
774
+ f"{len(ref_stats)} vs {len(dist_stats)}"
775
+ )
776
+
777
+ chroma_ratios = []
778
+ low_energy_threshold = 1.0 # Min SATAVG to consider (filters flat/black frames)
779
+
780
+ for i, (ref_s, dist_s) in enumerate(zip(ref_stats, dist_stats)):
781
+ ref_satavg = ref_s.get('SATAVG', 0)
782
+ dist_satavg = dist_s.get('SATAVG', 0)
783
+
784
+ # Skip frames with very low saturation in reference (B&W or flat content)
785
+ if ref_satavg < low_energy_threshold:
786
+ logger.debug(f"Frame {i} has low ref saturation ({ref_satavg:.3f}), skipping")
787
+ continue
788
+
789
+ # Use SATAVG² as proxy for chroma energy (analogous to var(U) + var(V))
790
+ ref_energy = ref_satavg ** 2
791
+ dist_energy = dist_satavg ** 2
792
+ chroma_ratio = dist_energy / ref_energy
793
+ chroma_ratios.append(chroma_ratio)
794
+ logger.debug(f"Frame {i} chroma ratio: {chroma_ratio:.3f}")
795
+
796
+ if not chroma_ratios:
797
+ logger.info("All frames have low saturation (e.g., B&W content), skipping chroma validation")
798
+ return True, "Chroma validation skipped (low-saturation content)"
799
+
800
+ avg_chroma_ratio = float(np.mean(chroma_ratios))
801
+ logger.info(f"Average chroma quality ratio (ffmpeg): {avg_chroma_ratio:.3f}, Threshold: {threshold}")
802
+
803
+ if avg_chroma_ratio < threshold:
804
+ return False, (
805
+ f"Chroma quality too low: {avg_chroma_ratio:.3f} < {threshold} "
806
+ f"(UV channels reduced/degraded)"
807
+ )
808
+
809
+ return True, f"Chroma quality validated: {avg_chroma_ratio:.3f}"
810
+
811
+ except Exception as e:
812
+ logger.error(f"Error validating chroma quality (ffmpeg): {e}")
813
+ return False, f"Error validating chroma: {str(e)}"
814
+
815
  # Calculate ClipIQA+ inspired score
816
  def calculate_clipiqa_plus_score(frames):
817
  """Calculate ClipIQA+ inspired score for given frames"""
 
1789
  step_time = time.time() - uid_start_time
1790
  logger.info(f"♎️ 5. Validated encoding settings ({encoding_msg}) in {step_time:.2f} seconds.")
1791
 
 
 
 
 
 
 
 
 
 
 
1792
  if len(dist_url) < 10:
1793
  logger.info(f"Wrong dist download URL: {dist_url}. Assigning score of 0.")
1794
  vmaf_scores.append(0.0)
 
1800
  continue
1801
 
1802
  step_time = time.time() - uid_start_time
1803
+ logger.info(f"♎️ 6. Validated distorted video in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1804
 
1805
  # Get frame count using ffprobe (no AV1 warnings)
1806
  dist_total_frames = get_frame_count(dist_path)
1807
 
1808
  logger.info(f"Distorted video has {dist_total_frames} frames.")
1809
  step_time = time.time() - uid_start_time
1810
+ logger.info(f"♎️ 7. Retrieved distorted video frame count in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1811
 
1812
  if abs(dist_total_frames - ref_total_frames) > FRAME_TOLERANCE:
1813
  logger.info(
 
1823
  os.unlink(dist_path)
1824
  continue
1825
 
1826
+ # Calculate VMAF — Docker-first with Y4M fallback
1827
+ # ref_clip_vmaf_path = None
1828
+ # dist_clip_vmaf_path = None
1829
  try:
1830
  vmaf_start = time.time()
1831
+
1832
+ # Trim 1-second clips for VMAF calculation (frame-accurate)
1833
+ ref_fps = get_video_fps(ref_path) or 30.0
1834
+ # vmaf_num_frames = int(ref_fps) # 1 second worth of frames
1835
+ # max_start_frame = max(0, ref_total_frames - vmaf_num_frames)
1836
+ # vmaf_start_frame = random.randint(0, max_start_frame)
1837
+
1838
+ # ref_clip_vmaf_path = trim_video_select(ref_path, vmaf_start_frame, vmaf_num_frames)
1839
+ # dist_clip_vmaf_path = trim_video_select(dist_path, vmaf_start_frame, vmaf_num_frames)
1840
+ # logger.info(f"Trimmed {vmaf_num_frames} frames starting at frame {vmaf_start_frame} for VMAF calculation")
1841
+
1842
+ if VMAF_FFMPEG_AVAILABLE:
1843
+ try:
1844
+ logger.info("Attempting Docker-based VMAF calculation (libvmaf_cuda)...")
1845
+ vmaf_score = vmaf_metric_ffmpeg(
1846
+ dist_path=dist_path,
1847
+ ref_path=ref_path,
1848
+ skip_frames=np.random.randint(0, ref_fps),
1849
+ n_subsample=np.random.randint(20, 30),
1850
+ )
1851
+ logger.info(f"Docker VMAF calculation succeeded: {vmaf_score}")
1852
+ except Exception as docker_err:
1853
+ logger.warning(f"Docker VMAF failed, falling back to Y4M: {docker_err}")
1854
+ vmaf_score = None # trigger fallback below
1855
+
1856
+ if not VMAF_FFMPEG_AVAILABLE or vmaf_score is None:
1857
+ # Fallback: Y4M-based VMAF calculation
1858
+ logger.info("Using Y4M-based VMAF calculation (fallback)...")
1859
+ random_frames = sorted(random.sample(range(ref_total_frames), min(ref_total_frames, VMAF_SAMPLE_COUNT)))
1860
+ ref_y4m_path = convert_mp4_to_y4m(ref_path, random_frames)
1861
+ vmaf_score = calculate_vmaf(ref_y4m_path, dist_path, random_frames, neg_model=False)
1862
+
1863
  vmaf_calc_time = time.time() - vmaf_start
1864
  logger.info(f"☣️☣️ VMAF calculation took {vmaf_calc_time:.2f} seconds.")
1865
 
1866
  step_time = time.time() - uid_start_time
1867
+ logger.info(f"♎️ 8. Completed VMAF calculation in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
1868
 
1869
  if vmaf_score is not None:
1870
  vmaf_scores.append(vmaf_score)
 
1881
  reasons.append("failed to calculate VMAF score due to video dimension mismatch")
1882
  logger.error(f"Error calculating VMAF score: {e}")
1883
  continue
1884
+ finally:
1885
+ pass
1886
+ # Clean up trimmed VMAF clips
1887
+ # if ref_clip_vmaf_path and os.path.exists(ref_clip_vmaf_path):
1888
+ # os.unlink(ref_clip_vmaf_path)
1889
+ # if dist_clip_vmaf_path and os.path.exists(dist_clip_vmaf_path):
1890
+ # os.unlink(dist_clip_vmaf_path)
1891
 
1892
  if vmaf_score / 100 < VMAF_THRESHOLD:
1893
  logger.info(f"VMAF score is too low, giving zero score, current VMAF score: {vmaf_score}")
 
2165
  compression_rate = 1.0
2166
  logger.info("Reference file size is 0 or distorted file size >= reference, setting compression rate to 1.0")
2167
 
2168
+ # Calculate VMAF — Docker-first with Y4M fallback
2169
+ # Docker path: FFmpeg signalstats for color/chroma validation (no Y4M needed)
2170
+ # Fallback path: Y4M-based VMAF + Y4M-based color/chroma validation
2171
+ # ref_clip_vmaf_path = None
2172
+ # dist_clip_vmaf_path = None
 
 
 
 
 
 
 
2173
  dist_y4m_path = None
2174
+ used_docker_vmaf = False
2175
  try:
2176
  vmaf_start = time.time()
2177
+ vmaf_score = None
2178
+
2179
+ # Trim 1-second clips for VMAF calculation (frame-accurate)
2180
+ ref_fps_val = get_video_fps(ref_path) or 30.0
2181
+ vmaf_num_frames = int(ref_fps_val) # 1 second worth of frames
2182
+ max_start_frame = max(0, ref_total_frames - vmaf_num_frames)
2183
+ vmaf_start_frame = random.randint(0, max_start_frame)
2184
+
2185
+ # ref_clip_vmaf_path = trim_video_select(ref_path, vmaf_start_frame, vmaf_num_frames)
2186
+ # dist_clip_vmaf_path = trim_video_select(dist_path, vmaf_start_frame, vmaf_num_frames)
2187
+ # logger.info(f"Trimmed {vmaf_num_frames} frames starting at frame {vmaf_start_frame} for VMAF calculation")
2188
+
2189
+ if VMAF_FFMPEG_AVAILABLE:
2190
+ try:
2191
+ logger.info("Attempting Docker-based VMAF calculation (libvmaf_cuda)...")
2192
+ vmaf_score = vmaf_metric_ffmpeg(
2193
+ dist_path=dist_path,
2194
+ ref_path=ref_path,
2195
+ neg_model=True,
2196
+ # skip_frames=np.random.randint(0, ref_fps_val),
2197
+ # n_subsample=np.random.randint(20, 30),
2198
+ )
2199
+ logger.info(f"Docker VMAF calculation succeeded: {vmaf_score}")
2200
+ used_docker_vmaf = True
2201
+ except Exception as docker_err:
2202
+ logger.warning(f"Docker VMAF failed, falling back to Y4M: {docker_err}")
2203
+ vmaf_score = None
2204
+
2205
+ if vmaf_score is None:
2206
+ # Fallback: Y4M-based VMAF calculation
2207
+ logger.info("Using Y4M-based VMAF calculation (fallback)...")
2208
+ random_frames = sorted(random.sample(range(ref_total_frames), min(ref_total_frames, VMAF_SAMPLE_COUNT)))
2209
+ ref_y4m_path = convert_mp4_to_y4m(ref_path, random_frames)
2210
+ logger.info("The reference video has been successfully converted to Y4M format.")
2211
+ vmaf_score, dist_y4m_path = calculate_vmaf(ref_y4m_path, dist_path, random_frames, neg_model=True, return_y4m_path=True)
2212
+
2213
  vmaf_calc_time = time.time() - vmaf_start
2214
  logger.info(f"☣️☣️ VMAF calculation took {vmaf_calc_time:.2f} seconds.")
2215
 
 
2231
  if dist_y4m_path and os.path.exists(dist_y4m_path):
2232
  os.unlink(dist_y4m_path)
2233
  continue
2234
+ finally:
2235
+ pass
2236
+ # Clean up trimmed VMAF clips — signalstats runs on originals, not clips
2237
+ # if ref_clip_vmaf_path and os.path.exists(ref_clip_vmaf_path):
2238
+ # os.unlink(ref_clip_vmaf_path)
2239
+ # if dist_clip_vmaf_path and os.path.exists(dist_clip_vmaf_path):
2240
+ # os.unlink(dist_clip_vmaf_path)
2241
+
2242
+ # === COLOR / CHROMA VALIDATION ===
2243
+ if used_docker_vmaf:
2244
+ # Docker path: use FFmpeg signalstats on original videos with time bounds (no Y4M needed)
2245
+ logger.info("Using FFmpeg signalstats for color/chroma validation (no Y4M conversion)")
2246
+
2247
+ # Compute signalstats once on original videos (not trimmed clips — avoids keyframe issues)
2248
+ # Convert frame-based position back to time for signalstats
2249
+ signalstats_start_time = vmaf_start_frame / ref_fps_val
2250
+ signalstats_duration = vmaf_num_frames / ref_fps_val
2251
+ ref_signal_stats = _get_signalstats(ref_path, start_time=signalstats_start_time, duration=signalstats_duration)
2252
+ dist_signal_stats = _get_signalstats(dist_path, start_time=signalstats_start_time, duration=signalstats_duration)
2253
+
2254
+ # Color validation (grayscale detection)
2255
+ color_valid, color_reason = validate_color_channels_ffmpeg(ref_signal_stats, dist_signal_stats)
2256
+ if not color_valid:
2257
+ logger.error(f"UID {uid}: {color_reason}")
2258
+ compression_rates.append(0.9999)
2259
+ final_scores.append(0.0)
2260
+ reasons.append(f"Color validation failed: {color_reason}")
2261
+ continue
2262
+
2263
+ logger.info(f"✅ UID {uid}: Color channels validated (ffmpeg) - {color_reason}")
2264
+ step_time = time.time() - uid_start_time
2265
+ logger.info(f"♎️ 8.6. Validated color channels in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2266
+
2267
+ # Chroma validation (UV reduction detection)
2268
+ chroma_valid, chroma_reason = validate_chroma_quality_ffmpeg(ref_signal_stats, dist_signal_stats, threshold=0.7)
2269
+ if not chroma_valid:
2270
+ logger.error(f"UID {uid}: {chroma_reason}")
2271
+ compression_rates.append(0.9999)
2272
+ final_scores.append(0.0)
2273
+ reasons.append(f"Chroma validation failed: {chroma_reason}")
2274
+ continue
2275
+
2276
+ logger.info(f"✅ UID {uid}: Chroma quality validated (ffmpeg) - {chroma_reason}")
2277
+ step_time = time.time() - uid_start_time
2278
+ logger.info(f"♎️ 8.7. Validated chroma quality in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2279
+ else:
2280
+ # Fallback path: use Y4M-based validation (existing approach)
2281
+ logger.info("Extracting frames from Y4M for color validation (reusing VMAF Y4M files)")
2282
+ dist_frames = extract_frames_from_y4m(dist_y4m_path)
2283
+ step_time = time.time() - uid_start_time
2284
+ logger.info(f"♎️ 8.5. Extracted {len(dist_frames)} frames from Y4M for color validation in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2285
+
2286
+ ref_frames = extract_frames_from_y4m(ref_y4m_path)
2287
+
2288
+ # Validate color channels (grayscale check)
2289
+ color_valid, color_reason = validate_color_channels_on_frames(ref_frames, dist_frames)
2290
+ if not color_valid:
2291
+ logger.error(f"UID {uid}: {color_reason}")
2292
+ compression_rates.append(0.9999)
2293
+ final_scores.append(0.0)
2294
+ reasons.append(f"Color validation failed: {color_reason}")
2295
+ if dist_path and os.path.exists(dist_path):
2296
+ os.unlink(dist_path)
2297
+ if dist_y4m_path and os.path.exists(dist_y4m_path):
2298
+ os.unlink(dist_y4m_path)
2299
+ continue
2300
+
2301
+ logger.info(f"✅ UID {uid}: Color channels validated - {color_reason}")
2302
+ step_time = time.time() - uid_start_time
2303
+ logger.info(f"♎️ 8.6. Validated color channels in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2304
 
2305
+ # Validate chroma quality (prevents partial UV reduction)
2306
+ chroma_valid, chroma_reason = validate_chroma_quality_on_frames(
2307
+ ref_frames, dist_frames, threshold=0.7
2308
+ )
2309
+ if not chroma_valid:
2310
+ logger.error(f"UID {uid}: {chroma_reason}")
2311
+ compression_rates.append(0.9999)
2312
+ final_scores.append(0.0)
2313
+ reasons.append(f"Chroma validation failed: {chroma_reason}")
2314
+ if dist_path and os.path.exists(dist_path):
2315
+ os.unlink(dist_path)
2316
+ if dist_y4m_path and os.path.exists(dist_y4m_path):
2317
+ os.unlink(dist_y4m_path)
2318
+ continue
2319
+
2320
+ logger.info(f"✅ UID {uid}: Chroma quality validated - {chroma_reason}")
2321
+ step_time = time.time() - uid_start_time
2322
+ logger.info(f"♎️ 8.7. Validated chroma quality in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2323
 
2324
  # Calculate compression score using the proper formula
2325
  # Check scoring function for details
 
2605
 
2606
  # === MAIN SCORING LOGIC ===
2607
  try:
2608
+ # Calculate 0.25 second clip using frame-accurate extraction
2609
+ clip_num_frames = max(1, int(ref_fps * 0.25)) # 0.25 seconds worth of frames
2610
+ max_start_frame = max(0, ref_total_frames - clip_num_frames)
2611
+ start_frame = random.randint(0, max_start_frame)
2612
+
2613
+ logger.info(f"Creating {clip_num_frames}-frame clips starting at frame {start_frame}")
2614
+
2615
+ # Frame-accurate extraction for both ref and dist
2616
+ ref_clip_path = trim_video_select(ref_path, start_frame, clip_num_frames)
 
 
 
2617
  logger.info(f"Created reference clip: {ref_clip_path}")
2618
+
2619
+ dist_clip_path = trim_video_select(dist_path, start_frame, clip_num_frames)
 
2620
  logger.info(f"Created distorted clip: {dist_clip_path}")
2621
 
2622
  # Upscale the reference clip
 
2633
  logger.info(f"Distorted ClipIQ score: {dist_clipiqa_score:.4f}")
2634
  logger.info(f"Upscaled reference ClipIQ score: {ref_upscaled_clipiqa_score:.4f}")
2635
 
2636
+ # Calculate VMAF — Docker-first with Y4M fallback
 
 
 
 
 
 
 
 
 
2637
  logger.info("Calculating VMAF score...")
2638
+ vmaf_score = None
2639
+
2640
+ if VMAF_FFMPEG_AVAILABLE and ref_upscaled_clip_path and dist_clip_path:
2641
+ try:
2642
+ logger.info("Attempting Docker-based VMAF calculation (libvmaf_cuda)...")
2643
+ vmaf_score = vmaf_metric_ffmpeg(
2644
+ dist_path=dist_clip_path,
2645
+ ref_path=ref_upscaled_clip_path,
2646
+ skip_frames=0,
2647
+ n_subsample=1,
2648
+ )
2649
+ logger.info(f"Docker VMAF calculation succeeded: {vmaf_score}")
2650
+ except Exception as docker_err:
2651
+ logger.warning(f"Docker VMAF failed, falling back to Y4M: {docker_err}")
2652
+ vmaf_score = None
2653
+
2654
+ if vmaf_score is None:
2655
+ # Fallback: Y4M-based VMAF calculation
2656
+ logger.info("Using Y4M-based VMAF calculation (fallback)...")
2657
+ ref_clip_frames = get_frame_count(ref_upscaled_clip_path)
2658
+ random_frames = sorted(random.sample(range(ref_clip_frames), min(ref_clip_frames, VMAF_SAMPLE_COUNT)))
2659
+ ref_y4m_path = convert_mp4_to_y4m(ref_upscaled_clip_path, random_frames)
2660
+ vmaf_score = calculate_vmaf(ref_y4m_path, dist_clip_path, random_frames, neg_model=False)
2661
 
2662
  if vmaf_score is None:
2663
  vmaf_score = 0.0
 
2901
  compression_rate = 1.0
2902
  logger.info("Reference file size is 0 or distorted file size >= reference, setting compression rate to 1.0")
2903
 
2904
+ # Calculate 0.5 second clip using frame-accurate extraction
 
 
 
2905
  ref_fps = get_video_fps(ref_path)
2906
  logger.info(f"Reference video FPS: {ref_fps}")
2907
+
2908
+ clip_num_frames = max(1, int(ref_fps * 0.5)) # 0.5 seconds worth of frames
2909
+ max_start_frame = max(0, ref_total_frames - clip_num_frames)
2910
+ start_frame = random.randint(0, max_start_frame)
2911
+
2912
+ logger.info(f"Creating {clip_num_frames}-frame clips starting at frame {start_frame}")
 
2913
  step_time = time.time() - uid_start_time
2914
+ logger.info(f"♎️ 6. Selected random start frame for video chunks in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2915
 
2916
+ # Create reference clip (frame-accurate)
2917
+ ref_clip_path = trim_video_select(ref_path, start_frame, clip_num_frames)
 
2918
  logger.info(f"Created reference clip: {ref_clip_path}")
2919
  step_time = time.time() - uid_start_time
2920
  logger.info(f"♎️ 7. Created reference video clip in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2921
 
2922
+ # Create distorted clip (frame-accurate)
2923
+ dist_clip_path = trim_video_select(dist_path, start_frame, clip_num_frames)
 
2924
  logger.info(f"Created distorted clip: {dist_clip_path}")
2925
  step_time = time.time() - uid_start_time
2926
  logger.info(f"♎️ 8. Created distorted video clip in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2927
 
2928
+ # Calculate VMAF — Docker-first with Y4M fallback
2929
+ # Docker path: FFmpeg signalstats for color/chroma validation (no Y4M needed)
2930
+ # Fallback path: Y4M-based VMAF + Y4M-based color/chroma validation
 
 
 
 
 
 
 
 
 
 
 
 
2931
  dist_y4m_path = None
2932
+ used_docker_vmaf = False
2933
  try:
2934
  vmaf_start = time.time()
2935
+ vmaf_score = None
2936
+
2937
+ if VMAF_FFMPEG_AVAILABLE and ref_clip_path and dist_clip_path:
2938
+ try:
2939
+ logger.info("Attempting Docker-based VMAF calculation (libvmaf_cuda)...")
2940
+ vmaf_score = vmaf_metric_ffmpeg(
2941
+ dist_path=dist_clip_path,
2942
+ ref_path=ref_clip_path,
2943
+ skip_frames=0,
2944
+ n_subsample=1,
2945
+ neg_model=True,
2946
+ )
2947
+ logger.info(f"Docker VMAF calculation succeeded: {vmaf_score}")
2948
+ used_docker_vmaf = True
2949
+ except Exception as docker_err:
2950
+ logger.warning(f"Docker VMAF failed, falling back to Y4M: {docker_err}")
2951
+ vmaf_score = None
2952
+
2953
+ if vmaf_score is None:
2954
+ # Fallback: Y4M-based VMAF calculation
2955
+ logger.info("Using Y4M-based VMAF calculation (fallback)...")
2956
+ ref_clip_frames = get_frame_count(ref_clip_path)
2957
+ logger.info(f"Reference clip has {ref_clip_frames} frames.")
2958
+ random_frames = sorted(random.sample(range(ref_clip_frames), min(VMAF_SAMPLE_COUNT, ref_clip_frames)))
2959
+ ref_y4m_path = convert_mp4_to_y4m(ref_clip_path, random_frames)
2960
+ logger.info("The reference video clip has been successfully converted to Y4M format.")
2961
+ step_time = time.time() - uid_start_time
2962
+ logger.info(f"♎️ 9. Converted reference video clip to Y4M in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
2963
+ vmaf_score, dist_y4m_path = calculate_vmaf(ref_y4m_path, dist_clip_path, random_frames, neg_model=True, return_y4m_path=True)
2964
+
2965
  vmaf_calc_time = time.time() - vmaf_start
2966
  logger.info(f"☣️☣️ VMAF calculation took {vmaf_calc_time:.2f} seconds.")
2967
 
 
2983
  if dist_y4m_path and os.path.exists(dist_y4m_path):
2984
  os.unlink(dist_y4m_path)
2985
  continue
 
 
 
 
 
 
 
2986
 
2987
+ # === COLOR / CHROMA VALIDATION ===
2988
+ if used_docker_vmaf:
2989
+ # Docker path: use FFmpeg signalstats on original videos with time bounds (no Y4M needed)
2990
+ logger.info("Using FFmpeg signalstats for color/chroma validation (no Y4M conversion)")
2991
+
2992
+ # Compute signalstats once on original videos (not trimmed clips — avoids keyframe issues)
2993
+ # Convert frame-based position back to time for signalstats
2994
+ signalstats_start_time = start_frame / ref_fps
2995
+ signalstats_duration = clip_num_frames / ref_fps
2996
+ ref_signal_stats = _get_signalstats(ref_path, start_time=signalstats_start_time, duration=signalstats_duration)
2997
+ dist_signal_stats = _get_signalstats(dist_path, start_time=signalstats_start_time, duration=signalstats_duration)
2998
+
2999
+ # Color validation (grayscale detection)
3000
+ color_valid, color_reason = validate_color_channels_ffmpeg(ref_signal_stats, dist_signal_stats)
3001
+ if not color_valid:
3002
+ logger.error(f"UID {uid}: {color_reason}")
3003
+ compression_rates.append(0.9999)
3004
+ final_scores.append(0.0)
3005
+ reasons.append(f"Color validation failed: {color_reason}")
3006
+ if dist_path and os.path.exists(dist_path):
3007
+ os.unlink(dist_path)
3008
+ if ref_clip_path and os.path.exists(ref_clip_path):
3009
+ os.unlink(ref_clip_path)
3010
+ if dist_clip_path and os.path.exists(dist_clip_path):
3011
+ os.unlink(dist_clip_path)
3012
+ continue
3013
+
3014
+ logger.info(f"✅ UID {uid}: Color channels validated (ffmpeg) - {color_reason}")
3015
+ step_time = time.time() - uid_start_time
3016
+ logger.info(f"♎️ 10.6. Validated color channels in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
3017
+
3018
+ # Chroma validation (UV reduction detection)
3019
+ chroma_valid, chroma_reason = validate_chroma_quality_ffmpeg(ref_signal_stats, dist_signal_stats, threshold=0.7)
3020
+ if not chroma_valid:
3021
+ logger.error(f"UID {uid}: {chroma_reason}")
3022
+ compression_rates.append(0.9999)
3023
+ final_scores.append(0.0)
3024
+ reasons.append(f"Chroma validation failed: {chroma_reason}")
3025
+ if dist_path and os.path.exists(dist_path):
3026
+ os.unlink(dist_path)
3027
+ if ref_clip_path and os.path.exists(ref_clip_path):
3028
+ os.unlink(ref_clip_path)
3029
+ if dist_clip_path and os.path.exists(dist_clip_path):
3030
+ os.unlink(dist_clip_path)
3031
+ continue
3032
+
3033
+ logger.info(f"✅ UID {uid}: Chroma quality validated (ffmpeg) - {chroma_reason}")
3034
+ step_time = time.time() - uid_start_time
3035
+ logger.info(f"♎️ 10.7. Validated chroma quality in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
3036
+ else:
3037
+ # Fallback path: use Y4M-based validation (existing approach)
3038
+ logger.info("Extracting frames from Y4M for color validation from clip (reusing VMAF Y4M files)")
3039
+ dist_clip_frames = extract_frames_from_y4m(dist_y4m_path)
3040
+ step_time = time.time() - uid_start_time
3041
+ logger.info(f"♎️ 10.5. Extracted {len(dist_clip_frames)} frames from Y4M for color validation in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
3042
+
3043
+ ref_clip_frames_data = extract_frames_from_y4m(ref_y4m_path)
3044
+
3045
+ # Validate color channels (grayscale check)
3046
+ color_valid, color_reason = validate_color_channels_on_frames(ref_clip_frames_data, dist_clip_frames)
3047
+ if not color_valid:
3048
+ logger.error(f"UID {uid}: {color_reason}")
3049
+ compression_rates.append(0.9999)
3050
+ final_scores.append(0.0)
3051
+ reasons.append(f"Color validation failed: {color_reason}")
3052
+ if dist_path and os.path.exists(dist_path):
3053
+ os.unlink(dist_path)
3054
+ if ref_clip_path and os.path.exists(ref_clip_path):
3055
+ os.unlink(ref_clip_path)
3056
+ if dist_clip_path and os.path.exists(dist_clip_path):
3057
+ os.unlink(dist_clip_path)
3058
+ if dist_y4m_path and os.path.exists(dist_y4m_path):
3059
+ os.unlink(dist_y4m_path)
3060
+ continue
3061
+
3062
+ logger.info(f"✅ UID {uid}: Color channels validated - {color_reason}")
3063
+ step_time = time.time() - uid_start_time
3064
+ logger.info(f"♎️ 10.6. Validated color channels in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
3065
 
3066
+ # Validate chroma quality (prevents partial UV reduction)
3067
+ chroma_valid, chroma_reason = validate_chroma_quality_on_frames(
3068
+ ref_clip_frames_data, dist_clip_frames, threshold=0.7
3069
+ )
3070
+ if not chroma_valid:
3071
+ logger.error(f"UID {uid}: {chroma_reason}")
3072
+ compression_rates.append(0.9999)
3073
+ final_scores.append(0.0)
3074
+ reasons.append(f"Chroma validation failed: {chroma_reason}")
3075
+ if dist_path and os.path.exists(dist_path):
3076
+ os.unlink(dist_path)
3077
+ if ref_clip_path and os.path.exists(ref_clip_path):
3078
+ os.unlink(ref_clip_path)
3079
+ if dist_clip_path and os.path.exists(dist_clip_path):
3080
+ os.unlink(dist_clip_path)
3081
+ if dist_y4m_path and os.path.exists(dist_y4m_path):
3082
+ os.unlink(dist_y4m_path)
3083
+ continue
3084
+
3085
+ logger.info(f"✅ UID {uid}: Chroma quality validated - {chroma_reason}")
3086
+ step_time = time.time() - uid_start_time
3087
+ logger.info(f"♎️ 10.7. Validated chroma quality in {step_time:.2f} seconds. Total time: {step_time:.2f} seconds.")
 
 
 
3088
 
3089
  # Calculate compression score using the proper formula
3090
  # Check scoring function for details
services/scoring/vmaf_metric.py CHANGED
@@ -1,5 +1,6 @@
1
  import subprocess
2
  import xml.etree.ElementTree as ET
 
3
  import os
4
  from moviepy.editor import VideoFileClip
5
  from loguru import logger
@@ -7,40 +8,144 @@ import tempfile
7
  import shutil
8
 
9
 
10
- def trim_video(input_path, start_time, trim_duration=1, target_crf=18):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  """
12
- Trims a video and re-encodes it to H.264 with minimal quality loss.
 
 
13
 
14
  Args:
15
  input_path (str): Path to the source (AV1, HEVC, etc.)
16
  start_time (float): Start point in seconds
17
  trim_duration (int): Duration in seconds
18
- target_crf (int): Quality level (17-18 for visually transparent)
 
19
  """
20
  filename, ext = os.path.splitext(input_path)
21
  output_path = f"{filename}_trimmed_{start_time:.2f}.mp4"
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  cmd = [
24
  "ffmpeg",
25
- "-y", # Overwrite if exists
26
- "-ss", str(start_time),
27
- "-t", str(trim_duration),
28
  "-i", input_path,
29
- "-c:v", "libx264", # Ensure H.264 output
30
- "-preset", "fast", # Better compression efficiency
31
- "-crf", str(target_crf),# High quality setting
32
- "-c:a", "aac", # Standard audio codec for MP4
33
- "-b:a", "192k", # Good audio bitrate
34
- output_path
 
35
  ]
36
-
37
  try:
38
  subprocess.run(cmd, check=True, capture_output=True)
39
  return output_path
40
  except subprocess.CalledProcessError as e:
41
- print(f"Error: {e.stderr.decode()}")
42
  return None
43
 
 
44
  def get_video_fps(video_path):
45
  """
46
  Get the frame rate of a video using ffprobe.
@@ -166,6 +271,138 @@ def vmaf_metric(ref_path, dist_path, output_file="vmaf_output.xml", neg_model=Fa
166
  print(f"Error in calculate_vmaf: {e}")
167
  raise
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  def calculate_vmaf(ref_y4m_path, dist_mp4_path, random_frames, neg_model=False, return_y4m_path=False):
170
  """
171
  Calculate VMAF score between reference and distorted videos.
 
1
  import subprocess
2
  import xml.etree.ElementTree as ET
3
+ import json
4
  import os
5
  from moviepy.editor import VideoFileClip
6
  from loguru import logger
 
8
  import shutil
9
 
10
 
11
+ _vmaf_ffmpeg_available = None # cached result
12
+
13
+ def is_vmaf_ffmpeg_available(docker_image="vmaf_ffmpeg"):
14
+ """
15
+ Check whether the vmaf_ffmpeg Docker image is available locally and
16
+ its FFmpeg build supports the libvmaf_cuda filter.
17
+ The result is cached so the check only runs once per process.
18
+ """
19
+ global _vmaf_ffmpeg_available
20
+ if _vmaf_ffmpeg_available is not None:
21
+ return _vmaf_ffmpeg_available
22
+
23
+ try:
24
+ # 1. Check if Docker image exists
25
+ result = subprocess.run(
26
+ ["docker", "images", "-q", docker_image],
27
+ capture_output=True, text=True, timeout=10,
28
+ )
29
+ if result.returncode != 0 or not result.stdout.strip():
30
+ logger.info(f"vmaf_ffmpeg Docker image '{docker_image}' not found locally.")
31
+ _vmaf_ffmpeg_available = False
32
+ return False
33
+
34
+ # 2. Check if FFmpeg in the image supports libvmaf_cuda
35
+ result = subprocess.run(
36
+ ["docker", "run", "--rm", docker_image, "-filters"],
37
+ capture_output=True, text=True, timeout=30,
38
+ )
39
+ if "libvmaf_cuda" not in (result.stdout + result.stderr):
40
+ logger.info(f"vmaf_ffmpeg Docker image does not support libvmaf_cuda filter.")
41
+ _vmaf_ffmpeg_available = False
42
+ return False
43
+
44
+ logger.info("vmaf_ffmpeg Docker image with libvmaf_cuda support detected ✅")
45
+ _vmaf_ffmpeg_available = True
46
+ return True
47
+
48
+ except Exception as e:
49
+ logger.warning(f"Error checking vmaf_ffmpeg availability: {e}")
50
+ _vmaf_ffmpeg_available = False
51
+ return False
52
+
53
+
54
+ def trim_video(input_path, start_time, trim_duration=1, target_crf=18, reencode=False):
55
  """
56
+ Trims a video segment. By default uses stream copy (no re-encoding) for
57
+ lossless, fast trimming. Set reencode=True to re-encode to H.264, which
58
+ is needed when the output must be in a standard codec (e.g. for upscale_video).
59
 
60
  Args:
61
  input_path (str): Path to the source (AV1, HEVC, etc.)
62
  start_time (float): Start point in seconds
63
  trim_duration (int): Duration in seconds
64
+ target_crf (int): Quality level (17-18 for visually transparent), only used when reencode=True
65
+ reencode (bool): If True, re-encode to H.264. If False, use stream copy (default).
66
  """
67
  filename, ext = os.path.splitext(input_path)
68
  output_path = f"{filename}_trimmed_{start_time:.2f}.mp4"
69
 
70
+ if reencode:
71
+ cmd = [
72
+ "ffmpeg",
73
+ "-y", # Overwrite if exists
74
+ "-ss", str(start_time),
75
+ "-t", str(trim_duration),
76
+ "-i", input_path,
77
+ "-c:v", "libx264", # Ensure H.264 output
78
+ "-preset", "fast", # Better compression efficiency
79
+ "-crf", str(target_crf),# High quality setting
80
+ "-c:a", "aac", # Standard audio codec for MP4
81
+ "-b:a", "192k", # Good audio bitrate
82
+ output_path
83
+ ]
84
+ else:
85
+ cmd = [
86
+ "ffmpeg",
87
+ "-y", # Overwrite if exists
88
+ "-ss", str(start_time),
89
+ "-t", str(trim_duration),
90
+ "-i", input_path,
91
+ "-c:v", "copy", # Stream copy — no re-encoding
92
+ "-c:a", "copy", # Stream copy audio
93
+ output_path
94
+ ]
95
+
96
+ try:
97
+ subprocess.run(cmd, check=True, capture_output=True)
98
+ return output_path
99
+ except subprocess.CalledProcessError as e:
100
+ print(f"Error: {e.stderr.decode()}")
101
+ return None
102
+
103
+
104
+ def trim_video_select(input_path, start_frame, num_frames, target_crf=18):
105
+ """
106
+ Frame-accurate video trimming using the select filter.
107
+
108
+ Unlike trim_video (which uses stream copy or time-based seeking and can
109
+ land on the wrong keyframe), this function extracts exact frame indices.
110
+ Both the reference and distorted videos will contain the exact same
111
+ frame range, eliminating alignment issues in VMAF comparisons.
112
+
113
+ Args:
114
+ input_path (str): Path to the source video.
115
+ start_frame (int): First frame index to include (0-based).
116
+ num_frames (int): Number of consecutive frames to extract.
117
+ target_crf (int): CRF quality for the re-encoded output (default: 18).
118
+
119
+ Returns:
120
+ str: Path to the trimmed MP4 file, or None on error.
121
+ """
122
+ filename, ext = os.path.splitext(input_path)
123
+ output_path = f"{filename}_trimmed_f{start_frame}.mp4"
124
+
125
+ end_frame = start_frame + num_frames - 1
126
+ select_expr = f"between(n\\,{start_frame}\\,{end_frame})"
127
+
128
  cmd = [
129
  "ffmpeg",
130
+ "-y",
 
 
131
  "-i", input_path,
132
+ "-vf", f"select='{select_expr}',setpts=N/FRAME_RATE/TB",
133
+ "-an", # Drop audio (not needed for VMAF)
134
+ "-pix_fmt", "yuv420p",
135
+ "-c:v", "libx264",
136
+ "-preset", "fast",
137
+ "-crf", str(target_crf),
138
+ output_path,
139
  ]
140
+
141
  try:
142
  subprocess.run(cmd, check=True, capture_output=True)
143
  return output_path
144
  except subprocess.CalledProcessError as e:
145
+ print(f"Error in trim_video_select: {e.stderr.decode()}")
146
  return None
147
 
148
+
149
  def get_video_fps(video_path):
150
  """
151
  Get the frame rate of a video using ffprobe.
 
271
  print(f"Error in calculate_vmaf: {e}")
272
  raise
273
 
274
+
275
+ def vmaf_metric_ffmpeg(
276
+ dist_path,
277
+ ref_path,
278
+ skip_frames=0,
279
+ n_subsample=1,
280
+ docker_image="vmaf_ffmpeg",
281
+ neg_model=False,
282
+ ):
283
+ """
284
+ Calculate VMAF score using the vmaf_ffmpeg Docker container with GPU-accelerated
285
+ libvmaf_cuda, operating directly on MP4 inputs.
286
+
287
+ The libvmaf_cuda filter expects: distorted first, reference second.
288
+ This matches FFmpeg's convention where the first -i is the distorted video
289
+ and the second -i is the reference video.
290
+
291
+ Args:
292
+ dist_path (str): Absolute path to the distorted MP4 video.
293
+ ref_path (str): Absolute path to the reference MP4 video.
294
+ skip_frames (int): Number of leading frames to skip (e.g. 51 to
295
+ drop the first 51 frames from both streams).
296
+ n_subsample (int): Subsample every N-th frame for faster scoring.
297
+ docker_image (str): Name of the Docker image (default "vmaf_ffmpeg").
298
+
299
+ Returns:
300
+ float: The VMAF harmonic mean score.
301
+ """
302
+ dist_path = os.path.abspath(dist_path)
303
+ ref_path = os.path.abspath(ref_path)
304
+
305
+ # Collect unique directories that need to be mounted
306
+ dist_dir = os.path.dirname(dist_path)
307
+ ref_dir = os.path.dirname(ref_path)
308
+
309
+ # Use a temporary directory for the JSON output
310
+ tmp_dir = tempfile.mkdtemp(prefix="vmaf_ffmpeg_")
311
+ output_json = os.path.join(tmp_dir, "vmaf_output.json")
312
+
313
+ try:
314
+ # Build volume mounts – map each host dir to the same path inside the
315
+ # container so that absolute paths work unchanged.
316
+ volumes = set()
317
+ volumes.add(dist_dir)
318
+ volumes.add(ref_dir)
319
+ volumes.add(tmp_dir)
320
+
321
+ vol_args = []
322
+ for vol in volumes:
323
+ vol_args.extend(["-v", f"{vol}:{vol}"])
324
+
325
+ # Build the filter_complex string
326
+ # skip_frames: select frames with index > skip_frames (i.e. drop first skip_frames+1 frames)
327
+ if skip_frames > 0:
328
+ select_filter = f"select=gt(n\\,{skip_frames}),"
329
+ else:
330
+ select_filter = ""
331
+
332
+ if neg_model:
333
+ logger.info("Using VMAF NEG model for scoring (ffmpeg/docker).")
334
+ model_param = ":model='version=vmaf_v0.6.1neg'"
335
+ else:
336
+ logger.info("Using standard VMAF model for scoring (ffmpeg/docker).")
337
+ model_param = ""
338
+
339
+ filter_complex = (
340
+ f"[0:v]{select_filter}format=yuv420p,hwupload_cuda[dis];"
341
+ f"[1:v]{select_filter}format=yuv420p,hwupload_cuda[ref];"
342
+ f"[dis][ref]libvmaf_cuda=n_subsample={n_subsample}{model_param}"
343
+ f":log_fmt=json:log_path={output_json}"
344
+ )
345
+
346
+ # Assemble the full docker command
347
+ # Entrypoint of the image is "ffmpeg", so we only pass ffmpeg args
348
+ cmd = [
349
+ "docker", "run", "--rm",
350
+ "--gpus", "all",
351
+ *vol_args,
352
+ docker_image,
353
+ "-i", dist_path,
354
+ "-i", ref_path,
355
+ "-filter_complex", filter_complex,
356
+ "-f", "null", "-",
357
+ ]
358
+
359
+ logger.info(f"Running VMAF via Docker: {' '.join(cmd)}")
360
+ result = subprocess.run(cmd, capture_output=True, text=True)
361
+
362
+ if result.returncode != 0:
363
+ raise Exception(
364
+ f"Docker VMAF command failed (exit {result.returncode}):\n"
365
+ f"stdout: {result.stdout}\nstderr: {result.stderr}"
366
+ )
367
+
368
+ # Parse the JSON log produced by libvmaf_cuda
369
+ if not os.path.exists(output_json):
370
+ raise FileNotFoundError(
371
+ f"Expected VMAF JSON output '{output_json}' not found."
372
+ )
373
+
374
+ with open(output_json, "r") as f:
375
+ vmaf_data = json.load(f)
376
+
377
+ # Extract per-frame VMAF scores
378
+ frames = vmaf_data.get("frames", [])
379
+ if not frames:
380
+ raise ValueError("No frames found in VMAF JSON output.")
381
+
382
+ scores = []
383
+ for frame in frames:
384
+ metrics = frame.get("metrics", {})
385
+ vmaf_score = metrics.get("vmaf")
386
+ if vmaf_score is not None and vmaf_score > 0:
387
+ scores.append(vmaf_score)
388
+
389
+ if not scores:
390
+ raise ValueError("No valid (> 0) VMAF scores found in output.")
391
+
392
+ # Compute harmonic mean: n / sum(1/x_i)
393
+ harmonic_mean = len(scores) / sum(1.0 / s for s in scores)
394
+ logger.info(f"VMAF harmonic mean (ffmpeg/docker): {harmonic_mean:.4f}")
395
+ return harmonic_mean
396
+
397
+ except Exception as e:
398
+ logger.error(f"Error in vmaf_metric_ffmpeg: {e}")
399
+ raise
400
+
401
+ finally:
402
+ # Clean up temporary directory
403
+ if os.path.exists(tmp_dir):
404
+ shutil.rmtree(tmp_dir, ignore_errors=True)
405
+
406
  def calculate_vmaf(ref_y4m_path, dist_mp4_path, random_frames, neg_model=False, return_y4m_path=False):
407
  """
408
  Calculate VMAF score between reference and distorted videos.
vidaio_subnet_core/__init__.py CHANGED
@@ -12,7 +12,7 @@ __all__ = [
12
  "CONFIG",
13
  ]
14
 
15
- __version__ = "2.1.34"
16
 
17
  version_split = __version__.split(".")
18
  __spec_version__ = (
 
12
  "CONFIG",
13
  ]
14
 
15
+ __version__ = "2.1.35"
16
 
17
  version_split = __version__.split(".")
18
  __spec_version__ = (
vmaf_utils/Dockerfile ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:22.04
2
+ ARG NV_CODEC_TAG="876af32a202d0de83bd1d36fe74ee0f7fcf86b0d"
3
+
4
+ # get and install building tools
5
+ RUN apt-get update && \
6
+ apt-get install -y \
7
+ build-essential \
8
+ ninja-build \
9
+ nasm \
10
+ doxygen \
11
+ python3 \
12
+ python3-pip \
13
+ python3-venv \
14
+ xxd \
15
+ clang \
16
+ wget \
17
+ unzip \
18
+ nvidia-cuda-dev \
19
+ nvidia-cuda-toolkit
20
+
21
+ # retrieve source code
22
+ COPY . /vmaf
23
+
24
+ # setup environment
25
+
26
+ ENV PATH=/vmaf:/vmaf/libvmaf/build/tools:$PATH
27
+ ENV PKG_CONFIG_PATH="/usr/local/lib/x86_64-linux-gnu/pkgconfig:$PKG_CONFIG_PATH"
28
+
29
+
30
+ RUN wget https://github.com/FFmpeg/nv-codec-headers/archive/${NV_CODEC_TAG}.zip && unzip ${NV_CODEC_TAG}.zip && cd nv-codec-headers-${NV_CODEC_TAG} && make && make install
31
+
32
+ # make vmaf
33
+ # when disabling NVCC, libvmaf will be built without cubin's which will compile kernels at start of the container
34
+ RUN cd /vmaf && make clean && make ENABLE_NVCC=true && make install && \
35
+ set -eux; \
36
+ for d in /usr/local/lib /usr/local/lib/x86_64-linux-gnu /usr/local/lib64; do \
37
+ if [ -d "$d" ]; then echo "$d"; fi; \
38
+ done > /etc/ld.so.conf.d/00-vmaf-local.conf && \
39
+ ldconfig
40
+
41
+ # install python tools
42
+ RUN pip3 install --no-cache-dir -r /vmaf/python/requirements.txt
43
+
44
+ WORKDIR /vmaf
45
+
46
+ ENV PYTHONPATH=python
47
+
48
+ ENTRYPOINT [ "vmaf" ]
vmaf_utils/Dockerfile.ffmpeg ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM vmaf
2
+
3
+ RUN apt-get update && \
4
+ apt-get install -y pkg-config libx264-dev git python3-pip && \
5
+ pip3 install meson
6
+
7
+ # build dav1d from source (requires >= 1.0.0 for ffmpeg)
8
+ RUN git clone --depth 1 --branch 1.4.2 https://code.videolan.org/videolan/dav1d.git && \
9
+ cd dav1d && \
10
+ mkdir build && cd build && \
11
+ meson setup .. --default-library=static --buildtype release && \
12
+ ninja && \
13
+ ninja install && \
14
+ ldconfig
15
+
16
+ ENV PKG_CONFIG_PATH="/usr/local/lib/pkgconfig:/usr/local/lib/x86_64-linux-gnu/pkgconfig:$PKG_CONFIG_PATH"
17
+
18
+ ARG FFMPEG_TAG=master
19
+ ARG NVCC_FLAGS="-gencode arch=compute_75,code=sm_75 -gencode arch=compute_75,code=compute_75 -O2"
20
+
21
+ # get ffmpeg
22
+ RUN git clone https://github.com/FFmpeg/FFmpeg ffmpeg
23
+
24
+ RUN cd ffmpeg && git reset --hard 33b215d1554a14e87416a24f8e6034312e629af7 && ./configure \
25
+ --enable-gpl \
26
+ --enable-libx264 \
27
+ --enable-libvmaf \
28
+ --enable-libdav1d \
29
+ --enable-nonfree \
30
+ --enable-cuda-nvcc \
31
+ --enable-libnpp \
32
+ --extra-cflags="-I/usr/local/cuda/include" \
33
+ --extra-ldflags="-L/usr/local/cuda/lib64" \
34
+ --disable-static \
35
+ --enable-shared \
36
+ --nvccflags="${NVCC_FLAGS}" && \
37
+ make -j && \
38
+ make install
39
+
40
+ RUN set -eux; \
41
+ test -f /usr/local/lib/x86_64-linux-gnu/libvmaf.so.3 || test -f /usr/local/lib/libvmaf.so.3; \
42
+ ldconfig
43
+
44
+ RUN mkdir /data
45
+ # VMAF+decode GPU (only works for NVDec supported formats https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-new)
46
+ ENTRYPOINT ["ffmpeg"]