Skip to content

Instantly share code, notes, and snippets.

@kjy00302
Created March 31, 2020 18:53
Show Gist options
  • Save kjy00302/0c66429c13f91285444d4c1f29375eee to your computer and use it in GitHub Desktop.
Save kjy00302/0c66429c13f91285444d4c1f29375eee to your computer and use it in GitHub Desktop.
Sofdec2(USM) subtitle file converter
import struct
import sys
desc = """
Sofdec2(USM) subtitle file converter
crisub_conv.py filename
"""
if len(sys.argv) != 2:
print(desc)
quit()
filename = sys.argv[1]
newfilename = '.'.join(filename.split('.')[:-1])
def millisec_to_timestamp(ms):
h = (ms // (3600*1000))
tmp = (ms % (3600*1000))
m = (tmp // (60*1000))
tmp = (ms % (60*1000))
s = (tmp // (1000))
ms = (ms % (1000))
return f'{h:02d}:{m:02d}:{s:02d},{ms:03d}'
subs = {}
with open(filename, 'rb') as f:
while rawdata := f.read(20):
substream_num, chk, pos, duration, txt_len = struct.unpack('<5I', rawdata)
assert chk == 1000
txt = struct.unpack(f'<{txt_len}s', f.read(txt_len))[0]
if subs.get(substream_num) == None:
subs[substream_num] = []
subs[substream_num].append({
'pos': pos,
'duration': duration,
'text': txt.rstrip(b'\x00').decode('utf-8')
})
for idx, sub in subs.items():
with open(f'{newfilename}.{idx}.srt', 'w') as f:
for n, i in enumerate(sub):
f.write(f'{n+1}\n')
f.write(f'{millisec_to_timestamp(i["pos"])} --> {millisec_to_timestamp(i["pos"] + i["duration"])}\n')
f.write(i['text'])
f.write('\n\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment