-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvmaf.cpp
More file actions
1604 lines (1476 loc) · 61.7 KB
/
Copy pathvmaf.cpp
File metadata and controls
1604 lines (1476 loc) · 61.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* Copyright 2016-2026 Netflix, Inc.
*
* Licensed under the BSD+Patent License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSDplusPatent
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* ADR-0809 — C++23 Wave 8: vmaf.c → vmaf.cpp.
* Conservative idioms: nullptr, static_cast, [[nodiscard]], and RAII
* wrappers for the three pointer-owning arrays (model, model_collection,
* model_collection_label) that previously required manual free() under the
* goto-cleanup ladder. The goto-cleanup spine is retained — it is a
* load-bearing invariant per ADR-0141 §2 (cleanup ownership chain); jumping
* over trivially-destructible or default-initialised objects is well-formed
* C++23. Spinner header uses inline to suppress ODR warnings. */
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <memory>
#include <string_view>
#ifdef _WIN32
/* MSVC/UCRT provides isatty / fileno via <io.h> under the MSVC-prefixed
* names _isatty / _fileno; the POSIX-style aliases stay available for
* source portability. MinGW ships <unistd.h>, so this split is strictly
* MSVC / clang-cl. */
#include <io.h>
#include <windows.h> /* QueryPerformanceCounter/Frequency for wall_time_s() */
#define isatty _isatty
#define fileno _fileno
#else
#include <fcntl.h>
#include <unistd.h>
#endif
#include "cli_parse.h"
#include "spinner.h"
#include "vidinput.h"
#include "libvmaf/picture.h"
#include "libvmaf/libvmaf.h"
#include "libvmaf/dnn.h"
#ifdef HAVE_CUDA
#include "libvmaf/libvmaf_cuda.h"
#endif
#ifdef HAVE_SYCL
#include "libvmaf/libvmaf_sycl.h"
#endif
#ifdef HAVE_HIP
#include "libvmaf/libvmaf_hip.h"
#endif
#ifdef HAVE_METAL
#include "libvmaf/libvmaf_metal.h"
#endif
/* ADR-0543 (extends ADR-0498): dedicated exit code for an explicit-
* backend init failure. Distinguishes a "you asked for SYCL but it
* couldn't initialise" failure from generic encode / score errors
* (which keep using non-zero-but-unspecified) so CI gates and the
* vmaf-tune bisect predicate can tell the two apart without parsing
* stderr. Mirrors the EX_* convention from <sysexits.h>; we don't pull
* sysexits.h in to stay portable to Windows/MSVC. */
#define VMAF_EXIT_BACKEND_INIT_FAILED 100
/* Dedicated exit code for "no frames decoded": run_frame_loop returned 0
* because neither input yielded a single frame (empty file, zero-byte pipe,
* frame_skip past EOF, or a fully unreadable stream). Without this guard the
* pooling path computes `picture_index - 1`, which underflows the unsigned
* counter to UINT_MAX and feeds a bogus index range into vmaf_score_pooled.
* Distinct from VMAF_EXIT_BACKEND_INIT_FAILED so CI gates can tell an
* empty/short input apart from a backend failure. */
#define VMAF_EXIT_NO_FRAMES_DECODED 101
/* ADR-0543: sentinel returned by init_gpu_backends when the user passed
* `--backend NAME` (non-auto/cpu) and that backend failed to initialise.
* The caller in main() distinguishes this from the generic `-1` path so
* (a) the binary exits with VMAF_EXIT_BACKEND_INIT_FAILED rather than the
* default 255 (= int -1 → uint8), and (b) the JSON output path, if
* provided, is overwritten with an `{"error": ..., "backend_requested": ...}`
* descriptor so downstream consumers see a structured failure instead of an
* empty file. The value is deliberately distinct from any errno-style
* negative returned by the underlying vmaf_*_state_init helpers (which
* are -EINVAL / -ENODEV / -ENOMEM range, well above -100 in magnitude
* for typical errno but never exactly -100 in practice). */
#define VMAF_INIT_GPU_EXPLICIT_FAIL (-100)
static enum VmafPixelFormat pix_fmt_map(int pf)
{
switch (pf) {
case PF_420:
return VMAF_PIX_FMT_YUV420P;
case PF_422:
return VMAF_PIX_FMT_YUV422P;
case PF_444:
return VMAF_PIX_FMT_YUV444P;
default:
return VMAF_PIX_FMT_UNKNOWN;
}
}
/* ADR-0543 (extends ADR-0498): when the explicit-backend gate fires we
* overwrite the requested ``--output`` file (if any) with a minimal JSON
* descriptor so downstream consumers (CI gates, vmaf-tune compare,
* MCP probes) get a structured signal instead of an empty file. The
* file is overwritten unconditionally — empty / partial / pre-existing
* content is replaced. No-op when output_path is NULL or the requested
* format isn't JSON; XML / CSV / SUB consumers don't read the error
* field, but the non-zero exit code still surfaces the failure.
*
* Schema (RFC 8259 strict):
* {
* "error": "<human-readable reason>",
* "backend_requested": "<sycl|cuda|hip|metal>",
* "errno": <int>,
* "adr": "ADR-0498",
* "exit_code": 100
* }
*
* `err_no` is the underlying ``vmaf_*_state_init`` return (negative
* errno-style) or 0 when the failure is structural (e.g. backend not
* compiled in).
*/
static void write_backend_error_json(const char *output_path, enum VmafOutputFormat fmt,
const char *backend_requested, const char *reason, int err_no)
{
if (!output_path || !backend_requested || !reason)
return;
if (fmt != VMAF_OUTPUT_FORMAT_JSON)
return;
/* Use open()+fdopen() with explicit 0644 mode so the created file is never
* world-writable regardless of the caller's umask (CodeQL cpp/world-writable-file-creation). */
#ifdef _WIN32
FILE *fp = fopen(output_path, "wb");
#else
int raw_fd = open(output_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
FILE *fp = (raw_fd >= 0) ? fdopen(raw_fd, "wb") : nullptr;
if (!fp && raw_fd >= 0)
(void)close(raw_fd);
#endif
if (!fp)
return;
/* Keep the JSON compact + single line — every consumer in the tree
* parses it with a permissive reader and the file is short. */
(void)fprintf(fp,
"{\"error\": \"%s\", \"backend_requested\": \"%s\", "
"\"errno\": %d, \"adr\": \"ADR-0498\", "
"\"exit_code\": %d}\n",
reason, backend_requested, err_no, VMAF_EXIT_BACKEND_INIT_FAILED);
(void)fclose(fp);
}
/* Validate per-video constraints that do not require comparing the two streams:
* supported bitdepth range and positive (non-zero) frame dimensions. */
[[nodiscard]] static int validate_video_info(const video_input_info *info)
{
int err_cnt = 0;
if (info->depth < 8 || info->depth > 16) {
(void)fprintf(stderr, "unsupported bitdepth: %d\n", info->depth);
err_cnt++;
}
/* A zero-width or zero-height frame will produce a divide-by-zero or
* zero-stride allocation in downstream code. */
if (info->frame_w <= 0 || info->frame_h <= 0) {
(void)fprintf(stderr, "non-positive dimensions: %dx%d\n", info->frame_w, info->frame_h);
err_cnt++;
}
return err_cnt;
}
/* Chroma-subsampled formats require even dimensions on the subsampled axes so
* that the chroma planes contain whole pixels. PF_420 subsamples both X and
* Y; PF_422 subsamples X only. */
[[nodiscard]] static int validate_chroma_alignment(const video_input_info *info)
{
int err_cnt = 0;
if (info->pixel_fmt == PF_420 || info->pixel_fmt == PF_422) {
if (info->frame_w % 2 != 0) {
(void)fprintf(stderr, "odd width %d not allowed for chroma-subsampled format\n",
info->frame_w);
err_cnt++;
}
}
if (info->pixel_fmt == PF_420) {
if (info->frame_h % 2 != 0) {
(void)fprintf(stderr, "odd height %d not allowed for 4:2:0 format\n", info->frame_h);
err_cnt++;
}
}
return err_cnt;
}
[[nodiscard]] static int validate_videos(video_input *vid1, video_input *vid2, bool common_bitdepth)
{
int err_cnt = 0;
video_input_info info1;
video_input_info info2;
video_input_get_info(vid1, &info1);
video_input_get_info(vid2, &info2);
if ((info1.frame_w != info2.frame_w) || (info1.frame_h != info2.frame_h)) {
(void)fprintf(stderr, "dimensions do not match: %dx%d, %dx%d\n", info1.frame_w,
info1.frame_h, info2.frame_w, info2.frame_h);
err_cnt++;
}
if (info1.pixel_fmt != info2.pixel_fmt) {
(void)fprintf(stderr, "pixel formats do not match: %d, %d\n", info1.pixel_fmt,
info2.pixel_fmt);
err_cnt++;
}
if (!pix_fmt_map(info1.pixel_fmt) || !pix_fmt_map(info2.pixel_fmt)) {
(void)fprintf(stderr, "unsupported pixel format: %d\n", info1.pixel_fmt);
err_cnt++;
}
if (!common_bitdepth && info1.depth != info2.depth) {
(void)fprintf(stderr, "bitdepths do not match: %d, %d\n", info1.depth, info2.depth);
err_cnt++;
}
err_cnt += validate_video_info(&info1);
err_cnt += validate_video_info(&info2);
err_cnt += validate_chroma_alignment(&info1);
return err_cnt;
}
/* Copy video input data to picture buffer. The four bit-depth × component
* branches (8-bit Y/U/V, 10-bit Y/U/V, 16-bit packed) duplicate the per-row
* loop with different per-sample casts; folding them through a function
* pointer would cost a per-row indirect call on every frame, so the
* branches stay inline. The nesting-level warning is structural to YUV
* (plane × row × column) — splitting wouldn't reduce it
* (ADR-0141 §2 load-bearing invariant: per-frame indirect-call cost;
* T7-5 sweep closeout — ADR-0278).
*/
// NOLINTNEXTLINE(readability-function-size,google-readability-function-size)
static void copy_picture_data(VmafPicture *pic, video_input_ycbcr ycbcr, video_input_info *info,
int depth)
{
if (info->depth == depth) {
if (info->depth == 8) {
for (unsigned i = 0; i < 3; i++) {
int xdec = i && !(info->pixel_fmt & 1);
int ydec = i && !(info->pixel_fmt & 2);
uint8_t *ycbcr_data = ycbcr[i].data +
static_cast<size_t>(info->pic_y >> ydec) * ycbcr[i].stride +
(info->pic_x >> xdec);
uint8_t *pic_data = static_cast<uint8_t *>(pic->data[i]);
for (unsigned j = 0; j < pic->h[i]; j++) {
memcpy(pic_data, ycbcr_data, sizeof(*pic_data) * pic->w[i]);
pic_data += pic->stride[i];
ycbcr_data += ycbcr[i].stride;
}
}
} else {
for (unsigned i = 0; i < 3; i++) {
int xdec = i && !(info->pixel_fmt & 1);
int ydec = i && !(info->pixel_fmt & 2);
uint16_t *ycbcr_data =
static_cast<uint16_t *>(static_cast<void *>(ycbcr[i].data)) +
static_cast<size_t>(info->pic_y >> ydec) * (ycbcr[i].stride / 2) +
(info->pic_x >> xdec);
uint16_t *pic_data = static_cast<uint16_t *>(pic->data[i]);
for (unsigned j = 0; j < pic->h[i]; j++) {
memcpy(pic_data, ycbcr_data, sizeof(*pic_data) * pic->w[i]);
pic_data += pic->stride[i] / 2;
ycbcr_data += ycbcr[i].stride / 2;
}
}
}
} else if (depth > 8) {
// unequal bit-depth
// therefore depth must be > 8 since we do not support depth < 8
int left_shift = depth - info->depth;
if (info->depth == 8) {
for (unsigned i = 0; i < 3; i++) {
int xdec = i && !(info->pixel_fmt & 1);
int ydec = i && !(info->pixel_fmt & 2);
uint8_t *ycbcr_data = ycbcr[i].data +
static_cast<size_t>(info->pic_y >> ydec) * ycbcr[i].stride +
(info->pic_x >> xdec);
uint16_t *pic_data = static_cast<uint16_t *>(pic->data[i]);
for (unsigned j = 0; j < pic->h[i]; j++) {
for (unsigned k = 0; k < pic->w[i]; k++) {
pic_data[k] = static_cast<uint16_t>(ycbcr_data[k] << left_shift);
}
pic_data += pic->stride[i] / 2;
ycbcr_data += ycbcr[i].stride;
}
}
} else {
for (unsigned i = 0; i < 3; i++) {
int xdec = i && !(info->pixel_fmt & 1);
int ydec = i && !(info->pixel_fmt & 2);
uint16_t *ycbcr_data =
static_cast<uint16_t *>(static_cast<void *>(ycbcr[i].data)) +
static_cast<size_t>(info->pic_y >> ydec) * (ycbcr[i].stride / 2) +
(info->pic_x >> xdec);
uint16_t *pic_data = static_cast<uint16_t *>(pic->data[i]);
for (unsigned j = 0; j < pic->h[i]; j++) {
for (unsigned k = 0; k < pic->w[i]; k++) {
pic_data[k] = static_cast<uint16_t>(ycbcr_data[k] << left_shift);
}
pic_data += pic->stride[i] / 2;
ycbcr_data += ycbcr[i].stride / 2;
}
}
}
}
}
[[nodiscard]] static int finish_unread_picture(VmafPicture *pic, int fetch_ret)
{
const int err_unref = vmaf_picture_unref(pic);
if (err_unref)
(void)fprintf(stderr, "\nproblem during vmaf_picture_unref (unread)\n");
return fetch_ret == 0 ? 1 : -1;
}
[[nodiscard]] static int fetch_picture(VmafContext *vmaf, video_input *vid, VmafPicture *pic,
int depth)
{
int ret;
video_input_info info;
video_input_get_info(vid, &info);
ret = vmaf_fetch_preallocated_picture(vmaf, pic);
if (ret) {
(void)fprintf(stderr, "problem fetching picture from pool.\n");
return -1;
}
#ifdef USE_DIRECT_READ
(void)depth;
ret = video_input_fetch_into_vmaf_picture(vid, pic);
if (ret < 1)
return finish_unread_picture(pic, ret);
#else
video_input_ycbcr ycbcr;
ret = video_input_fetch_frame(vid, ycbcr, nullptr);
if (ret < 1)
return finish_unread_picture(pic, ret);
copy_picture_data(pic, ycbcr, &info, depth);
#endif
return 0;
}
/* RAII wrapper for the three parallel model-tracking arrays.
* Owns heap-allocated VmafModel**, VmafModelCollection**, and const char**
* arrays sized to model_cnt. The destructor calls vmaf_model_destroy /
* vmaf_model_collection_destroy and frees the backing store so the
* goto-cleanup spine in main() simply lets this object go out of scope.
*
* ADR-0809: replaces the manual free()/vmaf_model*_destroy() calls that
* were previously duplicated across three locations in main(). */
struct ModelArrays {
VmafModel **model{nullptr};
VmafModelCollection **collection{nullptr};
const char **collection_label{nullptr};
unsigned model_cnt{0};
unsigned collection_cnt{0};
ModelArrays() = default;
/* Non-copyable, moveable */
ModelArrays(const ModelArrays &) = delete;
ModelArrays &operator=(const ModelArrays &) = delete;
[[nodiscard]] int allocate(unsigned cnt)
{
model_cnt = cnt;
if (cnt == 0)
return 0;
model = static_cast<VmafModel **>(malloc(sizeof(*model) * cnt));
if (!model)
return -1;
memset(static_cast<void *>(model), 0, sizeof(*model) * cnt);
collection = static_cast<VmafModelCollection **>(malloc(sizeof(*collection) * cnt));
if (!collection)
return -1;
memset(static_cast<void *>(collection), 0, sizeof(*collection) * cnt);
collection_label = static_cast<const char **>(malloc(sizeof(*collection_label) * cnt));
if (!collection_label)
return -1;
memset(static_cast<void *>(collection_label), 0, sizeof(*collection_label) * cnt);
return 0;
}
~ModelArrays()
{
if (model) {
for (unsigned i = 0; i < model_cnt; i++)
vmaf_model_destroy(model[i]);
free(static_cast<void *>(model));
}
if (collection) {
for (unsigned i = 0; i < collection_cnt; i++)
vmaf_model_collection_destroy(collection[i]);
free(static_cast<void *>(collection));
}
free(static_cast<void *>(collection_label));
}
};
/* Helper: pick the human-readable label (version preferred over path) for
* the given model-config entry, used in error messages.
*/
static const char *model_label(const CLISettings *c, unsigned i)
{
return c->model_config[i].version ? c->model_config[i].version : c->model_config[i].path;
}
/* Initialise a model-collection slot for entry `i`. The caller passes the
* current `*slot` index; on any failure path this helper bumps `*slot`
* before returning so the caller's cleanup loop unwinds the partially
* initialised entry. Returns 0 on success.
*/
[[nodiscard]] static int load_model_collection_entry(VmafContext *vmaf, CLISettings *c, unsigned i,
ModelArrays &arrays)
{
unsigned *slot = &arrays.collection_cnt;
int err;
if (c->model_config[i].version) {
err = vmaf_model_collection_load(&arrays.model[i], &arrays.collection[*slot],
&c->model_config[i].cfg, c->model_config[i].version);
} else {
err =
vmaf_model_collection_load_from_path(&arrays.model[i], &arrays.collection[*slot],
&c->model_config[i].cfg, c->model_config[i].path);
}
if (err) {
(void)fprintf(stderr, "problem loading model: %s\n", model_label(c, i));
return -1;
}
arrays.collection_label[*slot] = model_label(c, i);
for (unsigned j = 0; j < c->model_config[i].overload_cnt; j++) {
err = vmaf_model_collection_feature_overload(
arrays.model[i], &arrays.collection[*slot], c->model_config[i].feature_overload[j].name,
c->model_config[i].feature_overload[j].opts_dict);
if (err) {
(void)fprintf(stderr,
"problem overloading feature extractors from model collection: %s\n",
model_label(c, i));
(*slot)++;
return -1;
}
}
err = vmaf_use_features_from_model_collection(vmaf, arrays.collection[*slot]);
if (err) {
(void)fprintf(stderr, "problem loading feature extractors from model collection: %s\n",
model_label(c, i));
(*slot)++;
return -1;
}
(*slot)++;
return 0;
}
/* Load a single model entry from the CLI configuration. Handles the model
* vs model-collection fallback that the `--model` option's overloaded
* semantics require.
*/
[[nodiscard]] static int load_one_model_entry(VmafContext *vmaf, CLISettings *c, unsigned i,
ModelArrays &arrays)
{
int err;
if (c->model_config[i].version) {
err =
vmaf_model_load(&arrays.model[i], &c->model_config[i].cfg, c->model_config[i].version);
} else {
err = vmaf_model_load_from_path(&arrays.model[i], &c->model_config[i].cfg,
c->model_config[i].path);
}
/* `--model` is overloaded: if a single-model load fails, fall back to
* loading the same identifier as a model collection.
*/
if (err) {
return load_model_collection_entry(vmaf, c, i, arrays);
}
for (unsigned j = 0; j < c->model_config[i].overload_cnt; j++) {
err = vmaf_model_feature_overload(arrays.model[i],
c->model_config[i].feature_overload[j].name,
c->model_config[i].feature_overload[j].opts_dict);
if (err) {
(void)fprintf(stderr, "problem overloading feature extractors from model: %s\n",
model_label(c, i));
return -1;
}
}
err = vmaf_use_features_from_model(vmaf, arrays.model[i]);
if (err) {
(void)fprintf(stderr, "problem loading feature extractors from model: %s\n",
model_label(c, i));
return -1;
}
return 0;
}
/* Open both reference and distorted input streams (raw YUV via raw_input_open
* when --use_yuv is set, otherwise the codec auto-detection path via
* video_input_open). On success transfers FILE* ownership from *file_ref/dist
* to the corresponding video_input and zeros the pointers so the cleanup
* fclose() doesn't double-close. Sets *vid_ref_open / *vid_dist_open to true
* for cleanup unwinding. Returns 0 on success, -1 on any failure (caller
* should treat as fatal and `goto cleanup`).
*/
[[nodiscard]] static int open_input_videos(const CLISettings *c, FILE **file_ref, FILE **file_dist,
video_input *vid_ref, video_input *vid_dist,
bool *vid_ref_open, bool *vid_dist_open)
{
int err;
if (c->use_yuv) {
err = raw_input_open(vid_ref, *file_ref, c->width, c->height, c->pix_fmt, c->bitdepth);
} else {
err = video_input_open(vid_ref, *file_ref);
}
if (err) {
/* ADR-0520: --no-reference re-opens the distorted file as the
* "ref" slot; surface the actually-opened path on failure. */
const char *const opened_path = c->no_reference ? c->path_dist : c->path_ref;
(void)fprintf(stderr, "problem with reference file: %s\n", opened_path);
return -1;
}
*vid_ref_open = true;
*file_ref = nullptr; /* ownership transferred to vid_ref */
if (c->use_yuv) {
err = raw_input_open(vid_dist, *file_dist, c->width, c->height, c->pix_fmt, c->bitdepth);
} else {
err = video_input_open(vid_dist, *file_dist);
}
if (err) {
(void)fprintf(stderr, "problem with distorted file: %s\n", c->path_dist);
return -1;
}
*vid_dist_open = true;
*file_dist = nullptr; /* ownership transferred to vid_dist */
err = validate_videos(vid_ref, vid_dist, c->common_bitdepth);
if (err) {
(void)fprintf(stderr, "videos are incompatible, %d %s.\n", err,
err == 1 ? "problem" : "problems");
return -1;
}
return 0;
}
/* Initialise the GPU backends in declared priority order: SYCL first
* (preferred when --sycl_device or --gpumask is set), CUDA second
* (consulted only if SYCL was not activated), then HIP and Metal
* (explicit --hip_device / --metal_device opt-in). On a hard
* backend-import failure returns -1 so the caller can `goto cleanup`;
* soft init failures (state_init returning non-zero) silently fall
* back to CPU. State pointers are passed by reference so the cleanup
* block can free them after vmaf_close().
*
* The function is intentionally kept in a single TU even though
* several #ifdef-guarded backend stanzas push the line count past the
* 60-line threshold. Splitting into per-backend helpers would multiply
* the `#if defined(HAVE_X)` decoration without making the activation
* priority chain (SYCL > CUDA > HIP > Metal) any clearer to a reader
* (ADR-0141 §2 load-bearing invariant: backend-priority chain
* readability + #ifdef discipline; T7-5 sweep closeout — ADR-0278).
*/
// NOLINTNEXTLINE(readability-function-size,google-readability-function-size)
[[nodiscard]] static int init_gpu_backends(VmafContext *vmaf, const CLISettings *c
#ifdef HAVE_SYCL
,
VmafSyclState **sycl_state, bool *sycl_active
#endif
#ifdef HAVE_CUDA
,
bool *cuda_active_out
#endif
#ifdef HAVE_HIP
,
VmafHipState **hip_state, bool *hip_active
#endif
#ifdef HAVE_METAL
,
VmafMetalState **metal_state, bool *metal_active
#endif
)
{
int err;
(void)vmaf;
(void)c;
(void)err;
/* ADR-0498 / Bug #v2-E: when the user passes ``--backend NAME``
* (not the default ``auto``), an init failure for the requested
* backend must surface as a hard error — silently falling back to
* CPU corrupts CI gates that depend on backend-specific scoring.
* The ``auto`` selector keeps the legacy soft-fallback chain.
* Marked (void) so a build with no GPU backends compiled in
* doesn't trip ``-Wunused-variable``. */
const bool explicit_backend =
c->backend && strcmp(c->backend, "auto") != 0 && strcmp(c->backend, "cpu") != 0;
(void)explicit_backend;
/* If the requested backend isn't compiled into this libvmaf,
* surface that as a hard error too — otherwise the CLI silently
* runs on CPU and the user has no signal beyond stderr. */
if (explicit_backend) {
bool compiled_in = false;
#ifdef HAVE_SYCL
if (strcmp(c->backend, "sycl") == 0)
compiled_in = true;
#endif
#ifdef HAVE_CUDA
if (strcmp(c->backend, "cuda") == 0)
compiled_in = true;
#endif
#ifdef HAVE_HIP
if (strcmp(c->backend, "hip") == 0)
compiled_in = true;
#endif
#ifdef HAVE_METAL
if (strcmp(c->backend, "metal") == 0)
compiled_in = true;
#endif
if (!compiled_in) {
(void)fprintf(stderr,
"vmaf: --backend %s requested but this libvmaf was built "
"without %s support; refusing to silently fall back to CPU "
"(ADR-0498)\n",
c->backend, c->backend);
write_backend_error_json(c->output_path, c->output_fmt, c->backend,
"backend not compiled into this libvmaf", 0);
return VMAF_INIT_GPU_EXPLICIT_FAIL;
}
}
// GPU backend initialization: each backend activates only when its
// specific flag is passed. --gpumask enables the preferred backend
// (SYCL > CUDA). --sycl_device selects
// that specific backend. No flag = CPU only.
#ifdef HAVE_SYCL
VmafSyclConfiguration sycl_cfg = {
.device_index = c->sycl_device >= 0 ? c->sycl_device : 0,
};
if ((c->sycl_device >= 0 || c->use_gpumask) && !c->no_sycl) {
err = vmaf_sycl_state_init(sycl_state, sycl_cfg);
if (err) {
(void)fprintf(stderr, "problem during vmaf_sycl_state_init, using CPU\n");
if (explicit_backend && strcmp(c->backend, "sycl") == 0) {
(void)fprintf(stderr, "vmaf: --backend sycl requested but init failed; "
"refusing to silently fall back to CPU (ADR-0498)\n");
write_backend_error_json(c->output_path, c->output_fmt, "sycl",
"vmaf_sycl_state_init failed", err);
return VMAF_INIT_GPU_EXPLICIT_FAIL;
}
} else {
err = vmaf_sycl_import_state(vmaf, *sycl_state);
if (err) {
(void)fprintf(stderr, "problem during vmaf_sycl_import_state\n");
return -1;
}
*sycl_active = true;
}
}
#endif
#ifdef HAVE_CUDA
*cuda_active_out = false;
VmafCudaState *cu_state;
VmafCudaConfiguration cuda_cfg = {0};
if (c->use_gpumask && !c->no_cuda
#ifdef HAVE_SYCL
&& !*sycl_active
#endif
) {
err = vmaf_cuda_state_init(&cu_state, cuda_cfg);
if (err) {
(void)fprintf(stderr, "problem during vmaf_cuda_state_init, using CPU\n");
if (explicit_backend && strcmp(c->backend, "cuda") == 0) {
(void)fprintf(stderr, "vmaf: --backend cuda requested but init failed; "
"refusing to silently fall back to CPU (ADR-0498)\n");
write_backend_error_json(c->output_path, c->output_fmt, "cuda",
"vmaf_cuda_state_init failed", err);
return VMAF_INIT_GPU_EXPLICIT_FAIL;
}
} else {
err |= vmaf_cuda_import_state(vmaf, cu_state);
if (err) {
(void)fprintf(stderr, "problem during vmaf_cuda_import_state\n");
return -1;
}
*cuda_active_out = true;
}
}
#endif
#ifdef HAVE_HIP
/* HIP opt-in: explicit --hip_device only. Same lifetime model as
* SYCL — state is passed back by reference so the cleanup
* block can free it after vmaf_close(). */
VmafHipConfiguration hip_cfg = {
.device_index = c->hip_device,
.flags = 0,
};
if (c->hip_device >= 0 && !c->no_hip) {
err = vmaf_hip_state_init(hip_state, hip_cfg);
if (err) {
(void)fprintf(stderr, "problem during vmaf_hip_state_init (%d), using CPU\n", err);
if (explicit_backend && strcmp(c->backend, "hip") == 0) {
(void)fprintf(stderr, "vmaf: --backend hip requested but init failed; "
"refusing to silently fall back to CPU (ADR-0498)\n");
write_backend_error_json(c->output_path, c->output_fmt, "hip",
"vmaf_hip_state_init failed", err);
return VMAF_INIT_GPU_EXPLICIT_FAIL;
}
} else {
err = vmaf_hip_import_state(vmaf, *hip_state);
if (err) {
(void)fprintf(stderr, "problem during vmaf_hip_import_state\n");
return -1;
}
*hip_active = true;
}
}
(void)*hip_active;
#endif
#ifdef HAVE_METAL
/* Metal opt-in: explicit --metal_device only. macOS-only; on non-
* Apple hosts vmaf_metal_state_init returns -ENODEV and the CLI
* falls back to CPU. Same state-lifetime model as SYCL/HIP. */
VmafMetalConfiguration metal_cfg = {
.device_index = c->metal_device,
.flags = 0,
};
if (c->metal_device >= 0 && !c->no_metal) {
err = vmaf_metal_state_init(metal_state, metal_cfg);
if (err) {
(void)fprintf(stderr, "problem during vmaf_metal_state_init (%d), using CPU\n", err);
if (explicit_backend && strcmp(c->backend, "metal") == 0) {
(void)fprintf(stderr, "vmaf: --backend metal requested but init failed; "
"refusing to silently fall back to CPU (ADR-0498)\n");
write_backend_error_json(c->output_path, c->output_fmt, "metal",
"vmaf_metal_state_init failed", err);
return VMAF_INIT_GPU_EXPLICIT_FAIL;
}
} else {
err = vmaf_metal_import_state(vmaf, *metal_state);
if (err) {
(void)fprintf(stderr, "problem during vmaf_metal_import_state\n");
return -1;
}
*metal_active = true;
}
}
(void)*metal_active;
#endif
return 0;
}
/* ADR-0543 (extends ADR-0498): a feature whose name ends in ``_cuda``
* / ``_sycl`` / ``_hip`` / ``_metal`` is a GPU-pinned
* variant. Asking for ``--feature integer_motion_hip`` against a
* libvmaf build without HIP — or with HIP compiled in but no device
* available — silently registers the CPU twin and produces scores
* that look identical to the explicit-backend invocation, but were
* actually computed on the CPU. That defeats the entire point of the
* explicit-backend gate.
*
* This helper hard-fails any GPU-pinned feature name when the matching
* backend isn't compiled into this binary, OR is compiled in but the
* matching ``--<backend>_device`` / ``--backend <name>`` wasn't
* requested (so no state_init was attempted) or the state_init failed
* (in which case init_gpu_backends has already errored out earlier
* and we never reach here). Returns 0 on success, -1 on mismatch.
*
* Returns the backend keyword via *requested_backend_out (caller-
* owned; points into a static string table) so the caller can include
* the keyword in the error JSON. */
[[nodiscard]] static int feature_backend_suffix(const char *feature_name, const char **backend_out)
{
if (!feature_name || !backend_out)
return 0;
static const struct {
const char *suffix;
const char *backend;
} table[] = {
{"_cuda", "cuda"},
{"_sycl", "sycl"},
{"_hip", "hip"},
{"_metal", "metal"},
};
const size_t nlen = strlen(feature_name);
for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {
const size_t slen = strlen(table[i].suffix);
if (nlen > slen && strcmp(feature_name + nlen - slen, table[i].suffix) == 0) {
*backend_out = table[i].backend;
return 1;
}
}
return 0;
}
/* Returns 1 when the named backend is active in this run (state_init
* succeeded and the matching ``--<backend>_device`` was requested),
* 0 otherwise. The active flags live in main() so this helper accepts
* each as a parameter. */
[[nodiscard]] static int backend_active(const char *backend, bool sycl_act, bool cuda_act,
bool hip_act, bool metal_act)
{
if (!strcmp(backend, "sycl"))
return sycl_act ? 1 : 0;
if (!strcmp(backend, "cuda"))
return cuda_act ? 1 : 0;
if (!strcmp(backend, "hip"))
return hip_act ? 1 : 0;
if (!strcmp(backend, "metal"))
return metal_act ? 1 : 0;
return 0;
}
/* Translate the textual --tiny-device flag (cpu / cuda / openvino /
* coreml / coreml-ane / coreml-gpu / coreml-cpu / openvino-npu /
* openvino-cpu / openvino-gpu / rocm) into the corresponding
* VmafDnnDevice enum. The coreml-* keywords pin the CoreML EP to a
* single MLComputeUnits value (see ADR-0365); plain `coreml` lets
* CoreML auto-route across compute units. The openvino-* keywords pin
* the OpenVINO EP to a single device type with no fallback (see
* Research-0031); plain `openvino` keeps the GPU→CPU fallback chain.
* Unknown values fall back to VMAF_DNN_DEVICE_AUTO so the runtime
* picks a default.
*/
[[nodiscard]] static VmafDnnDevice resolve_tiny_device(const char *name)
{
if (!name)
return VMAF_DNN_DEVICE_AUTO;
using sv = std::string_view;
const sv n{name};
if (n == "cpu")
return VMAF_DNN_DEVICE_CPU;
if (n == "cuda")
return VMAF_DNN_DEVICE_CUDA;
if (n == "openvino")
return VMAF_DNN_DEVICE_OPENVINO;
if (n == "coreml")
return VMAF_DNN_DEVICE_COREML;
if (n == "coreml-ane")
return VMAF_DNN_DEVICE_COREML_ANE;
if (n == "coreml-gpu")
return VMAF_DNN_DEVICE_COREML_GPU;
if (n == "coreml-cpu")
return VMAF_DNN_DEVICE_COREML_CPU;
if (n == "openvino-npu")
return VMAF_DNN_DEVICE_OPENVINO_NPU;
if (n == "openvino-cpu")
return VMAF_DNN_DEVICE_OPENVINO_CPU;
if (n == "openvino-gpu")
return VMAF_DNN_DEVICE_OPENVINO_GPU;
if (n == "rocm")
return VMAF_DNN_DEVICE_ROCM;
return VMAF_DNN_DEVICE_AUTO;
}
/* Configure the tiny-AI (DNN) model on the VMAF context when --tiny-model
* is passed. Performs the optional Sigstore-bundle verification (T6-9 /
* ADR-0211) before opening the model so a signature failure short-circuits
* load and never touches ORT. Returns 0 on success, -1 on any failure
* (caller should treat as fatal and `goto cleanup`).
*/
[[nodiscard]] static int configure_tiny_model(VmafContext *vmaf, const CLISettings *c)
{
if (!c->tiny_model_path)
return 0;
if (!vmaf_dnn_available()) {
(void)fprintf(stderr,
"--tiny-model requested (%s) but libvmaf was built "
"without DNN support (-Denable_dnn=disabled).\n",
c->tiny_model_path);
return -1;
}
/* T6-9 / ADR-0211 — Sigstore-bundle verification. Runs *before*
* the model is opened so a verification failure short-circuits
* load and never touches ORT. Fails closed: missing registry,
* missing bundle, missing cosign, or any non-zero cosign exit
* all refuse to proceed. */
if (c->tiny_model_verify) {
const int verr = vmaf_dnn_verify_signature(c->tiny_model_path, nullptr);
if (verr != 0) {
(void)fprintf(stderr,
"--tiny-model-verify: signature verification "
"failed for %s (errno %d)\n",
c->tiny_model_path, -verr);
return -1;
}
}
VmafDnnConfig dnn_cfg = {
.device = resolve_tiny_device(c->tiny_device),
.device_index = 0,
.threads = c->tiny_threads,
.fp16_io = c->tiny_fp16,
};
int err = vmaf_use_tiny_model(vmaf, c->tiny_model_path, &dnn_cfg);
if (err) {
(void)fprintf(stderr, "problem loading tiny model %s: %d\n", c->tiny_model_path, err);
return -1;
}
/* ADR-0550: apply the user-selected NCHW auto-resize filter. NULL
* (no --tiny-resize) leaves the libvmaf default (DISABLED) in place:
* a size mismatch returns -ERANGE so the operator must explicitly opt
* in to auto-resize. The ~2% score spread across filters means filter
* choice is a model hyperparameter that should be documented. */
if (c->tiny_resize) {
VmafDnnResizeMode mode = VMAF_DNN_RESIZE_DISABLED;
using sv = std::string_view;
const sv rsz{c->tiny_resize};
if (rsz == "bilinear") {
mode = VMAF_DNN_RESIZE_BILINEAR;
} else if (rsz == "nearest") {
mode = VMAF_DNN_RESIZE_NEAREST;
} else if (rsz == "bicubic") {
mode = VMAF_DNN_RESIZE_BICUBIC;
} else if (rsz == "disabled") {
mode = VMAF_DNN_RESIZE_DISABLED;
}
const int rerr = vmaf_dnn_set_resize_mode(vmaf, mode);
if (rerr != 0) {
(void)fprintf(stderr, "--tiny-resize: vmaf_dnn_set_resize_mode failed (errno %d)\n",
-rerr);
return -1;
}
}
/* ADR-0519: populate the codec one-hot block for codec-aware
* models (e.g. fr_regressor_v2). Only fires when the user supplied
* at least one of --tiny-codec / --tiny-preset / --tiny-crf —
* otherwise the loader's pre-seeded "unknown" baseline from
* ADR-0518 stays in place so legacy invocations are byte-for-byte
* unchanged. */
if (c->tiny_codec || c->tiny_preset || c->tiny_crf >= 0) {
const int crf = c->tiny_crf >= 0 ? c->tiny_crf : 0;
const int cerr = vmaf_dnn_set_codec_context(vmaf, c->tiny_codec, c->tiny_preset, crf);
if (cerr == -ENOENT) {
(void)fprintf(stderr,
"--tiny-codec '%s' not found in model encoder_vocab; "
"use one of the names listed by --help.\n",
c->tiny_codec ? c->tiny_codec : "(null)");
return -1;
}
if (cerr == -ENOTSUP) {
(void)fprintf(stderr, "--tiny-codec / --tiny-preset / --tiny-crf require a "
"codec-aware tiny model (loaded model has no codec block).\n");
return -1;
}
if (cerr != 0) {
(void)fprintf(stderr, "vmaf_dnn_set_codec_context failed (errno %d)\n", -cerr);
return -1;
}
}