libaaruformat 1.0 Aaru Data Preservation Suite - Format Library

Loading...
Searching...
No Matches
decls.h File Reference
`#include "aaru.h"`
`#include "crc64.h"`
`#include "md5.h"`
`#include "sha1.h"`
`#include "sha256.h"`
`#include "simd.h"`
`#include "spamsum.h"`
`#include "structs/optical.h"`

Go to the source code of this file.

## Macros
#define | EXTERNC
#define | AARU_CALL
#define | AARU_EXPORT EXTERNC
#define | AARU_LOCAL
#define | FORCE_INLINE static inline __attribute__((always_inline))

## Functions
int | aaruf_identify (const char *filename)
| Identifies a file as an AaruFormat image using a file path.
int | aaruf_identify_stream (FILE *image_stream)
| Identifies a file as an AaruFormat image using an open stream.
void * | aaruf_open (const char *filepath, bool resume_mode, char *options)
void * | aaruf_create (const char *filepath, uint32_t media_type, uint32_t sector_size, uint64_t user_sectors, uint64_t negative_sectors, uint64_t overflow_sectors, const char *options, const uint8_t *application_name, uint8_t application_name_length, uint8_t application_major_version, uint8_t application_minor_version, bool is_tape)
| Creates a new AaruFormat image file.
int | aaruf_close (void *context)
| Close an Aaru image context, flushing pending data structures and releasing resources.
int32_t | aaruf_read_media_tag (void *context, uint8_t *data, int32_t tag, uint32_t *length)
| Reads a media tag from the AaruFormat image.
crc64_ctx * | aaruf_crc64_init ()
| Initializes a CRC64 context.
int | aaruf_crc64_update (crc64_ctx *ctx, const uint8_t *data, uint32_t len)
| Updates the CRC64 context with new data.
int | aaruf_crc64_final (crc64_ctx *ctx, uint64_t *crc)
| Computes the final CRC64 value from the context.
void | aaruf_crc64_free (crc64_ctx *ctx)
| Frees a CRC64 context.
void | aaruf_crc64_slicing (uint64_t *previous_crc, const uint8_t *data, uint32_t len)
| Updates a CRC64 value using the slicing-by-8 algorithm.
uint64_t | aaruf_crc64_data (const uint8_t *data, uint32_t len)
int32_t | aaruf_get_tracks (const void *context, uint8_t *buffer, size_t *length)
| Retrieve the array of track descriptors contained in an opened AaruFormat image.
int32_t | aaruf_set_tracks (void *context, TrackEntry *tracks, const int count)
| Replace (or clear) the in-memory track table for an AaruFormat image context.
int32_t | aaruf_read_sector (void *context, uint64_t sector_address, bool negative, uint8_t *data, uint32_t *length, uint8_t *sector_status)
| Reads a sector from the AaruFormat image.
int32_t | aaruf_read_sector_long (void *context, uint64_t sector_address, bool negative, uint8_t *data, uint32_t *length, uint8_t *sector_status)
| Reads a complete sector with all metadata from the AaruFormat image.
int32_t | aaruf_write_sector (void *context, uint64_t sector_address, bool negative, const uint8_t *data, uint8_t sector_status, uint32_t length)
| Writes a sector to the AaruFormat image.
int32_t | aaruf_write_sector_long (void *context, uint64_t sector_address, bool negative, const uint8_t *data, uint8_t sector_status, uint32_t length)
| Writes a full ("long") raw sector from optical or block media, parsing structure and validating content.
int32_t | aaruf_write_media_tag (void *context, const uint8_t *data, int32_t type, uint32_t length)
| Writes a media tag to the AaruFormat image, storing medium-specific metadata and descriptors.
int32_t | aaruf_write_sector_tag (void *context, uint64_t sector_address, bool negative, const uint8_t *data, size_t length, int32_t tag)
| Writes per-sector tag data (auxiliary metadata) for a specific sector.
int32_t | aaruf_verify_image (void *context)
| Verifies the integrity of an AaruFormat image file.
int32_t | aaruf_cst_transform (const uint8_t *interleaved, uint8_t *sequential, size_t length)
| Transforms interleaved subchannel data to sequential format.
int32_t | aaruf_cst_untransform (const uint8_t *sequential, uint8_t *interleaved, size_t length)
| Reverses the CST (Claunia's Subchannel Transform) transformation from sequential to interleaved data.
void * | aaruf_ecc_cd_init ()
| Initializes a Compact Disc ECC context.
bool | aaruf_ecc_cd_is_suffix_correct (void *context, const uint8_t *sector)
| Checks if the suffix (EDC/ECC) of a CD sector is correct (Mode 1).
bool | aaruf_ecc_cd_is_suffix_correct_mode2 (void *context, const uint8_t *sector)
| Checks if the suffix (EDC/ECC) of a CD sector is correct (Mode 2).
bool | aaruf_ecc_cd_check (void *context, const uint8_t *address, const uint8_t *data, uint32_t major_count, uint32_t minor_count, uint32_t major_mult, uint32_t minor_inc, const uint8_t *ecc, int32_t address_offset, int32_t data_offset, int32_t ecc_offset)
| Checks the ECC of a CD sector.
void | aaruf_ecc_cd_write (void *context, const uint8_t *address, const uint8_t *data, uint32_t major_count, uint32_t minor_count, uint32_t major_mult, uint32_t minor_inc, uint8_t *ecc, int32_t address_offset, int32_t data_offset, int32_t ecc_offset)
| Writes ECC for a CD sector.
void | aaruf_ecc_cd_write_sector (void *context, const uint8_t *address, const uint8_t *data, uint8_t *ecc, int32_t address_offset, int32_t data_offset, int32_t ecc_offset)
| Writes ECC for a full CD sector (both P and Q ECC).
void | aaruf_cd_lba_to_msf (int64_t pos, uint8_t *minute, uint8_t *second, uint8_t *frame)
| Converts a CD LBA (Logical Block Address) to MSF (Minute:Second:Frame) format.
void | aaruf_ecc_cd_reconstruct_prefix (uint8_t *sector, uint8_t type, int64_t lba)
| Reconstructs the prefix (sync, address, mode) of a CD sector.
void | aaruf_ecc_cd_reconstruct (void *context, uint8_t *sector, uint8_t type)
| Reconstructs the EDC and ECC fields of a CD sector.
uint32_t | aaruf_edc_cd_compute (void *context, uint32_t edc, const uint8_t *src, int size, int pos)
| Computes the EDC (Error Detection Code) for a CD sector.
int32_t | aaruf_read_track_sector (void *context, uint8_t *data, uint64_t sector_address, uint32_t *length, uint8_t track, uint8_t *sector_status)
| Reads a sector from a specific track in the AaruFormat image.
int32_t | aaruf_read_sector_tag (const void *context, uint64_t sector_address, bool negative, uint8_t *buffer, uint32_t *length, int32_t tag)
| Reads a specific sector tag from the AaruFormat image.
int32_t | aaruf_get_media_tag_type_for_datatype (int32_t type)
| Converts an image data type to an Aaru media tag type.
int32_t | aaruf_get_datatype_for_media_tag_type (int32_t tag_type)
| Converts an Aaru media tag type to an image data type.
int32_t | aaruf_get_xml_mediatype (int32_t type)
int32_t | aaruf_get_geometry (const void *context, uint32_t *cylinders, uint32_t *heads, uint32_t *sectors_per_track)
| Retrieves the logical CHS geometry from the AaruFormat image.
int32_t | aaruf_set_geometry (void *context, uint32_t cylinders, uint32_t heads, uint32_t sectors_per_track)
| Sets the logical CHS geometry for the AaruFormat image.
int32_t | aaruf_set_media_sequence (void *context, int32_t sequence, int32_t last_sequence)
| Sets the media sequence information for multi-volume media sets.
int32_t | aaruf_set_creator (void *context, const uint8_t *data, int32_t length)
| Sets the creator (person/operator) information for the image.
int32_t | aaruf_set_comments (void *context, const uint8_t *data, int32_t length)
| Sets user comments or notes for the image.
int32_t | aaruf_set_media_title (void *context, const uint8_t *data, int32_t length)
| Sets the media title or label for the image.
int32_t | aaruf_set_media_manufacturer (void *context, const uint8_t *data, int32_t length)
| Sets the media manufacturer information for the image.
int32_t | aaruf_set_media_model (void *context, const uint8_t *data, int32_t length)
| Sets the media model or product designation for the image.
int32_t | aaruf_set_media_serial_number (void *context, const uint8_t *data, int32_t length)
| Sets the media serial number for the image.
int32_t | aaruf_set_media_barcode (void *context, const uint8_t *data, int32_t length)
| Sets the media barcode information for the image.
int32_t | aaruf_set_media_part_number (void *context, const uint8_t *data, int32_t length)
| Sets the media part number or model designation for the image.
int32_t | aaruf_set_drive_manufacturer (void *context, const uint8_t *data, int32_t length)
| Sets the drive manufacturer information for the image.
int32_t | aaruf_set_drive_model (void *context, const uint8_t *data, int32_t length)
| Sets the drive model information for the image.
int32_t | aaruf_set_drive_serial_number (void *context, const uint8_t *data, int32_t length)
| Sets the drive serial number for the image.
int32_t | aaruf_set_drive_firmware_revision (void *context, const uint8_t *data, int32_t length)
| Sets the drive firmware revision for the image.
int32_t | aaruf_get_media_sequence (const void *context, int32_t *sequence, int32_t *last_sequence)
| Retrieves the media sequence metadata for multi-volume image sets.
int32_t | aaruf_get_creator (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the recorded creator (operator) name from the MetadataBlock.
int32_t | aaruf_get_comments (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the user comments or notes stored in the MetadataBlock.
int32_t | aaruf_get_media_title (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the media title or label captured during image creation.
int32_t | aaruf_get_media_manufacturer (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the recorded media manufacturer name.
int32_t | aaruf_get_media_model (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the media model or product designation metadata.
int32_t | aaruf_get_media_serial_number (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the media serial number recorded in the image metadata.
int32_t | aaruf_get_media_barcode (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the barcode assigned to the physical media or its packaging.
int32_t | aaruf_get_media_part_number (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the media part number recorded in the MetadataBlock.
int32_t | aaruf_get_drive_manufacturer (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the drive manufacturer metadata captured during imaging.
int32_t | aaruf_get_drive_model (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the device model information for the imaging drive.
int32_t | aaruf_get_drive_serial_number (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the imaging drive's serial number metadata.
int32_t | aaruf_get_drive_firmware_revision (const void *context, uint8_t *buffer, int32_t *length)
| Retrieves the firmware revision metadata for the imaging drive.
int32_t | aaruf_get_cicm_metadata (const void *context, uint8_t *buffer, size_t *length)
| Retrieves the embedded CICM XML metadata sidecar from the image.
int32_t | aaruf_get_aaru_json_metadata (const void *context, uint8_t *buffer, size_t *length)
| Retrieves the embedded Aaru metadata JSON from the image.
int32_t | aaruf_set_aaru_json_metadata (void *context, uint8_t *data, size_t length)
| Sets the Aaru metadata JSON for the image during creation.
int32_t | aaruf_get_user_sectors (const void *context, uint64_t *sectors)
| Retrieves the total number of user-accessible sectors in the AaruFormat image.
int32_t | aaruf_get_negative_sectors (const void *context, uint16_t *sectors)
| Retrieves the number of negative (pre-gap) sectors in the AaruFormat image.
int32_t | aaruf_get_overflow_sectors (const void *context, uint16_t *sectors)
| Retrieves the number of overflow (post-gap) sectors in the AaruFormat image.
int32_t | aaruf_get_image_info (const void *context, ImageInfo *image_info)
| Retrieves a deep copy of the ImageInfo structure from the AaruFormat image.
int32_t | aaruf_clear_media_sequence (void *context)
| Clears the media sequence information from the image metadata.
int32_t | aaruf_clear_creator (void *context)
| Clears the creator (person/operator) information from the image metadata.
int32_t | aaruf_clear_comments (void *context)
| Clears user comments or notes from the image metadata.
int32_t | aaruf_clear_media_title (void *context)
| Clears the media title or label from the image metadata.
int32_t | aaruf_clear_media_manufacturer (void *context)
| Clears the media manufacturer information from the image metadata.
int32_t | aaruf_clear_media_model (void *context)
| Clears the media model or product designation from the image metadata.
int32_t | aaruf_clear_media_serial_number (void *context)
| Clears the media serial number from the image metadata.
int32_t | aaruf_clear_media_barcode (void *context)
| Clears the media barcode information from the image metadata.
int32_t | aaruf_clear_media_part_number (void *context)
| Clears the media part number or model designation from the image metadata.
int32_t | aaruf_clear_drive_manufacturer (void *context)
| Clears the drive manufacturer information from the image metadata.
int32_t | aaruf_clear_drive_model (void *context)
| Clears the drive model information from the image metadata.
int32_t | aaruf_clear_drive_serial_number (void *context)
| Clears the drive serial number from the image metadata.
int32_t | aaruf_clear_drive_firmware_revision (void *context)
| Clears the drive firmware revision from the image metadata.
int32_t | aaruf_get_readable_sector_tags (const void *context, uint8_t *buffer, size_t *length)
| Retrieves which sector tags are readable in the AaruFormat image.
int32_t | aaruf_get_readable_media_tags (const void *context, uint8_t *buffer, size_t *length)
| Retrieves which media tags are present in the AaruFormat image.
int32_t | aaruf_get_tape_file (const void *context, uint8_t partition, uint32_t file, uint64_t *starting_block, uint64_t *ending_block)
| Retrieves the block range for a specific tape file from an Aaru tape image.
int32_t | aaruf_set_tape_file (void *context, uint8_t partition, uint32_t file, uint64_t starting_block, uint64_t ending_block)
| Sets or updates the block range for a specific tape file in an Aaru tape image.
int32_t | aaruf_get_tape_partition (const void *context, uint8_t partition, uint64_t *starting_block, uint64_t *ending_block)
| Retrieves the block range for a specific tape partition from an Aaru tape image.
int32_t | aaruf_set_tape_partition (void *context, uint8_t partition, uint64_t starting_block, uint64_t ending_block)
| Sets or updates the block range for a specific tape partition in an Aaru tape image.
int32_t | aaruf_get_all_tape_files (const void *context, uint8_t *buffer, size_t *length)
| Retrieves all tape file entries from the image.
int32_t | aaruf_get_all_tape_partitions (const void *context, uint8_t *buffer, size_t *length)
| Retrieves all tape partition entries from the image.
int32_t | aaruf_get_dumphw (void *context, uint8_t *buffer, size_t *length)
| Retrieves the dump hardware block containing acquisition environment information.
int32_t | aaruf_set_dumphw (void *context, uint8_t *data, size_t length)
| Sets the dump hardware block for the image during creation.
spamsum_ctx * | aaruf_spamsum_init (void)
int | aaruf_spamsum_update (spamsum_ctx *ctx, const uint8_t *data, uint32_t len)
| Updates the spamsum context with new data.
int | aaruf_spamsum_final (spamsum_ctx *ctx, uint8_t *result)
void | aaruf_spamsum_free (spamsum_ctx *ctx)
| Frees a spamsum (fuzzy hash) context.
void | fuzzy_engine_step (spamsum_ctx *ctx, uint8_t c)
void | roll_hash (spamsum_ctx *ctx, uint8_t c)
void | fuzzy_try_reduce_blockhash (spamsum_ctx *ctx)
void | fuzzy_try_fork_blockhash (spamsum_ctx *ctx)
size_t | aaruf_flac_decode_redbook_buffer (uint8_t *dst_buffer, size_t dst_size, const uint8_t *src_buffer, size_t src_size)
| Decodes a FLAC-compressed Red Book audio buffer.
size_t | aaruf_flac_encode_redbook_buffer (uint8_t *dst_buffer, size_t dst_size, const uint8_t *src_buffer, size_t src_size, uint32_t blocksize, int32_t do_mid_side_stereo, int32_t loose_mid_side_stereo, const char *apodization, uint32_t max_lpc_order, uint32_t qlp_coeff_precision, int32_t do_qlp_coeff_prec_search, int32_t do_exhaustive_model_search, uint32_t min_residual_partition_order, uint32_t max_residual_partition_order, const char *application_id, uint32_t application_id_len)
| Encodes a Red Book audio buffer to FLAC format.
int32_t | aaruf_lzma_decode_buffer (uint8_t *dst_buffer, size_t *dst_size, const uint8_t *src_buffer, size_t *src_size, const uint8_t *props, size_t props_size)
| Decodes an LZMA-compressed buffer.
int32_t | aaruf_lzma_encode_buffer (uint8_t *dst_buffer, size_t *dst_size, const uint8_t *src_buffer, size_t src_size, uint8_t *out_props, size_t *out_props_size, int32_t level, uint32_t dict_size, int32_t lc, int32_t lp, int32_t pb, int32_t fb, int32_t num_threads)
| Encodes a buffer using LZMA compression.
void | aaruf_md5_init (md5_ctx *ctx)
void | aaruf_md5_update (md5_ctx *ctx, const void *data, unsigned long size)
void | aaruf_md5_final (md5_ctx *ctx, unsigned char *result)
void | aaruf_md5_buffer (const void *data, unsigned long size, unsigned char *result)
void | aaruf_sha1_init (sha1_ctx *ctx)
void | aaruf_sha1_update (sha1_ctx *ctx, const void *data, unsigned long size)
void | aaruf_sha1_final (sha1_ctx *ctx, unsigned char *result)
void | aaruf_sha1_buffer (const void *data, unsigned long size, unsigned char *result)
void | aaruf_sha256_init (sha256_ctx *ctx)
void | aaruf_sha256_update (sha256_ctx *ctx, const void *data, unsigned long size)
void | aaruf_sha256_final (sha256_ctx *ctx, unsigned char *result)
void | aaruf_sha256_buffer (const void *data, unsigned long size, unsigned char *result)

## Macro Definition Documentation

## ◆ AARU_CALL

#define AARU_CALL

Definition at line 45 of file decls.h.

Referenced by aaruf_cd_lba_to_msf(), aaruf_clear_comments(), aaruf_clear_creator(), aaruf_clear_drive_firmware_revision(), aaruf_clear_drive_manufacturer(), aaruf_clear_drive_model(), aaruf_clear_drive_serial_number(), aaruf_clear_media_barcode(), aaruf_clear_media_manufacturer(), aaruf_clear_media_model(), aaruf_clear_media_part_number(), aaruf_clear_media_sequence(), aaruf_clear_media_serial_number(), aaruf_clear_media_title(), aaruf_close(), aaruf_crc64_data(), aaruf_crc64_final(), aaruf_crc64_free(), aaruf_crc64_init(), aaruf_crc64_slicing(), aaruf_crc64_update(), aaruf_create(), aaruf_cst_transform(), aaruf_cst_untransform(), aaruf_ecc_cd_check(), aaruf_ecc_cd_init(), aaruf_ecc_cd_is_suffix_correct(), aaruf_ecc_cd_is_suffix_correct_mode2(), aaruf_ecc_cd_reconstruct(), aaruf_ecc_cd_reconstruct_prefix(), aaruf_ecc_cd_write(), aaruf_ecc_cd_write_sector(), aaruf_edc_cd_compute(), aaruf_flac_decode_redbook_buffer(), aaruf_flac_encode_redbook_buffer(), aaruf_get_aaru_json_metadata(), aaruf_get_all_tape_files(), aaruf_get_all_tape_partitions(), aaruf_get_cicm_metadata(), aaruf_get_comments(), aaruf_get_creator(), aaruf_get_datatype_for_media_tag_type(), aaruf_get_drive_firmware_revision(), aaruf_get_drive_manufacturer(), aaruf_get_drive_model(), aaruf_get_drive_serial_number(), aaruf_get_dumphw(), aaruf_get_geometry(), aaruf_get_image_info(), aaruf_get_media_barcode(), aaruf_get_media_manufacturer(), aaruf_get_media_model(), aaruf_get_media_part_number(), aaruf_get_media_sequence(), aaruf_get_media_serial_number(), aaruf_get_media_tag_type_for_datatype(), aaruf_get_media_title(), aaruf_get_negative_sectors(), aaruf_get_overflow_sectors(), aaruf_get_readable_media_tags(), aaruf_get_readable_sector_tags(), aaruf_get_tape_file(), aaruf_get_tape_partition(), aaruf_get_tracks(), aaruf_get_user_sectors(), aaruf_get_xml_mediatype(), aaruf_identify(), aaruf_identify_stream(), aaruf_lzma_decode_buffer(), aaruf_lzma_encode_buffer(), aaruf_md5_buffer(), aaruf_md5_final(), aaruf_md5_init(), aaruf_md5_update(), aaruf_open(), aaruf_open(), aaruf_read_media_tag(), aaruf_read_sector(), aaruf_read_sector_long(), aaruf_read_sector_tag(), aaruf_read_track_sector(), aaruf_set_aaru_json_metadata(), aaruf_set_comments(), aaruf_set_creator(), aaruf_set_drive_firmware_revision(), aaruf_set_drive_manufacturer(), aaruf_set_drive_model(), aaruf_set_drive_serial_number(), aaruf_set_dumphw(), aaruf_set_geometry(), aaruf_set_media_barcode(), aaruf_set_media_manufacturer(), aaruf_set_media_model(), aaruf_set_media_part_number(), aaruf_set_media_sequence(), aaruf_set_media_serial_number(), aaruf_set_media_title(), aaruf_set_tape_file(), aaruf_set_tape_partition(), aaruf_set_tracks(), aaruf_sha1_buffer(), aaruf_sha1_final(), aaruf_sha1_init(), aaruf_sha1_update(), aaruf_sha256_buffer(), aaruf_sha256_final(), aaruf_sha256_init(), aaruf_sha256_update(), aaruf_spamsum_final(), aaruf_spamsum_free(), aaruf_spamsum_init(), aaruf_spamsum_update(), aaruf_verify_image(), aaruf_write_media_tag(), aaruf_write_sector(), aaruf_write_sector_long(), and aaruf_write_sector_tag().

## ◆ AARU_EXPORT

#define AARU_EXPORT EXTERNC

Definition at line 54 of file decls.h.

Referenced by aaruf_clear_comments(), aaruf_clear_creator(), aaruf_clear_drive_firmware_revision(), aaruf_clear_drive_manufacturer(), aaruf_clear_drive_model(), aaruf_clear_drive_serial_number(), aaruf_clear_media_barcode(), aaruf_clear_media_manufacturer(), aaruf_clear_media_model(), aaruf_clear_media_part_number(), aaruf_clear_media_sequence(), aaruf_clear_media_serial_number(), aaruf_clear_media_title(), aaruf_close(), aaruf_crc64_data(), aaruf_crc64_final(), aaruf_crc64_free(), aaruf_crc64_init(), aaruf_crc64_slicing(), aaruf_crc64_update(), aaruf_create(), aaruf_cst_transform(), aaruf_cst_untransform(), aaruf_ecc_cd_check(), aaruf_ecc_cd_init(), aaruf_ecc_cd_is_suffix_correct(), aaruf_ecc_cd_is_suffix_correct_mode2(), aaruf_ecc_cd_reconstruct(), aaruf_ecc_cd_reconstruct_prefix(), aaruf_ecc_cd_write(), aaruf_ecc_cd_write_sector(), aaruf_edc_cd_compute(), aaruf_flac_decode_redbook_buffer(), aaruf_flac_encode_redbook_buffer(), aaruf_get_aaru_json_metadata(), aaruf_get_all_tape_files(), aaruf_get_all_tape_partitions(), aaruf_get_cicm_metadata(), aaruf_get_comments(), aaruf_get_creator(), aaruf_get_drive_firmware_revision(), aaruf_get_drive_manufacturer(), aaruf_get_drive_model(), aaruf_get_drive_serial_number(), aaruf_get_dumphw(), aaruf_get_geometry(), aaruf_get_image_info(), aaruf_get_media_barcode(), aaruf_get_media_manufacturer(), aaruf_get_media_model(), aaruf_get_media_part_number(), aaruf_get_media_sequence(), aaruf_get_media_serial_number(), aaruf_get_media_title(), aaruf_get_negative_sectors(), aaruf_get_overflow_sectors(), aaruf_get_readable_media_tags(), aaruf_get_readable_sector_tags(), aaruf_get_tape_file(), aaruf_get_tape_partition(), aaruf_get_tracks(), aaruf_get_user_sectors(), aaruf_identify(), aaruf_identify_stream(), aaruf_lzma_decode_buffer(), aaruf_lzma_encode_buffer(), aaruf_md5_buffer(), aaruf_md5_final(), aaruf_md5_init(), aaruf_md5_update(), aaruf_open(), aaruf_open(), aaruf_read_media_tag(), aaruf_read_sector(), aaruf_read_sector_long(), aaruf_read_sector_tag(), aaruf_read_track_sector(), aaruf_set_aaru_json_metadata(), aaruf_set_comments(), aaruf_set_creator(), aaruf_set_drive_firmware_revision(), aaruf_set_drive_manufacturer(), aaruf_set_drive_model(), aaruf_set_drive_serial_number(), aaruf_set_dumphw(), aaruf_set_geometry(), aaruf_set_media_barcode(), aaruf_set_media_manufacturer(), aaruf_set_media_model(), aaruf_set_media_part_number(), aaruf_set_media_sequence(), aaruf_set_media_serial_number(), aaruf_set_media_title(), aaruf_set_tape_file(), aaruf_set_tape_partition(), aaruf_set_tracks(), aaruf_sha1_buffer(), aaruf_sha1_final(), aaruf_sha1_init(), aaruf_sha1_update(), aaruf_sha256_buffer(), aaruf_sha256_final(), aaruf_sha256_init(), aaruf_sha256_update(), aaruf_spamsum_final(), aaruf_spamsum_free(), aaruf_spamsum_init(), aaruf_spamsum_update(), aaruf_verify_image(), aaruf_write_media_tag(), aaruf_write_sector(), aaruf_write_sector_long(), and aaruf_write_sector_tag().

## ◆ AARU_LOCAL

#define AARU_LOCAL

Definition at line 55 of file decls.h.

Referenced by aaruf_cd_lba_to_msf(), aaruf_get_datatype_for_media_tag_type(), aaruf_get_media_tag_type_for_datatype(), aaruf_get_xml_mediatype(), aaruf_open(), fuzzy_engine_step(), fuzzy_try_fork_blockhash(), fuzzy_try_reduce_blockhash(), roll_hash(), sha1_transform(), and sha256_transform().

## ◆ EXTERNC

#define EXTERNC

Definition at line 34 of file decls.h.

## ◆ FORCE_INLINE

#define FORCE_INLINE static inline __attribute__((always_inline))

Definition at line 63 of file decls.h.

Referenced by __attribute__(), and md5_process_block_loaded().

## Function Documentation

## ◆ aaruf_cd_lba_to_msf()

void aaruf_cd_lba_to_msf | ( | const int64_t | pos,
|  | uint8_t * | minute,
|  | uint8_t * | second,
|  | uint8_t * | frame )

Converts a CD LBA (Logical Block Address) to MSF (Minute:Second:Frame) format.

Parameters

  pos | LBA position.
  minute | Pointer to store the minute value.
  second | Pointer to store the second value.
  frame | Pointer to store the frame value.

Definition at line 374 of file ecc_cd.c.

References AARU_CALL, AARU_LOCAL, and TRACE.

Referenced by aaruf_ecc_cd_reconstruct_prefix().

## ◆ aaruf_clear_comments()

int32_t aaruf_clear_comments | ( | void * | context | ) |

Clears user comments or notes from the image metadata.

Removes the comments string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This effectively removes any user-provided annotations, notes, or descriptions associated with the image. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized to avoid writing an empty metadata block to the image file.

This function is useful when removing outdated notes, clearing test comments before production deployment, sanitizing images for distribution, or resetting an image to a clean metadata state for repurposing.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared comments. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Either the metadata block was not initialized (early exit, nothing to clear) Or the comments string is freed (if it existed) and the pointer set to NULL The commentsLength field in the metadata block header is set to 0 If all metadata fields are now empty, the metadata block identifier is cleared
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image

Note
  Memory Management:
  - If ctx->comments is not NULL, the allocated memory is freed before clearing
  - The ctx->comments pointer is set to NULL after freeing
  - Safe to call even if comments were never set (NULL check protects against errors)
  - No memory leaks occur when clearing previously set comments
  Use Cases:
  - Removing temporary or development notes before production deployment
  - Clearing outdated comments that no longer apply
  - Sanitizing images for distribution by removing internal notes
  - Resetting images for repurposing with new documentation
  - Removing potentially sensitive information from comments
  - Preparing images for archival with standardized, minimal metadata
  Metadata Block State Management:
  - If the metadata block header is not initialized, function returns success immediately
  - After clearing, checks if all metadata fields are empty
  - If all fields empty, sets metadata block identifier to 0 (deinitialized)
  - Prevents writing empty metadata blocks, optimizing storage efficiency
  Information Loss Considerations:
  - Comments may contain valuable provenance or preservation information
  - Consider archiving comments externally before clearing if they contain important data
  - Comments might document imaging conditions, errors encountered, or quality notes
  - Workflow history and processing information may be lost

Warning
  The metadata changes are only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted to disk.
  After clearing, the comments are permanently lost unless:
  - The image file is not closed (context remains in memory)
  - A backup of the original image exists
  - The comments are documented in external metadata systems

See also
  aaruf_set_comments() for setting comment information.

Definition at line 4003 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::comments, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_creator()

int32_t aaruf_clear_creator | ( | void * | context | ) |

Clears the creator (person/operator) information from the image metadata.

Removes the creator name string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This effectively removes any record of who created the image. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized to avoid writing an empty metadata block to the image file.

This function is useful when anonymizing images for distribution, removing personally identifiable information for privacy compliance (e.g., GDPR), or correcting metadata that was set incorrectly during image creation.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared creator information. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Either the metadata block was not initialized (early exit, nothing to clear) Or the creator string is freed (if it existed) and the pointer set to NULL The creatorLength field in the metadata block header is set to 0 If all metadata fields are now empty, the metadata block identifier is cleared
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image

Note
  Memory Management:
  - If ctx->creator is not NULL, the allocated memory is freed before clearing
  - The ctx->creator pointer is set to NULL after freeing
  - Safe to call even if creator was never set (NULL check protects against errors)
  - No memory leaks occur when clearing previously set creator information
  Privacy and Anonymization:
  - Removes personally identifiable information from image metadata
  - Important for GDPR compliance and privacy protection
  - Consider clearing creator before distributing images publicly
  - May be required by institutional privacy policies
  Metadata Block State Management:
  - If the metadata block header is not initialized, function returns success immediately
  - After clearing, checks if all metadata fields are empty
  - If all fields empty, sets metadata block identifier to 0 (deinitialized)
  - Prevents writing empty metadata blocks, saving storage space
  Use Cases:
  - Anonymizing images for public distribution or research datasets
  - Compliance with data protection regulations (GDPR, CCPA, etc.)
  - Removing incorrect or outdated operator information
  - Preparing images for archival with institutional rather than personal attribution
  - Sanitizing test or development images before production use

Warning
  The metadata changes are only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted to disk.
  After clearing, the creator information is permanently lost unless:
  - The image file is not closed (context remains in memory)
  - A backup of the original image exists
  - The information is reconstructed from external documentation
  Clearing creator may affect:
  - Forensic chain of custody requirements
  - Provenance documentation for archival purposes
  - Accountability and quality assurance workflows
  - Consider legal and institutional requirements before clearing

See also
  aaruf_set_creator() for setting creator information.

Definition at line 3874 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, aaruformat_context::creator, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_drive_firmware_revision()

int32_t aaruf_clear_drive_firmware_revision | ( | void * | context | ) |

Clears the drive firmware revision from the image metadata.

Removes the drive firmware revision string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes any record of the firmware version or revision of the drive or device used to read or write the physical storage media during the imaging process. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared drive firmware revision.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->drive_firmware_revision if not NULL and sets pointer to NULL.
  Technical Impact: Removes specific firmware behavior and capability documentation.
  Use Cases: Simplifying metadata, removing technical details, or correcting errors.
  Troubleshooting: May affect ability to diagnose firmware-specific issues.
  Reproducibility: Reduces ability to reproduce exact imaging conditions.

Warning
  Loss of firmware revision information reduces imaging environment documentation.
  Firmware versions significantly affect drive behavior and error handling.
  May affect ability to identify firmware-related imaging issues or quirks.
  Impacts scientific reproducibility and technical troubleshooting capabilities.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_drive_firmware_revision() for setting drive firmware revision information.

Definition at line 4861 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, aaruformat_context::drive_firmware_revision, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_drive_manufacturer()

int32_t aaruf_clear_drive_manufacturer | ( | void * | context | ) |

Clears the drive manufacturer information from the image metadata.

Removes the drive manufacturer name string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes any record of the company that manufactured the drive or device used to read or write the physical storage media during the imaging process. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared drive manufacturer.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->drive_manufacturer if not NULL and sets pointer to NULL.
  Provenance Impact: Removes imaging equipment context from preservation metadata.
  Use Cases: Anonymizing imaging environment, removing commercial info, or correcting errors.
  Quality Assessment: May affect ability to evaluate imaging tool quality and reliability.

Warning
  Loss of drive manufacturer information reduces imaging process documentation.
  May affect forensic provenance and imaging environment reconstruction.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_drive_manufacturer() for setting drive manufacturer information.

Definition at line 4598 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, aaruformat_context::drive_manufacturer, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_drive_model()

int32_t aaruf_clear_drive_model | ( | void * | context | ) |

Clears the drive model information from the image metadata.

Removes the drive model string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes any record of the specific model or product designation of the drive or device used to read or write the physical storage media during the imaging process. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared drive model.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->drive_model if not NULL and sets pointer to NULL.
  Technical Context: Removes specific drive capability and feature information.
  Use Cases: Anonymizing imaging equipment, simplifying metadata, or correcting errors.
  Troubleshooting: May affect ability to diagnose model-specific imaging issues.

Warning
  Loss of drive model information reduces imaging tool documentation completeness.
  May affect understanding of drive-specific capabilities or limitations.
  Important for reproducing imaging conditions or troubleshooting issues.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_drive_model() for setting drive model information.

Definition at line 4684 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, aaruformat_context::drive_model, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_drive_serial_number()

int32_t aaruf_clear_drive_serial_number | ( | void * | context | ) |

Clears the drive serial number from the image metadata.

Removes the drive serial number string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes the unique identifier of the specific drive or device used to read or write the physical storage media during the imaging process. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared drive serial number.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->drive_serial_number if not NULL and sets pointer to NULL.
  Forensic Impact: Removes unique hardware identification from imaging provenance.
  Privacy: May be necessary for anonymizing specific equipment instances.
  Use Cases: Privacy compliance, equipment anonymization, or correcting errors.
  Equipment Tracking: Breaks correlation with equipment maintenance and calibration records.

Warning
  Loss of drive serial number eliminates unique hardware instance identification.
  May affect forensic chain of custody documentation requirements.
  Impacts ability to correlate images with specific equipment for quality analysis.
  Removes equipment tracking capability for maintenance and workload management.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_drive_serial_number() for setting drive serial number information.

Definition at line 4773 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, aaruformat_context::drive_serial_number, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_media_barcode()

int32_t aaruf_clear_media_barcode | ( | void * | context | ) |

Clears the media barcode information from the image metadata.

Removes the media barcode string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes any record of the barcode affixed to the physical storage media or its packaging, typically used in professional archival and library inventory systems. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared media barcode.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->media_barcode if not NULL and sets pointer to NULL.
  Inventory Impact: Removes correlation with physical media location systems.
  Use Cases: Anonymizing media, removing institutional tracking, or correcting errors.
  Archive Systems: May affect automated retrieval and inventory management.

Warning
  Loss of barcode breaks links to physical inventory and asset management systems.
  May affect robotic tape library operations and automated retrieval.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_media_barcode() for setting media barcode information.

Definition at line 4426 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, aaruformat_context::media_barcode, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_media_manufacturer()

int32_t aaruf_clear_media_manufacturer | ( | void * | context | ) |

Clears the media manufacturer information from the image metadata.

Removes the media manufacturer name string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes any record of the company that manufactured the physical storage media. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared media manufacturer.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->media_manufacturer if not NULL and sets pointer to NULL.
  Preservation Impact: Removes valuable information about media quality and lifespan characteristics.
  Use Cases: Anonymizing media source, removing commercial information, or correcting errors.

Warning
  Loss of manufacturer information may affect preservation planning and media assessment.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_media_manufacturer() for setting media manufacturer information.

Definition at line 4170 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, aaruformat_context::media_manufacturer, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_media_model()

int32_t aaruf_clear_media_model | ( | void * | context | ) |

Clears the media model or product designation from the image metadata.

Removes the media model string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes any record of the specific model, product line, or type designation of the physical storage media. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared media model.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->media_model if not NULL and sets pointer to NULL.
  Information Loss: Removes specific capacity, speed, and compatibility information.
  Use Cases: Removing product-specific details, generalizing metadata, or correcting errors.

Warning
  Loss of model information may affect media compatibility assessments.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_media_model() for setting media model information.

Definition at line 4254 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, aaruformat_context::media_model, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_media_part_number()

int32_t aaruf_clear_media_part_number | ( | void * | context | ) |

Clears the media part number or model designation from the image metadata.

Removes the media part number string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes the manufacturer's part number or catalog designation used for procurement and exact product identification. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared media part number.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->media_part_number if not NULL and sets pointer to NULL.
  Procurement Impact: Removes exact ordering and catalog reference information.
  Use Cases: Removing commercial details, generalizing metadata, or correcting errors.
  Documentation: May affect ability to source compatible replacement media.

Warning
  Loss of part number affects precise product identification and procurement.
  May impact ability to cross-reference with manufacturer specifications.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_media_part_number() for setting media part number information.

Definition at line 4512 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, aaruformat_context::media_part_number, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_media_sequence()

int32_t aaruf_clear_media_sequence | ( | void * | context | ) |

Clears the media sequence information from the image metadata.

Removes the media sequence and last media sequence fields from the AaruFormat image's metadata block, effectively removing any indication that this media is part of a multi-volume set. Both the current sequence number and the total sequence count are reset to zero. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized (identifier set to 0) to avoid writing an empty metadata block to the image file.

This function is useful when repurposing an image that was originally part of a multi-disc set but is now being treated as standalone media, or when correcting metadata that was set incorrectly.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared media sequence information. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Either the metadata block was not initialized (early exit, nothing to clear) Or the mediaSequence and lastMediaSequence fields are set to 0 If all metadata fields are now empty, the metadata block identifier is cleared
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image

Note
  Metadata Block State Management:
  - If the metadata block header is not initialized (identifier != MetadataBlock), the function returns successfully without any action (nothing to clear)
  - After clearing, if all metadata fields are empty, the metadata block header identifier is set to 0, preventing an empty block from being written
  - This automatic cleanup ensures efficient storage and avoids unnecessary blocks
  Sequence Field Reset:
  - Both mediaSequence and lastMediaSequence are set to 0
  - Zero values typically indicate "not part of a sequence" or "unknown sequence"
  - The function does not differentiate between never-set and explicitly-cleared
  Use Cases:
  - Correcting incorrectly set sequence metadata
  - Converting multi-volume images to standalone format
  - Removing obsolete sequence information during image repurposing
  - Cleaning up test or development images
  Relationship to Other Metadata:
  - This function only affects sequence fields; other metadata is preserved
  - Use aaruf_set_media_sequence() to set new sequence values after clearing
  - If reconstructing multi-volume metadata, set sequence before other fields

Warning
  The metadata changes are only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted to disk.
  After clearing, the sequence information is permanently lost unless:
  - The image file is not closed (context remains in memory)
  - A backup of the original image exists
  - The information is reconstructed from external sources

See also
  aaruf_set_media_sequence() for setting sequence information.

Definition at line 3743 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_media_serial_number()

int32_t aaruf_clear_media_serial_number | ( | void * | context | ) |

Clears the media serial number from the image metadata.

Removes the media serial number string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This removes the unique identifier assigned to the specific piece of physical storage media by the manufacturer. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared media serial number.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->media_serial_number if not NULL and sets pointer to NULL.
  Forensic Impact: Removes unique identification critical for chain of custody.
  Privacy: May be necessary for anonymizing specific media instances.
  Use Cases: Privacy compliance, removing tracking identifiers, or correcting errors.

Warning
  Loss of serial number eliminates unique media instance identification.
  May affect forensic chain of custody and authentication capabilities.
  Changes are only persisted during aaruf_close().

See also
  aaruf_set_media_serial_number() for setting media serial number information.

Definition at line 4340 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, aaruformat_context::media_serial_number, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_clear_media_title()

int32_t aaruf_clear_media_title | ( | void * | context | ) |

Clears the media title or label from the image metadata.

Removes the media title string from the AaruFormat image's metadata block, freeing the associated memory and resetting the length field to zero. This effectively removes any record of the title, label, or name that was printed or written on the physical storage media. If this operation results in all metadata fields being empty, the entire metadata block is deinitialized.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully cleared media title.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_READ_ONLY | (-13) The context is not opened for writing.

Note
  Memory Management: Frees ctx->media_title if not NULL and sets pointer to NULL.
  Metadata Block: If all fields become empty, the metadata block is deinitialized.
  Use Cases: Removing physical label information, anonymizing media, or correcting errors.

Warning
  Changes are only persisted during aaruf_close(). Lost unless backed up or not closed.

See also
  aaruf_set_media_title() for setting media title information.

Definition at line 4086 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, MetadataBlockHeader::commentsLength, MetadataBlockHeader::creatorLength, MetadataBlockHeader::driveFirmwareRevisionLength, MetadataBlockHeader::driveManufacturerLength, MetadataBlockHeader::driveModelLength, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, aaruformat_context::media_title, MetadataBlockHeader::mediaBarcodeLength, MetadataBlockHeader::mediaManufacturerLength, MetadataBlockHeader::mediaModelLength, MetadataBlockHeader::mediaPartNumberLength, MetadataBlockHeader::mediaSequence, MetadataBlockHeader::mediaSerialNumberLength, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_close()

int aaruf_close | ( | void * | context | ) |

Close an Aaru image context, flushing pending data structures and releasing resources.

Public API entry point used to finalize an image being written or simply dispose of a context opened for reading. For write-mode contexts (ctx->isWriting true) the function performs the following ordered steps:

1. Rewrite the (possibly updated) main header at offset 0.
2. Close any open data block via aaruf_close_current_block().
3. Flush a cached secondary DDT (multi-level) if pending.
4. Flush either the primary DDT (multi-level) or the single-level DDT table.
5. Finalize and append checksum block(s) for all enabled algorithms.
6. Write auxiliary metadata blocks: tracks, MODE 2 subheaders, sector prefix.
7. Serialize the global index and patch header.indexOffset.
8. Clear deduplication hash map if used.

Afterwards (or for read-mode contexts) all dynamically allocated buffers, arrays, hash tables and mapping structures are freed/unmapped. Media tags are removed from their hash table.

Error Handling:

- Returns -1 with errno = EINVAL if the provided pointer is NULL or not a valid context.
- Returns -1 with errno set to AARUF_ERROR_CANNOT_WRITE_HEADER if a header write fails.
- If any intermediate serialization helper returns an error status, that error value is propagated (converted to -1 with errno set accordingly by the caller if desired). In the current implementation aaruf_close() directly returns the negative error code for helper failures to preserve detail.

Parameters

  context | Opaque pointer returned by earlier open/create calls (must be an aaruformatContext).

Returns
  0 on success; -1 or negative libaaruformat error code on failure.

Return values

  0 | All pending data flushed (if writing) and resources released successfully.
  -1 | Invalid context pointer or initial header rewrite failure (errno = EINVAL or AARUF_ERROR_CANNOT_WRITE_HEADER).
  AARUF_ERROR_CANNOT_WRITE_HEADER | A later write helper (e.g., index, DDT) failed and returned this code directly.
  <other | negative libaaruformat code> Propagated from a write helper if future helpers add more error codes.

Note
  On success the context memory itself is freed; the caller must not reuse the pointer.

Definition at line 3997 of file close.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_close_current_block(), AARUF_ERROR_CANNOT_WRITE_HEADER, AARUF_STATUS_OK, aaruformat_context::checksums, aaruformat_context::cicm_block, mediaTagEntry::data, aaruformat_context::deduplicate, aaruformat_context::dump_hardware_entries_with_data, aaruformat_context::dump_hardware_header, aaruformat_context::ecc_cd_context, DumpHardwareHeader::entries, DumpHardwareEntriesWithData::extents, FATAL, DumpHardwareEntriesWithData::firmware, free_map(), aaruformat_context::header, aaruformat_context::imageStream, aaruformat_context::in_memory_ddt, aaruformat_context::index_entries, aaruformat_context::is_tape, aaruformat_context::is_writing, aaruformat_context::magic, DumpHardwareEntriesWithData::manufacturer, aaruformat_context::mapped_memory_ddt_size, aaruformat_context::mediaTags, aaruformat_context::metadata_block, aaruformat_context::mode2_subheaders, DumpHardwareEntriesWithData::model, aaruformat_context::readableSectorTags, DumpHardwareEntriesWithData::revision, aaruformat_context::sector_cpr_mai, aaruformat_context::sector_edc, aaruformat_context::sector_hash_map, aaruformat_context::sector_id, aaruformat_context::sector_ied, aaruformat_context::sector_prefix, aaruformat_context::sector_prefix_corrected, aaruformat_context::sector_prefix_ddt, aaruformat_context::sector_prefix_ddt2, aaruformat_context::sector_subchannel, aaruformat_context::sector_suffix, aaruformat_context::sector_suffix_corrected, aaruformat_context::sector_suffix_ddt, aaruformat_context::sector_suffix_ddt2, DumpHardwareEntriesWithData::serial, DumpHardwareEntriesWithData::softwareName, DumpHardwareEntriesWithData::softwareOperatingSystem, DumpHardwareEntriesWithData::softwareVersion, Checksums::spamsum, TRACE, aaruformat_context::track_entries, aaruformat_context::user_data_ddt, write_aaru_json_block(), write_cached_secondary_ddt(), write_checksum_block(), write_cicm_block(), write_dumphw_block(), write_dvd_long_sector_blocks(), write_dvd_title_key_decrypted_block(), write_geometry_block(), write_index_block(), write_media_tags(), write_metadata_block(), write_mode2_subheaders_block(), write_primary_ddt(), write_sector_prefix(), write_sector_prefix_ddt(), write_sector_subchannel(), write_sector_suffix(), write_sector_suffix_ddt(), write_single_level_ddt(), write_tape_ddt(), write_tape_file_block(), write_tape_partition_block(), write_tracks_block(), and aaruformat_context::writing_buffer.

Referenced by aaruf_open().

## ◆ aaruf_crc64_data()

uint64_t aaruf_crc64_data | ( | const uint8_t * | data,
|  | uint32_t | len )

Definition at line 160 of file crc64.c.

References AARU_CALL, AARU_EXPORT, aaruf_crc64_final(), aaruf_crc64_free(), aaruf_crc64_init(), and aaruf_crc64_update().

Referenced by aaruf_close_current_block(), aaruf_get_dumphw(), aaruf_set_dumphw(), aaruf_set_tracks(), process_data_block(), process_dumphw_block(), process_tape_files_block(), process_tape_partitions_block(), process_tracks_block(), set_ddt_multi_level_v2(), verify_index_v1(), write_cached_secondary_ddt(), write_dumphw_block(), write_dvd_long_sector_blocks(), write_dvd_title_key_decrypted_block(), write_media_tags(), write_mode2_subheaders_block(), write_sector_prefix(), write_sector_prefix_ddt(), write_sector_subchannel(), write_sector_suffix(), write_sector_suffix_ddt(), write_single_level_ddt(), write_tape_file_block(), and write_tape_partition_block().

## ◆ aaruf_crc64_final()

int aaruf_crc64_final | ( | crc64_ctx * | ctx,
|  | uint64_t * | crc )

Computes the final CRC64 value from the context.

Parameters

  ctx | Pointer to the CRC64 context.
  crc | Pointer to store the resulting CRC64 value.

Returns
  0 on success, -1 on error.

Definition at line 141 of file crc64.c.

References AARU_CALL, AARU_EXPORT, crc64_ctx::crc, and CRC64_ECMA_SEED.

Referenced by aaruf_close_current_block(), aaruf_crc64_data(), aaruf_verify_image(), decode_ddt_multi_level_v2(), process_ddt_v2(), set_ddt_multi_level_v2(), verify_index_v2(), verify_index_v3(), write_cached_secondary_ddt(), write_index_block(), and write_primary_ddt().

## ◆ aaruf_crc64_free()

void aaruf_crc64_free | ( | crc64_ctx * | ctx | ) |

Frees a CRC64 context.

Parameters

  ctx | Pointer to the CRC64 context to free.

Definition at line 155 of file crc64.c.

References AARU_CALL, and AARU_EXPORT.

Referenced by aaruf_close_current_block(), aaruf_crc64_data(), aaruf_verify_image(), verify_index_v2(), and verify_index_v3().

## ◆ aaruf_crc64_init()

crc64_ctx * aaruf_crc64_init | ( | void |  | ) |

Initializes a CRC64 context.

Allocates and initializes a CRC64 context for checksum calculations.

Returns
  Pointer to the initialized crc64_ctx structure, or NULL on failure.

Definition at line 32 of file crc64.c.

References AARU_CALL, AARU_EXPORT, crc64_ctx::crc, CRC64_ECMA_SEED, and TRACE.

Referenced by aaruf_close_current_block(), aaruf_crc64_data(), aaruf_verify_image(), decode_ddt_multi_level_v2(), process_ddt_v2(), set_ddt_multi_level_v2(), verify_index_v2(), verify_index_v3(), write_cached_secondary_ddt(), write_index_block(), and write_primary_ddt().

## ◆ aaruf_crc64_slicing()

void aaruf_crc64_slicing | ( | uint64_t * | previous_crc,
|  | const uint8_t * | data,
|  | uint32_t | len )

Updates a CRC64 value using the slicing-by-8 algorithm.

Parameters

  previous_crc | Pointer to the previous CRC64 value (input/output).
  data | Pointer to the data buffer.
  len | Length of the data buffer in bytes.

Definition at line 102 of file crc64.c.

References AARU_CALL, AARU_EXPORT, and crc64_table.

Referenced by aaruf_crc64_update().

## ◆ aaruf_crc64_update()

int aaruf_crc64_update | ( | crc64_ctx * | ctx,
|  | const uint8_t * | data,
|  | uint32_t | len )

Updates the CRC64 context with new data.

Processes the given data buffer and updates the CRC64 value in the context.

Parameters

  ctx | Pointer to the CRC64 context.
  data | Pointer to the data buffer.
  len | Length of the data buffer.

Returns
  0 on success, or -1 on error.

Definition at line 55 of file crc64.c.

References AARU_CALL, AARU_EXPORT, aaruf_crc64_slicing(), crc64_ctx::crc, and TRACE.

Referenced by aaruf_close_current_block(), aaruf_crc64_data(), decode_ddt_multi_level_v2(), process_ddt_v2(), set_ddt_multi_level_v2(), update_crc64_from_stream(), verify_index_v2(), verify_index_v3(), write_cached_secondary_ddt(), write_index_block(), and write_primary_ddt().

## ◆ aaruf_create()

void * aaruf_create | ( | const char * | filepath,
|  | const uint32_t | media_type,
|  | const uint32_t | sector_size,
|  | const uint64_t | user_sectors,
|  | const uint64_t | negative_sectors,
|  | const uint64_t | overflow_sectors,
|  | const char * | options,
|  | const uint8_t * | application_name,
|  | const uint8_t | application_name_length,
|  | const uint8_t | application_major_version,
|  | const uint8_t | application_minor_version,
|  | const bool | is_tape )

Creates a new AaruFormat image file.

Allocates and initializes a new aaruformat context and image file with the specified parameters. This function sets up all necessary data structures including headers, DDT (deduplication table), caches, and index entries for writing a new AaruFormat image. It also handles file creation, memory allocation, and proper initialization of the writing context. The function supports both block-based media (disks, optical media) and sequential tape media with different initialization strategies optimized for each media type.

Media Type Handling: The function creates different internal structures based on the is_tape parameter:

Block Media (is_tape = false):

- Initializes full DDT (Deduplication Table) version 2 for sector-level deduplication
- Allocates primary DDT table (userDataDdtMini or userDataDdtBig) as a preallocated array
- Configures multi-level DDT support for large images (> 138,412,552 sectors)
- Enables optional deduplication hash map for detecting duplicate sectors
- Reserves space for DDT at the beginning of the file (after header, block-aligned)
- Data blocks start after DDT table to maintain sequential layout
- DDT size is fixed and known upfront based on sector count

Tape Media (is_tape = true):

- Initializes DDT for sector-level deduplication using a different strategy
- Uses a growing hash table (tapeDdt) instead of a preallocated array
- Sets ctx->is_tape flag and initializes ctx->tapeDdt to NULL (populated on first write)
- Data blocks start immediately after the header (block-aligned)
- Hash table grows dynamically as blocks are written
- Optimized for sequential write patterns typical of tape media
- Tape file/partition metadata is managed separately via additional hash tables
- More memory-efficient for tapes with unknown final size

Initialization Flow:

1. Parse creation options (compression, alignment, deduplication, checksums)
2. Allocate and zero-initialize context structure
3. Create/open image file in binary write mode
4. Initialize AaruFormat header with application and version information
5. Set up image metadata and sector size information
6. Initialize block and header caches for performance
7. Initialize ECC context for Compact Disc support
8. Branch based on media type:
   - Block media: Configure DDT structures and calculate offsets with preallocated array
   - Tape media: Set tape flags and initialize for dynamic hash table DDT
9. Initialize index entries array for tracking all blocks
10. Configure compression, checksums, and deduplication based on options
11. Position file pointer at calculated data start position

DDT Configuration (Block Media Only): The function automatically selects optimal DDT parameters:

- Single-level DDT (tableShift=0): For images < 138,412,552 sectors
- Multi-level DDT (tableShift=22): For images ≥ 138,412,552 sectors

The DDT offset calculation ensures proper alignment:

- Primary DDT placed immediately after header (block-aligned)
- Data blocks positioned after DDT table (block-aligned)
- Alignment controlled by blockAlignmentShift from options

Parameters

  filepath | Path to the image file to create. The file will be created if it doesn't exist, or overwritten if it does. Must be a valid writable path.
  media_type | Media type identifier (e.g., CompactDisc, DVD, HardDisk, Tape formats). This affects how the image is structured and which features are enabled.
  sector_size | Size of each sector/block in bytes. Common values: 512 bytes: Hard disks, floppy disks 2048 bytes: CD-ROM, DVD Variable: Tape media (block size varies by format)
  user_sectors | Number of user data sectors/blocks in the image. This is the main data area excluding negative (lead-in) and overflow (lead-out) regions. For tape media, this may be an estimate as the final size is often unknown.
  negative_sectors | Number of negative sectors (typically lead-in area for optical media). Set to 0 for media types without lead-in areas. Not used for tape media.
  overflow_sectors | Number of overflow sectors (typically lead-out area for optical media). Set to 0 for media types without lead-out areas. Not used for tape media.
  options | String with creation options in key=value format, semicolon-separated. Supported options: "compress=true|false": Enable/disable LZMA compression "deduplicate=true|false": Enable/disable sector deduplication (all media types) "md5=true|false": Calculate MD5 checksum during write "sha1=true|false": Calculate SHA-1 checksum during write "sha256=true|false": Calculate SHA-256 checksum during write "spamsum=true|false": Calculate SpamSum fuzzy hash during write "blake3=true|false": Calculate BLAKE3 checksum during write "block_alignment=N": Block alignment shift value (default varies) "data_shift=N": Data shift value for DDT granularity "table_shift=N": Table shift for multi-level DDT (-1 for auto, block media only) "dictionary=N": LZMA dictionary size in bytes Example: "compress=true;deduplicate=true;md5=true;sha1=true"
  application_name | Pointer to the application name string (UTF-8 encoded). This identifies the software that created the image. The string will be copied directly to the image header.
  application_name_length | Length of the application name string in bytes. Must be ≤ AARU_HEADER_APP_NAME_LEN (64 bytes).
  application_major_version | Major version of the creating application (0-255).
  application_minor_version | Minor version of the creating application (0-255).
  is_tape | Boolean flag indicating tape media type: true: Initialize for tape media (sequential, dynamic hash table DDT, file/partition metadata) false: Initialize for block media (random access, preallocated array DDT)

Returns
  Returns one of the following:

Return values

  aaruformatContext* | Successfully created and initialized context. The returned pointer contains: Properly initialized AaruFormat headers and metadata For block media: Allocated and configured DDT structures with preallocated arrays For tape media: Tape flags set, DDT initialized as NULL (grows on demand) Initialized block and header caches for performance Open file stream ready for writing operations Index entries array ready for block tracking ECC context initialized for Compact Disc support Checksum contexts initialized based on options
  NULL | Creation failed. The specific error can be determined by checking errno, which will be set to: AARUF_ERROR_NOT_ENOUGH_MEMORY (-9) when memory allocation fails for: Context allocation Readable sector tags array allocation Application version string allocation Image version string allocation DDT table allocation (userDataDdtMini or userDataDdtBig, block media only) Index entries array allocation AARUF_ERROR_CANNOT_CREATE_FILE (-19) when file operations fail: Unable to open the specified filepath for writing File seek operations fail during initialization File system errors or permission issues AARUF_ERROR_INVALID_APP_NAME_LENGTH (-20) when: application_name_length exceeds AARU_HEADER_APP_NAME_LEN (64 bytes)

Note
  Memory Management:
  - The function performs extensive memory allocation for various context structures
  - On failure, all previously allocated memory is properly cleaned up
  - The returned context must be freed using aaruf_close() when finished
  File Operations:
  - Creates a new file at the specified path (overwrites existing files)
  - Opens the file in binary read/write mode ("wb+")
  - Positions the file pointer at the calculated data start position
  - File alignment is handled based on parsed options
  DDT Initialization (Block Media Only):
  - Uses DDT version 2 format with configurable compression and alignment
  - Calculates optimal table sizes based on sector counts and shift parameters
  - All DDT entries are initialized to zero (indicating unallocated sectors)
  - Multi-level DDT is used for images with ≥ 138,412,552 total sectors
  - Single-level DDT is used for smaller images for efficiency
  - DDT is a fixed-size preallocated array written to file at known offset
  Tape Media Initialization:
  - Tape images use a dynamic hash table DDT for sector-level deduplication
  - File and partition metadata is managed via separate hash tables
  - ctx->is_tape is set to 1 to indicate tape mode throughout the library
  - ctx->tapeDdt is initialized to NULL and grows dynamically as blocks are written
  - Data blocks can start immediately after header for optimal sequential access
  - The hash table DDT allows for efficient deduplication without knowing final size
  - More memory-efficient for tapes with unpredictable or very large sizes
  - Deduplication hash map may still be used alongside tapeDdt if enabled in options
  Options Parsing:
  - The options string is parsed to extract block_alignment, data_shift, and table_shift
  - These parameters affect memory usage, performance, and file organization
  - Invalid options may result in suboptimal performance but won't cause failure
  - Compression and checksums can be enabled independently via options
  Checksum Initialization:
  - MD5, SHA-1, SHA-256, SpamSum, and BLAKE3 can be calculated during write
  - Checksum contexts are initialized only if requested in options
  - Checksums are computed incrementally as sectors/blocks are written
  - Final checksums are stored in checksum block during image finalization

Warning
  The created context is in writing mode and expects proper finalization before closing to ensure index and metadata are written correctly.
  Application name length validation is strict - exceeding the limit will cause creation failure with AARUF_ERROR_INVALID_APP_NAME_LENGTH.
  For tape media, the DDT structure is fundamentally different (hash table vs array). The is_tape flag must accurately reflect the media type being created.
  The negative_sectors and overflow_sectors parameters are used only for block media. For tape media, these parameters are ignored.

See also
  aaruf_close() for proper context cleanup and image finalization
  aaruf_write_sector() for writing sectors to block media images
  aaruf_set_tape_file() for defining tape file metadata
  aaruf_set_tape_partition() for defining tape partition metadata

< Size in bytes (UTF-16LE) of application name field (32 UTF-16 code units).

< Size in bytes of GUID / UUID-like binary identifier.

Definition at line 279 of file create.c.

References AARU_CALL, AARU_EXPORT, AARU_HEADER_APP_NAME_LEN, AARU_MAGIC, aaruf_ecc_cd_init(), AARUF_ERROR_CANNOT_CREATE_FILE, AARUF_ERROR_INVALID_APP_NAME_LENGTH, AARUF_ERROR_NOT_ENOUGH_MEMORY, aaruf_get_xml_mediatype(), aaruf_md5_init(), aaruf_sha1_init(), aaruf_sha256_init(), aaruf_spamsum_init(), AARUF_VERSION_V2, ImageInfo::Application, AaruHeaderV2::application, AaruHeaderV2::applicationMajorVersion, AaruHeaderV2::applicationMinorVersion, ImageInfo::ApplicationVersion, aaru_options::blake3, aaruformat_context::blake3_context, aaru_options::block_alignment, aaruformat_context::block_cache, aaruformat_context::block_header_cache, DdtHeader2::blockAlignmentShift, DdtHeader2::blocks, CacheHeader::cache, aaruformat_context::calculating_blake3, aaruformat_context::calculating_md5, aaruformat_context::calculating_sha1, aaruformat_context::calculating_sha256, aaruformat_context::calculating_spamsum, cleanup_failed_create(), aaru_options::compress, DdtHeader2::compression, aaruformat_context::compression_enabled, create_map(), ImageInfo::CreationTime, AaruHeaderV2::creationTime, aaru_options::data_shift, DdtHeader2::dataShift, aaru_options::deduplicate, aaruformat_context::deduplicate, DeDuplicationTable2, aaru_options::dictionary, aaruformat_context::ecc_cd_context, DdtHeader2::entries, FATAL, generate_random_bytes(), get_filetime_uint64(), AaruHeaderV2::guid, GUID_SIZE, aaruformat_context::header, AaruHeaderV2::identifier, DdtHeader2::identifier, aaruformat_context::image_info, AaruHeaderV2::imageMajorVersion, AaruHeaderV2::imageMinorVersion, ImageInfo::ImageSize, aaruformat_context::imageStream, aaruformat_context::in_memory_ddt, aaruformat_context::index_entries, AaruHeaderV2::indexOffset, aaruformat_context::is_tape, aaruformat_context::is_writing, aaruformat_context::last_written_block, ImageInfo::LastModificationTime, AaruHeaderV2::lastWrittenTime, DdtHeader2::levels, LIBAARUFORMAT_MAJOR_VERSION, LIBAARUFORMAT_MINOR_VERSION, aaruformat_context::library_major_version, aaruformat_context::library_minor_version, aaruformat_context::lzma_dict_size, aaruformat_context::magic, MAX_CACHE_SIZE, CacheHeader::max_items, MaxSectorTag, aaru_options::md5, aaruformat_context::md5_context, ImageInfo::MediaType, AaruHeaderV2::mediaType, ImageInfo::MetadataMediaType, DdtHeader2::negative, aaruformat_context::next_block_position, None, DdtHeader2::overflow, parse_options(), DdtHeader2::previousLevelOffset, aaruformat_context::primary_ddt_offset, aaruformat_context::readableSectorTags, aaruformat_context::rewinded, aaruformat_context::sector_hash_map, ImageInfo::Sectors, ImageInfo::SectorSize, aaru_options::sha1, aaruformat_context::sha1_context, aaru_options::sha256, aaruformat_context::sha256_context, aaruformat_context::shift, aaru_options::spamsum, aaruformat_context::spamsum_context, DdtHeader2::start, aaru_options::table_shift, DdtHeader2::tableLevel, DdtHeader2::tableShift, aaruformat_context::tape_ddt, TRACE, DdtHeader2::type, aaruformat_context::user_data_ddt2, aaruformat_context::user_data_ddt_header, UserData, and ImageInfo::Version.

## ◆ aaruf_cst_transform()

int32_t aaruf_cst_transform | ( | const uint8_t * | interleaved,
|  | uint8_t * | sequential,
|  | const size_t | length )

Transforms interleaved subchannel data to sequential format.

Converts interleaved subchannel data into a sequential format for further processing.

Parameters

  interleaved | Pointer to the interleaved data buffer.
  sequential | Pointer to the output sequential data buffer.
  length | Length of the data buffer.

Returns
  AARUF_STATUS_OK on success, or an error code on failure.

Definition at line 35 of file cst.c.

References AARU_CALL, AARU_EXPORT, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_NOT_ENOUGH_MEMORY, and AARUF_STATUS_OK.

Referenced by write_sector_subchannel().

## ◆ aaruf_cst_untransform()

int32_t aaruf_cst_untransform | ( | const uint8_t * | sequential,
|  | uint8_t * | interleaved,
|  | const size_t | length )

Reverses the CST (Claunia's Subchannel Transform) transformation from sequential to interleaved data.

Parameters

  sequential | Pointer to the sequential data buffer.
  interleaved | Pointer to the output buffer for interleaved data.
  length | Length of the data in bytes.

Returns
  AARUF_STATUS_OK on success, or an error code on failure.

Definition at line 193 of file cst.c.

References AARU_CALL, AARU_EXPORT, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_NOT_ENOUGH_MEMORY, and AARUF_STATUS_OK.

Referenced by process_data_block().

## ◆ aaruf_ecc_cd_check()

bool aaruf_ecc_cd_check | ( | void * | context,
|  | const uint8_t * | address,
|  | const uint8_t * | data,
|  | const uint32_t | major_count,
|  | const uint32_t | minor_count,
|  | const uint32_t | major_mult,
|  | const uint32_t | minor_inc,
|  | const uint8_t * | ecc,
|  | const int32_t | address_offset,
|  | const int32_t | data_offset,
|  | const int32_t | ecc_offset )

Checks the ECC of a CD sector.

Parameters

  context | Pointer to the ECC context.
  address | Pointer to the address field.
  data | Pointer to the data field.
  major_count | Number of major iterations.
  minor_count | Number of minor iterations.
  major_mult | Major multiplier.
  minor_inc | Minor increment.
  ecc | Pointer to the ECC field.
  address_offset | Offset for the address field.
  data_offset | Offset for the data field.
  ecc_offset | Offset for the ECC field.

Returns
  true if ECC is correct, false otherwise.

Definition at line 227 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, CdEccContext::ecc_b_table, CdEccContext::ecc_f_table, CdEccContext::inited_edc, and TRACE.

Referenced by aaruf_ecc_cd_is_suffix_correct(), and aaruf_ecc_cd_is_suffix_correct_mode2().

## ◆ aaruf_ecc_cd_init()

void * aaruf_ecc_cd_init | ( |  | ) |

Initializes a Compact Disc ECC context.

Allocates and initializes a context for Compact Disc ECC calculations.

Returns
  Pointer to the initialized CdEccContext structure, or NULL on failure.

Definition at line 35 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, CdEccContext::ecc_b_table, CdEccContext::ecc_f_table, CdEccContext::edc_table, CdEccContext::inited_edc, and TRACE.

Referenced by aaruf_create(), and aaruf_open().

## ◆ aaruf_ecc_cd_is_suffix_correct()

bool aaruf_ecc_cd_is_suffix_correct | ( | void * | context,
|  | const uint8_t * | sector )

Checks if the suffix (EDC/ECC) of a CD sector is correct (Mode 1).

Parameters

  context | Pointer to the ECC context.
  sector | Pointer to the sector data.

Returns
  true if the suffix is correct, false otherwise.

Definition at line 101 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, aaruf_ecc_cd_check(), aaruf_edc_cd_compute(), CdEccContext::inited_edc, and TRACE.

Referenced by aaruf_write_sector_long().

## ◆ aaruf_ecc_cd_is_suffix_correct_mode2()

bool aaruf_ecc_cd_is_suffix_correct_mode2 | ( | void * | context,
|  | const uint8_t * | sector )

Checks if the suffix (EDC/ECC) of a CD sector is correct (Mode 2).

Parameters

  context | Pointer to the ECC context.
  sector | Pointer to the sector data.

Returns
  true if the suffix is correct, false otherwise.

Definition at line 165 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, aaruf_ecc_cd_check(), aaruf_edc_cd_compute(), CdEccContext::inited_edc, and TRACE.

Referenced by aaruf_write_sector_long().

## ◆ aaruf_ecc_cd_reconstruct()

void aaruf_ecc_cd_reconstruct | ( | void * | context,
|  | uint8_t * | sector,
|  | const uint8_t | type )

Reconstructs the EDC and ECC fields of a CD sector.

Parameters

  context | Pointer to the ECC context.
  sector | Pointer to the sector data (must be 2352 bytes).
  type | Track type (mode).

Definition at line 459 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, aaruf_ecc_cd_write_sector(), aaruf_edc_cd_compute(), CdMode1, CdMode2Form1, CdMode2Form2, CdEccContext::inited_edc, and TRACE.

Referenced by aaruf_read_sector_long().

## ◆ aaruf_ecc_cd_reconstruct_prefix()

void aaruf_ecc_cd_reconstruct_prefix | ( | uint8_t * | sector,
|  | const uint8_t | type,
|  | const int64_t | lba )

Reconstructs the prefix (sync, address, mode) of a CD sector.

Parameters

  sector | Pointer to the sector data (must be 2352 bytes).
  type | Track type (mode).
  lba | Logical Block Address.

Definition at line 392 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, aaruf_cd_lba_to_msf(), CdMode1, CdMode2Form1, CdMode2Form2, CdMode2Formless, and TRACE.

Referenced by aaruf_read_sector_long().

## ◆ aaruf_ecc_cd_write()

void aaruf_ecc_cd_write | ( | void * | context,
|  | const uint8_t * | address,
|  | const uint8_t * | data,
|  | const uint32_t | major_count,
|  | const uint32_t | minor_count,
|  | const uint32_t | major_mult,
|  | const uint32_t | minor_inc,
|  | uint8_t * | ecc,
|  | const int32_t | address_offset,
|  | const int32_t | data_offset,
|  | const int32_t | ecc_offset )

Writes ECC for a CD sector.

Parameters

  context | Pointer to the ECC context.
  address | Pointer to the address field.
  data | Pointer to the data field.
  major_count | Number of major iterations.
  minor_count | Number of minor iterations.
  major_mult | Major multiplier.
  minor_inc | Minor increment.
  ecc | Pointer to the ECC field to write.
  address_offset | Offset for the address field.
  data_offset | Offset for the data field.
  ecc_offset | Offset for the ECC field.

Definition at line 293 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, CdEccContext::ecc_b_table, CdEccContext::ecc_f_table, CdEccContext::inited_edc, and TRACE.

Referenced by aaruf_ecc_cd_write_sector().

## ◆ aaruf_ecc_cd_write_sector()

void aaruf_ecc_cd_write_sector | ( | void * | context,
|  | const uint8_t * | address,
|  | const uint8_t * | data,
|  | uint8_t * | ecc,
|  | const int32_t | address_offset,
|  | const int32_t | data_offset,
|  | const int32_t | ecc_offset )

Writes ECC for a full CD sector (both P and Q ECC).

Parameters

  context | Pointer to the ECC context.
  address | Pointer to the address field.
  data | Pointer to the data field.
  ecc | Pointer to the ECC field to write.
  address_offset | Offset for the address field.
  data_offset | Offset for the data field.
  ecc_offset | Offset for the ECC field.

Definition at line 352 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, aaruf_ecc_cd_write(), and TRACE.

Referenced by aaruf_ecc_cd_reconstruct().

## ◆ aaruf_edc_cd_compute()

uint32_t aaruf_edc_cd_compute | ( | void * | context,
|  | uint32_t | edc,
|  | const uint8_t * | src,
|  | int | size,
|  | int | pos )

Computes the EDC (Error Detection Code) for a CD sector.

Parameters

  context | Pointer to the ECC context.
  edc | Initial EDC value.
  src | Pointer to the data to compute EDC over.
  size | Number of bytes to process.
  pos | Starting position in the data.

Returns
  Computed EDC value.

Definition at line 547 of file ecc_cd.c.

References AARU_CALL, AARU_EXPORT, CdEccContext::edc_table, CdEccContext::inited_edc, and TRACE.

Referenced by aaruf_ecc_cd_is_suffix_correct(), aaruf_ecc_cd_is_suffix_correct_mode2(), aaruf_ecc_cd_reconstruct(), and aaruf_write_sector_long().

## ◆ aaruf_flac_decode_redbook_buffer()

size_t aaruf_flac_decode_redbook_buffer | ( | uint8_t * | dst_buffer,
|  | size_t | dst_size,
|  | const uint8_t * | src_buffer,
|  | size_t | src_size )

Decodes a FLAC-compressed Red Book audio buffer.

Decompresses FLAC-compressed Red Book audio data into the destination buffer.

Parameters

  dst_buffer | Pointer to the destination buffer.
  dst_size | Size of the destination buffer.
  src_buffer | Pointer to the source (compressed) buffer.
  src_size | Size of the source buffer.

Returns
  Number of bytes written to the destination buffer.

Definition at line 48 of file flac.c.

References AARU_CALL, AARU_EXPORT, aaru_flac_ctx::dst_buffer, aaru_flac_ctx::dst_len, aaru_flac_ctx::dst_pos, aaru_flac_ctx::error, error_callback(), read_callback(), aaru_flac_ctx::src_buffer, aaru_flac_ctx::src_len, aaru_flac_ctx::src_pos, and write_callback().

Referenced by aaruf_read_sector().

## ◆ aaruf_flac_encode_redbook_buffer()

size_t aaruf_flac_encode_redbook_buffer | ( | uint8_t * | dst_buffer,
|  | size_t | dst_size,
|  | const uint8_t * | src_buffer,
|  | size_t | src_size,
|  | uint32_t | blocksize,
|  | int32_t | do_mid_side_stereo,
|  | int32_t | loose_mid_side_stereo,
|  | const char * | apodization,
|  | uint32_t | max_lpc_order,
|  | uint32_t | qlp_coeff_precision,
|  | int32_t | do_qlp_coeff_prec_search,
|  | int32_t | do_exhaustive_model_search,
|  | uint32_t | min_residual_partition_order,
|  | uint32_t | max_residual_partition_order,
|  | const char * | application_id,
|  | uint32_t | application_id_len )

Encodes a Red Book audio buffer to FLAC format.

Parameters

  dst_buffer | Pointer to the destination buffer for FLAC data.
  dst_size | Size of the destination buffer in bytes.
  src_buffer | Pointer to the source Red Book audio buffer.
  src_size | Size of the source buffer in bytes.
  blocksize | FLAC block size.
  do_mid_side_stereo | Enable mid-side stereo encoding.
  loose_mid_side_stereo | Enable loose mid-side stereo encoding.
  apodization | Apodization string for FLAC encoder.
  max_lpc_order | Maximum LPC order.
  qlp_coeff_precision | QLP coefficient precision.
  do_qlp_coeff_prec_search | Enable QLP coefficient precision search.
  do_exhaustive_model_search | Enable exhaustive model search.
  min_residual_partition_order | Minimum residual partition order.
  max_residual_partition_order | Maximum residual partition order.
  application_id | Application ID string for FLAC encoder.
  application_id_len | Length of the application ID string.

Returns
  Number of bytes written to the destination buffer.

Definition at line 175 of file flac.c.

References AARU_CALL, AARU_EXPORT, aaru_flac_ctx::dst_buffer, aaru_flac_ctx::dst_len, aaru_flac_ctx::dst_pos, encoder_write_callback(), aaru_flac_ctx::error, aaru_flac_ctx::src_buffer, aaru_flac_ctx::src_len, and aaru_flac_ctx::src_pos.

Referenced by aaruf_close_current_block().

## ◆ aaruf_get_aaru_json_metadata()

int32_t aaruf_get_aaru_json_metadata | ( | const void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieves the embedded Aaru metadata JSON from the image.

Aaru metadata JSON is a structured metadata format that provides machine-readable, comprehensive information about the image, media, imaging session details, hardware configuration, optical disc tracks and sessions, checksums, and preservation metadata. This function extracts the raw JSON payload that was embedded in the AaruFormat image during creation. The JSON data is preserved in its original form without parsing or interpretation by the library, allowing callers to process the structured metadata using standard JSON parsing libraries.

This function supports a two-call pattern for buffer size determination:

1. First call with a buffer that may be too small returns AARUF_ERROR_BUFFER_TOO_SMALL and sets *length to the required size
2. Second call with a properly sized buffer retrieves the actual data

Alternatively, if the caller already knows the buffer is large enough, a single call will succeed and populate the buffer with the Aaru JSON data.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened image context).
  buffer | Pointer to a buffer that will receive the Aaru metadata JSON. Must be large enough to hold the entire JSON payload (at least *length bytes on input). The buffer will contain raw UTF-8 encoded JSON data on success.
  length | Pointer to a size_t that serves dual purpose: On input: size of the provided buffer in bytes On output: actual size of the Aaru metadata JSON in bytes If the function returns AARUF_ERROR_BUFFER_TOO_SMALL, this will be updated to contain the required buffer size for a subsequent successful call.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved Aaru metadata JSON. This is returned when: The context is valid and properly initialized The Aaru JSON block is present in the image (identifier == AaruMetadataJsonBlock) The provided buffer is large enough (>= required length) The Aaru JSON data is successfully copied to the buffer The *length parameter is set to the actual size of the JSON data
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()
  AARUF_ERROR_CANNOT_READ_BLOCK | (-7) The Aaru JSON block is not present. This occurs when: The image was created without Aaru metadata JSON ctx->jsonBlock is NULL (no data loaded) ctx->jsonBlockHeader.length is 0 (empty metadata) ctx->jsonBlockHeader.identifier doesn't equal AaruMetadataJsonBlock The Aaru JSON block was not found during image opening The *length output parameter is set to 0 to indicate no data available
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer is insufficient. This occurs when: The input *length is less than ctx->jsonBlockHeader.length The *length parameter is updated to contain the required buffer size No data is copied to the buffer The caller should allocate a larger buffer and call again

Note
  Aaru JSON Format and Encoding:
  - The JSON payload is stored in UTF-8 encoding
  - The payload may or may not be null-terminated
  - The library treats the JSON as opaque binary data
  - No JSON parsing, interpretation, or validation is performed by libaaruformat
  - JSON schema validation and parsing are the caller's responsibility
  Aaru Metadata JSON Purpose:
  - Provides machine-readable structured metadata using modern JSON format
  - Includes comprehensive information about media, sessions, tracks, and checksums
  - Enables programmatic access to metadata without XML parsing overhead
  - Documents imaging session details, hardware configuration, and preservation data
  - Used by Aaru and compatible tools for metadata exchange and analysis
  - Complements or serves as alternative to CICM XML metadata
  Buffer Size Handling:
  - First call with insufficient buffer returns required size in *length
  - Caller allocates properly sized buffer based on returned length
  - Second call with adequate buffer retrieves the actual JSON data
  - Single call succeeds if buffer is already large enough
  Data Availability:
  - Aaru JSON blocks are optional in AaruFormat images
  - Not all images will contain Aaru metadata JSON
  - The presence of JSON data depends on how the image was created
  - Check return value to handle missing metadata gracefully
  - Images may contain CICM XML, Aaru JSON, both, or neither
  Distinction from CICM XML:
  - CICM XML follows the Canary Islands Computer Museum schema (older format)
  - Aaru JSON follows the Aaru-specific metadata schema (newer format)
  - Both can coexist in the same image file
  - Aaru JSON may provide more detailed or different metadata than CICM XML
  - Different tools and workflows may prefer one format over the other

Warning
  This function reads from the in-memory Aaru JSON block loaded during aaruf_open(). It does not perform file I/O operations. The entire JSON is kept in memory for the lifetime of the context.
  The buffer parameter must be valid and large enough to hold the JSON data. Passing a buffer smaller than the required size will result in AARUF_ERROR_BUFFER_TOO_SMALL with no partial data copied.
  This function does not validate JSON syntax or schema. Corrupted JSON data will be retrieved successfully and errors will only be detected when attempting to parse.

See also
  AaruMetadataJsonBlockHeader for the on-disk structure definition.
  aaruf_get_cicm_metadata() for retrieving CICM XML metadata.
  process_aaru_metadata_json_block() for the loading process during image opening.

Definition at line 2102 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_CANNOT_READ_BLOCK, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, AaruMetadataJsonBlock, FATAL, AaruMetadataJsonBlockHeader::identifier, aaruformat_context::json_block, aaruformat_context::json_block_header, AaruMetadataJsonBlockHeader::length, aaruformat_context::magic, and TRACE.

## ◆ aaruf_get_all_tape_files()

int32_t aaruf_get_all_tape_files | ( | const void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieves all tape file entries from the image.

Extracts the complete set of tape file metadata entries from an Aaru tape image, returning an array of TapeFileEntry structures. Tape files represent logical file divisions on sequential access media (magnetic tapes) where data is organized into numbered files within numbered partitions. Each file entry defines a contiguous range of tape blocks (FirstBlock to LastBlock inclusive) that comprise one logical file unit on the tape medium.

Tape file organization is hierarchical:

- Partition: Physical or logical division of the tape (0-255)
- File: Numbered file within a partition (0-4,294,967,295)
- Block Range: Contiguous sequence of tape blocks containing the file data

This function is essential for applications that need to:

- Enumerate all logical files stored on a tape image
- Build file system catalogs or directory structures for tape media
- Implement tape navigation and seeking operations
- Extract individual files from multi-file tape archives
- Verify tape image completeness and structure
- Generate tape content manifests for archival documentation

The function supports a two-call pattern for buffer size determination:

1. First call with NULL buffer or insufficient length returns AARUF_ERROR_BUFFER_TOO_SMALL and sets *length to the required size (entry_count × sizeof(TapeFileEntry))
2. Second call with properly sized buffer retrieves all file entries

Alternatively, if the caller knows or pre-allocates sufficient buffer space, a single call will succeed and populate the buffer with all tape file entries.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened tape image context).
  buffer | Pointer to a buffer that will receive the array of TapeFileEntry structures. May be NULL to query the required buffer size without retrieving data.
  length | Pointer to a size_t that serves dual purpose: On input: size of the provided buffer in bytes (ignored if buffer is NULL) On output: actual size required/used for all entries in bytes

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved all tape file entries.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_ERROR_TAPE_FILE_NOT_FOUND | (-19) No tape file metadata exists.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-12) The provided buffer is insufficient.

See also
  aaruf_get_tape_file() to retrieve a specific file's block range
  aaruf_set_tape_file() to define or update a tape file entry
  aaruf_get_all_tape_partitions() to retrieve partition boundaries

Definition at line 1314 of file tape.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_TAPE_FILE_NOT_FOUND, AARUF_STATUS_OK, FATAL, TapeFileHashEntry::fileEntry, aaruformat_context::magic, aaruformat_context::tape_files, and TRACE.

## ◆ aaruf_get_all_tape_partitions()

int32_t aaruf_get_all_tape_partitions | ( | const void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieves all tape partition entries from the image.

Extracts the complete set of tape partition metadata entries from an Aaru tape image, returning an array of TapePartitionEntry structures. Tape partitions represent physical or logical divisions of sequential access media (magnetic tapes) that segment the tape into independent data regions. Each partition entry defines a contiguous range of tape blocks (FirstBlock to LastBlock inclusive) that comprise one partition on the tape medium.

Tape partitions enable:

- Multi-partition tapes: Modern tape formats (LTO-5+, SDLT) support multiple partitions
- Data organization: Separating metadata, indexes, and data into distinct partitions
- Fast access: Partition switching is faster than sequential seeking across the entire tape
- Logical separation: Isolating different data sets or file systems on the same tape

This function is essential for applications that need to:

- Enumerate all partitions on a multi-partition tape image
- Determine partition boundaries and sizes for navigation
- Implement partition-aware file system drivers or extraction tools
- Validate tape structure and partition layout integrity
- Generate tape structure documentation for archival purposes

The function supports a two-call pattern for buffer size determination:

1. First call with NULL buffer or insufficient length returns AARUF_ERROR_BUFFER_TOO_SMALL and sets *length to the required size (partition_count × sizeof(TapePartitionEntry))
2. Second call with properly sized buffer retrieves all partition entries

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened tape image context).
  buffer | Pointer to a buffer that will receive the array of TapePartitionEntry structures. May be NULL to query the required buffer size without retrieving data.
  length | Pointer to a size_t that serves dual purpose: On input: size of the provided buffer in bytes (ignored if buffer is NULL) On output: actual size required/used for all entries in bytes

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved all tape partition entries.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid.
  AARUF_ERROR_TAPE_PARTITION_NOT_FOUND | (-20) No tape partition metadata exists.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-12) The provided buffer is insufficient.

See also
  aaruf_get_tape_partition() to retrieve a specific partition's block range
  aaruf_set_tape_partition() to define or update a tape partition entry
  aaruf_get_all_tape_files() to retrieve all tape file entries

Definition at line 1416 of file tape.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_TAPE_PARTITION_NOT_FOUND, AARUF_STATUS_OK, FATAL, aaruformat_context::magic, TapePartitionHashEntry::partitionEntry, aaruformat_context::tape_partitions, and TRACE.

## ◆ aaruf_get_cicm_metadata()

int32_t aaruf_get_cicm_metadata | ( | const void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieves the embedded CICM XML metadata sidecar from the image.

CICM (Canary Islands Computer Museum) XML is a standardized metadata format used for documenting preservation and archival information about media and disk images. This function extracts the raw CICM XML payload that was embedded in the AaruFormat image during creation. The XML data is preserved in its original form without parsing, interpretation, or validation by the library. The metadata typically includes detailed information about the physical media, imaging process, checksums, device information, and preservation metadata following the CICM schema.

This function supports a two-call pattern for buffer size determination:

1. First call with a buffer that may be too small returns AARUF_ERROR_BUFFER_TOO_SMALL and sets *length to the required size
2. Second call with a properly sized buffer retrieves the actual data

Alternatively, if the caller already knows the buffer is large enough, a single call will succeed and populate the buffer with the CICM XML data.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened image context).
  buffer | Pointer to a buffer that will receive the CICM XML metadata. Must be large enough to hold the entire XML payload (at least *length bytes on input). The buffer will contain raw UTF-8 encoded XML data on success.
  length | Pointer to a size_t that serves dual purpose: On input: size of the provided buffer in bytes On output: actual size of the CICM XML metadata in bytes If the function returns AARUF_ERROR_BUFFER_TOO_SMALL, this will be updated to contain the required buffer size for a subsequent successful call.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved CICM XML metadata. This is returned when: The context is valid and properly initialized The CICM block is present in the image (identifier == CicmBlock) The provided buffer is large enough (>= required length) The CICM XML data is successfully copied to the buffer The *length parameter is set to the actual size of the XML data
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()
  AARUF_ERROR_CANNOT_READ_BLOCK | (-7) The CICM block is not present. This occurs when: The image was created without CICM XML metadata ctx->cicmBlock is NULL (no data loaded) ctx->cicmBlockHeader.length is 0 (empty metadata) ctx->cicmBlockHeader.identifier doesn't equal CicmBlock The CICM block was not found during image opening The *length output parameter is set to 0 to indicate no data available
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer is insufficient. This occurs when: The input *length is less than ctx->cicmBlockHeader.length The *length parameter is updated to contain the required buffer size No data is copied to the buffer The caller should allocate a larger buffer and call again

Note
  CICM XML Format:
  - The XML is stored in UTF-8 encoding
  - The payload may or may not be null-terminated
  - The library treats the XML as opaque binary data
  - No XML parsing, interpretation, or validation is performed by libaaruformat
  - Schema validation and XML processing are the caller's responsibility
  CICM Metadata Purpose:
  - Developed by the Canary Islands Computer Museum for digital preservation
  - Documents comprehensive preservation metadata
  - Includes checksums for data integrity verification
  - Records detailed device and media information
  - Supports archival and long-term preservation requirements
  - Provides standardized metadata for digital preservation workflows
  - Used by cultural heritage institutions and archives
  Buffer Size Handling:
  - First call with insufficient buffer returns required size in *length
  - Caller allocates properly sized buffer based on returned length
  - Second call with adequate buffer retrieves the actual XML data
  - Single call succeeds if buffer is already large enough
  Data Availability:
  - CICM blocks are optional in AaruFormat images
  - Not all images will contain CICM metadata
  - The presence of CICM data depends on how the image was created
  - Check return value to handle missing metadata gracefully

Warning
  The XML data may contain sensitive information about the imaging environment, personnel, locations, or media content. Handle appropriately for your use case.
  This function reads from the in-memory CICM block loaded during aaruf_open(). It does not perform file I/O operations. The entire CICM XML is kept in memory for the lifetime of the context.
  The buffer parameter must be valid and large enough to hold the XML data. Passing a buffer smaller than the required size will result in AARUF_ERROR_BUFFER_TOO_SMALL with no partial data copied.

See also
  CicmMetadataBlock for the on-disk structure definition.
  aaruf_set_cicm_metadata() for embedding CICM XML during image creation.

Definition at line 1947 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_CANNOT_READ_BLOCK, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, aaruformat_context::cicm_block, aaruformat_context::cicm_block_header, CicmBlock, FATAL, CicmMetadataBlock::identifier, CicmMetadataBlock::length, aaruformat_context::magic, and TRACE.

## ◆ aaruf_get_comments()

int32_t aaruf_get_comments | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the user comments or notes stored in the MetadataBlock.

Provides access to the UTF-16LE encoded comments associated with the image. Comments are often used for provenance notes, imaging details, or curator remarks. The function follows the same two-call buffer sizing pattern used by other metadata retrieval APIs: the caller may probe the required size before allocating memory.

Parameters

  context | Pointer to a valid aaruformat context opened with aaruf_open() or aaruf_create().
  buffer | Destination buffer that receives the comments data. May be NULL when probing size.
  length | Pointer to an int32_t. On input it contains the size of `buffer` in bytes; on output it is updated with the actual comments length.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Comments were available and copied successfully.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid or not a libaaruformat context.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No comments metadata exists in the image.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The supplied buffer was too small. *length is updated with the required size and no data is copied.

Note
  Comments are stored exactly as provided during image creation and may include multi-line text or other control characters. No validation or normalization is applied by the library.

Definition at line 2479 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, aaruformat_context::comments, MetadataBlockHeader::commentsLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_creator()

int32_t aaruf_get_creator | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the recorded creator (operator) name from the MetadataBlock.

Copies the UTF-16LE encoded creator string that identifies the person or operator who created the image. The function supports the common two-call pattern: the caller first determines the required buffer size by passing a buffer that may be NULL or too small, then allocates sufficient memory and calls again to obtain the actual data. On success the buffer contains an opaque UTF-16LE string of length *length bytes (not null-terminated).

Parameters

  context | Pointer to a valid aaruformat context opened for reading or writing.
  buffer | Pointer to the destination buffer that will receive the creator string. May be NULL to query the required size.
  length | Pointer to an int32_t that on input specifies the size of `buffer` in bytes and on output receives the actual length of the creator metadata.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) The creator string was copied successfully.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is NULL or not an aaruformat context.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) Creator metadata has not been recorded in the image.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer was insufficient; *length contains the required size and no data was copied.

Note
  The returned data is UTF-16LE encoded and may contain embedded null characters. Callers should treat it as an opaque byte array unless they explicitly handle UTF-16LE strings.
  The function does not allocate memory. Callers are responsible for ensuring `buffer` is large enough before requesting the data.

Definition at line 2407 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, aaruformat_context::creator, MetadataBlockHeader::creatorLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_datatype_for_media_tag_type()

int32_t aaruf_get_datatype_for_media_tag_type | ( | const int32_t | tag_type | ) |

Converts an Aaru media tag type to an image data type.

Maps the given Aaru media tag type to the corresponding image data type. This is the inverse function of aaruf_get_media_tag_type_for_datatype.

Parameters

  tag_type | Aaru media tag type identifier.

Returns
  Corresponding image data type, or -1 if not found.

Definition at line 197 of file helpers.c.

References AACS_CPRM_MKB, AACS_DataKeys, AACS_LBAExtents, AACS_MediaIdentifier, AACS_MKB, AACS_SerialNumber, AACS_VolumeIdentifier, AacsDataKeys, AacsLbaExtents, AacsMediaIdentifier, AacsMediaKeyBlock, AacsSerialNumber, AacsVolumeIdentifier, AARU_CALL, AARU_LOCAL, ATA_IDENTIFY, AtaIdentify, ATAPI_IDENTIFY, AtapiIdentify, BD_BCA, BD_CartridgeStatus, BD_DDS, BD_DI, BD_SpareArea, BlurayBca, BlurayCartridgeStatus, BlurayDds, BlurayDi, BluraySpareArea, CD_ATIP, CD_FirstTrackPregap, CD_FullTOC, CD_LeadIn, CD_LeadOut, CD_MCN, CD_PMA, CD_SessionInfo, CD_TEXT, CD_TOC, CompactDiscAtip, CompactDiscFirstTrackPregap, CompactDiscLeadIn, CompactDiscLeadInCdText, CompactDiscLeadOut, CompactDiscMediaCatalogueNumber, CompactDiscPartialToc, CompactDiscPma, CompactDiscSessionInfo, CompactDiscToc, CprmMediaKeyBlock, DiscControlBlock, DVD_ADIP, DVD_BCA, DVD_CMI, DVD_DiscKey, DVD_DiscKey_Decrypted, DVD_DMI, DVD_MediaIdentifier, DVD_MKB, DVD_PFI, DvdAdip, DvdBca, DvdDiscControlBlock, DvdDiscKey, DvdDiscKeyDecrypted, DVDDL_JumpIntervalSize, DVDDL_LayerCapacity, DVDDL_ManualLayerJumpLBA, DVDDL_MiddleZoneAddress, DvdDlJumpIntervalSize, DvdDlLayerCapacity, DvdDlManualLayerJumpLba, DvdDlMiddleZoneAddress, DvdDmi, DvdLeadInCmi, DvdMediaIdentifier, DvdMediaKeyBlock, DvdPfi, DVDR_MediaIdentifier, DVDR_PFI, DVDR_PreRecordedInfo, DVDR_RMD, DVDRAM_DDS, DVDRAM_MediumStatus, DVDRAM_SpareArea, DvdRamDds, DvdRamMediumStatus, DvdRamSpareArea, DvdRMediaIdentifier, DvdRPfi, DvdRPrerecordedInfo, DvdRRmd, Floppy_LeadOut, FloppyLeadOut, HDDVD_CPI, HDDVD_MediumStatus, HdDvdCpi, HdDvdMediumStatus, Hybrid_RecognizedLayers, HybridRecognizedLayers, MMC_CID, MMC_CSD, MMC_DiscInformation, MMC_ExtendedCSD, MMC_OCR, MMC_POWResourcesInformation, MMC_TrackResourcesInformation, MMC_WriteProtection, MultiMediaCardCid, MultiMediaCardCsd, MultiMediaCardExtendedCsd, MultiMediaCardOcr, PCMCIA_CIS, PcmciaCis, SCSI_INQUIRY, SCSI_MODEPAGE_2A, SCSI_MODESENSE_10, SCSI_MODESENSE_6, ScsiInquiry, ScsiMmcDiscInformation, ScsiMmcPowResourcesInformation, ScsiMmcTrackResourcesInformation, ScsiMmcWriteProtection, ScsiModePage2A, ScsiModeSense10, ScsiModeSense6, SD_CID, SD_CSD, SD_OCR, SD_SCR, SecureDigitalCid, SecureDigitalCsd, SecureDigitalOcr, SecureDigitalScr, USB_Descriptors, UsbDescriptors, Xbox_DMI, Xbox_PFI, Xbox_SecuritySector, XboxDmi, XboxPfi, and XboxSecuritySector.

Referenced by write_media_tags().

## ◆ aaruf_get_drive_firmware_revision()

int32_t aaruf_get_drive_firmware_revision | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the firmware revision metadata for the imaging drive.

Returns the UTF-16LE encoded firmware revision string that was captured when the image was created. Firmware information is critical for reproducing imaging environments and diagnosing drive-specific behavior or bugs.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Destination buffer for the firmware revision string. May be NULL when probing size.
  length | Pointer to an int32_t that specifies the buffer capacity in bytes on input and is updated with the actual metadata length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Firmware revision metadata was present and copied successfully.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No firmware metadata exists in the image.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The supplied buffer was too small; *length is updated.

Note
  Firmware revision formats vary between manufacturers (e.g., numeric, alphanumeric, dot-separated). The library stores the data verbatim without attempting normalization.

Definition at line 3181 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, aaruformat_context::drive_firmware_revision, MetadataBlockHeader::driveFirmwareRevisionLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_drive_manufacturer()

int32_t aaruf_get_drive_manufacturer | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the drive manufacturer metadata captured during imaging.

Copies the UTF-16LE encoded manufacturer name of the device used to read or write the medium. This information documents the hardware involved in the imaging process, which is crucial for forensic reporting and reproducibility studies.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Destination buffer for the manufacturer string. May be NULL when querying required length.
  length | Pointer to an int32_t specifying the buffer size on input and receiving the actual metadata length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Drive manufacturer metadata was copied successfully.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) The image lacks drive manufacturer metadata.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer is too small; *length holds the required size for a subsequent call.

Note
  The returned manufacturer string corresponds to the value recorded by aaruf_set_drive_manufacturer() and may include branding or OEM designations.

Definition at line 2971 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, aaruformat_context::drive_manufacturer, MetadataBlockHeader::driveManufacturerLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_drive_model()

int32_t aaruf_get_drive_model | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the device model information for the imaging drive.

Returns the UTF-16LE encoded model identifier for the drive used during acquisition. The model metadata provides finer granularity than the manufacturer name, enabling detailed documentation of imaging hardware capabilities and behavior.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Buffer that receives the model string; may be NULL while probing required capacity.
  length | Pointer to an int32_t indicating buffer size on input and receiving the metadata length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Drive model metadata was available and copied.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No drive model metadata exists in the image.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The supplied buffer was insufficient; *length is updated.

Note
  Model strings can include firmware suffixes, interface hints, or OEM variations. Consume the data verbatim to maintain accurate provenance records.

Definition at line 3041 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, aaruformat_context::drive_model, MetadataBlockHeader::driveModelLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_drive_serial_number()

int32_t aaruf_get_drive_serial_number | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the imaging drive's serial number metadata.

Copies the UTF-16LE encoded serial number reported for the drive used during the imaging session. This metadata enables correlation between images and specific hardware units for forensic chain of custody or quality assurance workflows.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Destination buffer for the serial number; may be NULL when querying size.
  length | Pointer to an int32_t carrying the buffer size on input and receiving the actual serial number length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Drive serial number metadata was copied to `buffer`.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No drive serial number metadata is available.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer was insufficient.

Note
  Serial numbers are stored exactly as returned by the imaging hardware and may include leading zeros or spacing that should be preserved.

Definition at line 3111 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, aaruformat_context::drive_serial_number, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_dumphw()

int32_t aaruf_get_dumphw | ( | void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieves the dump hardware block containing acquisition environment information.

Extracts the complete DumpHardwareBlock from the image, which documents the hardware and software environments used to create the image. A dump hardware block records one or more "dump environments" – typically combinations of physical devices (drives, controllers, adapters) and the software stacks that performed the read operations. This metadata is essential for understanding the imaging context, validating acquisition integrity, reproducing imaging conditions, and supporting forensic or archival documentation requirements.

Each environment entry includes hardware identification (manufacturer, model, revision, firmware, serial number), software identification (name, version, operating system), and optional extent ranges that specify which logical sectors or units were contributed by that particular environment. This structure supports complex imaging scenarios where multiple devices or software configurations were used to create a composite image.

The function reconstructs the complete on-disk binary representation of the dump hardware block, including the DumpHardwareHeader followed by all entries with their variable-length UTF-8 strings and extent arrays. The reconstructed block includes a calculated CRC64 checksum over the payload data for integrity verification.

This function supports a two-call pattern for buffer size determination:

1. First call with insufficient buffer (or NULL) returns AARUF_ERROR_BUFFER_TOO_SMALL and sets *length to the required size (sizeof(DumpHardwareHeader) + total payload length)
2. Second call with properly sized buffer retrieves the complete block data

Alternatively, if the caller already knows the buffer is large enough, a single call will succeed and populate the buffer with the complete dump hardware block.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened image context).
  buffer | Pointer to a buffer that will receive the dump hardware block data. Must be large enough to hold the complete block (at least *length bytes on input). May be NULL to query the required buffer size. The buffer will contain the DumpHardwareHeader followed by serialized entries, strings, and extent arrays on success.
  length | Pointer to a size_t that serves dual purpose: On input: size of the provided buffer in bytes (ignored if buffer is NULL) On output: actual size required/used for the dump hardware block in bytes If the function returns AARUF_ERROR_BUFFER_TOO_SMALL, this will be updated to contain the required buffer size for a subsequent successful call.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved dump hardware block. This is returned when: The context is valid and properly initialized The dump hardware block is present (identifier == DumpHardwareBlock) The provided buffer is large enough (>= required length) All hardware entries with their strings and extents are copied to the buffer The DumpHardwareHeader is written with calculated CRC64 at buffer offset 0 The *length parameter is set to the actual block size
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()
  AARUF_ERROR_CANNOT_READ_BLOCK | (-6) The dump hardware block is not present. This occurs when: The image was created without dump hardware information ctx->dumpHardwareEntriesWithData is NULL (no data loaded) ctx->dumpHardwareHeader.entries == 0 (no hardware entries) ctx->dumpHardwareHeader.identifier doesn't equal DumpHardwareBlock The dump hardware block was not found during image opening
  AARUF_ERROR_BUFFER_TOO_SMALL | (-12) The provided buffer is insufficient. This occurs when: buffer is NULL (size query mode) The input *length is less than sizeof(DumpHardwareHeader) + payload length The *length parameter is updated to contain the required buffer size No data is copied to the buffer The caller should allocate a larger buffer and call again Also returned if calculated entry size exceeds buffer during iteration (sanity check)

Note
  Dump Hardware Block Structure:
  - DumpHardwareHeader (16 bytes): identifier, entries count, payload length, CRC64
  - For each entry (variable size):
    - DumpHardwareEntry (36 bytes): length fields for all strings and extent count
    - Variable-length UTF-8 strings (in order): manufacturer, model, revision, firmware, serial, software name, software version, software operating system
    - Array of DumpExtent structures (16 bytes each) if extent count > 0
  - All strings are UTF-8 encoded and NOT null-terminated in the serialized block
  - String lengths are in bytes, not character counts
  Dump Hardware Environments:
  - Each entry represents one hardware/software combination used during imaging
  - Multiple entries support scenarios where different devices contributed different sectors
  - Extent arrays specify which logical sector ranges each environment contributed
  - Empty extent arrays (extents == 0) indicate the environment dumped the entire medium
  - Overlapping extents between entries may indicate verification passes or redundancy
  Hardware Identification Fields:
  - manufacturer: Device manufacturer (e.g., "Plextor", "Sony", "Samsung")
  - model: Device model number (e.g., "PX-716A", "DRU-820A")
  - revision: Hardware revision identifier
  - firmware: Firmware version (e.g., "1.11", "KY08")
  - serial: Device serial number for unique identification
  Software Identification Fields:
  - softwareName: Dumping software name (e.g., "Aaru", "ddrescue", "IsoBuster")
  - softwareVersion: Software version (e.g., "5.3.0", "1.25")
  - softwareOperatingSystem: Host OS (e.g., "Linux 5.10.0", "Windows 10", "macOS 12.0")
  CRC64 Calculation:
  - The function calculates CRC64-ECMA over the payload (everything after the header)
  - The calculated CRC64 is stored in the returned DumpHardwareHeader
  - This allows verification of the serialized block integrity
  - The CRC64 is computed from buffer data, not from the original context
  Buffer Layout After Successful Call:
  - Offset 0: DumpHardwareHeader with calculated CRC64
  - Offset 16: First DumpHardwareEntry
  - Followed by: First entry's UTF-8 strings (in documented order)
  - Followed by: First entry's DumpExtent array (if extents > 0)
  - Repeated for all remaining entries
  Use Cases:
  - Forensic documentation requiring complete equipment chain of custody
  - Archival metadata for long-term preservation requirements
  - Reproducing imaging conditions for verification or re-imaging
  - Identifying firmware-specific issues or drive-specific behaviors
  - Multi-device imaging scenario documentation
  - Correlating imaging artifacts with specific hardware/software combinations

Warning
  This function reads from the in-memory dump hardware data loaded during aaruf_open(). It does not perform file I/O operations. The data is reconstructed from the parsed context structures into the on-disk binary format.
  The buffer must be valid and large enough to hold the entire dump hardware block. Passing a buffer smaller than required will result in AARUF_ERROR_BUFFER_TOO_SMALL.
  String data in the serialized block is NOT null-terminated. Applications parsing the buffer must use the length fields in DumpHardwareEntry to determine string boundaries. The library adds null terminators only for in-memory convenience.
  The function performs bounds checking during serialization. If calculated entry sizes exceed the buffer length, AARUF_ERROR_BUFFER_TOO_SMALL is returned even after the initial size check. This should not occur with properly sized buffers but protects against data corruption.

See also
  DumpHardwareHeader for the block header structure definition.
  DumpHardwareEntry for the per-environment entry structure definition.
  DumpExtent for the extent range structure definition.
  process_dumphw_block() for the loading process during image opening.

Definition at line 186 of file dump.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_crc64_data(), AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_CANNOT_READ_BLOCK, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, DumpHardwareHeader::crc64, aaruformat_context::dump_hardware_entries_with_data, aaruformat_context::dump_hardware_header, DumpHardwareBlock, DumpHardwareHeader::entries, DumpHardwareEntriesWithData::entry, DumpHardwareEntriesWithData::extents, DumpHardwareEntry::extents, FATAL, DumpHardwareEntriesWithData::firmware, DumpHardwareEntry::firmwareLength, DumpHardwareHeader::identifier, DumpHardwareHeader::length, aaruformat_context::magic, DumpHardwareEntriesWithData::manufacturer, DumpHardwareEntry::manufacturerLength, DumpHardwareEntriesWithData::model, DumpHardwareEntry::modelLength, DumpHardwareEntriesWithData::revision, DumpHardwareEntry::revisionLength, DumpHardwareEntriesWithData::serial, DumpHardwareEntry::serialLength, DumpHardwareEntriesWithData::softwareName, DumpHardwareEntry::softwareNameLength, DumpHardwareEntriesWithData::softwareOperatingSystem, DumpHardwareEntry::softwareOperatingSystemLength, DumpHardwareEntriesWithData::softwareVersion, DumpHardwareEntry::softwareVersionLength, and TRACE.

## ◆ aaruf_get_geometry()

int32_t aaruf_get_geometry | ( | const void * | context,
|  | uint32_t * | cylinders,
|  | uint32_t * | heads,
|  | uint32_t * | sectors_per_track )

Retrieves the logical CHS geometry from the AaruFormat image.

Reads the Cylinder-Head-Sector (CHS) geometry information from the image's geometry block and returns the values through output parameters. The geometry block contains legacy-style logical addressing parameters that describe how the storage medium was originally organized in terms of cylinders, heads (tracks per cylinder), and sectors per track. This information is essential for software that requires CHS addressing or for accurately representing the original medium's logical structure.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened image context).
  cylinders | Pointer to store the number of cylinders. Updated on success.
  heads | Pointer to store the number of heads (tracks per cylinder). Updated on success.
  sectors_per_track | Pointer to store the number of sectors per track. Updated on success.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved geometry information. This is returned when: The context is valid and properly initialized The geometry block is present in the image (identifier == GeometryBlock) All three output parameters are successfully populated with geometry values The cylinders parameter contains the total number of cylinders The heads parameter contains the number of heads per cylinder The sectors_per_track parameter contains the number of sectors per track
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()
  AARUF_ERROR_CANNOT_READ_BLOCK | (-7) The geometry block is not present. This occurs when: The image was created without geometry information The geometryBlock.identifier field doesn't equal GeometryBlock The geometry block was not found during image opening The image format doesn't support or require CHS geometry

Note
  Geometry Interpretation:
  - Total logical sectors = cylinders × heads × sectors_per_track
  - Sector size is not included in the geometry block and must be obtained separately (typically 512 bytes for most block devices, but can vary)
  - The geometry represents logical addressing, not necessarily physical medium geometry
  - Modern storage devices often report translated or synthetic geometry values
  CHS Addressing Context:
  - CHS addressing was historically used for hard disk drives and floppy disks
  - Legacy BIOS and older operating systems relied on CHS parameters
  - LBA (Logical Block Addressing) has largely replaced CHS for modern devices
  - Some disk image formats and emulators still require CHS information
  Geometry Block Availability:
  - Not all image types contain geometry blocks
  - Optical media (CDs, DVDs) typically don't have CHS geometry
  - Modern large-capacity drives may not have meaningful CHS values
  - Check the return value to determine if geometry is available
  Parameter Validation:
  - All output parameters must be non-NULL valid pointers
  - The function does not validate the geometry values themselves
  - Geometry values of zero or unusually large values may indicate issues

Warning
  The output parameters are only modified on success (AARUF_STATUS_OK). On error, their values remain unchanged. Initialize them before calling if default values are needed on failure.
  This function reads from the in-memory geometry block loaded during aaruf_open(). It does not perform file I/O operations.
  Geometry values may not accurately represent physical device geometry, especially for modern drives with zone-based recording or flash storage.

Definition at line 94 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_CANNOT_READ_BLOCK, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, GeometryBlockHeader::cylinders, FATAL, aaruformat_context::geometry_block, GeometryBlock, GeometryBlockHeader::heads, GeometryBlockHeader::identifier, aaruformat_context::magic, GeometryBlockHeader::sectorsPerTrack, and TRACE.

## ◆ aaruf_get_image_info()

int32_t aaruf_get_image_info | ( | const void * | context,
|  | ImageInfo * | image_info )

Retrieves a deep copy of the ImageInfo structure from the AaruFormat image.

Returns a complete copy of the high-level image information summary containing metadata such as image size, sector count, sector size, version information, creation timestamps, and media type. This function performs a deep copy of all fields including string buffers, ensuring the caller receives a complete, independent copy of the image information.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened image context).
  image_info | Pointer to an ImageInfo structure to receive the copied data. Must be a valid pointer to allocated memory.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully copied image info. The image_info parameter contains a complete copy of all fields including: HasPartitions: Whether image contains partitions/tracks HasSessions: Whether image contains multiple sessions ImageSize: Size of image payload in bytes Sectors: Total count of addressable sectors/blocks SectorSize: Size of each logical sector in bytes Version: Image format version string (NUL-terminated) Application: Creating application name (NUL-terminated) ApplicationVersion: Application version string (NUL-terminated) CreationTime: Image creation timestamp (Windows FILETIME) LastModificationTime: Last modification timestamp (Windows FILETIME) MediaType: Media type identifier MetadataMediaType: Media type for sidecar generation
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC The context was not properly initialized

Note
  The ImageInfo structure contains fixed-size character arrays that are properly NUL-terminated, making it safe to use as C strings.
  This function performs a complete deep copy using memcpy, copying all fields including strings, integers, and timestamps.
  The caller is responsible for allocating the ImageInfo structure before calling this function. The structure is not dynamically allocated by this function.

Warning
  The image_info parameter must point to valid, allocated memory of at least sizeof(ImageInfo) bytes. Passing NULL or invalid pointers will result in undefined behavior.
  This function reads from the in-memory image_info loaded during aaruf_open() or populated during aaruf_create(). It does not perform file I/O operations.

Definition at line 3637 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, aaruformat_context::image_info, aaruformat_context::magic, and TRACE.

## ◆ aaruf_get_media_barcode()

int32_t aaruf_get_media_barcode | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the barcode assigned to the physical media or its packaging.

Returns the UTF-16LE encoded barcode string that was captured when the image was created. Barcodes are commonly used in institutional workflows for inventory tracking and automated retrieval.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Buffer that receives the barcode string; may be NULL when probing size requirements.
  length | Pointer to an int32_t specifying the buffer size on input and receiving the actual barcode length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Barcode metadata was present and copied successfully.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No barcode metadata exists in the image.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The supplied buffer was too small.

Note
  Barcode values can be strict alphanumeric codes (e.g., LTO cartridge IDs) or full strings from custom labeling systems. Preserve the returned string exactly for catalog interoperability.

Definition at line 2828 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::media_barcode, MetadataBlockHeader::mediaBarcodeLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_media_manufacturer()

int32_t aaruf_get_media_manufacturer | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the recorded media manufacturer name.

Provides access to the UTF-16LE encoded manufacturer metadata that identifies the company which produced the physical medium. This information is taken from the MetadataBlock and mirrors the value previously stored via aaruf_set_media_manufacturer().

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Buffer that receives the manufacturer string. May be NULL when probing size.
  length | Pointer to an int32_t specifying the buffer size on input and receiving the actual manufacturer string length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Manufacturer metadata was available and copied.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) The image lacks manufacturer metadata.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer was too small; *length indicates size.

Note
  Values may include trailing spaces or vendor-specific capitalization. Treat the returned data as authoritative and avoid trimming unless required by the consuming application.

Definition at line 2619 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::media_manufacturer, MetadataBlockHeader::mediaManufacturerLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_media_model()

int32_t aaruf_get_media_model | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the media model or product designation metadata.

Returns the UTF-16LE encoded model name that specifies the exact product variant of the physical medium. The function mirrors the set counterpart and is useful for accurately documenting media specifications during preservation workflows.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Destination buffer for the model string; may be NULL when querying required size.
  length | Pointer to an int32_t that on input contains the buffer capacity in bytes and on output is updated with the actual metadata length.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Model metadata was successfully copied.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No media model metadata is present in the image.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The caller-provided buffer is too small.

Note
  Model strings often contain performance ratings (e.g., "16x", "LTO-7"). The data is opaque and should be handled without modification unless necessary.

Definition at line 2689 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::media_model, MetadataBlockHeader::mediaModelLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_media_part_number()

int32_t aaruf_get_media_part_number | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the media part number recorded in the MetadataBlock.

Provides access to the UTF-16LE encoded part number identifying the precise catalog or ordering code for the physical medium. Part numbers help archivists procure exact replacements and document specific media variants used during acquisition.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Destination buffer for the part number string. May be NULL while querying size.
  length | Pointer to an int32_t that supplies the buffer size on input and is updated with the actual part number length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Part number metadata was returned successfully.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No part number metadata exists.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer was insufficient; *length contains the required size.

Note
  Part numbers may include manufacturer-specific formatting such as hyphens or suffix letters. The library stores and returns the data verbatim.

Definition at line 2899 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::media_part_number, MetadataBlockHeader::mediaPartNumberLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_media_sequence()

int32_t aaruf_get_media_sequence | ( | const void * | context,
|  | int32_t * | sequence,
|  | int32_t * | last_sequence )

Retrieves the media sequence metadata for multi-volume image sets.

Reads the media sequence fields stored in the MetadataBlock header and returns the current media number together with the final media number for the complete set. This information indicates the position of the imaged medium within a multi-volume collection (for example, "disc 2 of 5"). The function operates entirely on in-memory structures populated during aaruf_open(); no additional disk I/O is performed.

Parameters

  context | Pointer to an initialized aaruformat context opened for reading or writing.
  sequence | Pointer that receives the current media sequence number (typically 1-based).
  last_sequence | Pointer that receives the total number of media in the set.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Metadata was present and the output parameters were populated.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The provided context pointer is NULL or not an aaruformat context (magic mismatch).
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) The MetadataBlock was not present in the image, making sequence data unavailable.

Note
  For standalone media, both sequence and last_sequence are commonly set to 1. Some creators may also set them to 0 to indicate the absence of sequence semantics; callers should handle either pattern gracefully.
  The function does not validate logical consistency (e.g., whether sequence <= last_sequence); it simply returns the values stored in the image header.

Definition at line 2340 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaSequence, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_media_serial_number()

int32_t aaruf_get_media_serial_number | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the media serial number recorded in the image metadata.

Copies the UTF-16LE encoded serial number identifying the specific physical medium. Serial numbers are particularly important for forensic tracking and archival provenance, enabling correlation between the physical item and its digital representation.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Destination buffer for the serial number. May be NULL to determine required size.
  length | Pointer to an int32_t that on input holds the buffer size and on output receives the actual serial number length.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Serial number metadata was copied into `buffer`.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No serial number metadata was stored in the image.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer was too small.

Note
  Serial numbers may contain spaces, hyphens, or alphanumeric characters. The library does not normalize or validate these strings.

Definition at line 2759 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::media_serial_number, MetadataBlockHeader::mediaSerialNumberLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_media_tag_type_for_datatype()

int32_t aaruf_get_media_tag_type_for_datatype | ( | const int32_t | type | ) |

Converts an image data type to an Aaru media tag type.

Maps the given image data type to the corresponding Aaru media tag type.

Parameters

  type | Image data type identifier.

Returns
  Corresponding Aaru media tag type, or -1 if not found.

Definition at line 39 of file helpers.c.

References AACS_CPRM_MKB, AACS_DataKeys, AACS_LBAExtents, AACS_MediaIdentifier, AACS_MKB, AACS_SerialNumber, AACS_VolumeIdentifier, AacsDataKeys, AacsLbaExtents, AacsMediaIdentifier, AacsMediaKeyBlock, AacsSerialNumber, AacsVolumeIdentifier, AARU_CALL, AARU_LOCAL, ATA_IDENTIFY, AtaIdentify, ATAPI_IDENTIFY, AtapiIdentify, BD_BCA, BD_CartridgeStatus, BD_DDS, BD_DI, BD_SpareArea, BlurayBca, BlurayCartridgeStatus, BlurayDds, BlurayDi, BluraySpareArea, CD_ATIP, CD_FirstTrackPregap, CD_FullTOC, CD_LeadIn, CD_LeadOut, CD_MCN, CD_PMA, CD_SessionInfo, CD_TEXT, CD_TOC, CompactDiscAtip, CompactDiscFirstTrackPregap, CompactDiscLeadIn, CompactDiscLeadInCdText, CompactDiscLeadOut, CompactDiscMediaCatalogueNumber, CompactDiscPartialToc, CompactDiscPma, CompactDiscSessionInfo, CompactDiscToc, CprmMediaKeyBlock, DiscControlBlock, DVD_ADIP, DVD_BCA, DVD_CMI, DVD_DiscKey, DVD_DiscKey_Decrypted, DVD_DMI, DVD_MediaIdentifier, DVD_MKB, DVD_PFI, DvdAdip, DvdBca, DvdDiscControlBlock, DvdDiscKey, DvdDiscKeyDecrypted, DVDDL_JumpIntervalSize, DVDDL_LayerCapacity, DVDDL_ManualLayerJumpLBA, DVDDL_MiddleZoneAddress, DvdDlJumpIntervalSize, DvdDlLayerCapacity, DvdDlManualLayerJumpLba, DvdDlMiddleZoneAddress, DvdDmi, DvdLeadInCmi, DvdMediaIdentifier, DvdMediaKeyBlock, DvdPfi, DVDR_MediaIdentifier, DVDR_PFI, DVDR_PreRecordedInfo, DVDR_RMD, DVDRAM_DDS, DVDRAM_MediumStatus, DVDRAM_SpareArea, DvdRamDds, DvdRamMediumStatus, DvdRamSpareArea, DvdRMediaIdentifier, DvdRPfi, DvdRPrerecordedInfo, DvdRRmd, Floppy_LeadOut, FloppyLeadOut, HDDVD_CPI, HDDVD_MediumStatus, HdDvdCpi, HdDvdMediumStatus, Hybrid_RecognizedLayers, HybridRecognizedLayers, MMC_CID, MMC_CSD, MMC_DiscInformation, MMC_ExtendedCSD, MMC_OCR, MMC_POWResourcesInformation, MMC_TrackResourcesInformation, MMC_WriteProtection, MultiMediaCardCid, MultiMediaCardCsd, MultiMediaCardExtendedCsd, MultiMediaCardOcr, PCMCIA_CIS, PcmciaCis, SCSI_INQUIRY, SCSI_MODEPAGE_2A, SCSI_MODESENSE_10, SCSI_MODESENSE_6, ScsiInquiry, ScsiMmcDiscInformation, ScsiMmcPowResourcesInformation, ScsiMmcTrackResourcesInformation, ScsiMmcWriteProtection, ScsiModePage2A, ScsiModeSense10, ScsiModeSense6, SD_CID, SD_CSD, SD_OCR, SD_SCR, SecureDigitalCid, SecureDigitalCsd, SecureDigitalOcr, SecureDigitalScr, USB_Descriptors, UsbDescriptors, Xbox_DMI, Xbox_PFI, Xbox_SecuritySector, XboxDmi, XboxPfi, and XboxSecuritySector.

Referenced by process_data_block().

## ◆ aaruf_get_media_title()

int32_t aaruf_get_media_title | ( | const void * | context,
|  | uint8_t * | buffer,
|  | int32_t * | length )

Retrieves the media title or label captured during image creation.

Returns the UTF-16LE encoded media title string, representing markings or labels present on the original physical media. This function allows applications to present or archive the media title alongside the image, preserving contextual information from the physical artifact.

Parameters

  context | Pointer to a valid aaruformat context.
  buffer | Destination buffer for the UTF-16LE title string. May be NULL when querying size.
  length | Pointer to an int32_t that on input holds the buffer capacity in bytes and on output receives the actual title length.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) The media title was available and copied to `buffer`.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context pointer is invalid.
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) No media title metadata exists.
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The supplied buffer was insufficient.

Note
  Titles may contain international characters, control codes, or mixed casing. The library does not attempt to sanitize or interpret the string.

Definition at line 2549 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::magic, aaruformat_context::media_title, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_get_negative_sectors()

int32_t aaruf_get_negative_sectors | ( | const void * | context,
|  | uint16_t * | sectors )

Retrieves the number of negative (pre-gap) sectors in the AaruFormat image.

Returns the count of negative sectors that precede the standard user data area. Negative sectors are used to capture pre-gap data, lead-in areas, and other metadata that exists before the main user-accessible storage region. This is particularly important for optical media (CD, DVD, BD) where the lead-in contains the Table of Contents (TOC) and other essential disc structures, and for audio CDs where pre-gap sectors contain silence or hidden tracks. For most hard disk and floppy disk images, this value is typically zero.

Parameters

  context | Pointer to a valid aaruformat context (must be properly initialized).
  sectors | Pointer to a uint16_t that receives the negative sector count on success.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved the negative sector count. This is returned when: The context is valid and properly initialized The context magic number matches AARU_MAGIC The sectors parameter is successfully populated with the negative sector count The value is taken from ctx->user_data_ddt_header.negative For optical media with lead-in data: sectors may be non-zero For standard hard disk/floppy images: sectors is typically 0 Maximum value is 65,535 (uint16_t limit)
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()

Note
  Negative Sector Addressing:
  - Negative sectors are addressed with the 'negative' flag set to true
  - Sector addresses range from 0 to (negative_sectors - 1)
  - When calling aaruf_read_sector() or aaruf_write_sector():
    - Use negative=true
    - Use sector_address in range [0, negative_sectors - 1]
    - The actual logical position is before the user data area
  Optical Media Context:
  - CD-ROM/CD-DA: Negative sectors contain lead-in area with TOC (Table of Contents). The lead-in typically spans LBA -450000 to -1, though only a portion may be captured. Pre-gap sectors (usually 150 sectors/2 seconds before each track) may also be stored as negative sectors for the first track.
  - DVD: May contain lead-in with disc structure information, copyright data, and region codes. The lead-in area varies by format (DVD-ROM, DVD-R, DVD+R, etc.).
  - Blu-ray: Lead-in contains disc information, burst cutting area (BCA), and other metadata. The structure differs between BD-ROM, BD-R, and BD-RE.
  Hard Disk and Floppy Context:
  - Hard disk drives: Negative sectors are typically zero unless capturing special manufacturer reserved areas (HPA, DCO) that precede the standard user area.
  - Floppy disks: Negative sectors are typically zero as floppies have a simple linear sector layout without lead-in areas.
  Audio CD Hidden Tracks:
  - Some audio CDs contain hidden tracks in the pre-gap of the first track
  - These pre-gap sectors can extend up to several minutes before track 1
  - Negative sectors can capture this "hidden" audio data
  - The pre-gap for track 1 typically starts at LBA -150 (2 seconds)
  DDT Header Source:
  - The value is retrieved from ctx->user_data_ddt_header.negative
  - The DDT (Deduplication and Data Table) header tracks all sector allocation
  - This field is populated during image creation with aaruf_create()
  - The value is fixed for read-only images opened with aaruf_open()
  - Maximum representable value is 65,535 (uint16_t)
  Total Addressable Space:
  - Total sectors = negative_sectors + user_sectors + overflow_sectors
  - The negative region comes first in logical order
  - Followed by the user region [0, user_sectors - 1]
  - Followed by the overflow region if present
  Relationship to Image Creation:
  - The negative_sectors value is specified when calling aaruf_create()
  - It should be set based on the medium type and imaging requirements:
    - Optical discs: Set to the number of lead-in sectors captured
    - Hard disks: Typically 0, unless capturing HPA/DCO areas
    - Floppy disks: Typically 0
    - Audio CDs: May be non-zero to capture pre-gap hidden tracks

Warning
  The sectors parameter is only modified on success (AARUF_STATUS_OK). On error, its value remains unchanged. Initialize it before calling if a default value is needed on failure.
  This function reads from the in-memory DDT header loaded during aaruf_open() or set during aaruf_create(). It does not perform file I/O operations and executes quickly.
  The maximum negative sector count is 65,535 due to the uint16_t storage type. If imaging optical media with larger lead-in areas, some data may not be representable. This limit is generally sufficient for most practical cases.
  Negative sector data may contain copy-protected or encrypted content (e.g., CSS on DVDs, AACS on Blu-rays). Handle this data according to applicable laws and licensing agreements.

Definition at line 3420 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, aaruformat_context::magic, DdtHeader2::negative, TRACE, and aaruformat_context::user_data_ddt_header.

## ◆ aaruf_get_overflow_sectors()

int32_t aaruf_get_overflow_sectors | ( | const void * | context,
|  | uint16_t * | sectors )

Retrieves the number of overflow (post-gap) sectors in the AaruFormat image.

Returns the count of overflow sectors that follow the standard user data area. Overflow sectors are used to capture post-gap data, lead-out areas, and other metadata that exists after the main user-accessible storage region. This is particularly important for optical media (CD, DVD, BD) where the lead-out marks the physical end of the recorded data and contains disc finalization information, and for multi-session discs where gaps between sessions need to be preserved. For most hard disk and floppy disk images, this value is typically zero.

Parameters

  context | Pointer to a valid aaruformat context (must be properly initialized).
  sectors | Pointer to a uint16_t that receives the overflow sector count on success.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved the overflow sector count. This is returned when: The context is valid and properly initialized The context magic number matches AARU_MAGIC The sectors parameter is successfully populated with the overflow sector count The value is taken from ctx->user_data_ddt_header.overflow For optical media with lead-out data: sectors may be non-zero For standard hard disk/floppy images: sectors is typically 0 Maximum value is 65,535 (uint16_t limit)
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()

Note
  Overflow Sector Addressing:
  - Overflow sectors are addressed with the 'negative' flag set to false
  - Sector addresses range from user_sectors to (user_sectors + overflow_sectors - 1)
  - When calling aaruf_read_sector() or aaruf_write_sector():
    - Use negative=false
    - Use sector_address in range [user_sectors, user_sectors + overflow_sectors - 1]
    - The actual logical position is after the user data area
  Optical Media Context:
  - CD-ROM/CD-DA: Overflow sectors contain the lead-out area, which marks the physical end of the disc's recorded data. The lead-out consists of unreadable sectors filled with specific patterns.
  - DVD: May contain lead-out with disc finalization data, middle area (for dual-layer), and outer zone. DVD+R/RW discs may have substantial lead-out areas.
  - Blu-ray: Lead-out contains disc finalization markers and padding. For multi-layer discs, may include middle zones and outer areas.
  Multi-Session and Track Context:
  - Multi-session optical discs have gaps between sessions
  - Audio CDs with post-gap after the last track may use overflow sectors
  - Track post-gaps (silence after audio tracks) typically 2 seconds/150 sectors
  Hard Disk and Floppy Context:
  - Hard disk drives: Overflow sectors are typically zero unless capturing special manufacturer reserved areas (like DCO or HPA) that follow the standard user area.
  - Floppy disks: Overflow sectors are typically zero as floppies have a simple linear sector layout without lead-out areas. They may contain mastering information.
  - Some proprietary copy protection schemes may place data beyond the normal capacity, which could be captured as overflow sectors.
  DDT Header Source:
  - The value is retrieved from ctx->user_data_ddt_header.overflow
  - The DDT (Deduplication and Data Table) header tracks all sector allocation
  - This field is populated during image creation with aaruf_create()
  - The value is fixed for read-only images opened with aaruf_open()
  - Maximum representable value is 65,535 (uint16_t)
  Total Addressable Space:
  - Total sectors = negative_sectors + user_sectors + overflow_sectors
  - The negative region comes first in logical order
  - Followed by the user region [0, user_sectors - 1]
  - Followed by the overflow region at the end
  - Overflow represents the final addressable range in the image
  Relationship to Image Creation:
  - The overflow_sectors value is specified when calling aaruf_create()
  - It should be set based on the medium type and imaging requirements:
    - Optical discs: Set to the number of lead-out sectors captured
    - Multi-session discs: May include inter-session gaps
    - Hard disks: Typically 0, unless capturing post-user reserved areas
    - Floppy disks: Typically 0
    - Copy-protected media: May be non-zero to capture protection schemes
  Forensic Imaging Considerations:
  - Some copy protection schemes intentionally place data in overflow regions
  - These "overburn" areas extend beyond the disc's rated capacity
  - Overflow sectors ensure complete forensic capture of all readable data
  - Important for authenticity verification and copy protection analysis

Warning
  The sectors parameter is only modified on success (AARUF_STATUS_OK). On error, its value remains unchanged. Initialize it before calling if a default value is needed on failure.
  This function reads from the in-memory DDT header loaded during aaruf_open() or set during aaruf_create(). It does not perform file I/O operations and executes quickly.
  The maximum overflow sector count is 65,535 due to the uint16_t storage type. If imaging optical media with larger lead-out areas or extensive overburn regions, some data may not be representable. This limit is generally sufficient for most practical cases.
  Overflow sector data may be difficult or impossible to read on some drives, as it often resides in lead-out areas or beyond rated capacity. The presence of overflow sectors in an image indicates the imaging drive was capable of reading these extended areas, but other drives may not be able to access them.

Definition at line 3555 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, aaruformat_context::magic, DdtHeader2::overflow, TRACE, and aaruformat_context::user_data_ddt_header.

## ◆ aaruf_get_readable_media_tags()

int32_t aaruf_get_readable_media_tags | ( | const void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieves which media tags are present in the AaruFormat image.

Returns an array of booleans indicating the presence of each MediaTagType in the image. The array is indexed by MediaTagType enum values (0 to MaxMediaTag), where each boolean is true if the corresponding media tag exists in the image's mediaTags hash table.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened image context).
  buffer | Pointer to a buffer to store the boolean array. Can be NULL to query required length.
  length | Pointer to the buffer length. On input, contains buffer size; on output, contains required size.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved readable media tags. This is returned when: The context is valid and properly initialized The buffer is large enough to hold all MediaTagType values (0 to MaxMediaTag) The output array has been populated with true/false for each MediaTagType
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The buffer is too small. This occurs when: The buffer parameter is NULL The length parameter is NULL The provided buffer is smaller than required (size = MaxMediaTag + 1 bytes) The length output will contain the required buffer size

Note
  Buffer Size: The buffer must be at least (MaxMediaTag + 1) bytes, where each byte represents whether the corresponding MediaTagType is present in the image.
  Query Mode: To query the required buffer size, pass buffer == NULL or *length < required. The function will return AARUF_ERROR_BUFFER_TOO_SMALL and set *length to required size.

Warning
  The output parameters are only modified on success (AARUF_STATUS_OK). On error, their values remain unchanged.

Definition at line 706 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, aaruformat_context::magic, MaxMediaTag, aaruformat_context::mediaTags, and TRACE.

## ◆ aaruf_get_readable_sector_tags()

int32_t aaruf_get_readable_sector_tags | ( | const void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieves which sector tags are readable in the AaruFormat image.

Returns an array of booleans indicating whether each SectorTagType was successfully read from the image. The array is indexed by SectorTagType enum values (0 to MaxSectorTag), where each boolean is true if the corresponding sector tag data is present and readable in the image. Sector tags contain per-sector metadata such as sync headers, ECC/EDC codes, subchannels, and other sector-level information essential for exact media reconstruction.

Parameters

  context | Pointer to the aaruformat context (must be a valid, opened image context).
  buffer | Pointer to a buffer to store the boolean array. Can be NULL to query required length.
  length | Pointer to the buffer length. On input, contains buffer size; on output, contains required size.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved readable sector tags. This is returned when: The context is valid and properly initialized The readableSectorTags array is populated in the context The buffer is large enough to hold all SectorTagType values (0 to MaxSectorTag) The output array has been successfully copied from the internal readableSectorTags
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()
  AARUF_ERROR_METADATA_NOT_PRESENT | (-30) The sector tags array is not available. This occurs when: The readableSectorTags array is NULL (not initialized in the context) The image was created without sector tag support The image format does not support or require sector tags
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The buffer is too small. This occurs when: The buffer parameter is NULL The length parameter is NULL The provided buffer is smaller than required (size = (MaxSectorTag + 1) * sizeof(bool)) The length output will contain the required buffer size in bytes

Note
  Buffer Size: The buffer must be at least (MaxSectorTag + 1) bytes, where each byte represents whether the corresponding SectorTagType data was successfully read in the image. On most systems, sizeof(bool) == 1, so the required size is (MaxSectorTag + 1) bytes.
  Sector Tag Types: Sector tags preserve on-disk structures not part of main user data. Examples include:
  - CD sector sync/header information (CdSectorSync, CdSectorHeader)
  - CD subheaders and ECC/EDC codes (CdSectorSubHeader, CdSectorEcc, CdSectorEdc)
  - DVD sector numbers and IED (DvdSectorNumber)
  - Media-specific proprietary tags (AppleProfileTagAaru, PriamDataTowerTagAaru)
  Query Mode: To query the required buffer size, pass buffer == NULL or *length < required. The function will return AARUF_ERROR_BUFFER_TOO_SMALL and set *length to required size. This allows allocation of properly sized buffers without prior knowledge of MaxSectorTag.
  Data Interpretation: A true value (non-zero) at buffer[i] indicates sector tag type i was readable. A false value (zero) at buffer[i] indicates that sector tag type i is either not present or was not successfully read from the image during opening. The readableSectorTags array is populated during image opening/processing in data blocks.
  Image Opening Context: The readableSectorTags array is initialized during aaruf_open() or aaruf_create() and populated as data blocks are processed. It reflects what was actually present and readable in the image file, not what theoretically could be present for the media type.

Warning
  The output parameters are only modified on success (AARUF_STATUS_OK). On error, their values remain unchanged. Initialize them before calling if default values are needed on failure.
  If readableSectorTags is NULL in the context, AARUF_ERROR_NOT_FOUND is returned. This typically indicates the image format does not support sector-level tags, rather than indicating an error state. Check return value to distinguish.

See also
  SectorTagType for enumeration of all available sector tag types
  aaruf_read_sector_tag() for reading individual sector tag data
  aaruf_write_sector_tag() for writing sector tags during image creation

Definition at line 618 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_METADATA_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, FATAL, aaruformat_context::magic, MaxSectorTag, aaruformat_context::readableSectorTags, and TRACE.

## ◆ aaruf_get_tape_file()

int32_t aaruf_get_tape_file | ( | const void * | context,
|  | const uint8_t | partition,
|  | const uint32_t | file,
|  | uint64_t * | starting_block,
|  | uint64_t * | ending_block )

Retrieves the block range for a specific tape file from an Aaru tape image.

Queries the tape file hash table to locate a file by its partition and file number, returning the first and last block addresses that define the file's extent on the tape medium. This function provides the core lookup mechanism for accessing logical files stored in tape images.

Tape File Identification: Each tape file is uniquely identified by a combination of:

- Partition number (8-bit): The tape partition containing the file
- File number (32-bit): The sequential file number within that partition

These two values are combined into a 64-bit composite key: key = (partition << 32) | file_number

This composite key is used to perform a hash table lookup in the context's tapeFiles table, which was previously populated by process_tape_files_block() during image initialization.

Block Range Semantics: The returned block range [FirstBlock, LastBlock] is inclusive on both ends:

- FirstBlock: The first block address where the file begins
- LastBlock: The final block address where the file ends (inclusive)
- Block count: (LastBlock - FirstBlock + 1)

Block addresses are absolute positions within the tape image's logical block space, not relative to the partition or file.

Typical Usage Flow:

1. Open an Aaru tape image with aaruf_open()
2. Call aaruf_get_tape_file() to get the block range for a specific file
3. Use the returned block range to read the file's data blocks
4. Repeat for other files as needed

Error Handling: The function performs validation in the following order:

1. Context pointer validation (NULL check)
2. Magic number verification (ensures valid aaruformat context)
3. Hash table lookup for the specified partition/file combination

If any validation fails, an appropriate error code is returned and the output parameters (starting_block, ending_block) are left unmodified.

Thread Safety: This function performs read-only operations on the context and is safe to call from multiple threads concurrently, provided the context is not being modified by other operations (e.g., during image opening/closing).

Performance Characteristics:

- Hash table lookup: O(1) average case
- No I/O operations performed
- Minimal stack usage
- Suitable for high-frequency queries

Parameters

  | context | Pointer to an initialized aaruformat context. Must not be NULL. The context must have been successfully opened with aaruf_open() and contain a valid tape file hash table. The context is treated as const and is not modified by this operation.
  | partition | The partition number (0-255) containing the requested file. For single-partition tapes, this is typically 0. Multi-partition tapes may have files in different partitions with potentially overlapping file numbers.
  | file | The file number within the specified partition. File numbers are typically sequential starting from 0 or 1, but gaps may exist if files were deleted or the tape was written non-sequentially.
  [out] | starting_block | Pointer to receive the first block address of the file. Must not be NULL. Only modified on success. The value written represents the inclusive start of the file's block range.
  [out] | ending_block | Pointer to receive the last block address of the file. Must not be NULL. Only modified on success. The value written represents the inclusive end of the file's block range.

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved tape file information. Both output parameters have been populated with valid block addresses. The requested partition/file combination exists in the image's file table.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) Invalid context or context validation failed. This is returned when: The context pointer is NULL The context magic number doesn't match AARU_MAGIC (corrupted or wrong type) The output parameters are not modified.
  AARUF_ERROR_TAPE_FILE_NOT_FOUND | (-28) The requested partition/file combination does not exist in the image's tape file table. This is returned when: The specified partition number has no files The specified file number doesn't exist in the given partition The tape file block was not present or failed to load during image open The output parameters are not modified.

Note
  The function logs entry and exit points via TRACE macros when tracing is enabled, including parameter values and return codes for debugging.
  The tape file hash table (ctx->tapeFiles) must have been populated during image initialization. If the image doesn't contain a TapeFileBlock, or if that block failed to load, all queries will return AARUF_ERROR_TAPE_FILE_NOT_FOUND.
  For images without tape file metadata, applications should fall back to direct block-based access or partition-level operations.
  The returned block addresses are logical block numbers. To read actual data, these must be translated through the appropriate read functions that handle the image's block encoding, compression, and DDT mapping.

Warning
  The output parameter pointers must be valid. Passing NULL for either starting_block or ending_block will cause undefined behavior (likely a crash when the function attempts to dereference them on success).
  If the same partition/file combination appears multiple times in the TapeFileBlock, only the last occurrence is retained (due to HASH_REPLACE behavior in process_tape_files_block). This should not occur in valid images but may happen with corrupted or malformed tape file metadata.

See also
  process_tape_files_block() for tape file table initialization
  TapeFileEntry for the structure defining file block ranges
  tapeFileHashEntry for the hash table entry structure
  aaruf_get_tape_partition() for partition-level queries (if available)

Definition at line 569 of file tape.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_TAPE_FILE_NOT_FOUND, AARUF_STATUS_OK, FATAL, TapeFileHashEntry::fileEntry, TapeFileEntry::FirstBlock, TapeFileEntry::LastBlock, aaruformat_context::magic, aaruformat_context::tape_files, and TRACE.

## ◆ aaruf_get_tape_partition()

int32_t aaruf_get_tape_partition | ( | const void * | context,
|  | const uint8_t | partition,
|  | uint64_t * | starting_block,
|  | uint64_t * | ending_block )

Retrieves the block range for a specific tape partition from an Aaru tape image.

Queries the tape partition hash table to locate a partition by its partition number, returning the first and last block addresses that define the partition's extent on the tape medium. This function provides the core lookup mechanism for accessing partition layout information in tape images.

Tape Partition Identification: Each tape partition is uniquely identified by its partition number (0-255). Most tapes have a single partition (partition 0), but multi-partition formats like LTO, DLT, and AIT support multiple partitions with independent block address spaces.

The partition number is used as the hash table key to perform a lookup in the context's tapePartitions table, which was previously populated by process_tape_partitions_block() during image initialization.

Block Range Semantics: The returned block range [FirstBlock, LastBlock] is inclusive on both ends:

- FirstBlock: The first block address in the partition (often 0, but format-dependent)
- LastBlock: The final block address in the partition (inclusive)
- Block count: (LastBlock - FirstBlock + 1)

Block addresses are local to each partition. Different partitions may have overlapping logical block numbers (e.g., both partition 0 and partition 1 can have blocks 0-1000). When accessing blocks, both the partition number and block number are required for unique identification.

Typical Usage Flow:

1. Open an Aaru tape image with aaruf_open()
2. Call aaruf_get_tape_partition() to get the block range for a specific partition
3. Use the returned block range to understand partition boundaries
4. Access files within the partition using aaruf_get_tape_file()
5. Repeat for other partitions as needed

Error Handling: The function performs validation in the following order:

1. Context pointer validation (NULL check)
2. Magic number verification (ensures valid aaruformat context)
3. Hash table lookup for the specified partition number

If any validation fails, an appropriate error code is returned and the output parameters (starting_block, ending_block) are left unmodified.

Thread Safety: This function performs read-only operations on the context and is safe to call from multiple threads concurrently, provided the context is not being modified by other operations (e.g., during image opening/closing).

Performance Characteristics:

- Hash table lookup: O(1) average case
- No I/O operations performed
- Minimal stack usage
- Suitable for high-frequency queries

Partition Layout Information: The partition metadata is essential for:

- Understanding the physical organization of the tape
- Determining partition boundaries for file access
- Validating that file block ranges fall within partition limits
- Supporting multi-partition tape formats correctly
- Preserving original tape partitioning schemes

Parameters

  | context | Pointer to an initialized aaruformat context. Must not be NULL. The context must have been successfully opened with aaruf_open() and contain a valid tape partition hash table. The context is treated as const and is not modified by this operation.
  | partition | The partition number (0-255) to query. For single-partition tapes, this is typically 0. Multi-partition tapes may have multiple partitions numbered sequentially from 0.
  [out] | starting_block | Pointer to receive the first block address of the partition. Must not be NULL. Only modified on success. The value written represents the inclusive start of the partition's block range (often 0, but format-dependent).
  [out] | ending_block | Pointer to receive the last block address of the partition. Must not be NULL. Only modified on success. The value written represents the inclusive end of the partition's block range.

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved tape partition information. Both output parameters have been populated with valid block addresses. The requested partition exists in the image's partition table.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) Invalid context or context validation failed. This is returned when: The context pointer is NULL The context magic number doesn't match AARU_MAGIC (corrupted or wrong type) The output parameters are not modified.
  AARUF_ERROR_TAPE_PARTITION_NOT_FOUND | (-29) The requested partition number does not exist in the image's tape partition table. This is returned when: The specified partition number was not defined in the TapePartitionBlock The tape partition block was not present or failed to load during image open The partition number is out of range for this tape The output parameters are not modified.

Note
  The function logs entry and exit points via TRACE macros when tracing is enabled, including parameter values and return codes for debugging.
  The tape partition hash table (ctx->tapePartitions) must have been populated during image initialization. If the image doesn't contain a TapePartitionBlock, or if that block failed to load, all queries will return AARUF_ERROR_TAPE_PARTITION_NOT_FOUND.
  For images without tape partition metadata, the entire tape may be treated as a single implicit partition, and applications should handle the absence of partition information gracefully.
  The returned block addresses are logical block numbers within the partition's address space. To read actual data, these must be combined with the partition number and translated through the appropriate read functions.
  Partition metadata is primarily informational and used for validation. File access is primarily driven by file metadata (TapeFileBlock), which references partition numbers to establish context.

Warning
  The output parameter pointers must be valid. Passing NULL for either starting_block or ending_block will cause undefined behavior (likely a crash when the function attempts to dereference them on success).
  If the same partition number appears multiple times in the TapePartitionBlock, only the last occurrence is retained (due to HASH_REPLACE behavior in process_tape_partitions_block). This should not occur in valid images but may happen with corrupted or malformed partition metadata.
  Single-partition tapes may not include a TapePartitionBlock at all, in which case this function will always return AARUF_ERROR_TAPE_PARTITION_NOT_FOUND. Applications should handle this case and assume a default partition 0 spanning the entire tape.

See also
  process_tape_partitions_block() for partition table initialization
  TapePartitionEntry for the structure defining partition block ranges
  TapePartitionHashEntry for the hash table entry structure
  aaruf_get_tape_file() for file-level queries within partitions
  aaruf_set_tape_partition() for setting partition information during write

Definition at line 982 of file tape.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_TAPE_PARTITION_NOT_FOUND, AARUF_STATUS_OK, FATAL, TapePartitionEntry::FirstBlock, TapePartitionEntry::LastBlock, aaruformat_context::magic, TapePartitionHashEntry::partitionEntry, aaruformat_context::tape_partitions, and TRACE.

## ◆ aaruf_get_tracks()

int32_t aaruf_get_tracks | ( | const void * | context,
|  | uint8_t * | buffer,
|  | size_t * | length )

Retrieve the array of track descriptors contained in an opened AaruFormat image.

Provides the caller with a contiguous array of all track entries found in the image. The function follows a two-step usage pattern allowing callers to query the required buffer size before performing the actual copy.

Usage pattern:

- First call with buffer == NULL (or *length smaller than required). The function sets *length to the required size and returns AARUF_ERROR_BUFFER_TOO_SMALL.
- Allocate a buffer of at least *length bytes and call again. On success, the function copies all TrackEntry structures and returns AARUF_STATUS_OK with *length set to the bytes copied.

The returned data is a raw copy of internal TrackEntry structures (host endianness). The caller does not assume ownership of internal memory; only the caller-provided buffer should be freed by the caller.

Preconditions (

Precondition
  ):
  context is a valid pointer to an aaruformatContext previously returned by an open function.
  context->magic == AARU_MAGIC.
  process_tracks_block() has run (implicitly done during image open) populating trackEntries.

Thread safety:

- Read-only access; safe for concurrent calls on different contexts.
- Concurrent calls on the same context are safe only if no other thread is modifying/destroying it.

Buffer sizing logic:

- required_length = ctx->tracksHeader.entries * sizeof(TrackEntry)
- If buffer == NULL OR *length < required_length => *length updated, return AARUF_ERROR_BUFFER_TOO_SMALL.
- On success *length == required_length.

Error strategy:

- Validation failures: return specific error codes and log through FATAL()/TRACE().
- No partial copies are performed.

Parameters

  context | Opaque pointer that MUST point to a valid aaruformatContext.
  buffer | Destination buffer for a copy of all TrackEntry structures, or NULL to query size.
  length | In/Out: On entry capacity of buffer (ignored if buffer == NULL). On return required or copied size in bytes. Must not be NULL.

Returns
  int32_t API status code.

Return values

  AARUF_STATUS_OK | Success; buffer filled.
  AARUF_ERROR_NOT_AARUFORMAT | context is NULL or not a valid libaaruformat context.
  AARUF_ERROR_TRACK_NOT_FOUND | No tracks present (entries == 0 or internal array NULL).
  AARUF_ERROR_BUFFER_TOO_SMALL | Sizing query / provided buffer insufficient; *length updated.

Warning
  Passing an invalid context yields an error; no data is written to buffer.
  The function never performs partial copies.

Note
  Order of TrackEntry elements matches on-disk order.
  Caller may further filter (e.g., data vs audio) after retrieval.

Since
  1.0

Usage example (conceptual):

1. Open an image obtaining a valid aaruformatContext pointer.
2. Invoke aaruf_get_tracks(ctx, NULL, &size) to query required buffer size (expect AARUF_ERROR_BUFFER_TOO_SMALL).
3. Allocate a buffer of "size" bytes.
4. Invoke aaruf_get_tracks(ctx, buffer, &size) again; on AARUF_STATUS_OK iterate over (size / sizeof(TrackEntry)) entries.
5. Free the buffer and close the image when done.

Definition at line 281 of file optical.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_TRACK_NOT_FOUND, AARUF_STATUS_OK, TracksHeader::entries, FATAL, aaruformat_context::magic, TRACE, aaruformat_context::track_entries, and aaruformat_context::tracks_header.

## ◆ aaruf_get_user_sectors()

int32_t aaruf_get_user_sectors | ( | const void * | context,
|  | uint64_t * | sectors )

Retrieves the total number of user-accessible sectors in the AaruFormat image.

Returns the count of standard user data sectors in the image, excluding any negative (pre-gap) or overflow (post-gap) sectors. This represents the primary addressable sector range that contains the main user data, typically corresponding to the logical capacity of the storage medium as it would be seen by an operating system or file system. For optical media, this excludes lead-in and lead-out areas. For hard disks, this represents the standard LBA-addressable range.

Parameters

  context | Pointer to a valid aaruformat context (must be properly initialized).
  sectors | Pointer to a uint64_t that receives the total user sector count on success.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully retrieved the user sector count. This is returned when: The context is valid and properly initialized The context magic number matches AARU_MAGIC The sectors parameter is successfully populated with the user sector count The value is taken from ctx->user_data_ddt_header.blocks For block devices: sectors typically equals the total capacity in sectors For optical media: sectors represents the user data area excluding lead-in/lead-out For tape media: sectors may represent the total block count across all files
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_open() or aaruf_create()

Note
  Sector Range Context:
  - User sectors represent the standard addressable range: 0 to (user_sectors - 1)
  - Total addressable sectors = negative_sectors + user_sectors + overflow_sectors
  - Negative sectors precede user sectors (pre-gap, lead-in)
  - Overflow sectors follow user sectors (post-gap, lead-out)
  - Use aaruf_get_negative_sectors() to get the negative sector count
  - Use aaruf_get_overflow_sectors() to get the overflow sector count
  Media Type Considerations:
  - Optical Media (CD/DVD/BD): User sectors exclude lead-in and lead-out areas. Negative sectors may contain TOC and pre-gap data. Overflow sectors may contain post-gap and lead-out data.
  - Hard Disk Drives: User sectors represent the full LBA range. Negative and overflow sectors are typically zero unless capturing special areas.
  - Floppy Disks: User sectors represent the standard formatted capacity.
  - Tape Media: User sectors may represent the total block count. Negative and overflow sectors are typically not used for tape.
  DDT Header Source:
  - The value is retrieved from ctx->user_data_ddt_header.blocks
  - The DDT (Deduplication and Data Table) header tracks sector allocation
  - This field is populated during image creation with aaruf_create()
  - The value is fixed for read-only images opened with aaruf_open()
  - For write-enabled images, this represents the allocated capacity
  Addressing and I/O Operations:
  - When reading/writing sectors with aaruf_read_sector() or aaruf_write_sector():
    - Set negative=false and use sector_address in range [0, user_sectors - 1]
    - For negative sectors: set negative=true, sector_address in [0, negative_sectors - 1]
    - For overflow sectors: set negative=false, sector_address in [user_sectors, user_sectors + overflow_sectors

- 1]

Note
  Relationship to Image Creation:
  - The user_sectors value is specified when calling aaruf_create()
  - It should match the logical capacity of the medium being imaged
  - For forensic images, ensure it matches the source medium exactly
  - For virtual disks, set it to the desired capacity

Definition at line 3295 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, DdtHeader2::blocks, FATAL, aaruformat_context::magic, TRACE, and aaruformat_context::user_data_ddt_header.

## ◆ aaruf_get_xml_mediatype()

int32_t aaruf_get_xml_mediatype | ( | int32_t | type | ) |

Definition at line 347 of file helpers.c.

References AARU_CALL, AARU_LOCAL, BDR, BDRE, BDREXL, BDROM, BDRXL, BlockMedia, CBHD, CD, CD32, CDDA, CDEG, CDG, CDI, CDIREADY, CDMIDI, CDMO, CDMRW, CDPLUS, CDR, CDROM, CDROMXA, CDRW, CDTV, CDV, DDCD, DDCDR, DDCDRW, DTSCD, DVDDownload, DVDPR, DVDPRDL, DVDPRW, DVDPRWDL, DVDR, DVDRAM, DVDRDL, DVDROM, DVDRW, DVDRWDL, EVD, FDDVD, FMTOWNS, FVD, GDR, GDROM, GOD, HDDVDR, HDDVDRAM, HDDVDRDL, HDDVDROM, HDDVDRW, HDDVDRWDL, HDVMD, HVD, JaguarCD, LD, LDROM, LDROM2, LVROM, MEGACD, MegaLD, MilCD, NeoGeoCD, Nuon, OpticalDisc, PCD, PCFX, Pippin, Playdia, PS1CD, PS2CD, PS2DVD, PS3BD, PS3DVD, PS4BD, SACD, SATURNCD, SuperCDROM2, SVCD, SVOD, ThreeDO, UMD, VCD, VCDHD, VideoNow, VideoNowColor, VideoNowXp, WOD, WUOD, XGD, XGD2, XGD3, and XGD4.

Referenced by aaruf_create(), and aaruf_open().

## ◆ aaruf_identify()

int aaruf_identify | ( | const char * | filename | ) |

Identifies a file as an AaruFormat image using a file path.

Opens the file at the given path and determines if it is an AaruFormat image by examining the file header for valid AaruFormat signatures and version information. This function provides a simple file-based interface that handles file opening, identification, and cleanup automatically. It delegates the actual identification logic to aaruf_identify_stream().

Parameters

  filename | Path to the file to identify (must be accessible and readable).

Returns
  Returns one of the following values:

Return values

  100 | Maximum confidence - Definitive AaruFormat image. This is returned when: The file header contains a valid AaruFormat signature (DIC_MAGIC or AARU_MAGIC) The image major version is less than or equal to the supported version (AARUF_VERSION) The file structure passes all header validation checks This indicates the file is definitely a supported AaruFormat image
  0 | Not recognized - File is not an AaruFormat image. This is returned when: The file header doesn't contain a recognized AaruFormat signature The image major version exceeds the maximum supported version The file header cannot be read completely (file too small or corrupted) The file format doesn't match AaruFormat specifications
  Positive | errno values - File access errors from system calls. Common values include: ENOENT (2) - File not found or path doesn't exist EACCES (13) - Permission denied, file not readable EISDIR (21) - Path refers to a directory, not a file EMFILE (24) - Too many open files (process limit reached) ENFILE (23) - System limit on open files reached ENOMEM (12) - Insufficient memory to open file EIO (5) - I/O error occurred during file access Other platform-specific errno values from fopen()

Note
  Identification Process:
  - Opens the file in binary read mode ("rb")
  - Delegates identification to aaruf_identify_stream() for actual header analysis
  - Automatically closes the file stream regardless of identification result
  - Returns system errno values directly if file opening fails
  Confidence Scoring:
  - Uses binary scoring: 100 (definitive match) or 0 (no match)
  - No intermediate confidence levels are returned
  - Designed for simple yes/no identification rather than probabilistic matching
  Version Compatibility:
  - Only recognizes AaruFormat versions up to AARUF_VERSION
  - Future versions beyond library support are treated as unrecognized
  - Backwards compatible with older DIC_MAGIC identifiers

Warning
  The function opens and closes the file for each identification. For repeated operations on the same file, consider using aaruf_identify_stream() with a pre-opened stream for better performance.
  File access permissions and availability are checked at runtime. Network files or files on removable media may cause variable access times.
  The function performs minimal file content validation. A positive result indicates the file appears to be AaruFormat but doesn't guarantee the entire file is valid or uncorrupted.

Definition at line 84 of file identify.c.

References AARU_CALL, AARU_EXPORT, and aaruf_identify_stream().

## ◆ aaruf_identify_stream()

int aaruf_identify_stream | ( | FILE * | image_stream | ) |

Identifies a file as an AaruFormat image using an open stream.

Determines if the provided stream is an AaruFormat image by reading and validating the file header at the beginning of the stream. This function performs the core identification logic by checking for valid AaruFormat signatures and version compatibility. It's designed to work with any FILE stream, making it suitable for integration with existing file handling code.

Parameters

  image_stream | Open FILE stream positioned at any location (will be repositioned to start).

Returns
  Returns one of the following values:

Return values

  100 | Maximum confidence - Definitive AaruFormat image. This is returned when: The stream is successfully repositioned to the beginning The AaruFormat header is successfully read (AaruHeader structure) The header identifier matches either DIC_MAGIC or AARU_MAGIC (valid signatures) The image major version is less than or equal to AARUF_VERSION (supported version) All validation checks pass indicating a compatible AaruFormat image
  0 | Not recognized - Stream is not an AaruFormat image. This is returned when: The stream parameter is NULL Cannot read a complete AaruHeader structure from the stream (file too small) The header identifier doesn't match DIC_MAGIC or AARU_MAGIC (wrong format) The image major version exceeds AARUF_VERSION (unsupported future version) Any validation check fails indicating the stream is not a valid AaruFormat image

Note
  Stream Handling:
  - Always seeks to position 0 at the beginning of the function
  - Reads exactly one AaruHeader structure (size depends on format version)
  - Does not restore the original stream position after identification
  - Stream remains open and positioned after the header on function return
  Signature Recognition:
  - DIC_MAGIC: Legacy identifier from original DiscImageChef format
  - AARU_MAGIC: Current AaruFormat identifier
  - Both signatures are accepted for backwards compatibility
  - Signature validation is performed using exact byte matching
  Version Validation:
  - Only checks the major version number for compatibility
  - Minor version differences are ignored (assumed backwards compatible)
  - Future major versions are rejected to prevent compatibility issues
  - Version check prevents attempting to read unsupported format variants
  Confidence Scoring:
  - Binary result: 100 (definitive) or 0 (not recognized)
  - No probabilistic or partial matching
  - Designed for definitive identification rather than format detection

Warning
  The function modifies the stream position by seeking to the beginning and reading the header. The stream position is not restored.
  This function performs only header-level validation. A positive result indicates the file appears to have a valid AaruFormat header but doesn't guarantee the entire image structure is valid or uncorrupted.
  The stream must support seeking operations. Non-seekable streams (like pipes or network streams) may cause undefined behavior.
  No error codes are returned for I/O failures during header reading. Such failures result in a return value of 0 (not recognized).

Definition at line 163 of file identify.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_VERSION, DIC_MAGIC, AaruHeader::identifier, and AaruHeader::imageMajorVersion.

Referenced by aaruf_identify().

## ◆ aaruf_lzma_decode_buffer()

int32_t aaruf_lzma_decode_buffer | ( | uint8_t * | dst_buffer,
|  | size_t * | dst_size,
|  | const uint8_t * | src_buffer,
|  | size_t * | src_len,
|  | const uint8_t * | props,
|  | const size_t | props_size )

Decodes an LZMA-compressed buffer.

Decompresses data from the source buffer into the destination buffer using LZMA.

Parameters

  dst_buffer | Pointer to the destination buffer.
  dst_size | Pointer to the size of the destination buffer; updated with the actual size.
  src_buffer | Pointer to the source (compressed) buffer.
  src_len | Pointer to the size of the source buffer; updated with the actual size read.
  props | Pointer to the LZMA properties.
  props_size | Size of the LZMA properties.

Returns
  0 on success, or an error code on failure.

Definition at line 39 of file lzma.c.

References AARU_CALL, and AARU_EXPORT.

Referenced by aaruf_read_sector(), decode_ddt_multi_level_v2(), process_data_block(), process_ddt_v1(), and process_ddt_v2().

## ◆ aaruf_lzma_encode_buffer()

int32_t aaruf_lzma_encode_buffer | ( | uint8_t * | dst_buffer,
|  | size_t * | dst_size,
|  | const uint8_t * | src_buffer,
|  | const size_t | src_len,
|  | uint8_t * | out_props,
|  | size_t * | out_props_size,
|  | const int32_t | level,
|  | const uint32_t | dict_size,
|  | const int32_t | lc,
|  | const int32_t | lp,
|  | const int32_t | pb,
|  | const int32_t | fb,
|  | const int32_t | num_threads )

Encodes a buffer using LZMA compression.

Compresses data from the source buffer into the destination buffer using LZMA.

Parameters

  dst_buffer | Pointer to the destination buffer.
  dst_size | Pointer to the size of the destination buffer; updated with the actual size.
  src_buffer | Pointer to the source (uncompressed) buffer.
  src_len | Size of the source buffer.
  out_props | Pointer to the output LZMA properties.
  out_props_size | Pointer to the size of the output LZMA properties.
  level | Compression level.
  dict_size | Dictionary size.
  lc | LZMA literal context bits.
  lp | LZMA literal position bits.
  pb | LZMA position bits.
  fb | Number of fast bytes.
  num_threads | Number of threads to use.

Returns
  0 on success, or an error code on failure.

Definition at line 65 of file lzma.c.

References AARU_CALL, and AARU_EXPORT.

Referenced by aaruf_close_current_block(), set_ddt_multi_level_v2(), write_cached_secondary_ddt(), write_dvd_long_sector_blocks(), write_dvd_title_key_decrypted_block(), write_media_tags(), write_mode2_subheaders_block(), write_sector_prefix(), write_sector_prefix_ddt(), write_sector_subchannel(), write_sector_suffix(), write_sector_suffix_ddt(), and write_single_level_ddt().

## ◆ aaruf_md5_buffer()

void aaruf_md5_buffer | ( | const void * | data,
|  | unsigned long | size,
|  | unsigned char * | result )

Definition at line 518 of file md5.c.

References AARU_CALL, AARU_EXPORT, aaruf_md5_final(), aaruf_md5_init(), and aaruf_md5_update().

## ◆ aaruf_md5_final()

void aaruf_md5_final | ( | md5_ctx * | ctx,
|  | unsigned char * | result )

Definition at line 485 of file md5.c.

References md5_ctx::a, AARU_CALL, AARU_EXPORT, md5_ctx::b, body(), md5_ctx::buffer, md5_ctx::c, md5_ctx::d, md5_ctx::hi, md5_ctx::lo, and OUT.

Referenced by aaruf_md5_buffer(), and write_checksum_block().

## ◆ aaruf_md5_init()

void aaruf_md5_init | ( | md5_ctx * | ctx | ) |

Definition at line 436 of file md5.c.

References md5_ctx::a, AARU_CALL, AARU_EXPORT, md5_ctx::b, md5_ctx::c, md5_ctx::d, md5_ctx::hi, and md5_ctx::lo.

Referenced by aaruf_create(), and aaruf_md5_buffer().

## ◆ aaruf_md5_update()

void aaruf_md5_update | ( | md5_ctx * | ctx,
|  | const void * | data,
|  | unsigned long | size )

Definition at line 447 of file md5.c.

References AARU_CALL, AARU_EXPORT, AARU_RESTRICT, body(), md5_ctx::buffer, md5_ctx::hi, LIKELY, md5_ctx::lo, and UNLIKELY.

Referenced by aaruf_md5_buffer(), aaruf_write_sector(), and aaruf_write_sector_long().

## ◆ aaruf_open()

void * aaruf_open | ( | const char * | filepath,
|  | bool | resume_mode,
|  | char * | options )

References AARU_CALL, AARU_EXPORT, and AARU_LOCAL.

## ◆ aaruf_read_media_tag()

int32_t aaruf_read_media_tag | ( | void * | context,
|  | uint8_t * | data,
|  | const int32_t | tag,
|  | uint32_t * | length )

Reads a media tag from the AaruFormat image.

Reads the specified media tag from the image and stores it in the provided buffer. Media tags contain metadata information about the storage medium such as disc information, lead-in/lead-out data, manufacturer-specific information, or other medium-specific metadata. This function uses a hash table lookup for efficient tag retrieval and supports buffer size querying when data pointer is NULL.

Parameters

  context | Pointer to the aaruformat context.
  data | Pointer to the buffer to store the tag data. Can be NULL to query tag length.
  tag | Tag identifier to read (specific to media type and format).
  length | Pointer to the length of the buffer on input; updated with actual tag length on output.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully read the media tag. This is returned when: The context is valid and properly initialized The requested media tag exists in the image's media tag hash table The provided buffer is large enough to contain the tag data The tag data is successfully copied to the output buffer The length parameter is updated with the actual tag data length
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_ERROR_MEDIA_TAG_NOT_PRESENT | (-11) The requested media tag does not exist. This occurs when: The tag identifier is not found in the image's media tag hash table The image was created without the requested metadata The tag identifier is not supported for this media type The length parameter is set to 0 when this error is returned
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer is insufficient. This occurs when: The data parameter is NULL (used for length querying) The buffer length (*length) is smaller than the required tag data length The length parameter is updated with the required size for retry

Note
  Buffer Size Querying:
  - Pass data as NULL to query the required buffer size without reading data
  - The length parameter will be updated with the required size
  - This allows proper buffer allocation before the actual read operation
  Media Tag Types:
  - Tags are media-type specific (optical disc, floppy disk, hard disk, etc.)
  - Common tags include TOC data, lead-in/out, manufacturer data, defect lists
  - Tag availability depends on what was preserved during the imaging process
  Hash Table Lookup:
  - Uses efficient O(1) hash table lookup for tag retrieval
  - Tag identifiers are integer values specific to the media format
  - Hash table is populated during image opening from indexed metadata blocks

Warning
  The function performs a direct memory copy operation. Ensure the output buffer has sufficient space to prevent buffer overflows.
  Media tag data is stored as-is from the original medium. No format conversion or validation is performed on the tag content.

Definition at line 85 of file read.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_MEDIA_TAG_NOT_PRESENT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_STATUS_OK, mediaTagEntry::data, FATAL, mediaTagEntry::length, aaruformat_context::magic, aaruformat_context::mediaTags, and TRACE.

## ◆ aaruf_read_sector()

int32_t aaruf_read_sector | ( | void * | context,
|  | const uint64_t | sector_address,
|  | bool | negative,
|  | uint8_t * | data,
|  | uint32_t * | length,
|  | uint8_t * | sector_status )

Reads a sector from the AaruFormat image.

Reads user data from the specified sector address in the image. This function reads only the user data portion of the sector, without any additional metadata or ECC/EDC information. It handles block-based deduplication, compression (LZMA/FLAC), and caching for optimal performance. The function supports both DDT v1 and v2 formats for sector-to-block mapping.

Parameters

  context | Pointer to the aaruformat context.
  sector_address | The logical sector address to read from.
  negative | Indicates if the sector address is negative.
  data | Pointer to buffer where sector data will be stored. Can be NULL to query length.
  length | Pointer to variable containing buffer size on input, actual data length on output.
  sector_status | Pointer to variable that will receive the sector status flags. Must not be NULL. The status indicates the condition of the sector data, such as whether it contains errors, was not dumped, or has other quality indicators from the imaging process.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully read the sector data. This is returned when: The sector data is successfully retrieved from cache or decompressed from storage Block header and data are successfully read and processed Decompression (if needed) completes successfully The sector data is copied to the output buffer The length parameter is updated with the actual sector size
  AARUF_STATUS_SECTOR_NOT_DUMPED | (1) The sector was not dumped during imaging. This occurs when: The DDT entry indicates the sector status is SectorStatusNotDumped The original imaging process skipped this sector due to read errors The length parameter is set to the expected sector size for buffer allocation
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_ERROR_SECTOR_OUT_OF_BOUNDS | (-5) The sector address exceeds image bounds. This occurs when: sector_address is greater than or equal to ctx->imageInfo.Sectors Attempting to read beyond the logical extent of the imaged medium
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The provided buffer is insufficient. This occurs when: The data parameter is NULL (used for length querying) The buffer length (*length) is smaller than the block's sector size The length parameter is updated with the required size for retry
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: Cannot allocate memory for block header (if not cached) Cannot allocate memory for uncompressed block data Cannot allocate memory for compressed data buffer (LZMA/FLAC) Cannot allocate memory for decompressed block buffer
  AARUF_ERROR_CANNOT_READ_HEADER | (-6) Block header reading failed. This occurs when: Cannot read the complete BlockHeader structure from the image stream File I/O errors prevent reading header data at the calculated block offset Image file corruption or truncation
  AARUF_ERROR_CANNOT_READ_BLOCK | (-7) Block data reading failed. This occurs when: Cannot read uncompressed block data from the image stream Cannot read LZMA properties from compressed blocks Cannot read compressed data from LZMA or FLAC blocks File I/O errors during block data access
  AARUF_ERROR_CANNOT_DECOMPRESS_BLOCK | (-17) Decompression failed. This occurs when: LZMA decoder returns a non-zero error code during decompression FLAC decoder fails to decompress audio data properly Decompressed data size doesn't match the expected block length Compression algorithm encounters corrupted or invalid compressed data
  AARUF_ERROR_UNSUPPORTED_COMPRESSION | (-8) Unsupported compression algorithm. This occurs when: The block header specifies a compression type not supported by this library Future compression algorithms not implemented in this version
  Other | error codes may be propagated from DDT decoding functions: From decode_ddt_entry_v1(): AARUF_ERROR_NOT_AARUFORMAT (-1) From decode_ddt_entry_v2(): AARUF_ERROR_NOT_AARUFORMAT (-1), AARUF_ERROR_CANNOT_READ_BLOCK (-7), AARUF_ERROR_CANNOT_DECOMPRESS_BLOCK (-17), AARUF_ERROR_INVALID_BLOCK_CRC (-18)

Note
  DDT Processing:
  - Automatically selects DDT v1 or v2 decoding based on ctx->ddtVersion
  - DDT decoding provides sector offset within block and block file offset
  - Handles deduplication where multiple sectors may reference the same block
  Caching Mechanism:
  - Block headers are cached for performance (ctx->blockHeaderCache)
  - Decompressed block data is cached to avoid repeated decompression (ctx->blockCache)
  - Cache hits eliminate file I/O and decompression overhead
  - Cache sizes are determined during context initialization
  Compression Support:
  - None: Direct reading of uncompressed block data
  - LZMA: Industry-standard compression with properties header
  - FLAC: Audio-optimized compression for CD audio blocks
  - Each compression type has specific decompression requirements and error conditions
  Buffer Size Querying:
  - Pass data as NULL to query the required buffer size without reading data
  - The length parameter will be updated with the block's sector size
  - Useful for dynamic buffer allocation before the actual read operation

Warning
  This function reads only user data. For complete sector data including metadata and ECC/EDC information, use aaruf_read_sector_long().
  Memory allocated for caching is managed by the context. Do not free cached block data as it may be reused by subsequent operations.
  Sector addresses are zero-based. The maximum valid address is ctx->imageInfo.Sectors - 1.

Definition at line 253 of file read.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_CANNOT_DECOMPRESS_BLOCK, AARUF_ERROR_CANNOT_READ_BLOCK, AARUF_ERROR_CANNOT_READ_HEADER, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_ERROR_SECTOR_OUT_OF_BOUNDS, AARUF_ERROR_UNSUPPORTED_COMPRESSION, aaruf_flac_decode_redbook_buffer(), aaruf_lzma_decode_buffer(), AARUF_STATUS_OK, AARUF_STATUS_SECTOR_NOT_DUMPED, add_to_cache_uint64(), aaruformat_context::block_cache, aaruformat_context::block_header_cache, BlockHeader::cmpLength, BlockHeader::compression, aaruformat_context::ddt_version, decode_ddt_entry_v1(), decode_ddt_entry_v2(), FATAL, find_in_cache_uint64(), Flac, aaruformat_context::image_info, aaruformat_context::imageStream, BlockHeader::length, Lzma, LZMA_PROPERTIES_LENGTH, aaruformat_context::magic, DdtHeader2::negative, None, DdtHeader2::overflow, ImageInfo::Sectors, ImageInfo::SectorSize, BlockHeader::sectorSize, SectorStatusNotDumped, TRACE, and aaruformat_context::user_data_ddt_header.

Referenced by aaruf_read_sector_long(), and aaruf_read_track_sector().

## ◆ aaruf_read_sector_long()

int32_t aaruf_read_sector_long | ( | void * | context,
|  | const uint64_t | sector_address,
|  | bool | negative,
|  | uint8_t * | data,
|  | uint32_t * | length,
|  | uint8_t * | sector_status )

Reads a complete sector with all metadata from the AaruFormat image.

Reads the complete sector data including user data, ECC/EDC, subchannel data, and other metadata depending on the media type. For optical discs, this returns a full 2352-byte sector with sync, header, user data, and ECC/EDC. For block media with tags, this includes both the user data and tag information. The function handles complex sector reconstruction including ECC correction and format-specific metadata assembly.

Parameters

  context | Pointer to the aaruformat context.
  sector_address | The logical sector address to read from.
  negative | Indicates if the sector address is negative.
  data | Pointer to buffer where complete sector data will be stored. Can be NULL to query length.
  length | Pointer to variable containing buffer size on input, actual data length on output.
  sector_status | Pointer to variable that will receive the sector status flags. Must not be NULL. The status indicates the condition of the sector data, such as whether it contains errors, was not dumped, or has other quality indicators from the imaging process.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully read the complete sector with metadata. This is returned when: The sector data is successfully retrieved and reconstructed with all metadata For optical discs: sync, header, user data, and ECC/EDC are assembled into 2352 bytes For block media: user data and tags are combined according to media type ECC reconstruction (if applicable) completes successfully All required metadata (prefix/suffix, subheaders, etc.) is available and applied
  AARUF_STATUS_SECTOR_NOT_DUMPED | (1) The sector or metadata was not dumped. This can occur when: The underlying sector data was not dumped during imaging CD prefix or suffix metadata indicates NotDumped status for the sector ECC reconstruction cannot be performed due to missing correction data
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_ERROR_INCORRECT_MEDIA_TYPE | (-5) The media type doesn't support long sector reading. This occurs when: ctx->imageInfo.XmlMediaType is not OpticalDisc or BlockMedia For BlockMedia: the specific media type is not supported (not Apple, Priam, etc.) Media types that don't have extended sector formats
  AARUF_ERROR_BUFFER_TOO_SMALL | (-10) The buffer is insufficient for complete sector data. This occurs when: The data parameter is NULL (used for length querying) For optical discs: buffer length is less than 2352 bytes For block media: buffer length is less than (user data size + tag size) The length parameter is updated with the required size for retry
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: Cannot allocate memory for bare user data during optical disc processing Cannot allocate memory for user data during block media processing Memory allocation fails in underlying aaruf_read_sector() calls
  AARUF_ERROR_TRACK_NOT_FOUND | (-13) Cannot locate the sector's track. This occurs when: For optical discs: the sector address doesn't fall within any data track boundaries No track contains the specified sector address (address not in any track.start to track.end range) The track list is empty or corrupted
  AARUF_ERROR_INVALID_TRACK_FORMAT | (-14) The track has an unsupported format. This occurs when: The track type is not recognized (not Audio, Data, CdMode1, CdMode2*, etc.) Internal track format validation fails
  AARUF_ERROR_REACHED_UNREACHABLE_CODE | (-15) Internal logic error. This occurs when: Required metadata structures (sectorPrefix, sectorSuffix, etc.) are unexpectedly NULL Control flow reaches states that should be impossible with valid image data Indicates potential image corruption or library bug
  All | error codes from aaruf_read_sector() may be propagated: AARUF_ERROR_SECTOR_OUT_OF_BOUNDS (-5) - Calculated sector address exceeds image bounds AARUF_ERROR_CANNOT_READ_HEADER (-6) - Block header cannot be read AARUF_ERROR_CANNOT_READ_BLOCK (-7) - Block data cannot be read AARUF_ERROR_CANNOT_DECOMPRESS_BLOCK (-17) - Decompression fails AARUF_ERROR_UNSUPPORTED_COMPRESSION (-8) - Compression algorithm not supported

Note
  Optical Disc Sector Reconstruction:
  - Creates full 2352-byte sectors from separate user data, sync, header, and ECC/EDC components
  - Supports different CD modes: Mode 1, Mode 2 Form 1, Mode 2 Form 2, Mode 2 Formless
  - Handles ECC correction using stored correction data or reconstructed ECC
  - Uses prefix/suffix DDTs to determine correction strategy for each sector
  Block Media Tag Assembly:
  - Combines user data (typically 512 bytes) with media-specific tags
  - Tag sizes vary by media type: Apple (12-20 bytes), Priam (24 bytes)
  - Tags contain manufacturer-specific information like spare sector mapping
  ECC Reconstruction Modes:
  - Correct: Reconstructs ECC/EDC from user data (no stored correction data needed)
  - NotDumped: Indicates the metadata portion was not successfully read during imaging
  - Stored: Uses pre-computed correction data stored separately in the image
  Buffer Size Requirements:
  - Optical discs: Always 2352 bytes (full raw sector)
  - Block media: User data size + tag size (varies by media type)
  - Pass data as NULL to query the exact required buffer size

Warning
  For optical discs, this function requires track information to be available. Images without track data may not support long sector reading.
  The function performs complex sector reconstruction. Corrupted metadata or missing correction data may result in incorrect sector assembly.
  Not all AaruFormat images contain the metadata necessary for long sector reading. Some images may only support basic sector reading via aaruf_read_sector().

Definition at line 826 of file read.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_ecc_cd_reconstruct(), aaruf_ecc_cd_reconstruct_prefix(), AARUF_ERROR_BUFFER_TOO_SMALL, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_INCORRECT_MEDIA_TYPE, AARUF_ERROR_INVALID_TRACK_FORMAT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_ERROR_REACHED_UNREACHABLE_CODE, AARUF_ERROR_SECTOR_OUT_OF_BOUNDS, AARUF_ERROR_TRACK_NOT_FOUND, aaruf_read_sector(), AARUF_STATUS_OK, AARUF_STATUS_SECTOR_NOT_DUMPED, AppleFileWare, AppleProfile, AppleSonyDS, AppleSonySS, AppleWidget, Audio, BlockMedia, CD_DFIX_MASK, CD_XFIX_MASK, CdMode1, CdMode2Form1, CdMode2Form2, CdMode2Formless, Correct, Data, aaruformat_context::data_tracks, DVDDownload, DVDPR, DVDPRDL, DVDPRW, DVDPRWDL, DVDR, DVDRAM, DVDRDL, DVDROM, DVDRW, DVDRWDL, aaruformat_context::ecc_cd_context, FATAL, aaruformat_context::image_info, aaruformat_context::magic, ImageInfo::MediaType, ImageInfo::MetadataMediaType, aaruformat_context::mode2_subheaders, Mode2Form1Ok, Mode2Form2NoCrc, Mode2Form2Ok, DdtHeader2::negative, NotDumped, aaruformat_context::number_of_data_tracks, Nuon, OpticalDisc, DdtHeader2::overflow, PriamDataTower, PS2DVD, PS3DVD, SACD, aaruformat_context::sector_cpr_mai, aaruformat_context::sector_edc, aaruformat_context::sector_id, aaruformat_context::sector_ied, aaruformat_context::sector_prefix, aaruformat_context::sector_prefix_corrected, aaruformat_context::sector_prefix_ddt, aaruformat_context::sector_prefix_ddt2, aaruformat_context::sector_subchannel, aaruformat_context::sector_suffix, aaruformat_context::sector_suffix_corrected, aaruformat_context::sector_suffix_ddt, aaruformat_context::sector_suffix_ddt2, ImageInfo::Sectors, SectorStatusMode1Correct, SectorStatusMode2Form1Ok, SectorStatusMode2Form2NoCrc, SectorStatusMode2Form2Ok, SectorStatusNotDumped, TrackEntry::start, TRACE, TrackEntry::type, and aaruformat_context::user_data_ddt_header.

## ◆ aaruf_read_sector_tag()

int32_t aaruf_read_sector_tag | ( | const void * | context,
|  | const uint64_t | sector_address,
|  | const bool | negative,
|  | uint8_t * | buffer,
|  | uint32_t * | length,
|  | const int32_t | tag )

Reads a specific sector tag from the AaruFormat image.

Reads sector-level metadata tags such as subchannel data, track information, DVD sector metadata, or Apple/Priam proprietary tags from the specified sector. Sector tags are ancillary data stored separately from the main user data and provide format-specific metadata like track flags, ISRC codes, DVD encryption information, or ECC/EDC data. This function validates tag type against media type and ensures the tag data is present in the image before returning it.

Parameters

  context | Pointer to the aaruformat context.
  sector_address | The logical sector address to read the tag from.
  negative | Indicates if the sector address is negative (pre-track area).
  buffer | Pointer to buffer where tag data will be stored. Can be NULL to query tag length.
  length | Pointer to variable containing buffer size on input, actual tag length on output.
  tag | Tag identifier specifying which sector tag to read (see SectorTagType enum).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully read the sector tag. This is returned when: The context is valid and properly initialized The requested tag type exists and is applicable to the media type The tag data is present in the image for the specified sector The provided buffer is large enough to contain the tag data The tag data is successfully copied to the output buffer The length parameter is updated with the actual tag data length
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_ERROR_SECTOR_OUT_OF_BOUNDS | (-5) The sector address exceeds image bounds. This occurs when: negative is true and sector_address > ctx->userDataDdtHeader.negative - 1 negative is false and sector_address > ctx->imageInfo.Sectors + ctx->userDataDdtHeader.overflow - 1 Attempting to read beyond the logical extent of the imaged medium
  AARUF_ERROR_INCORRECT_MEDIA_TYPE | (-12) Tag type incompatible with media type. This occurs when: Optical disc tags (CdTrackFlags, CdTrackIsrc, CdSectorSubchannel, DvdSector*) requested from BlockMedia Block media tags (AppleSonyTag, AppleProfileTag, PriamDataTowerTag) requested from OpticalDisc Tag type is specific to a media format not present in the current image
  AARUF_ERROR_INCORRECT_DATA_SIZE | (-26) The provided buffer has incorrect size. This occurs when: The buffer parameter is NULL (used for length querying - NOT an error, updates length and returns this) The buffer length (*length) doesn't match the required tag data length The length parameter is updated with the required exact size for retry
  AARUF_ERROR_SECTOR_TAG_NOT_PRESENT | (-16) The requested tag is not stored in the image. This occurs when: The tag data was not captured during the imaging process The storage pointer for the tag is NULL (e.g., ctx->sector_subchannel is NULL) The imaging hardware/software did not support reading this tag type The tag is optional and was not available on the source medium
  AARUF_ERROR_TRACK_NOT_FOUND | (-13) Track information not found for the sector. This occurs when: Requesting CdTrackFlags or CdTrackIsrc for a sector not within any track boundaries The sector address doesn't fall within any track's start/end range in ctx->trackEntries[] Track metadata was not properly initialized or is corrupted
  AARUF_ERROR_INVALID_TAG | (-27) The tag identifier is not recognized or supported. This occurs when: The tag parameter value doesn't match any known SectorTagType enum value Future/unsupported tag types not implemented in this library version

Note
  Supported Tag Types and Sizes: Optical Disc Tags (OpticalDisc media only):
  - CdTrackFlags (11): 1 byte - Track control flags (audio/data, copy permitted, pre-emphasis)
  - CdTrackIsrc (9): 12 bytes - International Standard Recording Code (no null terminator)
  - CdSectorSubchannel (71): 96 bytes - Raw P-W subchannel data
  - DvdSectorCprMai (81): 6 bytes - DVD Copyright Management Information (CPR_MAI)
  - DvdSectorInformation (16): 1 byte - DVD sector information byte from ID field
  - DvdSectorNumber (17): 3 bytes - DVD sector number from ID field
  - DvdSectorIed (84): 2 bytes - DVD ID Error Detection code
  - DvdSectorEdc (85): 4 bytes - DVD Error Detection Code
  - DvdDiscKeyDecrypted (80): 5 bytes - Decrypted DVD title key for the sector

Block Media Tags (BlockMedia only):

- AppleSonyTag (73): 12 bytes - Apple Sony format 12-byte sector tag
- AppleProfileTag (72): 20 bytes - Apple Profile format 20-byte sector tag
- PriamDataTowerTag (74): 24 bytes - Priam DataTower format 24-byte sector tag

Note
  Sector Address Correction:
  - The function automatically adjusts sector addresses based on the negative parameter
  - Negative sectors are adjusted: corrected = sector_address - ctx->userDataDdtHeader.negative
  - Positive sectors are adjusted: corrected = sector_address + ctx->userDataDdtHeader.negative
  - Corrected addresses are used for indexing into tag data arrays
  Track-Based Tags (CdTrackFlags, CdTrackIsrc):
  - These tags are per-track, not per-sector
  - Function searches ctx->trackEntries[] for track containing the sector
  - All sectors within a track return the same track-level metadata
  - Returns AARUF_ERROR_TRACK_NOT_FOUND if sector is outside all tracks
  DVD Sector Tags:
  - DVD sector tags are extracted from the DVD ID field or associated metadata
  - DvdSectorInformation and DvdSectorNumber are derived from ctx->sector_id array
  - Multiple tags may share the same underlying storage (e.g., ID field breakdown)
  - Presence depends on the DVD reading capabilities during imaging
  Buffer Size Querying:
  - Pass buffer as NULL to query the required buffer size without reading data
  - The length parameter will be updated with the exact required size
  - Returns AARUF_ERROR_INCORRECT_DATA_SIZE (not a fatal error in this context)
  - Allows proper buffer allocation before the actual read operation
  Tag Data Storage:
  - Tag data is stored in dedicated context arrays (ctx->sector_subchannel, ctx->sector_cpr_mai, etc.)
  - Each tag type has a specific array with fixed-size entries per sector
  - NULL storage pointer indicates tag was not captured/available
  - Tag data is indexed using the corrected sector address

Warning
  The buffer must be exactly the required size for each tag type. Unlike aaruf_read_sector(), this function enforces strict size matching.
  Tag availability is hardware and media dependent. Always check for AARUF_ERROR_SECTOR_TAG_NOT_PRESENT and handle gracefully.
  Track-based tags (CdTrackFlags, CdTrackIsrc) return the same value for all sectors within a track. Do not assume per-sector uniqueness.
  Some tags contain binary data without string termination (e.g., ISRC). Do not treat tag buffers as null-terminated strings without validation.

Definition at line 1474 of file read.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_INCORRECT_MEDIA_TYPE, AARUF_ERROR_INVALID_TAG, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_SECTOR_OUT_OF_BOUNDS, AARUF_ERROR_SECTOR_TAG_NOT_PRESENT, AARUF_ERROR_TRACK_NOT_FOUND, AARUF_STATUS_OK, AppleProfileTagAaru, AppleSonyTagAaru, BlockMedia, CdSectorSubchannelAaru, CdTrackFlags, CdTrackIsrc, DvdCmi, DvdSectorEdcAaru, DvdSectorIedAaru, DvdSectorInformation, DvdSectorNumber, DvdTitleKeyDecrypted, TracksHeader::entries, FATAL, TrackEntry::flags, aaruformat_context::image_info, TrackEntry::isrc, aaruformat_context::magic, ImageInfo::MetadataMediaType, DdtHeader2::negative, OpticalDisc, DdtHeader2::overflow, PriamDataTowerTagAaru, aaruformat_context::sector_cpr_mai, aaruformat_context::sector_decrypted_title_key, aaruformat_context::sector_edc, aaruformat_context::sector_id, aaruformat_context::sector_ied, aaruformat_context::sector_subchannel, ImageInfo::Sectors, TrackEntry::start, TRACE, aaruformat_context::track_entries, aaruformat_context::tracks_header, and aaruformat_context::user_data_ddt_header.

## ◆ aaruf_read_track_sector()

int32_t aaruf_read_track_sector | ( | void * | context,
|  | uint8_t * | data,
|  | const uint64_t | sector_address,
|  | uint32_t * | length,
|  | const uint8_t | track,
|  | uint8_t * | sector_status )

Reads a sector from a specific track in the AaruFormat image.

Reads user data from the specified sector address within a particular track. This function is specifically designed for optical disc images where sectors are organized by tracks. The sector address is relative to the start of the track. It validates the media type, locates the specified track by sequence number, calculates the absolute sector address, and delegates to aaruf_read_sector().

Parameters

  context | Pointer to the aaruformat context.
  data | Pointer to buffer where sector data will be stored.
  sector_address | The sector address relative to the track start.
  length | Pointer to variable containing buffer size on input, actual data length on output.
  track | The track sequence number to read from.
  sector_status | Pointer to variable that will receive the sector status flags. Must not be NULL. The status indicates the condition of the sector data, such as whether it contains errors, was not dumped, or has other quality indicators from the imaging process.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully read the sector data from the specified track. This is returned when: The context is valid and the media type is OpticalDisc The specified track sequence number exists in the data tracks array The underlying aaruf_read_sector() call succeeds The sector data is successfully retrieved and copied to the output buffer
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_ERROR_INCORRECT_MEDIA_TYPE | (-5) The media is not an optical disc. This occurs when: ctx->imageInfo.XmlMediaType is not OpticalDisc This function is only applicable to CD, DVD, BD, and other optical disc formats
  AARUF_ERROR_TRACK_NOT_FOUND | (-13) The specified track does not exist. This occurs when: No track in ctx->dataTracks[] has a sequence number matching the requested track The track may not contain data or may not have been imaged Only data tracks are searched; audio-only tracks are not included
  All | other error codes from aaruf_read_sector() may be returned: AARUF_STATUS_SECTOR_NOT_DUMPED (1) - Sector was not dumped during imaging AARUF_ERROR_SECTOR_OUT_OF_BOUNDS (-5) - Calculated absolute sector address exceeds image bounds AARUF_ERROR_BUFFER_TOO_SMALL (-10) - Data buffer is NULL or insufficient size AARUF_ERROR_NOT_ENOUGH_MEMORY (-9) - Memory allocation fails during sector reading AARUF_ERROR_CANNOT_READ_HEADER (-6) - Block header cannot be read from image stream AARUF_ERROR_CANNOT_READ_BLOCK (-7) - Block data cannot be read from image stream AARUF_ERROR_CANNOT_DECOMPRESS_BLOCK (-17) - LZMA or FLAC decompression fails AARUF_ERROR_UNSUPPORTED_COMPRESSION (-8) - Block uses unsupported compression

Note
  Track-Relative Addressing:
  - The sector_address parameter is relative to the start of the specified track
  - The function calculates the absolute sector address as: track.start + sector_address
  - Track boundaries are defined by track.start and track.end values
  Data Track Filtering:
  - Only tracks in the ctx->dataTracks[] array are searched
  - Audio-only tracks without data content are not included in this search
  - The track sequence number is the logical track number from the disc TOC
  Function Delegation:
  - This function is a wrapper that performs track validation and address calculation
  - The actual sector reading is performed by aaruf_read_sector()
  - All caching, decompression, and DDT processing occurs in the underlying function

Warning
  This function is only applicable to optical disc media types. Attempting to use it with block media will result in AARUF_ERROR_INCORRECT_MEDIA_TYPE.
  The sector_address is relative to the track start, not the disc start. Ensure correct address calculation when working with multi-track discs.
  Track sequence numbers may not be contiguous. Always verify track existence before assuming a track number is valid.

Definition at line 670 of file read.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_INCORRECT_MEDIA_TYPE, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_TRACK_NOT_FOUND, aaruf_read_sector(), aaruformat_context::data_tracks, FATAL, aaruformat_context::image_info, aaruformat_context::magic, ImageInfo::MetadataMediaType, aaruformat_context::number_of_data_tracks, OpticalDisc, TrackEntry::sequence, TrackEntry::start, and TRACE.

## ◆ aaruf_set_aaru_json_metadata()

int32_t aaruf_set_aaru_json_metadata | ( | void * | context,
|  | uint8_t * | data,
|  | size_t | length )

Sets the Aaru metadata JSON for the image during creation.

Embeds Aaru metadata JSON into the image being created. The Aaru metadata JSON format is a structured, machine-readable representation of comprehensive image metadata including media information, imaging session details, hardware configuration, optical disc tracks and sessions, checksums, and preservation metadata. This function stores the JSON payload in its original form without parsing or validation, allowing callers to provide pre-generated JSON conforming to the Aaru metadata schema. The JSON data will be written to the image file during aaruf_close() as an AaruMetadataJsonBlock.

The function accepts raw UTF-8 encoded JSON data as an opaque byte array and creates an internal copy that persists for the lifetime of the context. If Aaru JSON metadata was previously set on this context, the old data is freed and replaced with the new JSON. The JSON is treated as opaque binary data by the library; no parsing, interpretation, or schema validation is performed during the set operation.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the Aaru metadata JSON data in UTF-8 encoding (opaque byte array). The JSON should conform to the Aaru metadata schema, though this is not validated. Must not be NULL.
  length | Length of the JSON data in bytes. The payload may or may not be null-terminated; the length should reflect the actual JSON data size.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set Aaru metadata JSON. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the JSON data succeeded The JSON data is copied to ctx->jsonBlock The jsonBlockHeader is initialized with identifier AaruMetadataJsonBlock The jsonBlockHeader.length field is set to the provided length Any previous Aaru JSON data is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the JSON data System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Aaru JSON Format and Encoding:
  - The JSON payload must be valid UTF-8 encoded data
  - The payload may or may not be null-terminated
  - The library treats the JSON as opaque binary data
  - No JSON parsing, interpretation, or validation is performed during set
  - Schema compliance is the caller's responsibility
  - Ensure the JSON conforms to the Aaru metadata schema for compatibility
  Aaru Metadata JSON Purpose:
  - Provides machine-readable structured metadata using modern JSON format
  - Includes comprehensive information about media, sessions, tracks, and checksums
  - Enables programmatic access to metadata without XML parsing overhead
  - Documents imaging session details, hardware configuration, and preservation data
  - Used by Aaru and compatible tools for metadata exchange and analysis
  - Complements or serves as alternative to CICM XML metadata
  JSON Content Examples:
  - Media type and physical characteristics
  - Track and session information for optical media
  - Partition and filesystem metadata
  - Checksums (MD5, SHA-1, SHA-256, etc.) for integrity verification
  - Hardware information (drive manufacturer, model, firmware)
  - Imaging software version and configuration
  - Timestamps for image creation and modification
  Memory Management:
  - The function creates an internal copy of the JSON data
  - The caller retains ownership of the input data buffer
  - The caller may free the input data immediately after this function returns
  - The internal copy is freed automatically during aaruf_close()
  - Calling this function multiple times replaces previous JSON data
  Relationship to CICM XML:
  - Both CICM XML and Aaru JSON can be set on the same image
  - CICM XML follows the Canary Islands Computer Museum schema (older format)
  - Aaru JSON follows the Aaru-specific metadata schema (newer format)
  - Setting one does not affect the other
  - Different tools may prefer one format over the other
  - Consider including both for maximum compatibility

Warning
  The Aaru JSON block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted to disk.
  No validation is performed on the JSON data:
  - Invalid JSON syntax will be stored and only detected during parsing
  - Schema violations will not be caught by this function
  - Ensure JSON is valid and schema-compliant before calling
  - Use a JSON validation library before embedding if correctness is critical
  The function accepts any length value:
  - Ensure the length accurately reflects the JSON data size
  - Incorrect length values may cause truncation or include garbage data
  - For null-terminated JSON, length should not include the null terminator unless it is intended to be part of the stored data

See also
  AaruMetadataJsonBlockHeader for the on-disk structure definition.
  aaruf_get_aaru_json_metadata() for retrieving Aaru JSON from opened images.
  write_aaru_json_block() for the serialization process during image closing.

Definition at line 2261 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, AaruMetadataJsonBlock, FATAL, AaruMetadataJsonBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::json_block, aaruformat_context::json_block_header, AaruMetadataJsonBlockHeader::length, aaruformat_context::magic, and TRACE.

## ◆ aaruf_set_comments()

int32_t aaruf_set_comments | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets user comments or notes for the image.

Records arbitrary user-provided comments, notes, or annotations associated with the AaruFormat image. This metadata field allows users to document the image's purpose, provenance, condition, or any other relevant information. Comments are stored in UTF-16LE encoding and can contain multi-line text, special characters, and detailed descriptions.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the comments string data in UTF-16LE encoding (opaque byte array).
  length | Length of the comments data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set comments. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the comments string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The comments data is copied to ctx->imageInfo.Comments The commentsLength field is set in the metadata block header Any previous comments string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the comments string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  UTF-16LE Encoding:
  - The data parameter must contain a valid UTF-16LE encoded string
  - Length must be in bytes, not character count
  - The library treats the data as opaque and does not validate encoding
  - Null termination is not required; length specifies the exact byte count
  Common Uses for Comments:
  - Documentation of image source and creation date
  - Notes about media condition or read errors encountered
  - Preservation metadata and archival notes
  - User annotations for organizing image collections
  - Workflow status or processing history
  Memory Management:
  - The function allocates a new buffer and copies the data
  - If previous comments exist, they are freed before replacement
  - The caller retains ownership of the input data buffer
  - The allocated memory is freed when the context is closed or destroyed

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 609 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::comments, MetadataBlockHeader::commentsLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_creator()

int32_t aaruf_set_creator | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the creator (person/operator) information for the image.

Records the name of the person or operator who created the AaruFormat image. This metadata identifies the individual responsible for the imaging process, which is valuable for provenance tracking, accountability, and understanding the human context in which the image was created. The creator name is stored in UTF-16LE encoding and preserved exactly as provided by the caller.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the creator name string data in UTF-16LE encoding (opaque byte array).
  length | Length of the creator data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set creator information. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the creator string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The creator data is copied to ctx->imageInfo.Creator The creatorLength field is set in the metadata block header Any previous creator string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the creator string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  UTF-16LE Encoding:
  - The data parameter must contain a valid UTF-16LE encoded string
  - Length must be in bytes, not character count (UTF-16LE uses 2 or 4 bytes per character)
  - The library treats the data as opaque and does not validate UTF-16LE encoding
  - Null termination is not required; length specifies the exact byte count
  - Ensure even byte lengths to maintain UTF-16LE character alignment
  Creator Name Format:
  - Typically contains the full name of the person who created the image
  - May include titles, credentials, or institutional affiliations
  - Common formats: "John Smith", "Dr. Jane Doe", "Smith, John (Archivist)"
  - Should identify the individual operator, not the software used
  - May include contact information or employee/operator ID in institutional settings
  Provenance and Accountability:
  - Identifies who performed the imaging operation
  - Important for establishing chain of custody in forensic contexts
  - Provides contact point for questions about the imaging process
  - Supports institutional recordkeeping and quality assurance
  - May be required for compliance with archival standards
  Privacy Considerations:
  - Consider privacy implications when recording personal names
  - Some organizations may use operator IDs instead of full names
  - Institutional policies may govern what personal information is recorded
  - GDPR and similar regulations may apply in some jurisdictions
  Memory Management:
  - The function allocates a new buffer and copies the data
  - If a previous creator string exists, it is freed before replacement
  - The caller retains ownership of the input data buffer
  - The allocated memory is freed when the context is closed or destroyed
  Metadata Block Initialization:
  - If the metadata block header is not yet initialized, this function initializes it
  - The metadataBlockHeader.identifier is set to MetadataBlock automatically
  - Multiple metadata setter functions can be called to build complete metadata

Warning
  The data buffer must remain valid for the duration of this function call. After the function returns, the caller may free or reuse the data buffer.
  Invalid UTF-16LE encoding may cause issues when reading the metadata:
  - The library does not validate UTF-16LE correctness
  - Malformed strings may display incorrectly or cause decoding errors
  - Ensure the data is properly encoded before calling this function
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 495 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::creator, MetadataBlockHeader::creatorLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_drive_firmware_revision()

int32_t aaruf_set_drive_firmware_revision | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the drive firmware revision for the image.

Records the firmware version or revision of the drive or device used to read or write the physical storage media. Firmware revisions can significantly affect drive behavior, error handling, performance, and compatibility. This metadata is crucial for understanding the imaging environment, troubleshooting issues, and ensuring reproducibility. Different firmware versions of the same drive model can behave quite differently, making this information essential for comprehensive documentation. The firmware revision is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the drive firmware revision string data in UTF-16LE encoding (opaque byte array).
  length | Length of the drive firmware revision data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set drive firmware revision. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the drive firmware revision string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The drive firmware revision data is copied to ctx->imageInfo.DriveFirmwareRevision The driveFirmwareRevisionLength field is set in the metadata block header Any previous drive firmware revision string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the drive firmware revision string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Firmware Revision Examples:
  - Optical drives: "1.07", "1.00a", "VER A302"
  - Tape drives: "B8S1", "7760", "V4.0"
  - Hard drives: "CC45", "80.00A80", "HPG9"
  - Format varies by manufacturer and device type
  Firmware Impact on Imaging:
  - Different firmware versions may have different error recovery strategies
  - Bug fixes in newer firmware can improve read reliability
  - Some firmware versions have known issues with specific media types
  - Performance characteristics may vary between firmware revisions
  - Firmware can affect features like C2 error reporting on optical drives
  Troubleshooting and Support:
  - Essential for diagnosing drive-specific problems
  - Manufacturer support often requires firmware version information
  - Helps identify if issues are resolved in newer firmware
  - Enables correlation of problems with known firmware bugs
  - Supports decision-making about firmware updates
  Reproducibility and Documentation:
  - Complete environment documentation for scientific reproducibility
  - Important for forensic work requiring detailed equipment records
  - Helps explain variations in imaging results over time
  - Supports compliance with archival and preservation standards
  - Enables future researchers to understand imaging conditions
  Historical Tracking:
  - Documents firmware changes over the life of imaging equipment
  - Helps assess impact of firmware updates on imaging quality
  - Useful for long-term archival projects spanning years
  - Aids in understanding evolution of drive technology

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.
  Firmware revisions are device-specific and format varies widely:
  - No standard format exists across manufacturers
  - May include letters, numbers, dots, or other characters
  - Should be recorded exactly as reported by the device

Definition at line 1795 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::drive_firmware_revision, MetadataBlockHeader::driveFirmwareRevisionLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_drive_manufacturer()

int32_t aaruf_set_drive_manufacturer | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the drive manufacturer information for the image.

Records the name of the company that manufactured the drive or device used to read or write the physical storage media. This metadata provides valuable context about the imaging process, as different drives may have different capabilities, error handling characteristics, and compatibility with specific media types. The manufacturer name is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the drive manufacturer string data in UTF-16LE encoding (opaque byte array).
  length | Length of the drive manufacturer data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set drive manufacturer. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the drive manufacturer string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The drive manufacturer data is copied to ctx->imageInfo.DriveManufacturer The driveManufacturerLength field is set in the metadata block header Any previous drive manufacturer string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the drive manufacturer string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Common Drive Manufacturers:
  - Optical drives: Pioneer, Plextor, LG, ASUS, Sony, Samsung
  - Tape drives: HP, IBM, Quantum, Tandberg, Exabyte
  - Hard drives: Seagate, Western Digital, Hitachi, Toshiba
  - Floppy drives: Teac, Panasonic, Mitsumi, Sony
  Imaging Context and Quality:
  - Different manufacturers have varying error recovery capabilities
  - Some drives are better suited for archival-quality imaging
  - Plextor drives were historically preferred for optical disc preservation
  - Professional-grade drives often have better read accuracy
  - Important for understanding potential limitations in the imaging process
  Forensic and Provenance Value:
  - Documents the complete imaging environment
  - Helps assess reliability and trustworthiness of the image
  - Useful for troubleshooting or reproducing imaging results
  - May be required for forensic chain of custody
  - Supports quality assurance and validation processes

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 1414 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::drive_manufacturer, MetadataBlockHeader::driveManufacturerLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_drive_model()

int32_t aaruf_set_drive_model | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the drive model information for the image.

Records the specific model or product designation of the drive or device used to read or write the physical storage media. This metadata provides detailed information about the imaging equipment, which can be important for understanding the capabilities, limitations, and characteristics of the imaging process. Different drive models within the same manufacturer's product line may have significantly different features and performance characteristics. The model information is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the drive model string data in UTF-16LE encoding (opaque byte array).
  length | Length of the drive model data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set drive model. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the drive model string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The drive model data is copied to ctx->imageInfo.DriveModel The driveModelLength field is set in the metadata block header Any previous drive model string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the drive model string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Drive Model Examples:
  - Optical drives: "DVR-111D" (Pioneer), "PX-716A" (Plextor), "GH24NSB0" (LG)
  - Tape drives: "Ultrium 7-SCSI" (HP), "TS1140" (IBM), "SDLT600" (Quantum)
  - Hard drives: "ST2000DM008" (Seagate), "WD40EZRZ" (Western Digital)
  - Floppy drives: "FD-235HF" (Teac), "JU-257A633P" (Panasonic)
  Model-Specific Characteristics:
  - Different models may have different error correction algorithms
  - Some models are known for superior read quality (e.g., Plextor Premium)
  - Certain models may have bugs or quirks in specific firmware versions
  - Professional models often have features not available in consumer versions
  - Important for reproducing imaging conditions or troubleshooting issues
  Forensic Documentation:
  - Complete drive identification aids in forensic reporting
  - Helps establish the reliability of the imaging process
  - May be required for compliance with forensic standards
  - Supports validation and verification procedures
  - Enables assessment of tool suitability for the imaging task
  Historical and Research Value:
  - Documents evolution of imaging technology over time
  - Helps identify best practices for specific media types
  - Useful for academic research on digital preservation
  - Aids in understanding drive availability and obsolescence

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 1536 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::drive_model, MetadataBlockHeader::driveModelLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_drive_serial_number()

int32_t aaruf_set_drive_serial_number | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the drive serial number for the image.

Records the unique serial number of the drive or device used to read or write the physical storage media. This metadata provides a unique identifier for the specific piece of hardware used in the imaging process, which is particularly important for forensic work, equipment tracking, and quality assurance. The serial number enables correlation between multiple images created with the same drive and can help identify drive-specific issues or characteristics. The serial number is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the drive serial number string data in UTF-16LE encoding (opaque byte array).
  length | Length of the drive serial number data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set drive serial number. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the drive serial number string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The drive serial number data is copied to ctx->imageInfo.DriveSerialNumber The driveSerialNumberLength field is set in the metadata block header Any previous drive serial number string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the drive serial number string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Serial Number Sources:
  - Hard drives and SSDs: Retrieved via ATA/SCSI IDENTIFY commands
  - Optical drives: Available through SCSI inquiry or ATA identify
  - Tape drives: Typically reported via SCSI inquiry data
  - USB devices: May have USB serial numbers or internal device serials
  - Some older or consumer devices may not report serial numbers
  Forensic Applications:
  - Critical for forensic chain of custody documentation
  - Uniquely identifies the specific hardware used for imaging
  - Enables tracking of drive calibration and maintenance history
  - Supports correlation of images created with the same equipment
  - May be required by forensic standards and best practices
  Equipment Management:
  - Helps track drive usage and workload for maintenance planning
  - Enables identification of drives requiring replacement or service
  - Supports equipment inventory and asset management systems
  - Useful for identifying drives with known issues or recalls
  - Facilitates warranty and support claim processing
  Quality Assurance:
  - Enables analysis of drive-specific error patterns
  - Helps identify if multiple imaging issues stem from the same drive
  - Supports statistical quality control processes
  - Aids in evaluating drive reliability over time
  - Can reveal degradation or calibration drift in aging hardware

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 1660 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::drive_serial_number, MetadataBlockHeader::driveSerialNumberLength, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_dumphw()

int32_t aaruf_set_dumphw | ( | void * | context,
|  | uint8_t * | data,
|  | size_t | length )

Sets the dump hardware block for the image during creation.

Embeds dump hardware information into the image being created. The dump hardware block documents the hardware and software environments used to create the image, recording one or more "dump environments" – typically combinations of physical devices (drives, controllers, adapters) and the software stacks that performed the read operations. This metadata is essential for understanding the imaging context, validating acquisition integrity, reproducing imaging conditions, and supporting forensic or archival documentation requirements.

Each environment entry includes hardware identification (manufacturer, model, revision, firmware, serial number), software identification (name, version, operating system), and optional extent ranges that specify which logical sectors or units were contributed by that particular environment. This structure supports complex imaging scenarios where multiple devices or software configurations were used to create a composite image.

The function accepts a complete, pre-serialized DumpHardwareBlock in the on-disk binary format (as returned by aaruf_get_dumphw() or manually constructed). The block is validated for correct identifier, length consistency, and CRC64 integrity before being parsed and stored in the context. The function deserializes the binary block, extracts all entries with their variable-length UTF-8 strings and extent arrays, and creates null-terminated in-memory copies for internal use.

Validation performed:

1. Context validation (non-NULL, correct magic, write mode)
2. Data buffer validation (non-NULL, non-zero length)
3. Block identifier validation (must be DumpHardwareBlock)
4. Length consistency (buffer length must equal sizeof(DumpHardwareHeader) + header.length)
5. CRC64 integrity verification (calculated CRC64 must match header.crc64)

Parsing process:

1. Read and validate the DumpHardwareHeader from the buffer
2. Allocate array for all dump hardware entries
3. For each entry:
   - Read the DumpHardwareEntry structure (36 bytes)
   - Allocate and copy each non-empty UTF-8 string with +1 byte for null terminator
   - Allocate and copy the DumpExtent array if extents > 0
4. Free any previously set dump hardware data
5. Store the new parsed data in ctx->dumpHardwareEntriesWithData
6. Store the header in ctx->dumpHardwareHeader

Memory management: If any memory allocation fails during parsing, all previously allocated memory for the new data is freed via the free_copy_and_error label, and AARUF_ERROR_NOT_ENOUGH_MEMORY is returned. Any existing dump hardware data in the context is freed before storing new data, ensuring no memory leaks when replacing dump hardware information.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the dump hardware block data in on-disk binary format. Must contain a complete DumpHardwareBlock starting with DumpHardwareHeader followed by all entries, strings, and extent arrays. Must not be NULL.
  length | Length of the dump hardware block data in bytes. Must equal sizeof(DumpHardwareHeader) + header.length for validation to succeed.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set dump hardware block. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) The data buffer contains a valid DumpHardwareBlock The block identifier is DumpHardwareBlock The length is consistent (buffer length == header size + payload length) The CRC64 checksum is valid All memory allocations succeeded All entries with strings and extents are parsed and stored Any previous dump hardware data is freed ctx->dumpHardwareEntriesWithData is populated with parsed entries ctx->dumpHardwareHeader is updated with the new header
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_CANNOT_READ_BLOCK | (-6) Invalid block identifier. This occurs when: The identifier field in the DumpHardwareHeader doesn't equal DumpHardwareBlock The data buffer doesn't contain a valid dump hardware block The block type is incorrect or corrupted
  AARUF_ERROR_INCORRECT_DATA_SIZE | (-11) Invalid data or length. This occurs when: The data parameter is NULL The length parameter is 0 (empty block) The buffer length doesn't match sizeof(DumpHardwareHeader) + header.length Length inconsistency indicates corrupted or incomplete block data
  AARUF_ERROR_INVALID_BLOCK_CRC | (-10) CRC64 checksum mismatch. This occurs when: The calculated CRC64 over the payload doesn't match header.crc64 Block data is corrupted or tampered with Block was not properly constructed or serialized
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-8) Memory allocation failed. This occurs when: calloc() or malloc() failed to allocate memory for entries array Failed to allocate memory for any string field (manufacturer, model, etc.) Failed to allocate memory for extent arrays System is out of memory or memory is severely fragmented All partially allocated memory is freed before returning

Note
  Dump Hardware Block Format:
  - The data buffer must contain a complete serialized DumpHardwareBlock
  - Format: DumpHardwareHeader + repeated entries with strings and extents
  - All strings are UTF-8 encoded and NOT null-terminated in the buffer
  - The function adds null terminators when copying strings to internal storage
  - String lengths are in bytes, not character counts
  Creating Block Data:
  - Use aaruf_get_dumphw() to retrieve a block from an existing image
  - Manually construct by serializing DumpHardwareHeader, entries, strings, and extents
  - Calculate CRC64-ECMA over the payload (everything after the header)
  - Ensure all length fields accurately reflect the data sizes
  - Ensure total buffer size equals sizeof(DumpHardwareHeader) + payload length
  Hardware Identification Fields:
  - manufacturer: Device manufacturer (e.g., "Plextor", "Sony", "Samsung")
  - model: Device model number (e.g., "PX-716A", "DRU-820A")
  - revision: Hardware revision identifier
  - firmware: Firmware version (e.g., "1.11", "KY08")
  - serial: Device serial number for unique identification
  Software Identification Fields:
  - softwareName: Dumping software name (e.g., "Aaru", "ddrescue", "IsoBuster")
  - softwareVersion: Software version (e.g., "5.3.0", "1.25")
  - softwareOperatingSystem: Host OS (e.g., "Linux 5.10.0", "Windows 10", "macOS 12.0")
  Extent Arrays:
  - Each DumpExtent specifies a [start, end] logical sector range
  - Extents indicate which sectors this environment contributed
  - Empty extent arrays (extents == 0) mean the environment dumped entire medium
  - Extents are stored in the order provided in the input buffer
  Memory Ownership:
  - The function creates internal copies of all data
  - The caller retains ownership of the input data buffer
  - The caller may free the input buffer immediately after this function returns
  - Internal copies are freed during aaruf_close() or when replaced by another call
  Replacing Existing Data:
  - Calling this function multiple times replaces previous dump hardware data
  - All previous entries, strings, and extents are freed before storing new data
  - No memory leaks occur when updating dump hardware information

Warning
  The dump hardware block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted to disk.
  CRC64 validation protects against corrupted blocks, but construction errors in the input buffer (incorrect lengths, misaligned data) may cause parsing to fail or produce incorrect results even with a valid checksum.
  The function assumes the input buffer is properly formatted and packed according to the DumpHardwareBlock specification. Malformed input may cause crashes or memory corruption.

See also
  DumpHardwareHeader for the block header structure definition.
  DumpHardwareEntry for the per-environment entry structure definition.
  DumpExtent for the extent range structure definition.
  aaruf_get_dumphw() for retrieving dump hardware from opened images.
  write_dumphw_block() for the serialization process during image closing.

Definition at line 531 of file dump.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_crc64_data(), AARUF_ERROR_CANNOT_READ_BLOCK, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_INVALID_BLOCK_CRC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, compare_extents(), COPY_STRING_FIELD, DumpHardwareHeader::crc64, aaruformat_context::dump_hardware_entries_with_data, aaruformat_context::dump_hardware_header, DumpHardwareBlock, DumpHardwareHeader::entries, DumpHardwareEntriesWithData::entry, DumpHardwareEntriesWithData::extents, DumpHardwareEntry::extents, FATAL, free_dump_hardware_entries(), DumpHardwareHeader::identifier, aaruformat_context::is_writing, DumpHardwareHeader::length, aaruformat_context::magic, and TRACE.

## ◆ aaruf_set_geometry()

int32_t aaruf_set_geometry | ( | void * | context,
|  | const uint32_t | cylinders,
|  | const uint32_t | heads,
|  | const uint32_t | sectors_per_track )

Sets the logical CHS geometry for the AaruFormat image.

Configures the Cylinder-Head-Sector (CHS) geometry information for the image being created or modified. This function populates both the geometry block (used for storage in the image file) and the image information structure (used for runtime calculations). The geometry block contains legacy-style logical addressing parameters that describe how the storage medium should be logically organized in terms of cylinders, heads (tracks per cylinder), and sectors per track. This information is crucial for creating images that will be used with software requiring CHS addressing or for accurately preserving the original medium's logical structure.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  cylinders | The number of cylinders to set for the geometry.
  heads | The number of heads (tracks per cylinder) to set for the geometry.
  sectors_per_track | The number of sectors per track to set for the geometry.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set geometry information. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) The geometry block identifier is set to GeometryBlock The geometry block fields (cylinders, heads, sectorsPerTrack) are updated The image info fields (Cylinders, Heads, SectorsPerTrack) are synchronized All parameters are stored for subsequent write operations
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image

Note
  Dual Storage:
  - Geometry is stored in two locations within the context:
    1. ctx->geometryBlock: Written to the image file as a GeometryBlock during close
    2. ctx->imageInfo: Used for runtime calculations and metadata queries
  - Both locations are kept synchronized by this function
  Geometry Calculation:
  - Total logical sectors = cylinders × heads × sectors_per_track
  - Ensure the product matches the actual sector count in the image
  - Mismatched geometry may cause issues with legacy software or emulators
  - Sector size is separate and should be set via other API calls
  CHS Addressing Requirements:
  - Required for images intended for legacy BIOS or MBR partition schemes
  - Essential for floppy disk images and older hard disk images
  - May be optional or synthetic for modern large-capacity drives
  - Some virtualization platforms require valid CHS geometry
  Parameter Constraints:
  - No validation is performed on the geometry values
  - Zero values are technically accepted but may cause issues
  - Extremely large values may overflow in calculations (cylinders × heads × sectors_per_track)
  - Common constraints for legacy systems:
    - Cylinders: typically 1-1024 for BIOS, up to 65535 for modern systems
    - Heads: typically 1-255 for most systems
    - Sectors per track: typically 1-63 for BIOS, up to 255 for modern systems
  Write Mode Requirement:
  - This function is intended for use during image creation
  - Should be called after aaruf_create() and before writing sector data
  - The geometry block is serialized during aaruf_close()
  - Must be used with a write-enabled context
  Historical Context:
  - CHS geometry was the original addressing scheme for disk drives
  - Physical CHS reflected actual disk platters, heads, and sector layout
  - Logical CHS often differs from physical due to zone-bit recording and translation
  - Modern drives use LBA (Logical Block Addressing) internally

Warning
  This function does not validate geometry consistency:
  - Does not check if cylinders × heads × sectors_per_track equals image sector count
  - Does not prevent overflow in the multiplication
  - Caller must ensure geometry values are appropriate for the medium type
  - Invalid geometry may cause boot failures or data access issues
  The geometry block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.
  Changing geometry after writing sector data may create inconsistencies. Set geometry before beginning sector write operations for best results.
  Some image formats and use cases don't require CHS geometry:
  - Optical media (CD/DVD/BD) use different addressing schemes
  - Modern GPT-partitioned disks don't rely on CHS
  - Flash-based storage typically doesn't have meaningful CHS geometry
  - Setting geometry for such media types is harmless but unnecessary

Definition at line 230 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, aaruformat_context::cylinders, GeometryBlockHeader::cylinders, FATAL, aaruformat_context::geometry_block, GeometryBlock, aaruformat_context::heads, GeometryBlockHeader::heads, GeometryBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::sectors_per_track, GeometryBlockHeader::sectorsPerTrack, and TRACE.

## ◆ aaruf_set_media_barcode()

int32_t aaruf_set_media_barcode | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the media barcode information for the image.

Records the barcode affixed to the physical storage media or its packaging. Barcodes are commonly used in professional archival and library environments for automated inventory management, tracking, and retrieval systems. This metadata enables correlation between physical media location systems and digital image files. The barcode is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the media barcode string data in UTF-16LE encoding (opaque byte array).
  length | Length of the media barcode data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set media barcode. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the media barcode string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The media barcode data is copied to ctx->imageInfo.MediaBarcode The mediaBarcodeLength field is set in the metadata block header Any previous media barcode string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the media barcode string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Common Barcode Uses:
  - Library and archival tape management systems
  - Automated tape library robotics (e.g., LTO tape cartridges)
  - Inventory tracking in large media collections
  - Asset management in corporate or institutional settings
  - Chain of custody tracking in forensic environments
  Barcode Types and Formats:
  - Code 39 and Code 128 are common for media labeling
  - LTO tapes use specific 6 or 8-character barcode formats
  - May include library-specific prefixes or location codes
  - Some systems use 2D barcodes (QR codes, Data Matrix)
  - Barcode should be recorded exactly as it appears
  Integration with Physical Systems:
  - Enables automated correlation between physical and digital catalogs
  - Supports robotic tape library operations
  - Facilitates retrieval from off-site storage facilities
  - Links to broader asset management databases
  - Critical for large-scale archival operations
  Preservation Context:
  - Important for long-term archival planning
  - Helps maintain inventory accuracy over time
  - Supports audit and compliance requirements
  - Enables efficient physical media location and retrieval

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 1178 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::media_barcode, MetadataBlockHeader::mediaBarcodeLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_media_manufacturer()

int32_t aaruf_set_media_manufacturer | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the media manufacturer information for the image.

Records the name of the company that manufactured the physical storage media. This metadata is valuable for preservation and forensic purposes, as it can help identify the media type, quality characteristics, and manufacturing period. The manufacturer name is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the media manufacturer string data in UTF-16LE encoding (opaque byte array).
  length | Length of the media manufacturer data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set media manufacturer. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the media manufacturer string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The media manufacturer data is copied to ctx->imageInfo.MediaManufacturer The mediaManufacturerLength field is set in the metadata block header Any previous media manufacturer string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the media manufacturer string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Common Media Manufacturers:
  - Optical discs: Verbatim, Sony, Maxell, TDK, Taiyo Yuden
  - Magnetic tapes: Fujifilm, Maxell, Sony, IBM
  - Floppy disks: 3M, Maxell, Sony, Verbatim
  - Flash media: SanDisk, Kingston, Samsung
  Identification Methods:
  - May be printed on the media surface or packaging
  - Can sometimes be detected from media ID codes (e.g., ATIP for CD-R)
  - Historical records or catalogs may provide this information
  - Important for understanding media quality and longevity characteristics
  Preservation Value:
  - Helps assess expected media lifespan and degradation patterns
  - Useful for identifying counterfeit or remarked media
  - Aids in research about media quality and failure modes
  - Provides context for archival planning and migration strategies

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 834 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::media_manufacturer, MetadataBlockHeader::mediaManufacturerLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_media_model()

int32_t aaruf_set_media_model | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the media model or product designation for the image.

Records the specific model, product line, or type designation of the physical storage media. This is more specific than the manufacturer and identifies the exact product variant. This metadata helps in identifying specific media characteristics, performance specifications, and compatibility information. The model information is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the media model string data in UTF-16LE encoding (opaque byte array).
  length | Length of the media model data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set media model. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the media model string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The media model data is copied to ctx->imageInfo.MediaModel The mediaModelLength field is set in the metadata block header Any previous media model string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the media model string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Model Designation Examples:
  - Optical discs: "DVD+R 16x", "CD-R 80min", "BD-R DL 50GB"
  - Tapes: "LTO-7", "DLT-IV", "AIT-3"
  - Floppy disks: "HD 1.44MB", "DD 720KB"
  - Flash cards: "SDHC Class 10", "CompactFlash 1000x"
  Model Information Usage:
  - Identifies specific capacity and speed ratings
  - Indicates format compatibility (e.g., DVD-R vs DVD+R)
  - Helps determine recording characteristics and quality tier
  - Useful for matching replacement media or troubleshooting issues

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 941 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::media_model, MetadataBlockHeader::mediaModelLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_media_part_number()

int32_t aaruf_set_media_part_number | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the media part number or model designation for the image.

Records the manufacturer's part number or catalog designation for the specific type of physical storage media. This is distinct from the media model in that it represents the exact ordering or catalog number used for procurement and inventory purposes. Part numbers are particularly important for sourcing compatible replacement media and for precise identification in technical documentation. The part number is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the media part number string data in UTF-16LE encoding (opaque byte array).
  length | Length of the media part number data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set media part number. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the media part number string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The media part number data is copied to ctx->imageInfo.MediaPartNumber The mediaPartNumberLength field is set in the metadata block header Any previous media part number string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the media part number string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Part Number Examples:
  - Optical media: "MR-25332" (Verbatim DVD+R), "CDR80JC" (Sony CD-R)
  - Tape media: "C7973A" (HP LTO-3), "TK88" (Maxell DLT-IV)
  - Floppy disks: "MF2HD" (3.5" high-density), "2D" (5.25" double-density)
  - May include regional variations or packaging size indicators
  Practical Applications:
  - Procurement and ordering of compatible replacement media
  - Cross-referencing with manufacturer specifications and datasheets
  - Identifying specific product revisions or manufacturing batches
  - Ensuring compatibility for archival media migration projects
  - Tracking costs and suppliers in institutional settings
  Relationship to Model:
  - Part number is more specific than model designation
  - Model might be "DVD+R 16x", part number "MR-25332"
  - Part numbers may vary by region, packaging quantity, or color
  - Critical for exact product identification in catalogs and databases
  Documentation and Compliance:
  - Useful for creating detailed preservation documentation
  - Supports compliance with archival standards and best practices
  - Enables precise replication of archival environments
  - Facilitates research on media types and failure modes

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 1299 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::media_part_number, MetadataBlockHeader::mediaPartNumberLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_media_sequence()

int32_t aaruf_set_media_sequence | ( | void * | context,
|  | const int32_t | sequence,
|  | const int32_t | last_sequence )

Sets the media sequence information for multi-volume media sets.

Configures the sequence numbering for media that is part of a larger set, such as multi-disk software distributions, backup sets spanning multiple tapes, or optical disc sets. This function records both the current media's position in the sequence and the total number of media in the complete set. This metadata is essential for proper ordering and completeness verification when working with multi-volume archives.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  sequence | The sequence number of this media (1-based index indicating position in the set).
  last_sequence | The total number of media in the complete set (indicates the final sequence number).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set media sequence information. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) The metadata block header is initialized (identifier set to MetadataBlock) The mediaSequence field is set to the provided sequence value The lastMediaSequence field is set to the provided last_sequence value Both values are stored for serialization during image close
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image

Note
  Sequence Numbering:
  - Sequence numbers are typically 1-based (first disc is 1, not 0)
  - The sequence parameter should be in the range [1, last_sequence]
  - last_sequence indicates the total count of media in the set
  - Example: For a 3-disc set, disc 2 would have sequence=2, last_sequence=3
  Common Use Cases:
  - Multi-CD/DVD software installations (e.g., "Disc 2 of 4")
  - Backup tape sets spanning multiple volumes
  - Split archive formats requiring sequential processing
  - Multi-floppy disk software distributions
  - Large data sets divided across multiple optical discs
  Metadata Block Initialization:
  - If the metadata block header is not yet initialized, this function initializes it
  - The metadataBlockHeader.identifier is set to MetadataBlock automatically
  - Multiple metadata setter functions can be called to build complete metadata
  - All metadata is written to the image file during aaruf_close()
  Single Media Images:
  - For standalone media not part of a set, use sequence=1, last_sequence=1
  - Setting both values to 0 may be used to indicate "not part of a sequence"
  - The function does not validate that sequence <= last_sequence
  Parameter Validation:
  - No validation is performed on sequence numbers
  - Negative values are accepted but may be semantically incorrect
  - sequence > last_sequence is not prevented but indicates an error condition
  - Callers should ensure sequence and last_sequence are logically consistent
  Archive Integrity:
  - Proper sequence metadata is crucial for multi-volume restoration
  - Archival software may refuse to extract if sequence information is incorrect
  - Missing volumes can be detected by checking sequence completeness
  - Helps prevent data loss from incomplete multi-volume sets
  Historical Context:
  - Multi-volume sets were common in the floppy disk era due to size constraints
  - CD/DVD sets were used for large software distributions (operating systems, games)
  - Tape backup systems still use multi-volume sets for large archives
  - Modern optical media (BD-R DL) reduced the need for multi-disc sets

Warning
  This function does not validate the logical consistency of sequence numbers:
  - Does not check if sequence <= last_sequence
  - Does not prevent negative or zero values if semantically inappropriate
  - Caller must ensure values represent a valid sequence relationship
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.
  Incorrect sequence information may prevent proper reconstruction:
  - Software relying on sequence numbers may fail to recognize media order
  - Archival systems may incorrectly report missing volumes
  - Restoration processes may fail if sequence is inconsistent

Definition at line 364 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, MetadataBlockHeader::lastMediaSequence, aaruformat_context::magic, MetadataBlockHeader::mediaSequence, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_media_serial_number()

int32_t aaruf_set_media_serial_number | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the media serial number for the image.

Records the unique serial number assigned to the physical storage media by the manufacturer. This metadata provides a unique identifier for the specific piece of media, which is invaluable for tracking, authentication, and forensic analysis. Not all media types have serial numbers; this is most common with professional-grade media and some consumer optical discs. The serial number is stored in UTF-16LE encoding.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the media serial number string data in UTF-16LE encoding (opaque byte array).
  length | Length of the media serial number data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set media serial number. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the media serial number string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The media serial number data is copied to ctx->imageInfo.MediaSerialNumber The mediaSerialNumberLength field is set in the metadata block header Any previous media serial number string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the media serial number string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Serial Number Availability:
  - Professional tape media (LTO, DLT, etc.) typically have printed serial numbers
  - Some optical discs have embedded media IDs that can serve as serial numbers
  - Hard drives and SSDs have electronically-readable serial numbers
  - Consumer recordable media (CD-R, DVD-R) rarely have unique serial numbers
  - May be printed on labels, hubs, or cartridge shells
  Forensic and Archival Importance:
  - Uniquely identifies the specific physical media instance
  - Critical for chain of custody in forensic investigations
  - Enables tracking of media throughout its lifecycle
  - Helps prevent mix-ups in large media collections
  - Can verify authenticity and detect counterfeits
  Format Considerations:
  - Serial numbers may be alphanumeric, numeric, or contain special characters
  - Format varies widely between manufacturers and media types
  - May include check digits or formatting separators
  - Should be recorded exactly as it appears on the media

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 1056 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::media_serial_number, MetadataBlockHeader::mediaSerialNumberLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_media_title()

int32_t aaruf_set_media_title | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | length )

Sets the media title or label for the image.

Records the title, label, or name printed or written on the physical storage media. This metadata is particularly useful for identifying discs, tapes, or other media that have user-applied labels or manufacturer-printed titles. The title is stored in UTF-16LE encoding to support international characters and special symbols.

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  data | Pointer to the media title string data in UTF-16LE encoding (opaque byte array).
  length | Length of the media title data in bytes (must include full UTF-16LE character sequences).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully set media title. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) Memory allocation for the media title string succeeded The metadata block header is initialized (identifier set to MetadataBlock) The media title data is copied to ctx->imageInfo.MediaTitle The mediaTitleLength field is set in the metadata block header Any previous media title string is properly freed before replacement
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: malloc() failed to allocate the required memory for the media title string System is out of memory or memory is severely fragmented The requested allocation size is too large

Note
  Common Media Title Examples:
  - Handwritten labels on optical discs or tapes
  - Pre-printed software names on distribution media (e.g., "Windows 95 Setup Disk 1")
  - Volume labels or disc names (e.g., "BACKUP_2024", "INSTALL_CD")
  - Game titles printed on cartridges or discs
  - Album or movie titles on multimedia discs
  Preservation Context:
  - Important for archival purposes to record exactly what appears on the media
  - Helps identify media in large collections
  - May differ from filesystem volume labels
  - Useful for matching physical media to digital images
  UTF-16LE Encoding:
  - The data parameter must contain a valid UTF-16LE encoded string
  - Length must be in bytes, not character count
  - Supports international characters, emoji, and special symbols
  - Null termination is not required; length specifies the exact byte count

Warning
  The metadata block is only written to the image file during aaruf_close(). Changes made by this function are not immediately persisted.

Definition at line 722 of file metadata.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, MetadataBlockHeader::identifier, aaruformat_context::is_writing, aaruformat_context::magic, aaruformat_context::media_title, MetadataBlockHeader::mediaTitleLength, aaruformat_context::metadata_block_header, MetadataBlock, and TRACE.

## ◆ aaruf_set_tape_file()

int32_t aaruf_set_tape_file | ( | void * | context,
|  | const uint8_t | partition,
|  | const uint32_t | file,
|  | const uint64_t | starting_block,
|  | const uint64_t | ending_block )

Sets or updates the block range for a specific tape file in an Aaru tape image.

Creates or modifies a tape file entry in the context's hash table, defining the logical file's extent on the tape medium by its partition number, file number, and block range. This function is the write-mode counterpart to aaruf_get_tape_file() and is used when creating or modifying tape images to establish the file structure metadata.

Tape File Registration: When writing a tape image, this function should be called for each logical file to register its location. Each file is uniquely identified by:

- Partition number (8-bit): The tape partition containing the file
- File number (32-bit): The sequential file number within that partition

These values are combined into a 64-bit composite key: key = (partition << 32) | file_number

The file entry (including the block range) is then stored in the context's tapeFiles hash table and will be written to the image's TapeFileBlock during finalization.

Block Range Definition: The block range [starting_block, ending_block] defines the file's extent:

- starting_block: The first block address where the file begins (inclusive)
- ending_block: The final block address where the file ends (inclusive)
- Block count: (ending_block - starting_block + 1)

Block addresses must be absolute positions within the tape image's logical block space. The caller is responsible for ensuring:

- starting_block <= ending_block (no validation is performed)
- Block ranges don't conflict with other files (no validation is performed)
- All blocks in the range have been or will be written to the image

Typical Usage Flow:

1. Open or create an Aaru tape image with write access
2. Write the file's data blocks to the image
3. Call aaruf_set_tape_file() to register the file's block range
4. Repeat for all files on the tape
5. Close the image (TapeFileBlock will be written during finalization)

Update/Replace Behavior: If a file entry with the same partition/file combination already exists:

- The old entry is automatically freed
- The new entry replaces it in the hash table
- A TRACE message indicates the replacement

This allows updating file metadata or correcting errors without manual deletion.

Error Handling: The function performs validation in the following order:

1. Context pointer validation (NULL check)
2. Magic number verification (ensures valid aaruformat context)
3. Write mode verification (ensures image is opened for writing)
4. Memory allocation for the hash entry

If any validation fails, an appropriate error code is returned and no modifications are made to the context's tape file table.

Thread Safety: This function modifies the shared context's hash table and is NOT thread-safe. Concurrent calls to aaruf_set_tape_file() or other functions that modify ctx->tapeFiles may result in data corruption or memory leaks. The caller must ensure exclusive access through external synchronization if needed.

Memory Management:

- Allocates a new hash table entry (tapeFileHashEntry) for each call
- HASH_REPLACE automatically frees replaced entries
- All hash entries are freed when the context is closed
- On allocation failure, no entry is added and an error is returned

Performance Characteristics:

- Hash table insertion/replacement: O(1) average case
- No I/O operations performed (metadata written during image close)
- Minimal stack usage
- Suitable for bulk file registration operations

Parameters

  context | Pointer to an initialized aaruformat context. Must not be NULL. The context must have been opened with write access (isWriting=true). The context's tapeFiles hash table will be updated with the new entry.
  partition | The partition number (0-255) where the file is located. For single-partition tapes, this is typically 0. Multi-partition tapes can have files in different partitions with potentially overlapping file numbers.
  file | The file number within the specified partition. File numbers are typically sequential (0, 1, 2, ...) but gaps are allowed. The same file number can exist in different partitions without conflict.
  starting_block | The first block address of the file (inclusive). This should be the absolute block number in the image where the file's first byte begins. Must be <= ending_block (not validated).
  ending_block | The last block address of the file (inclusive). This should be the absolute block number in the image where the file's last byte ends. Must be >= starting_block (not validated).

Return values

  AARUF_STATUS_OK | (0) Successfully set tape file information. The hash table has been updated with the file entry. If an entry with the same partition/file combination existed, it has been replaced. The metadata will be written to the TapeFileBlock when the image is closed.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) Invalid context or context validation failed. This is returned when: The context pointer is NULL The context magic number doesn't match AARU_MAGIC (corrupted or wrong type) No modifications are made to the context.
  AARUF_READ_ONLY | (-22) The context is not opened for writing. This is returned when ctx->isWriting is false, indicating the image was opened in read-only mode. Tape file metadata cannot be modified in read-only mode. No modifications are made to the context.
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. The system could not allocate memory for the hash table entry (tapeFileHashEntry). This is a critical error indicating low memory conditions. No modifications are made to the context.

Note
  The function logs entry and exit points via TRACE macros when tracing is enabled, including parameter values and return codes for debugging.
  The tape file metadata is not immediately written to disk. It remains in the context's hash table until the image is closed, at which point all entries are serialized and written to a TapeFileBlock.
  No validation is performed on the block range values. The caller is responsible for ensuring that starting_block <= ending_block and that the range is valid for the image being created.
  No validation is performed to detect overlapping file ranges. Multiple files can reference the same or overlapping block ranges, which may be intentional (e.g., for multi-track or multi-partition scenarios).
  If the same partition/file combination is set multiple times, only the last values are retained. This can be used to update file metadata but also means accidental duplicate calls will silently overwrite previous values.

Warning
  This function is NOT thread-safe. Concurrent modifications to the tape file table may result in undefined behavior, memory corruption, or memory leaks.
  The caller must ensure the image is opened with write access before calling this function. Attempting to modify read-only images will fail with AARUF_READ_ONLY.
  Parameter validation is minimal. Invalid block ranges (starting_block > ending_block) are accepted and will be written to the image, potentially causing problems when reading the image later.
  If memory allocation fails (AARUF_ERROR_NOT_ENOUGH_MEMORY), the file entry is not added. The caller should handle this error appropriately, potentially by freeing memory and retrying or aborting the write operation.

See also
  aaruf_get_tape_file() for retrieving tape file information from images
  process_tape_files_block() for tape file table initialization during read
  TapeFileEntry for the structure defining file block ranges
  tapeFileHashEntry for the hash table entry structure

Definition at line 770 of file tape.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, TapeFileEntry::File, TapeFileHashEntry::fileEntry, TapeFileEntry::FirstBlock, aaruformat_context::is_writing, TapeFileHashEntry::key, TapeFileEntry::LastBlock, aaruformat_context::magic, TapeFileEntry::Partition, aaruformat_context::tape_files, and TRACE.

## ◆ aaruf_set_tape_partition()

int32_t aaruf_set_tape_partition | ( | void * | context,
|  | const uint8_t | partition,
|  | const uint64_t | starting_block,
|  | const uint64_t | ending_block )

Sets or updates the block range for a specific tape partition in an Aaru tape image.

Creates or modifies a tape partition entry in the context's hash table, defining the physical partition's extent on the tape medium by its partition number and block range. This function is the write-mode counterpart to aaruf_get_tape_partition() and is used when creating or modifying tape images to establish the partition structure metadata.

Tape Partition Registration: When writing a tape image, this function should be called for each physical partition to register its block range. Each partition is uniquely identified by its partition number (0-255), and most tapes have a single partition (partition 0), though formats like LTO, DLT, and AIT support multiple partitions.

The partition entry (including the block range) is stored in the context's tapePartitions hash table and will be written to the image's TapePartitionBlock during finalization.

Block Range Definition: The block range [starting_block, ending_block] defines the partition's extent:

- starting_block: The first block address in the partition (often 0, but format-dependent)
- ending_block: The final block address in the partition (inclusive)
- Block count: (ending_block - starting_block + 1)

Block addresses are local to each partition. The caller is responsible for ensuring:

- starting_block <= ending_block (no validation is performed)
- Partition ranges don't overlap (no validation is performed)
- All blocks in the range have been or will be written to the image
- Files referencing this partition have block addresses within this range

Typical Usage Flow:

1. Open or create an Aaru tape image with write access
2. Define partition layout by calling aaruf_set_tape_partition() for each partition
3. Write data blocks to the image within the defined partition ranges
4. Register files within partitions using aaruf_set_tape_file()
5. Close the image (TapePartitionBlock will be written during finalization)

Update/Replace Behavior: If a partition entry with the same partition number already exists:

- The old entry is automatically freed
- The new entry replaces it in the hash table
- A TRACE message indicates the replacement

This allows updating partition metadata or correcting errors without manual deletion.

Error Handling: The function performs validation in the following order:

1. Context pointer validation (NULL check)
2. Magic number verification (ensures valid aaruformat context)
3. Write mode verification (ensures image is opened for writing)
4. Memory allocation for the hash entry

If any validation fails, an appropriate error code is returned and no modifications are made to the context's tape partition table.

Thread Safety: This function modifies the shared context's hash table and is NOT thread-safe. Concurrent calls to aaruf_set_tape_partition() or other functions that modify ctx->tapePartitions may result in data corruption or memory leaks. The caller must ensure exclusive access through external synchronization if needed.

Memory Management:

- Allocates a new hash table entry (TapePartitionHashEntry) for each call
- HASH_REPLACE automatically frees replaced entries
- All hash entries are freed when the context is closed
- On allocation failure, no entry is added and an error is returned

Performance Characteristics:

- Hash table insertion/replacement: O(1) average case
- No I/O operations performed (metadata written during image close)
- Minimal stack usage
- Suitable for bulk partition registration operations

Partition Organization: Proper partition metadata is essential for:

- Documenting the physical layout of multi-partition tapes
- Validating file block ranges against partition boundaries
- Preserving the original tape's partitioning scheme for archival purposes
- Supporting tape formats that require specific partition structures
- Enabling applications to understand and navigate complex tape layouts

Parameters

  context | Pointer to an initialized aaruformat context. Must not be NULL. The context must have been opened with write access (isWriting=true). The context's tapePartitions hash table will be updated with the new entry.
  partition | The partition number (0-255) to set. For single-partition tapes, this is typically 0. Multi-partition tapes use sequential numbers (0, 1, 2, ...) though the numbering scheme is format-specific.
  starting_block | The first block address of the partition (inclusive). This defines where the partition begins in the tape's block address space. Often 0 for the first partition, but format-dependent. Must be <= ending_block (not validated).
  ending_block | The last block address of the partition (inclusive). This defines where the partition ends in the tape's block address space. Must be >= starting_block (not validated).

Return values

  AARUF_STATUS_OK | (0) Successfully set tape partition information. The hash table has been updated with the partition entry. If an entry with the same partition number existed, it has been replaced. The metadata will be written to the TapePartitionBlock when the image is closed.
  AARUF_ERROR_NOT_AARUFORMAT | (-1) Invalid context or context validation failed. This is returned when: The context pointer is NULL The context magic number doesn't match AARU_MAGIC (corrupted or wrong type) No modifications are made to the context.
  AARUF_READ_ONLY | (-22) The context is not opened for writing. This is returned when ctx->isWriting is false, indicating the image was opened in read-only mode. Tape partition metadata cannot be modified in read-only mode. No modifications are made to the context.
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. The system could not allocate memory for the hash table entry (TapePartitionHashEntry). This is a critical error indicating low memory conditions. No modifications are made to the context.

Note
  The function logs entry and exit points via TRACE macros when tracing is enabled, including parameter values and return codes for debugging.
  The tape partition metadata is not immediately written to disk. It remains in the context's hash table until the image is closed, at which point all entries are serialized and written to a TapePartitionBlock.
  No validation is performed on the block range values. The caller is responsible for ensuring that starting_block <= ending_block and that the range is valid for the image being created.
  No validation is performed to detect overlapping partition ranges. Partitions with overlapping block addresses may be accepted but will likely cause problems when reading the image or accessing files.
  If the same partition number is set multiple times, only the last values are retained. This can be used to update partition metadata but also means accidental duplicate calls will silently overwrite previous values.
  For single-partition tapes, it may be acceptable to omit the TapePartitionBlock entirely. Applications reading such images should assume a default partition 0 spanning the entire tape if no partition metadata is present.
  Block addresses are local to each partition. Files within a partition reference blocks relative to that partition's address space, not the global tape address space (though in practice, many formats use absolute addressing).

Warning
  This function is NOT thread-safe. Concurrent modifications to the tape partition table may result in undefined behavior, memory corruption, or memory leaks.
  The caller must ensure the image is opened with write access before calling this function. Attempting to modify read-only images will fail with AARUF_READ_ONLY.
  Parameter validation is minimal. Invalid block ranges (starting_block > ending_block) are accepted and will be written to the image, potentially causing problems when reading the image later.
  If memory allocation fails (AARUF_ERROR_NOT_ENOUGH_MEMORY), the partition entry is not added. The caller should handle this error appropriately, potentially by freeing memory and retrying or aborting the write operation.
  Partition metadata should be consistent with file metadata. Files should only reference partitions that have been defined, and their block ranges should fall within the partition boundaries. No automatic validation is performed.

See also
  aaruf_get_tape_partition() for retrieving tape partition information from images
  process_tape_partitions_block() for partition table initialization during read
  TapePartitionEntry for the structure defining partition block ranges
  TapePartitionHashEntry for the hash table entry structure
  aaruf_set_tape_file() for setting file metadata within partitions

Definition at line 1196 of file tape.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, FATAL, TapePartitionEntry::FirstBlock, aaruformat_context::is_writing, TapePartitionHashEntry::key, TapePartitionEntry::LastBlock, aaruformat_context::magic, TapePartitionEntry::Number, TapePartitionHashEntry::partitionEntry, aaruformat_context::tape_partitions, and TRACE.

## ◆ aaruf_set_tracks()

int32_t aaruf_set_tracks | ( | void * | context,
|  | TrackEntry * | tracks,
|  | const int | count )

Replace (or clear) the in-memory track table for an AaruFormat image context.

Copies an array of caller-provided TrackEntry structures into the internal context, replacing any previously stored track metadata. A CRC64 is recomputed over the new table and stored in the associated TracksHeader. Passing a count of 0 clears existing track information.

Typical usage:

- Prepare an array of TrackEntry structures describing each track (filled by the caller).
- Call aaruf_set_tracks() with the array and the track count to load them into the context.
- Subsequently the table can be retrieved with aaruf_get_tracks().

Memory ownership:

- The function allocates (or frees when clearing) internal storage sized to (count * sizeof(TrackEntry)).
- The caller retains ownership of the input array (if any) and may free or reuse it after the call.

Validation performed:

- `context` must be non-NULL and reference aaruformatContext with magic == AARU_MAGIC.
- `tracks` must be non-NULL when `count` > 0.
- `count` must be >= 0. (Negative values produce AARUF_ERROR_INVALID_TRACK_FORMAT.)
- (Implementation detail) count is truncated to uint16_t for header storage; values > UINT16_MAX will silently wrap. Callers should ensure count <= 65535. This behavior may change in a future version.

Concurrency & thread-safety:

- Not thread-safe. Mutates shared context state. External synchronization is required if multiple threads access the same context.

Side effects:

- Frees any existing internal track table before allocating the new one.
- Updates ctx->tracksHeader.identifier, entries, crc64.
- When clearing (count == 0) sets header to zero and frees internal table.

Error handling & atomicity:

- On allocation failure the previous track table is already freed (non-atomic replace) and the header is zeroed (no partial new state left). Caller must repopulate.
- No partial copies: either all tracks are stored or none.

Parameters

  context | Opaque pointer that MUST point to a valid aaruformatContext returned by an open/create call.
  tracks | Pointer to an array of TrackEntry structures to copy. Must not be NULL if count > 0. Ignored (may be NULL) when count == 0.
  count | Number of TrackEntry elements in `tracks`. If 0, existing tracks are cleared. Must be >= 0 and (recommended) <= UINT16_MAX.

Returns
  int32_t API status code indicating success or the nature of the failure.

Return values

  AARUF_STATUS_OK | Success (tracks replaced or cleared).
  AARUF_ERROR_NOT_AARUFORMAT | `context` is NULL or not a recognized libaaruformat context.
  AARUF_ERROR_INVALID_TRACK_FORMAT | Invalid input (tracks NULL with count > 0, or count < 0).
  AARUF_ERROR_NOT_ENOUGH_MEMORY | Memory allocation failed while copying tracks.

Warning
  Not thread-safe. Do not invoke concurrently with readers/writers of the same context.

Note
  After success, aaruf_get_tracks() can be used to read back the stored table.

See also
  aaruf_get_tracks()

Since
  1.0

Usage example (conceptual):

1. Prepare an array of TrackEntry structures (N elements) and fill the fields.
2. Call aaruf_set_tracks(ctx, array, N) to store them; check for AARUF_STATUS_OK.
3. To clear all tracks later call aaruf_set_tracks(ctx, NULL, 0).
4. Use aaruf_get_tracks() afterwards to retrieve them if needed.

Definition at line 392 of file optical.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_crc64_data(), AARUF_ERROR_INVALID_TRACK_FORMAT, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_STATUS_OK, TracksHeader::crc64, aaruformat_context::data_tracks, TracksHeader::entries, FATAL, ImageInfo::HasPartitions, ImageInfo::HasSessions, TracksHeader::identifier, aaruformat_context::image_info, aaruformat_context::magic, aaruformat_context::number_of_data_tracks, TrackEntry::sequence, TRACE, aaruformat_context::track_entries, aaruformat_context::tracks_header, and TracksBlock.

## ◆ aaruf_sha1_buffer()

void aaruf_sha1_buffer | ( | const void * | data,
|  | unsigned long | size,
|  | unsigned char * | result )

Definition at line 155 of file sha1.c.

References AARU_CALL, AARU_EXPORT, aaruf_sha1_final(), aaruf_sha1_init(), and aaruf_sha1_update().

## ◆ aaruf_sha1_final()

void aaruf_sha1_final | ( | sha1_ctx * | ctx,
|  | unsigned char * | result )

Definition at line 124 of file sha1.c.

References AARU_CALL, AARU_EXPORT, aaruf_sha1_update(), sha1_ctx::buffer, sha1_ctx::count, and sha1_ctx::state.

Referenced by aaruf_sha1_buffer(), and write_checksum_block().

## ◆ aaruf_sha1_init()

void aaruf_sha1_init | ( | sha1_ctx * | ctx | ) |

Definition at line 34 of file sha1.c.

References AARU_CALL, AARU_EXPORT, sha1_ctx::buffer, sha1_ctx::count, and sha1_ctx::state.

Referenced by aaruf_create(), and aaruf_sha1_buffer().

## ◆ aaruf_sha1_update()

void aaruf_sha1_update | ( | sha1_ctx * | ctx,
|  | const void * | data,
|  | unsigned long | size )

Definition at line 89 of file sha1.c.

References AARU_CALL, AARU_EXPORT, sha1_ctx::buffer, sha1_ctx::count, sha1_transform(), and sha1_ctx::state.

Referenced by aaruf_sha1_buffer(), aaruf_sha1_final(), aaruf_write_sector(), and aaruf_write_sector_long().

## ◆ aaruf_sha256_buffer()

void aaruf_sha256_buffer | ( | const void * | data,
|  | unsigned long | size,
|  | unsigned char * | result )

Definition at line 141 of file sha256.c.

References AARU_CALL, AARU_EXPORT, aaruf_sha256_final(), aaruf_sha256_init(), and aaruf_sha256_update().

## ◆ aaruf_sha256_final()

void aaruf_sha256_final | ( | sha256_ctx * | ctx,
|  | unsigned char * | result )

Definition at line 115 of file sha256.c.

References AARU_CALL, AARU_EXPORT, aaruf_sha256_update(), sha256_ctx::bitcount, sha256_ctx::buffer, and sha256_ctx::state.

Referenced by aaruf_sha256_buffer(), and write_checksum_block().

## ◆ aaruf_sha256_init()

void aaruf_sha256_init | ( | sha256_ctx * | ctx | ) |

Definition at line 76 of file sha256.c.

References AARU_CALL, AARU_EXPORT, sha256_ctx::bitcount, sha256_ctx::buffer, and sha256_ctx::state.

Referenced by aaruf_create(), and aaruf_sha256_buffer().

## ◆ aaruf_sha256_update()

void aaruf_sha256_update | ( | sha256_ctx * | ctx,
|  | const void * | data,
|  | unsigned long | size )

Definition at line 90 of file sha256.c.

References AARU_CALL, AARU_EXPORT, sha256_ctx::bitcount, sha256_ctx::buffer, sha256_transform(), and sha256_ctx::state.

Referenced by aaruf_sha256_buffer(), aaruf_sha256_final(), aaruf_write_sector(), and aaruf_write_sector_long().

## ◆ aaruf_spamsum_final()

int aaruf_spamsum_final | ( | spamsum_ctx * | ctx,
|  | uint8_t * | result )

Definition at line 191 of file spamsum.c.

References AARU_CALL, AARU_EXPORT, b64, spamsum_ctx::bh, spamsum_ctx::bh_end, spamsum_ctx::bh_start, blockhash_ctx::d_len, blockhash_ctx::digest, FUZZY_MAX_RESULT, blockhash_ctx::h, blockhash_ctx::half_digest, blockhash_ctx::half_h, NUM_BLOCKHASHES, ROLL_SUM, SPAMSUM_LENGTH, and SSDEEP_BS.

Referenced by write_checksum_block().

## ◆ aaruf_spamsum_free()

void aaruf_spamsum_free | ( | spamsum_ctx * | ctx | ) |

Frees a spamsum (fuzzy hash) context.

Parameters

  ctx | Pointer to the spamsum context to free.

Definition at line 75 of file spamsum.c.

References AARU_CALL, and AARU_EXPORT.

Referenced by cleanup_failed_create(), and write_checksum_block().

## ◆ aaruf_spamsum_init()

spamsum_ctx * aaruf_spamsum_init | ( | void |  | ) |

Definition at line 37 of file spamsum.c.

References AARU_CALL, AARU_EXPORT, spamsum_ctx::bh, spamsum_ctx::bh_end, blockhash_ctx::h, blockhash_ctx::half_h, and HASH_INIT.

Referenced by aaruf_create().

## ◆ aaruf_spamsum_update()

int aaruf_spamsum_update | ( | spamsum_ctx * | ctx,
|  | const uint8_t * | data,
|  | const uint32_t | len )

Updates the spamsum context with new data.

Parameters

  ctx | Pointer to the spamsum context.
  data | Pointer to the data to process.
  len | Length of the data in bytes.

Returns
  0 on success, -1 on error.

Definition at line 59 of file spamsum.c.

References AARU_CALL, AARU_EXPORT, fuzzy_engine_step(), and spamsum_ctx::total_size.

Referenced by aaruf_write_sector(), and aaruf_write_sector_long().

## ◆ aaruf_verify_image()

int32_t aaruf_verify_image | ( | void * | context | ) |

Verifies the integrity of an AaruFormat image file.

Checks the integrity of all blocks and deduplication tables in the image by validating CRC64 checksums for each indexed block. This function performs comprehensive verification of data blocks, DDT v1 and v2 tables, tracks blocks, and other structural components. It reads blocks in chunks to optimize memory usage during verification and supports version-specific CRC endianness handling.

Parameters

  context | Pointer to the aaruformat context.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully verified image integrity. This is returned when: All indexed blocks are successfully read and processed All CRC64 checksums match their expected values Index verification passes for the detected index version All block headers are readable and valid Memory allocation for verification buffer succeeds
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_ERROR_CANNOT_READ_HEADER | (-6) Failed to read critical headers. This occurs when: Cannot read the index signature from the image stream File I/O errors prevent reading header structures
  AARUF_ERROR_CANNOT_READ_INDEX | (-4) Index processing or validation failed. This occurs when: Index signature is not a recognized type (IndexBlock, IndexBlock2, or IndexBlock3) Index verification functions return error codes Index processing functions return NULL (corrupted or invalid index)
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: Cannot allocate VERIFY_SIZE (1MB) buffer for reading block data during verification System is out of available memory for verification operations
  AARUF_ERROR_CANNOT_READ_BLOCK | (-7) Block reading failed. This occurs when: Cannot read block headers (DataBlock, DeDuplicationTable, DeDuplicationTable2, TracksBlock) File I/O errors prevent reading block structure data CRC64 context initialization fails (internal error)
  AARUF_ERROR_INVALID_BLOCK_CRC | (-18) CRC verification failed. This occurs when: Calculated CRC64 doesn't match the expected CRC64 in block headers Data corruption is detected in any verified block This applies to DataBlock, DeDuplicationTable, DeDuplicationTable2, and TracksBlock types

Note
  Verification Process:
  - Reads blocks in VERIFY_SIZE (1MB) chunks to optimize memory usage
  - Supports version-specific CRC64 endianness (v1 uses byte-swapped CRC64)
  - Verifies only blocks that have CRC checksums (skips blocks without checksums)
  - Unknown block types are logged but don't cause verification failure
  Block Types Verified:
  - DataBlock: Verifies compressed data CRC64 against block header
  - DeDuplicationTable (v1): Verifies DDT data CRC64 with version-specific endianness
  - DeDuplicationTable2 (v2): Verifies DDT data CRC64 (no endianness conversion)
  - TracksBlock: Verifies track entries CRC64 with version-specific endianness
  - Other block types are ignored during verification
  Performance Considerations:
  - Uses chunked reading to minimize memory footprint during verification
  - Processes blocks sequentially to maintain good disk access patterns
  - CRC64 contexts are created and destroyed for each block to prevent memory leaks

Warning
  This function performs read-only verification and does not modify the image. It requires the image to be properly opened with a valid context.
  Verification failure indicates data corruption or tampering. Images that fail verification should not be trusted for data recovery operations.
  The function allocates a 1MB buffer for verification. Ensure sufficient memory is available before calling this function on resource-constrained systems.

Definition at line 130 of file verify.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_crc64_final(), aaruf_crc64_free(), aaruf_crc64_init(), AARUF_ERROR_CANNOT_READ_BLOCK, AARUF_ERROR_CANNOT_READ_HEADER, AARUF_ERROR_CANNOT_READ_INDEX, AARUF_ERROR_INVALID_BLOCK_CRC, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_STATUS_OK, AARUF_VERSION_V1, IndexEntry::blockType, bswap_64, BlockHeader::cmpCrc64, DdtHeader2::cmpCrc64, DdtHeader::cmpCrc64, BlockHeader::cmpLength, DdtHeader2::cmpLength, DdtHeader::cmpLength, TracksHeader::crc64, DataBlock, DeDuplicationTable, DeDuplicationTable2, TracksHeader::entries, FATAL, aaruformat_context::header, AaruHeaderV2::imageMajorVersion, aaruformat_context::imageStream, IndexBlock, IndexBlock2, IndexBlock3, AaruHeaderV2::indexOffset, aaruformat_context::magic, IndexEntry::offset, process_index_v1(), process_index_v2(), process_index_v3(), TRACE, TracksBlock, update_crc64_from_stream(), verify_index_v1(), verify_index_v2(), verify_index_v3(), and VERIFY_SIZE.

## ◆ aaruf_write_media_tag()

int32_t aaruf_write_media_tag | ( | void * | context,
|  | const uint8_t * | data,
|  | const int32_t | type,
|  | const uint32_t | length )

Writes a media tag to the AaruFormat image, storing medium-specific metadata and descriptors.

This function stores arbitrary media-specific metadata (media tags) in the AaruFormat image context for later serialization during image finalization. Media tags represent higher-level descriptors and metadata structures that characterize the storage medium beyond sector data, including disc information structures, lead-in/lead-out data, manufacturer identifiers, drive capabilities, and format-specific metadata. The function uses a hash table for efficient tag storage and retrieval, automatically replacing existing tags of the same type and managing memory for tag data.

Supported Media Tag Categories:

Optical Disc Metadata (CD/DVD/BD/HD DVD):

- CD_TOC (0): Table of Contents from READ TOC/PMA/ATIP command (Format 0000b - Formatted TOC)
  - Contains track entries, session boundaries, lead-in/lead-out addressing, and track types
  - Essential for multi-session and mixed-mode CD structure representation
- CD_FullTOC (1): Full TOC (Format 0010b) including session info and point/ADR/control fields
  - Provides complete session structure with ADR field interpretation and sub-Q channel details
- CD_SessionInfo (2): Session information (Format 0001b) for multi-session discs
- CD_TEXT (3): CD-TEXT data from lead-in area (artist, title, performer, songwriter metadata)
- CD_ATIP (4): Absolute Time In Pregroove (CD-R/RW timing calibration and media manufacturer data)
- CD_PMA (5): Power Management Area (CD-R/RW recording session management metadata)
- DVD_PFI (6): Physical Format Information (DVD layer characteristics, book type, linear density)
- DVD_DMI (7): Disc Manufacturing Information (DVD unique identifier and replication metadata)
- DVD_BCA (8): Burst Cutting Area (copy protection and regional management data for DVD-Video)
- BD_DI (28): Disc Information (Blu-ray layer count, recording format, disc size, channel bit length)
- BD_BCA (29): Blu-ray Burst Cutting Area (unique disc identifier and anti-counterfeiting data)

Recordable Media Structures:

- DVDR_RMD (17): Recorded Media Data (last border-out RMD for DVD-R/-RW finalization state)
- DVDR_PreRecordedInfo (18): Pre-recorded information area from lead-in (DVD-R physical specs)
- DVDR_MediaIdentifier (19): Writable media identifier (DVD-R/-RW unique ID from manufacturer)
- BD_DDS (30): Disc Definition Structure (BD-R/RE recording management and spare area allocation)
- BD_SpareArea (32): BD spare area allocation map (defect management for recordable Blu-ray)

Copy Protection and Security:

- AACS_VolumeIdentifier (33): AACS Volume Identifier (content identifier for AACS-protected media)
- AACS_SerialNumber (34): Pre-recorded media serial number (unique per AACS disc pressing)
- AACS_MediaIdentifier (35): AACS Media Identifier (cryptographic binding to physical medium)
- AACS_MKB (36): AACS Media Key Block (encrypted title keys and revocation lists)
- AACS_DataKeys (37): Extracted AACS title/volume keys (when decrypted, for archival purposes)
- AACS_CPRM_MKB (39): CPRM Media Key Block (Content Protection for Recordable Media)

Device and Drive Information:

- SCSI_INQUIRY (45): SCSI INQUIRY standard data (device type, vendor, model, firmware revision)
- SCSI_MODEPAGE_2A (46): SCSI Mode Page 2Ah (CD/DVD/BD capabilities and supported features)
- ATA_IDENTIFY (47): ATA IDENTIFY DEVICE response (512 bytes of drive capabilities and geometry)
- ATAPI_IDENTIFY (48): ATA PACKET IDENTIFY DEVICE (ATAPI drive identification and features)
- MMC_WriteProtection (41): Write protection status from MMC GET CONFIGURATION command
- MMC_DiscInformation (42): Disc Information (recordable status, erasable flag, last session)

Flash and Solid-State Media:

- SD_CID (50): SecureDigital Card ID register (manufacturer, OEM, product name, serial number)
- SD_CSD (51): SecureDigital Card Specific Data (capacity, speed class, file format)
- SD_SCR (52): SecureDigital Configuration Register (SD spec version, bus widths, security)
- SD_OCR (53): SecureDigital Operation Conditions Register (voltage ranges, capacity type)
- MMC_CID (54): MMC Card ID (similar to SD_CID for eMMC/MMC devices)
- MMC_CSD (55): MMC Card Specific Data (MMC device parameters)
- MMC_ExtendedCSD (57): MMC Extended CSD (512 bytes of extended MMC capabilities)

Gaming Console Media:

- Xbox_SecuritySector (58): Xbox/Xbox 360 Security Sector (SS.bin - anti-piracy signature data)
- Xbox_DMI (66): Xbox Disc Manufacturing Info (manufacturing plant and batch metadata)
- Xbox_PFI (67): Xbox Physical Format Information (Xbox-specific DVD layer configuration)

Specialized Structures:

- CD_FirstTrackPregap (61): First track pregap (index 0 contents, typically silent on audio CDs)
- CD_LeadOut (62): Lead-out area contents (post-data region signaling disc end)
- CD_LeadIn (68): Raw lead-in data (TOC frames and sub-Q channel from pre-data region)
- Floppy_LeadOut (59): Manufacturer/duplication cylinder (floppy copy protection metadata)
- PCMCIA_CIS (49): PCMCIA/CardBus Card Information Structure tuple chain
- USB_Descriptors (65): Concatenated USB descriptors (device/config/interface for USB drives)

Data Processing Pipeline:

1. Context Validation: Verifies context is valid AaruFormat context with write permissions
2. Parameter Validation: Checks data pointer is non-NULL and length is non-zero
3. Memory Allocation: Allocates new buffer for tag data and mediaTagEntry structure
4. Data Copying: Performs deep copy of tag data to ensure context owns the memory
5. Hash Table Insertion: Adds or replaces entry in mediaTags hash table using uthash HASH_REPLACE_INT
6. Cleanup: Frees old media tag entry and data if replacement occurred
7. Return Success: Returns AARUF_STATUS_OK on successful completion

Memory Management Strategy:

- Deep Copy Semantics: Function performs deep copy of input data; caller retains ownership of original buffer
- Automatic Replacement: Existing tag of same type is automatically freed when replaced
- Hash Table Storage: Media tags stored in uthash-based hash table for O(1) lookup by type
- Deferred Serialization: Tag data remains in memory until aaruf_close() serializes to image file
- Cleanup on Close: All media tag memory automatically freed during aaruf_close()

Tag Type Identification: The type parameter accepts MediaTagType enumeration values (0-68) that identify the semantic meaning of the tag data. The library does not validate tag data structure or size against the type identifier - callers are responsible for providing correctly formatted tag data matching the declared type. Type values are preserved as-is and used during serialization to identify tag purpose during image reading.

Replacement Behavior: When a media tag of the same type already exists in the context:

- The old tag entry is removed from the hash table
- The old tag's data buffer is freed
- The old tag entry structure is freed
- The new tag replaces the old tag in the hash table
- No warning or error is generated for replacement This allows incremental updates to media tags during image creation.

Serialization and Persistence: Media tags written via this function are not immediately written to the image file. Instead, they are accumulated in the context's mediaTags hash table and serialized during aaruf_close() as part of the image finalization process. The serialization creates a metadata block in the image file that preserves all media tags with their type identifiers and data lengths.

Thread Safety and Concurrency: This function is NOT thread-safe. The context contains mutable shared state including:

- mediaTags hash table modification
- Memory allocation and deallocation
- No internal locking or synchronization External synchronization required for concurrent access from multiple threads.

Performance Considerations:

- Hash table insertion is O(1) average case for new tags
- Hash table replacement is O(1) for existing tags
- Memory allocation overhead proportional to tag data size
- No disk I/O occurs during this call (deferred to aaruf_close())
- Suitable for frequent tag updates during image creation workflow

Typical Usage Scenarios:

- Optical Disc Imaging: Store TOC, PMA, ATIP, CD-TEXT from READ TOC family commands
- Copy Protection Preservation: Store BCA, AACS structures, media identifiers for archival
- Drive Capabilities: Store INQUIRY, Mode Page 2Ah, IDENTIFY data for forensic metadata
- Flash Card Imaging: Store CID, CSD, SCR, OCR registers from SD/MMC cards
- Console Game Preservation: Store Xbox security sectors and manufacturing metadata
- Recordable Media: Store RMD, media identifiers, spare area maps for write-once media

Validation and Error Handling:

- Context validity checked via magic number comparison (AARU_MAGIC)
- Write permission verified via isWriting flag
- NULL data pointer triggers AARUF_ERROR_INCORRECT_DATA_SIZE
- Zero length triggers AARUF_ERROR_INCORRECT_DATA_SIZE
- Memory allocation failures return AARUF_ERROR_NOT_ENOUGH_MEMORY
- No validation of tag data structure or size against type identifier

Data Format Requirements: The function accepts arbitrary binary data without format validation. Callers must ensure:

- Tag data matches the declared MediaTagType structure and size
- Binary data is properly byte-ordered for the target platform
- Variable-length tags include proper internal length fields if required
- Tag data represents a complete, self-contained structure

Integration with Image Creation Workflow: Media tags should typically be written after creating the image context (aaruf_create()) but before writing sector data. However, tags can be added or updated at any point during the writing process. Common workflow:

1. Create image context with aaruf_create()
2. Set tracks with aaruf_set_tracks() if applicable
3. Write media tags with write_media_tag() for all available metadata
4. Write sector data with aaruf_write_sector() or aaruf_write_sector_long()
5. Close image with aaruf_close() to finalize and serialize all metadata

Parameters

  context | Pointer to a valid aaruformatContext with magic == AARU_MAGIC opened for writing. Must be created via aaruf_create() and not yet closed. The context's isWriting flag must be true, indicating write mode is active.
  data | Pointer to the media tag data buffer to write. Must be a valid non-NULL pointer to a buffer containing the complete tag data. The function performs a deep copy of this data, so the caller retains ownership and may free or modify the source buffer after this call returns. The data format must match the structure expected for the specified type parameter.
  type | Integer identifier specifying the type of media tag (MediaTagType enumeration). Values range from 0 (CD_TOC) to 68 (CD_LeadIn). The type identifies the semantic meaning of the tag data and is preserved in the image file for interpretation during reading. The library does not validate that the data structure matches the declared type - caller responsibility to ensure correctness.
  length | Length in bytes of the media tag data buffer. Must be greater than zero. Specifies how many bytes to copy from the data buffer. No maximum length enforced, but extremely large tags may cause memory allocation failures.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully wrote the media tag. This is returned when: Context is valid with correct magic number (AARU_MAGIC) Context is in writing mode (isWriting == true) Data pointer is non-NULL and length is non-zero Memory allocation succeeded for both tag data and entry structure Tag entry successfully inserted into mediaTags hash table If replacing existing tag, old tag successfully freed
  AARUF_ERROR_NOT_AARUFORMAT | (-1) Invalid context provided. This occurs when: context parameter is NULL (no context provided) Context magic number != AARU_MAGIC (wrong context type, corrupted context, or uninitialized) Context was not created by aaruf_create() or has been corrupted
  AARUF_READ_ONLY | (-22) Attempting to write to read-only image. This occurs when: Context isWriting flag is false Image was opened with aaruf_open() instead of aaruf_create() Context is in read-only mode and modifications are not permitted
  AARUF_ERROR_INCORRECT_DATA_SIZE | (-26) Invalid data or length parameters. This occurs when: data parameter is NULL (no tag data provided) length parameter is zero (no data to write) Parameters indicate invalid or empty tag data
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: Failed to allocate buffer for tag data copy (malloc(length) failed) Failed to allocate mediaTagEntry structure (malloc(sizeof(mediaTagEntry)) failed) System is out of available memory for requested allocation size Memory allocation fails due to resource exhaustion or fragmentation

Note
  Cross-References: This function is the write counterpart to aaruf_read_media_tag(). See also:
  - aaruf_read_media_tag(): Reads media tag data from opened image
  - aaruf_create(): Creates writable image context required for this function
  - aaruf_close(): Serializes media tags to image file and frees tag memory
  - MediaTagType enumeration in aaru.h: Defines valid type identifier values
  Memory Ownership: The function performs a deep copy of tag data. After successful return, the context owns the copied tag data and the caller may free or modify the original data buffer. On failure, no memory is retained by the context - caller maintains full ownership of input buffer regardless of success or failure.
  Tag Uniqueness: Only one media tag of each type can exist in an image. Writing a tag with a type that already exists will replace the previous tag, freeing its memory and using the new tag data. No error or warning is generated for replacements.
  Deferred Serialization: Media tags are not written to disk until aaruf_close() is called. All tags remain in memory throughout the image creation process. For images with many or large media tags, memory usage may be significant.
  No Type Validation: The library does not validate that tag data matches the declared type. Callers must ensure data structure correctness. Mismatched data may cause reading applications to fail or misinterpret tag contents.

Warning
  Memory Growth: Each media tag consumes memory equal to tag data size plus mediaTagEntry structure overhead. Large tags or many tags can significantly increase memory usage. Monitor memory consumption when writing extensive metadata.
  Type Correctness: No validation occurs for tag data format against type identifier. Providing incorrectly formatted data or mismatched type identifiers will create a valid image file with invalid tag data that may cause failures when reading. Ensure data format matches MediaTagType specification requirements.
  Replacement Silent: Replacing an existing tag does not generate warnings or errors. Applications expecting to detect duplicate tag writes must track this externally. The most recent write_media_tag() call for each type determines the final tag value.

See also
  aaruf_read_media_tag() for corresponding media tag reading functionality
  aaruf_create() for image context creation in write mode
  aaruf_close() for media tag serialization and memory cleanup
  MediaTagType enumeration for valid type identifier values and meanings

Definition at line 1800 of file write.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_READ_ONLY, AARUF_STATUS_OK, mediaTagEntry::data, FATAL, aaruformat_context::is_writing, mediaTagEntry::length, aaruformat_context::magic, aaruformat_context::mediaTags, TRACE, and mediaTagEntry::type.

## ◆ aaruf_write_sector()

int32_t aaruf_write_sector | ( | void * | context,
|  | uint64_t | sector_address,
|  | bool | negative,
|  | const uint8_t * | data,
|  | uint8_t | sector_status,
|  | uint32_t | length )

Writes a sector to the AaruFormat image.

Writes the given data to the specified sector address in the image, with the given status and length. This function handles buffering data into blocks, automatically closing blocks when necessary (sector size changes or block size limits are reached), and managing the deduplication table (DDT) entries.

Parameters

  context | Pointer to the aaruformat context.
  sector_address | Logical sector address to write.
  negative | Indicates if the sector address is negative.
  data | Pointer to the data buffer to write.
  sector_status | Status of the sector to write.
  length | Length of the data buffer.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully wrote the sector data. This is returned when: The sector data is successfully copied to the writing buffer The DDT entry is successfully updated for the sector address Block management operations complete successfully Buffer positions and offsets are properly updated
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type)
  AARUF_READ_ONLY | (-22) Attempting to write to a read-only image. This occurs when: The context's isWriting flag is false The image was opened in read-only mode
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: Failed to allocate memory for the writing buffer when creating a new block The system is out of available memory for buffer allocation
  AARUF_ERROR_CANNOT_WRITE_BLOCK_HEADER | (-23) Failed to write block header to the image file. This can occur during automatic block closure when: The fwrite() call for the block header fails Disk space is insufficient or file system errors occur
  AARUF_ERROR_CANNOT_WRITE_BLOCK_DATA | (-24) Failed to write block data to the image file. This can occur during automatic block closure when: The fwrite() call for the block data fails Disk space is insufficient or file system errors occur
  AARUF_ERROR_CANNOT_SET_DDT_ENTRY | (-25) Failed to update the deduplication table (DDT) entry. This occurs when: The DDT entry for the specified sector address could not be set or updated Internal DDT management functions return failure DDT table corruption or memory issues prevent entry updates

Note
  Block Management:
  - The function automatically closes the current block when sector size changes
  - Blocks are also closed when they reach the maximum size (determined by dataShift)
  - New blocks are created automatically when needed with appropriate headers
  Memory Management:
  - Writing buffers are allocated on-demand when creating new blocks
  - Buffer memory is freed when blocks are closed
  - Buffer size is calculated based on sector size and data shift parameters
  DDT Updates:
  - Each written sector updates the corresponding DDT entry
  - DDT entries track block offset, position, and sector status
  - Uses DDT version 2 format for entries

Warning
  The function may trigger automatic block closure, which can result in disk I/O operations and potential write errors even for seemingly simple sector writes.

Definition at line 98 of file write.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_close_current_block(), AARUF_ERROR_CANNOT_SET_DDT_ENTRY, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_ERROR_SECTOR_OUT_OF_BOUNDS, aaruf_md5_update(), AARUF_READ_ONLY, aaruf_sha1_update(), aaruf_sha256_update(), aaruf_spamsum_update(), AARUF_STATUS_OK, Audio, aaruformat_context::blake3_context, aaruformat_context::block_zero_written, aaruformat_context::calculating_blake3, aaruformat_context::calculating_md5, aaruformat_context::calculating_sha1, aaruformat_context::calculating_sha256, aaruformat_context::calculating_spamsum, BlockHeader::compression, aaruformat_context::compression_enabled, aaruformat_context::current_block_header, aaruformat_context::current_block_offset, aaruformat_context::current_track_type, Data, DataBlock, DdtHeader2::dataShift, aaruformat_context::deduplicate, TrackEntry::end, TracksHeader::entries, FATAL, Flac, BlockHeader::identifier, aaruformat_context::image_info, insert_map(), aaruformat_context::is_writing, JaguarCD, aaruformat_context::last_written_block, lookup_map(), Lzma, aaruformat_context::magic, aaruformat_context::md5_context, ImageInfo::MediaType, ImageInfo::MetadataMediaType, DdtHeader2::negative, aaruformat_context::next_block_position, None, OpticalDisc, DdtHeader2::overflow, aaruformat_context::rewinded, aaruformat_context::sector_hash_map, ImageInfo::Sectors, BlockHeader::sectorSize, TrackEntry::sequence, TrackEntry::session, set_ddt_entry_v2(), aaruformat_context::sha1_context, aaruformat_context::sha256_context, aaruformat_context::spamsum_context, TrackEntry::start, TRACE, aaruformat_context::track_entries, aaruformat_context::tracks_header, BlockHeader::type, TrackEntry::type, aaruformat_context::user_data_ddt_header, UserData, VideoNow, VideoNowColor, VideoNowXp, aaruformat_context::writing_buffer, aaruformat_context::writing_buffer_position, and aaruformat_context::writing_long.

Referenced by aaruf_write_sector_long().

## ◆ aaruf_write_sector_long()

int32_t aaruf_write_sector_long | ( | void * | context,
|  | uint64_t | sector_address,
|  | bool | negative,
|  | const uint8_t * | data,
|  | uint8_t | sector_status,
|  | uint32_t | length )

Writes a full ("long") raw sector from optical or block media, parsing structure and validating content.

This function processes complete raw sectors including structural metadata, error correction codes, and subchannel information. It is the primary entry point for ingesting raw sector data where the caller provides the complete sector including synchronization patterns, headers, user data, and error correction information. The function intelligently parses the sector structure based on media type and track information, validates correctness, and delegates user data writing to aaruf_write_sector().

Supported Media Types and Sector Formats:

Optical Disc Media (2352-byte sectors):

- Audio tracks: Raw PCM audio data (2352 bytes) passed directly to aaruf_write_sector()
- Data tracks: Raw data sectors passed directly to aaruf_write_sector()
- CD Mode 1: Sync(12) + Header(4) + UserData(2048) + EDC(4) + Reserved(8) + ECC_P(172) + ECC_Q(104)
  - Validates sync pattern (00 FF FF FF FF FF FF FF FF FF FF 00), mode byte (01), and MSF timing
  - Checks EDC/ECC correctness using aaruf_ecc_cd_is_suffix_correct()
  - Stores anomalous prefixes/suffixes in separate buffers with mini-DDT indexing
- CD Mode 2 Form 1: Sync(12) + Header(4) + Subheader(8) + UserData(2048) + EDC(4) + ECC_P(172) + ECC_Q(104)
  - Validates sync pattern, mode byte (02), and Form 1 identification in subheader
  - Checks both EDC and ECC correctness for Form 1 sectors
  - Extracts and stores 8-byte subheader separately in mode2_subheaders buffer
- CD Mode 2 Form 2: Sync(12) + Header(4) + Subheader(8) + UserData(2324) + EDC(4)
  - Validates sync pattern, mode byte (02), and Form 2 identification in subheader
  - Checks EDC correctness, handles missing EDC (zero) as valid state
  - No ECC validation for Form 2 sectors (not present in format)
- CD Mode 2 Formless: Similar to Form 2 but without form determination from subheader

Block Media (512+ byte sectors with tags):

- Apple Profile/FileWare: 512-byte sectors + 20-byte Profile tags
- Apple Sony SS/DS: 512-byte sectors + 12-byte Sony tags
- Apple Widget: 512-byte sectors with tag conversion support
- Priam DataTower: 512-byte sectors + 24-byte Priam tags
- Supports automatic tag format conversion between Sony (12), Profile (20), and Priam (24) byte formats
- Tag data stored in sector_subchannel buffer for preservation

Data Processing Pipeline:

1. Context and Parameter Validation: Verifies context magic, write permissions, and sector bounds
2. Track Resolution: Locates track entry covering the sector address to determine track type
3. Rewind Detection: Detects out-of-order writing and disables hash calculations to maintain integrity
4. Hash Updates: Updates MD5, SHA1, SHA256, SpamSum, and BLAKE3 contexts for user-range sectors
5. Structure Parsing: Splits raw sector into prefix, user data, and suffix components
6. Validation: Checks sync patterns, timing fields, EDC/ECC correctness, and format compliance
7. Metadata Storage: Stores anomalous or non-standard components in dedicated buffers
8. User Data Delegation: Calls aaruf_write_sector() with extracted user data and derived status

Memory Management Strategy:

- DDT Arrays: Lazily allocated 64-bit arrays sized for total addressable space (negative + user + overflow)
  - sectorPrefixDdt2: Tracks prefix status and buffer offsets (high 4 bits = status, low 60 bits = offset/16)
  - sectorSuffixDdt2: Tracks suffix status and buffer offsets (high 4 bits = status, low 60 bits = offset/288)
- Prefix Buffer: Dynamically growing buffer storing non-standard 16-byte CD prefixes
- Suffix Buffer: Dynamically growing buffer storing non-standard CD suffixes (288 bytes for Mode 1, 4 bytes for Mode 2 Form 2, 280 bytes for Mode 2 Form 1)
- Subheader Buffer: Fixed-size buffer (8 bytes per sector) for Mode 2 subheaders
- Subchannel Buffer: Fixed-size buffer for block media tag data
- All buffers use doubling reallocation strategy when capacity exceeded

Address Space Management: The function handles three logical address regions:

- Negative Region: Pre-gap sectors (sector_address < negative region size, negative=true)
- User Region: Main data sectors (0 ≤ sector_address < Sectors, negative=false)
- Overflow Region: Post-data sectors (sector_address ≥ Sectors, negative=false) Internal corrected_sector_address provides linear indexing: corrected = address ± negative_size

Sector Status Classification: Status codes stored in high nibble of mini-DDT entries:

- SectorStatusMode1Correct: Valid Mode 1 sector with correct sync, timing, EDC, and ECC
- SectorStatusMode2Form1Ok: Valid Mode 2 Form 1 with correct subheader, EDC, and ECC
- SectorStatusMode2Form2Ok: Valid Mode 2 Form 2 with correct subheader and EDC
- SectorStatusMode2Form2NoCrc: Mode 2 Form 2 with zero EDC (acceptable state)
- SectorStatusErrored: Sector with validation errors, anomalous data stored in buffers
- SectorStatusNotDumped: All-zero sectors treated as not dumped

Deduplication Integration: Long sector processing does not directly perform deduplication - this occurs in the delegated aaruf_write_sector() call for the extracted user data portion. The prefix/suffix/subheader metadata is stored separately and not subject to deduplication.

Hash Calculation Behavior:

- Hashes computed on complete raw sector data (all 2352 bytes for optical, full tag+data for block)
- Only performed for sectors in user address range (not negative or overflow regions)
- Permanently disabled upon rewind detection to prevent corrupted streaming digests
- Supports MD5, SHA1, SHA256, SpamSum, and BLAKE3 simultaneously when enabled

Error Recovery and Validation:

- Sync pattern validation for optical sectors (CD standard 12-byte sync)
- MSF timing validation (Minutes:Seconds:Frames converted to LBA must match sector_address)
- Mode byte validation (01 for Mode 1, 02 for Mode 2)
- EDC validation using aaruf_edc_cd_compute() for computed vs stored comparison
- ECC validation using aaruf_ecc_cd_is_suffix_correct() and aaruf_ecc_cd_is_suffix_correct_mode2()
- Form determination from subheader flags (bit 5 of bytes 18 and 22)
- Tag format validation and conversion for block media

Thread Safety and Concurrency: This function is NOT thread-safe. The context contains mutable shared state including:

- Buffer pointers and offsets
- Hash computation contexts
- Rewind detection state
- DDT modification operations External synchronization required for concurrent access.

Performance Considerations:

- Buffer allocation occurs lazily on first use
- Buffer growth uses doubling strategy to amortize allocation cost
- Validation operations are optimized for common cases (correct sectors)
- Memory copying minimized for standard compliant sectors
- Hash updates operate on full sector to maintain streaming performance

Parameters

  context | Pointer to a valid aaruformatContext with magic == AARU_MAGIC opened for writing.
  sector_address | Logical Block Address (LBA) for the sector. For negative regions, this is the negative-space address; for user/overflow regions, this is the standard 0-based LBA.
  negative | true if sector_address refers to the negative (pre-gap) region; false for user or overflow regions.
  data | Pointer to the complete raw sector buffer. Must contain: For optical: exactly 2352 bytes of raw sector data For block media: 512 bytes + tag data (12, 20, or 24 bytes depending on format)
  sector_status | Initial sector status hint from caller. May be overridden based on validation results when delegating to aaruf_write_sector().
  length | Length in bytes of the data buffer. Must be exactly 2352 for optical discs. For block media: 512 (no tags), 524 (Sony), 532 (Profile), or 536 (Priam).

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Sector successfully processed and user data written. This occurs when: Raw sector structure parsed and validated successfully Prefix/suffix/subheader metadata stored appropriately User data portion successfully delegated to aaruf_write_sector() All buffer allocations and DDT updates completed successfully
  AARUF_ERROR_NOT_AARUFORMAT | (-1) Invalid context provided. This occurs when: context parameter is NULL Context magic number != AARU_MAGIC (wrong context type or corruption)
  AARUF_READ_ONLY | (-22) Attempting to write to read-only image. This occurs when: Context isWriting flag is false Image was opened without write permissions
  AARUF_ERROR_SECTOR_OUT_OF_BOUNDS | (-5) Sector address outside valid ranges. This occurs when: negative=true and sector_address >= negative region size negative=false and sector_address >= (Sectors + overflow region size)
  AARUF_ERROR_INCORRECT_DATA_SIZE | (-26) Invalid sector size for media type. This occurs when: length != 2352 for optical disc media length not in {512, 524, 532, 536} for supported block media types
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: Failed to allocate mini-DDT arrays (sectorPrefixDdt2, sectorSuffixDdt2) Failed to allocate or grow prefix buffer (sector_prefix) Failed to allocate or grow suffix buffer (sector_suffix) Failed to allocate subheader buffer (mode2_subheaders) Failed to allocate subchannel buffer (sector_subchannel) System out of memory during buffer reallocation
  AARUF_ERROR_INCORRECT_MEDIA_TYPE | (-12) Unsupported media type for long sectors. This occurs when: Media type is not OpticalDisc or supported BlockMedia variant Block media type does not support the provided tag format
  AARUF_ERROR_CANNOT_SET_DDT_ENTRY | (-25) DDT update failed. Propagated from aaruf_write_sector() when: User data DDT entry could not be updated DDT table corruption prevents entry modification
  AARUF_ERROR_CANNOT_WRITE_BLOCK_HEADER | (-23) Block header write failed. Propagated from aaruf_write_sector() when: Automatic block closure triggered by user data write fails File system error prevents header write
  AARUF_ERROR_CANNOT_WRITE_BLOCK_DATA | (-24) Block data write failed. Propagated from aaruf_write_sector() when: User data portion write fails during block flush Insufficient disk space or I/O error occurs

Note
  Cross-References: This function is the primary companion to aaruf_write_sector() for raw sector ingestion. See also:
  - aaruf_write_sector(): Handles user data portion writing and deduplication
  - aaruf_ecc_cd_is_suffix_correct(): CD Mode 1 ECC validation
  - aaruf_ecc_cd_is_suffix_correct_mode2(): CD Mode 2 Form 1 ECC validation
  - aaruf_edc_cd_compute(): EDC calculation and validation for all CD modes
  - aaruf_close(): Serializes prefix/suffix/subheader metadata to image file
  Buffer Management: All dynamically allocated buffers (prefix, suffix, subheader, subchannel) are automatically freed during aaruf_close(). Applications should not attempt to access these buffers directly or free them manually.
  Metadata Persistence: Prefix, suffix, and subheader data captured by this function is serialized to the image file during aaruf_close() as separate metadata blocks with corresponding mini-DDT tables for efficient access during reading.
  Tag Format Conversion: For block media, automatic conversion between Sony, Profile, and Priam tag formats ensures compatibility regardless of source format. Conversion preserves all semantic information while adapting to target media type requirements.

Warning
  Rewind Detection: Writing sectors out of strictly increasing order triggers rewind detection, permanently disabling hash calculations for the session. This prevents corrupted streaming digests but means hash values will be unavailable if non-sequential writing occurs. Plan sector writing order carefully if digest calculation is required.
  Memory Growth: Prefix and suffix buffers grow dynamically and can consume significant memory for images with many non-standard sectors. Monitor memory usage when processing damaged or non-compliant optical media.
  Media Type Constraints: This function only supports OpticalDisc and specific BlockMedia types. Other media types will return AARUF_ERROR_INCORRECT_MEDIA_TYPE. Use aaruf_write_sector() directly for unsupported media types.

See also
  aaruf_write_sector() for user data writing and deduplication
  aaruf_read_sector_long() for corresponding long sector reading functionality
  aaruf_close() for metadata serialization and cleanup

Definition at line 537 of file write.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, aaruf_ecc_cd_is_suffix_correct(), aaruf_ecc_cd_is_suffix_correct_mode2(), aaruf_edc_cd_compute(), AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_INCORRECT_MEDIA_TYPE, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_ERROR_SECTOR_OUT_OF_BOUNDS, aaruf_md5_update(), AARUF_READ_ONLY, aaruf_sha1_update(), aaruf_sha256_update(), aaruf_spamsum_update(), aaruf_write_sector(), AppleFileWare, AppleProfile, AppleSonyDS, AppleSonySS, AppleWidget, Audio, aaruformat_context::blake3_context, aaruformat_context::block_zero_written, BlockMedia, bytes_to_priam_tag(), bytes_to_profile_tag(), bytes_to_sony_tag(), aaruformat_context::calculating_blake3, aaruformat_context::calculating_md5, aaruformat_context::calculating_sha1, aaruformat_context::calculating_sha256, aaruformat_context::calculating_spamsum, CdMode1, CdMode2Form1, CdMode2Form2, CdMode2Formless, Data, DVDDownload, DVDPR, DVDPRDL, DVDPRW, DVDPRWDL, DVDR, DVDRAM, DVDRDL, DVDROM, DVDRW, DVDRWDL, aaruformat_context::ecc_cd_context, TrackEntry::end, TracksHeader::entries, FATAL, aaruformat_context::image_info, aaruformat_context::is_writing, aaruformat_context::last_written_block, aaruformat_context::magic, aaruformat_context::md5_context, ImageInfo::MediaType, ImageInfo::MetadataMediaType, aaruformat_context::mode2_subheaders, DdtHeader2::negative, Nuon, OpticalDisc, DdtHeader2::overflow, priam_tag_to_bytes(), priam_tag_to_profile(), priam_tag_to_sony(), PriamDataTower, profile_tag_to_bytes(), profile_tag_to_priam(), profile_tag_to_sony(), PS2DVD, PS3DVD, aaruformat_context::rewinded, SACD, aaruformat_context::sector_cpr_mai, aaruformat_context::sector_edc, aaruformat_context::sector_id, aaruformat_context::sector_ied, aaruformat_context::sector_prefix, aaruformat_context::sector_prefix_ddt2, aaruformat_context::sector_prefix_length, aaruformat_context::sector_prefix_offset, aaruformat_context::sector_subchannel, aaruformat_context::sector_suffix, aaruformat_context::sector_suffix_ddt2, aaruformat_context::sector_suffix_length, aaruformat_context::sector_suffix_offset, ImageInfo::Sectors, SectorStatusErrored, SectorStatusMode1Correct, SectorStatusMode2Form1Ok, SectorStatusMode2Form2NoCrc, SectorStatusMode2Form2Ok, SectorStatusNotDumped, TrackEntry::sequence, aaruformat_context::sha1_context, aaruformat_context::sha256_context, sony_tag_to_bytes(), sony_tag_to_priam(), sony_tag_to_profile(), aaruformat_context::spamsum_context, TrackEntry::start, TRACE, aaruformat_context::track_entries, aaruformat_context::tracks_header, TrackEntry::type, aaruformat_context::user_data_ddt_header, and aaruformat_context::writing_long.

## ◆ aaruf_write_sector_tag()

int32_t aaruf_write_sector_tag | ( | void * | context,
|  | const uint64_t | sector_address,
|  | const bool | negative,
|  | const uint8_t * | data,
|  | const size_t | length,
|  | const int32_t | tag )

Writes per-sector tag data (auxiliary metadata) for a specific sector.

This function stores auxiliary metadata associated with individual sectors, such as CD subchannel data, DVD auxiliary fields, track metadata, or proprietary tag formats used by specific storage systems. Unlike media tags (which apply to the entire medium), sector tags are per-sector metadata that provide additional context, error correction, copy protection, or device-specific information for each individual sector.

The function validates the tag type against the media type, verifies the data size matches the expected length for that tag type, allocates buffers as needed, and stores the tag data at the appropriate offset within the tag buffer. Some tags (like track flags and ISRC) update track metadata rather than per-sector buffers.

Supported tag types and their characteristics:

Optical Disc (CD/DVD) Tags:

- CdTrackFlags (1 byte): Track control flags for CD tracks
  - Updates track metadata in ctx->trackEntries for the track containing the sector
  - Includes flags like copy permitted, data track, four-channel audio, etc.
- CdTrackIsrc (12 bytes): International Standard Recording Code for CD tracks
  - Updates track metadata in ctx->trackEntries for the track containing the sector
  - Identifies the recording for copyright and royalty purposes
- CdSectorSubchannel (96 bytes): CD subchannel data (P-W subchannels)
  - Stored in ctx->sector_subchannel buffer
  - Contains control information, track numbers, timecodes, and CD-TEXT data
- DvdSectorCprMai (6 bytes): DVD Copyright Management Information
  - Stored in ctx->sector_cpr_mai buffer
  - Contains copy protection and media authentication information
- DvdSectorInformation (1 byte): DVD sector information field
  - Stored in first byte of ctx->sector_id buffer (4 bytes per sector)
  - Contains sector type and layer information
- DvdSectorNumber (3 bytes): DVD sector number field
  - Stored in bytes 1-3 of ctx->sector_id buffer (4 bytes per sector)
  - Physical sector address encoded in the sector header
- DvdSectorIed (2 bytes): DVD ID Error Detection field
  - Stored in ctx->sector_ied buffer
  - Error detection code for the sector ID field
- DvdSectorEdc (4 bytes): DVD Error Detection Code
  - Stored in ctx->sector_edc buffer
  - Error detection code for the entire sector
- DvdDiscKeyDecrypted (5 bytes): Decrypted DVD title key
  - Stored in ctx->sector_decrypted_title_key buffer
  - Used for accessing encrypted DVD content

Block Media (Proprietary Format) Tags:

- AppleSonyTag (12 bytes): Apple II Sony 3.5" disk tag data
  - Stored in ctx->sector_subchannel buffer
  - Contains file system metadata used by Apple II systems
- AppleProfileTag (20 bytes): Apple ProFile/FileWare hard drive tag data
  - Stored in ctx->sector_subchannel buffer
  - Contains file system and bad block metadata
- PriamDataTowerTag (24 bytes): Priam Data Tower hard drive tag data
  - Stored in ctx->sector_subchannel buffer
  - Contains proprietary metadata used by Priam drives

Sector addressing: The function supports both positive and negative sector addressing:

- Negative sectors: Lead-in area before sector 0 (for optical media)
- Positive sectors: Main data area and lead-out overflow area
- Internal correction adjusts addresses to buffer offsets

Buffer allocation: Tag buffers are allocated on-demand when the first tag of a given type is written. Buffers are sized to accommodate all sectors (negative + normal + overflow) and persist for the lifetime of the context. Memory is freed during aaruf_close().

Parameters

  context | Pointer to the aaruformat context (must be a valid, write-enabled image context).
  sector_address | The logical sector number to write the tag for. Must be within valid bounds for the image (0 to Sectors-1 for positive, 0 to negative-1 when using negative addressing).
  negative | If true, sector_address refers to a negative (lead-in) sector; if false, it refers to a positive sector (main data or overflow area).
  data | Pointer to the tag data to write. Must not be NULL. The data size must exactly match the expected size for the tag type.
  length | Length of the tag data in bytes. Must match the required size for the tag type.
  tag | Tag type identifier (from the tag enumeration). Determines which buffer to write to and the expected data size.

Returns
  Returns one of the following status codes:

Return values

  AARUF_STATUS_OK | (0) Successfully wrote sector tag. This is returned when: The context is valid and properly initialized The context is opened in write mode (ctx->isWriting is true) The sector address is within valid bounds The tag type is supported and appropriate for the media type The data length matches the required size for the tag type Memory allocation succeeded (if buffer needed to be created) Tag data was copied to the appropriate buffer or track metadata updated
  AARUF_ERROR_NOT_AARUFORMAT | (-1) The context is invalid. This occurs when: The context parameter is NULL The context magic number doesn't match AARU_MAGIC (invalid context type) The context was not properly initialized by aaruf_create()
  AARUF_READ_ONLY | (-13) The context is not opened for writing. This occurs when: The image was opened with aaruf_open() instead of aaruf_create() The context's isWriting flag is false Attempting to modify a read-only image
  AARUF_ERROR_SECTOR_OUT_OF_BOUNDS | (-5) Sector address is invalid. This occurs when: negative is true and sector_address > negative-1 negative is false and sector_address > Sectors+overflow-1 Attempting to write beyond the image boundaries
  AARUF_ERROR_INCORRECT_DATA_SIZE | (-26) Invalid data or length. This occurs when: The data parameter is NULL The length parameter is 0 The length doesn't match the required size for the tag type Tag size validation failed
  AARUF_ERROR_INCORRECT_MEDIA_TYPE | (-12) Invalid media type for tag. This occurs when: Attempting to write optical disc tags (CD/DVD) to block media Attempting to write block media tags to optical disc Tag type is incompatible with ctx->imageInfo.XmlMediaType
  AARUF_ERROR_NOT_ENOUGH_MEMORY | (-9) Memory allocation failed. This occurs when: calloc() failed to allocate buffer for tag data System is out of memory or memory is severely fragmented Buffer allocation is required but cannot be satisfied
  AARUF_ERROR_TRACK_NOT_FOUND | (-13) Track not found for sector. This occurs when: Writing CdTrackFlags or CdTrackIsrc tags The specified sector is not contained within any defined track Track metadata has not been initialized
  AARUF_ERROR_INVALID_TAG | (-27) Unsupported or unknown tag type. This occurs when: The tag parameter doesn't match any known tag type The tag type is not implemented Invalid tag identifier provided

Note
  Tag Data Persistence:
  - Tag data is stored in memory until aaruf_close() is called
  - Tags are written as separate data blocks during image finalization
  - CD subchannel and DVD auxiliary fields are written by dedicated block writers
  - Track metadata (flags, ISRC) is written as part of the tracks block
  Buffer Reuse:
  - Some tag types share the same buffer (ctx->sector_subchannel)
  - CD subchannel uses 96 bytes per sector
  - Apple Sony tag uses 12 bytes per sector
  - Apple Profile tag uses 20 bytes per sector
  - Priam Data Tower tag uses 24 bytes per sector
  - Ensure consistent tag type usage within a single image
  DVD Sector ID Split:
  - DVD sector ID is 4 bytes but written as two separate tags
  - DvdSectorInformation writes byte 0 (sector info)
  - DvdSectorNumber writes bytes 1-3 (sector number)
  - Both tags share ctx->sector_id buffer
  Tag Size Validation:
  - Each tag type has a fixed expected size
  - Size mismatches are rejected with AARUF_ERROR_INCORRECT_DATA_SIZE
  - This prevents partial writes and buffer corruption
  Media Type Validation:
  - Optical disc tags require XmlMediaType == OpticalDisc
  - Block media tags require XmlMediaType == BlockMedia
  - This prevents incompatible tag types from being written
  Multiple Writes to Same Sector:
  - Writing the same tag type to the same sector multiple times replaces the previous value
  - No warning or error is generated for overwrites
  - Last write wins

Warning
  Tag data is not immediately written to disk. All tag data is buffered in memory and written during aaruf_close(). Ensure sufficient memory is available for large images with extensive tag data.
  Mixing incompatible tag types that share buffers (e.g., CD subchannel and Apple tags) will cause data corruption. Only use tag types appropriate for your media format.
  For track-based tags (CdTrackFlags, CdTrackIsrc), tracks must be defined before writing tags. Call aaruf_set_tracks() to initialize track metadata first.

See also
  aaruf_write_media_tag() for writing whole-medium tags.
  aaruf_write_sector_long() for writing sectors with embedded tag data.
  write_sector_subchannel() for the serialization of CD subchannel data.
  write_dvd_long_sector_blocks() for the serialization of DVD auxiliary data.

Definition at line 2069 of file write.c.

References AARU_CALL, AARU_EXPORT, AARU_MAGIC, AARUF_ERROR_INCORRECT_DATA_SIZE, AARUF_ERROR_INCORRECT_MEDIA_TYPE, AARUF_ERROR_INVALID_TAG, AARUF_ERROR_NOT_AARUFORMAT, AARUF_ERROR_NOT_ENOUGH_MEMORY, AARUF_ERROR_SECTOR_OUT_OF_BOUNDS, AARUF_ERROR_TRACK_NOT_FOUND, AARUF_READ_ONLY, AARUF_STATUS_OK, AppleProfileTagAaru, AppleSonyTagAaru, BlockMedia, CdSectorSubchannelAaru, CdTrackFlags, CdTrackIsrc, DvdCmi, DvdSectorEdcAaru, DvdSectorIedAaru, DvdSectorInformation, DvdSectorNumber, DvdTitleKeyDecrypted, TracksHeader::entries, FATAL, TrackEntry::flags, aaruformat_context::image_info, aaruformat_context::is_writing, TrackEntry::isrc, aaruformat_context::magic, ImageInfo::MetadataMediaType, DdtHeader2::negative, OpticalDisc, DdtHeader2::overflow, PriamDataTowerTagAaru, aaruformat_context::sector_cpr_mai, aaruformat_context::sector_decrypted_title_key, aaruformat_context::sector_edc, aaruformat_context::sector_id, aaruformat_context::sector_ied, aaruformat_context::sector_subchannel, ImageInfo::Sectors, TrackEntry::start, TRACE, aaruformat_context::track_entries, aaruformat_context::tracks_header, and aaruformat_context::user_data_ddt_header.

## ◆ fuzzy_engine_step()

void fuzzy_engine_step | ( | spamsum_ctx * | ctx,
|  | uint8_t | c )
| inline

Definition at line 84 of file spamsum.c.

References AARU_LOCAL, b64, spamsum_ctx::bh, spamsum_ctx::bh_start, blockhash_ctx::d_len, blockhash_ctx::digest, fuzzy_try_fork_blockhash(), fuzzy_try_reduce_blockhash(), blockhash_ctx::h, blockhash_ctx::half_digest, blockhash_ctx::half_h, HASH_INIT, roll_hash(), ROLL_SUM, SPAMSUM_LENGTH, SSDEEP_BS, and SUM_HASH.

Referenced by aaruf_spamsum_update().

## ◆ fuzzy_try_fork_blockhash()

void fuzzy_try_fork_blockhash | ( | spamsum_ctx * | ctx | ) |
| inline

Definition at line 175 of file spamsum.c.

References AARU_LOCAL, spamsum_ctx::bh, spamsum_ctx::bh_end, blockhash_ctx::d_len, blockhash_ctx::digest, blockhash_ctx::h, blockhash_ctx::half_digest, blockhash_ctx::half_h, and NUM_BLOCKHASHES.

Referenced by fuzzy_engine_step().

## ◆ fuzzy_try_reduce_blockhash()

void fuzzy_try_reduce_blockhash | ( | spamsum_ctx * | ctx | ) |
| inline

Definition at line 155 of file spamsum.c.

References AARU_LOCAL, spamsum_ctx::bh, spamsum_ctx::bh_end, spamsum_ctx::bh_start, blockhash_ctx::d_len, SPAMSUM_LENGTH, SSDEEP_BS, and spamsum_ctx::total_size.

Referenced by fuzzy_engine_step().

## ◆ roll_hash()

void roll_hash | ( | spamsum_ctx * | ctx,
|  | uint8_t | c )
| inline

Definition at line 137 of file spamsum.c.

References AARU_LOCAL, roll_state::h1, roll_state::h2, roll_state::h3, roll_state::n, spamsum_ctx::roll, ROLLING_WINDOW, and roll_state::window.

Referenced by fuzzy_engine_step().