-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbifgen.py
executable file
·209 lines (184 loc) · 8.01 KB
/
bifgen.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
#!/usr/bin/env python3
import os
import sys
import struct
import array
import shutil
import tempfile
import cv2
from argparse import ArgumentParser
from PIL import Image
from pathlib import Path
modes = {'sd': (240,136), 'hd': (320,180)}
def human_duration(t):
dur = []
while t and len(dur) < 3:
dur.append(t % 60)
t = t//60
if len(dur) == 1: dur.append(0)
dur.reverse()
return ':'.join([str(dur[0])] + ['0' * (2 - len(str(n))) + str(n) for n in dur[1:]])
def greatest_common_denom(a, b):
while b:
a, b = b, a % b
return a
def get_metadata(filepath):
metadata = {}
if os.path.isfile(filepath):
vcap = cv2.VideoCapture(filepath)
if vcap.isOpened():
metadata['width'] = int(vcap.get(cv2.CAP_PROP_FRAME_WIDTH))
metadata['height'] = int(vcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
metadata['aspect'] = float(metadata['width'] / metadata['height'])
vcap.set(cv2.CAP_PROP_POS_AVI_RATIO,1)
fps = vcap.get(cv2.CAP_PROP_FPS)
frame_count = vcap.get(cv2.CAP_PROP_FRAME_COUNT)
metadata['duration_ms'] = int(frame_count/fps) * 1000
metadata['duration'] = int(frame_count/fps)
return (True, metadata)
return (False, metadata)
def extract_images(filepath, metadata, directory, args):
vcap = cv2.VideoCapture(filepath)
if vcap.isOpened():
# start at [offset] seconds & go to [duration] seconds
# via [interval] second `skips', saving an image of the
# proper size each time
img_count = 0
if not args.silent:
print('extracting images... ', end='', flush=True)
msg = ''
while ((args.offset + (img_count * args.interval)) * 1000
< metadata['duration_ms']):
pos = args.offset + (img_count * args.interval)
vcap.set(cv2.CAP_PROP_POS_MSEC, pos * 1000)
if not args.silent:
newmsg = '[{0:.0f}%]'.format(100 * pos / metadata['duration'])
if not msg == newmsg:
print('\b' * len(msg) + '\x1B[K', end='')
msg = newmsg
print(msg, end='', flush=True)
img_count += 1
success,img = vcap.read()
if success:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
img = img.resize(modes[args.mode], Image.LANCZOS)
filename = (8 - len(str(img_count))) * '0' + str(img_count) + '.jpg'
img.save(os.path.join(directory, filename))
else:
if not args.silent:
print('\r\x1B[Kerror capturing frame {0} (@{1}sec)!'.format(img_count, pos))
print('could not finish generating bif file.')
return False
if not args.silent:
print('\b' * len(msg) + '\x1B[K', end='')
print('done ({0} images)'.format(img_count))
return True
def assemble_bif(output_location, img_directory, args):
magic_number = [0x89,0x42,0x49,0x46,0x0d,0x0a,0x1a,0x0a]
version = 0
if not args.silent:
print('assembling bif file... ', end='', flush=True)
msg=''
images = [image for image in os.listdir('{0}'.format(img_directory)) if os.path.splitext(image)[1] == '.jpg']
images.sort()
with open(output_location, 'wb') as f:
array.array('B', magic_number).tofile(f)
f.write(struct.pack('<I', version))
f.write(struct.pack('<I', len(images)))
f.write(struct.pack('<I', 1000 * args.interval))
array.array('B', [0x00] * 44).tofile(f)
total_size = 8 * (len(images) + 1)
index = 64 + total_size
for n in range(len(images)):
if not args.silent:
print('\b' * len(msg) + '\x1B[K', end='')
msg = '[{0}%]'.format(int(50 * n / len(images)))
print(msg, end='', flush=True)
image = images[n]
f.write(struct.pack('<I', n))
f.write(struct.pack('<I', index))
index += os.stat(os.path.join(img_directory, image)).st_size
f.write(struct.pack('<I', 0xffffffff))
f.write(struct.pack('<I', index))
for n in range(len(images)):
if not args.silent:
print('\b' * len(msg) + '\x1B[K', end='')
msg = '[{0}%]'.format(50 + int(50 * n / len(images)))
print(msg, end='', flush=True)
data = open(os.path.join(img_directory, images[n]), 'rb').read()
f.write(data)
if not args.silent:
print('\b' * len(msg) + '\x1B[K', end='')
print('done')
def cmdline_main():
parser = ArgumentParser(description='''generate bif files in order to
enable/support positional trickplay thumbnails on
roku devices.''')
parser.add_argument('filepaths', metavar='sourcevid', nargs='+', type=str,
help='video file(s) to process')
parser.add_argument('-i', '--interval', metavar='N', dest='interval',
type=int, default=10,
help='interval between images in seconds (10 by '
'default)')
parser.add_argument('-O', '--offset', metavar='N', dest='offset', type=int,
default=0,
help='offset to first image in seconds (0 by default)')
parser.add_argument('-o', '--out', metavar='PATH', dest='output', type=str,
help='destination path where result will be saved')
parser.add_argument('--sd', dest='mode', action='store_const', const='sd',
default='hd',
help='resulting bif file will be sd instead of hd')
parser.add_argument('-s', '--silent', dest='silent', action='store_const',
const=True, default=False,
help='do not print progress or diagnostic information '
'to stdout')
'''
parser.add_argument('-y', '--overwrite', dest='overwrite',
action='store_const', const=True, default=False,
help='if destination exists, overwrite it without '
'prompting')
'''
args = parser.parse_args()
for file in args.filepaths:
success, metadata = get_metadata(file)
if not success:
if not args.silent:
print('ERROR: invalid or corrupt video file: {0}'.format(file))
continue
gcd=greatest_common_denom(metadata['width'], metadata['height'])
if not args.silent:
print('source: {0} (aspect ratio {1}:{2}, runtime {3})'.format(
os.path.basename(file),
int(metadata['width'] / gcd),
int(metadata['height'] / gcd),
human_duration(metadata['duration'])))
width, height = modes[args.mode]
width = int(metadata['aspect'] * height)
modes[args.mode] = (width, height)
temp_dest = tempfile.mkdtemp()
out_fn = '{0}-{1}.bif'.format(
os.path.splitext(os.path.basename(file))[0], args.mode.upper())
dest = args.output
if dest is None:
dest = './{0}'.format(out_fn)
elif os.path.isdir(dest):
dest = Path(dest, out_fn)
elif len(args.filepaths) > 1:
dest = Path(os.path.dirname(file), out_fn)
'''
if os.path.isfile(dest) and not args.overwrite:
print('output file {0} already exists.', end=' ')
result = input('Overwrite? [y/N] ').lower()
if result.lower() != 'y' and result != 'yes':
print('skipping {0}'.format(file))
continue
'''
if extract_images(file, metadata, temp_dest, args):
assemble_bif(dest, temp_dest, args)
shutil.rmtree(temp_dest)
if not args.silent:
print('result: {0}'.format(dest))
if __name__ == '__main__':
cmdline_main()
# vim:fdm=marker