From 3ca76272cc88792cfc0c8030a5b0ce4f57505843 Mon Sep 17 00:00:00 2001 From: Juan Cobo Betancourt Date: Fri, 13 Nov 2026 13:18:27 -0800 Subject: [PATCH] feat: DNG remote capture, with the JPEG of the same exposure shoot(stream=True, dng=True) raised NotImplementedError, because CHDK sends a DNG as two transfers, the header and the raw data, and the library fetched one format. It now asks for both, fetches each as the camera offers it, and returns a complete DNG. With jpeg=True it asks for the JPEG too and returns a DngCapture with .dng and .jpeg, both from one exposure and one script. assemble_dng builds the file from the two parts: it reads the strip offsets and sizes from the header, swaps the byte pairs of the raw data, makes the thumbnail the header describes from the raw data, and refuses a header it cannot read or raw data of another length. It uses the standard library only. The streamed JPEG path sends what it sent before. Run on two Canon PowerShot A2500s under CHDK 1.5.1, one capture each: 4.2 s and 4.1 s for the DNG and the JPEG together, and both DNGs open in macOS. Repeated captures and other viewers are not yet tested. --- README.md | 21 +- src/pychdk/__init__.py | 4 + src/pychdk/chdk.py | 10 +- src/pychdk/device.py | 187 ++++++++++++---- src/pychdk/dng.py | 382 ++++++++++++++++++++++++++++++++ src/pychdk/multicam.py | 4 +- tests/data/a2500_dng_header.bin | Bin 0 -> 1344 bytes tests/test_device.py | 323 +++++++++++++++++++++++++-- tests/test_dng.py | 242 ++++++++++++++++++++ tests/test_imports.py | 9 + 10 files changed, 1123 insertions(+), 59 deletions(-) create mode 100644 src/pychdk/dng.py create mode 100644 tests/data/a2500_dng_header.bin create mode 100644 tests/test_dng.py diff --git a/README.md b/README.md index 86a820e..3a6a3b7 100644 --- a/README.md +++ b/README.md @@ -51,9 +51,24 @@ print(result) # 4 # Switch to record mode and capture cam.switch_mode("record") data = cam.shoot(stream=True) # JPEG bytes via remote capture +dng = cam.shoot(stream=True, dng=True) # DNG bytes +both = cam.shoot(stream=True, dng=True, jpeg=True) # one exposure +both.dng, both.jpeg # DNG and the camera's JPEG cam.close() ``` +### DNG capture + +`shoot(stream=True, dng=True)` asks CHDK for the DNG header and the raw data (`init_usb_capture(6)`), fetches each as the camera offers it, and returns a complete DNG file as bytes. Adding `jpeg=True` asks for the JPEG too (`init_usb_capture(7)`) and returns a `DngCapture` with `.dng` and `.jpeg`, both from the same exposure and the same script. + +The camera does not send a thumbnail, and sends the raw data with every pair of bytes swapped. `pychdk.assemble_dng(header, raw)` builds the file: it reads the thumbnail and raw strip offsets and sizes from the header, swaps the byte pairs, makes the 8-bit RGB thumbnail the header describes by sampling the raw data (black and white levels, as-shot white balance, a display gamma), and writes header, thumbnail and raw data end to end. It raises `DngError`, a `ValueError`, when the header is not a TIFF it can read, when the raw data's length differs from what the header declares, or when the header's offsets do not lay the three out end to end. It is pure Python with no I/O; for an A2500 frame it takes a few hundredths of a second on a desktop Mac. + +What was measured, on one Canon PowerShot A2500 running CHDK 1.5.1, one capture each with formats 6 and 7: the header (1,344 bytes) is ready about 1.8 s after the script starts; the raw data (24,724,224 bytes, 4704x3504 at 12 bits) is ready right after it and arrives in one chunk, fetched in 0.84 s; with format 7 the ready mask then reads 0 while the script is still running, and the JPEG is ready at about 4.0 s and arrives in several chunks with seeks. The mask showed one format at a time. A file built from those parts — header, 36,864 thumbnail bytes, then the raw data with its byte pairs swapped — opened and rendered correctly in macOS. A file written by `assemble_dng` itself has not yet been opened in a viewer. + +`shoot(stream=True, dng=True, jpeg=True)` itself was then run once on each of two A2500s (4.2 s and 4.1 s per capture); both files opened in macOS. + +Not yet verified: repeated captures, any other camera or CHDK build (including the 1.6.1 build `tools/flash_chdk.py` installs), and viewers other than macOS. The byte-pair swap is applied unconditionally and has been established on the A2500 only. + ### Multi-camera capture ```python @@ -85,6 +100,7 @@ pyusb / libusb — raw USB access | `usb_transport.py` | USB device discovery, interface claiming, bulk I/O | | `ptp.py` | PTP container packing/unpacking, session lifecycle, transactions | | `chdk.py` | CHDK commands — script execution, message queue, file transfer, remote capture | +| `dng.py` | DNG assembly from the remote capture header and raw data; standard library only | | `device.py` | `ChdkDevice` class and `list_devices()` discovery | | `multicam.py` | `MultiCam` class for concurrent operations across cameras | | `util.py` | APEX96 conversions (`shutter_to_tv96`, `iso_to_sv96`, `aperture_to_av96`) and camera path helpers | @@ -142,6 +158,7 @@ src/pychdk/ ptp.py # PTP protocol containers and sessions chdk.py # CHDK extension protocol device.py # high-level ChdkDevice API + dng.py # DNG assembly from remote capture parts multicam.py # multi-camera coordination util.py # exposure conversions, path helpers tests/ @@ -149,6 +166,8 @@ tests/ test_ptp.py test_chdk.py test_device.py + test_dng.py + data/ # a DNG header from an A2500, for test_dng.py test_multicam.py test_util.py examples/ @@ -160,7 +179,7 @@ tools/ ## Known limitations -- **Remote capture on A2500 is unverified**: `tools/flash_chdk.py` installs CHDK 1.6.1 r6315 for A2500 firmware 1.00A, and this library's streaming remote capture has never been run against that camera. Earlier versions of this file called the port "alpha-level"; that is not supported by the build we install — `camera_list.csv` in release-1_6 carries a `BETA_STATUS` column, 34 of its 397 entries are marked `ALPHA` or `BETA`, and the A2500's entry (`a2500,100a,,,`) is not one of them. The same sentence reported a `0x2002` failure on this camera; we have no record of observing it, so treat that as a possibility to test rather than a known behaviour. What the code does establish is that if streaming does fail, the library does not fall back — the exception reaches the caller and nothing else is attempted. Nor does the exception tell you what state the camera is in: the failure can come from the script submission, before `init_usb_capture` has run at all, or from a capture that initialized and was then cancelled. So whether USB remote capture is still enabled afterwards, and whether an ordinary `shoot()` would recover the picture, are both unestablished. Recovery is an open question for the bench, not a documented workaround. +- **Remote capture on A2500 is verified only in part**: one A2500 running CHDK 1.5.1 delivered the DNG header, raw data and JPEG of one exposure with `init_usb_capture(7)`, and the header and raw data with `init_usb_capture(6)`, one capture each (see "DNG capture" above). Streamed JPEG has run further: two A2500s under CHDK 1.5.1 took 1,200 pairs, 2,400 captures, in one session on 12 November 2026, and every file was a whole JPEG. That is not the build `tools/flash_chdk.py` installs — CHDK 1.6.1 r6315 for A2500 firmware 1.00A — and streaming has not been run against that build. Earlier versions of this file called the port "alpha-level"; that is not supported by the build we install — `camera_list.csv` in release-1_6 carries a `BETA_STATUS` column, 34 of its 397 entries are marked `ALPHA` or `BETA`, and the A2500's entry (`a2500,100a,,,`) is not one of them. The same sentence reported a `0x2002` failure on this camera; we have no record of observing it, so treat that as a possibility to test rather than a known behaviour. What the code does establish is that if streaming does fail, the library does not fall back — the exception reaches the caller and nothing else is attempted. Nor does the exception tell you what state the camera is in: the failure can come from the script submission, before `init_usb_capture` has run at all, or from a capture that initialized and was then cancelled. So whether USB remote capture is still enabled afterwards, and whether an ordinary `shoot()` would recover the picture, are both unestablished. Recovery is an open question for the bench, not a documented workaround. - **macOS only** for `tools/flash_chdk.py`. The library itself works on macOS and Linux. - **Canon cameras only** — CHDK is Canon-specific. Device discovery defaults to Canon's USB vendor ID (`0x04A9`). diff --git a/src/pychdk/__init__.py b/src/pychdk/__init__.py index 115c121..cfcba75 100644 --- a/src/pychdk/__init__.py +++ b/src/pychdk/__init__.py @@ -7,6 +7,7 @@ "ChdkDevice", "list_devices", "DeviceInfo", "install_signal_handlers", "PTPError", "ChdkPTP", "MultiCam", "util", "parse_own_txt", "format_own_txt", + "DngCapture", "assemble_dng", "DngError", ] # Submodules reachable as attributes of the package. @@ -23,6 +24,9 @@ "MultiCam": "pychdk.multicam", "parse_own_txt": "pychdk.util", "format_own_txt": "pychdk.util", + "DngCapture": "pychdk.device", + "assemble_dng": "pychdk.dng", + "DngError": "pychdk.dng", } diff --git a/src/pychdk/chdk.py b/src/pychdk/chdk.py index 99a7c21..78d1f7f 100644 --- a/src/pychdk/chdk.py +++ b/src/pychdk/chdk.py @@ -450,7 +450,7 @@ def remote_capture_get_chunk(self, format_flag): data = data[:size] return data, more, position - def remote_capture_get_data(self, format_flag): + def remote_capture_get_data(self, format_flag, accumulate=False): """Download remote capture image data. Loops over remote_capture_get_chunk until the camera clears its @@ -463,6 +463,11 @@ def remote_capture_get_data(self, format_flag): Args: format_flag: Which format to download (JPEG=1, RAW=2, DNG_HDR=4). + accumulate: If True, add this download's chunks to + last_capture_chunks instead of starting the count + again. A capture that fetches several formats passes + it, having zeroed the count with reset_capture_chunks, + so the count covers the whole capture. The chunk count is left in last_capture_chunks rather than returned, so the signature callers depend on is unchanged. @@ -475,7 +480,8 @@ def remote_capture_get_data(self, format_flag): """ image = bytearray() cursor = 0 - self._last_capture_chunks = 0 + if not accumulate: + self._last_capture_chunks = 0 for _ in range(MAX_CAPTURE_CHUNKS): chunk, more, position = self.remote_capture_get_chunk(format_flag) self._last_capture_chunks += 1 diff --git a/src/pychdk/device.py b/src/pychdk/device.py index 379fda3..0139730 100644 --- a/src/pychdk/device.py +++ b/src/pychdk/device.py @@ -22,6 +22,7 @@ REMOTE_CAP_RAW, REMOTE_CAP_DNG_HDR, ) +from pychdk.dng import assemble_dng from pychdk.util import shutter_to_tv96 @@ -36,6 +37,48 @@ "vendor_id", "product_id", "bus_num", "device_num", "serial_num", ]) +DngCapture = namedtuple("DngCapture", ["dng", "jpeg"]) +DngCapture.__doc__ = """A DNG and the camera's JPEG from one exposure. + +Returned by shoot(stream=True, dng=True, jpeg=True). Both fields are +bytes: dng is a complete file, jpeg is the JPEG exactly as the camera +sent it. +""" + +# The order the parts of a DNG capture are fetched in when the camera +# offers more than one at once, and their names for messages. An A2500 +# offers them one at a time, in this order. +_FETCH_ORDER = (REMOTE_CAP_DNG_HDR, REMOTE_CAP_RAW, REMOTE_CAP_JPEG) +_PART_NAMES = { + REMOTE_CAP_DNG_HDR: "DNG header", + REMOTE_CAP_RAW: "raw data", + REMOTE_CAP_JPEG: "JPEG", +} + + +def _name_parts(mask): + names = [_PART_NAMES[flag] for flag in _FETCH_ORDER if mask & flag] + if len(names) <= 1: + return "".join(names) + return ", ".join(names[:-1]) + " and " + names[-1] + + +def _arrived(received, remaining): + """Say which parts arrived and which did not, for an error message. + + Empty when nothing arrived, so a capture that fails before its first + part reads exactly as it always has. + """ + if not received: + return "" + got = 0 + for flag in received: + got |= flag + return ( + f"; received the {_name_parts(got)}, " + f"not the {_name_parts(remaining)}" + ) + def list_devices(): """Find all connected CHDK-capable Canon cameras. @@ -283,7 +326,7 @@ def lua_execute(self, lua_code, do_return=True, timeout=10.0): return None def shoot(self, shutter_speed=None, market_iso=None, dng=False, - stream=False): + stream=False, jpeg=False): """Capture a photo. Args: @@ -333,19 +376,37 @@ def shoot(self, shutter_speed=None, market_iso=None, dng=False, stop, on a camera using CHDK's default. The offset is per-camera (the IXUS700 platform sets 20), so the size of the old error varies by body. - dng: Request DNG. Not implemented on either path: streaming - refuses it, and the card path ignores it. + dng: With stream=True, return a DNG built from the + camera's DNG header and raw data instead of the JPEG. + The card path ignores it: it runs shoot() and takes + whatever the camera is set to produce. stream: If True, use remote capture (direct USB transfer). + jpeg: With stream=True and dng=True, also return the + camera's JPEG of the same exposure, from the same + script. With stream=True alone it changes nothing: the + JPEG is what streaming returns anyway. It needs + stream=True. Returns: - The JPEG as bytes when stream=True. Otherwise None: the - camera shoots to its own SD card and nothing is fetched - back: shoot() does not discover or return the saved - filename. download_file fetches a card file by path, and - CHDK's own Lua (get_image_dir, the exposure counter, a - directory listing) can be used to find one — none of that - happens here. + When stream=True: the JPEG as bytes; with dng=True, the DNG + as bytes; with dng=True and jpeg=True, a DngCapture holding + both. Otherwise None: the camera shoots to its own SD card + and nothing is fetched back: shoot() does not discover or + return the saved filename. download_file fetches a card + file by path, and CHDK's own Lua (get_image_dir, the + exposure counter, a directory listing) can be used to find + one — none of that happens here. + + Raises: + ValueError: If jpeg=True without stream=True. A DngError, + which is a ValueError, if the DNG parts cannot be + assembled. """ + if jpeg and not stream: + raise ValueError( + "jpeg=True applies to streamed capture only; pass " + "stream=True and dng=True" + ) parts = [] if shutter_speed is not None: tv96 = shutter_to_tv96(shutter_speed) @@ -359,13 +420,26 @@ def shoot(self, shutter_speed=None, market_iso=None, dng=False, ) if stream: - return self._shoot_streaming(parts, dng) + return self._shoot_streaming(parts, dng, jpeg) else: return self._shoot_standard(parts) - def _shoot_streaming(self, setup_parts, dng): + def _shoot_streaming(self, setup_parts, dng, jpeg=False): """Capture using remote capture (PTP commands 13/14). + Asks for the JPEG alone (init_usb_capture(1)), or with dng for + the DNG header and raw data (6), or with jpeg as well for all + three (7), and fetches each part as the camera offers it. + + Measured on one Canon PowerShot A2500 with CHDK 1.5.1, one + capture each with 6 and 7: the header (0x04, 1,344 bytes) is + ready about 1.8 s after the script starts and the raw data + (0x02, 24,724,224 bytes, one chunk) right after it; with 7 the + ready mask then reads 0 while the script is still running, and + the JPEG (0x01, several chunks with seeks) is ready at about + 4.0 s. The mask showed one format at a time. The camera sends + no thumbnail; assemble_dng makes one. + The chunk count is zeroed here, at the attempt, rather than where the download begins: a capture refused, or one that never becomes ready, would otherwise keep reporting the chunks of the @@ -389,28 +463,43 @@ def _shoot_streaming(self, setup_parts, dng): capture does not read a stale message: it is a bounded sweep of what is already waiting, not a wait for a result still to come. + Every part is fetched once. Nothing is retried: a part that + never arrives ends the capture with an error naming the parts + that did. + Raises: RuntimeError: If the camera refuses to initialize remote - capture. - NotImplementedError: If dng is True. CHDK's DNG_HDR flag - sends the DNG header only; the raw data is a separate - transfer, and the client has to splice the two into a - file. This method downloads one format, so it cannot, - and _shoot_standard does not request a DNG either. + capture, the script fails, the camera offers a part + that was not asked for or was already taken, or the + script ends before every part has arrived. + TimeoutError: If the parts have not all arrived by the + deadline. + DngError: If the header and raw data cannot be assembled. """ self._chdk.reset_capture_chunks() if dng: - raise NotImplementedError( - "DNG capture is not implemented. Streaming would need the " - "DNG header and the raw data fetched as two separate " - "transfers and assembled into a file on this side, which " - "this library does not do; capturing to the card does not " - "request a DNG either, it runs shoot() and takes whatever " - "the camera is set to produce. Streamed JPEG works." - ) + fmt = REMOTE_CAP_DNG_HDR | REMOTE_CAP_RAW + if jpeg: + fmt |= REMOTE_CAP_JPEG + else: + fmt = REMOTE_CAP_JPEG + received = self._capture_parts(setup_parts, fmt) + if not dng: + return received[REMOTE_CAP_JPEG] + image = assemble_dng( + received[REMOTE_CAP_DNG_HDR], received[REMOTE_CAP_RAW], + ) + if jpeg: + return DngCapture(dng=image, jpeg=received[REMOTE_CAP_JPEG]) + return image + + def _capture_parts(self, setup_parts, fmt): + """Run one capture script and fetch every format in fmt. - fmt = REMOTE_CAP_JPEG + Returns: + {format flag: bytes} for every bit in fmt. + """ setup = "".join(part + "; " for part in setup_parts) script = ( f"{setup}local ok = init_usb_capture({fmt}); " @@ -420,7 +509,8 @@ def _shoot_streaming(self, setup_parts, dng): ) script_id = self._chdk.execute_script(script) - image = None + received = {} + remaining = fmt deadline = time.monotonic() + 30 grace = CAPTURE_INIT_GRACE init_deadline = time.monotonic() + grace @@ -428,16 +518,28 @@ def _shoot_streaming(self, setup_parts, dng): ready, status = self._chdk.remote_capture_is_ready() formats = status if ready: - # A mask without the format we asked for is a fault, not - # a menu: the other bits are a different picture. - if not formats & fmt: + # A mask without a format still to come is a fault, not + # a menu: the other bits are a different picture, or a + # part already taken. + wanted = formats & remaining + if not wanted: raise RuntimeError( - f"The camera has no 0x{fmt:02x} data ready; " + f"The camera has no 0x{remaining:02x} data ready; " f"it offers 0x{formats:02x}" + + _arrived(received, remaining) ) # The request parameter is one bit, not the whole mask. - image = self._chdk.remote_capture_get_data(fmt) - break + flag = next(f for f in _FETCH_ORDER if wanted & f) + if fmt == REMOTE_CAP_JPEG: + received[flag] = self._chdk.remote_capture_get_data(flag) + else: + received[flag] = self._chdk.remote_capture_get_data( + flag, accumulate=True, + ) + remaining &= ~flag + if not remaining: + break + continue running, has_msgs = self._chdk.get_script_status() if has_msgs: @@ -475,20 +577,29 @@ def _shoot_streaming(self, setup_parts, dng): "afterwards — CHDK clears the capture target " "after its own download timeout, and reports " "that the same way as never having initialized" + + _arrived(received, remaining) ) - if time.monotonic() >= init_deadline: + if time.monotonic() >= init_deadline and not received: raise RuntimeError( "The capture script did not initialize remote " f"capture within {grace}s and is still running" ) if not running: + if received: + raise RuntimeError( + "The capture script finished before every part " + "arrived" + _arrived(received, remaining) + ) raise RuntimeError( "The capture script finished without producing a capture" ) time.sleep(0.1) - if image is None: - raise TimeoutError("Remote capture did not complete") + if remaining: + raise TimeoutError( + "Remote capture did not complete" + + _arrived(received, remaining) + ) # Clear what the script left behind so the next capture does not # read a stale message — but never at the cost of this picture. @@ -496,7 +607,7 @@ def _shoot_streaming(self, setup_parts, dng): self._chdk.drain_messages() except Exception: pass - return image + return received def _shoot_standard(self, setup_parts): """Capture to the camera's SD card and leave it there. diff --git a/src/pychdk/dng.py b/src/pychdk/dng.py new file mode 100644 index 0000000..6bc6843 --- /dev/null +++ b/src/pychdk/dng.py @@ -0,0 +1,382 @@ +"""Assemble a DNG file from the parts CHDK's remote capture sends. + +With init_usb_capture asking for the DNG header (0x04) and the raw data +(0x02), CHDK sends two separate transfers and no thumbnail. The header +is a complete TIFF directory structure whose strip offsets point past +its own end: IFD0 describes an RGB thumbnail stored straight after the +header, and a SubIFD describes the CFA raw image stored after the +thumbnail. A file is therefore header + thumbnail + raw data, and the +thumbnail has to be made on this side. + +On a Canon PowerShot A2500 running CHDK 1.5.1 the raw data arrives with +the two bytes of every 16-bit pair swapped; once swapped back, the +12-bit samples are packed most significant bit first, two pixels in +three bytes, which is what the header's uncompressed CFA strip +describes. assemble_dng swaps every pair unconditionally. That has been +measured on the A2500 only. + +Everything here is pure: bytes in, bytes out, standard library only. +""" +import struct +from array import array +from collections import namedtuple + + +class DngError(ValueError): + """The header and raw data cannot be assembled into a DNG.""" + + +DngHeader = namedtuple("DngHeader", [ + "thumb_width", "thumb_height", "thumb_offset", "thumb_bytes", + "width", "height", "bits", "raw_offset", "raw_bytes", + "cfa_pattern", "black_level", "white_level", "active_area", + "as_shot_neutral", +]) +DngHeader.__doc__ = """What assemble_dng reads from a CHDK DNG header. + +active_area is (top, left, bottom, right), as the DNG ActiveArea tag +orders it. cfa_pattern is the 2x2 CFAPattern, row by row, with 0 for +red, 1 for green and 2 for blue. as_shot_neutral is None when the +header does not carry the tag. +""" + +# TIFF field types: byte size and struct code of one value. Rationals +# are read as two integers and divided. +_TYPES = { + 1: (1, "B"), 2: (1, "B"), 3: (2, "H"), 4: (4, "I"), + 5: (8, "II"), 6: (1, "b"), 7: (1, "B"), 8: (2, "h"), + 9: (4, "i"), 10: (8, "ii"), 11: (4, "f"), 12: (8, "d"), + 13: (4, "I"), +} + +_NEW_SUBFILE_TYPE = 0x00FE +_IMAGE_WIDTH = 0x0100 +_IMAGE_LENGTH = 0x0101 +_BITS_PER_SAMPLE = 0x0102 +_COMPRESSION = 0x0103 +_PHOTOMETRIC = 0x0106 +_STRIP_OFFSETS = 0x0111 +_SAMPLES_PER_PIXEL = 0x0115 +_STRIP_BYTE_COUNTS = 0x0117 +_SUB_IFDS = 0x014A +_CFA_REPEAT_PATTERN_DIM = 0x828D +_CFA_PATTERN = 0x828E +_BLACK_LEVEL = 0xC61A +_WHITE_LEVEL = 0xC61D +_AS_SHOT_NEUTRAL = 0xC628 +_ACTIVE_AREA = 0xC68D + +_PHOTOMETRIC_RGB = 2 +_PHOTOMETRIC_CFA = 32803 + +# The thumbnail is for previews, so a display gamma is enough. +_THUMB_GAMMA = 1 / 2.2 + + +def _read_ifd(data, offset, endian): + """Read one image file directory into {tag: tuple of values}.""" + if offset < 8 or offset + 2 > len(data): + raise DngError( + f"The header points to a directory at {offset}, outside its " + f"{len(data)} bytes" + ) + (count,) = struct.unpack_from(endian + "H", data, offset) + end = offset + 2 + 12 * count + if end + 4 > len(data): + raise DngError( + f"The directory at {offset} has {count} entries and runs past " + f"the end of the {len(data)}-byte header" + ) + entries = {} + for i in range(count): + at = offset + 2 + 12 * i + tag, typ, n = struct.unpack_from(endian + "HHI", data, at) + if typ not in _TYPES: + continue + size, code = _TYPES[typ] + total = size * n + if total <= 4: + where = at + 8 + else: + (where,) = struct.unpack_from(endian + "I", data, at + 8) + if where + total > len(data): + raise DngError( + f"Tag 0x{tag:04x} points to {total} bytes at {where}, " + f"outside the {len(data)}-byte header" + ) + if typ == 2: + entries[tag] = (bytes(data[where:where + total]),) + continue + values = struct.unpack_from(endian + code * n, data, where) + if typ in (5, 10): + pairs = [] + for num, den in zip(values[::2], values[1::2]): + if den == 0: + raise DngError(f"Tag 0x{tag:04x} has a zero denominator") + pairs.append(num / den) + values = tuple(pairs) + entries[tag] = values + return entries + + +def _one(ifd, tag, name, default=None): + values = ifd.get(tag) + if not values: + if default is not None: + return default + raise DngError(f"The {name} has no tag 0x{tag:04x}") + return values[0] + + +def _single_strip(ifd, name): + offsets = ifd.get(_STRIP_OFFSETS, ()) + counts = ifd.get(_STRIP_BYTE_COUNTS, ()) + if len(offsets) != 1 or len(counts) != 1: + raise DngError( + f"The {name} is not stored as a single strip " + f"({len(offsets)} offsets, {len(counts)} byte counts)" + ) + return int(offsets[0]), int(counts[0]) + + +def read_dng_header(header): + """Read the thumbnail and raw image descriptions from a DNG header. + + Args: + header: The bytes CHDK sends for the DNG header (format 0x04). + + Returns: + A DngHeader. + + Raises: + DngError: If the header is not a TIFF, or does not describe an + uncompressed 8-bit RGB thumbnail in IFD0 and an + uncompressed single-strip CFA image with a 2x2 pattern in a + SubIFD. + """ + header = bytes(header) + if header[:4] == b"II*\x00": + endian = "<" + elif header[:4] == b"MM\x00*": + endian = ">" + else: + raise DngError( + "The DNG header is not a TIFF: it does not begin with a TIFF " + f"byte-order mark (first bytes {header[:4]!r})" + ) + (ifd0_offset,) = struct.unpack_from(endian + "I", header, 4) + ifd0 = _read_ifd(header, ifd0_offset, endian) + + raw_ifd = None + for sub_offset in ifd0.get(_SUB_IFDS, ()): + sub = _read_ifd(header, sub_offset, endian) + if sub.get(_PHOTOMETRIC, (None,))[0] == _PHOTOMETRIC_CFA: + raw_ifd = sub + break + if raw_ifd is None: + raise DngError( + "The DNG header describes no CFA raw image: no SubIFD has " + "PhotometricInterpretation 32803" + ) + + # The thumbnail: IFD0, uncompressed 8-bit RGB. + thumb_width = int(_one(ifd0, _IMAGE_WIDTH, "thumbnail")) + thumb_height = int(_one(ifd0, _IMAGE_LENGTH, "thumbnail")) + if (_one(ifd0, _PHOTOMETRIC, "thumbnail") != _PHOTOMETRIC_RGB + or _one(ifd0, _SAMPLES_PER_PIXEL, "thumbnail", 1) != 3 + or tuple(ifd0.get(_BITS_PER_SAMPLE, ())) != (8, 8, 8) + or _one(ifd0, _COMPRESSION, "thumbnail", 1) != 1): + raise DngError( + "The DNG header's IFD0 is not an uncompressed 8-bit RGB " + "thumbnail" + ) + thumb_offset, thumb_bytes = _single_strip(ifd0, "thumbnail") + if thumb_bytes != thumb_width * thumb_height * 3: + raise DngError( + f"The thumbnail strip is {thumb_bytes} bytes; a " + f"{thumb_width}x{thumb_height} RGB thumbnail needs " + f"{thumb_width * thumb_height * 3}" + ) + + # The raw image. + width = int(_one(raw_ifd, _IMAGE_WIDTH, "raw image")) + height = int(_one(raw_ifd, _IMAGE_LENGTH, "raw image")) + bits = int(_one(raw_ifd, _BITS_PER_SAMPLE, "raw image")) + if _one(raw_ifd, _COMPRESSION, "raw image", 1) != 1: + raise DngError("The raw image is compressed; only uncompressed is read") + if not 8 <= bits <= 16: + raise DngError(f"The raw image has {bits} bits per sample") + if _one(raw_ifd, _SAMPLES_PER_PIXEL, "raw image", 1) != 1: + raise DngError("The raw image has more than one sample per pixel") + raw_offset, raw_bytes = _single_strip(raw_ifd, "raw image") + row_bytes = (width * bits + 7) // 8 + if raw_bytes != row_bytes * height: + raise DngError( + f"The raw strip is {raw_bytes} bytes, which does not match the " + f"dimensions: {width}x{height} at {bits} bits is " + f"{row_bytes * height}" + ) + if raw_bytes % 2: + raise DngError( + f"The raw strip is {raw_bytes} bytes, an odd number, so its " + "byte pairs cannot be swapped" + ) + if tuple(raw_ifd.get(_CFA_REPEAT_PATTERN_DIM, ())) != (2, 2): + raise DngError("The raw image does not have a 2x2 CFA pattern") + cfa = tuple(int(v) for v in raw_ifd.get(_CFA_PATTERN, ())) + if len(cfa) != 4 or set(cfa) != {0, 1, 2}: + raise DngError(f"The raw image's CFA pattern {cfa} is not RGB 2x2") + + black_values = raw_ifd.get(_BLACK_LEVEL, (0,)) + black = sum(black_values) / len(black_values) + white = float(_one(raw_ifd, _WHITE_LEVEL, "raw image", (1 << bits) - 1)) + if not 0 <= black < white: + raise DngError( + f"The raw image's black level {black} is not below its white " + f"level {white}" + ) + area = tuple(int(v) for v in raw_ifd.get( + _ACTIVE_AREA, (0, 0, height, width))) + top, left, bottom, right = area if len(area) == 4 else (None,) * 4 + if (top is None or not 0 <= top < bottom <= height + or not 0 <= left < right <= width + or bottom - top < 2 or right - left < 2): + raise DngError( + f"The raw image's active area {area} does not fit " + f"{width}x{height}" + ) + + neutral = ifd0.get(_AS_SHOT_NEUTRAL) + if neutral is not None and (len(neutral) != 3 or min(neutral) <= 0): + neutral = None + + return DngHeader( + thumb_width=thumb_width, thumb_height=thumb_height, + thumb_offset=thumb_offset, thumb_bytes=thumb_bytes, + width=width, height=height, bits=bits, + raw_offset=raw_offset, raw_bytes=raw_bytes, + cfa_pattern=cfa, black_level=black, white_level=white, + active_area=area, as_shot_neutral=neutral, + ) + + +def _thumbnail(info, raw): + """Make the RGB thumbnail by sampling the swapped raw data. + + One 2x2 CFA block per thumbnail pixel, taken from the middle of the + stretch of the active area that pixel covers: red and blue from + their own sites, green as the mean of the block's two greens. Each + channel is scaled from the black level to the white level, given + the as-shot white balance when the header carries one, and + gamma-encoded. Only width x height x 4 samples are read, so the + cost does not depend on the size of the raw image. + + The CFA pattern is taken as anchored at row 0, column 0 of the raw + image, and the blocks start on even rows and columns. Where the + active area begins on an even row and column — 26 and 16 on the + A2500 — this is the same as anchoring it at the active area. + """ + bits = info.bits + mask = (1 << bits) - 1 + row_bits = ((info.width * bits + 7) // 8) * 8 + top, left, bottom, right = info.active_area + top += top & 1 + left += left & 1 + block_rows = (bottom - top) // 2 + block_cols = (right - left) // 2 + if block_rows < 1 or block_cols < 1: + raise DngError(f"The active area {info.active_area} has no 2x2 block") + + if info.as_shot_neutral: + green = info.as_shot_neutral[1] + gains = [green / n for n in info.as_shot_neutral] + else: + gains = [1.0, 1.0, 1.0] + black = info.black_level + span = info.white_level - black + luts = [] + for gain in gains: + lut = bytearray(mask + 1) + for level in range(mask + 1): + v = (level - black) / span * gain + if v <= 0: + continue + lut[level] = 255 if v >= 1 else int(255 * v ** _THUMB_GAMMA + 0.5) + luts.append(lut) + + def sample(row, col): + bit = row * row_bits + col * bits + byte = bit >> 3 + shift = bit & 7 + n = (shift + bits + 7) >> 3 + value = int.from_bytes(raw[byte:byte + n], "big") + return (value >> (n * 8 - shift - bits)) & mask + + cfa = info.cfa_pattern + tw, th = info.thumb_width, info.thumb_height + cols = [left + ((2 * x + 1) * block_cols // (2 * tw)) * 2 for x in range(tw)] + out = bytearray(tw * th * 3) + i = 0 + for y in range(th): + row = top + ((2 * y + 1) * block_rows // (2 * th)) * 2 + for col in cols: + sums = [0, 0, 0] + counts = [0, 0, 0] + for k, (dy, dx) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))): + colour = cfa[k] + sums[colour] += sample(row + dy, col + dx) + counts[colour] += 1 + out[i] = luts[0][sums[0] // counts[0]] + out[i + 1] = luts[1][sums[1] // counts[1]] + out[i + 2] = luts[2][sums[2] // counts[2]] + i += 3 + return bytes(out) + + +def assemble_dng(header, raw): + """Build a DNG file from a CHDK DNG header and its raw data. + + The file is the header, then a thumbnail made from the raw data, + then the raw data with every pair of bytes swapped. Offsets and + sizes are read from the header, and the header has to place the + thumbnail straight after itself and the raw data straight after + the thumbnail, which is the layout CHDK's header describes. + + Args: + header: DNG header bytes (remote capture format 0x04). + raw: Raw data bytes as received (format 0x02). + + Returns: + The DNG as bytes. + + Raises: + DngError: A ValueError. Raised when the header is not a TIFF + this can read, when the raw data's length differs from the + header's byte count, or when the header's offsets do not + lay out header + thumbnail + raw data end to end. + """ + header = bytes(header) + info = read_dng_header(header) + if len(raw) != info.raw_bytes: + raise DngError( + f"The raw data is {len(raw)} bytes; the header declares " + f"{info.raw_bytes}" + ) + if info.thumb_offset != len(header): + raise DngError( + f"The thumbnail offset is {info.thumb_offset}; it has to be " + f"{len(header)}, the end of the header" + ) + if info.raw_offset != info.thumb_offset + info.thumb_bytes: + raise DngError( + f"The raw data offset is {info.raw_offset}; it has to be " + f"{info.thumb_offset + info.thumb_bytes}, the end of the " + "thumbnail" + ) + + swapped = array("H") + swapped.frombytes(raw) + swapped.byteswap() + view = memoryview(swapped).cast("B") + thumb = _thumbnail(info, view) + return b"".join((header, thumb, view)) diff --git a/src/pychdk/multicam.py b/src/pychdk/multicam.py index 044a535..971e88c 100644 --- a/src/pychdk/multicam.py +++ b/src/pychdk/multicam.py @@ -44,7 +44,9 @@ def shoot(self, **kwargs): Returns: One entry per camera, in the same order as self.cameras. What the entries are depends on the path taken. With - stream=True each is the JPEG bytes that camera sent back. + stream=True each is what ChdkDevice.shoot returned for that + camera: the JPEG bytes, the DNG bytes with dng=True, or a + DngCapture with dng=True and jpeg=True. Otherwise each camera shoots to its own SD card and every entry is None — shoot() does not discover or return the saved filenames. ChdkDevice.download_file fetches a card file by diff --git a/tests/data/a2500_dng_header.bin b/tests/data/a2500_dng_header.bin new file mode 100644 index 0000000000000000000000000000000000000000..08b7156798e36d2448ab5ad6fc8f22b159f969b5 GIT binary patch literal 1344 zcmZ{k&ubG=5XWbC^Q)mYZCX=_QP&E#w6g53q%9F4HY(O$1aArw4=whRK$VIfG~}Qj ztfUK~_@j7`9z2MLA|fhy==Nm)2|>i8#|n+#**BX+h%daI&zm)7klbQJ@f0>>a9!oD9o4EDeS60;a3N_WKB zE6nf62$#XbVowdCT!+1bnElv)0|ys81pWv<0S@xO`n>qAL-DlU)-T>yId0(48Bas@ zD)+Q6j5vcK!*|G6=ii3@u%DzJ*#7{J`q7{!76Ob3p9PP@hR<*XJOMrP0{ED41#Af~ zgKaPb-NECM->xlGlxcN`S7CR`>2`PC?NQy~xAbCm>&}r{N97+Ah1F)Cu-Y7_RqfI( zEvu=Mui;eth1bEIT^N&&aQ9d02C>xfdsLT7qUc#)Rr@aX4hT0>M2Em^{}wS#;rHMb zFa&+Uqqr5P9C(`*7z6aIu1@s}nwP@A!6Oe;-8kZ?aDf+%co5BYUB_ssd$I$2%~L(< z!#&hJ6*B{li2firD*B_~n6L$o<05nAfYc+*cQGk8lh|l@dT=-L4$*1{M_()78QAkk z1i#YNO0`14)4Wi= self.ends_after: + return False + return self.taken < len(self.parts) + + def respond(self, operation, params=None, **kwargs): + command = params[0] + if command == ChdkCommand.EXECUTE_SCRIPT: + self.scripts.append(kwargs.get("send_data")) + return ([self.script_id, 0], b"") + if command == ChdkCommand.REMOTE_CAPTURE_IS_READY: + mask = 0 + if self.running and self.taken < len(self.parts): + part = self.parts[self.taken] + if part[1] > 0: + part[1] -= 1 + else: + mask = part[0] + self.polls.append(mask) + return ([mask], b"") + if command == ChdkCommand.REMOTE_CAPTURE_GET_DATA: + flag = params[1] + self.fetches.append(flag) + part = self.parts[self.taken] + assert flag == part[0], f"asked for {flag}, offering {part[0]}" + data, position = part[2][self._chunk] + self._chunk += 1 + more = self._chunk < len(part[2]) + if not more: + self.taken += 1 + self._chunk = 0 + return ([len(data), int(more), position & 0xFFFFFFFF], data) + if command == ChdkCommand.SCRIPT_STATUS: + return ([0b01 if self.running else 0], b"") + raise AssertionError(f"unexpected command {command}") + + +def _a2500_parts(header, raw, jpeg=True): + parts = [ + (DNG_HDR, 3, [(header, -1)]), + (RAW, 0, [(raw, -1)]), + ] + if jpeg: + # Three chunks, the last seeking back into the middle. + parts.append((JPEG, 4, [ + (b"\xff\xd8AAAA", -1), + (b"CCCC\xff\xd9", 10), + (b"BBBB", 6), + ])) + return parts + + +class TestStreamedDng: + """shoot(stream=True, dng=True), against the bench-measured order.""" + + def _device(self, camera, monkeypatch): + info = DeviceInfo( + vendor_id=0x04A9, product_id=0x1234, + bus_num=1, device_num=5, serial_num="ABC", + ) + session = MagicMock() + with patch("pychdk.device.PTPDevice"), \ + patch("pychdk.device.PTPSession", return_value=session): + dev = ChdkDevice(info, _usb_device=MagicMock()) + session.transaction.side_effect = camera.respond + # The clock never moves, so only the camera ends the loop, and + # the 0.1 s sleeps between polls cost nothing. + monkeypatch.setattr("pychdk.device.time", _FakeClock([0.0])) + return dev + + def _script(self, camera): + assert len(camera.scripts) == 1 + return camera.scripts[0].rstrip(b"\x00").decode() + + def test_dng_alone_returns_the_assembled_file( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera(_a2500_parts(header, raw, jpeg=False)) + dev = self._device(camera, monkeypatch) + result = dev.shoot(stream=True, dng=True) + assert isinstance(result, bytes) + assert result == assemble_dng(header, raw) + + def test_dng_alone_asks_for_header_and_raw_only( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera(_a2500_parts(header, raw, jpeg=False)) + dev = self._device(camera, monkeypatch) + dev.shoot(stream=True, dng=True) + assert "init_usb_capture(6)" in self._script(camera) + assert camera.fetches == [DNG_HDR, RAW] + + def test_dng_and_jpeg_come_from_one_script( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera(_a2500_parts(header, raw)) + dev = self._device(camera, monkeypatch) + result = dev.shoot(stream=True, dng=True, jpeg=True) + assert isinstance(result, DngCapture) + assert result.dng == assemble_dng(header, raw) + assert result.jpeg == b"\xff\xd8AAAABBBBCCCC\xff\xd9" + script = self._script(camera) + assert script == JPEG_SCRIPT.replace("(1)", "(7)") + + def test_each_part_is_fetched_once_as_it_becomes_ready( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera(_a2500_parts(header, raw)) + dev = self._device(camera, monkeypatch) + dev.shoot(stream=True, dng=True, jpeg=True) + # Header and raw in that order, three JPEG chunks, nothing twice. + assert camera.fetches == [DNG_HDR, RAW, JPEG, JPEG, JPEG] + # The mask read 0 between the raw data and the JPEG. + assert camera.polls[camera.polls.index(RAW) + 1] == 0 + + def test_the_chunk_count_covers_every_part( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera(_a2500_parts(header, raw)) + dev = self._device(camera, monkeypatch) + dev.shoot(stream=True, dng=True, jpeg=True) + assert dev.last_capture_chunks == 5 + + def test_a_script_that_ends_before_the_jpeg_says_what_arrived( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera(_a2500_parts(header, raw), ends_after=2) + dev = self._device(camera, monkeypatch) + with pytest.raises(RuntimeError) as caught: + dev.shoot(stream=True, dng=True, jpeg=True) + message = str(caught.value) + assert "DNG header" in message + assert "raw data" in message + assert "JPEG" in message + assert "finished" in message + assert camera.fetches == [DNG_HDR, RAW] + + def test_a_raw_part_that_never_arrives_times_out_naming_the_header( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera( + [(DNG_HDR, 0, [(header, -1)]), (RAW, 10**9, [(raw, -1)])], + ) + dev = self._device(camera, monkeypatch) + monkeypatch.setattr( + "pychdk.device.time", _FakeClock([0.0] * 8 + [999.0]), + ) + with pytest.raises(TimeoutError) as caught: + dev.shoot(stream=True, dng=True) + message = str(caught.value) + assert "did not complete" in message + assert "received the DNG header" in message + assert "raw data" in message + assert camera.fetches == [DNG_HDR] + + def test_a_mask_offering_a_part_already_taken_is_a_fault( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera([ + (DNG_HDR, 0, [(header, -1)]), + (DNG_HDR, 0, [(header, -1)]), + ]) + dev = self._device(camera, monkeypatch) + with pytest.raises(RuntimeError, match=r"0x02.*0x04"): + dev.shoot(stream=True, dng=True) + assert camera.fetches == [DNG_HDR] + + def test_a_script_error_after_the_header_names_it( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera( + [(DNG_HDR, 0, [(header, -1)]), (RAW, 10**9, [(raw, -1)])], + ) + dev = self._device(camera, monkeypatch) + base = camera.respond + state = {"sent": False} + + def respond(operation, params=None, **kwargs): + command = params[0] + # Once the header is taken the script has an error to + # report, and has ended once it has been read. + if command == ChdkCommand.SCRIPT_STATUS and camera.taken: + return ([0 if state["sent"] else 0b11], b"") + if command == ChdkCommand.READ_SCRIPT_MSG: + state["sent"] = True + return ([MessageType.ERR, ScriptErrorType.RUN, 7, 9], + b"raw failed\x00") + return base(operation, params, **kwargs) + + dev._chdk._session.transaction.side_effect = respond + with pytest.raises(RuntimeError, match="raw failed"): + dev.shoot(stream=True, dng=True) + + def test_no_capture_shutdown_is_sent(self, dng_parts, monkeypatch): + header, raw = dng_parts + camera = _StreamingCamera(_a2500_parts(header, raw)) + dev = self._device(camera, monkeypatch) + dev.shoot(stream=True, dng=True, jpeg=True) + assert len(camera.scripts) == 1 + assert b"init_usb_capture(0)" not in camera.scripts[0] + + def test_a_header_that_cannot_be_read_is_refused( + self, dng_parts, monkeypatch, + ): + header, raw = dng_parts + camera = _StreamingCamera([ + (DNG_HDR, 0, [(b"not a tiff", -1)]), + (RAW, 0, [(raw, -1)]), + ]) + dev = self._device(camera, monkeypatch) + with pytest.raises(DngError, match="not a TIFF"): + dev.shoot(stream=True, dng=True) + + def test_the_jpeg_script_is_unchanged(self, monkeypatch): + camera = _StreamingCamera([(JPEG, 0, [(b"jpeg", -1)])]) + dev = self._device(camera, monkeypatch) + assert dev.shoot(stream=True) == b"jpeg" + assert self._script(camera) == JPEG_SCRIPT + assert camera.fetches == [JPEG] + + def test_jpeg_without_dng_is_the_plain_jpeg_path(self, monkeypatch): + camera = _StreamingCamera([(JPEG, 0, [(b"jpeg", -1)])]) + dev = self._device(camera, monkeypatch) + assert dev.shoot(stream=True, jpeg=True) == b"jpeg" + assert self._script(camera) == JPEG_SCRIPT + + def test_jpeg_on_the_card_path_is_refused(self, monkeypatch): + camera = _StreamingCamera([]) + dev = self._device(camera, monkeypatch) + with pytest.raises(ValueError, match="stream"): + dev.shoot(dng=True, jpeg=True) + assert camera.scripts == [] diff --git a/tests/test_dng.py b/tests/test_dng.py new file mode 100644 index 0000000..e8bf6a2 --- /dev/null +++ b/tests/test_dng.py @@ -0,0 +1,242 @@ +"""Tests for DNG assembly from a remote capture's header and raw data.""" +import struct +import time +from array import array +from pathlib import Path + +import pytest + +from pychdk.dng import DngError, assemble_dng, read_dng_header + +HEADER_PATH = Path(__file__).parent / "data" / "a2500_dng_header.bin" + +# The A2500's numbers, as its header states them. The code reads them +# from the header; the tests only use them to check what it read. +WIDTH, HEIGHT = 4704, 3504 +ROW_BYTES = WIDTH * 12 // 8 +RAW_BYTES = ROW_BYTES * HEIGHT # 24,724,224 +THUMB_OFFSET, THUMB_BYTES = 1344, 128 * 96 * 3 +RAW_OFFSET = THUMB_OFFSET + THUMB_BYTES # 38,208 + +# Levels for the synthetic picture, per CFA colour. +RED, GREEN, BLUE = 3000, 1000, 127 + + +@pytest.fixture(scope="module") +def header(): + return HEADER_PATH.read_bytes() + + +def _pack_pair(first, second): + """Two 12-bit samples, MSB first, in three bytes.""" + return bytes([ + first >> 4, + ((first & 0x0F) << 4) | (second >> 8), + second & 0xFF, + ]) + + +def _swap_pairs(data): + swapped = array("H") + swapped.frombytes(data) + swapped.byteswap() + return swapped.tobytes() + + +@pytest.fixture(scope="module") +def correct_raw(): + """The raw image as it belongs in the file: CFA [1,2,0,1], i.e. + G B on even rows and R G on odd rows, built one row at a time.""" + even = _pack_pair(GREEN, BLUE) * (WIDTH // 2) + odd = _pack_pair(RED, GREEN) * (WIDTH // 2) + return (even + odd) * (HEIGHT // 2) + + +@pytest.fixture(scope="module") +def received_raw(correct_raw): + """The same image as the camera sends it, byte pairs swapped.""" + return _swap_pairs(correct_raw) + + +def _entry_offset(data, ifd_offset, tag): + count = struct.unpack_from(" g > b == 0 + + def test_a_black_picture_gives_a_black_thumbnail(self, header): + black = _pack_pair(127, 127) * (RAW_BYTES // 3) + dng = assemble_dng(header, _swap_pairs(black)) + assert not any(dng[THUMB_OFFSET:RAW_OFFSET]) + + def test_assembly_takes_well_under_a_second(self, header, received_raw): + start = time.perf_counter() + assemble_dng(header, received_raw) + assert time.perf_counter() - start < 1.0 + + def test_bytearray_and_memoryview_are_accepted( + self, header, received_raw, + ): + expected = assemble_dng(header, received_raw) + assert assemble_dng( + bytearray(header), memoryview(received_raw), + ) == expected + + +class TestRefusals: + def test_not_a_tiff(self, received_raw): + with pytest.raises(DngError, match="not a TIFF"): + assemble_dng(b"\xff\xd8\xff\xe0" + bytes(1340), received_raw) + + def test_an_empty_header(self, received_raw): + with pytest.raises(DngError, match="not a TIFF"): + assemble_dng(b"", received_raw) + + def test_a_truncated_header(self, header, received_raw): + with pytest.raises(DngError): + assemble_dng(header[:300], received_raw) + + def test_a_header_without_a_raw_image(self, header, received_raw): + # PhotometricInterpretation 2 (RGB) instead of 32803 (CFA). + no_cfa = _patch(header, SUBIFD, 0x0106, 2) + with pytest.raises(DngError, match="CFA"): + assemble_dng(no_cfa, received_raw) + + def test_raw_data_shorter_than_the_header_says( + self, header, received_raw, + ): + with pytest.raises(DngError, match=r"24724222.*24724224"): + assemble_dng(header, received_raw[:-2]) + + def test_raw_data_longer_than_the_header_says( + self, header, received_raw, + ): + with pytest.raises(DngError, match=r"24724226.*24724224"): + assemble_dng(header, received_raw + b"\x00\x00") + + def test_a_thumbnail_that_overlaps_the_header( + self, header, received_raw, + ): + bad = _patch(header, IFD0, 0x0111, 1000) + with pytest.raises(DngError, match="offset"): + assemble_dng(bad, received_raw) + + def test_raw_data_that_overlaps_the_thumbnail( + self, header, received_raw, + ): + bad = _patch(header, SUBIFD, 0x0111, RAW_OFFSET - 2) + with pytest.raises(DngError, match="offset"): + assemble_dng(bad, received_raw) + + def test_raw_data_that_leaves_a_gap_after_the_thumbnail( + self, header, received_raw, + ): + bad = _patch(header, SUBIFD, 0x0111, RAW_OFFSET + 2) + with pytest.raises(DngError, match="offset"): + assemble_dng(bad, received_raw) + + def test_a_thumbnail_strip_of_the_wrong_size( + self, header, received_raw, + ): + bad = _patch(header, IFD0, 0x0117, THUMB_BYTES - 3) + with pytest.raises(DngError, match="thumbnail"): + assemble_dng(bad, received_raw) + + def test_a_raw_strip_that_does_not_match_the_dimensions( + self, header, received_raw, + ): + bad = _patch(header, SUBIFD, 0x0117, RAW_BYTES - 2) + with pytest.raises(DngError, match="dimensions"): + assemble_dng(bad, received_raw[:-2]) + + def test_compressed_raw_data(self, header, received_raw): + bad = _patch(header, SUBIFD, 0x0103, 7) + with pytest.raises(DngError, match="compress"): + assemble_dng(bad, received_raw) + + def test_the_refusal_is_a_value_error(self, received_raw): + with pytest.raises(ValueError): + assemble_dng(b"nope", received_raw) diff --git a/tests/test_imports.py b/tests/test_imports.py index c194f07..933248b 100644 --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -43,3 +43,12 @@ def test_util_is_the_submodule(self): def test_unknown_name_raises_attribute_error(self): with pytest.raises(AttributeError, match="has no attribute 'nope'"): pychdk.nope + + +class TestDngAssemblyStaysStdlibOnly: + def test_importing_pychdk_dng_does_not_pull_in_pyusb(self): + result = _run_import( + "import pychdk.dng, sys; print('usb' in sys.modules)" + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "False"