| 1 |
import struct |
| 2 |
|
| 3 |
import mutagen |
| 4 |
import mutagen.asf |
| 5 |
|
| 6 |
from mediafile.utils import Image |
| 7 |
|
| 8 |
from .base import ListStorageStyle |
| 9 |
|
| 10 |
|
| 11 |
def _unpack_asf_image(data): |
| 12 |
"""Unpack image data from a WM/Picture tag. Return a tuple |
| 13 |
containing the MIME type, the raw image data, a type indicator, and |
| 14 |
the image's description. |
| 15 |
|
| 16 |
This function is treated as "untrusted" and could throw all manner |
| 17 |
of exceptions (out-of-bounds, etc.). We should clean this up |
| 18 |
sometime so that the failure modes are well-defined. |
| 19 |
""" |
| 20 |
type, size = struct.unpack_from("<bi", data) |
| 21 |
pos = 5 |
| 22 |
mime = b"" |
| 23 |
while data[pos : pos + 2] != b"\x00\x00": |
| 24 |
mime += data[pos : pos + 2] |
| 25 |
pos += 2 |
| 26 |
pos += 2 |
| 27 |
description = b"" |
| 28 |
while data[pos : pos + 2] != b"\x00\x00": |
| 29 |
description += data[pos : pos + 2] |
| 30 |
pos += 2 |
| 31 |
pos += 2 |
| 32 |
image_data = data[pos : pos + size] |
| 33 |
return (mime.decode("utf-16-le"), image_data, type, description.decode("utf-16-le")) |
| 34 |
|
| 35 |
|
| 36 |
def _pack_asf_image(mime, data, type=3, description=""): |
| 37 |
"""Pack image data for a WM/Picture tag.""" |
| 38 |
tag_data = struct.pack("<bi", type, len(data)) |
| 39 |
tag_data += mime.encode("utf-16-le") + b"\x00\x00" |
| 40 |
tag_data += description.encode("utf-16-le") + b"\x00\x00" |
| 41 |
tag_data += data |
| 42 |
return tag_data |
| 43 |
|
| 44 |
|
| 45 |
class ASFStorageStyle(ListStorageStyle): |
| 46 |
"""A general storage style for Windows Media/ASF files.""" |
| 47 |
|
| 48 |
formats = ["ASF"] |
| 49 |
|
| 50 |
def deserialize(self, data): |
| 51 |
if isinstance(data, mutagen.asf.ASFBaseAttribute): |
| 52 |
data = data.value |
| 53 |
return data |
| 54 |
|
| 55 |
|
| 56 |
class ASFImageStorageStyle(ListStorageStyle): |
| 57 |
"""Store images packed into Windows Media/ASF byte array attributes. |
| 58 |
Values are `Image` objects. |
| 59 |
""" |
| 60 |
|
| 61 |
formats = ["ASF"] |
| 62 |
|
| 63 |
def __init__(self): |
| 64 |
super().__init__(key="WM/Picture") |
| 65 |
|
| 66 |
def deserialize(self, asf_picture): |
| 67 |
mime, data, type, desc = _unpack_asf_image(asf_picture.value) |
| 68 |
return Image(data, desc=desc, type=type) |
| 69 |
|
| 70 |
def serialize(self, image): |
| 71 |
pic = mutagen.asf.ASFByteArrayAttribute() |
| 72 |
pic.value = _pack_asf_image( |
| 73 |
image.mime_type, |
| 74 |
image.data, |
| 75 |
type=image.type_index, |
| 76 |
description=image.desc or "", |
| 77 |
) |
| 78 |
return pic |