Skip to content

Instantly share code, notes, and snippets.

@0KepOnline
Created February 19, 2023 10:06
Show Gist options
  • Save 0KepOnline/e1c77afd3a78253394081848fea122c1 to your computer and use it in GitHub Desktop.
Save 0KepOnline/e1c77afd3a78253394081848fea122c1 to your computer and use it in GitHub Desktop.
import os, subprocess, mimetypes, zlib, sys, getopt
def help():
help = [
'Options:',
' -i (--input) - input stream file',
' -o (--output) - output archive file (.mkv)',
' -d (--dir) - archive directory (file)',
]
print("\n".join(help))
sys.exit()
def get_crc32(file_path):
with open(file_path, 'rb') as file:
return zlib.crc32(file.read())
def get_mime(file_path):
mime_type = mimetypes.guess_type(file_path)[0]
with open(file_path, 'rb') as file:
if not mime_type:
try:
file.read().decode('utf-8')
except UnicodeDecodeError:
mime_type = 'application/octet-stream'
else:
mime_type = 'text/plain'
return mime_type
def create_archive(archive_dir, input_file, output_file):
file_list = []
if os.path.isdir(archive_dir):
for root, dirs, files in os.walk(archive_dir):
for file in files:
file_list.append(os.path.join(root, file))
elif os.path.isfile(archive_dir):
file_list.append(archive_dir)
ffargs = ['ffmpeg', '-i', input_file, '-c', 'copy', '-map_metadata', '0']
file_number = 0
for file in file_list:
mime_type = get_mime(file)
crc32 = get_crc32(file)
file_size = os.path.getsize(file)
if mime_type and crc32 and file_size:
ffargs += [
'-metadata:s:t:' + str(file_number), f'mimetype={mime_type}',
'-metadata:s:t:' + str(file_number), f'crc32={format(crc32, "08x")}',
'-metadata:s:t:' + str(file_number), f'size={file_size}',
'-attach', file
]
file_number += 1
ffargs += [output_file]
subprocess.run(ffargs)
def main(argv):
archive_dir = ''
input_file = 'dummy.mkv'
output_file = 'archive.mkv'
if argv:
opts, args = getopt.getopt(argv,'i:o:d:h',['input=','output=','dir='])
for opt, arg in opts:
if opt in ('-i', '--input'):
input_file = arg
elif opt in ('-o', '--output'):
output_file = arg
elif opt in ('-d', '--dir'):
archive_dir = arg
elif opt == '-h':
help()
else:
help()
create_archive(archive_dir, input_file, output_file)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment