Skip to content

Media Primitives

miniproto handles chunked upload, messages.sendMedia, upload.getFile, CDN redirects and reupload tokens, AES-CTR CDN decryption, resumable destinations and progress callbacks. Rich-media wrappers, bound message helpers, albums, thumbnail generation and framework ergonomics belong in the planned mpgram layer.

Use Client.send_file(peer, file, caption="...") for a standard upload. It uses 512 KiB parts by default, upload.saveFilePart for files up to 10 MiB and upload.saveBigFilePart for larger files, then sends messages.sendMedia with inputMediaUploadedDocument by default. quick_ack=True or quick_ack_callback=callback applies only to that final RPC. It does not request an acknowledgement for each upload part or replace the final Telegram result.

High-level uploads use two dedicated MTProto sender lanes by default. A reset on a media lane leaves unrelated requests on the main sender and other media lanes alone. media_lanes=0 uses the main sender; a positive value sets the number of media lanes independently of part concurrency. Low-level callers can use miniproto.media.upload_file() to get the generated InputFile or InputFileBig object.

For uploads, max_buffer_size checks that the requested part_size * concurrency fits. The producer queue and active sends both retain part payloads, and automatic part-size growth to meet max_file_parts can raise memory use beyond that value. Treat it as a concurrency-window check, not a process-memory cap.

Normalized Media objects for documents and photos expose media.file_id. The mpf1_ value is base64-encoded JSON containing reusable Telegram location fields, including the access hash and file reference. Treat it as sensitive reference data. Decoding does not check account permissions or refresh an expired file reference. Messages returned by helpers and pushed message events expose normalized media. Photo file IDs and downloads select the largest declared variant, including the final size of a progressive photo. Passing a file ID to Client.send_file(peer, file_id, caption="...") sends inputMediaDocument or inputMediaPhoto and skips reuploading the bytes. Telegram represents videos, GIFs, audio, voice notes, stickers and ordinary files as document media with different DocumentAttribute values, so miniproto groups those under the document file-ID family and photos under photo. upload_file() enforces Telegram’s upload-part ceiling and can grow a caller-supplied small part_size up to the 512 KiB maximum to stay under max_file_parts. Client.send_file(..., upload_limit_parts="app_config") fetches the current help.getAppConfig value when you need the server’s current part limit.

Supported upload inputs are paths, bytes-like objects, seekable binary file objects, sync iterables of byte chunks and async iterables of byte chunks. Miniproto spools unknown-size sources so it can choose the small- or big-file method, retain photo upload support and check the part cap before sending. Telegram also defines a streamed upload mode that sends an unknown total as -1 (that mode always uses upload.saveBigFilePart and excludes uploaded photos). When max_file_parts is enabled, the spool rejects a chunk before writing beyond that count times the maximum 512 KiB part size. max_file_parts=None explicitly removes that bound. Immediate chunk producers periodically yield so cancellation can run. Owned spools close on setup failure, transfer failure or cancellation, while caller-owned readers stay open. Short reads are combined to fill each expected part. EOF before the measured size raises MediaUploadError, a successful result matches the bytes and parts accepted by Telegram. Keep seekable sources unchanged while the upload runs. Upload progress callbacks receive monotonically increasing byte counts. If an async callback is still running, later completions accumulate into the next callback, and the upload waits for final progress delivery. Telegram file uploads

Use Client.download_media(media, destination=None) for a standard download. It resolves public Media, miniproto file IDs, raw MessageMediaDocument, MessageMediaPhoto, Document, Photo or generated InputFileLocation objects into upload.getFile requests. With no destination, it returns bytes in MediaDownloadResult.data; a path destination writes to disk.
Public media operations require a connected client before creating lanes or scheduler registrations. Path destinations grow as downloaded chunks are written, declared sizes and limits do not preallocate disk space. Size metadata still controls requested coverage and progress, so applications should validate their own accepted download sizes.

With resume=True, the client trusts bytes already in the destination. If the file already covers a requested limit, the operation makes no file request and truncates the path to that limit on success. If more data is needed, the client resumes from the last 1 KiB boundary and re-downloads the unaligned tail. A failed download restores the original contents, including that tail. New downloads use a private temporary sibling. Success publishes the completed file atomically and retains an existing target’s POSIX access bits. A symbolic link keeps pointing to its target. Other hard links to the old inode keep their previous contents. Once final publication starts, the client waits for and returns its outcome.

With no concurrency or ClientConfig.media_concurrency override, downloads use concurrency=6 pipelined requests across two warm sender lanes. They start with 512 KiB parts, can adapt up to 1 MiB and use an 8 MiB rolling in-flight byte window. media_lanes=0 uses the main sender. max_in_flight_bytes (or the legacy max_buffer_size alias) limits the requested-but-unyielded and reorder byte window. It does not cap total process memory. Plain-hash verification and CDN verification may assemble complete hash intervals outside this window; cache/read-ahead, transport and writer buffers, and in-memory results also need separate allowances.

The 8 MiB window applies to one transfer. All transfers from one client also share byte-weighted schedulers keyed by (target DC, direction). Download and upload traffic use separate budgets. Each request reserves bytes in 64 KiB units while its RPC runs; retry and flood sleeps keep the transfer’s local slot but release the shared permit. The defaults are 16 MiB for downloads and 8 MiB for uploads per DC, configured with ClientConfig.media_download_max_in_flight_bytes_per_dc and ClientConfig.media_upload_max_in_flight_bytes_per_dc. These values are separate from media_max_buffer_size and max_in_flight_bytes.

Schedulers use deficit round robin across transfers. Foreground requests get priority. After eight foreground grants, a scheduler tries a background queue head first; it grants that request only when its deficit, byte budget and operation limit fit. If the background head does not fit, the scheduler tries foreground work.

For downloads, the scheduler applies Telegram’s 20 MiB small/large same-DC operation classes. Explicit ClientConfig.media_download_small_queue_limit and media_download_large_queue_limit values take precedence. Otherwise, miniproto uses fallback limits of five small and two large transfers, then updates them when help.getAppConfig supplies small_queue_max_active_operations_count or large_queue_max_active_operations_count. Missing dynamic values do not set capacity to zero. FILE_MIGRATE_X moves the transfer registration and future permits to the target DC without changing the main session.

Client.iter_download(media, ...) exposes the same ordered engine as an async byte iterator. It accepts the range, precision, part-size, concurrency, lane, retry, cache, read-ahead, reference-refresh and integrity options from download_media(), but it has no destination and does not accept resume or bot multi_session. Resume a stream by setting offset. The iterator yields the first verified part before later requests finish. It holds out-of-order results until their predecessors arrive, and max_in_flight_bytes bounds requested but unyielded data and the reorder buffer. Verifier overfetch, cache/read-ahead, transport and destination memory use separate allowances.

Call await iterator.aclose() or use async with contextlib.aclosing(iterator): to close early and cancel and join iterator-owned part tasks. A bare break from async for does not close the iterator at that point. Closing the iterator does not cancel shared range-cache fetches. The cache owns those tasks and retains cached bytes until eviction or await cache.clear(), which cancels pending cache producers and clears entries. download_file() and download_media() use the same engine and a destination writer, so they share its range validation, migration, refresh, CDN, retry, ordering and integrity behavior.

Bot downloads can use auxiliary authorization keys with multi_session=True. Miniproto uses one session through 50 MiB, two through 250 MiB and four above 250 MiB. The option is off by default and applies only to complete, known-size bot downloads. For user accounts, resumed or ranged downloads, and unknown-size inputs, miniproto logs an error and uses one session. It creates auxiliary sessions only when the file size needs them. Each one issues one 1 MiB request at a time and does not poll or receive updates.

Auxiliary sessions keep their storage for later downloads and process restarts. The workers open independent file handles onto one temporary file and write their assigned ranges at their final offsets. Once every range and file identity has been checked, a path destination is flushed, synced and atomically replaced. An in-memory result reads the temporary file once. A caller-owned stream receives one sequential copy and flush. Failure cleanup joins workers and any finalization already in progress before removing staging files and disconnecting auxiliary clients. A finalization that has already started can complete during cancellation. Cleanup preserves the original failure or cancellation, disconnect errors are logged. Main-client shutdown also runs auxiliary cleanup. With EncryptedSQLiteSessionStorage("bot.sqlite", ...), sibling storage names are bot-download-1.sqlite through bot-download-3.sqlite. Pass the bot token through ClientConfig(..., bot_token=token) when a missing auxiliary session may need authorization after restart. A token passed to sign_in_bot(token) stays in memory only for that client lifetime. Built-in in-memory and encrypted SQLite storage support sibling sessions, custom storage without sibling support logs an error and uses one session.

Media-lane pools are keyed by operation kind and target DC. New pool targets must match a configured session DC option, including media-only endpoints, before a pool or idle reaper is allocated. Requesting a different lane count resizes the existing pool. Miniproto prewarms lanes in parallel at transfer start and closes lanes that sit idle for ClientConfig.media_idle_close seconds, 120 by default. Set it to None to keep them open, closed lanes reopen on the next transfer. Media stored on another DC uses a dedicated pool for that DC and an exported authorization (auth.exportAuthorization -> per-DC auth key -> auth.importAuthorization on the media connection). FILE_MIGRATE_X moves future media requests to the target DC without changing the main session.

Every emitted upload.getFile request satisfies Telegram’s alignment rules: without precise, offsets and limits are 4 KiB-aligned, limits divide 1 MiB and requests never straddle a 1 MiB boundary; miniproto switches individual transfers to precise mode automatically when 1 KiB granularity is needed (odd resume offsets or sub-4 KiB part sizes). part_size/max_part_size must be powers of two.

Concurrent downloads treat FLOOD_WAIT as a pacing signal. The flooded request sleeps while holding its window slot, so miniproto does not launch replacement work into that slot. Other active requests continue. Flood retries use a separate cap of 16 per part and do not consume max_retries. FLOOD_WAIT_0 sleeps for at least 1 second; each flood sleep adds at most 0.3 seconds of jitter.

Generic floods pause adaptive-window growth but do not shrink the window. After a cooldown, eight clean request completions increase the window by one. Disconnects and timeouts reduce it by one. FloodPremiumWait switches the adaptive window to one request for the rest of the transfer and prevents further window growth.

Downloads fill the initial request window immediately. With the default launch_stagger=True, a flood wait enables pacing for subsequent launches. The pacer estimates a rate from recent completions and caps its added spacing at 250 ms. Pacing is skipped when the active window is one. Large downloads sample bytes received over elapsed wall time and try larger chunks up to 1 MiB. A regression returns the part size to the best observed value. Set adaptive_part_size=False to keep the chunk size fixed or adaptive_concurrency=False to keep the request window fixed.

For range-style workflows, pass range_cache=True or a DownloadRangeCache plus an optional read_ahead_bytes budget. Both high-level download APIs derive an automatic canonical file ID from the resolved document/photo location, including its type, ID, access hash, file reference and thumbnail. A supplied Media.file_id cannot name a different raw attachment’s cache entries. Size, filename, MIME metadata and alternate JSON spellings do not partition the same effective location. Legacy locations without a supported file-ID encoding have no automatic key. Raw download_file() callers can pass range_cache_key, they own its correspondence to the requested location.

Read-ahead is disabled for open-ended streams (limit=None) and ranges that reach or pass the known file end. Miniproto records media.download.read_ahead_disabled when it disables read-ahead. Background prefetch is capped at 32 tasks. Overlapping prefetches from one transfer share a single background scheduler registration. Path-backed writes use a threaded writer on sequential and concurrent downloads. Each destination write() must accept the full payload, a short write raises MediaDownloadError. Known-size concurrent downloads require every requested byte range to be received and committed before success. An empty or short response before the target end raises MediaDownloadError. Failure or cancellation joins owned part and writer tasks before discarding its own staging file or restoring the open resumed file to its original contents. Secondary progress or write acknowledgement errors during unwind cannot skip cleanup or replace the original failure, and progress callbacks remain cancellable. Filesystem rollback failures are logged without replacing the original error or cancellation. Resume does not compare the retained prefix with the remote file, so verify that it belongs to the same file when integrity matters. Progress callbacks run at most once per 250 ms or 8 parts. The final callback runs only after complete coverage and destination flush.

The default download does not enable a range cache. range_cache=True or read-ahead without an explicit cache intentionally uses the process-shared cache. Its media/range keys do not distinguish accounts, sessions or Telegram environments, so a hit or pending fetch can reuse bytes without another account’s file request. Use this sharing only when all callers may access the same cached data.
For account/session isolation, create a separate DownloadRangeCache for each account/session and Telegram environment, then pass it explicitly to every cached or read-ahead download. Stop its consumers and call await cache.clear() before disconnecting its producing client or changing the cache’s account/session ownership. Clearing cancels and joins pending producers and drops entries. Cached payloads are not zeroized. The cache retains 32-byte SHA-256 key identities and evicts completed ranges by both max_bytes and max_entries, the latter defaults to 4,096. The byte budget measures payloads only, pending fetch counts still follow caller concurrency.
File-reference refresh is available through the low-level file_reference_refresher hook, and miniproto deduplicates concurrent refreshes for the same old reference. Client.download_media() installs a message-backed refresher when given a raw Telegram message, a public Message retaining its raw message, or a Media retaining its raw source message. It refetches the message through messages.getMessages or channels.getMessages and retries with a renewed reference only when the concrete location type and every other TL location field still match the original. An edited attachment raises MediaDownloadError instead of replacing the requested file, even if its size matches. Multi-session assembly also checks each worker’s returned location identity.

Ordinary non-CDN downloads can opt into Telegram’s upload.getFileHashes verification with verify_plain_hashes=True; the default is off. Miniproto validates and caches hash metadata by file-location identity, fetches missing coverage through the same target-DC media context, then checks SHA-256 before yielding a part or writing it. A complete hash interval inside the received bytes is checked locally. At a partial boundary, miniproto fetches the full interval and compares the overlap before releasing the requested bytes. Invalid intervals, gaps, contradictory overlaps, response loops, location changes and digest mismatches raise MediaIntegrityError with only the non-secret offset and length. CDN verification is mandatory; CDN integrity failures raise CdnIntegrityError. With plain verification off, miniproto sends no upload.getFileHashes requests.
Plain verification admits at most 4,096 entries in one hash response, including duplicates, and retains at most 65,536 distinct intervals per location identity. These are local resource policies, independent of Telegram limits and the plaintext cache. Exceeding either raises MediaIntegrityError. Metadata commits only after the bounded batch passes duplicate and overlap checks, retained contradiction history is not evicted. Ordered interval lookup avoids rescanning the full history for each hash.

When upload.getFile returns upload.fileCdnRedirect, miniproto keeps upload.getCdnFileHashes and upload.reuploadCdnFile on the authorized origin path. It creates a separate auth-key-only sender for the CDN datacenter and sends upload.getCdnFile through that sender. CDN senders use RSA keys from help.getCdnConfig; miniproto does not import user authorization into a CDN datacenter.
Each transfer caches its redirect and the hashes returned by the origin, including hashes returned during reupload. A CDN request can span several complete hash intervals, with at most three reupload authorizations per wire range. CDN data requests register the logical transfer with the shared download scheduler for the actual CDN DC, preserving its size class and priority. Each wire attempt reserves its requested bytes, including verifier overfetch, and releases the permit before retry or flood-wait sleep. Origin metadata and reupload requests keep their origin routing and permits.

CDN requests use stricter boundaries than precise origin-file requests. Miniproto over-fetches a legal 4 KiB-aligned range whose limit divides 1 MiB, decrypts it with the redirect IV prefix plus the requested block counter, verifies every complete Telegram-declared SHA-256 interval through origin metadata, then returns the requested slice. Miniproto does not accept a finite 1 KiB or 4 KiB range based on partial bytes alone. Live CDN authorization, routing and edge behavior require separate gated integration coverage.

The opt-in live check is tests/integration/test_media_live.py. It requires MINIPROTO_INTEGRATION=1, MINIPROTO_REAL_INTEGRATION=1, MINIPROTO_API_ID, MINIPROTO_API_HASH, MINIPROTO_SESSION_KEY and an existing MINIPROTO_TEST_UPLOAD_FILE. It reuses an encrypted phone session when one exists; otherwise it also requires MINIPROTO_REAL_PHONE and login-code entry enabled by MINIPROTO_LIVE_PROMPT_CODE=1 in an interactive shell. If the account uses 2FA, provide MINIPROTO_REAL_PASSWORD or enter it interactively. MINIPROTO_TEST_DOWNLOAD_PATH is optional and defaults to .tmp/miniproto-live-download.bin. The test skips when external prerequisites are absent.
Interactive login codes and 2FA passwords use hidden terminal input. If hidden input is unavailable, the prompt raises rather than falling back to echoed input. Environment-provided passwords retain their exact whitespace. The benchmark’s HTTP form also masks code entry. Authorized POST bodies require one decimal Content-Length of at most 256 bytes, transfer encoding is rejected, and an absolute five-second read deadline is capped by the remaining prompt lifetime. Keep this transient prompt behind the access boundary described in the development guide.

Media requests are not controlled only by a count of coroutines. MediaSchedulerRegistry owns lazy schedulers keyed by (data centre, direction), where direction is upload or download. A transfer opens a registration, then acquires a permit before a chunk request. Each permit charges the request rounded up to a 64 KiB unit and returns capacity exactly once when released.

The default ClientConfig byte budgets are 16 MiB per DC for downloads and 8 MiB per DC for uploads. Download schedulers also default to five active small transfers and two active large transfers. The scheduler classifies known transfers of at least 20 MiB and unknown-size transfers as large. These are local resource limits, not claims about Telegram’s own throughput or rate limits.

Within one scheduler, grants use deficit round robin across logical transfers. Foreground requests get priority. After eight foreground grants, the scheduler tries a background queue head first; it grants that request only when its deficit, byte budget and operation limit fit. If it cannot grant the background head, it tries foreground work. MediaSchedulerSnapshot reports queued bytes, active bytes, the scheduler’s lifetime grant count and per-transfer grants for current registrations.

Each data centre and transfer direction has its own scheduler, so uploads do not consume download capacity and separate DCs do not share one byte budget. Transfers aimed at the same DC and direction share that scheduler.

Cancelling a queued acquire removes it; cancelling immediately after grant releases the just-granted capacity. Closing a transfer rejects new acquires and cancels still-pending work, while a live permit remains charged until its owner releases it. This prevents cancellation and shutdown from leaking scheduler capacity.

When Telegram redirects future work to another DC, a transfer can rebind. Pending future work moves to the new scheduler; already granted permits drain at the old binding. Schedulers are evicted only after complete drain and client disconnect closes the registry. Use async with for a permit whenever practical so exceptional control flow returns capacity.