AVFoundation

RSS for tag

Work with audiovisual assets, control device cameras, process audio, and configure system audio interactions using AVFoundation.

Posts under AVFoundation tag

200 Posts

Post

Replies

Boosts

Views

Activity

AirPods Sleep Detection pauses meditation playback with no API/callback to identify the reason
Good morning! I work on a meditation app, and since Sleep Detection was introduced for AirPods in iOS 26, we've been receiving complaints from users reporting that their meditation sessions unexpectedly stop after approximately 15–20 minutes when Sleep Detection is enabled. This seems to happen particularly during deep meditation sessions, where the user may remain still and exhibit behavior that could potentially be interpreted as falling asleep. I've also tested this on iOS 27 with the latest beta firmware available for AirPods Pro, and the same behavior still occurs. While investigating and debugging the issue, I found that there doesn't appear to be any public API that allows an app to determine that playback was paused specifically because of AirPods Sleep Detection. From the application's perspective, the AirPods appear to simply send a standard pause command to the AVPlayer, without providing any additional context or reason. There also doesn't seem to be an API that allows us to determine whether the user has Sleep Detection enabled. Even having access to that information would allow us to warn users that their meditation session could potentially be interrupted. AVAudioSession.InterruptionReason does not seem to help in this case either: https://developer.apple.com/documentation/avfaudio/avaudiosession/interruptionreason Is there currently any supported way for an app to: Detect that playback was paused specifically because of AirPods Sleep Detection? Determine whether Sleep Detection is enabled for the connected AirPods? Prevent Sleep Detection from pausing playback for specific apps or specific types of audio sessions? If none of these are currently possible, could Apple consider providing either a notification/callback indicating that Sleep Detection triggered the pause, or an option for users to exclude specific apps from Sleep Detection? This behavior is particularly problematic for meditation apps, since a user in a deep meditation session can easily be mistaken for someone who has fallen asleep. Other meditation apps appear to be affected by the same behavior as well. Best regards, Carlos Antunes
1
0
422
20h
Can an iOS app programmatically enable Voice Isolation microphone mode?
Hi, I’m developing an iOS app that captures the user’s voice and sends the microphone input to an AI model for speech processing. For this use case, Voice Isolation provides a significantly better input signal in noisy environments. However, I’m currently unable to enable Voice Isolation programmatically when the app starts recording. As I understand it, microphone modes such as Automatic, Standard, Voice Isolation, and Wide Spectrum are controlled by the user through the system UI. My app can detect/observe the current microphone mode, but I have not found a public API that allows the app to select Voice Isolation itself. My questions are: Is there currently a supported public API to programmatically switch the microphone mode from Automatic/Standard → Voice Isolation? If direct selection is not supported, is there a recommended way for an app that primarily processes speech/voice input for an AI model to request or prefer Voice Isolation? Would using AVAudioSession with an appropriate voice-processing configuration, such as .voiceChat, or enabling voice processing through AVAudioEngine, provide equivalent Voice Isolation processing? Is AVCaptureDevice.showSystemUserInterface(.microphoneModes) the intended approach when an app needs the user to change the microphone mode? I understand that Apple may intentionally keep microphone-mode selection under user control. I’m mainly trying to determine whether there is a supported programmatic approach that I may have overlooked, rather than relying on a custom noise-suppression implementation. Any guidance on the recommended architecture for this use case would be greatly appreciated. Thank you!
0
0
223
1d
Does the TN3135 audio-session networking exception have a defined lifetime? Seeing a ~38.5 s revoke/re-grant cycle
TN3135 describes the exception that lets a watchOS app use low-level networking while it holds an active audio session. I have that working, and the app functions — but the network path is withdrawn and restored on a strikingly regular cycle, and I would like to know whether that is expected behaviour rather than something I am doing wrong. Setup Apple Watch Series 10 (Watch7,9), watchOS 26.5. Reproduced on a Series 6 (Watch6,2). UIBackgroundModes: [audio]; AVAudioSession category .playAndRecord, mode .spokenAudio; activated with the async activate(options:completionHandler:). NWConnection with NWProtocolWebSocket to a WebSocket relay over TLS. The app streams 16 kHz mono PCM continuously while transmitting and holds the socket open otherwise. Symptom NWPathMonitor reports .unsatisfied, then .satisfied about two seconds later, over and over. Measured with the iPhone powered off, so the watch was on its own Wi-Fi: Uptime between drops Outage 36.4 s 2.1 s 36.7 s 1.9 s 36.9 s 2.1 s The regularity is what prompts the question — uptime varies by ±0.3 s and the outage is consistently 2.0 s. That reads as a timeout expiring rather than radio behaviour. What I have ruled out Not the network or the server. A browser client on the same relay, same TLS, same wire protocol, holds a WebSocket indefinitely. Not the interface. Identical cadence over the companion ipsec1 tunnel with the iPhone present, and over the watch's own en0 with the iPhone powered off. Pinning requiredInterfaceType = .wifi while the iPhone is reachable fails outright — the path offers only ipsec1. Not audio-session interruption. I observe interruptionNotification, routeChangeNotification, mediaServicesWereResetNotification and silenceSecondaryAudioHintNotification. None fire at a drop. At the moment the path goes .unsatisfied, the engine is running and the player node is actively playing. Not session idleness. Playing continuous silence for the whole session, rather than only while reconnecting, made no difference — still 36.4 s. The control that surprised me To test whether this affects any long-lived watch socket or only audio-unlocked ones, I built a second app with no AVAudioSession at all, no audio background mode, holding a URLSessionWebSocketTask and kept alive by a WKExtendedRuntimeSession so screen sleep was not a factor. It never connected. NWPathMonitor reported .unsatisfied once and never changed, across a 30 s run, and every request failed with "The Internet connection appears to be offline." I had expected URLSession to be permitted regardless. Questions Does the audio-session networking exception in TN3135 have a defined lifetime, and is a periodic revoke/re-grant cycle expected? If so, is there a supported way to hold it continuously — or is the correct design simply to expect the interruption and reconnect through it? Is it expected that an app with no audio session gets no network path at all on watchOS, including via URLSession, even in the foreground with an extended runtime session?
15
0
2.9k
2d
AVCaptureDevice.uniqueID for UVC devices is unstable - bug or overstated documentation?
The documentation for AVCaptureDevice.uniqueID states the following: Capture devices have a unique identifier that persists on one system across device connections and disconnections, application restarts, and reboots of the system itself. You can store the value returned by this property to recall or track the status of a specific device in the future. For UVC capture devices this documentation does not hold. The video uniqueID is a hex string of the form 0x<locationID><vendorID><productID>, and the identifying half is the locationID (bus number plus port path). Which identifies a port, not a device. I ran a suite of tests with three identical Elgato 4K X capture cards connected to a Mac Studio w/ M3 Ultra running macOS 26.5.2, and reproduced my findings on a MacBook w/ M3 Pro (same macOS version). See the script at the bottom of the post for how uniqueId & USB serial number are being retrieved. 1. The uniqueID follows the port. Swapping two cards between two built-in ports swaps their uniqueIDs: # Before swap. 4K X uid=0x2000000fd9009b serial=A7SNB50424UBQI 4K X uid=0x12000000fd9009b serial=A7SNB504219J0R # After swapping the cards between the same two ports. 4K X uid=0x2000000fd9009b serial=A7SNB504219J0R 4K X uid=0x12000000fd9009b serial=A7SNB50424UBQI An app that stored 0x2000000fd9009b to recall a specific capture card now silently opens another. 2. A reboot alone can swap uniqueIDs. External USB controllers (here, PCIe USB cards in two Thunderbolt enclosures) can race for bus numbers at boot, so with every cable left in place, a reboot swapped two of the cards: # Before reboot. 4K X uid=0x262000000fd9009b serial=A7SNB504219J0R 4K X uid=0x252000000fd9009b serial=A7SNB50423R73R # After reboot, no cables touched. 4K X uid=0x262000000fd9009b serial=A7SNB50423R73R 4K X uid=0x252000000fd9009b serial=A7SNB504219J0R This behavior is intermittent, a second reboot changed nothing, but a third caused another swap. Cards left alone in built-in ports retain their uniqueIDs across reboots in my testing; the failure requires dynamically enumerated external USB controllers. 3. Even the product ID tail can drift. One unit intermittently enumerates with idProduct 0x009c instead of 0x009b, same port (USB PCIe card in a Thunderbolt enclosure), cables untouched: # Before reboot. 4K X uid=0x222000000fd9009b serial=A7SNB50424UBQI # After reboot. 4K X uid=0x222000000fd9009c serial=A7SNB50424UBQI IOKit and AVFoundation agree each boot... So the change is upstream of both? I'm uncertain where to place blame for this specific issue (UVC device or macOS). Audio on the same physical units is unaffected. The audio uniqueID (AppleUSBAudioEngine:...:<serial>:...) embeds the USB serial and stayed stable through every test. So AVCaptureDevice can provide a stable per-device identifier, just not for UVC video devices. Questions: Is this a bug, or is the documentation overstating the persistence guarantee for USB video devices? What is the supported way to identify a specific physical UVC video device across reboots and port changes? The USB serial number is stable and is what I've fallen back on via IOKit, but there is no documented AVFoundation API to retrieve USB serial number from a UVC video AVCaptureDevice. Related: thread 803759, where the locationID-derived format is described. Script used for all output above (swift ./list-uvc.swift): import AVFoundation import IOKit func usbSerial(forLocation location: UInt32) -> String? { var iterator: io_iterator_t = 0 guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOUSBHostDevice"), &iterator) == KERN_SUCCESS else { return nil } defer { IOObjectRelease(iterator) } var result: String? var service = IOIteratorNext(iterator) while service != 0 { var loc: UInt32 = 0 if let ref = IORegistryEntryCreateCFProperty(service, "locationID" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), let num = ref as? NSNumber { loc = num.uint32Value } if loc == location, let ref = IORegistryEntryCreateCFProperty(service, "USB Serial Number" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), let serial = ref as? String { result = serial } IOObjectRelease(service) if result != nil { break } service = IOIteratorNext(iterator) } return result } let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.external], mediaType: .video, position: .unspecified) for device in session.devices { let uid = device.uniqueID let location = UInt32(truncatingIfNeeded: strtoull(uid, nil, 16) >> 32) let serial = usbSerial(forLocation: location) ?? "N/A" print("\(device.localizedName) uid=\(uid) serial=\(serial)") }
6
0
1.6k
3d
iOS 27 beta: setExposureModeCustom silently ignored on the front camera
On every iOS 27.0 beta, setExposureModeCustom has no effect on the front camera (.builtInTrueDepthCamera). exposureMode does change to .custom, but the sensor keeps auto-exposing: device.iso and device.exposureDuration report auto-exposure's values, not the requested ones, and frame brightness does not change. No error is thrown. The same code works on iOS 18.x and 26.x on the same devices. Device: iPhone 15 Pro, every iOS 27.0 beta. Also seen on iPhone 14 Pro Max, 16, 16 Pro Max and 17 Pro Max. Session: front camera, AVCaptureVideoDataOutput (BGRA) + AVCaptureDepthDataOutput. Format advertises ISO 20...1920, duration 0.00004...0.06667 s. isExposureModeSupported(.custom) is true. Repro: let auto-exposure settle, then try device.lockForConfiguration() device.setExposureModeCustom(duration: CMTime(value: 1, timescale: 15), iso: 1920, completionHandler: nil) device.unlockForConfiguration() then poll device.iso / device.exposureDuration (the completion handler never fires on this device) and measure frame luma. Readback, polled 0.8 s after the call: requested ISO 1920, 66.7 ms -> reported ISO 349, 60.0 ms requested ISO 20, 0.04 ms -> reported ISO 188, 66.5 ms Requesting the shortest exposure returns the longest, and the same ISO 1920 request returned 249, 349 and 450 on three consecutive runs, so these are auto-exposure's values. Frame luma stayed within 1% between the two phases. setExposureTargetBias, however, is honored on the same device: at +4 EV auto-exposure drives the sensor to ISO 1920 / 66.5 ms and at -4 EV to ISO 24 / 30.0 ms, moving mean luma from 49 to 232. So the sensor does reach the values setExposureModeCustom cannot set. Question: is this intentional or a regression, and how should an app detect that a custom exposure request was refused?
0
0
62
3d
PhotoKit IMG_XXXX names for videos?
I save stills and videos with PHAssetCreationRequest. I do not set originalFilename. Photos saved with addResource(with: .photo, data:) show originalFilename values like IMG_XXXX.HEIC in PHAssetResource. Videos saved with addResource(with: .video, fileURL:) from AVCaptureMovieFileOutput keep the temp file name (a UUID .mov). The docs say that if originalFilename is omitted, Photos infers a name from the file URL when one is provided, otherwise it generates a name. Is there a supported way for a third-party app to get a system IMG_XXXX original filename for a newly saved video? Thank you.
1
0
491
3d
iOS 27 beta 5: cameracaptured repeatedly crashes in BWVISNode with two stabilized front-camera video outputs
I’m seeing a repeatable first-party cameracaptured crash on an iPhone 14 Pro (iPhone15,2) running iOS 27 beta 5 (24A5424a). The single-camera AVCaptureSession configuration is: Front wide camera 3840×2160 at 30 fps, SDR/420f Two AVCaptureVideoDataOutput connections: Main recording output: 3840×2160 Auxiliary preview output: approximately 2096×1178 Both connections request and activate .standard video stabilization Within roughly two minutes, cameracaptured crashed three times—once during recording and twice during idle preview. The application receives AVErrorMediaServicesWereReset (-11819) after each crash. All three reports have the same faulting queue and underlying stack: com.apple.coremedia.capture.videodata-stabilization.front FigCFDictionaryGetCGRectIfPresent -[BWVISNode _transformRectanglesInMetadata:pts:] -[BWVISNode _stabilizeMetadataForSampleBuffer:] -[BWVISNode _tallyAndEmitSampleBuffer:] VideoStabilizationV2 The first two crashes are: EXC_BAD_ACCESS / EXC_ARM_PAC_FAIL address: 0x00000000dac11a30 termination: PAC_EXCEPTION, code 261 The third reaches the same stabilization stack but terminates with: EXC_BAD_ACCESS / SIGSEGV KERN_INVALID_ADDRESS at 0x30 App-side frame analytics were disabled, system pressure remained nominal, and neither audiomxd nor bluetoothd restarted. The first crash report also shows two front- stabilization worker threads, consistent with the two stabilized video outputs. I have filed Feedback Assistant report FB24553011 with the complete log archive and all three cameracaptured reports. With the iOS 27 public release approaching, waiting for an OS-side fix is not a viable shipping strategy; an app-side workaround is effectively the only option available for our release. Is this a known issue? In particular: Is it safe to leave .standard stabilization on the main recording connection while forcing the auxiliary preview connection to .off? Would disabling/removing the auxiliary AVCaptureVideoDataOutput reliably reduce this to one stabilization pipeline? If a single stabilized front output remains affected, is disabling front-camera stabilization entirely the only supported containment? Is there any public API for disabling the rectangle-metadata processing performed by BWVISNode? The current field workaround is to use the front camera with stabilization Off, or use a rear camera when stabilization is required.
0
0
257
6d
Apple Music real-time DJ mixing: is there an API or entitlement beyond MusicKit?
Hello, I am developing an iOS app that uses MusicKit and ApplicationMusicPlayer to create automatic transitions between songs from Apple Music. The app already analyzes tracks using BPM, musical key and danceability, orders them for compatible transitions, and uses MusicPlayer.Transition.crossfade for playback. With the public MusicKit APIs, however, I have reached a limitation. ApplicationMusicPlayer manages the playback queue and crossfade internally. I cannot independently control the outgoing and incoming Apple Music tracks as two decks, which would be required for DJ-style transitions (for example, starting the incoming track while independently controlling the outgoing track, choosing precise mix points, and managing the two playback positions during the overlap). I experimented with MusicPlayer.Queue.Entry startTime and endTime, but changing the end point is not equivalent to having independent deck control and can result in the current track ending before the desired transition. I understand that Apple Music content is protected and that direct access to decoded audio samples may intentionally not be available through the public MusicKit APIs. I am not looking to download, extract, record, or export Apple Music audio. My use case is real-time playback only, for authenticated Apple Music subscribers. My questions are: Is there a public API that allows two Apple Music tracks to be independently controlled and mixed in real time? If not, is there a restricted entitlement, API, or developer program available for DJ/mixing applications? If this capability requires a commercial or technical partnership with Apple Music rather than a public API, is there an official channel through which a developer can request or discuss such access? I am aware that some third-party DJ applications provide real-time mixing with Apple Music, so I would like to understand whether there is an officially supported integration path for other developers, rather than trying to work around the limitations of ApplicationMusicPlayer. Thank you.
0
0
460
1w
videoZoomFactor updates do not propagate smoothly to an unstabilized secondary AVCaptureVideoDataOutput
I’m seeing a device/OS-specific AVFoundation issue on iPhone 14 Pro running iOS 26.6. A secondary AVCaptureVideoDataOutput is used to provide an unstabilized monitoring feed while the main recording connection is stabilized. During continuous zoom changes, frames from the secondary output continue arriving and scene motion remains live, but its visible zoom/crop/FOV intermittently remains unchanged and then catches up. The saved recording remains smooth and reflects the requested zoom correctly. Minimal configuration: Device: iPhone 14 Pro iOS: 26.6 Physical Ultra Wide camera 1920×1080 at 30 fps SDR, 8-bit YUV Main VDO: 420v Main connection stabilization: .cinematicExtendedEnhanced Auxiliary VDO: 420f Auxiliary connection stabilization: explicitly .off automaticallyConfiguresOutputBufferDimensions = false deliversPreviewSizedOutputBuffers = true alwaysDiscardsLateVideoFrames = true Deferred start disabled Both outputs use a serial delegate queue The auxiliary output is displayed directly without image processing. During continuous videoZoomFactor updates: AVCaptureDevice.videoZoomFactor advances correctly. The UI zoom value advances correctly. The main recorded output zooms smoothly. Frames from the auxiliary output continue arriving and scene motion remains live. Only the auxiliary output's visible zoom/crop/FOV intermittently holds at an older value and then catches up. This is not a complete preview-frame stall: camera movement remains visible during the periods when zoom does not visually advance. The problem occurs with any non-Off stabilization tier in the production app because that configuration installs the unstabilized auxiliary output. Stabilization Off removes the auxiliary topology, and zoom then appears smooth on the main preview feed. A standalone capture sample reproduces the problem without the application’s writer or rendering pipeline. Current device matrix: iPhone 14 Pro, iOS 26.6: reproduces. iPhone 13 Pro, iOS 18.6.x, same released application version: does not reproduce. iPhone 17 Pro, iOS 26.6, isolated sample: does not reproduce. iPhone 14 Pro, iOS 27 beta 5: testing in progress — result to be added. The issue was initially reported with HEVC/Apple Log capture, but it remains reproducible after reducing the graph to 1080p30 SDR8. Questions: Is using two video-data-output connections with different stabilization modes—Extreme on the recording output and Off on the monitoring output—a supported configuration? Is delayed propagation of zoom geometry/crop to a secondary video-data output known on iPhone 14 Pro/iOS 26 when another output connection is stabilized? Is there a recommended AVFoundation topology for obtaining a low-latency, unstabilized monitoring feed while separately recording stabilized video? Are there output or connection properties that must be set to make videoZoomFactor geometry changes propagate synchronously to both outputs? I can provide the standalone sample project, screen recordings, connection-mode logs, buffer PTS/arrival cadence, and a sysdiagnose. EDIT: Issue seen on iOS 27 beta 5 devices as well. No such issue is seen in iOS 18 devices.
0
0
72
1w
How should live latency be measured and maintained with AVPlayer (HLS / LL-HLS)?
We keep live playback at a consistent distance from the live edge using small playback rate adjustments, with a target range based on recommendedTimeOffsetFromLive. Since the live edge is not exposed by AVPlayer, we currently fall back to seekableTimeRanges.end as our best approximation. What should be treated as the live edge, and how should the current live latency be measured? Is rate adjustment the appropriate way to hold a target latency? While playing above 1.0x, the playhead can reach the seekable end, at which point AVPlayerItemDidPlayToEndTime fires and halts the live stream. How can we guard against ? Does any of this differ between regular HLS and LL-HLS? A clear statement of the intended contract here would resolve a lot of uncertainty. Thanks in advance.
3
0
644
1w
Video recording goes fine but adding audio fails mysteriously
I'm trying to update an old unity app for a client. The app has been crashing on iOS in a plugin they use called NatCorder. They use it to record video only separately and then re-record it with effects and audio gathered separately. Instead of trying to update the plugin to something else which would be quite the hassle, I noticed the API for the native part of the plugin, where the crash occurs, is very simple, especially if you don't try to support everything the plugin does and the app does not use. So I tried to re-implement that native library using AVFoundation. I got the video recording right, it captures the camera from the iPhone and writes it to a file properly. However, when the app does the second part, where it sends video and audio frames to the plugin, it fails. The app sends all the video frames and then sends all the audio frames. The video frames are eaten fine by AVFoundation but the audio fails at random points with unknown errors. I wonder if I'm trying to use incompatible audio-video formats or if I'm using timestamps wrong or something. Here's my init code. Anything suspicious to you? void* NCCreateMP4Recorder(int width, int height, float framerate, int bitrate, int keyframeInterval, int sampleRate, int channelCount, const char* recordingPath, void (*callback)(void*, void*), void* context) { Recorder* recorder = calloc(1, sizeof(Recorder)); recorder->context = context; recorder->callback = callback; recorder->path = strdup(recordingPath); recorder->width = width; recorder->channelCount = channelCount; recorder->sampleRate = sampleRate; recorder->height = height; NSError *error = nil; NSURL* url = createURLFromArgumentCString(recordingPath); recorder->writer = [AVAssetWriter assetWriterWithURL:url fileType:AVFileTypeMPEG4 error:&error]; if (recorder->writer == nil) NSLog(@"Failed creating media writer: %@", error); NSDictionary *videoSettings = @{ AVVideoCodecKey: AVVideoCodecTypeH264, AVVideoWidthKey: @(width), AVVideoHeightKey: @(height), AVVideoCompressionPropertiesKey: @{ AVVideoAverageBitRateKey: @(bitrate), AVVideoMaxKeyFrameIntervalKey: @(keyframeInterval), } }; recorder->video = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings]; if (recorder->video == nil) NSLog(@"Failed creating video writer input"); recorder->video.expectsMediaDataInRealTime = true; NSDictionary* videoSource = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, [NSNumber numberWithInt:width], kCVPixelBufferWidthKey, [NSNumber numberWithInt:height], kCVPixelBufferHeightKey, nil]; recorder->videoAdaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:recorder->video sourcePixelBufferAttributes:videoSource]; if (recorder->videoAdaptor == nil) NSLog(@"Failed creating video adaptor"); if ([recorder->writer canAddInput:recorder->video]) [recorder->writer addInput:recorder->video]; else NSLog(@"Could not add video input to writer"); if (sampleRate > 0 && channelCount > 0) { AudioChannelLayout layout = { .mChannelLayoutTag = channelCount == 1 ? kAudioChannelLayoutTag_Mono : kAudioChannelLayoutTag_Stereo, .mChannelBitmap = 0, .mNumberChannelDescriptions = 0 }; NSDictionary* audioOutputSettings = @{ AVFormatIDKey: @(kAudioFormatMPEG4AAC), AVNumberOfChannelsKey: @(channelCount), AVSampleRateKey: @(sampleRate), AVEncoderBitRateKey: @128000, AVChannelLayoutKey: [NSData dataWithBytes:&layout length:sizeof(layout)] }; recorder->audio = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:audioOutputSettings]; if (!recorder->audio) NSLog(@"Failed creating audio adaptor"); recorder->audio.expectsMediaDataInRealTime = true; AudioStreamBasicDescription audioStreamDesc = { .mSampleRate = sampleRate, .mFormatID = kAudioFormatLinearPCM, .mFormatFlags = kAudioFormatFlagIsPacked | kAudioFormatFlagIsFloat, .mBytesPerPacket = channelCount * sizeof(float), .mFramesPerPacket = 1, .mBytesPerFrame = channelCount * sizeof(float), .mChannelsPerFrame = channelCount, .mBitsPerChannel = sizeof(float) * 8, }; OSStatus status = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &audioStreamDesc, sizeof(layout), &layout, 0, nil, nil, &recorder->audioDesc); if (status) NSLog(@"Failed creating audio format description: %d", (int)status); if ([recorder->writer canAddInput:recorder->audio]) [recorder->writer addInput:recorder->audio]; else NSLog(@"Could not add audio input to writer"); } if (![recorder->writer startWriting]) NSLog(@"Could not start writing: %@", recorder->writer.error); [recorder->writer startSessionAtSourceTime:kCMTimeZero]; NSLog(@"Recording started to %s", recordingPath); return recorder; }
2
0
102
1w
Processing / tapping an HLS audio stream (or global app output)
I'm trying to do some realtime audio processing on audio served from an HLS stream (i.e. an AVPlayer created using an M3U HTTP URL). It doesn't seem like attaching an AVAudioMix configured with with an `audioTapProcessor` has any effect; none of the callbacks except `init` are being invoked. Is this a known limitation? If so, is this documented somewhere?If the above is a limitation, what are my options using some of the other audio APIs? I looked into `AVAudioEngine` as well but it doesn't seem like there's any way I can configure any of the input node types to use an HLS stream. Am I wrong? Are there lower level APIs available to play HLS streams that provide the necessary hooks?Alternatively, is there some generic way to tap into all audio being output by my app regardless of its source?Thanks a lot!
12
0
5.2k
2w
AVPlayerItemSampleBufferOutput
I am using AVPlayer, but I am unable to retrieve PCM data from .m3u8 streams via the AVPlayerItemSampleBufferOutput API in iOS 27 beta. I have tried both the Objective-C and Swift APIs: the Objective-C delegate methods are not being called, and the Swift methods nextAvailableSampleBuffer() and nextSampleBuffer() are returning no data.
1
0
208
2w
watchOS: Network framework WebSocket loses its path ~35 s in, while URLSession keeps working
Following up on TN3135 and the resolution in https://developer.apple.com/forums/thread/773362 — that thread solved establishing a low-level connection on watchOS (the asynchronous AVAudioSession.activate(options:completionHandler:) instead of the synchronous setActive()). This question is about a connection staying established, which I could not find discussed anywhere. Environment: Apple Watch, watchOS 26.6 (23U67). Audio app, WKBackgroundModes = ["self-care"]. Real device, TestFlight build, not the simulator. What works Opening an NWConnection WebSocket to my own server is reliable — 8 attempts out of 8 reached .ready in 0.28–0.98 s, and an echo frame round-tripped in 27–89 ms. Interestingly, in my measurements it opens under BOTH activation variants: the asynchronous activate(options:completionHandler:) AND the synchronous setActive(true). The two are within ~0.2 s of each other. I mention it only because the thread above concluded the synchronous one is insufficient; on 26.6 I cannot reproduce that difference for establishment. What fails The connection goes quiet after roughly half a minute, and an NWPathMonitor running alongside it shows why: the path transitions to .unsatisfied. Four runs: +34.0 s (cellular) +34.6 s (cellular) +36.0 s (Wi-Fi) +34.3 s (companion link only — availableInterfaces ["other", "other"]) The server sends a heartbeat frame every 5 s and closes the socket on a schedule, so I can tell "the peer closed" from "we stopped receiving". The client receives beats 1–6 (5 s … 30 s) and then nothing; the scheduled close never arrives. What I ruled out Server side. The same client construction run on macOS against the same endpoint receives all 8 heartbeats and the scheduled close at 45.1 s. Both audio-session activation variants — no difference, as above. Network type — cellular, Wi-Fi and companion-link-only all drop at ~35 s. The app being suspended. The app keeps logging densely throughout, and in the last run it held a WKExtendedRuntimeSession (delegate reported extendedRuntimeSessionDidStart) and was actively playing audio through AVAudioEngine from the first second — i.e. the audio-streaming condition TN3135 describes — for the entire window. The path dropped anyway, at +34.3 s. An idle socket. Server traffic arrives every 5 s until the drop. The comparison that puzzles me The same app, on the same watch, the same afternoon, relays the same realtime audio session over plain HTTPS (URLSession) instead — and that runs for 64 s continuously without a stall, including straight through a WatchConnectivity "reachability settled: unreachable" transition. So a high-level URLSession request stream survives a period in which a low-level NWConnection's path is reported unsatisfied. That is consistent with the note in thread 773362 that "on watchOS every session is kinda like a background session, where the actual work is done out of process" — but it leaves me unsure what the intended behaviour is. Questions Is a ~35 s path lifetime the expected behaviour for low-level networking on watchOS, or does it indicate something wrong on my side? Does the TN3135 audio-streaming exception cover only the establishment of a low-level connection, or is it also supposed to keep the path available for the duration of the audio streaming? If it is supposed to persist: is there something beyond an active audio session, flowing audio and a WKExtendedRuntimeSession that an app must do to keep the path alive? If ~35 s is the expected ceiling, is a WebSocket a supported transport for a multi-minute conversational audio session on watchOS at all — or is relaying over URLSession the intended approach despite the guidance to prefer Network framework? Happy to file a bug with a sysdiagnose and a reduced sample project if that is more useful — please say the word and I will attach the numbers above.
4
0
995
2w
fail to get HLS realtime stream via AVPlayerItemSampleBufferOutputDelegate
Hi, I'm trying to do some realtime audio processing on audio served from an HLS stream (i.e. an AVPlayer created using an M3U HTTP URL). And I find that new APIs(AVPlayerItemSampleBufferOutput) are available in iOS 27.0 to achieve it. However, I failed to get the available data via the AVPlayerItemSampleBufferOutputDelegate. And I found some error in the system log: I create AVPlayerItemSampleBufferOutput and set the delegate after receiving the AVPlayerItemStatusReadyToPlay event. And here's my code: @interface OCAudioSamplebuffer () <AVPlayerItemSampleBufferOutputDelegate> @property (nonatomic, strong) AVPlayerItemSampleBufferOutput *bufferOutput; @property (nonatomic, strong) dispatch_queue_t bufferOutputQueue; @property (nonatomic, strong) AVPlayerItem *playerItem; @end - (void)playItem:(AVPlayerItem *)item { if (@available(iOS 27, *)) { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; if([NSThread mainThread]){ [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil]; }else{ dispatch_async(dispatch_get_main_queue(), ^{ [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil]; }); } AVPlayerItemSampleBufferOutputAudioConfiguration *cfg = [[AVPlayerItemSampleBufferOutputAudioConfiguration alloc] init]; CMFormatDescriptionRef formatDescription = [self createPCMFormatDescriptionWithSampleRate:44100.0 channels:2 isFloat:YES]; cfg.requestedAudioFormat = formatDescription; if (formatDescription) { NSLog(@"create PCM Format Description success"); CFRelease(formatDescription); } else { NSLog(@"fail to create PCM Format Description"); } self.bufferOutput = [[AVPlayerItemSampleBufferOutput alloc] initWithConfiguration:cfg]; NSLog(@"create buffer success, PCM Format Description%@---,%@", cfg.requestedAudioFormat, formatDescription); self.bufferOutputQueue = dispatch_queue_create("audioSamplebufferQueue", DISPATCH_QUEUE_CONCURRENT); [self.bufferOutput setDelegate:self queue:self.bufferOutputQueue]; [item addOutput:self.bufferOutput]; self.playerItem = item; } else { // Fallback on earlier versions } } Any help. Thank you
1
0
518
3w
flashMode .on overrides locked focus — AF scan runs and refocuses before the strobe
I'm building a fixed-focus camera app (Bayer RAW, manual exposure, focus permanently locked at a known lens position) and need a full-power flash still that keeps that locked focus. On iPhone 17 Pro, iOS 26, any capture with flashMode = .on runs an autofocus-assist scan — visible lens hunt, assist lamp in low light — and the exposure happens at whatever the scan converged on (usually the far background), not my locked position. In low light it reproduces every time; bright-scene behavior varied by configuration (see matrix), and in my current build it hunts in daylight too. This follows https://developer.apple.com/forums/thread/724897 where DTS confirmed locked lens position + flash "is possible" in a test app, but the differentiating configuration was never identified. I've now exhausted every documented lever, with instrumentation, and would like guidance on whether this stage is bypassable at all. Session configuration session.sessionPreset = .photo // Plain wide camera (also reproduced on .builtInLiDARDepthCamera). let camera = AVCaptureDevice.default( .builtInWideAngleCamera, for: .video, position: .back )! session.addInput(try AVCaptureDeviceInput(device: camera)) session.addOutput(photoOutput) photoOutput.maxPhotoQualityPrioritization = .speed photoOutput.isZeroShutterLagEnabled = false photoOutput.isResponsiveCaptureEnabled = true // Pre-allocate flash capture resources up front. photoOutput.setPreparedPhotoSettingsArray( [makeFlashRawSettings()], completionHandler: nil ) Device configuration (before any capture) try camera.lockForConfiguration() camera.isSubjectAreaChangeMonitoringEnabled = false camera.isSmoothAutoFocusEnabled = false camera.autoFocusRangeRestriction = .near camera.automaticallyEnablesLowLightBoostWhenAvailable = false camera.automaticallyAdjustsFaceDrivenAutoFocusEnabled = false camera.isFaceDrivenAutoFocusEnabled = false // true is worse; see matrix camera.automaticallyAdjustsFaceDrivenAutoExposureEnabled = false camera.isFaceDrivenAutoExposureEnabled = false camera.setFocusModeLocked(lensPosition: 0.60) // ~1 m on this device let gains = camera.deviceWhiteBalanceGains( for: .init(temperature: 4000, tint: 0) ) camera.setWhiteBalanceModeLocked(with: gains) camera.setExposureModeCustom( duration: CMTime(value: 1, timescale: 125), iso: 400 ) camera.unlockForConfiguration() Capture func makeFlashRawSettings() -> AVCapturePhotoSettings { let bayer = photoOutput.availableRawPhotoPixelFormatTypes.first { AVCapturePhotoOutput.isBayerRAWPixelFormat($0) }! let settings = AVCapturePhotoSettings(rawPixelFormatType: bayer) settings.flashMode = .on settings.isAutoRedEyeReductionEnabled = false settings.isAutoStillImageStabilizationEnabled = false settings.isAutoVirtualDeviceFusionEnabled = false settings.isAutoContentAwareDistortionCorrectionEnabled = false settings.photoQualityPrioritization = .speed return settings } // Right before the request, exposure flips .custom → .locked (same // duration/ISO), one preview frame presents, then: photoOutput.capturePhoto(with: makeFlashRawSettings(), delegate: self) What I measure (KVO during the capture window) isAdjustingFocus goes true after the request: a scan runs despite focusMode == .locked (assist lamp on in low light). lensPosition moves from the locked 0.60 to a far position and stays there through willCapturePhotoFor — the exposure uses the scan's answer. When isAdjustingFocus falls back to false (before the metering preflash) I issue one setFocusModeLocked(lensPosition: 0.60). The call succeeds, yet the exposure still happens at the far position — something re-asserts the scan's focus before the strobe. With flashMode = .off, locked focus and custom exposure are honored perfectly (my app's normal path). Tried, all reproduced focusMode = .locked + setFocusModeLocked(lensPosition:): scan still runs. Exposure .custom → .locked for the flash window: no change. Plain wide vs LiDAR wide device: no change. Subject-area / smooth AF / face-driven AF+AE / low-light boost all off: scan still runs in low light. isFaceDrivenAutoFocusEnabled = true (steer scan toward faces): worse — scans in daylight too. Red-eye reduction, fusion, distortion correction off: no change. autoFocusRangeRestriction = .near: still converges far. photoQualityPrioritization = .speed everywhere: no change. Prepared photo settings (flash RAW): no change. Re-lock lens mid-scan: fights the scan; worse convergence. Re-lock lens after scan, before strobe: succeeds; exposure still at the scan's position. Torch lit at request time: scans even in bright daylight. The last two items seem diagnostic: the gate is not scene brightness. A torch adding no visible light in daylight still arms the scan, and face-driven AF arms it in bright scenes — the AF-assist stage runs whenever the sequence sees any reason to focus, and a client's .locked focus mode is never treated as that reason being absent. Questions Is the flash AF-assist stage skippable when focusMode == .locked? The earlier thread's DTS reply achieved a locked-focus flash photo — what configuration makes that true on current hardware/iOS? If not skippable: is there a supported way for the final exposure to honor the locked lens position — run the scan but not apply its result? Why does a successful setFocusModeLocked(lensPosition:) issued between scan end and strobe not stick? Is the sequence re-asserting its own focus at exposure time? Are the observed triggers (torch active at request; face-driven AF enabled — each arming the scan regardless of brightness) expected for flashMode = .on? Goal: full-power flash still + fixed focus + manual exposure, which flashMode = .off already delivers minus the flash. Any guidance — including "file a feedback, here's the rdar to duplicate" — appreciated. Happy to attach a focused sample project and sysdiagnose.
0
0
411
3w
Turning AutoFocus off while flash is on.
Hello, I am creating a simple camere app where I want to turn OFF the autofocus (and set the focus within the app) then take a picture with the flash. The only problem is as soon as i set the flash and take a photo, it auto focuses even though i have set the focus mode locked and lens position? Is this even possible? My av capture output settings:     photoOutput.isHighResolutionCaptureEnabled = true     photoOutput.isLivePhotoCaptureEnabled = false;     photoOutput.isDepthDataDeliveryEnabled = false;     photoOutput.isPortraitEffectsMatteDeliveryEnabled = false     photoOutput.isAppleProRAWEnabled = false;     photoOutput.setPreparedPhotoSettingsArray([buildPhotoSettings(flash: flash)]); my AVCapturePhoto Settings     let photoSettings = AVCapturePhotoSettings(rawPixelFormatType: availbleRaw[0]);     photoSettings.isAutoStillImageStabilizationEnabled = false;     photoSettings.flashMode = flash ?.on :.off;     photoSettings.isHighResolutionPhotoEnabled = true;     photoSettings.isAutoRedEyeReductionEnabled = false; my device input settings           //--white balance     let whiteBalanceValues = AVCaptureDevice.WhiteBalanceTemperatureAndTintValues(temperature: settings.whiteBalanceTemp, tint: settings.whiteBalanceTint);     let newWhiteBalance = videoDeviceInput.device.deviceWhiteBalanceGains(for:whiteBalanceValues);     let maxGain = videoDeviceInput.device.maxWhiteBalanceGain           if(newWhiteBalance.redGain > maxGain || newWhiteBalance.greenGain > maxGain || newWhiteBalance.blueGain > maxGain){       videoDeviceInput.device.unlockForConfiguration();       return (false, "WhiteBalance values are invalid (over maximum gain allowed)");     }           videoDeviceInput.device.setWhiteBalanceModeLocked(with: newWhiteBalance);           //--iso and exposure     let exposure = Float64(settings.exposure/1000);     let exposureTime = CMTime(seconds: exposure, preferredTimescale: 1000)     let iso = Float(settings.iso)           if(exposureTime > videoDeviceInput.device.activeFormat.maxExposureDuration || exposureTime < videoDeviceInput.device.activeFormat.minExposureDuration){       videoDeviceInput.device.unlockForConfiguration();       return (false, "Exposure out of bounds");     }           if(iso > videoDeviceInput.device.activeFormat.maxISO || iso < videoDeviceInput.device.activeFormat.minISO){       videoDeviceInput.device.unlockForConfiguration();       return (false, "ISO out of bounds");     }           videoDeviceInput.device.setExposureModeCustom(duration: exposureTime, iso: iso);           //--Lens focus     if(settings.lensPosition < 0 || settings.lensPosition>1){       videoDeviceInput.device.unlockForConfiguration();       return (false, "Lens position out of bounds");     }               if(videoDeviceInput.device.isFocusModeSupported(.locked)){       videoDeviceInput.device.focusMode = .locked;       videoDeviceInput.device.setFocusModeLocked(lensPosition: settings.lensPosition);             }           if #available(iOS 15.4, *) {       if(videoDeviceInput.device.isFaceDrivenAutoFocusEnabled){         videoDeviceInput.device.automaticallyAdjustsFaceDrivenAutoFocusEnabled = false;                 }               if(videoDeviceInput.device.isFaceDrivenAutoExposureEnabled){         videoDeviceInput.device.automaticallyAdjustsFaceDrivenAutoExposureEnabled = false;       }               if(videoDeviceInput.device.isLowLightBoostSupported){         videoDeviceInput.device.automaticallyEnablesLowLightBoostWhenAvailable = false;       }     } else {       // Fallback on earlier versions     }           //--Torch ON     videoDeviceInput.device.torchMode = settings.torch ? AVCaptureDevice.TorchMode.on :AVCaptureDevice.TorchMode.off;           if(settings.torch){       if(settings.torchLevel<0 || settings.torchLevel>1){         return (false, "Flash out of bounds");       }               try? videoDeviceInput.device.setTorchModeOn(level: Float(settings.torchLevel));     }                       //--Finish     videoDeviceInput.device.unlockForConfiguration();
3
0
1.8k
3w
Supported Core Image workflow for cropping/scaling Apple Log x422 buffers without converting to HLG?
We capture Apple Log video using AVCaptureVideoDataOutput with: AVCaptureDevice.activeColorSpace = .appleLog or .appleLog2 kCVPixelFormatType_422YpCbCr10BiPlanarVideoRange (x422) AVAssetWriter for the final ProRes/HEVC recording We need to bake spatial operations such as a centre crop and optional anamorphic desqueeze into the recorded raster. We want the result to remain Apple Log for subsequent grading; we do not want to display-transform or convert it to HLG. Core Image/Core Graphics does not appear to expose a public Apple Log or Apple Log 2 CGColorSpace. Core Video instead identifies the signal using kCVImageBufferLogTransferFunctionKey. Would this be the supported Core Image approach for spatial-only processing? let image = CIImage( cvPixelBuffer: sourceBuffer, options: [.colorSpace: NSNull()] ) let context = CIContext( mtlDevice: metalDevice, options: [ .workingColorSpace: NSNull(), .outputColorSpace: NSNull(), .cacheIntermediates: false ] ) let outputImage = image .cropped(to: cropRect) .transformed(by: spatialTransform) context.render( outputImage, to: destinationX422Buffer, bounds: outputBounds, colorSpace: nil ) We would then copy the source buffer’s Apple Log colour and Log-transfer attachments to the destination buffer and append it to an AVAssetWriterInputPixelBufferAdaptor. Could an Apple engineer clarify the following? Does CIImage(cvPixelBuffer:) natively interpret kCVImageBufferLogTransferFunctionKey, even though no public Apple Log CGColorSpace exists? When NSNull()/nil is supplied as above, does Core Image leave the Apple Log values unmanaged during crop and affine operations? When rendering x422 to x422, can Core Image preserve the Log signal apart from expected resampling/rounding, or does it internally perform a colour conversion such as YCbCr → RGB → YCbCr? For scaling or anamorphic desqueeze, is Apple’s recommended workflow to: resample the encoded Apple Log values with colour management disabled, or explicitly decode Apple Log to a linear working space, resample, and encode back using a custom Metal implementation? Is copying kCVImageBufferLogTransferFunctionKey and the related colour attachments from source to destination sufficient for AVAssetWriter, assuming the writer settings were obtained from recommendedVideoSettingsForAssetWriter(writingTo:)? Is there ever a supported reason to use HLG as an intermediate for Apple Log processing, or should that be avoided? This this part, we are concerned about preserving the captured Log signal in a recording pipeline, not applying a viewing LUT or displaying Apple Log. Next, we also support optional LUT processing with CIColorCube. Some LUTs are technical Apple Log-to-display transforms, while others expect linear or Rec.709 input. If the image is created with .colorSpace: NSNull(), we understand that the LUT receives unmanaged Apple Log code values and that the LUT itself must perform the required transfer-function and gamut conversion. Does Core Image synthesize an Apple Log-aware input color space from kCVImageBufferLogTransferFunctionKey, or must applications implement Apple Log/Apple Log 2 decoding explicitly before using ordinary Core Image filters? Is there a supported CGColorSpace, ColorSync profile, or Core Image conversion API for this? Additionally, what numeric range does CIColorCube receive when its source is an x422 video-range Apple Log buffer— normalized Log RGB values, or values requiring explicit video-range conversion?
0
0
511
3w
Supported way to re-acquire genlock after follow() detaches mid-session?
Summary. iPhone 17 Pro Max + Blackmagic Camera ProDock, genlock BNC in from a generator confirmed at a true 30.00 fps. follow(_:videoFrameDuration:delegate:) reaches .activeSync in ~2 s. On one unit the lock then holds for 10+ minutes. On a second unit, same binary and same reference, it detaches 6 s to ~4 min after lock: .activeSync → .ready with input.externalSyncDevice == nil, no runtime error and no delegate error. Calling follow() again on the still-running session is rejected with -11800 every time, while unfollowExternalSyncDevice() plus a stopRunning()/startRunning() bounce recovers reliably. I am not looking for a fix. I want to know whether my call sequence is wrong, whether this transition is expected, and how a shipping app should be structured around it. Questions Is re-following a running session supported? Is the unfollow + bounce the intended reset sequence, or is there a lighter-weight way to clear whatever state the -11800 is keyed on? And once detached, is re-acquisition entirely the app's responsibility, or is the system expected to re-calibrate on its own while the reference is present? Is a hard detach a legal outcome for an already-calibrated input? The documentation describes .freeRunSync as the hold-over when a locked input loses sync. Is that hold-over guaranteed, or must an app also handle .activeSync → .ready with a nil externalSyncDevice? Is anything in my call sequence wrong (code in a reply below), and is polling input.externalSyncDevice the right signal to key recovery on, or is there a supported notification for detach? Setup. Video-only AVCaptureSession: one .builtInWideAngleCamera input, one AVCaptureVideoDataOutput. No multi-cam, no depth output, no synchronizer, no audio. Both frame durations set to CMTime(1, 30) before the input is created, never rewritten while a follow is live. Device A (iOS 26.0.1) holds: 601 s and 956 s runs, zero detaches. Device B (26.3.1, then 26.5.2) has 39 drops across 6 logs. The ProDock, cable and generator were swapped between units; the failure followed the phone. Caveat: n=2, and unit and OS build vary together. The detach. No AVCaptureSessionRuntimeError and no delegate error (-11892 has never been observed here, so this is not the documented frame-duration-mismatch path). The session keeps running and delivering frames. Status is .ready, not .unavailable — the ProDock stays enumerated, the reference unchanged. No confirmed drop has passed through .freeRunSync. PTS ground truth, independent of the follow state: while locked, every frame PTS sits exactly on the 1/30 grid, zero drift. At the drop there is exactly one teardown gap, 238–337 ms across 8 runs, after which the clock free-runs at ~30.013 fps (444 ppm) and never returns to the grid. On -11800. It surfaces through AVCaptureSessionRuntimeErrorNotification. The bounce recovers 3/3, with no activeFormat change. Caveat: -11800 is AVErrorUnknown and I see it in unrelated cases too, so I do not assume it is specific to retained follow state. Ruled out. Exposure duration — a run at ≤ 16.67 ms, within the recommendation in the follow() documentation, still drops. Reference drift — zero, by microsecond PTS. Accessory chain — full swap; the failure followed the phone. Another client — Final Cut Camera holds genlock on the fragile unit with the same ProDock and reference. Load and resolution — load changes time-to-drop, not whether it drops; with recording and audio off it still drops, and Device B drops at both 12 MP and 1080p. Code and supporting logs are in replies below; the length limit would not take them inline. Per-frame PTS CSVs, raw status logs, and a minimal Xcode project that still drops are available on request. Prior art read: forums/thread/799739 and thread/804594 — neither covers post-lock detach or re-acquisition.
3
0
990
3w
AirPods Sleep Detection pauses meditation playback with no API/callback to identify the reason
Good morning! I work on a meditation app, and since Sleep Detection was introduced for AirPods in iOS 26, we've been receiving complaints from users reporting that their meditation sessions unexpectedly stop after approximately 15–20 minutes when Sleep Detection is enabled. This seems to happen particularly during deep meditation sessions, where the user may remain still and exhibit behavior that could potentially be interpreted as falling asleep. I've also tested this on iOS 27 with the latest beta firmware available for AirPods Pro, and the same behavior still occurs. While investigating and debugging the issue, I found that there doesn't appear to be any public API that allows an app to determine that playback was paused specifically because of AirPods Sleep Detection. From the application's perspective, the AirPods appear to simply send a standard pause command to the AVPlayer, without providing any additional context or reason. There also doesn't seem to be an API that allows us to determine whether the user has Sleep Detection enabled. Even having access to that information would allow us to warn users that their meditation session could potentially be interrupted. AVAudioSession.InterruptionReason does not seem to help in this case either: https://developer.apple.com/documentation/avfaudio/avaudiosession/interruptionreason Is there currently any supported way for an app to: Detect that playback was paused specifically because of AirPods Sleep Detection? Determine whether Sleep Detection is enabled for the connected AirPods? Prevent Sleep Detection from pausing playback for specific apps or specific types of audio sessions? If none of these are currently possible, could Apple consider providing either a notification/callback indicating that Sleep Detection triggered the pause, or an option for users to exclude specific apps from Sleep Detection? This behavior is particularly problematic for meditation apps, since a user in a deep meditation session can easily be mistaken for someone who has fallen asleep. Other meditation apps appear to be affected by the same behavior as well. Best regards, Carlos Antunes
Replies
1
Boosts
0
Views
422
Activity
20h
Can an iOS app programmatically enable Voice Isolation microphone mode?
Hi, I’m developing an iOS app that captures the user’s voice and sends the microphone input to an AI model for speech processing. For this use case, Voice Isolation provides a significantly better input signal in noisy environments. However, I’m currently unable to enable Voice Isolation programmatically when the app starts recording. As I understand it, microphone modes such as Automatic, Standard, Voice Isolation, and Wide Spectrum are controlled by the user through the system UI. My app can detect/observe the current microphone mode, but I have not found a public API that allows the app to select Voice Isolation itself. My questions are: Is there currently a supported public API to programmatically switch the microphone mode from Automatic/Standard → Voice Isolation? If direct selection is not supported, is there a recommended way for an app that primarily processes speech/voice input for an AI model to request or prefer Voice Isolation? Would using AVAudioSession with an appropriate voice-processing configuration, such as .voiceChat, or enabling voice processing through AVAudioEngine, provide equivalent Voice Isolation processing? Is AVCaptureDevice.showSystemUserInterface(.microphoneModes) the intended approach when an app needs the user to change the microphone mode? I understand that Apple may intentionally keep microphone-mode selection under user control. I’m mainly trying to determine whether there is a supported programmatic approach that I may have overlooked, rather than relying on a custom noise-suppression implementation. Any guidance on the recommended architecture for this use case would be greatly appreciated. Thank you!
Replies
0
Boosts
0
Views
223
Activity
1d
Does the TN3135 audio-session networking exception have a defined lifetime? Seeing a ~38.5 s revoke/re-grant cycle
TN3135 describes the exception that lets a watchOS app use low-level networking while it holds an active audio session. I have that working, and the app functions — but the network path is withdrawn and restored on a strikingly regular cycle, and I would like to know whether that is expected behaviour rather than something I am doing wrong. Setup Apple Watch Series 10 (Watch7,9), watchOS 26.5. Reproduced on a Series 6 (Watch6,2). UIBackgroundModes: [audio]; AVAudioSession category .playAndRecord, mode .spokenAudio; activated with the async activate(options:completionHandler:). NWConnection with NWProtocolWebSocket to a WebSocket relay over TLS. The app streams 16 kHz mono PCM continuously while transmitting and holds the socket open otherwise. Symptom NWPathMonitor reports .unsatisfied, then .satisfied about two seconds later, over and over. Measured with the iPhone powered off, so the watch was on its own Wi-Fi: Uptime between drops Outage 36.4 s 2.1 s 36.7 s 1.9 s 36.9 s 2.1 s The regularity is what prompts the question — uptime varies by ±0.3 s and the outage is consistently 2.0 s. That reads as a timeout expiring rather than radio behaviour. What I have ruled out Not the network or the server. A browser client on the same relay, same TLS, same wire protocol, holds a WebSocket indefinitely. Not the interface. Identical cadence over the companion ipsec1 tunnel with the iPhone present, and over the watch's own en0 with the iPhone powered off. Pinning requiredInterfaceType = .wifi while the iPhone is reachable fails outright — the path offers only ipsec1. Not audio-session interruption. I observe interruptionNotification, routeChangeNotification, mediaServicesWereResetNotification and silenceSecondaryAudioHintNotification. None fire at a drop. At the moment the path goes .unsatisfied, the engine is running and the player node is actively playing. Not session idleness. Playing continuous silence for the whole session, rather than only while reconnecting, made no difference — still 36.4 s. The control that surprised me To test whether this affects any long-lived watch socket or only audio-unlocked ones, I built a second app with no AVAudioSession at all, no audio background mode, holding a URLSessionWebSocketTask and kept alive by a WKExtendedRuntimeSession so screen sleep was not a factor. It never connected. NWPathMonitor reported .unsatisfied once and never changed, across a 30 s run, and every request failed with "The Internet connection appears to be offline." I had expected URLSession to be permitted regardless. Questions Does the audio-session networking exception in TN3135 have a defined lifetime, and is a periodic revoke/re-grant cycle expected? If so, is there a supported way to hold it continuously — or is the correct design simply to expect the interruption and reconnect through it? Is it expected that an app with no audio session gets no network path at all on watchOS, including via URLSession, even in the foreground with an extended runtime session?
Replies
15
Boosts
0
Views
2.9k
Activity
2d
AVCaptureDevice.uniqueID for UVC devices is unstable - bug or overstated documentation?
The documentation for AVCaptureDevice.uniqueID states the following: Capture devices have a unique identifier that persists on one system across device connections and disconnections, application restarts, and reboots of the system itself. You can store the value returned by this property to recall or track the status of a specific device in the future. For UVC capture devices this documentation does not hold. The video uniqueID is a hex string of the form 0x<locationID><vendorID><productID>, and the identifying half is the locationID (bus number plus port path). Which identifies a port, not a device. I ran a suite of tests with three identical Elgato 4K X capture cards connected to a Mac Studio w/ M3 Ultra running macOS 26.5.2, and reproduced my findings on a MacBook w/ M3 Pro (same macOS version). See the script at the bottom of the post for how uniqueId & USB serial number are being retrieved. 1. The uniqueID follows the port. Swapping two cards between two built-in ports swaps their uniqueIDs: # Before swap. 4K X uid=0x2000000fd9009b serial=A7SNB50424UBQI 4K X uid=0x12000000fd9009b serial=A7SNB504219J0R # After swapping the cards between the same two ports. 4K X uid=0x2000000fd9009b serial=A7SNB504219J0R 4K X uid=0x12000000fd9009b serial=A7SNB50424UBQI An app that stored 0x2000000fd9009b to recall a specific capture card now silently opens another. 2. A reboot alone can swap uniqueIDs. External USB controllers (here, PCIe USB cards in two Thunderbolt enclosures) can race for bus numbers at boot, so with every cable left in place, a reboot swapped two of the cards: # Before reboot. 4K X uid=0x262000000fd9009b serial=A7SNB504219J0R 4K X uid=0x252000000fd9009b serial=A7SNB50423R73R # After reboot, no cables touched. 4K X uid=0x262000000fd9009b serial=A7SNB50423R73R 4K X uid=0x252000000fd9009b serial=A7SNB504219J0R This behavior is intermittent, a second reboot changed nothing, but a third caused another swap. Cards left alone in built-in ports retain their uniqueIDs across reboots in my testing; the failure requires dynamically enumerated external USB controllers. 3. Even the product ID tail can drift. One unit intermittently enumerates with idProduct 0x009c instead of 0x009b, same port (USB PCIe card in a Thunderbolt enclosure), cables untouched: # Before reboot. 4K X uid=0x222000000fd9009b serial=A7SNB50424UBQI # After reboot. 4K X uid=0x222000000fd9009c serial=A7SNB50424UBQI IOKit and AVFoundation agree each boot... So the change is upstream of both? I'm uncertain where to place blame for this specific issue (UVC device or macOS). Audio on the same physical units is unaffected. The audio uniqueID (AppleUSBAudioEngine:...:<serial>:...) embeds the USB serial and stayed stable through every test. So AVCaptureDevice can provide a stable per-device identifier, just not for UVC video devices. Questions: Is this a bug, or is the documentation overstating the persistence guarantee for USB video devices? What is the supported way to identify a specific physical UVC video device across reboots and port changes? The USB serial number is stable and is what I've fallen back on via IOKit, but there is no documented AVFoundation API to retrieve USB serial number from a UVC video AVCaptureDevice. Related: thread 803759, where the locationID-derived format is described. Script used for all output above (swift ./list-uvc.swift): import AVFoundation import IOKit func usbSerial(forLocation location: UInt32) -> String? { var iterator: io_iterator_t = 0 guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOUSBHostDevice"), &iterator) == KERN_SUCCESS else { return nil } defer { IOObjectRelease(iterator) } var result: String? var service = IOIteratorNext(iterator) while service != 0 { var loc: UInt32 = 0 if let ref = IORegistryEntryCreateCFProperty(service, "locationID" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), let num = ref as? NSNumber { loc = num.uint32Value } if loc == location, let ref = IORegistryEntryCreateCFProperty(service, "USB Serial Number" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), let serial = ref as? String { result = serial } IOObjectRelease(service) if result != nil { break } service = IOIteratorNext(iterator) } return result } let session = AVCaptureDevice.DiscoverySession(deviceTypes: [.external], mediaType: .video, position: .unspecified) for device in session.devices { let uid = device.uniqueID let location = UInt32(truncatingIfNeeded: strtoull(uid, nil, 16) >> 32) let serial = usbSerial(forLocation: location) ?? "N/A" print("\(device.localizedName) uid=\(uid) serial=\(serial)") }
Replies
6
Boosts
0
Views
1.6k
Activity
3d
iOS 27 beta: setExposureModeCustom silently ignored on the front camera
On every iOS 27.0 beta, setExposureModeCustom has no effect on the front camera (.builtInTrueDepthCamera). exposureMode does change to .custom, but the sensor keeps auto-exposing: device.iso and device.exposureDuration report auto-exposure's values, not the requested ones, and frame brightness does not change. No error is thrown. The same code works on iOS 18.x and 26.x on the same devices. Device: iPhone 15 Pro, every iOS 27.0 beta. Also seen on iPhone 14 Pro Max, 16, 16 Pro Max and 17 Pro Max. Session: front camera, AVCaptureVideoDataOutput (BGRA) + AVCaptureDepthDataOutput. Format advertises ISO 20...1920, duration 0.00004...0.06667 s. isExposureModeSupported(.custom) is true. Repro: let auto-exposure settle, then try device.lockForConfiguration() device.setExposureModeCustom(duration: CMTime(value: 1, timescale: 15), iso: 1920, completionHandler: nil) device.unlockForConfiguration() then poll device.iso / device.exposureDuration (the completion handler never fires on this device) and measure frame luma. Readback, polled 0.8 s after the call: requested ISO 1920, 66.7 ms -> reported ISO 349, 60.0 ms requested ISO 20, 0.04 ms -> reported ISO 188, 66.5 ms Requesting the shortest exposure returns the longest, and the same ISO 1920 request returned 249, 349 and 450 on three consecutive runs, so these are auto-exposure's values. Frame luma stayed within 1% between the two phases. setExposureTargetBias, however, is honored on the same device: at +4 EV auto-exposure drives the sensor to ISO 1920 / 66.5 ms and at -4 EV to ISO 24 / 30.0 ms, moving mean luma from 49 to 232. So the sensor does reach the values setExposureModeCustom cannot set. Question: is this intentional or a regression, and how should an app detect that a custom exposure request was refused?
Replies
0
Boosts
0
Views
62
Activity
3d
PhotoKit IMG_XXXX names for videos?
I save stills and videos with PHAssetCreationRequest. I do not set originalFilename. Photos saved with addResource(with: .photo, data:) show originalFilename values like IMG_XXXX.HEIC in PHAssetResource. Videos saved with addResource(with: .video, fileURL:) from AVCaptureMovieFileOutput keep the temp file name (a UUID .mov). The docs say that if originalFilename is omitted, Photos infers a name from the file URL when one is provided, otherwise it generates a name. Is there a supported way for a third-party app to get a system IMG_XXXX original filename for a newly saved video? Thank you.
Replies
1
Boosts
0
Views
491
Activity
3d
iOS 27 beta 5: cameracaptured repeatedly crashes in BWVISNode with two stabilized front-camera video outputs
I’m seeing a repeatable first-party cameracaptured crash on an iPhone 14 Pro (iPhone15,2) running iOS 27 beta 5 (24A5424a). The single-camera AVCaptureSession configuration is: Front wide camera 3840×2160 at 30 fps, SDR/420f Two AVCaptureVideoDataOutput connections: Main recording output: 3840×2160 Auxiliary preview output: approximately 2096×1178 Both connections request and activate .standard video stabilization Within roughly two minutes, cameracaptured crashed three times—once during recording and twice during idle preview. The application receives AVErrorMediaServicesWereReset (-11819) after each crash. All three reports have the same faulting queue and underlying stack: com.apple.coremedia.capture.videodata-stabilization.front FigCFDictionaryGetCGRectIfPresent -[BWVISNode _transformRectanglesInMetadata:pts:] -[BWVISNode _stabilizeMetadataForSampleBuffer:] -[BWVISNode _tallyAndEmitSampleBuffer:] VideoStabilizationV2 The first two crashes are: EXC_BAD_ACCESS / EXC_ARM_PAC_FAIL address: 0x00000000dac11a30 termination: PAC_EXCEPTION, code 261 The third reaches the same stabilization stack but terminates with: EXC_BAD_ACCESS / SIGSEGV KERN_INVALID_ADDRESS at 0x30 App-side frame analytics were disabled, system pressure remained nominal, and neither audiomxd nor bluetoothd restarted. The first crash report also shows two front- stabilization worker threads, consistent with the two stabilized video outputs. I have filed Feedback Assistant report FB24553011 with the complete log archive and all three cameracaptured reports. With the iOS 27 public release approaching, waiting for an OS-side fix is not a viable shipping strategy; an app-side workaround is effectively the only option available for our release. Is this a known issue? In particular: Is it safe to leave .standard stabilization on the main recording connection while forcing the auxiliary preview connection to .off? Would disabling/removing the auxiliary AVCaptureVideoDataOutput reliably reduce this to one stabilization pipeline? If a single stabilized front output remains affected, is disabling front-camera stabilization entirely the only supported containment? Is there any public API for disabling the rectangle-metadata processing performed by BWVISNode? The current field workaround is to use the front camera with stabilization Off, or use a rear camera when stabilization is required.
Replies
0
Boosts
0
Views
257
Activity
6d
Apple Music real-time DJ mixing: is there an API or entitlement beyond MusicKit?
Hello, I am developing an iOS app that uses MusicKit and ApplicationMusicPlayer to create automatic transitions between songs from Apple Music. The app already analyzes tracks using BPM, musical key and danceability, orders them for compatible transitions, and uses MusicPlayer.Transition.crossfade for playback. With the public MusicKit APIs, however, I have reached a limitation. ApplicationMusicPlayer manages the playback queue and crossfade internally. I cannot independently control the outgoing and incoming Apple Music tracks as two decks, which would be required for DJ-style transitions (for example, starting the incoming track while independently controlling the outgoing track, choosing precise mix points, and managing the two playback positions during the overlap). I experimented with MusicPlayer.Queue.Entry startTime and endTime, but changing the end point is not equivalent to having independent deck control and can result in the current track ending before the desired transition. I understand that Apple Music content is protected and that direct access to decoded audio samples may intentionally not be available through the public MusicKit APIs. I am not looking to download, extract, record, or export Apple Music audio. My use case is real-time playback only, for authenticated Apple Music subscribers. My questions are: Is there a public API that allows two Apple Music tracks to be independently controlled and mixed in real time? If not, is there a restricted entitlement, API, or developer program available for DJ/mixing applications? If this capability requires a commercial or technical partnership with Apple Music rather than a public API, is there an official channel through which a developer can request or discuss such access? I am aware that some third-party DJ applications provide real-time mixing with Apple Music, so I would like to understand whether there is an officially supported integration path for other developers, rather than trying to work around the limitations of ApplicationMusicPlayer. Thank you.
Replies
0
Boosts
0
Views
460
Activity
1w
videoZoomFactor updates do not propagate smoothly to an unstabilized secondary AVCaptureVideoDataOutput
I’m seeing a device/OS-specific AVFoundation issue on iPhone 14 Pro running iOS 26.6. A secondary AVCaptureVideoDataOutput is used to provide an unstabilized monitoring feed while the main recording connection is stabilized. During continuous zoom changes, frames from the secondary output continue arriving and scene motion remains live, but its visible zoom/crop/FOV intermittently remains unchanged and then catches up. The saved recording remains smooth and reflects the requested zoom correctly. Minimal configuration: Device: iPhone 14 Pro iOS: 26.6 Physical Ultra Wide camera 1920×1080 at 30 fps SDR, 8-bit YUV Main VDO: 420v Main connection stabilization: .cinematicExtendedEnhanced Auxiliary VDO: 420f Auxiliary connection stabilization: explicitly .off automaticallyConfiguresOutputBufferDimensions = false deliversPreviewSizedOutputBuffers = true alwaysDiscardsLateVideoFrames = true Deferred start disabled Both outputs use a serial delegate queue The auxiliary output is displayed directly without image processing. During continuous videoZoomFactor updates: AVCaptureDevice.videoZoomFactor advances correctly. The UI zoom value advances correctly. The main recorded output zooms smoothly. Frames from the auxiliary output continue arriving and scene motion remains live. Only the auxiliary output's visible zoom/crop/FOV intermittently holds at an older value and then catches up. This is not a complete preview-frame stall: camera movement remains visible during the periods when zoom does not visually advance. The problem occurs with any non-Off stabilization tier in the production app because that configuration installs the unstabilized auxiliary output. Stabilization Off removes the auxiliary topology, and zoom then appears smooth on the main preview feed. A standalone capture sample reproduces the problem without the application’s writer or rendering pipeline. Current device matrix: iPhone 14 Pro, iOS 26.6: reproduces. iPhone 13 Pro, iOS 18.6.x, same released application version: does not reproduce. iPhone 17 Pro, iOS 26.6, isolated sample: does not reproduce. iPhone 14 Pro, iOS 27 beta 5: testing in progress — result to be added. The issue was initially reported with HEVC/Apple Log capture, but it remains reproducible after reducing the graph to 1080p30 SDR8. Questions: Is using two video-data-output connections with different stabilization modes—Extreme on the recording output and Off on the monitoring output—a supported configuration? Is delayed propagation of zoom geometry/crop to a secondary video-data output known on iPhone 14 Pro/iOS 26 when another output connection is stabilized? Is there a recommended AVFoundation topology for obtaining a low-latency, unstabilized monitoring feed while separately recording stabilized video? Are there output or connection properties that must be set to make videoZoomFactor geometry changes propagate synchronously to both outputs? I can provide the standalone sample project, screen recordings, connection-mode logs, buffer PTS/arrival cadence, and a sysdiagnose. EDIT: Issue seen on iOS 27 beta 5 devices as well. No such issue is seen in iOS 18 devices.
Replies
0
Boosts
0
Views
72
Activity
1w
How should live latency be measured and maintained with AVPlayer (HLS / LL-HLS)?
We keep live playback at a consistent distance from the live edge using small playback rate adjustments, with a target range based on recommendedTimeOffsetFromLive. Since the live edge is not exposed by AVPlayer, we currently fall back to seekableTimeRanges.end as our best approximation. What should be treated as the live edge, and how should the current live latency be measured? Is rate adjustment the appropriate way to hold a target latency? While playing above 1.0x, the playhead can reach the seekable end, at which point AVPlayerItemDidPlayToEndTime fires and halts the live stream. How can we guard against ? Does any of this differ between regular HLS and LL-HLS? A clear statement of the intended contract here would resolve a lot of uncertainty. Thanks in advance.
Replies
3
Boosts
0
Views
644
Activity
1w
Video recording goes fine but adding audio fails mysteriously
I'm trying to update an old unity app for a client. The app has been crashing on iOS in a plugin they use called NatCorder. They use it to record video only separately and then re-record it with effects and audio gathered separately. Instead of trying to update the plugin to something else which would be quite the hassle, I noticed the API for the native part of the plugin, where the crash occurs, is very simple, especially if you don't try to support everything the plugin does and the app does not use. So I tried to re-implement that native library using AVFoundation. I got the video recording right, it captures the camera from the iPhone and writes it to a file properly. However, when the app does the second part, where it sends video and audio frames to the plugin, it fails. The app sends all the video frames and then sends all the audio frames. The video frames are eaten fine by AVFoundation but the audio fails at random points with unknown errors. I wonder if I'm trying to use incompatible audio-video formats or if I'm using timestamps wrong or something. Here's my init code. Anything suspicious to you? void* NCCreateMP4Recorder(int width, int height, float framerate, int bitrate, int keyframeInterval, int sampleRate, int channelCount, const char* recordingPath, void (*callback)(void*, void*), void* context) { Recorder* recorder = calloc(1, sizeof(Recorder)); recorder->context = context; recorder->callback = callback; recorder->path = strdup(recordingPath); recorder->width = width; recorder->channelCount = channelCount; recorder->sampleRate = sampleRate; recorder->height = height; NSError *error = nil; NSURL* url = createURLFromArgumentCString(recordingPath); recorder->writer = [AVAssetWriter assetWriterWithURL:url fileType:AVFileTypeMPEG4 error:&error]; if (recorder->writer == nil) NSLog(@"Failed creating media writer: %@", error); NSDictionary *videoSettings = @{ AVVideoCodecKey: AVVideoCodecTypeH264, AVVideoWidthKey: @(width), AVVideoHeightKey: @(height), AVVideoCompressionPropertiesKey: @{ AVVideoAverageBitRateKey: @(bitrate), AVVideoMaxKeyFrameIntervalKey: @(keyframeInterval), } }; recorder->video = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings]; if (recorder->video == nil) NSLog(@"Failed creating video writer input"); recorder->video.expectsMediaDataInRealTime = true; NSDictionary* videoSource = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, [NSNumber numberWithInt:width], kCVPixelBufferWidthKey, [NSNumber numberWithInt:height], kCVPixelBufferHeightKey, nil]; recorder->videoAdaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:recorder->video sourcePixelBufferAttributes:videoSource]; if (recorder->videoAdaptor == nil) NSLog(@"Failed creating video adaptor"); if ([recorder->writer canAddInput:recorder->video]) [recorder->writer addInput:recorder->video]; else NSLog(@"Could not add video input to writer"); if (sampleRate > 0 && channelCount > 0) { AudioChannelLayout layout = { .mChannelLayoutTag = channelCount == 1 ? kAudioChannelLayoutTag_Mono : kAudioChannelLayoutTag_Stereo, .mChannelBitmap = 0, .mNumberChannelDescriptions = 0 }; NSDictionary* audioOutputSettings = @{ AVFormatIDKey: @(kAudioFormatMPEG4AAC), AVNumberOfChannelsKey: @(channelCount), AVSampleRateKey: @(sampleRate), AVEncoderBitRateKey: @128000, AVChannelLayoutKey: [NSData dataWithBytes:&layout length:sizeof(layout)] }; recorder->audio = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeAudio outputSettings:audioOutputSettings]; if (!recorder->audio) NSLog(@"Failed creating audio adaptor"); recorder->audio.expectsMediaDataInRealTime = true; AudioStreamBasicDescription audioStreamDesc = { .mSampleRate = sampleRate, .mFormatID = kAudioFormatLinearPCM, .mFormatFlags = kAudioFormatFlagIsPacked | kAudioFormatFlagIsFloat, .mBytesPerPacket = channelCount * sizeof(float), .mFramesPerPacket = 1, .mBytesPerFrame = channelCount * sizeof(float), .mChannelsPerFrame = channelCount, .mBitsPerChannel = sizeof(float) * 8, }; OSStatus status = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &audioStreamDesc, sizeof(layout), &layout, 0, nil, nil, &recorder->audioDesc); if (status) NSLog(@"Failed creating audio format description: %d", (int)status); if ([recorder->writer canAddInput:recorder->audio]) [recorder->writer addInput:recorder->audio]; else NSLog(@"Could not add audio input to writer"); } if (![recorder->writer startWriting]) NSLog(@"Could not start writing: %@", recorder->writer.error); [recorder->writer startSessionAtSourceTime:kCMTimeZero]; NSLog(@"Recording started to %s", recordingPath); return recorder; }
Replies
2
Boosts
0
Views
102
Activity
1w
Processing / tapping an HLS audio stream (or global app output)
I'm trying to do some realtime audio processing on audio served from an HLS stream (i.e. an AVPlayer created using an M3U HTTP URL). It doesn't seem like attaching an AVAudioMix configured with with an `audioTapProcessor` has any effect; none of the callbacks except `init` are being invoked. Is this a known limitation? If so, is this documented somewhere?If the above is a limitation, what are my options using some of the other audio APIs? I looked into `AVAudioEngine` as well but it doesn't seem like there's any way I can configure any of the input node types to use an HLS stream. Am I wrong? Are there lower level APIs available to play HLS streams that provide the necessary hooks?Alternatively, is there some generic way to tap into all audio being output by my app regardless of its source?Thanks a lot!
Replies
12
Boosts
0
Views
5.2k
Activity
2w
AVPlayerItemSampleBufferOutput
I am using AVPlayer, but I am unable to retrieve PCM data from .m3u8 streams via the AVPlayerItemSampleBufferOutput API in iOS 27 beta. I have tried both the Objective-C and Swift APIs: the Objective-C delegate methods are not being called, and the Swift methods nextAvailableSampleBuffer() and nextSampleBuffer() are returning no data.
Replies
1
Boosts
0
Views
208
Activity
2w
watchOS: Network framework WebSocket loses its path ~35 s in, while URLSession keeps working
Following up on TN3135 and the resolution in https://developer.apple.com/forums/thread/773362 — that thread solved establishing a low-level connection on watchOS (the asynchronous AVAudioSession.activate(options:completionHandler:) instead of the synchronous setActive()). This question is about a connection staying established, which I could not find discussed anywhere. Environment: Apple Watch, watchOS 26.6 (23U67). Audio app, WKBackgroundModes = ["self-care"]. Real device, TestFlight build, not the simulator. What works Opening an NWConnection WebSocket to my own server is reliable — 8 attempts out of 8 reached .ready in 0.28–0.98 s, and an echo frame round-tripped in 27–89 ms. Interestingly, in my measurements it opens under BOTH activation variants: the asynchronous activate(options:completionHandler:) AND the synchronous setActive(true). The two are within ~0.2 s of each other. I mention it only because the thread above concluded the synchronous one is insufficient; on 26.6 I cannot reproduce that difference for establishment. What fails The connection goes quiet after roughly half a minute, and an NWPathMonitor running alongside it shows why: the path transitions to .unsatisfied. Four runs: +34.0 s (cellular) +34.6 s (cellular) +36.0 s (Wi-Fi) +34.3 s (companion link only — availableInterfaces ["other", "other"]) The server sends a heartbeat frame every 5 s and closes the socket on a schedule, so I can tell "the peer closed" from "we stopped receiving". The client receives beats 1–6 (5 s … 30 s) and then nothing; the scheduled close never arrives. What I ruled out Server side. The same client construction run on macOS against the same endpoint receives all 8 heartbeats and the scheduled close at 45.1 s. Both audio-session activation variants — no difference, as above. Network type — cellular, Wi-Fi and companion-link-only all drop at ~35 s. The app being suspended. The app keeps logging densely throughout, and in the last run it held a WKExtendedRuntimeSession (delegate reported extendedRuntimeSessionDidStart) and was actively playing audio through AVAudioEngine from the first second — i.e. the audio-streaming condition TN3135 describes — for the entire window. The path dropped anyway, at +34.3 s. An idle socket. Server traffic arrives every 5 s until the drop. The comparison that puzzles me The same app, on the same watch, the same afternoon, relays the same realtime audio session over plain HTTPS (URLSession) instead — and that runs for 64 s continuously without a stall, including straight through a WatchConnectivity "reachability settled: unreachable" transition. So a high-level URLSession request stream survives a period in which a low-level NWConnection's path is reported unsatisfied. That is consistent with the note in thread 773362 that "on watchOS every session is kinda like a background session, where the actual work is done out of process" — but it leaves me unsure what the intended behaviour is. Questions Is a ~35 s path lifetime the expected behaviour for low-level networking on watchOS, or does it indicate something wrong on my side? Does the TN3135 audio-streaming exception cover only the establishment of a low-level connection, or is it also supposed to keep the path available for the duration of the audio streaming? If it is supposed to persist: is there something beyond an active audio session, flowing audio and a WKExtendedRuntimeSession that an app must do to keep the path alive? If ~35 s is the expected ceiling, is a WebSocket a supported transport for a multi-minute conversational audio session on watchOS at all — or is relaying over URLSession the intended approach despite the guidance to prefer Network framework? Happy to file a bug with a sysdiagnose and a reduced sample project if that is more useful — please say the word and I will attach the numbers above.
Replies
4
Boosts
0
Views
995
Activity
2w
fail to get HLS realtime stream via AVPlayerItemSampleBufferOutputDelegate
Hi, I'm trying to do some realtime audio processing on audio served from an HLS stream (i.e. an AVPlayer created using an M3U HTTP URL). And I find that new APIs(AVPlayerItemSampleBufferOutput) are available in iOS 27.0 to achieve it. However, I failed to get the available data via the AVPlayerItemSampleBufferOutputDelegate. And I found some error in the system log: I create AVPlayerItemSampleBufferOutput and set the delegate after receiving the AVPlayerItemStatusReadyToPlay event. And here's my code: @interface OCAudioSamplebuffer () <AVPlayerItemSampleBufferOutputDelegate> @property (nonatomic, strong) AVPlayerItemSampleBufferOutput *bufferOutput; @property (nonatomic, strong) dispatch_queue_t bufferOutputQueue; @property (nonatomic, strong) AVPlayerItem *playerItem; @end - (void)playItem:(AVPlayerItem *)item { if (@available(iOS 27, *)) { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; if([NSThread mainThread]){ [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil]; }else{ dispatch_async(dispatch_get_main_queue(), ^{ [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryPlayback error:nil]; [audioSession setActive:YES error:nil]; }); } AVPlayerItemSampleBufferOutputAudioConfiguration *cfg = [[AVPlayerItemSampleBufferOutputAudioConfiguration alloc] init]; CMFormatDescriptionRef formatDescription = [self createPCMFormatDescriptionWithSampleRate:44100.0 channels:2 isFloat:YES]; cfg.requestedAudioFormat = formatDescription; if (formatDescription) { NSLog(@"create PCM Format Description success"); CFRelease(formatDescription); } else { NSLog(@"fail to create PCM Format Description"); } self.bufferOutput = [[AVPlayerItemSampleBufferOutput alloc] initWithConfiguration:cfg]; NSLog(@"create buffer success, PCM Format Description%@---,%@", cfg.requestedAudioFormat, formatDescription); self.bufferOutputQueue = dispatch_queue_create("audioSamplebufferQueue", DISPATCH_QUEUE_CONCURRENT); [self.bufferOutput setDelegate:self queue:self.bufferOutputQueue]; [item addOutput:self.bufferOutput]; self.playerItem = item; } else { // Fallback on earlier versions } } Any help. Thank you
Replies
1
Boosts
0
Views
518
Activity
3w
flashMode .on overrides locked focus — AF scan runs and refocuses before the strobe
I'm building a fixed-focus camera app (Bayer RAW, manual exposure, focus permanently locked at a known lens position) and need a full-power flash still that keeps that locked focus. On iPhone 17 Pro, iOS 26, any capture with flashMode = .on runs an autofocus-assist scan — visible lens hunt, assist lamp in low light — and the exposure happens at whatever the scan converged on (usually the far background), not my locked position. In low light it reproduces every time; bright-scene behavior varied by configuration (see matrix), and in my current build it hunts in daylight too. This follows https://developer.apple.com/forums/thread/724897 where DTS confirmed locked lens position + flash "is possible" in a test app, but the differentiating configuration was never identified. I've now exhausted every documented lever, with instrumentation, and would like guidance on whether this stage is bypassable at all. Session configuration session.sessionPreset = .photo // Plain wide camera (also reproduced on .builtInLiDARDepthCamera). let camera = AVCaptureDevice.default( .builtInWideAngleCamera, for: .video, position: .back )! session.addInput(try AVCaptureDeviceInput(device: camera)) session.addOutput(photoOutput) photoOutput.maxPhotoQualityPrioritization = .speed photoOutput.isZeroShutterLagEnabled = false photoOutput.isResponsiveCaptureEnabled = true // Pre-allocate flash capture resources up front. photoOutput.setPreparedPhotoSettingsArray( [makeFlashRawSettings()], completionHandler: nil ) Device configuration (before any capture) try camera.lockForConfiguration() camera.isSubjectAreaChangeMonitoringEnabled = false camera.isSmoothAutoFocusEnabled = false camera.autoFocusRangeRestriction = .near camera.automaticallyEnablesLowLightBoostWhenAvailable = false camera.automaticallyAdjustsFaceDrivenAutoFocusEnabled = false camera.isFaceDrivenAutoFocusEnabled = false // true is worse; see matrix camera.automaticallyAdjustsFaceDrivenAutoExposureEnabled = false camera.isFaceDrivenAutoExposureEnabled = false camera.setFocusModeLocked(lensPosition: 0.60) // ~1 m on this device let gains = camera.deviceWhiteBalanceGains( for: .init(temperature: 4000, tint: 0) ) camera.setWhiteBalanceModeLocked(with: gains) camera.setExposureModeCustom( duration: CMTime(value: 1, timescale: 125), iso: 400 ) camera.unlockForConfiguration() Capture func makeFlashRawSettings() -> AVCapturePhotoSettings { let bayer = photoOutput.availableRawPhotoPixelFormatTypes.first { AVCapturePhotoOutput.isBayerRAWPixelFormat($0) }! let settings = AVCapturePhotoSettings(rawPixelFormatType: bayer) settings.flashMode = .on settings.isAutoRedEyeReductionEnabled = false settings.isAutoStillImageStabilizationEnabled = false settings.isAutoVirtualDeviceFusionEnabled = false settings.isAutoContentAwareDistortionCorrectionEnabled = false settings.photoQualityPrioritization = .speed return settings } // Right before the request, exposure flips .custom → .locked (same // duration/ISO), one preview frame presents, then: photoOutput.capturePhoto(with: makeFlashRawSettings(), delegate: self) What I measure (KVO during the capture window) isAdjustingFocus goes true after the request: a scan runs despite focusMode == .locked (assist lamp on in low light). lensPosition moves from the locked 0.60 to a far position and stays there through willCapturePhotoFor — the exposure uses the scan's answer. When isAdjustingFocus falls back to false (before the metering preflash) I issue one setFocusModeLocked(lensPosition: 0.60). The call succeeds, yet the exposure still happens at the far position — something re-asserts the scan's focus before the strobe. With flashMode = .off, locked focus and custom exposure are honored perfectly (my app's normal path). Tried, all reproduced focusMode = .locked + setFocusModeLocked(lensPosition:): scan still runs. Exposure .custom → .locked for the flash window: no change. Plain wide vs LiDAR wide device: no change. Subject-area / smooth AF / face-driven AF+AE / low-light boost all off: scan still runs in low light. isFaceDrivenAutoFocusEnabled = true (steer scan toward faces): worse — scans in daylight too. Red-eye reduction, fusion, distortion correction off: no change. autoFocusRangeRestriction = .near: still converges far. photoQualityPrioritization = .speed everywhere: no change. Prepared photo settings (flash RAW): no change. Re-lock lens mid-scan: fights the scan; worse convergence. Re-lock lens after scan, before strobe: succeeds; exposure still at the scan's position. Torch lit at request time: scans even in bright daylight. The last two items seem diagnostic: the gate is not scene brightness. A torch adding no visible light in daylight still arms the scan, and face-driven AF arms it in bright scenes — the AF-assist stage runs whenever the sequence sees any reason to focus, and a client's .locked focus mode is never treated as that reason being absent. Questions Is the flash AF-assist stage skippable when focusMode == .locked? The earlier thread's DTS reply achieved a locked-focus flash photo — what configuration makes that true on current hardware/iOS? If not skippable: is there a supported way for the final exposure to honor the locked lens position — run the scan but not apply its result? Why does a successful setFocusModeLocked(lensPosition:) issued between scan end and strobe not stick? Is the sequence re-asserting its own focus at exposure time? Are the observed triggers (torch active at request; face-driven AF enabled — each arming the scan regardless of brightness) expected for flashMode = .on? Goal: full-power flash still + fixed focus + manual exposure, which flashMode = .off already delivers minus the flash. Any guidance — including "file a feedback, here's the rdar to duplicate" — appreciated. Happy to attach a focused sample project and sysdiagnose.
Replies
0
Boosts
0
Views
411
Activity
3w
Turning AutoFocus off while flash is on.
Hello, I am creating a simple camere app where I want to turn OFF the autofocus (and set the focus within the app) then take a picture with the flash. The only problem is as soon as i set the flash and take a photo, it auto focuses even though i have set the focus mode locked and lens position? Is this even possible? My av capture output settings:     photoOutput.isHighResolutionCaptureEnabled = true     photoOutput.isLivePhotoCaptureEnabled = false;     photoOutput.isDepthDataDeliveryEnabled = false;     photoOutput.isPortraitEffectsMatteDeliveryEnabled = false     photoOutput.isAppleProRAWEnabled = false;     photoOutput.setPreparedPhotoSettingsArray([buildPhotoSettings(flash: flash)]); my AVCapturePhoto Settings     let photoSettings = AVCapturePhotoSettings(rawPixelFormatType: availbleRaw[0]);     photoSettings.isAutoStillImageStabilizationEnabled = false;     photoSettings.flashMode = flash ?.on :.off;     photoSettings.isHighResolutionPhotoEnabled = true;     photoSettings.isAutoRedEyeReductionEnabled = false; my device input settings           //--white balance     let whiteBalanceValues = AVCaptureDevice.WhiteBalanceTemperatureAndTintValues(temperature: settings.whiteBalanceTemp, tint: settings.whiteBalanceTint);     let newWhiteBalance = videoDeviceInput.device.deviceWhiteBalanceGains(for:whiteBalanceValues);     let maxGain = videoDeviceInput.device.maxWhiteBalanceGain           if(newWhiteBalance.redGain > maxGain || newWhiteBalance.greenGain > maxGain || newWhiteBalance.blueGain > maxGain){       videoDeviceInput.device.unlockForConfiguration();       return (false, "WhiteBalance values are invalid (over maximum gain allowed)");     }           videoDeviceInput.device.setWhiteBalanceModeLocked(with: newWhiteBalance);           //--iso and exposure     let exposure = Float64(settings.exposure/1000);     let exposureTime = CMTime(seconds: exposure, preferredTimescale: 1000)     let iso = Float(settings.iso)           if(exposureTime > videoDeviceInput.device.activeFormat.maxExposureDuration || exposureTime < videoDeviceInput.device.activeFormat.minExposureDuration){       videoDeviceInput.device.unlockForConfiguration();       return (false, "Exposure out of bounds");     }           if(iso > videoDeviceInput.device.activeFormat.maxISO || iso < videoDeviceInput.device.activeFormat.minISO){       videoDeviceInput.device.unlockForConfiguration();       return (false, "ISO out of bounds");     }           videoDeviceInput.device.setExposureModeCustom(duration: exposureTime, iso: iso);           //--Lens focus     if(settings.lensPosition < 0 || settings.lensPosition>1){       videoDeviceInput.device.unlockForConfiguration();       return (false, "Lens position out of bounds");     }               if(videoDeviceInput.device.isFocusModeSupported(.locked)){       videoDeviceInput.device.focusMode = .locked;       videoDeviceInput.device.setFocusModeLocked(lensPosition: settings.lensPosition);             }           if #available(iOS 15.4, *) {       if(videoDeviceInput.device.isFaceDrivenAutoFocusEnabled){         videoDeviceInput.device.automaticallyAdjustsFaceDrivenAutoFocusEnabled = false;                 }               if(videoDeviceInput.device.isFaceDrivenAutoExposureEnabled){         videoDeviceInput.device.automaticallyAdjustsFaceDrivenAutoExposureEnabled = false;       }               if(videoDeviceInput.device.isLowLightBoostSupported){         videoDeviceInput.device.automaticallyEnablesLowLightBoostWhenAvailable = false;       }     } else {       // Fallback on earlier versions     }           //--Torch ON     videoDeviceInput.device.torchMode = settings.torch ? AVCaptureDevice.TorchMode.on :AVCaptureDevice.TorchMode.off;           if(settings.torch){       if(settings.torchLevel<0 || settings.torchLevel>1){         return (false, "Flash out of bounds");       }               try? videoDeviceInput.device.setTorchModeOn(level: Float(settings.torchLevel));     }                       //--Finish     videoDeviceInput.device.unlockForConfiguration();
Replies
3
Boosts
0
Views
1.8k
Activity
3w
Supported Core Image workflow for cropping/scaling Apple Log x422 buffers without converting to HLG?
We capture Apple Log video using AVCaptureVideoDataOutput with: AVCaptureDevice.activeColorSpace = .appleLog or .appleLog2 kCVPixelFormatType_422YpCbCr10BiPlanarVideoRange (x422) AVAssetWriter for the final ProRes/HEVC recording We need to bake spatial operations such as a centre crop and optional anamorphic desqueeze into the recorded raster. We want the result to remain Apple Log for subsequent grading; we do not want to display-transform or convert it to HLG. Core Image/Core Graphics does not appear to expose a public Apple Log or Apple Log 2 CGColorSpace. Core Video instead identifies the signal using kCVImageBufferLogTransferFunctionKey. Would this be the supported Core Image approach for spatial-only processing? let image = CIImage( cvPixelBuffer: sourceBuffer, options: [.colorSpace: NSNull()] ) let context = CIContext( mtlDevice: metalDevice, options: [ .workingColorSpace: NSNull(), .outputColorSpace: NSNull(), .cacheIntermediates: false ] ) let outputImage = image .cropped(to: cropRect) .transformed(by: spatialTransform) context.render( outputImage, to: destinationX422Buffer, bounds: outputBounds, colorSpace: nil ) We would then copy the source buffer’s Apple Log colour and Log-transfer attachments to the destination buffer and append it to an AVAssetWriterInputPixelBufferAdaptor. Could an Apple engineer clarify the following? Does CIImage(cvPixelBuffer:) natively interpret kCVImageBufferLogTransferFunctionKey, even though no public Apple Log CGColorSpace exists? When NSNull()/nil is supplied as above, does Core Image leave the Apple Log values unmanaged during crop and affine operations? When rendering x422 to x422, can Core Image preserve the Log signal apart from expected resampling/rounding, or does it internally perform a colour conversion such as YCbCr → RGB → YCbCr? For scaling or anamorphic desqueeze, is Apple’s recommended workflow to: resample the encoded Apple Log values with colour management disabled, or explicitly decode Apple Log to a linear working space, resample, and encode back using a custom Metal implementation? Is copying kCVImageBufferLogTransferFunctionKey and the related colour attachments from source to destination sufficient for AVAssetWriter, assuming the writer settings were obtained from recommendedVideoSettingsForAssetWriter(writingTo:)? Is there ever a supported reason to use HLG as an intermediate for Apple Log processing, or should that be avoided? This this part, we are concerned about preserving the captured Log signal in a recording pipeline, not applying a viewing LUT or displaying Apple Log. Next, we also support optional LUT processing with CIColorCube. Some LUTs are technical Apple Log-to-display transforms, while others expect linear or Rec.709 input. If the image is created with .colorSpace: NSNull(), we understand that the LUT receives unmanaged Apple Log code values and that the LUT itself must perform the required transfer-function and gamut conversion. Does Core Image synthesize an Apple Log-aware input color space from kCVImageBufferLogTransferFunctionKey, or must applications implement Apple Log/Apple Log 2 decoding explicitly before using ordinary Core Image filters? Is there a supported CGColorSpace, ColorSync profile, or Core Image conversion API for this? Additionally, what numeric range does CIColorCube receive when its source is an x422 video-range Apple Log buffer— normalized Log RGB values, or values requiring explicit video-range conversion?
Replies
0
Boosts
0
Views
511
Activity
3w
Supported way to re-acquire genlock after follow() detaches mid-session?
Summary. iPhone 17 Pro Max + Blackmagic Camera ProDock, genlock BNC in from a generator confirmed at a true 30.00 fps. follow(_:videoFrameDuration:delegate:) reaches .activeSync in ~2 s. On one unit the lock then holds for 10+ minutes. On a second unit, same binary and same reference, it detaches 6 s to ~4 min after lock: .activeSync → .ready with input.externalSyncDevice == nil, no runtime error and no delegate error. Calling follow() again on the still-running session is rejected with -11800 every time, while unfollowExternalSyncDevice() plus a stopRunning()/startRunning() bounce recovers reliably. I am not looking for a fix. I want to know whether my call sequence is wrong, whether this transition is expected, and how a shipping app should be structured around it. Questions Is re-following a running session supported? Is the unfollow + bounce the intended reset sequence, or is there a lighter-weight way to clear whatever state the -11800 is keyed on? And once detached, is re-acquisition entirely the app's responsibility, or is the system expected to re-calibrate on its own while the reference is present? Is a hard detach a legal outcome for an already-calibrated input? The documentation describes .freeRunSync as the hold-over when a locked input loses sync. Is that hold-over guaranteed, or must an app also handle .activeSync → .ready with a nil externalSyncDevice? Is anything in my call sequence wrong (code in a reply below), and is polling input.externalSyncDevice the right signal to key recovery on, or is there a supported notification for detach? Setup. Video-only AVCaptureSession: one .builtInWideAngleCamera input, one AVCaptureVideoDataOutput. No multi-cam, no depth output, no synchronizer, no audio. Both frame durations set to CMTime(1, 30) before the input is created, never rewritten while a follow is live. Device A (iOS 26.0.1) holds: 601 s and 956 s runs, zero detaches. Device B (26.3.1, then 26.5.2) has 39 drops across 6 logs. The ProDock, cable and generator were swapped between units; the failure followed the phone. Caveat: n=2, and unit and OS build vary together. The detach. No AVCaptureSessionRuntimeError and no delegate error (-11892 has never been observed here, so this is not the documented frame-duration-mismatch path). The session keeps running and delivering frames. Status is .ready, not .unavailable — the ProDock stays enumerated, the reference unchanged. No confirmed drop has passed through .freeRunSync. PTS ground truth, independent of the follow state: while locked, every frame PTS sits exactly on the 1/30 grid, zero drift. At the drop there is exactly one teardown gap, 238–337 ms across 8 runs, after which the clock free-runs at ~30.013 fps (444 ppm) and never returns to the grid. On -11800. It surfaces through AVCaptureSessionRuntimeErrorNotification. The bounce recovers 3/3, with no activeFormat change. Caveat: -11800 is AVErrorUnknown and I see it in unrelated cases too, so I do not assume it is specific to retained follow state. Ruled out. Exposure duration — a run at ≤ 16.67 ms, within the recommendation in the follow() documentation, still drops. Reference drift — zero, by microsecond PTS. Accessory chain — full swap; the failure followed the phone. Another client — Final Cut Camera holds genlock on the fragile unit with the same ProDock and reference. Load and resolution — load changes time-to-drop, not whether it drops; with recording and audio off it still drops, and Device B drops at both 12 MP and 1080p. Code and supporting logs are in replies below; the length limit would not take them inline. Per-frame PTS CSVs, raw status logs, and a minimal Xcode project that still drops are available on request. Prior art read: forums/thread/799739 and thread/804594 — neither covers post-lock detach or re-acquisition.
Replies
3
Boosts
0
Views
990
Activity
3w
How to hide route button `showsRouteButton = false` in `MPVolumeView` without deprecation warning?
MPVolumeView's showsRouteButton was deprecated (https://developer.apple.com/documentation/mediaplayer/mpvolumeview/showsroutebutton?language=objc). It's not clear how can we now hide this button without deprecation warning. The documentation is lacking. Please advise. Thank you!
Replies
6
Boosts
0
Views
1.1k
Activity
4w