Sample CodemacOSReviewed 2026-07-21View on Apple Developer

Adding a display mask rectangle metadata track to a movie file

At a glance

Item Summary
Purpose Show a specific area of a video by using timed display mask rectangle metadata.
App architecture A Swift sample with the source-visible chain AVAddDisplayMaskTrackMovieProcessorAVFoundation APIs.
Main patterns No named application pattern supported by the extracted structure
Project style 2 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries.
Execution model Source-visible boundaries: async declaration or closure, DispatchQueue(label:); none alone proves a background thread.
State/event model No structured observation or publisher-scheduling marker indexed.
Key frameworks/packages AVFoundation, Foundation, ArgumentParser, CoreMedia; these are source dependencies, not architecture labels.

Project structure

Source bundle/
├── AVAddDisplayMaskTrack.swift
├── MovieProcessor.swift
├── AVAddDisplayMaskTrack.xcodeproj/
│   ├── .xcodesamplecode.plist
│   └── project.pbxproj
└── Configuration/
    └── SampleCode.xcconfig

Structure observations

  • Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
  • Primary languages: Swift.
  • The verified tree contains 3 project/configuration file(s) and 5 source declaration(s).

Overall architecture

Reference code

AVAddDisplayMaskTrack.swift:14 — architecture anchor

@main
struct AVAddDisplayMaskTrack: AsyncParsableCommand {
    static let configuration = CommandConfiguration(
        abstract: "Appends a display mask metadata track to a movie file.",
        usage: """
            AVAddDisplayMaskTrack <input-path> <output-path> [display-mask-type]
            Examples:
               AVAddDisplayMaskTrack input.mov output.mov
               AVAddDisplayMaskTrack input.mov output.mov 2
            """,
        discussion: """
            Creates a new QuickTime movie file that contains the media tracks from the input movie file
            and an additional timed metadata track. The metadata track contains a display mask rectangle
            in boxed metadata format (`mebx`). The metadata track is associated to the enabled video track
            with a render ('rndr') track reference.
            """
    )
    // ...
}

Interpretation

The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into AVFoundation.

Ownership and state

Ownership evidence

AVAddDisplayMaskTrack.swift:16 — stored dependency or nearest verified ownership anchor

@main
struct AVAddDisplayMaskTrack: AsyncParsableCommand {
    // ...
}
Owner Object or state Relationship Mutation authority
AVAddDisplayMaskTrack CommandConfiguration (configuration) creates and retains Initialized by the owner; the binding is immutable
AVAddDisplayMaskTrack String (inputPath) owns value state App/module collaborators
AVAddDisplayMaskTrack String (outputPath) owns value state App/module collaborators
AVAddDisplayMaskTrack Int (displayMaskType) owns value state App/module collaborators

Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.

Concurrency, scheduling, and thread safety

Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.

Concern Source mechanism Verified placement or handoff Evidence
Suspension boundary async declaration or closure The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. AVAddDisplayMaskTrack.swift:41
Queue scheduling DispatchQueue(label:) The source constructs a dispatch queue; its label alone does not prove a thread. MovieProcessor.swift:203

@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.

Reference code

AVAddDisplayMaskTrack.swift:41 — representative execution boundary

    mutating func run() async throws {
        // ...
            let processor = MovieProcessor()
        // ...
    }

State propagation, frameworks, and dependencies

Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.

Category Mechanism or module Verified role Evidence
Source import AVFoundation The cited file imports this module; runtime use and architectural role are not inferred. AVAddDisplayMaskTrack.swift:9
Source import Foundation The cited file imports this module; runtime use and architectural role are not inferred. AVAddDisplayMaskTrack.swift:8
Source import ArgumentParser The cited file imports this module; runtime use and architectural role are not inferred. AVAddDisplayMaskTrack.swift:11
Source import CoreMedia The cited file imports this module; runtime use and architectural role are not inferred. AVAddDisplayMaskTrack.swift:10

receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.

Class and protocol design

MovieProcessor.swift:11 — representative type boundary

class MovieProcessor {
    private var readerOutputs: [AVAssetReaderOutput] = []
    // ...
}
Type Responsibility Depends on or conforms to
MovieProcessor Owns a feature processing stage Concrete collaborators/imported frameworks
AVAddDisplayMaskTrack Represents a feature value or composable behavior AsyncParsableCommand
VideoTrackInfo Represents feature data Concrete collaborators/imported frameworks
BouncingBoxInfo Represents feature data Concrete collaborators/imported frameworks
ProcessingError Represents feature failure conditions LocalizedError

No local protocol conformance is claimed as protocol-oriented design; external framework conformances are listed only as dependencies.

Access control

Symbol Access Verified effect Likely rationale
readerOutputs (MovieProcessor.swift:12) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
writerInputs (MovieProcessor.swift:13) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
metadataInput (MovieProcessor.swift:14) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.
metadataAdaptor (MovieProcessor.swift:15) private Use is restricted to the lexical declaration and same-file extensions allowed by Swift. Inference: keep state mutation or dependency lifetime inside the owning implementation.

Reference code

MovieProcessor.swift:12 — representative boundary

class MovieProcessor {
    private var readerOutputs: [AVAssetReaderOutput] = []
    // ...
}

Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.

Logic ownership and placement

Logic Owning type or file Placement rationale
Owns a feature processing stage MovieProcessor The source’s Processor suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
No named application pattern AVAddDisplayMaskTrack.swift:14 The verified source directly composes concrete framework types; this document avoids forcing a pattern name.

Main application flow

Reference code

MovieProcessor.swift:108setupExistingTracksForPassthroughAndReturnEnabledVideoInput()

    private func setupExistingTracksForPassthroughAndReturnEnabledVideoInput(from asset: AVAsset, reader: AVAssetReader, writer: AVAssetWriter) async throws -> (videoInput: AVAssetWriterInput, videoInfo: VideoTrackInfo) {
        // ...
        var enabledVideoInput: AVAssetWriterInput? = nil
        var enabledVideoInfo = VideoTrackInfo()
        let allTracks = try await asset.load(.tracks)
        print("Found \(allTracks.count) track(s).")
        for sourceTrack in allTracks {
            let readerOutput = AVAssetReaderTrackOutput(track: sourceTrack, outputSettings: nil)
            readerOutput.alwaysCopiesSampleData = false
            let writerInput = AVAssetWriterInput(mediaType: sourceTrack.mediaType, outputSettings: nil)
            writerInput.expectsMediaDataInRealTime = false
            if reader.canAdd(readerOutput) && writer.canAdd(writerInput) {
                reader.add(readerOutput)
                writer.add(writerInput)
                readerOutputs.append(readerOutput)
                writerInputs.append(writerInput)
            }
            if sourceTrack.mediaType == .video {
                if try await sourceTrack.load(.isEnabled) {
                    enabledVideoInput = writerInput
                    enabledVideoInfo.dimensions = try await sourceTrack.load(.naturalSize)
                    let trackTimeRange = try await sourceTrack.load(.timeRange)
                    enabledVideoInfo.trackDuration = trackTimeRange.end
                    enabledVideoInfo.timescale = try await sourceTrack.load(.naturalTimeScale)
                    enabledVideoInfo.frameRate = try await sourceTrack.load(.nominalFrameRate)
                }
            }
        }
        guard let enabledVideoInput = enabledVideoInput else {
            throw ProcessingError.noEnabledVideoTrack
        }
        return (enabledVideoInput, enabledVideoInfo)
    }

Naming conventions

  • Types: Processor: MovieProcessor.
  • Protocols: no local protocol declaration in the scanned source.
  • Methods: run, processMovie, setupExistingTracksForPassthroughAndReturnEnabledVideoInput, addDisplayMaskMetadataTrack, performMediaProcessing, setupMediaDataTransfer, setupDisplayMaskMetadataTransfer, createMetadataGroupForDisplayMask.
  • Files: AVAddDisplayMaskTrack.swift, MovieProcessor.swift.

Architecture takeaways

  • AVAddDisplayMaskTrack is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches AVFoundation, ArgumentParser, CoreMedia through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
  • Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
  • Access-control conclusions separate verified language visibility from the likely design rationale.
  • The source does not justify labeling the design protocol-oriented.

Source map

Source file Relevant symbols
AVAddDisplayMaskTrack.swift Cited implementation, async declaration or closure, AVFoundation, Foundation, ArgumentParser, CoreMedia, AVAddDisplayMaskTrack
MovieProcessor.swift MovieProcessor, Cited implementation, DispatchQueue(label:), VideoTrackInfo, BouncingBoxInfo, ProcessingError