-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1kt.py
More file actions
2165 lines (2014 loc) · 82 KB
/
Copy path1kt.py
File metadata and controls
2165 lines (2014 loc) · 82 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""1KeyTranscoder — 主入口 (thin orchestrator).
硬件后端 (NVEncC/QSVEncC) 的批量逻辑已抽出至 core/batch_hw.py;
x265 路径作为显式手动选项保留在本文件 (legacy, 永不自动回退软件).
典型用法:
python 1kt.py --input <dir> --output <dir> --encoder nvenc --preset hq
python 1kt.py ... --check basic|advanced|full
python 1kt.py ... --jobs auto (单后端自适应调度)
python 1kt.py ... --experimental-multihw (实验性双后端并行)
python 1kt.py ... --headless (无人值守)
python 1kt.py --input <dir> --output <dir> --retry-list failed_files.json --encoder x265
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any
from core.batch_hw import (
BatchCtx,
detect_vfr,
hw_backend_for,
is_dji_source,
run_hw_pool,
run_multihw_pool,
load_retry_list,
record_failure,
)
from core.config import (
find_executable,
load_config,
load_json_file,
load_scaling_config,
load_svtav1_config,
resolve_config_file,
verify_executable,
)
from core.dashboard import DashboardStatus
from core.logging_utils import (
SCALING_CSV_FIELDS,
append_csv,
build_file_logger,
make_scaling_csv_row,
resolve_log_level,
setup_logger,
)
from core.models import PRESETS, EffectiveParams
from core.paths import (
discover_sources,
format_path_relation,
job_id_for,
output_path_for,
per_file_log_path,
)
from core.postprobe import postprobe_and_log
from core.probe import build_source_info, count_frames, probe_source
from core.scaling import ScalingEngine
from core.source_classifier import SourceClassifier
from core.version import version_string
from encoders.svtav1 import SvtAv1Backend
from encoders.x265 import X265Backend
from preservation.gpac import GpacContainerBackend
from preservation.gyroflow import find_gyroflow
from preservation.pipeline import run_sony_pipeline
EXPERIMENTAL_BANNER = (
"=" * 72
+ "\n[EXPERIMENTAL] --experimental-multihw 已启用:\n"
+ " 多硬件后端并行属于实验性功能, 无法保证视频编码质量一致性.\n"
+ " 如需质量一致性保证, 请使用单后端模式 (默认).\n"
+ "=" * 72
)
#: `--audio-plan` 里选择器使用的**来源身份**。取固定名而不是文件名主干,
#: 这样同一份计划文件对整批素材都可读、可复现 ("source:s1:c0")。
AUDIO_SOURCE_ID = "source"
# ---------------------------------------------------------------------------
# x265 legacy path (manual --encoder x265 only; never auto-selected)
# ---------------------------------------------------------------------------
def run_ffmpeg(
cmd: list[str],
raw_log_path: Path,
total_frames: int,
file_logger: logging.Logger,
) -> tuple[int | None, float]:
"""Run one FFmpeg command with live progress."""
import re
import time
started = time.monotonic()
last_console = 0.0
last_logged_progress = 0.0
proc: subprocess.Popen[str] | None = None
try:
with raw_log_path.open("w", encoding="utf-8", errors="replace") as raw_log:
proc = subprocess.Popen(
cmd,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
)
assert proc.stderr is not None
for raw_line in proc.stderr:
line = raw_line.rstrip("\r\n")
raw_log.write(line + "\n")
raw_log.flush()
frame_match = re.search(r"frame=\s*([0-9]+)", line)
bitrate_match = re.search(
r"bitrate=\s*([0-9.]+)\s*kbits/s",
line,
re.IGNORECASE,
)
if not frame_match:
continue
current_frame = int(frame_match.group(1))
elapsed = time.monotonic() - started
bitrate = (
float(bitrate_match.group(1))
if bitrate_match
else None
)
now = time.monotonic()
if now - last_console >= 1.0:
total = str(total_frames) if total_frames > 0 else "?"
bitrate_text = (
f"{bitrate:.1f} kbps"
if bitrate is not None
else "N/A"
)
try:
print(
f"\r[PROGRESS] {current_frame} frames / "
f"{total} frames total | "
f"{elapsed:.1f} sec elapsed | "
f"{bitrate_text} ",
end="",
flush=True,
)
except OSError:
pass
last_console = now
if now - last_logged_progress >= 10.0:
file_logger.info(
"PROGRESS | frames=%d/%s | elapsed=%.3f sec | "
"bitrate=%s kbps",
current_frame,
total_frames if total_frames > 0 else "?",
elapsed,
(
f"{bitrate:.1f}"
if bitrate is not None
else "N/A"
),
)
last_logged_progress = now
return_code = proc.wait()
try:
print()
except OSError:
pass
return return_code, time.monotonic() - started
except KeyboardInterrupt:
try:
print()
except OSError:
pass
file_logger.warning(
"INTERRUPTED | elapsed=%.3f sec",
time.monotonic() - started,
)
if proc is not None:
try:
proc.kill()
proc.wait(timeout=5)
except Exception:
pass
return None, time.monotonic() - started
except Exception:
try:
print()
except OSError:
pass
file_logger.exception(
"EXECUTION FAILED | elapsed=%.3f sec",
time.monotonic() - started,
)
return None, time.monotonic() - started
class Prepared:
def __init__(
self,
summary: dict[str, Any],
streams: list[dict[str, Any]],
src_info,
classification,
effective: EffectiveParams,
) -> None:
self.summary = summary
self.streams = streams
self.src_info = src_info
self.classification = classification
self.effective = effective
def prepare_source(
*,
src: Path,
preset: str,
ffprobe: Path,
preprobe_csv: Path,
preprobe_stream_csv: Path,
scaling_csv: Path,
profile: dict[str, Any],
classifier,
engine,
backend,
file_logger: logging.Logger,
) -> Prepared:
from core.logging_utils import (
PRE_CSV_FIELDS,
STREAM_CSV_FIELDS,
append_rows,
make_stream_rows,
make_summary_csv_row,
)
source_summary, source_streams = probe_source(ffprobe, src)
append_csv(
preprobe_csv, PRE_CSV_FIELDS,
make_summary_csv_row(src, source_summary, preset),
)
append_rows(
preprobe_stream_csv, STREAM_CSV_FIELDS,
make_stream_rows(src, source_streams, preset),
)
src_info = build_source_info(src, source_summary, source_streams)
classification = classifier.classify(src_info)
effective = engine.build(
profile, preset, src_info, classification,
param_order=backend.param_order,
format_fixed=backend.format_fixed,
)
append_csv(
scaling_csv, SCALING_CSV_FIELDS,
make_scaling_csv_row(src, preset, effective),
)
return Prepared(
source_summary, source_streams, src_info,
classification, effective,
)
def log_encode_header(
*,
logger: logging.Logger,
file_logger: logging.Logger,
src: Path,
preset: str,
prepared: Prepared,
engine,
effective_params: dict[str, Any],
cmd: list[str],
) -> None:
from core.logging_utils import format_mb
source_summary = prepared.summary
src_info = prepared.src_info
classification = prepared.classification
effective = prepared.effective
logger.info(
"[START] %s | preset=%s | fps=%.6f | frames=%s | LA-cap=%d",
src, preset, source_summary["fps"],
source_summary["total_frames"] or "?", engine.la_cap,
)
logger.info(
"[SOURCE] size=%s MB | duration=%.3f sec | bitrate=%.3f kbps | "
"streams=%d",
format_mb(source_summary["source_size_bytes"]),
source_summary["duration"],
source_summary["container_bitrate_kbps"],
source_summary["stream_count"],
)
logger.info(
"[CLASS] %s | class=%s | normalized_ob=%.6f bits/pixel-frame",
src.name, classification.source_class, classification.normalized_ob,
)
logger.info(
"[SCALING] spatial=%.6f | temporal=%.6f | pixel_rate=%.6f",
effective.spatial_factor, effective.temporal_factor,
effective.pixel_rate_factor,
)
logger.info("[COMMAND] %s", subprocess.list2cmdline(cmd))
file_logger.info(
"SOURCE | path=%s | size=%s MB | duration=%.3f sec | fps=%.9f | "
"frames=%s",
src, format_mb(source_summary["source_size_bytes"]),
source_summary["duration"], source_summary["fps"],
source_summary["total_frames"] or "?",
)
file_logger.info(
"SOURCE_FORMAT | %sx%s | codec=%s | profile=%s | pix_fmt=%s | "
"bit_depth=%d | chroma=%s | OB=%.3f kbps",
src_info.width, src_info.height, src_info.codec, src_info.profile,
src_info.pix_fmt, src_info.bit_depth, src_info.chroma,
src_info.ob_kbps,
)
file_logger.info(
"CLASSIFICATION | source_class=%s | normalized_ob=%.6f | "
"evidence=%s",
classification.source_class, classification.normalized_ob,
classification.evidence,
)
file_logger.info("COMMAND | %s", subprocess.list2cmdline(cmd))
file_logger.info(
"EFFECTIVE_X265 | %s",
json.dumps(effective_params, ensure_ascii=False, sort_keys=True),
)
def _apply_audio_plan(
*,
src: Path,
video: Path,
video_container: str,
dst: Path,
work_dir: Path,
audio_plan_request,
ffmpeg: Path,
ffprobe: Path,
logger: logging.Logger,
file_logger: logging.Logger,
) -> tuple[bool, bool, str]:
"""显式音频计划: **一个**实现, 软件与硬件后端共用 (v0.8.0+)。
返回 `(ok, applied, detail)`:
* `ok=False` -> 计划被拒绝/编排失败。调用方必须**明确失败**, 绝不忽略计划
继续输出 (否则用户会以为计划生效了);
* `applied=True` -> 最终文件已经写好;
* `applied=False` -> "没有要做的事"(空计划), 调用方保持既有路径原样。
为什么软件与硬件必须共用这一个函数: §11/§26 要求"同一个 AudioPlan, 换视频
后端不得改变音频结果"。两条路径各写一遍是唯一能破坏这个性质的方式。
⚠️ 本函数是 `1kt.py` 里**唯一**触达音频域的地方, 且只通过
`production.output` —— 生产入口不认识 `AudioPlan` / `AudioTimeline` /
`AudioEncoder`, 只转交一个不透明的请求对象。
"""
from production.output import (
VideoOutputArtifact,
produce_audio_output,
resolve_source_audio_plan,
)
try:
candidate = resolve_source_audio_plan(
ffprobe, src, audio_plan_request, source_id=AUDIO_SOURCE_ID,
)
except Exception as exc: # noqa: BLE001
logger.error("[AUDIO-FAIL] %s | %s", src, exc)
file_logger.error("AUDIO PLAN REJECTED | %s", exc)
return False, False, str(exc)
outcome = produce_audio_output(
plan=candidate,
video=VideoOutputArtifact(
path=str(video), container=video_container, label="encoded",
),
output_path=dst,
audio_source=src,
ffmpeg=ffmpeg,
ffprobe=ffprobe,
work_dir=work_dir,
request=audio_plan_request,
log=lambda msg: logger.info("[AUDIO] %s | %s", src.name, msg),
)
file_logger.info(
"AUDIO_OUTPUT | %s | %s",
outcome.path.value,
json.dumps(outcome.summary(), ensure_ascii=False),
)
if not outcome.ok:
logger.error(
"[AUDIO-FAIL] %s | %s | %s",
src, outcome.reasons,
[e.get("detail") for e in outcome.errors],
)
file_logger.error(
"AUDIO OUTPUT FAILED | %s",
json.dumps(outcome.errors, ensure_ascii=False),
)
return False, False, ", ".join(outcome.reasons)
if outcome.applied and Path(outcome.output_path) != dst:
# Composer 写到了别处: 不猜, 明确报错 (调用方会删掉中间产物)。
file_logger.error(
"AUDIO OUTPUT PATH MISMATCH | %s != %s",
outcome.output_path, dst,
)
return False, False, "audio output path mismatch"
return True, bool(outcome.applied), outcome.path.value
def _audio_plan_handoff(
*,
audio_plan_request,
ffmpeg: Path,
ffprobe: Path,
logger: logging.Logger,
) -> Any:
"""给硬件批量层用的"接手最终输出"钩子 (v0.8.0+)。
硬件批量层只传一个 `VideoHandoff` (源 / 视频产物 / 目标 / 工作目录), 不知道
音频的存在; 音频域也完全不知道视频是 NVENC 还是 QSV 编的。两侧因此保持
零耦合:
NVENC / QSV -> VideoHandoff -> (本钩子) -> production.output
钩子内部与软件路径调用**同一个** `_apply_audio_plan`, 所以同一个计划在
x265 / SVT-AV1 / NVENC / QSV 上必须得到相同的音频结构。
"""
if audio_plan_request is None:
return None
def hook(request: Any) -> Any:
from core.batch_hw import HandoffOutcome
file_logger = getattr(request, "file_logger", None) or logger
try:
ok, applied, detail = _apply_audio_plan(
src=request.source,
video=request.video,
video_container="mp4",
dst=request.output,
work_dir=request.work_dir / "audio",
audio_plan_request=audio_plan_request,
ffmpeg=ffmpeg,
ffprobe=ffprobe,
logger=logger,
file_logger=file_logger,
)
except Exception as exc: # noqa: BLE001
logger.exception("[AUDIO-FAIL] %s", request.source)
return HandoffOutcome(
ok=False, applied=False,
detail=f"{type(exc).__name__}: {exc}",
errors=[str(exc)],
)
return HandoffOutcome(
ok=ok, applied=applied,
detail=detail if (not ok or applied) else "audio plan disabled",
errors=[] if ok else [detail],
)
return hook
def encode_one(
*,
src: Path,
dst: Path,
part_dst: Path,
prepared: Prepared,
ffmpeg: Path,
ffprobe: Path,
postprobe_csv: Path,
postprobe_stream_csv: Path,
profile: dict[str, Any],
preset: str,
backend,
engine,
check_level: str = "basic",
quality_opts: dict[str, Any] | None = None,
quality_csv: Path | None = None,
channel_sync: bool = False,
channel_sync_opts: dict[str, Any] | None = None,
audio_plan_request=None,
gpac: Any = None,
work_dir: Path | None = None,
logger: logging.Logger,
file_logger: logging.Logger,
dry_run: bool,
) -> str:
"""Classic single-pass (x265/svtav1 software backends). At
check_level='full' the PSNR/SSIM sample gates delivery; with
channel_sync the fixed audio replaces the copied audio post-encode.
With an explicit audio plan the same encoder command is derived into a
video-only one and the audio is produced separately, then composed at the
end (Phase 4C). Without a plan nothing here changes."""
from core.paths import safe_unlink
safe_unlink(part_dst)
safe_unlink(part_dst.with_name(part_dst.name + ".ffmpeg.log"))
source_summary = prepared.summary
cmd, effective_params = backend.build_command(
ffmpeg, src, part_dst, profile, prepared.effective,
source_summary["video_streams"], prepared.src_info,
)
# 显式音频计划: 视频产物必须独立, 否则 Composer 没有可编排的视频输入。
# 派生只去掉音频 token, 不碰任何编码参数 (视频 bitstream 因此不变)。
if audio_plan_request is not None:
from production.output import derive_video_only_command
cmd = derive_video_only_command(cmd)
log_encode_header(
logger=logger, file_logger=file_logger, src=src, preset=preset,
prepared=prepared, engine=engine,
effective_params=effective_params, cmd=cmd,
)
if dry_run:
file_logger.info("DRY-RUN | no encode performed.")
return "dry-run"
dst.parent.mkdir(parents=True, exist_ok=True)
ffmpeg_log = part_dst.with_name(part_dst.name + ".ffmpeg.log")
return_code, elapsed = run_ffmpeg(
cmd, ffmpeg_log, source_summary["total_frames"], file_logger
)
if return_code is None:
logger.warning("[INTERRUPTED/EXEC-FAIL] %s", src)
safe_unlink(part_dst)
return "failed"
if return_code != 0:
logger.error("[FAIL] return=%d | elapsed=%.3f sec | %s",
return_code, elapsed, src)
file_logger.error("FAILED | return=%d | elapsed=%.3f sec",
return_code, elapsed)
safe_unlink(part_dst)
return "failed"
if not part_dst.is_file() or part_dst.stat().st_size <= 0:
logger.error("[FAIL] ffmpeg returned 0 but output is missing/empty | %s",
src)
file_logger.error("FAILED | ffmpeg returned 0 but output missing/empty")
safe_unlink(part_dst)
return "failed"
# PSNR/SSIM quality sample (check=full) gates delivery
if check_level == "full":
from preservation.quality import run_quality_sample
q = run_quality_sample(
original=src,
final=part_dst,
ffmpeg=ffmpeg,
ffprobe=ffprobe,
scratch=(work_dir or part_dst.parent) / "quality",
opts=quality_opts,
csv_path=quality_csv,
log=lambda msg: logger.info("[QUALITY] %s | %s", src.name, msg),
)
if q["status"] == "FAIL":
logger.error("[FAIL] quality sample | %s | %s", src, q["detail"])
file_logger.error("QUALITY SAMPLE FAILED | %s", q["detail"])
safe_unlink(part_dst)
return "failed"
# 显式音频计划 (Phase 4C / v0.8.0): 音频与视频是**平行**分支 —— 视频已在
# 上一步编码完成, 这里只负责把音频域的产物与它组装成最终输出。
# ⚠️ `1kt.py` **不** import 任何 `core.audio_*` 模块: 音频域的计划解析、
# 格式策略与编排全部收在 `production.output` 之后, 生产入口只传
# "源 + 请求"(请求对象对它是**不透明**的)。
if audio_plan_request is not None:
audio_ok, audio_applied, _detail = _apply_audio_plan(
src=src, video=part_dst, video_container="",
dst=dst,
work_dir=(work_dir or part_dst.parent) / "audio",
audio_plan_request=audio_plan_request,
ffmpeg=ffmpeg, ffprobe=ffprobe,
logger=logger, file_logger=file_logger,
)
if not audio_ok:
safe_unlink(part_dst)
return "failed"
if audio_applied:
# Composer 已经写出最终文件; 视频中间产物不再需要。
safe_unlink(part_dst)
postprobe_and_log(
src=src, dst=dst, preset=preset, elapsed=elapsed,
source_summary=source_summary, ffprobe=ffprobe,
postprobe_csv=postprobe_csv,
postprobe_stream_csv=postprobe_stream_csv,
logger=logger, file_logger=file_logger,
)
safe_unlink(ffmpeg_log)
return "done"
# applied=False = 计划为空 -> 既有路径原样继续 (不做任何改动)。
# 自动延时补偿 (经典路径): 修正后的音频轨替换拷贝音频
if channel_sync:
from core.channel_sync import run_channel_sync
from preservation.audio_sync import remux_replace_audio
try:
res = run_channel_sync(
source=src,
ffmpeg=ffmpeg,
work_dir=(work_dir or part_dst.parent) / "channel_sync",
streams=prepared.streams,
opts=channel_sync_opts,
log=lambda msg: logger.info("[SYNC] %s | %s", src.name, msg),
)
file_logger.info(
"CHANNEL_SYNC | %s | %s",
res["status"],
json.dumps(res.get("channels", []), ensure_ascii=False),
)
if res["status"] == "applied":
synced = part_dst.with_name(part_dst.stem + ".synced.mov")
remux_replace_audio(
gpac=gpac, video_src=part_dst,
fixed_files=[Path(p) for p in (res.get("audio_files")
or res["fixed_files"])],
dst=synced,
log=lambda msg: logger.info("[SYNC] %s", msg),
)
# GPAC 输出 mvhd timescale 与源不同: 按实际 timescale 修复
# tkhd/elst 时长 (否则音频被 elst 截断为 1/3)
from core.channel_sync import repair_remux_timescale
repair_remux_timescale(
synced, log=lambda msg: logger.info("[SYNC] %s", msg)
)
safe_unlink(part_dst)
os.replace(synced, part_dst)
elif res["status"] in ("measure_failed", "verify_failed"):
logger.warning(
"[SYNC-SKIP] %s | %s — 原音频照旧",
src.name, res["detail"],
)
except Exception as exc:
logger.warning("[SYNC-FAIL] %s | %s — 原音频照旧", src, exc)
file_logger.exception("CHANNEL SYNC FAILED")
try:
os.replace(part_dst, dst)
except OSError as exc:
logger.error("[RENAME-FAIL] %s -> %s | %s", part_dst, dst, exc)
file_logger.exception("RENAME FAILED | elapsed=%.3f sec", elapsed)
return "failed"
postprobe_and_log(
src=src, dst=dst, preset=preset, elapsed=elapsed,
source_summary=source_summary, ffprobe=ffprobe,
postprobe_csv=postprobe_csv,
postprobe_stream_csv=postprobe_stream_csv,
logger=logger, file_logger=file_logger,
)
safe_unlink(ffmpeg_log)
return "done"
def encode_one_sony(
*,
src: Path,
dst: Path,
prepared: Prepared,
profile: dict[str, Any],
preset: str,
backend,
engine,
ffmpeg: Path,
ffprobe: Path,
postprobe_csv: Path,
postprobe_stream_csv: Path,
gpac: GpacContainerBackend,
gyroflow: Path | None,
work_root: Path,
check_level: str = "basic",
codec: str = "hevc",
quality_opts: dict[str, Any] | None = None,
quality_csv: Path | None = None,
channel_sync: bool = False,
channel_sync_opts: dict[str, Any] | None = None,
logger: logging.Logger,
file_logger: logging.Logger,
dry_run: bool,
) -> str:
"""Sony preservation path (rtmd) for ffmpeg software backends
(x265 / svtav1; --check levels apply like on hardware backends).
codec="av1" 保留元数据但不恢复 XAVC brand (AV1 不在 XAVC 规范内)。"""
import time
from core.paths import job_id_for, safe_unlink
source_summary = prepared.summary
work_dir = work_root / job_id_for(src)
# AV1 中间文件必须是 MP4 (ffmpeg 9 的 MOV muxer 不接受 AV1;
# GPAC 对 MP4/MOV 一视同仁, 时间轴保真不受影响)
encoded_mov = work_dir / "video" / (
"encoded.mp4" if codec == "av1" else "encoded.mov"
)
cmd, effective_params = backend.build_video_command(
ffmpeg, src, encoded_mov, profile,
prepared.effective, prepared.src_info,
)
log_encode_header(
logger=logger, file_logger=file_logger, src=src, preset=preset,
prepared=prepared, engine=engine,
effective_params=effective_params, cmd=cmd,
)
logger.info("[PRESERVE] Sony rtmd source -> preservation pipeline")
file_logger.info("PRESERVATION | sony | work_dir=%s", work_dir)
if dry_run:
file_logger.info("DRY-RUN | no encode performed.")
return "dry-run"
started = time.monotonic()
def encode_video(source: Path, out_mov: Path) -> None:
out_mov.parent.mkdir(parents=True, exist_ok=True)
raw_log = out_mov.with_name(out_mov.name + ".ffmpeg.log")
rc, _ = run_ffmpeg(
cmd, raw_log, source_summary["total_frames"], file_logger
)
if rc is None:
raise RuntimeError("video encode interrupted/failed to run")
if rc != 0:
raise RuntimeError(f"video encode failed (rc={rc}), see {raw_log}")
if not out_mov.is_file() or out_mov.stat().st_size <= 0:
raise RuntimeError("video encode produced no output")
out_frames, out_fps = count_frames(ffprobe, out_mov)
src_frames = source_summary["total_frames"]
if src_frames and out_frames != src_frames:
raise RuntimeError(
f"frame count mismatch: source {src_frames} vs "
f"encoded {out_frames}"
)
src_fps = source_summary["avg_frame_rate"]
if src_fps and out_fps != src_fps:
raise RuntimeError(
f"frame rate mismatch: source {src_fps} vs encoded {out_fps}"
)
def pipe_log(msg: str) -> None:
logger.info("[SONY] %s", msg)
file_logger.info("PIPELINE | %s", msg)
try:
if codec == "av1":
logger.info(
"[POLICY] %s | AV1 保留管线: rtmd/nrtm/uuid 元数据保留, "
"不打 XAVC tag (AV1 不在 XAVC 规范内)",
src.name,
)
file_logger.info(
"POLICY | AV1 Sony preserve: rtmd/nrtm/uuid kept, "
"XAVC brand NOT restored (AV1 not in XAVC spec)"
)
# 自动延时补偿 (Sony): 修正后的音频轨在重建时替代源音轨
audio_sources = None
if channel_sync and source_summary["audio_streams"] > 0:
from core.channel_sync import run_channel_sync
try:
res = run_channel_sync(
source=src,
ffmpeg=ffmpeg,
work_dir=work_dir / "channel_sync",
streams=prepared.streams,
opts=channel_sync_opts,
log=lambda msg: logger.info("[SYNC] %s | %s", src.name, msg),
)
file_logger.info(
"CHANNEL_SYNC | %s | %s",
res["status"],
json.dumps(res.get("channels", []), ensure_ascii=False),
)
if res["status"] == "applied":
audio_sources = [Path(p) for p in (
res.get("audio_files") or res["fixed_files"]
)]
elif res["status"] in ("measure_failed", "verify_failed"):
logger.warning(
"[SYNC-SKIP] %s | %s — 原音频照旧",
src.name, res["detail"],
)
except Exception as exc:
logger.warning("[SYNC-FAIL] %s | %s — 原音频照旧", src, exc)
file_logger.exception("CHANNEL SYNC FAILED")
report = run_sony_pipeline(
source=src,
work_dir=work_dir,
encode_video=encode_video,
gpac=gpac,
ffprobe=ffprobe,
has_audio=source_summary["audio_streams"] > 0,
gyroflow=gyroflow,
fix_hw_timing=False,
check_level=check_level,
codec=codec,
encoded_path=encoded_mov,
ffmpeg=ffmpeg,
quality_opts=quality_opts,
quality_csv=quality_csv,
audio_sources=audio_sources,
log=pipe_log,
)
except Exception as exc:
logger.error("[FAIL] preservation pipeline | %s | %s", src, exc)
file_logger.exception("PRESERVATION PIPELINE FAILED")
return "failed"
elapsed = time.monotonic() - started
gyro = report.get("gyroflow")
if not report.get("structural_success"):
logger.error(
"[FAIL] structural preservation failed | %s | missing=%s "
"modified=%s",
src, report.get("critical_missing"),
report.get("critical_modified"),
)
file_logger.error(
"STRUCTURAL VALIDATION FAILED | missing=%s | modified=%s",
report.get("critical_missing"),
report.get("critical_modified"),
)
return "failed"
if gyro is not None and gyro.get("status") != "PASS":
logger.error("[FAIL] Gyroflow consumer validation | %s | %s",
src, gyro.get("detail"))
file_logger.error("GYROFLOW VALIDATION FAILED | %s", gyro.get("detail"))
return "failed"
dst.parent.mkdir(parents=True, exist_ok=True)
final = work_dir / "final" / "output.mov"
try:
safe_unlink(dst)
os.replace(final, dst)
except OSError as exc:
logger.error("[RENAME-FAIL] %s -> %s | %s", final, dst, exc)
file_logger.exception("RENAME FAILED | elapsed=%.3f sec", elapsed)
return "failed"
s = report["summary"]
logger.info(
"[PRESERVE-OK] %s | PRESERVED=%d MODIFIED=%d MISSING=%d | "
"gyroflow=%s",
src.name, s["PRESERVED"], s["MODIFIED"], s["MISSING"],
gyro.get("status") if gyro else "not-run",
)
file_logger.info(
"PRESERVATION_REPORT | %s",
json.dumps(
{
"summary": s,
"structural_success": report["structural_success"],
"gyroflow": gyro,
"report": str(work_dir / "report.json"),
},
ensure_ascii=False,
),
)
postprobe_and_log(
src=src, dst=dst, preset=preset, elapsed=elapsed,
source_summary=source_summary, ffprobe=ffprobe,
postprobe_csv=postprobe_csv,
postprobe_stream_csv=postprobe_stream_csv,
logger=logger, file_logger=file_logger,
)
return "done"
def encode_one_dji_x265(
*,
src: Path,
dst: Path,
prepared: Prepared,
profile: dict[str, Any],
preset: str,
backend,
engine,
ffmpeg: Path,
ffprobe: Path,
postprobe_csv: Path,
postprobe_stream_csv: Path,
gpac: GpacContainerBackend,
gyroflow: Path | None,
work_root: Path,
check_level: str = "basic",
video_entry: str = "hvc1",
quality_opts: dict[str, Any] | None = None,
quality_csv: Path | None = None,
channel_sync: bool = False,
channel_sync_opts: dict[str, Any] | None = None,
logger: logging.Logger,
file_logger: logging.Logger,
dry_run: bool,
) -> str:
"""DJI preservation path for ffmpeg software backends (x265/svtav1).
Video-only encode (video intermediate is an FFmpeg MOV — no rigaya
millisecond quantization, so fix_hw_timing=False) + shared GPAC
rebuild (djmd/dbgi/tmcd native copies) + dji check.
video_entry: "hvc1" (HEVC) / "av01" (AV1)."""
import time
from core.paths import job_id_for, safe_unlink
from preservation import dji
source_summary = prepared.summary
work_dir = work_root / job_id_for(src)
# AV1 中间文件必须是 MP4 (ffmpeg 9 的 MOV muxer 不接受 AV1)
encoded_mov = work_dir / "video" / (
"encoded.mp4" if video_entry == "av01" else "encoded.mov"
)
cmd, effective_params = backend.build_video_command(
ffmpeg, src, encoded_mov, profile,
prepared.effective, prepared.src_info,
)
log_encode_header(
logger=logger, file_logger=file_logger, src=src, preset=preset,
prepared=prepared, engine=engine,
effective_params=effective_params, cmd=cmd,
)
file_logger.info(
"POLICY | DJI source (djmd): %s 保留管线 "
"(视频重编码 + djmd/dbgi/tmcd 原生保留)",
backend.name,
)
logger.info(
"[POLICY] %s | DJI: %s 保留管线, djmd/dbgi/tmcd 原生保留",
src.name, backend.name,
)
if dry_run:
file_logger.info("DRY-RUN | no encode performed.")
return "dry-run"
started = time.monotonic()
def pipe_log(msg: str) -> None:
logger.info("[DJI] %s", msg)
file_logger.info("DJI_PIPELINE | %s", msg)
try:
encoded_mov.parent.mkdir(parents=True, exist_ok=True)
raw_log = encoded_mov.with_name(encoded_mov.name + ".ffmpeg.log")
rc, _ = run_ffmpeg(
cmd, raw_log, source_summary["total_frames"], file_logger
)
if rc is None or rc != 0:
raise RuntimeError(f"video encode failed (rc={rc})")
if not encoded_mov.is_file() or encoded_mov.stat().st_size <= 0:
raise RuntimeError("video encode produced no output")
out_frames, out_fps = count_frames(ffprobe, encoded_mov)
src_frames = source_summary["total_frames"]
if src_frames and out_frames != src_frames:
raise RuntimeError(
f"frame count mismatch: source {src_frames} vs "
f"encoded {out_frames}"
)
pipe_log(f"video ready: {encoded_mov}")
# 自动延时补偿 (DJI): 修正后的音频轨在重建时替代源音轨
audio_sources = None
if channel_sync and source_summary["audio_streams"] > 0:
from core.channel_sync import run_channel_sync
try:
res = run_channel_sync(
source=src,
ffmpeg=ffmpeg,
work_dir=work_dir / "channel_sync",
streams=prepared.streams,
opts=channel_sync_opts,
log=lambda msg: logger.info("[SYNC] %s | %s", src.name, msg),
)
file_logger.info(
"CHANNEL_SYNC | %s | %s",
res["status"],
json.dumps(res.get("channels", []), ensure_ascii=False),
)