-
Notifications
You must be signed in to change notification settings - Fork 1
/
chunk_norris.py
2064 lines (1870 loc) · 94.4 KB
/
chunk_norris.py
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
# Chunk Norris
#
# A very simple Python script to do chunked encoding using an AV1 or x265 CLI encoder.
#
# Make sure you have ffmpeg and the encoder in PATH or where you run the script.
#
# Set common parameters in default_params and add/edit the presets as needed.
# Set base_working_folder and scene_change_file_path according to your folder structure.
# Set max_parallel_encodes to the maximum number of encodes you want to run simultaneously (tune according to your processor and memory usage!)
import os
import subprocess
import re
import sys
import concurrent.futures
import shutil
import argparse
import csv
import ffmpeg
import math
import json
import configparser
import copy
import shlex
import logging
from datetime import datetime
from tqdm import tqdm
def get_video_props(video_path):
probe = ffmpeg.probe(video_path, v='error')
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
if video_stream:
video_width = int(video_stream['width'])
video_height = int(video_stream['height'])
video_length = int(video_stream['nb_frames'])
video_framerate = str(video_stream['r_frame_rate'])
num, denom = map(int, video_framerate.split('/'))
fr = float(num/denom)
video_framerate = int(math.ceil(num/denom))
try:
video_transfer = str(video_stream['color_transfer'])
except Exception as e:
logging.warning(f"Could not detect the source video transfer characteristics. Exception code {e}")
logging.warning("Setting transfer to \"unknown\".")
video_transfer = 'unknown'
try:
video_matrix = str(video_stream['color_space'])
except Exception as e:
logging.warning(f"Could not detect the source video colormatrix. Exception code {e}")
if video_transfer == 'smpte2084':
logging.warning("Setting matrix to \"2020ncl\".")
video_matrix = '2020ncl'
else:
logging.warning("Setting matrix to \"709\".")
video_matrix = '709'
video_matrix = video_matrix.replace("bt2020nc", "2020ncl")
video_matrix = video_matrix.replace("bt", "")
video_matrix = video_matrix.replace("smpte", "")
video_matrix = video_matrix.replace("unknown", "709")
return video_width, video_height, video_length, video_transfer, video_matrix, video_framerate, fr
else:
print("No video stream found in the input video.")
return None
# Function to clean up a folder
def clean_folder(folder):
for item in os.listdir(folder):
item_path = os.path.join(folder, item)
if os.path.isfile(item_path):
os.unlink(item_path)
elif os.path.isdir(item_path):
shutil.rmtree(item_path)
def clean_files(folder, pattern):
for item in os.listdir(folder):
item_path = os.path.join(folder, item)
if os.path.isfile(item_path) and item.startswith(pattern):
os.unlink(item_path)
# Define a function to extract sections from the baseline grain table file
def extract_sections(filename):
sections = []
current_section = []
section_number = 0 # Track the current section number
with open(filename, 'r') as file:
for line in file:
if line.startswith('E'):
# If we encounter a line starting with 'E', it's the start of a new section
current_section = [line]
section_number += 1 # Increment section number
# print(f"Processing section {section_number}...")
elif current_section:
# If we are in a section, add the line to the current section
current_section.append(line)
if len(current_section) == 8: # Each section has 8 lines, including the header
sections.append(current_section)
# length = timestamp_difference(current_section)
# print (length)
current_section = []
if not sections:
print("No valid sections found in the file.")
return sections
# Define a function to calculate the timestamp difference for a section in the baseline grain table
def timestamp_difference(section):
start_timestamp = int(section[0].split()[1])
end_timestamp = int(section[0].split()[2])
return end_timestamp - start_timestamp
def create_scxvid_file(scene_change_csv, scd_method, scd_tonemap, encode_script, cudasynth, downscale_scd, scd_script, scene_change_file_path):
if scd_method == 5:
with open(encode_script, 'r') as file:
# Read the first line from the original file
source = file.readline()
if scd_tonemap != 0 and cudasynth and "dgsource" in source.lower():
source = source.replace(".dgi\",", ".dgi\",h2s_enable=1,")
source = source.replace(".dgi\")", ".dgi\",h2s_enable=1)")
with open(scd_script, 'w') as scd_file:
# Write the first line content to the new file
scd_file.write(source)
if downscale_scd > 1:
scd_file.write('\n')
scd_file.write(f'Spline16Resize(width()/{downscale_scd},height()/{downscale_scd})\n')
scd_file.write('Crop(16,16,-16,-16)\n')
if scd_tonemap != 0 and not cudasynth:
scd_file.write('\nConvertBits(16).DGHDRtoSDR(gamma=1/2.4)\n')
scd_file.write('ConvertBits(8)\n')
scd_file.write(f'SCXvid(log="{scene_change_csv}")')
else:
with open(encode_script, 'r') as file:
# Read the first line from the original file
source = file.readlines()
for i in range(len(source)):
if scd_tonemap != 0 and cudasynth and "dgsource" in source[i].lower():
source[i] = source[i].replace(".dgi\",", ".dgi\",h2s_enable=1,")
source[i] = source[i].replace(".dgi\")", ".dgi\",h2s_enable=1)")
with open(scd_script, 'w') as scd_file:
scd_file.writelines(source)
if scd_tonemap != 0 and not cudasynth:
scd_file.write('\nConvertBits(16).DGHDRtoSDR(gamma=1/2.4)\n')
scd_file.write(f'\nConvertBits(bits=8)\n')
scd_file.write(f'SCXvid(log="{scene_change_csv}")')
scene_change_command = [
"ffmpeg",
"-i", scd_script,
"-loglevel", "warning",
"-an", "-f", "null", "NUL"
]
start_time = datetime.now()
print("Detecting scene changes using SCXviD.\n")
scd_process = subprocess.Popen(scene_change_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
scd_process.communicate()
if scd_process.returncode != 0:
logging.error(f"Error in scene change detection phase, return code: {scd_process.returncode}")
print("Error in scene change detection phase, return code:", scd_process.returncode)
sys.exit(1)
end_time = datetime.now()
scd_time = end_time - start_time
logging.info(f"Scene change detection done, duration {scd_time}.")
print("Converting logfile to QP file format.\n")
# Read the input file
with open(scene_change_csv, "r") as file:
scdxvid_data = file.readlines()
# Initialize variables
output_lines = []
current_line_number = -3 # The actual data starts from line 4, so this ensures the first scene change has frame number 0.
# Iterate through the lines
for line in scdxvid_data:
# Split the line into tokens
tokens = line.strip().split()
# Check if the line starts with 'i'
if tokens and tokens[0] == 'i':
# Append the current line number and 'I' to the output
output_lines.append(f"{current_line_number} I")
current_line_number += 1
# Join the output lines
scenechangelist = '\n'.join(output_lines)
# Write the output to a new file or print it
qpfile = os.path.splitext(os.path.basename(encode_script))[0] + ".qp.txt"
qpfile = os.path.join(scene_change_file_path, qpfile)
with open(qpfile, "w") as file:
file.write(scenechangelist)
# Function to find the scene change file recursively
def find_scene_change_file(start_dir, filename):
for root, dirs, files in os.walk(start_dir):
if filename in files:
return os.path.join(root, filename)
return None
# Function to detect scene changes with ffmpeg
def ffscd(scd_script, scdthresh, scene_change_csv):
# Step 1: Detect Scene Changes
scene_change_command = [
"ffmpeg",
"-i", scd_script,
"-vf", f"select='gt(scene,{scdthresh})',metadata=print",
"-an", "-f", "null",
"-",
]
# Redirect stderr to the CSV file
start_time = datetime.now()
print("Detecting scene changes using ffmpeg.\n")
with open(scene_change_csv, "w") as stderr_file:
scd_process = subprocess.Popen(scene_change_command, stdout=subprocess.PIPE, stderr=stderr_file, shell=True)
scd_process.communicate()
if scd_process.returncode != 0:
logging.error(f"Error in scene change detection, return code: {scd_process.returncode}")
print("Error in scene change detection, return code:", scd_process.returncode)
sys.exit(1)
# Step 2: Split the Encode into Chunks
scene_changes = [0]
# Initialize variables to store frame rate and frame number
frame_rate = None
# Function to check if a line contains 'pts_time' information
def has_pts_time(line):
return 'pts_time' in line and ':' in line
with open(scene_change_csv, "r") as csv_file:
for line in csv_file:
if "error" in line:
logging.error(f"Error in scene change detection, error message: {line}")
logging.error(f"More details in {scene_change_csv}.")
print("Scene change detection reported an error, exiting.")
print(f"Error message: {line}")
print(f"More details in {scene_change_csv}.")
sys.exit(1)
if "Stream #0:" in line and "fps," in line:
# Extract frame rate using regular expression
match = re.search(r"(\d+\.\d+)\s*fps,", line)
if match:
frame_rate = float(match.group(1))
elif has_pts_time(line):
parts = line.split("pts_time:")
if len(parts) == 2:
try:
scene_time = float(parts[1].strip())
# Calculate frame number based on pts_time and frame rate
scene_frame = int(scene_time * frame_rate)
scene_changes.append(scene_frame)
except ValueError:
print(f"Error converting to float: {line}")
# print("scene_changes:", scene_changes)
end_time = datetime.now()
scd_time = end_time - start_time
logging.info(f"Scene change detection done, duration {scd_time}.")
return scene_changes
# Function to detect scene changes with PySceneDetect
def pyscd(scd_script, output_folder_name, scdthresh, min_chunk_length, scene_change_csv):
scene_change_command = [
"scenedetect.exe",
"-i", scd_script,
"-b", "moviepy",
"-d", "1",
"-o", output_folder_name,
"detect-adaptive",
"-t", f"{scdthresh}",
"-m", f"{min_chunk_length}",
"list-scenes",
"-f", scene_change_csv,
"-q"
]
print("Detecting scene changes using PySceneDetect.\n")
start_time = datetime.now()
scd_process = subprocess.Popen(scene_change_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
scd_process.communicate()
if scd_process.returncode != 0:
logging.error(f"Error in scene change detection, return code: {scd_process.returncode}")
print("Error in scene change detection, return code:", scd_process.returncode)
sys.exit(1)
end_time = datetime.now()
scd_time = end_time - start_time
logging.info(f"Scene change detection done, duration {scd_time}.")
def create_fgs_table(encode_params, output_grain_table, scripts_folder, video_width, encode_script, graintable_sat, decode_method, encoder, threads, cpu, graintable_cpu, output_grain_file_encoded, output_grain_file_lossless,
output_grain_table_baseline):
# Create the grain table only if it doesn't exist already
if os.path.exists(output_grain_table) is False:
grain_script = os.path.join(scripts_folder, f"grainscript.avs")
referencefile_start_frame = input("Please enter the first frame of FGS grain table process: ")
referencefile_end_frame = input("Please enter the last frame of FGS grain table process (default 5 seconds of frames if empty) : ")
# Check the need to pad the video because grav1synth :/
# This check and workaround currently supports resolutions only up to 4K
padleft = 0
padright = 0
if 3584 < video_width < 3840:
padleft = (3840 - video_width) / 2
if padleft % 2 != 0:
padleft += 1
padright = 3840 - video_width - padleft
elif 2560 < video_width < 3584:
padleft = (3584 - video_width) / 2
if padleft % 2 != 0:
padleft += 1
padright = 3584 - video_width - padleft
elif 1920 < video_width < 2560:
padleft = (2560 - video_width) / 2
if padleft % 2 != 0:
padleft += 1
padright = 2560 - video_width - padleft
elif 1480 < video_width < 1920:
padleft = (1920 - video_width) / 2
if padleft % 2 != 0:
padleft += 1
padright = 1920 - video_width - padleft
elif 1280 < video_width < 1480:
padleft = (1480 - video_width) / 2
if padleft % 2 != 0:
padleft += 1
padright = 1480 - video_width - padleft
elif video_width < 1280:
padleft = (1280 - video_width) / 2
if padleft % 2 != 0:
padleft += 1
padright = 1280 - video_width - padleft
print("\nVideo width:", video_width)
print("Padding left:", padleft)
print("Padding right:", padright)
print("Final width:", video_width + padleft + padright)
with open(grain_script, 'w') as grain_file:
grain_file.write(f'Import("{encode_script}")\n')
if referencefile_end_frame != '':
grain_file.write(f'Trim({referencefile_start_frame}, {referencefile_end_frame})\n')
if graintable_sat < 1.0:
grain_file.write(f'Tweak(sat={graintable_sat})\n')
grain_file.write('ConvertBits(10)\n')
grain_file.write(f'AddBorders({int(padleft)},0,{int(padright)},0)')
else:
grain_file.write('grain_frame_rate = Ceil(FrameRate())\n')
grain_file.write(f'grain_end_frame = {referencefile_start_frame} + (grain_frame_rate * 5)\n')
grain_file.write(f'Trim({referencefile_start_frame}, grain_end_frame)\n')
if graintable_sat < 1.0:
grain_file.write(f'Tweak(sat={graintable_sat})\n')
grain_file.write('ConvertBits(10)\n')
grain_file.write(f'AddBorders({int(padleft)},0,{int(padright)},0)')
# Create the encoding command lines
if decode_method == 0:
decode_command_grain = [
"avs2yuv64.exe",
"-no-mt",
'"' + grain_script + '"',
"-"
]
else:
decode_command_grain = [
"ffmpeg.exe",
"-loglevel", "fatal",
"-i", '"' + grain_script + '"',
"-f", "yuv4mpegpipe",
"-strict", "-1",
"-"
]
if encoder == 'rav1e':
encode_params_grain = [x.replace(f'--threads {threads}', '--threads 0').replace(f'--speed {cpu}', f'--speed {graintable_cpu}') for x in encode_params]
enc_command_grain = [
"rav1e.exe",
*encode_params_grain,
"-o", '"' + output_grain_file_encoded + '"',
"-"
]
elif encoder == 'svt':
encode_params_grain = [x.replace(f'--lp {threads}', '--lp 0').replace(f'--preset {cpu}', f'--preset {graintable_cpu}') for x in encode_params]
enc_command_grain = [
"svtav1encapp.exe",
*encode_params_grain,
"-b", '"' + output_grain_file_encoded + '"',
"-i -"
]
else:
encode_params_grain = [x.replace(f'--cpu-used={cpu}', f'--cpu-used={graintable_cpu}').replace(f'--threads={threads}', f'--threads={os.cpu_count()}') for x in encode_params]
enc_command_grain = [
"aomenc.exe",
"--ivf",
*encode_params_grain,
"--passes=1",
"-o", '"' + output_grain_file_encoded + '"',
"-"
]
ffmpeg_command_grain = [
"ffmpeg.exe",
"-i", grain_script,
"-y",
"-loglevel", "fatal",
"-c:v", "ffv1",
"-pix_fmt", "yuv420p10le",
output_grain_file_lossless
]
# Create the command line to compare the original and encoded files to get the grain table
grav1synth_command = [
"grav1synth.exe",
"diff",
"-o", output_grain_table_baseline,
output_grain_file_lossless,
output_grain_file_encoded
]
# print (avs2yuv_command_grain, enc_command_grain)
decode_command_grain = ' '.join(decode_command_grain)
enc_command_grain = ' '.join(enc_command_grain)
enc_command_grain = decode_command_grain + ' | ' + enc_command_grain
print("Encoding the FGS analysis AV1 file.")
enc_process_grain = subprocess.Popen(enc_command_grain, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
enc_process_grain.communicate()
if enc_process_grain.returncode != 0:
logging.error(f"Error in FGS analysis encoder processing, return code: {enc_process_grain.returncode}")
print("Error in FGS analysis encoder processing, return code:", enc_process_grain.returncode)
sys.exit(1)
print("Encoding the FGS analysis lossless file.")
enc_process_grain_ffmpeg = subprocess.Popen(ffmpeg_command_grain, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
enc_process_grain_ffmpeg.communicate()
if enc_process_grain_ffmpeg.returncode != 0:
logging.error(f"Error in FGS analysis lossless file processing, return code: {enc_process_grain_ffmpeg.returncode}")
print("Error in FGS analysis lossless file processing, return code:", enc_process_grain_ffmpeg.returncode)
sys.exit(1)
print("Creating the FGS grain table file.\n")
enc_process_grain_grav = subprocess.Popen(grav1synth_command, shell=True)
enc_process_grain_grav.communicate()
if enc_process_grain_grav.returncode != 0:
logging.error(f"Error in grav1synth process, return code: {enc_process_grain_grav.returncode}")
print("Error in grav1synth process, return code:", enc_process_grain_grav.returncode)
sys.exit(1)
sections = extract_sections(output_grain_table_baseline)
if len(sections) == 1:
single_section = sections[0]
# Print the single section to the output file
print("\nFGS table (only one FGS section found) :")
with open(output_grain_table, 'w', newline='\n') as output_file:
print("filmgrn1", file=output_file)
for line in single_section:
print(line, end='') # Print to the console
print(line, end='', file=output_file) # Print to the output file
print("\n")
elif len(sections) >= 2:
# Find the second-longest section based on timestamp difference
# Sort sections by timestamp difference in descending order
sorted_sections = sorted(sections, key=timestamp_difference, reverse=True)
# The second-longest section is at index 1 (index 0 is the longest)
second_longest_section = sorted_sections[1]
# Replace the header with one from the first section
second_longest_section[0] = sections[0][0]
# Replace the end timestamp with 9223372036854775807
second_longest_section[0] = second_longest_section[0].replace(
second_longest_section[0].split()[2], '9223372036854775807'
)
with open(output_grain_table, 'w', newline='\n') as output_file:
print("filmgrn1", file=output_file)
print("\nFGS table:")
for line in second_longest_section:
print(line, end='') # Print to the console
print(line, end='', file=output_file) # Print to the output file
else:
print("The FGS grain table file exists already, skipping creation.\n")
def scene_change_detection(scd_script, scd_method, scdthresh, encode_script, scd_tonemap, cudasynth, downscale_scd, scene_change_csv, output_folder_name, min_chunk_length):
scene_changes = []
# Detect scene changes or use QP-file
if scd_method in (0, 5, 6):
# Find the scene change file recursively
scene_change_filename = os.path.splitext(os.path.basename(encode_script))[0] + ".qp.txt"
scene_change_file_path = os.path.dirname(encode_script)
scene_change_file_path = find_scene_change_file(scene_change_file_path, scene_change_filename)
if scene_change_file_path is None:
logging.error(f"Scene change file not found: {scene_change_filename}")
print(f"Scene change file not found: {scene_change_filename}")
sys.exit(1)
# Read scene changes from the file
with open(scene_change_file_path, "r") as scene_change_file:
for line in scene_change_file:
parts = line.strip().split()
if len(parts) == 2:
start_frame = int(parts[0])
scene_changes.append(start_frame)
print("Read scene changes from QP file.\n")
# Debug: Print the scene changes from the file
# print("\nScene Changes from File:")
# for i, start_frame in enumerate(scene_changes):
# end_frame = 0 if i == len(scene_changes) - 1 else scene_changes[i + 1] - 1
# print(f"Scene {i}: Start Frame: {start_frame}, End Frame: {end_frame}")
elif scd_method == 1:
if os.path.exists(scd_script) is False:
print(f"Scene change analysis script not found: {scd_script}, created manually.\n")
with open(encode_script, 'r') as file:
# Read the first line from the original file
source = file.readline()
if scd_tonemap != 0 and cudasynth and "dgsource" in source.lower():
source = source.replace(".dgi\",", ".dgi\",h2s_enable=1,")
source = source.replace(".dgi\")", ".dgi\",h2s_enable=1)")
with open(scd_script, 'w') as scd_file:
# Write the first line content to the new file
scd_file.write(source)
if downscale_scd > 1:
scd_file.write('\n')
scd_file.write(f'Spline16Resize(width()/{downscale_scd},height()/{downscale_scd})\n')
scd_file.write('Crop(16,16,-16,-16)')
if scd_tonemap != 0 and not cudasynth:
scd_file.write('\nConvertBits(16).DGHDRtoSDR(gamma=1/2.4)')
scene_changes = ffscd(scd_script, scdthresh, scene_change_csv)
else:
print(f"Using scene change analysis script: {scd_script}.\n")
scene_changes = ffscd(scd_script, scdthresh, scene_change_csv)
elif scd_method == 2:
print(f"Using scene change analysis script: {encode_script}.\n")
scd_script = encode_script
scene_changes = ffscd(scd_script, scdthresh, scene_change_csv)
elif scd_method == 3:
scd_script = os.path.splitext(os.path.basename(encode_script))[0] + "_scd.avs"
scd_script = os.path.join(os.path.dirname(encode_script), scd_script)
if os.path.exists(scd_script) is False:
print(f"Scene change analysis script not found: {scd_script}, created manually.\n")
with open(encode_script, 'r') as file:
# Read the first line from the original file
source = file.readline()
if scd_tonemap != 0 and cudasynth and "dgsource" in source.lower():
source = source.replace(".dgi\",", ".dgi\",h2s_enable=1,")
source = source.replace(".dgi\")", ".dgi\",h2s_enable=1)")
with open(scd_script, 'w') as scd_file:
# Write the first line content to the new file
scd_file.write(source)
scd_file.write(f'\nSpline16Resize(width()/{downscale_scd},height()/{downscale_scd})\n')
scd_file.write('Crop(16,16,-16,-16)')
if scd_tonemap != 0 and not cudasynth:
scd_file.write('\nConvertBits(16).DGHDRtoSDR(gamma=1/2.4)')
pyscd(scd_script, output_folder_name, scdthresh, min_chunk_length, scene_change_csv)
else:
print(f"Using scene change analysis script: {scd_script}.\n")
pyscd(scd_script, output_folder_name, scdthresh, min_chunk_length, scene_change_csv)
else:
print(f"Using scene change analysis script: {encode_script}.\n")
pyscd(encode_script, output_folder_name, scdthresh, min_chunk_length, scene_change_csv)
return scene_changes
def adjust_chunkdata(chunkdata_list, credits_start_frame, min_chunk_length, q, credits_q):
adjusted_chunkdata_list = []
last_frame = chunkdata_list[-1]['end']
for i, chunkdata in enumerate(chunkdata_list):
if chunkdata['start'] <= credits_start_frame <= chunkdata['end']:
# Update the end frame of the chunk where credits start
adjusted_length = credits_start_frame - chunkdata['start']
chunkdata_list[i]['end'] = credits_start_frame - 1
chunkdata_list[i]['length'] = adjusted_length
break
elif i == len(chunkdata_list) - 1 and credits_start_frame == chunkdata['end'] + 1:
# Credits start at the end of the last chunk
adjusted_chunk = {
'chunk': chunkdata['chunk'],
'length': credits_start_frame - chunkdata['start'],
'start': chunkdata['start'],
'end': credits_start_frame - 1,
'credits': 0,
'q': q
}
adjusted_chunkdata_list.append(adjusted_chunk)
break
# Remove chunks that start after the credits start frame
chunkdata_list = [chunkdata for chunkdata in chunkdata_list if chunkdata['start'] <= credits_start_frame]
# Check if the last chunk before the credits is too short
if len(chunkdata_list) > 1 and chunkdata_list[-1]['length'] < min_chunk_length:
# Merge the last chunk with the second last chunk
chunkdata_list[-2]['end'] = chunkdata_list[-1]['end']
chunkdata_list[-2]['length'] = chunkdata_list[-2]['end'] - chunkdata_list[-2]['start'] + 1
chunkdata_list.pop()
# Create a new chunk for the credits
credits_chunk = {
'chunk': len(chunkdata_list) + 1,
'length': last_frame - credits_start_frame + 1,
'start': credits_start_frame,
'end': last_frame,
'credits': 1,
'q': credits_q
}
# Append the adjusted chunks to the list
adjusted_chunkdata_list = chunkdata_list + [credits_chunk]
# Update the length of each chunk in the adjusted_chunkdata_list
for chunkdata in adjusted_chunkdata_list:
chunkdata['length'] = chunkdata['end'] - chunkdata['start'] + 1
return adjusted_chunkdata_list
def preprocess_chunks(encode_commands, input_files, chunklist, qadjust_cycle, stored_encode_params, scd_method, scene_changes, video_length, scene_change_csv, credits_start_frame, min_chunk_length, q, credits_q,
encoder, chunks_folder, rpu, qadjust_cpu, encode_script, qadjust_original_file, video_width, video_height, qadjust_b, qadjust_c, scripts_folder, decode_method, cpu, credits_cpu, qadjust_crop, qadjust_crop_values):
encode_params_original = stored_encode_params.copy()
enc_command = []
encode_params = []
if qadjust_cycle < 2:
if scd_method in (0, 1, 2, 5, 6):
chunk_number = 1
i = 0
combined = False
next_scene_index = None
while i < len(scene_changes):
start_frame = scene_changes[i]
if i < len(scene_changes) - 1:
end_frame = scene_changes[i + 1] - 1
else:
end_frame = video_length - 1
# print(i,start_frame,end_frame)
# Check if the current scene is too short
if end_frame - start_frame + 1 < min_chunk_length:
next_scene_index = i + 2
combined = True
# Combine scenes until the chunk length is at least min_chunk_length
while next_scene_index < len(scene_changes):
end_frame = scene_changes[next_scene_index] - 1
chunk_length = end_frame - start_frame + 1
if chunk_length >= min_chunk_length:
break # The combined chunk is long enough
else:
next_scene_index += 1 # Move to the next scene
if next_scene_index == len(scene_changes):
# No more scenes left to combine
end_frame = video_length - 1 # Set end_frame based on the total video length for the last scene (Avisynth counts from 0, hence the minus one)
# print(f'Next scene index: {next_scene_index}')
chunk_length = end_frame - start_frame + 1
# chunk_length = 999999 if chunk_length < 0 else chunk_length
chunkdata = {
'chunk': chunk_number, 'length': chunk_length, 'start': start_frame, 'end': end_frame, 'credits': 0, 'q': q
}
chunklist.append(chunkdata)
chunk_number += 1
if combined:
i = next_scene_index
combined = False
else:
i += 1
else:
with open(scene_change_csv, 'r') as pyscd_file:
scenelist = csv.reader(pyscd_file)
scenelist = list(scenelist)
found_start = False # Flag to indicate when a line starting with a number is found
# Process each line in the CSV file
for row in scenelist:
if not found_start:
if row and row[0].isdigit():
found_start = True # Start processing lines
else:
continue # Skip lines until a line starting with a number is found
if len(row) >= 5:
chunk_number = int(row[0]) # First column
start_frame = int(row[1]) - 1 # Second column
end_frame = int(row[4]) - 1 # Fifth column
chunk_length = int(row[7]) # Eighth column
chunkdata = {
'chunk': chunk_number, 'length': chunk_length, 'start': start_frame, 'end': end_frame, 'credits': 0, 'q': q
}
chunklist.append(chunkdata)
if credits_start_frame:
chunklist = adjust_chunkdata(chunklist, credits_start_frame, min_chunk_length, q, credits_q)
if qadjust_cycle == 2:
chunklist = sorted(chunklist, key=lambda x: x['chunk'], reverse=False)
for i in chunklist:
if qadjust_cycle == 1 and i['credits'] == 1:
continue
if encoder != 'x265':
output_chunk = os.path.join(chunks_folder, f"encoded_chunk_{i['chunk']}.ivf")
else:
output_chunk = os.path.join(chunks_folder, f"encoded_chunk_{i['chunk']}.hevc")
input_files.append(output_chunk) # Add the input file for concatenation
if qadjust_cycle != 1:
if rpu and encoder in ('svt', 'x265'):
chunklist_length = len(chunklist)
print("Splitting the RPU file based on chunks.\n")
logging.info("Splitting the RPU file.")
# Use ThreadPoolExecutor for multithreading
with concurrent.futures.ThreadPoolExecutor(max_workers=int(os.cpu_count()/2)) as executor:
# Submit each chunk to the executor
futures = [executor.submit(process_rpu, i, chunklist_length, video_length, scripts_folder, chunks_folder, rpu) for i in chunklist]
# Wait for all threads to complete
for future in futures:
future.result()
chunklist = sorted(chunklist, key=lambda x: x['length'], reverse=True)
if qadjust_cycle == 1:
if encoder == 'svt':
replacements_list = {'--fast-decode ': '--fast-decode 1',
'--film-grain ': '--film-grain 0',
'--preset ': f'--preset {qadjust_cpu}'}
encode_params_original = [
next((replacements_list[key] for key in replacements_list if x.startswith(key)), x)
for x in encode_params_original
]
if not any('--fast-decode' in param for param in encode_params_original):
encode_params_original.append('--fast-decode 1')
else:
replacements_list = {'--preset ': '--preset fast',
'--limit-refs ': '--limit-refs 3',
'--rdoq-level ': '--rdoq-level 2',
'--rc-lookahead ': '--rc-lookahead 40',
'--lookahead-slices ': '--lookahead-slices 0',
'--b-adapt ': '--b-adapt 2'}
encode_params_original = [
next((replacements_list[key] for key in replacements_list if x.startswith(key)), x)
for x in encode_params_original
]
if not any('--preset' in param for param in encode_params_original):
encode_params_original.append('--preset fast')
if not any('--rdoq-level' in param for param in encode_params_original):
encode_params_original.append('--rdoq-level 2')
if not any('--rc-lookahead' in param for param in encode_params_original):
encode_params_original.append('--rc-lookahead 40')
if not any('--lookahead-slices' in param for param in encode_params_original):
encode_params_original.append('--lookahead-slices 0')
if not any('--b-adapt' in param for param in encode_params_original):
encode_params_original.append('--b-adapt 2')
with open(encode_script, 'r') as file:
source = file.readline()
with open(qadjust_original_file, "w") as qadjust_script:
qadjust_script.write(source)
if qadjust_crop != '0,0,0,0':
qadjust_script.write(f'Crop({qadjust_crop_values[0]}, {qadjust_crop_values[1]}, -{abs(qadjust_crop_values[2])}, -{abs(qadjust_crop_values[3])})\n')
qadjust_script.write(f'BicubicResize({video_width},{video_height},b={qadjust_b},c={qadjust_c})\n')
for i in chunklist:
if qadjust_cycle == 1 and i['credits'] == 1:
continue
encode_params = copy.deepcopy(encode_params_original)
if encoder in ('svt', 'x265'):
encode_params.append(f'--crf {i['q']}')
if rpu and encoder in ('svt', 'x265') and qadjust_cycle != 1:
rpupath = os.path.join(chunks_folder, f"scene_{i['chunk']}_rpu.bin")
encode_params.append(f'--dolby-vision-rpu {rpupath}')
scene_script_file = os.path.join(scripts_folder, f"scene_{i['chunk']}.avs")
if encoder != 'x265':
output_chunk = os.path.join(chunks_folder, f"encoded_chunk_{i['chunk']}.ivf")
else:
output_chunk = os.path.join(chunks_folder, f"encoded_chunk_{i['chunk']}.hevc")
# Create the Avisynth script for this scene
if qadjust_cycle != 1:
with open(scene_script_file, "w") as scene_script:
scene_script.write(f'Import("{encode_script}")\n')
scene_script.write(f"Trim({i['start']}, {i['end']})\n")
if encoder != 'x265':
scene_script.write('ConvertBits(10)')
else:
with open(scene_script_file, 'w') as scene_script:
# scene_script.write(source)
scene_script.write(f'Import("qadjust_original.avs")\n')
scene_script.write(f"Trim({i['start']}, {i['end']})\n")
# scene_script.write(f'BicubicResize({video_width},{video_height},b={qadjust_b},c={qadjust_c})\n')
if encoder != 'x265':
scene_script.write('ConvertBits(10)')
if decode_method == 0:
decode_command = [
"avs2yuv64.exe",
"-no-mt",
'"'+scene_script_file+'"', # Use the Avisynth script for this scene
"-"
]
else:
decode_command = [
"ffmpeg.exe",
"-loglevel", "fatal",
"-i", '"'+scene_script_file+'"',
"-f", "yuv4mpegpipe",
"-strict", "-1",
"-"
]
if encoder == 'rav1e':
if i['credits'] == 0:
enc_command = [
"rav1e.exe",
*encode_params,
"-q",
"-o", '"' + output_chunk + '"',
"-"
]
else:
encode_params = [x.replace(f'--speed {cpu}', f'--speed {credits_cpu}').replace(f'--quantizer {q}', f'--quantizer {credits_q}') for x in encode_params]
enc_command = [
"rav1e.exe",
*encode_params,
"-q",
"-o", '"' + output_chunk + '"',
"-"
]
elif encoder == 'svt':
if i['credits'] == 0:
enc_command = [
"svtav1encapp.exe",
*encode_params,
"-b", '"'+output_chunk+'"',
"-i -"
]
elif qadjust_cycle != 1:
encode_params = [x.replace(f'--preset {cpu}', f'--preset {credits_cpu}').replace(f'--crf {q}', f'--crf {credits_q}') for x in encode_params]
enc_command = [
"svtav1encapp.exe",
*encode_params,
"-b", '"'+output_chunk+'"',
"-i -"
]
elif encoder == 'aom':
if i['credits'] == 0:
enc_command = [
"aomenc.exe",
"-q",
"--ivf",
*encode_params,
"--passes=1",
"-o", '"'+output_chunk+'"',
"-"
]
else:
encode_params = [x.replace(f'--cpu-used={cpu}', f'--cpu-used={credits_cpu}').replace(f'--cq-level={q}', f'--cq-level={credits_q}') for x in encode_params]
enc_command = [
"aomenc.exe",
"-q",
"--ivf",
*encode_params,
"--passes=1",
"-o", '"' + output_chunk + '"',
"-"
]
else:
if i['credits'] == 0:
enc_command = [
"x265.exe",
"--y4m",
"--no-progress",
*encode_params,
"--output", '"'+output_chunk+'"',
"--input", "-"
]
else:
encode_params = [x.replace(f'--crf {q}', f'--crf {credits_q}') for x in encode_params]
enc_command = [
"x265.exe",
"--y4m",
"--no-progress",
*encode_params,
"--output", '"' + output_chunk + '"',
"--input", "-"
]
encode_commands.append((decode_command, enc_command, output_chunk))
# print (encode_commands)
chunklist_dict = {chunk_dict['chunk']: chunk_dict['length'] for chunk_dict in chunklist}
# print (chunklist)
if qadjust_cycle != 1:
logging.info(f"Total {len(chunklist)} chunks created.")
return encode_commands, input_files, chunklist, chunklist_dict, encode_params
def process_rpu(i, chunklist_length, video_length, scripts_folder, chunks_folder, rpu):
lastframe = video_length - 1
# print (chunklist)
jsonpath = os.path.join(scripts_folder, f"scene_{i['chunk']}_rpu.json")
rpupath = os.path.join(chunks_folder, f"scene_{i['chunk']}_rpu.bin")
if i['chunk'] == 1:
start = i['end'] + 1
data = {
"remove": [f"{start}-{lastframe}"]
}
elif i['chunk'] < chunklist_length:
start = 0
end = i['start'] - 1
start_2 = i['end'] + 1
data = {
"remove": [f"{start}-{end}", f"{start_2}-{lastframe}"]
}
else:
start = 0
end = i['start'] - 1
data = {
"remove": [f"{start}-{end}"]
}
with open(jsonpath, 'w') as json_file:
json.dump(data, json_file, indent=2)
dovitool_command = [
"dovi_tool.exe",
"editor",
"-i", rpu,
"-j", jsonpath,
"-o", rpupath
]
dovitool_process = subprocess.Popen(dovitool_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
dovitool_process.communicate()
if dovitool_process.returncode != 0:
logging.error(f"Error in RPU processing, return code {dovitool_process.returncode}")
print("Error in RPU processing, return code:", dovitool_process.returncode)
sys.exit(1)
def parse_master_display(master_display, max_cll):
# Define conversion factors
conversion_factors = {'G': 0.00002, 'B': 0.00002, 'R': 0.00002, 'WP': 0.00002, 'L': 0.0001}
# Regular expression to extract values from the input string
pattern = re.compile(r'([A-Z]+)\((\d+),(\d+)\)')
# Function to apply the conversion factor to the extracted values
def convert(match):
group, value1, value2 = match.groups()
factor = conversion_factors.get(group, 1.0)
new_value1 = int(value1) * factor
new_value2 = int(value2) * factor
# Round the values to three decimals
new_value1 = round(new_value1, 3)
new_value2 = round(new_value2, 3)
# If the result is greater than 1, convert to int
if new_value1 > 1:
new_value1 = int(new_value1)
if new_value2 > 1:
new_value2 = int(new_value2)
return f'{group}({new_value1},{new_value2})'
# Extract all values from the input string
matches = pattern.findall(master_display)
# Check if any of the original values is greater than 1
if any(int(value1) > 1 or int(value2) > 1 for group, value1, value2 in matches):
# Apply the conversion function to the input string
processed_string = pattern.sub(convert, master_display)
else:
processed_string = master_display
# Remove quotes from the result
processed_string = processed_string.replace('"', '')
max_cll = max_cll.replace('"', '')
# print(processed_string, max_cll)