Technical Article

Memory-Mapped PDF Reading in Delphi: Sliding Window

Wrap a TFileStream in a critical section, take the lock inside Seek, take it again inside Read, and two worker threads pulling objects out of the same large PDF can still hand each other the wrong bytes. Each call is protected. The pair is not. Between thread A's Seek and its Read, thread B moves the one shared cursor, and A copies part of a font program into a buffer it believes holds an image stream. A bigger lock around both calls works, right up until every page and object worker in the process queues behind it. The cleaner answer is a read call that carries its own offset and never touches the cursor, served from a view of the file that stays the same size whether the PDF is 20 MB or 20 GB

Why a loaded PDF keeps going back to disk

Loading a PDF does not finish reading it. A cross-reference table or cross-reference stream (ISO 32000-1 §7.5.4 and §7.5.8) records only where each indirect object starts; the bytes themselves arrive later, when a page is rendered, a font program is decoded, or an embedded file stream (ISO 32000-1 §7.11.4) is extracted. Suppose an archive of 2 GB holds tens of thousands of objects. After the load, every one of those objects is a small read at an offset nobody knew in advance, issued in whatever order the rendering or extraction job happens to need it

The ordinary positional stream pays for that pattern twice. Every fragment goes through a file read call even when the operating system already holds that page in its cache, and every fragment has to move the shared position first. The second cost is the one that bites. Per-call locking cannot close the gap between a Seek and the Read that follows it, so once concurrent page and object work share one stream, the read itself has to carry its offset, and the local-file path and the range-served path behind progressive PDF range loading with prefetch should share that contract rather than each inventing its own

TPDFReadAtStream: one contract for absolute reads

PDFlibPas defines that contract as TPDFReadAtStream, an abstract TStream descendant with exactly one virtual method. ReadAt takes an absolute offset, copies up to Count bytes, returns how many it copied, and leaves Position exactly where it was. Two sources in the PDF Library for Delphi derive from it: TReadOnlyMappedFileStream for local files and TByteRangeStream for remote files served in byte ranges. When the parser needs an object slice, it checks once whether its source is a TPDFReadAtStream; if the source is a plain TFileStream or TMemoryStream, it falls back to the familiar seek-then-read sequence and nothing else changes

PDFlibPas routes object-slice reads through TPDFReadAtStream, an abstract TStream descendant whose single virtual ReadAt(Offset, Buffer, Count) honours an absolute offset without touching Position; TReadOnlyMappedFileStream covers local files through a mapped window and TByteRangeStream covers range-served remote sources, while the parser asks once for the interface and otherwise falls back to the ordinary Seek plus Read sequence
Both cursor-independent sources in PDFlibPas derive from one abstract base, so nested parser levels issue absolute reads with no save-and-restore dance and an ordinary stream still works through the seek-then-read fallback
type
  // Read-only streams whose absolute reads avoid a shared Seek plus Read
  TPDFReadAtStream = class(TStream)
  public
    function ReadAt(Offset: Int64; var Buffer;
      Count: Integer): Integer; virtual; abstract;
  end;

  // Windowed read-only access to one local file
  TReadOnlyMappedFileStream = class(TPDFReadAtStream)
  private
    FMemoryMapped: Boolean;
  public
    constructor Create(const FileName: WideString; WindowSize: Int64 = 0);
    function GetStats: TPDFMappedFileStats;
    function Read(var Buffer; Count: Longint): Longint; override;
    function ReadAt(Offset: Int64; var Buffer;
      Count: Integer): Integer; override;
    function Write(const Buffer; Count: Longint): Longint; override;
    function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
    property MemoryMapped: Boolean read FMemoryMapped;
  end;

The mapped stream is still a complete TStream. Read, Seek and Size behave the way stream code expects, Seek clamps the logical position into the range from 0 to the file size, and Write always returns 0 because the file is opened read-only. One critical section covers the mapped view, the fallback file cursor, the logical position and the statistics. ReadAt takes it and copies; Read takes the same lock, copies from the current logical position through the same internal path, and then advances that position before releasing it. So a sequential reader and any number of absolute readers can share one instance, and a remap triggered by one caller cannot pull the view out from under another caller mid-copy

Opening a gigabyte PDF through a mapped view

Mapping is opt-in through two explicit entry points. LoadFromMappedFile loads a document and selects it, just like LoadFromFile. DAOpenMappedFile returns a Direct Access handle, which is the mode you want when merging and splitting gigabyte PDFs through Direct Access. LoadFromFile and DAOpenFile keep their existing file sharing, error codes and compatibility behaviour, so code that never calls the mapped variants sees no difference at all. Both mapped entry points take a WindowSize in bytes and an Options bitmask, and both parameters default to 0

var
  Pdf: TPDFlib;
  I: Integer;
  Info: WideString;
begin
  Pdf := TPDFlib.Create;
  try
    // WindowSize 0 selects the 64 MiB default; mapping is mandatory here
    if Pdf.LoadFromMappedFile('archive-2026.pdf', '', 0,
      PDF_MAPPED_FILE_REQUIRE_MAPPING) <> 1 then
      raise Exception.CreateFmt('mapped open refused, LastErrorCode=%d',
        [Pdf.LastErrorCode]);

    // Embedded file indexes are 1-based; each payload goes straight to disk
    for I := 1 to Pdf.EmbeddedFileCount do
      if Pdf.GetEmbeddedFileContentToFile(I,
        Format('attachment-%d.bin', [I])) <> 1 then
        Writeln('attachment ', I, ' was not written');

    // {"memoryMapped":true,"fileSize":...,"windowSize":67108864,...}
    if Pdf.GetMappedFileInfo(Info) = 1 then
      Writeln(Info);
  finally
    Pdf.Free;
  end;
end;

For large attachments we would pick GetEmbeddedFileContentToFile over GetEmbeddedFileContentToString every time. The string variant returns the whole decoded payload as one AnsiString, which on a 32-bit build competes for the same address space the mapped window needs. One more thing trips people up the first time: GetMappedFileInfo answers only for documents opened through LoadFromMappedFile. Call it on a document loaded with LoadFromFile or LoadFromStream and it returns 0 with LastErrorCode 401, which reads like a broken file until you notice which entry point opened it

What does PDF_MAPPED_FILE_REQUIRE_MAPPING enforce?

PDF_MAPPED_FILE_REQUIRE_MAPPING makes the open fail unless the first mapped view was actually established, and reports the refusal as LastErrorCode 401. With Options left at 0, both entry points accept a read-only file-stream fallback instead: if the target platform has no mapping code, or the mapping call fails, the document still opens and every read goes through an ordinary file stream. That fallback is convenient for portable code and annoying in a benchmark, because a document that opened without a mapping performs exactly like LoadFromFile and gives you no outward sign of it

PDFlibPas mapped entry points LoadFromMappedFile and DAOpenMappedFile fall back to a read-only file stream when no mapping can be established, but PDF_MAPPED_FILE_REQUIRE_MAPPING turns that quiet downgrade into an immediate refusal at open time with LastErrorCode 401, the same code returned for a negative WindowSize or an unknown Options bit
Without the flag a missing mapping degrades silently into ordinary file-stream reads; with it, the document only opens when the first view exists, so a portable promise that can legitimately fail announces itself at open time

On Windows the mapped stream opens a second read-only handle with FILE_SHARE_READ, FILE_SHARE_WRITE and FILE_SHARE_DELETE plus FILE_FLAG_RANDOM_ACCESS, creates a PAGE_READONLY mapping over it, and maps the first window inside the constructor. Mapping eagerly is deliberate. A "mapping required" failure belongs at the LoadFromMappedFile call, where the caller can still choose another path, and should not wait for the first deferred object read halfway through a rendering job. The mapping code is compiled for Windows targets only, and a zero-byte file never attempts a mapping, so on Linux or macOS the flag refuses every open. A negative WindowSize, any Options bit other than this one, and a file that does not exist are all rejected with the same 401

Our advice is to set the flag in Windows builds where mapping is the reason you chose this entry point, and to leave it at 0 in code shared with other platforms. Know where its reach ends, though. The flag checks the first view only. If a later remap fails, for example because a 32-bit process has no contiguous block of address space left for the next window, the stream closes the mapping and finishes the job through plain file reads. The document keeps working; the statistics simply flip memoryMapped to false

Sizing the sliding window

The mapped stream holds exactly one view at a time, so the address space it uses does not grow with the file. A WindowSize of 0 selects 64 MiB. A value below the system allocation granularity is raised to it, a value above 1 GiB is capped, and the result is rounded up to a whole number of granularity units: 65536 bytes on Windows unless GetSystemInfo reports a different dwAllocationGranularity. When a read lands outside the current view, the stream unmaps it, aligns the requested offset down to a granularity boundary and maps a fresh window there. The last window is clamped to the physical file size, so the view never reaches past the end of the file

PDFlibPas keeps exactly one sliding read-only window over a gigabyte PDF: a read landing outside the current view unmaps it, aligns the offset down to the 65536-byte allocation granularity and maps a fresh window clamped to the file size, while the windowSize, mappedOffset and remapCount fields that GetMappedFileInfo reports show what was actually retained
Only one view is ever retained and it is remapped on demand at allocation-granularity boundaries, which keeps address space flat on gigabyte files while every byte still arrives through an absolute-offset copy into parser buffers

A single read may cross any number of windows. The copy loop takes what the current view can supply, remaps, and continues; a request that runs past the end of the file returns a short count rather than failing. The stream never hands out a pointer into the view, because the next cross-window read would unmap the memory behind it and no caller could defend against that. Bytes are copied straight into buffers the parser owns, which removes the extra file input buffer and the position juggling, at the price of one memory copy per fragment. The write side composes with this too: byte-level reference shifting during a fast PDF merge streams object bytes out while the mapped source feeds them in

For a 2 GiB file read front to back, the default window works out to about 32 view positions, so remapCount should end near 32. A 16 MiB window raises that to about 128. Random access is different: a job that alternates between pages stored at opposite ends of the file can force a remap on nearly every read when the window is small. In a 64-bit process we would keep the 64 MiB default and only move it after GetMappedFileInfo shows a remap count far above the sequential estimate. In a 32-bit process we would start at 16 MiB, because every remap needs one contiguous free block of that size and fragmentation in a busy 32-bit address space is exactly what makes a large remap fail

Reading the statistics, and one Free Pascal trap

GetMappedFileInfo for a loaded document and DAGetMappedFileInfo for a Direct Access handle return the same JSON object. Read it once the work is done: a remap failure partway through shows up there and nowhere else. The example below walks every page of a mapped Direct Access file and then checks whether the mapping survived the run

var
  Pdf: TPDFlib;
  Handle, Page, PageRef: Integer;
  Info: WideString;
begin
  Pdf := TPDFlib.Create;
  try
    // 16 MiB windows leave more headroom in a 32-bit process
    Handle := Pdf.DAOpenMappedFile('archive-2026.pdf', '',
      16 * 1024 * 1024, PDF_MAPPED_FILE_REQUIRE_MAPPING);
    if Handle = 0 then
      raise Exception.CreateFmt('DAOpenMappedFile failed, LastErrorCode=%d',
        [Pdf.LastErrorCode]);
    try
      for Page := 1 to Pdf.DAGetPageCount(Handle) do
      begin
        PageRef := Pdf.DAFindPage(Handle, Page);
        Writeln(Pdf.DAExtractPageText(Handle, PageRef, 0));
      end;

      // Your own check, not a library call: the flag only guarded the open
      if (Pdf.DAGetMappedFileInfo(Handle, Info) = 1) and
        (Pos('"memoryMapped":false', Info) > 0) then
        Writeln('mapping dropped during the run: ', Info);
    finally
      Pdf.DACloseFile(Handle);
    end;
  finally
    Pdf.Free;
  end;
end;
  • memoryMapped is false whenever the file-stream fallback is serving reads, whether that started at open or after a failed remap
  • windowSize is the effective, aligned window rather than the value you requested; mappedBytes is smaller than it when the current view is the tail window
  • mappedOffset is the aligned start of the current view, or -1 when no view is active
  • readCalls counts in-range read requests, bytesRead counts bytes copied to callers, and remapCount includes the initial view
  • fileSize is the physical size captured when the stream was created

The Free Pascal trap is worth knowing if you write your own locked stream class. FPC's Windows unit declares a record named TCriticalSection, and once that unit is in the uses clause it shadows SyncObjs.TCriticalSection. We ran into this when the mapped stream gained its lock: Delphi compiled the unqualified field without complaint, while FPC resolved it to the record, which has no Create, Enter or Leave, so the build failed at every use of the lock. Writing SyncObjs.TCriticalSection at both the field declaration and the construction site settles it for both compilers

If your profiler on a gigabyte PDF job keeps pointing at file reads rather than at parsing, swapping LoadFromFile for LoadFromMappedFile is a one-line experiment, and the JSON from GetMappedFileInfo tells you whether the mapping held for the whole run. A trial build and the full API reference are on the PDF Library for Delphi product page