| 1 |
import re |
| 2 |
import struct |
| 3 |
|
| 4 |
from concurrent.futures import ProcessPoolExecutor |
| 5 |
|
| 6 |
from pyglet.util import DecodeException |
| 7 |
from pyglet.media.codecs.base import StreamingSource, AudioData, AudioFormat, StaticSource |
| 8 |
from pyglet.media.codecs import MediaDecoder |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
class FLACDecodeException(DecodeException): |
| 16 |
pass |
| 17 |
|
| 18 |
|
| 19 |
FIXED_PREDICTION_COEFFICIENTS = ((), (1,), (2, -1), (3, -3, 1), (4, -6, 4, -1)) |
| 20 |
|
| 21 |
|
| 22 |
def _initializer(filename, numchannels, sample_size): |
| 23 |
"""Function to open a copy of the file locally in each Process.""" |
| 24 |
global _file |
| 25 |
global _numchannels |
| 26 |
global _sample_size |
| 27 |
_file = open(filename, 'rb') |
| 28 |
_numchannels = numchannels |
| 29 |
_sample_size = sample_size |
| 30 |
|
| 31 |
|
| 32 |
def decode_frame(offset): |
| 33 |
try: |
| 34 |
|
| 35 |
numchannels = _numchannels |
| 36 |
sample_size = _sample_size |
| 37 |
_file.seek(offset) |
| 38 |
inp = BitInputStream(_file) |
| 39 |
|
| 40 |
temp = inp.read_byte() |
| 41 |
if temp == -1: |
| 42 |
return False |
| 43 |
sync = temp << 6 | inp.read_uint(6) |
| 44 |
if sync != 0x3FFE: |
| 45 |
raise FLACDecodeException("Sync code expected") |
| 46 |
|
| 47 |
inp.read_uint(1) |
| 48 |
inp.read_uint(1) |
| 49 |
blocksizecode = inp.read_uint(4) |
| 50 |
sampleratecode = inp.read_uint(4) |
| 51 |
chanasgn = inp.read_uint(4) |
| 52 |
inp.read_uint(3) |
| 53 |
inp.read_uint(1) |
| 54 |
|
| 55 |
temp = inp.read_uint(8) |
| 56 |
while temp >= 0b11000000: |
| 57 |
inp.read_uint(8) |
| 58 |
temp = (temp << 1) & 0xFF |
| 59 |
|
| 60 |
if blocksizecode == 1: |
| 61 |
blocksize = 192 |
| 62 |
elif 2 <= blocksizecode <= 5: |
| 63 |
blocksize = 576 << blocksizecode - 2 |
| 64 |
elif blocksizecode == 6: |
| 65 |
blocksize = inp.read_uint(8) + 1 |
| 66 |
elif blocksizecode == 7: |
| 67 |
blocksize = inp.read_uint(16) + 1 |
| 68 |
elif 8 <= blocksizecode <= 15: |
| 69 |
blocksize = 256 << (blocksizecode - 8) |
| 70 |
else: |
| 71 |
raise FLACDecodeException("Invalid Blocksize") |
| 72 |
|
| 73 |
if sampleratecode == 12: |
| 74 |
inp.read_uint(8) |
| 75 |
elif sampleratecode in (13, 14): |
| 76 |
inp.read_uint(16) |
| 77 |
|
| 78 |
crc8 = inp.read_byte() |
| 79 |
|
| 80 |
|
| 81 |
if 0 <= chanasgn <= 7: |
| 82 |
samples = [decode_subframe(inp, blocksize, sample_size) for _ in range(chanasgn + 1)] |
| 83 |
elif 8 <= chanasgn <= 10: |
| 84 |
temp0 = decode_subframe(inp, blocksize, sample_size + (1 if (chanasgn == 9) else 0)) |
| 85 |
temp1 = decode_subframe(inp, blocksize, sample_size + (0 if (chanasgn == 9) else 1)) |
| 86 |
if chanasgn == 8: |
| 87 |
for i in range(blocksize): |
| 88 |
temp1[i] = temp0[i] - temp1[i] |
| 89 |
elif chanasgn == 9: |
| 90 |
for i in range(blocksize): |
| 91 |
temp0[i] += temp1[i] |
| 92 |
elif chanasgn == 10: |
| 93 |
for i in range(blocksize): |
| 94 |
side = temp1[i] |
| 95 |
right = temp0[i] - (side >> 1) |
| 96 |
temp1[i] = right |
| 97 |
temp0[i] = right + side |
| 98 |
samples = [temp0, temp1] |
| 99 |
else: |
| 100 |
raise FLACDecodeException("Reserved channel assignment") |
| 101 |
|
| 102 |
inp.align_to_byte() |
| 103 |
inp.read_byte() |
| 104 |
inp.read_byte() |
| 105 |
|
| 106 |
|
| 107 |
fmt = str(blocksize * numchannels) + 'h' |
| 108 |
if sample_size == 8: |
| 109 |
return struct.pack(fmt, *(samples[i][j] + 128 for j in range(blocksize) for i in range(numchannels))) |
| 110 |
else: |
| 111 |
return struct.pack(fmt, *(samples[i][j] for j in range(blocksize) for i in range(numchannels))) |
| 112 |
except: |
| 113 |
return b"" |
| 114 |
|
| 115 |
|
| 116 |
def decode_subframe(inp, blocksize, sampledepth): |
| 117 |
inp.read_uint(1) |
| 118 |
subframe_type = inp.read_uint(6) |
| 119 |
shift = inp.read_uint(1) |
| 120 |
if shift == 1: |
| 121 |
while inp.read_uint(1) == 0: |
| 122 |
shift += 1 |
| 123 |
sampledepth -= shift |
| 124 |
|
| 125 |
if subframe_type == 0: |
| 126 |
result = [inp.read_signed_int(sampledepth)] * blocksize |
| 127 |
elif subframe_type == 1: |
| 128 |
result = [inp.read_signed_int(sampledepth) for _ in range(blocksize)] |
| 129 |
elif 8 <= subframe_type <= 12: |
| 130 |
result = decode_fixed_prediction_subframe(inp, subframe_type - 8, blocksize, sampledepth) |
| 131 |
elif 32 <= subframe_type <= 63: |
| 132 |
result = decode_linear_predictive_coding_subframe(inp, subframe_type - 31, blocksize, sampledepth) |
| 133 |
else: |
| 134 |
raise FLACDecodeException("Reserved subframe type") |
| 135 |
return [(v << shift) for v in result] |
| 136 |
|
| 137 |
|
| 138 |
def decode_fixed_prediction_subframe(inp, predorder, blocksize, sampledepth): |
| 139 |
result = [inp.read_signed_int(sampledepth) for _ in range(predorder)] |
| 140 |
decode_residuals(inp, blocksize, result) |
| 141 |
restore_linear_prediction(result, FIXED_PREDICTION_COEFFICIENTS[predorder], 0) |
| 142 |
return result |
| 143 |
|
| 144 |
|
| 145 |
def decode_linear_predictive_coding_subframe(inp, lpcorder, blocksize, sampledepth): |
| 146 |
result = [inp.read_signed_int(sampledepth) for _ in range(lpcorder)] |
| 147 |
precision = inp.read_uint(4) + 1 |
| 148 |
shift = inp.read_signed_int(5) |
| 149 |
coefs = [inp.read_signed_int(precision) for _ in range(lpcorder)] |
| 150 |
decode_residuals(inp, blocksize, result) |
| 151 |
restore_linear_prediction(result, coefs, shift) |
| 152 |
return result |
| 153 |
|
| 154 |
|
| 155 |
def decode_residuals(inp, blocksize, result): |
| 156 |
method = inp.read_uint(2) |
| 157 |
if method >= 2: |
| 158 |
raise FLACDecodeException("Reserved residual coding method") |
| 159 |
parambits = [4, 5][method] |
| 160 |
escapeparam = [0xF, 0x1F][method] |
| 161 |
|
| 162 |
partitionorder = inp.read_uint(4) |
| 163 |
numpartitions = 1 << partitionorder |
| 164 |
if blocksize % numpartitions != 0: |
| 165 |
raise FLACDecodeException("Block size not divisible by number of Rice partitions") |
| 166 |
|
| 167 |
for i in range(numpartitions): |
| 168 |
count = blocksize >> partitionorder |
| 169 |
if i == 0: |
| 170 |
count -= len(result) |
| 171 |
param = inp.read_uint(parambits) |
| 172 |
if param < escapeparam: |
| 173 |
result.extend(inp.read_rice_signed_int(param) for _ in range(count)) |
| 174 |
else: |
| 175 |
numbits = inp.read_uint(5) |
| 176 |
result.extend(inp.read_signed_int(numbits) for _ in range(count)) |
| 177 |
|
| 178 |
|
| 179 |
def restore_linear_prediction(result, coefs, shift): |
| 180 |
for i in range(len(coefs), len(result)): |
| 181 |
result[i] += sum((result[i - 1 - j] * c) for (j, c) in enumerate(coefs)) >> shift |
| 182 |
|
| 183 |
|
| 184 |
class BitInputStream: |
| 185 |
__slots__ = 'inp', 'bitbuffer', 'bitbufferlen' |
| 186 |
|
| 187 |
def __init__(self, inp): |
| 188 |
self.inp = inp |
| 189 |
self.bitbuffer = 0 |
| 190 |
self.bitbufferlen = 0 |
| 191 |
|
| 192 |
def align_to_byte(self): |
| 193 |
self.bitbufferlen -= self.bitbufferlen % 8 |
| 194 |
|
| 195 |
def read_byte(self): |
| 196 |
if self.bitbufferlen >= 8: |
| 197 |
return self.read_uint(8) |
| 198 |
else: |
| 199 |
result = self.inp.read(1) |
| 200 |
if len(result) == 0: |
| 201 |
return -1 |
| 202 |
return result[0] |
| 203 |
|
| 204 |
def read_uint(self, n): |
| 205 |
bitbuffer = self.bitbuffer |
| 206 |
bitbufferlen = self.bitbufferlen |
| 207 |
|
| 208 |
while bitbufferlen < n: |
| 209 |
temp = self.inp.read(1) |
| 210 |
if len(temp) == 0: |
| 211 |
raise EOFError() |
| 212 |
temp = temp[0] |
| 213 |
bitbuffer = (bitbuffer << 8) | temp |
| 214 |
bitbufferlen += 8 |
| 215 |
bitbufferlen -= n |
| 216 |
result = (bitbuffer >> bitbufferlen) & ((1 << n) - 1) |
| 217 |
bitbuffer &= (1 << bitbufferlen) - 1 |
| 218 |
|
| 219 |
self.bitbuffer = bitbuffer |
| 220 |
self.bitbufferlen = bitbufferlen |
| 221 |
return result |
| 222 |
|
| 223 |
def read_signed_int(self, n): |
| 224 |
temp = self.read_uint(n) |
| 225 |
temp -= (temp >> (n - 1)) << n |
| 226 |
return temp |
| 227 |
|
| 228 |
def read_rice_signed_int(self, param): |
| 229 |
read_uint = self.read_uint |
| 230 |
val = 0 |
| 231 |
while read_uint(1) == 0: |
| 232 |
val += 1 |
| 233 |
val = (val << param) | read_uint(param) |
| 234 |
return (val >> 1) ^ -(val & 1) |
| 235 |
|
| 236 |
def close(self): |
| 237 |
self.inp.close() |
| 238 |
|
| 239 |
|
| 240 |
def _find_frame_indicies(data): |
| 241 |
magic1 = struct.pack('BB', int('11111111', 2), int('11111000', 2)) |
| 242 |
magic2 = struct.pack('BB', int('11111111', 2), int('11111001', 2)) |
| 243 |
indices1 = [m.start() for m in re.finditer(magic1, data)] |
| 244 |
indices2 = [m.start() for m in re.finditer(magic2, data)] |
| 245 |
indices = indices1 + indices2 |
| 246 |
indices.sort() |
| 247 |
return indices |
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
class FLACSource(StreamingSource): |
| 254 |
def __init__(self, filename, file=None): |
| 255 |
if file is None: |
| 256 |
file = open(filename, 'rb') |
| 257 |
|
| 258 |
self.frame_indices = _find_frame_indicies(file.read()) |
| 259 |
self.frame_index = 0 |
| 260 |
file.seek(0) |
| 261 |
self._file = BitInputStream(file) |
| 262 |
self._filename = filename |
| 263 |
|
| 264 |
if file.read(4) != b'fLaC': |
| 265 |
raise FLACDecodeException("Does not appear to be a FLAC file.") |
| 266 |
|
| 267 |
samplerate = numchannels = bits_per_sample = numsamples = None |
| 268 |
|
| 269 |
last = False |
| 270 |
while not last: |
| 271 |
last = self._file.read_uint(1) != 0 |
| 272 |
block_type = self._file.read_uint(7) |
| 273 |
length = self._file.read_uint(24) |
| 274 |
if block_type == 0: |
| 275 |
min_block_size = self._file.read_uint(16) |
| 276 |
max_block_size = self._file.read_uint(16) |
| 277 |
min_frame_size = self._file.read_uint(24) |
| 278 |
max_frame_size = self._file.read_uint(24) |
| 279 |
samplerate = self._file.read_uint(20) |
| 280 |
numchannels = self._file.read_uint(3) + 1 |
| 281 |
bits_per_sample = self._file.read_uint(5) + 1 |
| 282 |
numsamples = self._file.read_uint(36) |
| 283 |
self._file.read_uint(128) |
| 284 |
else: |
| 285 |
for i in range(length): |
| 286 |
self._file.read_byte() |
| 287 |
|
| 288 |
for offset in self.frame_indices: |
| 289 |
if offset < self._file.inp.tell(): |
| 290 |
self.frame_indices.remove(offset) |
| 291 |
|
| 292 |
if not samplerate: |
| 293 |
raise FLACDecodeException("Stream info metadata block absent") |
| 294 |
if bits_per_sample % 8 != 0: |
| 295 |
raise FLACDecodeException("Sample depth {} not supported".format(bits_per_sample)) |
| 296 |
|
| 297 |
self._numsamples = numsamples |
| 298 |
self._duration = float(numsamples) / samplerate / 60 |
| 299 |
self.audio_format = AudioFormat(numchannels, bits_per_sample, samplerate) |
| 300 |
|
| 301 |
self.executor = ProcessPoolExecutor(max_workers=3, initializer=_initializer, |
| 302 |
initargs=(filename, numchannels, bits_per_sample)) |
| 303 |
|
| 304 |
def __del__(self): |
| 305 |
self._file.close() |
| 306 |
|
| 307 |
def get_audio_data(self, num_bytes, compensation_time=0.0): |
| 308 |
|
| 309 |
data = b'' |
| 310 |
|
| 311 |
while not data and (self.frame_index <= len(self.frame_indices)): |
| 312 |
offset = self.frame_indices[self.frame_index] |
| 313 |
future = self.executor.submit(decode_frame, offset) |
| 314 |
data += future.result() |
| 315 |
self.frame_index += 1 |
| 316 |
|
| 317 |
if not data: |
| 318 |
return None |
| 319 |
|
| 320 |
return AudioData(data, len(data), timestamp=0.1, duration=0.5, events=[]) |
| 321 |
|
| 322 |
def save(self, filename="output.wav"): |
| 323 |
with open(filename, 'wb') as out: |
| 324 |
numsamples = self._numsamples |
| 325 |
numchannels = self.audio_format.channels |
| 326 |
samplerate = self.audio_format.sample_rate |
| 327 |
sample_size = self.audio_format.sample_size |
| 328 |
|
| 329 |
|
| 330 |
sampledatalen = numsamples * numchannels * (sample_size // 8) |
| 331 |
|
| 332 |
out.write(b"RIFF") |
| 333 |
out.write(struct.pack("<I", sampledatalen + 36)) |
| 334 |
out.write(b"WAVE") |
| 335 |
out.write(b"fmt ") |
| 336 |
out.write(struct.pack("<IHHIIHH", |
| 337 |
16, |
| 338 |
0x0001, |
| 339 |
numchannels, |
| 340 |
samplerate, |
| 341 |
samplerate * numchannels * (sample_size // 8), |
| 342 |
numchannels * (sample_size // 8), |
| 343 |
sample_size)) |
| 344 |
out.write(b"data") |
| 345 |
out.write(struct.pack("<I", sampledatalen)) |
| 346 |
|
| 347 |
import time |
| 348 |
start = time.time() |
| 349 |
futures = [self.executor.submit(decode_frame, offset) for offset in self.frame_indices] |
| 350 |
print("elapsed future making", time.time() - start) |
| 351 |
|
| 352 |
while futures: |
| 353 |
data = futures.pop(0).result() |
| 354 |
out.write(data) |
| 355 |
|
| 356 |
def seek(self, timestamp): |
| 357 |
pass |
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
class FLACDecoder(MediaDecoder): |
| 364 |
|
| 365 |
def get_file_extensions(self): |
| 366 |
return '.flac', |
| 367 |
|
| 368 |
def decode(self, file, filename, streaming=True): |
| 369 |
if streaming: |
| 370 |
return FLACSource(filename, file) |
| 371 |
else: |
| 372 |
return StaticSource(FLACSource(filename, file)) |
| 373 |
|
| 374 |
|
| 375 |
def get_decoders(): |
| 376 |
return [FLACDecoder()] |
| 377 |
|
| 378 |
|
| 379 |
def get_encoders(): |
| 380 |
return [] |