Sample CodemacOSReviewed 2026-07-21View on Apple Developer

Capturing Metal commands programmatically

At a glance

Item Summary
Purpose Invoke a Metal frame capture from your app, then save the resulting GPU trace to a file or view it in Xcode.
App architecture A C/Objective-C header, Metal, Objective-C sample with the source-visible chain mainAAPLViewControllerAAPLCaptureManagerAAPLRenderermetal_stdlib APIs.
Main patterns Delegate or data-source callbacks
Project style 9 scanned source file(s) across C/Objective-C header, Metal, Objective-C, organized around ranked entry, type, and file boundaries.
Execution model No structured execution marker indexed; callback threading requires source review.
State/event model No structured observation or publisher-scheduling marker indexed.
Key frameworks/packages simd, Cocoa, Foundation, metal_stdlib; these are source dependencies, not architecture labels.

Project structure

Source bundle/
├── Application/
│   ├── main.m
│   ├── AAPLViewController.h
│   ├── AAPLViewController.m
│   └── macOS/
│       ├── Base.lproj/
│       │   └── Main.storyboard
│       └── Info.plist
├── Renderer/
│   ├── AAPLCaptureManager.h
│   ├── AAPLCaptureManager.m
│   ├── AAPLRenderer.h
│   ├── AAPLRenderer.m
│   ├── AAPLShaderTypes.h
│   └── AAPLShaders.metal
└── Capture Manager.xcodeproj/
    └── .xcodesamplecode.plist

Structure observations

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

Overall architecture

Reference code

Application/main.m:10 — architecture anchor

int main(int argc, const char * argv[])
{
    return NSApplicationMain(argc, argv);
}

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 Metal.

Ownership and state

Ownership evidence

Renderer/AAPLCaptureManager.h:23 — stored dependency or nearest verified ownership anchor

@interface AAPLCaptureManager : NSObject
// ...
@property (readwrite, nonatomic) MTLCaptureDescriptor* _Nullable captureDescriptor;
// ...
@end
Owner Object or state Relationship Mutation authority
AAPLCaptureManager _Nullable (captureDescriptor) stores or receives Header-visible collaborators
AAPLRenderer _Nonnull (captureManager) stores or receives Header-visible 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.

No source-visible execution, scheduling, or synchronization boundary was found in the indexed source.

@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.

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 simd The cited file imports this module; runtime use and architectural role are not inferred. Renderer/AAPLShaderTypes.h:18
Source import Cocoa The cited file imports this module; runtime use and architectural role are not inferred. Application/main.m:8
Source import Foundation The cited file imports this module; runtime use and architectural role are not inferred. Renderer/AAPLShaderTypes.h:15
Source import metal_stdlib The cited file imports this module; runtime use and architectural role are not inferred. Renderer/AAPLShaders.metal:8

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

Application/AAPLViewController.h:10 — representative type boundary

@interface AAPLViewController : NSViewController

@end
Type Responsibility Depends on or conforms to
AAPLViewController View lifecycle, callbacks, and feature coordination NSViewController
AAPLCaptureManager Long-lived feature or framework coordination NSObject
AAPLRenderer Owns drawing, GPU, or presentation processing NSObject, MTKViewDelegate

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
captureDescriptor (Renderer/AAPLCaptureManager.h:23) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.
captureManager (Renderer/AAPLRenderer.h:15) header-visible The declaration is exposed to translation units that import the header. Inference: declare a contract needed by other Objective-C/C translation units.
AAPLViewController (Application/AAPLViewController.m:8) language/file boundary Visibility follows header/implementation and language linkage rules. Inference: the language’s file or module boundary is sufficient for this sample collaboration.

Reference code

Renderer/AAPLCaptureManager.h:23 — representative boundary

@interface AAPLCaptureManager : NSObject
// ...
@property (readwrite, nonatomic) MTLCaptureDescriptor* _Nullable captureDescriptor;
// ...
@end

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
View lifecycle, callbacks, and feature coordination AAPLViewController The source’s Controller suffix makes this role explicit.
Long-lived feature or framework coordination AAPLCaptureManager The source’s Manager suffix makes this role explicit.
Owns drawing, GPU, or presentation processing AAPLRenderer The source’s Renderer suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
Delegate or data-source callbacks Renderer/AAPLRenderer.h:11 Callback protocols invert event delivery back into the sample’s owner.

Main application flow

Reference code

Renderer/AAPLCaptureManager.m:59setupCaptureToFile()

- (void)setupCaptureToFile:(nonnull MTKView *)view
{
    // Use the `.gputrace` extension for your GPU trace capture files.
    NSSavePanel *savePanel = [NSSavePanel savePanel];
    savePanel.nameFieldStringValue = @"My_Trace.gputrace";

    [savePanel beginSheetModalForWindow:view.window completionHandler:^(NSModalResponse result)
      {
        if (result == NSModalResponseOK) {
            NSURL *URL = savePanel.URL;
            NSLog(@"%@", URL);

            MTLCaptureDescriptor *descriptor = [[MTLCaptureDescriptor alloc] init];
            descriptor.destination = MTLCaptureDestinationGPUTraceDocument;
            descriptor.outputURL = URL;
            descriptor.captureObject = ((MTKView *)view).device;

            // Set up a completion handler to be called in the next rendered frame.
            [self captureWithDescriptor:descriptor completionHandler:^(BOOL success, NSError *error)
              {
                if (success) {
                    [NSWorkspace.sharedWorkspace activateFileViewerSelectingURLs:@[ URL ]];
                } else {
                    NSAlert *alert = [NSAlert alertWithError:error];
                    [alert beginSheetModalForWindow:view.window completionHandler:nil];
                }
              }];
        }
      }];
}

Naming conventions

  • Types: Controller: AAPLViewController; Manager: AAPLCaptureManager; Renderer: AAPLRenderer.
  • Protocols: no local protocol declaration in the scanned source.
  • Methods: viewDidLoad, captureInXcode, captureToFile, setupCaptureInXcode, setupCaptureToFile, captureWithDescriptor, startCapture, stopCapture.
  • Files: Application/AAPLViewController.h, Application/AAPLViewController.m, Renderer/AAPLCaptureManager.h, Renderer/AAPLCaptureManager.m, Renderer/AAPLRenderer.h, Renderer/AAPLRenderer.m.

Architecture takeaways

  • main is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches simd, Cocoa, metal_stdlib 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
Application/main.m Cited implementation, Cocoa, Feature implementation
Renderer/AAPLCaptureManager.h Cited implementation, captureDescriptor, AAPLCaptureManager
Application/AAPLViewController.h AAPLViewController
Renderer/AAPLRenderer.h captureManager, Cited implementation, AAPLRenderer
Application/AAPLViewController.m AAPLViewController
Renderer/AAPLShaderTypes.h simd, Foundation, Feature implementation
Renderer/AAPLShaders.metal metal_stdlib, Feature implementation
Renderer/AAPLCaptureManager.m AAPLCaptureManager
Renderer/AAPLRenderer.m AAPLRenderer