Separate system accounts and household people, add generation directory and consented member location sharing
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
"""Readable archive paths and lossless MP4 provenance metadata.
|
||||
|
||||
Camera H.264/H.265 streams already encode inter-frame differences. Preserve
|
||||
their packets and timing, rather than spending the small server's CPU on a
|
||||
second lossy encode or discarding supposedly static frames.
|
||||
"""
|
||||
import datetime as dt
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
ZONE = dt.timezone(dt.timedelta(hours=8))
|
||||
ID = r'[a-f0-9]{16}'
|
||||
STAMP = r'\d{4}-\d\d-\d\d_\d\d-\d\d-\d\d-\d{6}'
|
||||
|
||||
|
||||
def label(name, fallback):
|
||||
value = re.sub(r'[\x00-\x1f\x7f/\\:*?"<>|]', '_', str(name or '')).strip(' .')
|
||||
return value[:40] or fallback
|
||||
|
||||
|
||||
def times(row):
|
||||
return tuple(dt.datetime.fromtimestamp(n, ZONE) for n in (row['started'], row['started']+row['duration']))
|
||||
|
||||
|
||||
def remote_path(folder, instance, row, family_name, camera_name):
|
||||
start, end = times(row)
|
||||
filename = (start.strftime('%Y-%m-%d_%H-%M-%S-%f')+'_至_'+end.strftime('%Y-%m-%d_%H-%M-%S-%f')
|
||||
+'_UTC+0800_'+instance+'_'+row['id']+'.mp4')
|
||||
return ('/apps/'+folder+'/'+label(family_name,'家庭')+'_'+row['family']+'/摄像头/'
|
||||
+label(camera_name,'摄像头')+'_'+row['camera']+'/'+start.strftime('%Y/%m/%d')+'/'+filename)
|
||||
|
||||
|
||||
def valid_path(remote, folder, instance, row=None):
|
||||
"""Exact application/instance scope; optional row binds both ownership IDs."""
|
||||
if not re.fullmatch(ID, instance): return False
|
||||
old = '/apps/'+folder+'/监控录像/'+instance+'/'
|
||||
if remote.startswith(old):
|
||||
match = re.fullmatch('('+ID+')/('+ID+')/'+r'(\d{4}-\d\d-\d\d)/('+STAMP+r'\.mp4)', remote[len(old):])
|
||||
return bool(match and (row is None or (match[1]==row['family'] and match[2]==row['camera']
|
||||
and match[3]==times(row)[0].strftime('%Y-%m-%d') and match[4]==row['path'].replace('\\','/').split('/')[-1])))
|
||||
root = '/apps/'+folder+'/'
|
||||
if not remote.startswith(root): return False
|
||||
parts = remote[len(root):].split('/')
|
||||
if len(parts) != 7 or parts[1] != '摄像头': return False
|
||||
family = re.fullmatch(r'([^/\\:*?"<>|\x00-\x1f\x7f]{1,40})_('+ID+')', parts[0])
|
||||
camera = re.fullmatch(r'([^/\\:*?"<>|\x00-\x1f\x7f]{1,40})_('+ID+')', parts[2])
|
||||
name = re.fullmatch('('+STAMP+')_至_('+STAMP+')'+r'_UTC\+0800_'+instance+r'_([a-f0-9]{32})\.mp4', parts[6])
|
||||
if not family or not camera or not name: return False
|
||||
try:
|
||||
start = dt.datetime.strptime(name[1], '%Y-%m-%d_%H-%M-%S-%f')
|
||||
end = dt.datetime.strptime(name[2], '%Y-%m-%d_%H-%M-%S-%f')
|
||||
if end <= start or parts[3:6] != start.strftime('%Y/%m/%d').split('/'): return False
|
||||
except ValueError: return False
|
||||
if row is None: return True
|
||||
return (family[2]==row['family'] and camera[2]==row['camera'] and name[3]==row['id']
|
||||
and (name[1],name[2])==tuple(t.strftime('%Y-%m-%d_%H-%M-%S-%f') for t in times(row)))
|
||||
|
||||
|
||||
def probe(file):
|
||||
result = subprocess.run(['ffprobe','-v','error','-count_packets','-show_entries',
|
||||
'format=duration:format_tags:stream=codec_name,codec_type,width,height,nb_read_packets,avg_frame_rate',
|
||||
'-of','json',str(file)], capture_output=True, check=True, timeout=60)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def packet_hash(file):
|
||||
result = subprocess.run(['ffmpeg','-v','error','-nostdin','-i',str(file),'-map','0:v','-map','0:a?',
|
||||
'-c','copy','-f','streamhash','-hash','sha256','-'],capture_output=True,check=True,timeout=90)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def prepare(source, target, row, family_name, camera_name):
|
||||
"""Remux one closed segment; verify every encoded packet before using it."""
|
||||
start, end = times(row)
|
||||
before = probe(source)
|
||||
tags = dict(creation_time=start.astimezone(dt.timezone.utc).isoformat(),
|
||||
recording_start=start.isoformat(),recording_end=end.isoformat(),
|
||||
recording_timezone='Asia/Shanghai (UTC+08:00)',recording_time_source='server_segment_clock',
|
||||
household_id=row['family'],camera_id=row['camera'],recording_id=row['id'],
|
||||
title=camera_name,album=family_name,
|
||||
comment=f'录制开始:{start.isoformat()};录制结束:{end.isoformat()};时间基准:服务器录制时钟;原始码流连续保存')
|
||||
command=['ffmpeg','-v','error','-nostdin','-y','-i',str(source),'-map','0:v','-map','0:a?',
|
||||
'-c','copy','-movflags','+faststart+use_metadata_tags']
|
||||
for key,value in tags.items(): command += ['-metadata',key+'='+str(value)]
|
||||
command += ['-metadata:s:v:0','creation_time='+tags['creation_time'],str(target)]
|
||||
subprocess.run(command,capture_output=True,check=True,timeout=120)
|
||||
after=probe(target)
|
||||
streams=lambda p:[(s['codec_type'],s['codec_name'],s.get('width'),s.get('height'),s.get('nb_read_packets'))
|
||||
for s in p['streams'] if s['codec_type'] in ('video','audio')]
|
||||
if (streams(before)!=streams(after)
|
||||
or abs(float(before['format']['duration'])-float(after['format']['duration']))>.15
|
||||
or abs(float(before['format']['duration'])-row['duration'])>2
|
||||
or after['format'].get('tags',{}).get('recording_start')!=tags['recording_start']
|
||||
or after['format'].get('tags',{}).get('recording_end')!=tags['recording_end']
|
||||
or packet_hash(source)!=packet_hash(target)):
|
||||
raise ValueError('录像封装校验失败,原片段已保留')
|
||||
video=next(s for s in after['streams'] if s['codec_type']=='video')
|
||||
return dict(start=start.isoformat(),end=end.isoformat(),timezone='Asia/Shanghai',
|
||||
codec=video['codec_name'],width=video.get('width'),height=video.get('height'),
|
||||
packets=video.get('nb_read_packets'),mode='original-packet-copy',
|
||||
timeSource='server_segment_clock',familyName=family_name,cameraName=camera_name,size=target.stat().st_size)
|
||||
Reference in New Issue
Block a user