#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2024 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from struct import unpack from sys import argv, exit, stderr, stdin, stdout info = ''' id3pic [options...] [filepath/URI...] Extract picture/thumbnail bytes from ID3/MP3 metadata, when available. Any leading options can start with either single or double-dash: -h show this help message -help show this help message ''' # handle standard help cmd-line options, quitting right away in that case if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'): print(info.strip(), file=stderr) exit(0) def seems_url(s: str) -> bool: protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') return any(s.startswith(p) for p in protocols) def read_byte(src) -> int: b = src.read(1) return b[0] if b else -1 def skip_zstring(src) -> int: return match_byte(src, 0) def skip_thumbnail_type_apic(src) -> int: if read_byte(src) < 0: raise Exception('failed to sync to thumbnail text-encoding') n = 1 m = match_byte(src, ord('/')) if m < 0: raise Exception('failed to sync to thumbnail MIME-type') n += m m = skip_zstring(src) if m < 0: raise Exception('failed to sync to thumbnail MIME-type') n += m if read_byte(src) < 0: raise Exception('failed to sync to thumbnail picture type') n += 1 m = skip_zstring(src) if m < 0: raise Exception('failed to sync to thumbnail comment') n += m return n def match_byte(src, what: int) -> int: n = 0 while True: b = src.read(1) if not b: return -1 n += 1 if b[0] == what: return n def match_bytes(src, seq: bytes) -> int: i = 0 n = 0 end = len(seq) while True: b = src.read(1) if not b: return -1 n += 1 if b[0] == seq[i]: i += 1 else: i = 0 if i >= end: return n def handle_apic(w, src) -> bool: # section-size seems stored as 4 little-endian bytes chunk = src.read(4) if not chunk: raise Exception('failed to read thumbnail-payload size') size = unpack('>I', chunk)[0] n = skip_thumbnail_type_apic(src) if n < 0: raise Exception('failed to sync to start of thumbnail data') size -= n # copy all thumbnail bytes w.write(src.read(size)) return True def handle_pic(w, src) -> bool: # http://www.unixgods.org/Ruby/ID3/docs/id3v2-00.html#PIC # thumbnail-payload-size seems stored as 3 big-endian bytes a = src.read(1) b = src.read(1) c = src.read(1) if not (a and b and c): raise Exception('failed to read thumbnail-payload size') size = (256 * 256) * a[0] + 256 * b[0] + c[0] # skip the text encoding src.read(5) # skip a null-delimited string while True: b = src.read(1) if not b: raise Exception('failed to read thumbnail-payload description') if b[0] == 0: break # copy all thumbnail bytes w.write(src.read(size)) return True def handle_id3_picture(w, src) -> bool: a = ord('A') p = ord('P') i = ord('I') c = ord('C') while True: chunk = src.read(1) if not chunk: break v = chunk[0] if v == a: if src.read(1)[0] != p: continue if src.read(1)[0] != i: continue if src.read(1)[0] != c: continue return handle_apic(w, src) if v == p: if src.read(1)[0] != i: continue if src.read(1)[0] != c: continue return handle_pic(w, src) return False def handle_bytes(w, src) -> None: if not handle_id3_picture(w, src): raise Exception('no thumbnail found') name = '-' if len(argv) == 1 else argv[1] if len(argv) > 2: print('\x1b[31mmultiple inputs not allowed\x1b[0m', file=stderr) exit(1) try: if seems_url(name): from urllib.request import urlopen # handle all named inputs given if name == '-': handle_bytes(stdout.buffer, stdin.buffer) elif seems_url(name): with urlopen(name) as inp: handle_bytes(stdout.buffer, inp) else: with open(name, mode='rb') as inp: handle_bytes(stdout.buffer, inp) except BrokenPipeError: # quit quietly, instead of showing a confusing error message stderr.close() except KeyboardInterrupt: exit(2) except Exception as e: print(f'\x1b[31m{e}\x1b[0m', file=stderr) exit(1)