From 7130a1b85c37d6e78b454094ec938544acdee14b Mon Sep 17 00:00:00 2001 From: Nymiro Date: Mon, 20 Oct 2025 12:55:31 +1300 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20HEICFile=20=E5=92=8C?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E7=B1=BB=E4=BB=A5=E6=94=AF=E6=8C=81=20'iref'?= =?UTF-8?q?=20=E5=8A=9F=E8=83=BD=EF=BC=8C=E6=B7=BB=E5=8A=A0=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E7=BD=91=E6=A0=BC=E5=B8=83=E5=B1=80=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95=EF=BC=8C=E5=A2=9E=E5=BC=BA=E6=96=87=E4=BB=B6=E5=88=86?= =?UTF-8?q?=E6=9E=90=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .DS_Store | Bin 8196 -> 8196 bytes __pycache__/heic_file.cpython-314.pyc | Bin 8781 -> 9845 bytes __pycache__/heic_types.cpython-314.pyc | Bin 13810 -> 17209 bytes __pycache__/parser.cpython-314.pyc | Bin 3184 -> 3237 bytes heic_file.py | 37 +++++-- heic_types.py | 129 ++++++++++++++++--------- main.py | 14 ++- parser.py | 16 +-- 8 files changed, 133 insertions(+), 63 deletions(-) diff --git a/.DS_Store b/.DS_Store index f68cfb6e4d83b8042f9216ee5a4c21dc78473dfa..b015eeef113ab545cabaac011acde4a5d4962ed8 100644 GIT binary patch delta 154 zcmZp1XmQw}CJN delta 155 zcmZp1XmQw}CJ?9L$iTqB!l1{H&XCDalAG`1l9ZF51Qg={V(05Y$I;|d@X8lt7zQWj z=N161nnI54=IKs=$hfcP|ye_NgYX%j4Mhq?tU8@BE$$?{CNv?Ui`zi6*DkwXtNn@ zN@H4aLgV%HIr<)-remX7@)XUuqom-<$bbREmGMN0;m&vgWg+zmsb5Gvf};pdKybX7 zpyA6B!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j=`qZy4GrWb-BJ;4nH6q%JrPJe~>zc-w3f& zyoR;Fk=6mY)*5~l1#1Qu)vtFZi@ZioEDnXP&G52QPtNG2{M52rJOI4gMN-)v^=>Mg pXA0?3PTRuXf$p}ZrUfEV%YuW@u6yLEd!)N;%~9%qND#%c{{gJC;LZR5 diff --git a/__pycache__/heic_types.cpython-314.pyc b/__pycache__/heic_types.cpython-314.pyc index 7227956207280384cd95800bdc2e619a0f821f1e..524e1919512843b6ee60188fa10bd2951cfe5881 100644 GIT binary patch delta 4226 zcmbVPeNdD49sm9EMo2;uNC<={Bu{_)qzQzvtmiy6tv* z?(+G)ecygB-lSSM?$;g%`Ez=XSr)wi*`tbG_Y}WS7Zi_!6O1WTgj!oEmN|thSKn zOb;8J>ZJ6Lznd$B8Lo!Hdh)sHr{*c>9!C>uZ8&tQ@Agn_GbaqD z$k97l#kaDGM-9$s-I$^5ijrK-8o=qKA)8Op$US%pX~+lJRk)cPl@$_;c^J2lPt2bI zzOP`&hdImizYui%U)T6YtGPl3?7}B(N+xcKTMbj(8UUx93)24Lo&A6@<392eCeP}D zCB72i-*56dvl$4FWEZGoiaWn&joAEsXU)eS(w3q6|_C15xek_OetBKqT81E!~wj4Z825m9Lb5wYkJi{2t z3D$x4kSJS~8m5zUg><-086}qcz-)@5 z*(b;o_7eO!Ic=ZB5%O%_I=q)$&-(xm2pZ4im*OsRJ>RX5fJAP9LMlMZB{IpF@JV7V zC|12lXDK{RS__Ksi}ME&AOn`Qf2HE%kv@PDEYQzS(<*%m2If;G;x*P`a05IYGK4zDx9Wp(6yAp58zBE@0RY%p;wTU`@2J2Z&Kp(B~yc3PteB)j`>Nk z%W6r7S>wd^0Y9*6~=h+7Xv)Cs$5QDL9 zo$_Z?Ir5Sz1Rx4KL#E1#!6}&KC-Mb(3>ESw1tCNTcku=tQaDLQmYeV!g11aAPY3Ul zlz#!^zm{*rgp{xNJmUyZB~<}F(9MTBy7&3HH;AobEq;mYsyMFvB`i8IcZQrYvkLAC z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{zM z-Q3mECIsO1{4)G0Y%5HJ$^2H?Cq%%3g%Pk6B(vwq;sUHKxTB_e!eh`e*?vETsh7h(}oct;Yx_fT;}1F=65{r>^Aj)Q(Hn@O$^Sv_ zIPISkCS+Ys@A*1a$CBJbbR~pTIfZpM_X_tO)mep9R~1Uix>v=mDBw=t1~Ey09605O zuBB8hrcrHeRb#ujt28Sls1{?VI2UT;2{h$hxzRDqj4mQHNYb?OFP$wK7~VPa+D z(IhSGazV*!)d3ZNF#wD;P(cH1r+i`237IZH2+#|F=bs_k1Tp+4ONLVG(XFI5OlP>n zd~L=#%o2?8BXYc;=4Vv-j=XuBfNgoikwXIW+kn~Esg4Et9#@biKny~ z*(ZLRFnI=}=H%mypABSzR>%Nxu_};gVEE2pz$o|;M9ks%0HW47gQ+bpdxW=o0wp%T zV!FV>s4#gq`+hcYpq3(u$qgL!jQW!}o%uoL6dA$@naM$%5u6^33_OAjK3`lXZ|02S zuz+yPCrff!a_E3LA2cUNahY-`KxAYmPv;6|yfOJTmrK1I&?GxfAaRQ&B{MIrNC0HA z5SX7?P?TRJ2xjJ{mL%R{$<5C%yTwvcl$d>sH7ygU+KwG8n~{=J1knfz%OYVAAp#Mee#0O?ZM#kF=y!ROt?=pxzWf1w!#LUR_odHOEWMG~g#-lCw ffuBQwse$K{1cPu4V*~#!Ue^Y$?`*&j2b&H6kbr!Y diff --git a/heic_file.py b/heic_file.py index 5c5f7ef..cc7b71b 100644 --- a/heic_file.py +++ b/heic_file.py @@ -5,7 +5,7 @@ from base import Box from parser import parse_boxes from heic_types import ( ItemLocationBox, PrimaryItemBox, ItemInfoBox, ItemPropertiesBox, - ImageSpatialExtentsBox + ImageSpatialExtentsBox, ItemReferenceBox # <-- Import the new class ) from handlers.base_handler import VendorHandler @@ -20,6 +20,7 @@ class HEICFile: self._iinf_box: ItemInfoBox | None = None self._pitm_box: PrimaryItemBox | None = None self._iprp_box: ItemPropertiesBox | None = None + self._iref_box: ItemReferenceBox | None = None # <-- Add new instance variable self.handler: VendorHandler | None = None with open(self.filepath, 'rb') as f: @@ -28,7 +29,6 @@ class HEICFile: self._find_essential_boxes(self.boxes) self._detect_vendor() - # --- FIX: Changed 'elif' to separate 'if' statements for robustness --- def _find_essential_boxes(self, boxes: list[Box]): """Recursively search for essential boxes.""" for box in boxes: @@ -40,13 +40,37 @@ class HEICFile: self._pitm_box = box if isinstance(box, ItemPropertiesBox): self._iprp_box = box + if isinstance(box, ItemReferenceBox): # <-- Find and store the 'iref' box + self._iref_box = box if box.type == 'ftyp': self._ftyp_box = box if box.children: self._find_essential_boxes(box.children) - # All other methods remain unchanged + # --- NEW Method for Task 3.2 --- + def get_grid_layout(self) -> list[int] | None: + """ + Uses 'iref' and 'pitm' to find the tile IDs for the primary grid image. + Returns a list of item IDs that make up the grid. + """ + primary_id = self.get_primary_item_id() + if not primary_id: + return None + + if not self._iref_box: + print("Warning: 'iref' box not found. Cannot determine grid layout.") + return None + + # Find the reference entry that originates from the primary item ID + grid_tile_ids = self._iref_box.references.get(primary_id) + + if not grid_tile_ids: + print(f"Warning: No grid reference found for primary item ID {primary_id}.") + return None + + return grid_tile_ids + def get_image_size(self, item_id: int) -> tuple[int, int] | None: """ Gets the width and height of a given image item ID. @@ -62,8 +86,8 @@ class HEICFile: item_associations = self._iprp_box.ipma.entries[item_id].associations for assoc in item_associations: - property_index = assoc - 1 - if property_index < len(self._iprp_box.ipco.children): + property_index = assoc - 1 # Property indices are 1-based + if 0 <= property_index < len(self._iprp_box.ipco.children): prop = self._iprp_box.ipco.children[property_index] if isinstance(prop, ImageSpatialExtentsBox): return (prop.image_width, prop.image_height) @@ -96,7 +120,6 @@ class HEICFile: self.handler = AppleHandler() return - print("Could not detect a specific vendor. Using default handler.") self.handler = VendorHandler() def get_item_data(self, item_id: int) -> bytes | None: @@ -119,5 +142,7 @@ class HEICFile: if offset is not None: with open(self.filepath, 'rb') as f: f.seek(offset) + # The actual video data could be the rest of the file or a specific length + # For now, we assume it's a reasonable chunk. return f.read() return None \ No newline at end of file diff --git a/heic_types.py b/heic_types.py index 77996d3..a7ac1bd 100644 --- a/heic_types.py +++ b/heic_types.py @@ -30,8 +30,8 @@ class ItemLocationBox(Box): for _ in range(item_count): item_id = struct.unpack('>H', stream[current_pos : current_pos+2])[0] current_pos += 2 - current_pos += 2 - current_pos += base_offset_size + current_pos += 2 # Skip 2 bytes of construction_method + current_pos += base_offset_size # Skip base_offset extent_count = struct.unpack('>H', stream[current_pos : current_pos+2])[0] current_pos += 2 if extent_count > 0: @@ -61,9 +61,13 @@ class ItemInfoBox(Box): self.entries: list[ItemInfoEntry] = [] self._parse_entries() def _parse_entries(self): + # Assumes version 0 of 'iinf' box + if len(self.raw_data) < 6: return item_count = struct.unpack('>H', self.raw_data[4:6])[0] for infe_box in self.children: if infe_box.type == 'infe': + # Assumes version 2 of 'infe' box + if len(infe_box.raw_data) < 12: continue item_id = struct.unpack('>H', infe_box.raw_data[4:6])[0] item_type = infe_box.raw_data[8:12].decode('ascii').strip('\x00') item_name_bytes = infe_box.raw_data[12:] @@ -76,15 +80,14 @@ class PrimaryItemBox(Box): self.item_id: int = 0 self._parse_item_id() def _parse_item_id(self): + # Assumes version 0 of 'pitm' box + if len(self.raw_data) < 6: return self.item_id = struct.unpack('>H', self.raw_data[4:6])[0] -# --- NEW classes for Task 3.1 & 3.2 --- - class ImageSpatialExtentsBox(Box): """'ispe' box, contains image dimensions.""" def __init__(self, size: int, box_type: str, offset: int, raw_data: bytes): super().__init__(size, box_type, offset, raw_data) - # 'ispe' is a FullBox self.image_width = struct.unpack('>I', self.raw_data[4:8])[0] self.image_height = struct.unpack('>I', self.raw_data[8:12])[0] def __repr__(self): @@ -95,7 +98,7 @@ class ItemPropertyAssociationEntry: def __init__(self, item_id, association_count): self.item_id = item_id self.association_count = association_count - self.associations = [] # List of property indices + self.associations = [] def __repr__(self): return f"" @@ -108,60 +111,30 @@ class ItemPropertyAssociationBox(Box): def _parse_associations(self): stream = self.raw_data - - # A FullBox has a 4-byte header (version + flags) version_flags = struct.unpack('>I', stream[:4])[0] version = version_flags >> 24 flags = version_flags & 0xFFFFFF - entry_count = struct.unpack('>I', stream[4:8])[0] pos = 8 - - # Determine field sizes based on the box version and flags item_id_size = 4 if version >= 1 else 2 is_large_property_index = (flags & 1) == 1 for _ in range(entry_count): - # Boundary check for the item ID - if pos + item_id_size > len(stream): - break - - if item_id_size == 4: - item_id = struct.unpack('>I', stream[pos:pos+4])[0] - pos += 4 - else: # item_id_size == 2 - item_id = struct.unpack('>H', stream[pos:pos+2])[0] - pos += 2 - - # Boundary check for association_count - if pos + 1 > len(stream): - break - + if pos + item_id_size > len(stream): break + item_id = struct.unpack('>I' if item_id_size == 4 else '>H', stream[pos:pos+item_id_size])[0] + pos += item_id_size + if pos + 1 > len(stream): break association_count = stream[pos] pos += 1 - entry = ItemPropertyAssociationEntry(item_id, association_count) - for __ in range(association_count): - if is_large_property_index: - # 2-byte association entry - if pos + 2 > len(stream): - break # Not enough data - assoc_value = struct.unpack('>H', stream[pos:pos+2])[0] - property_index = assoc_value & 0x7FFF # Lower 15 bits - pos += 2 - else: - # 1-byte association entry - if pos + 1 > len(stream): - break # Not enough data - assoc_value = stream[pos] - property_index = assoc_value & 0x7F # Lower 7 bits - pos += 1 - - # A property_index of 0 is not a valid index. + prop_size = 2 if is_large_property_index else 1 + if pos + prop_size > len(stream): break + assoc_value = struct.unpack('>H' if prop_size == 2 else '>B', stream[pos:pos+prop_size])[0] + property_index = assoc_value & (0x7FFF if prop_size == 2 else 0x7F) + pos += prop_size if property_index > 0: entry.associations.append(property_index) - self.entries[item_id] = entry class ItemPropertyContainerBox(Box): @@ -170,7 +143,6 @@ class ItemPropertyContainerBox(Box): class ItemPropertiesBox(Box): """'iprp' box. Container for 'ipco' and 'ipma'.""" - @property def ipco(self) -> ItemPropertyContainerBox | None: """Finds and returns the 'ipco' child box if it exists.""" @@ -185,4 +157,67 @@ class ItemPropertiesBox(Box): for child in self.children: if isinstance(child, ItemPropertyAssociationBox): return child - return None \ No newline at end of file + return None + +# --- NEW classes for Task 3.1 ('iref') --- + +class ItemReferenceEntry: + """Helper class for a single reference in the 'iref' box.""" + def __init__(self, from_id, to_ids): + self.from_item_id = from_id + self.to_item_ids = to_ids + def __repr__(self): + return f"" + +class ItemReferenceBox(Box): + """'iref' box, describes relationships between items.""" + def __init__(self, size: int, box_type: str, offset: int, raw_data: bytes): + super().__init__(size, box_type, offset, raw_data) + self.references: dict[int, list[int]] = {} + self._parse_references() + + def _parse_references(self): + stream = self.raw_data + version_flags = struct.unpack('>I', stream[:4])[0] + version = version_flags >> 24 + pos = 4 + + item_id_size = 4 if version == 1 else 2 + + # The 'iref' box contains one or more SingleItemTypeReferenceBox(es) + # We parse them in a loop until we run out of data. + while pos < len(stream): + # Each sub-box has its own size and type + if pos + 8 > len(stream): break + ref_box_size = struct.unpack('>I', stream[pos:pos+4])[0] + ref_box_type = stream[pos+4:pos+8].decode('ascii') + + if pos + ref_box_size > len(stream): break + + # We are interested in 'grid', but could parse others like 'thmb' + # The structure is the same for SingleItemTypeReferenceBox + + if item_id_size == 4: + from_item_id = struct.unpack('>I', stream[pos+8:pos+12])[0] + ref_count_pos = pos + 12 + else: # item_id_size == 2 + from_item_id = struct.unpack('>H', stream[pos+8:pos+10])[0] + ref_count_pos = pos + 10 + + reference_count = struct.unpack('>H', stream[ref_count_pos:ref_count_pos+2])[0] + + to_ids_pos = ref_count_pos + 2 + to_item_ids = [] + for _ in range(reference_count): + if to_ids_pos + item_id_size > len(stream): break + if item_id_size == 4: + to_id = struct.unpack('>I', stream[to_ids_pos:to_ids_pos+4])[0] + else: # item_id_size == 2 + to_id = struct.unpack('>H', stream[to_ids_pos:to_ids_pos+2])[0] + to_item_ids.append(to_id) + to_ids_pos += item_id_size + + self.references[from_item_id] = to_item_ids + + # Move to the next reference box within 'iref' + pos += ref_box_size \ No newline at end of file diff --git a/main.py b/main.py index bcbf4e5..0c4c124 100644 --- a/main.py +++ b/main.py @@ -14,11 +14,21 @@ def analyze_file(filename: str): if primary_id: print(f"The primary item ID is: {primary_id}") - # --- Use our new feature! --- + # Get the primary image dimensions size = heic_file.get_image_size(primary_id) if size: print(f"Primary image dimensions (WxH): {size[0]} x {size[1]}") - + + # --- Use our new feature! --- + grid_layout = heic_file.get_grid_layout() + if grid_layout: + print(f"Primary image is a grid composed of these item IDs: {grid_layout}") + # Optional: Get size of the first tile to see the difference + first_tile_id = grid_layout[0] + tile_size = heic_file.get_image_size(first_tile_id) + if tile_size: + print(f" - Size of the first tile (ID {first_tile_id}): {tile_size[0]} x {tile_size[1]}") + print("\n" + "="*40 + "\n") def main(): diff --git a/parser.py b/parser.py index e0cad8a..22d4c34 100644 --- a/parser.py +++ b/parser.py @@ -5,10 +5,10 @@ from io import BytesIO from base import Box from heic_types import ( ItemLocationBox, PrimaryItemBox, ItemInfoBox, ItemPropertiesBox, - ItemPropertyContainerBox, ItemPropertyAssociationBox, ImageSpatialExtentsBox + ItemPropertyContainerBox, ItemPropertyAssociationBox, ImageSpatialExtentsBox, + ItemReferenceBox # <-- Import the new class ) -# The factory map remains the same BOX_TYPE_MAP = { 'iloc': ItemLocationBox, 'pitm': PrimaryItemBox, @@ -17,14 +17,13 @@ BOX_TYPE_MAP = { 'ipco': ItemPropertyContainerBox, 'ipma': ItemPropertyAssociationBox, 'ispe': ImageSpatialExtentsBox, + 'iref': ItemReferenceBox, # <-- Register the new class } -# --- FIX: Add 'iinf' to CONTAINER_BOXES --- -# 'iinf' is a container for 'infe' boxes, so it needs to be parsed recursively. -CONTAINER_BOXES = {'meta', 'moov', 'trak', 'iprp', 'ipco', 'dinf', 'fiinf', 'ipro', 'iinf'} -FULL_BOXES = {'meta', 'hdlr', 'pitm', 'iinf', 'iloc', 'ipma', 'ispe'} +# 'iref' is also a container. +CONTAINER_BOXES = {'meta', 'moov', 'trak', 'iprp', 'ipco', 'dinf', 'fiinf', 'ipro', 'iinf', 'iref'} +FULL_BOXES = {'meta', 'hdlr', 'pitm', 'iinf', 'iloc', 'ipma', 'ispe', 'iref'} -# The parse_boxes function remains completely unchanged def parse_boxes(stream: BinaryIO, max_size: int) -> List[Box]: """ Parses boxes from a file stream up to a maximum size. @@ -66,7 +65,8 @@ def parse_boxes(stream: BinaryIO, max_size: int) -> List[Box]: child_stream = BytesIO(box.raw_data) parse_size = len(box.raw_data) if box.type in FULL_BOXES: - child_stream.read(4) # Skip version/flags + # Skip version/flags from the beginning of the raw_data + child_stream.read(4) parse_size -= 4 box.children = parse_boxes(child_stream, parse_size)