> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/argmaxinc/WhisperKit/llms.txt
> Use this file to discover all available pages before exploring further.

# Core Protocols

> Protocol definitions for WhisperKit's modular pipeline components

WhisperKit's transcription pipeline is built from modular, protocol-based components. This allows you to customize or replace individual parts of the pipeline while maintaining compatibility with the rest of the system.

## AudioProcessing

Handles audio loading, recording, and preprocessing.

### Required Properties

<ResponseField name="audioSamples" type="ContiguousArray<Float>">
  Stores the audio samples to be transcribed.
</ResponseField>

<ResponseField name="relativeEnergy" type="[Float]">
  A measure of current buffer's energy in dB, normalized from 0-1 based on the quietest buffer's energy in a specified window.
</ResponseField>

<ResponseField name="relativeEnergyWindow" type="Int">
  How many past buffers of audio to use when calculating relative energy. The lowest average energy value within this window is used as the silence baseline.
</ResponseField>

### Required Methods

<ResponseField name="loadAudio(fromPath:channelMode:startTime:endTime:maxReadFrameSize:)" type="static func">
  Loads audio data from a specified file path.

  **Parameters:**

  * `audioFilePath: String` - The file path of the audio file
  * `channelMode: ChannelMode` - How to handle multi-channel audio
  * `startTime: Double?` - Optional start time in seconds
  * `endTime: Double?` - Optional end time in seconds
  * `maxReadFrameSize: AVAudioFrameCount?` - Maximum frames to read at once

  **Returns:** `AVAudioPCMBuffer` containing the audio data
</ResponseField>

<ResponseField name="loadAudio(at:channelMode:)" type="static func">
  Loads and converts audio data from multiple file paths.

  **Parameters:**

  * `audioPaths: [String]` - Array of file paths
  * `channelMode: ChannelMode` - How to handle multi-channel audio

  **Returns:** Array of `Result<[Float], Error>` for each file
</ResponseField>

<ResponseField name="padOrTrimAudio(fromArray:startAt:toLength:saveSegment:)" type="static func">
  Pads or trims audio data to the desired length.

  **Parameters:**

  * `audioArray: [Float]` - Audio frames to process
  * `startIndex: Int` - Index to start at
  * `frameLength: Int` - Desired length in frames
  * `saveSegment: Bool` - Whether to save for debugging

  **Returns:** `MLMultiArray?` containing the processed audio
</ResponseField>

<ResponseField name="padOrTrim(fromArray:startAt:toLength:)" type="func">
  Instance method to pad or trim audio data.

  **Returns:** `AudioProcessorOutputType?`
</ResponseField>

<ResponseField name="purgeAudioSamples(keepingLast:)" type="func">
  Empties the audio samples array, keeping the last N samples.
</ResponseField>

<ResponseField name="startRecordingLive(inputDeviceID:callback:)" type="func">
  Starts recording audio from the specified input device, resetting previous state.

  **Parameters:**

  * `inputDeviceID: DeviceID?` - Input device (macOS only)
  * `callback: (([Float]) -> Void)?` - Called with each audio buffer
</ResponseField>

<ResponseField name="startStreamingRecordingLive(inputDeviceID:)" type="func">
  Starts live audio recording with an async stream.

  **Returns:** Tuple of `AsyncThrowingStream<[Float], Error>` and its continuation
</ResponseField>

<ResponseField name="pauseRecording()" type="func">
  Pauses the current recording.
</ResponseField>

<ResponseField name="stopRecording()" type="func">
  Stops recording and cleans up resources.
</ResponseField>

<ResponseField name="resumeRecordingLive(inputDeviceID:callback:)" type="func">
  Resumes recording audio, appending to continuous audioArray after pause.
</ResponseField>

## FeatureExtracting

Extracts mel spectrogram features from audio.

### Properties

<ResponseField name="melCount" type="Int?">
  Number of mel frequency bins (typically 80 or 128).
</ResponseField>

<ResponseField name="windowSamples" type="Int?">
  Number of audio samples per window (typically 480,000 for 30 seconds at 16kHz).
</ResponseField>

### Methods

<ResponseField name="logMelSpectrogram(fromAudio:)" type="async func">
  Converts audio samples to log mel spectrogram features.

  **Parameters:**

  * `inputAudio: AudioProcessorOutputType` - Processed audio samples

  **Returns:** `FeatureExtractorOutputType?` - Mel spectrogram features

  **Throws:** `WhisperError` if extraction fails
</ResponseField>

## AudioEncoding

Encodes audio features into embeddings.

### Properties

<ResponseField name="embedSize" type="Int?">
  Size of the embedding dimension produced by the encoder.
</ResponseField>

### Methods

<ResponseField name="encodeFeatures(_:)" type="async func">
  Encodes audio features into embeddings.

  **Parameters:**

  * `features: FeatureExtractorOutputType` - Mel spectrogram features

  **Returns:** `AudioEncoderOutputType?` - Encoded audio embeddings

  **Throws:** `WhisperError` if encoding fails
</ResponseField>

## TextDecoding

Decodes audio embeddings into text.

### Properties

<ResponseField name="tokenizer" type="WhisperTokenizer?">
  Tokenizer for encoding/decoding text.
</ResponseField>

<ResponseField name="prefillData" type="WhisperMLModel?">
  Optional prefill model for KV cache initialization.
</ResponseField>

<ResponseField name="isModelMultilingual" type="Bool">
  Whether the model supports multiple languages.
</ResponseField>

<ResponseField name="supportsWordTimestamps" type="Bool">
  Whether the model can generate word-level timestamps.
</ResponseField>

<ResponseField name="logitsSize" type="Int?">
  Size of the vocabulary (number of possible tokens).
</ResponseField>

<ResponseField name="logitsFilters" type="[LogitsFiltering]?">
  Array of filters applied to logits before sampling.
</ResponseField>

<ResponseField name="kvCacheEmbedDim" type="Int?">
  Embedding dimension for key-value cache.
</ResponseField>

<ResponseField name="kvCacheMaxSequenceLength" type="Int?">
  Maximum sequence length for KV cache.
</ResponseField>

<ResponseField name="windowSize" type="Int?">
  Size of the attention window.
</ResponseField>

<ResponseField name="embedSize" type="Int?">
  Size of encoder output embeddings.
</ResponseField>

### Methods

<ResponseField name="predictLogits(_:)" type="async func">
  Predicts logits for the next token.

  **Parameters:**

  * `inputs: TextDecoderInputType` - Decoder inputs including tokens and caches

  **Returns:** `TextDecoderOutputType?` - Logits and updated caches
</ResponseField>

<ResponseField name="prepareDecoderInputs(withPrompt:)" type="func">
  Prepares decoder inputs with an initial prompt.

  **Parameters:**

  * `initialPrompt: [Int]` - Array of prompt token IDs

  **Returns:** `DecodingInputsType` - Initialized decoder inputs

  **Throws:** `WhisperError` if preparation fails
</ResponseField>

<ResponseField name="prefillDecoderInputs(_:withOptions:)" type="async func">
  Prefills decoder inputs with language and task tokens.

  **Parameters:**

  * `decoderInputs: DecodingInputsType` - Inputs to prefill
  * `options: DecodingOptions?` - Decoding configuration

  **Returns:** `DecodingInputsType` - Prefilled inputs
</ResponseField>

<ResponseField name="prefillKVCache(withTask:andLanguage:)" type="async func">
  Prefills the key-value cache using the prefill model.

  **Parameters:**

  * `task: MLMultiArray` - Task token (transcribe/translate)
  * `language: MLMultiArray` - Language token

  **Returns:** `DecodingCache?` - Prefilled cache data
</ResponseField>

<ResponseField name="decodeText(from:using:sampler:options:callback:)" type="async func">
  Decodes audio embeddings into text.

  **Parameters:**

  * `encoderOutput: AudioEncoderOutputType` - Encoded audio
  * `decoderInputs: DecodingInputsType` - Decoder state
  * `tokenSampler: TokenSampling` - Token sampling strategy
  * `decoderOptions: DecodingOptions` - Decoding configuration
  * `callback: TranscriptionCallback` - Progress callback

  **Returns:** `DecodingResult` - Decoded text and metadata
</ResponseField>

<ResponseField name="detectLanguage(from:using:sampler:options:temperature:)" type="async func">
  Detects the language of the audio.

  **Parameters:**

  * `encoderOutput: AudioEncoderOutputType` - Encoded audio
  * `decoderInputs: DecodingInputsType` - Decoder state
  * `tokenSampler: TokenSampling` - Token sampling strategy
  * `options: DecodingOptions` - Decoding configuration
  * `temperature: FloatType` - Sampling temperature

  **Returns:** `DecodingResult` - Detected language and probabilities
</ResponseField>

<ResponseField name="updateKVCache(keyTensor:keySlice:valueTensor:valueSlice:insertAtIndex:)" type="static func">
  Updates the key-value cache with new values.

  **Parameters:**

  * `keyTensor: MLMultiArray` - Key cache tensor
  * `keySlice: MLMultiArray` - New key values
  * `valueTensor: MLMultiArray` - Value cache tensor
  * `valueSlice: MLMultiArray` - New value values
  * `index: Int` - Position to insert
</ResponseField>

## LogitsFiltering

Filters model logits before token sampling.

### Methods

<ResponseField name="filterLogits(_:withTokens:)" type="func">
  Filters the logits based on current tokens and rules.

  **Parameters:**

  * `logits: MLMultiArray` - Raw model logits
  * `tokens: [Int]` - Currently generated tokens

  **Returns:** `MLMultiArray` - Filtered logits
</ResponseField>

### Built-in Filters

* **SuppressTokensFilter** - Suppresses specific token IDs
* **SuppressBlankFilter** - Suppresses blank tokens at segment start
* **TimestampRulesFilter** - Enforces timestamp pairing rules
* **LanguageLogitsFilter** - Retains only language tokens

## SegmentSeeking

Manages audio segmentation and word-level timestamps.

### Methods

<ResponseField name="findSeekPointAndSegments(decodingResult:options:allSegmentsCount:currentSeek:segmentSize:sampleRate:timeToken:specialToken:tokenizer:)" type="func">
  Finds the next seek point and creates transcription segments.

  **Returns:** Tuple of `(Int, [TranscriptionSegment]?)` - next seek position and segments
</ResponseField>

<ResponseField name="addWordTimestamps(segments:alignmentWeights:tokenizer:seek:segmentSize:prependPunctuations:appendPunctuations:lastSpeechTimestamp:options:timings:)" type="func">
  Adds word-level timestamps to segments using alignment weights.

  **Returns:** `[TranscriptionSegment]?` - Segments with word timestamps

  **Throws:** `WhisperError` if timestamp alignment fails
</ResponseField>

## WhisperTokenizer

Tokenizes and detokenizes text for Whisper models.

### Properties

<ResponseField name="specialTokens" type="SpecialTokens">
  Special token IDs used by the model (start, end, language tokens, etc.).
</ResponseField>

<ResponseField name="allLanguageTokens" type="Set<Int>">
  Set of all language token IDs supported by the model.
</ResponseField>

### Methods

<ResponseField name="encode(text:)" type="func">
  Encodes text into token IDs.

  **Returns:** `[Int]` - Array of token IDs
</ResponseField>

<ResponseField name="decode(tokens:)" type="func">
  Decodes token IDs into text.

  **Returns:** `String` - Decoded text
</ResponseField>

<ResponseField name="convertTokenToId(_:)" type="func">
  Converts a token string to its ID.

  **Returns:** `Int?` - Token ID, or nil if not found
</ResponseField>

<ResponseField name="convertIdToToken(_:)" type="func">
  Converts a token ID to its string representation.

  **Returns:** `String?` - Token string, or nil if not found
</ResponseField>

<ResponseField name="splitToWordTokens(tokenIds:)" type="func">
  Splits token IDs into words and their constituent tokens.

  **Returns:** Tuple of `(words: [String], wordTokens: [[Int]])`
</ResponseField>

## WhisperMLModel

Base protocol for Core ML model wrappers.

### Properties

<ResponseField name="model" type="MLModel?">
  The underlying Core ML model instance.
</ResponseField>

### Methods

<ResponseField name="loadModel(at:computeUnits:prewarmMode:)" type="async func">
  Loads a Core ML model from disk.

  **Parameters:**

  * `modelPath: URL` - Path to the .mlmodelc file
  * `computeUnits: MLComputeUnits` - Compute units to use
  * `prewarmMode: Bool` - Whether to load in prewarm mode
</ResponseField>

<ResponseField name="unloadModel()" type="func">
  Unloads the model from memory.
</ResponseField>

## Usage Example

```swift theme={null}
// Custom audio processor
class MyAudioProcessor: AudioProcessing {
    var audioSamples: ContiguousArray<Float> = []
    var relativeEnergy: [Float] = []
    var relativeEnergyWindow: Int = 20
    
    // Implement required methods...
}

// Use custom processor
let config = WhisperKitConfig(
    model: "openai_whisper-base",
    audioProcessor: MyAudioProcessor()
)

let whisperKit = try await WhisperKit(config)
```

## Related Types

* [ModelComputeOptions](/api/core/model-compute-options)
* [ModelState](/api/core/model-state)
* [DecodingOptions](/api/core/decoding-options)
