Dive into the technical aspects of audio on your device, including codecs, format support, and customization options.

Audio Documentation

Posts under Audio subtopic

Post

Replies

Boosts

Views

Activity

AVAssetExportSession trims audio with some error
Hi there!My goal is to trim audio quite precisely. I'm facing some strange issue when exporting it using AVAssetExportSession.The code is pretty straightforward.import UIKit import AVFoundation import PlaygroundSupport let asset: AVURLAsset = AVURLAsset(url: Bundle.main.url(forResource: "tmp", withExtension: "aac")!) print(asset) let timeRange = CMTimeRange( start: CMTime(seconds: 20.0, preferredTimescale: asset.duration.timescale), end: CMTime(seconds: 25.0, preferredTimescale: asset.duration.timescale) ) let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough)! exportSession.outputFileType = .m4a let fm = FileManager.default let tmpDirURL = FileManager.default.temporaryDirectory.appendingPathComponent("cut.m4a") try? fm.removeItem(at: tmpDirURL) exportSession.outputURL = tmpDirURL print(tmpDirURL) exportSession.timeRange = timeRange exportSession.exportAsynchronously { switch exportSession.status { case .completed: print("completed") default: print("exportSession: \(exportSession.error?.localizedDescription ?? "error")") } }When I started analyzing results in the Audacity, I see that file is trimmed with some error which is very critical.If I align it by peaks (on the eye) I see ~500 ms error in this particular case. Error varies and repeats for different files I've tried.I've tried it with AVMutableComposition. Same result.Maybe I'm doing something wrong? Or am I missing something? I want files to be cut exactly by the time I set timeRange property of AVAssetExportSession.
1
0
1.5k
Oct ’21
Why is my AVAssetWriterInput failing to append CMSampleBuffers?
The beginRecording() func and the endRecording() func matter the most. InterpretRawFrameData is just decoding the video stream the entire time and i want to record parts of the stream. In the decodeFrameData func i attempt and fail to append a CMSampleBuffer to my AVAssetWriterInput objectimport Foundation import ************ import AVFoundation import Photos typealias FrameData = Array protocol VideoFrameDecoderDelegate { func receivedDisplayableFrame(_ frame: CVPixelBuffer) } class VideoFrameDecoder { static var delegate: VideoFrameDecoderDelegate? private var formatDesc: CMVideoFormatDescription? private var decompressionSession: VTDecompressionSession? var isRecording: Bool = false { didSet { isRecording ? beginRecording() : endRecording() } } var outputURL: URL? var path = "" var videoWriter: AVAssetWriter? var videoWriterInput: AVAssetWriterInput? func interpretRawFrameData(_ frameData: inout FrameData) { var naluType = frameData[4] & 0x1F if naluType != 7 && formatDesc == nil { return } // Replace start code with the size var frameSize = CFSwapInt32HostToBig(UInt32(frameData.count - 4)) memcpy(&frameData, &frameSize, 4) // The start indices for nested packets. Default to 0. var ppsStartIndex = 0 var frameStartIndex = 0 var sps: Array? var pps: Array? // SPS parameters if naluType == 7 { for i in 4..<40 { if frameData[i] == 0 && frameData[i+1] == 0 && frameData[i+2] == 0 && frameData[i+3] == 1 { ppsStartIndex = i // Includes the start header sps = Array(frameData[4..<i]) // Set naluType to the nested packet's NALU type naluType = frameData[i + 4] & 0x1F break } } } // PPS parameters if naluType == 8 { for i in ppsStartIndex+4..<ppsstartindex+34 {<br=""> if frameData[i] == 0 && frameData[i+1] == 0 && frameData[i+2] == 0 && frameData[i+3] == 1 { frameStartIndex = i pps = Array(frameData[ppsStartIndex+4..<i]) // Set naluType to the nested packet's NALU type naluType = frameData[i+4] & 0x1F break } } guard let sps = sps, let pps = pps, createFormatDescription(sps: sps, pps: pps) else { print("===== ===== Failed to create formatDesc") return } guard createDecompressionSession() else { print("===== ===== Failed to create decompressionSession") return } } if (naluType == 1 || naluType == 5) && decompressionSession != nil { // If this is successful, the callback will be called // The callback will send the full decoded and decompressed frame to the delegate decodeFrameData(Array(frameData[frameStartIndex...frameData.count - 1])) } } private func decodeFrameData(_ frameData: FrameData) { let bufferPointer = UnsafeMutableRawPointer(mutating: frameData) // Replace the start code with the size of the NALU var frameSize = CFSwapInt32HostToBig(UInt32(frameData.count - 4)) memcpy(bufferPointer, &frameSize, 4) // Create a memory location to store the processed image var outputBuffer: CVPixelBuffer? var blockBuffer: CMBlockBuffer? var status = CMBlockBufferCreateWithMemoryBlock( allocator: kCFAllocatorDefault, memoryBlock: bufferPointer, blockLength: frameData.count, blockAllocator: kCFAllocatorNull, customBlockSource: nil, offsetToData: 0, dataLength: frameData.count, flags: 0, blockBufferOut: &blockBuffer) // Return if there was an error allocating processed image location guard status == kCMBlockBufferNoErr else { return } // Do some image processing var sampleBuffer: CMSampleBuffer? let sampleSizeArray = [frameData.count] status = CMSampleBufferCreateReady( allocator: kCFAllocatorDefault, dataBuffer: blockBuffer, formatDescription: formatDesc, sampleCount: 1, sampleTimingEntryCount: 0, sampleTimingArray: nil, sampleSizeEntryCount: 1, sampleSizeArray: sampleSizeArray, sampleBufferOut: &sampleBuffer) // Return if there was an error if let buffer = sampleBuffer, status == kCMBlockBufferNoErr { let attachments: CFArray? = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: true) if let attachmentsArray = attachments { let dic = unsafeBitCast(CFArrayGetValueAtIndex(attachmentsArray, 0), to: CFMutableDictionary.self) CFDictionarySetValue( dic, Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(), Unmanaged.passUnretained(kCFBooleanTrue).toOpaque()) // Decompress with ************ var flagOut = VTDecodeInfoFlags(rawValue: 0) status = VTDecompressionSessionDecodeFrame( decompressionSession!, sampleBuffer: buffer, flags: [], frameRefcon: &outputBuffer, infoFlagsOut: &flagOut) // Record CMSampleBuffer with AVFoundation if isRecording, let vidInput = videoWriterInput, vidInput.isReadyForMoreMediaData { print("Appended: \(vidInput.append(buffer))") } } } } private func createFormatDescription(sps: [UInt8], pps: [UInt8]) -> Bool { let pointerSPS = UnsafePointer(sps) let pointerPPS = UnsafePointer(pps) let dataParamArray = [pointerSPS, pointerPPS] let parameterSetPointers = UnsafePointer(dataParamArray) let sizeParamArray = [sps.count, pps.count] let parameterSetSizes = UnsafePointer(sizeParamArray) let status = CMVideoFormatDescriptionCreateFromH264ParameterSets( allocator: kCFAllocatorDefault, parameterSetCount: 2, parameterSetPointers: parameterSetPointers, parameterSetSizes: parameterSetSizes, nalUnitHeaderLength: 4, formatDescriptionOut: &formatDesc) return status == noErr } private func createDecompressionSession() -> Bool { guard let desc = formatDesc else { return false } if let session = decompressionSession { VTDecompressionSessionInvalidate(session) decompressionSession = nil } let decoderParameters = NSMutableDictionary() let destinationPixelBufferAttributes = NSMutableDictionary() var outputCallback = VTDecompressionOutputCallbackRecord() outputCallback.decompressionOutputCallback = callback outputCallback.decompressionOutputRefCon = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) let status = VTDecompressionSessionCreate( allocator: kCFAllocatorDefault, formatDescription: desc, decoderSpecification: decoderParameters, imageBufferAttributes: destinationPixelBufferAttributes, outputCallback: &outputCallback, decompressionSessionOut: &decompressionSession) return status == noErr } private var callback: VTDecompressionOutputCallback = {( decompressionOutputRefCon: UnsafeMutableRawPointer?, sourceFrameRefCon: UnsafeMutableRawPointer?, status: OSStatus, infoFlags: VTDecodeInfoFlags, imageBuffer: CVPixelBuffer?, presentationTimeStamp: CMTime, duration: CMTime) in guard let newImage = imageBuffer, status == noErr else { // -12909 is Bad Video Error, nothing too bad unless there's no feed if status != -12909 { print("===== Failed to decompress. VT Error \(status)") } return } // print("===== Image successfully decompressed") delegate?.receivedDisplayableFrame(imageBuffer!) } private func handlePhotoLibraryAuth() { if PHPhotoLibrary.authorizationStatus() != .authorized { PHPhotoLibrary.requestAuthorization { _ in } } } private func createFilePath() { let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) guard let documentDirectory: NSURL = urls.first as NSURL? else { fatalError("documentDir Error") } guard let videoOutputURL = documentDirectory.appendingPathComponent("iTello-\(Date()).mp4") else { return } outputURL = videoOutputURL path = videoOutputURL.path if FileManager.default.fileExists(atPath: path) { do { try FileManager.default.removeItem(atPath: path) } catch { print("Unable to delete file: \(error) : \(#function).") return } } } private func beginRecording() { handlePhotoLibraryAuth() createFilePath() guard let videoOutputURL = outputURL, let vidWriter = try? AVAssetWriter(outputURL: videoOutputURL, fileType: AVFileType.mp4) else { fatalError("AVAssetWriter error") } if formatDesc == nil { print("Warning: No Format For Video") } let vidInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: nil, sourceFormatHint: formatDesc) guard vidWriter.canAdd(vidInput) else { print("Error: Cant add video writer input") return } vidInput.expectsMediaDataInRealTime = true vidWriter.add(vidInput) guard vidWriter.startWriting() else { print("Error: Cant write with vid writer") return } vidWriter.startSession(atSourceTime: CMTime.zero) self.videoWriter = vidWriter self.videoWriterInput = vidInput print("Recording Video Stream") } private func saveRecordingToPhotoLibrary() { let fileManager = FileManager.default guard fileManager.fileExists(atPath: self.path) else { print("Error: The file: \(self.path) not exists, so cannot move this file camera roll") return } print("The file: \(self.path) has been save into documents folder, and is ready to be moved to camera roll") PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: self.path)) }) { completed, error in guard completed else { print ("Error: Cannot move the video \(self.path) to camera roll, error: \(String(describing: error?.localizedDescription))") return } print("Video \(self.path) has been moved to camera roll") } } private func endRecording() { guard let vidInput = videoWriterInput, let vidWriter = videoWriter else { print("Error, no video writer or video input") return } vidInput.markAsFinished() if !vidInput.isReadyForMoreMediaData { vidWriter.finishWriting { print("Finished Recording") guard vidWriter.status == .completed else { print("Warning: The Video Writer status is not completed, status: \(vidWriter.status.rawValue)") print(vidWriter.error.debugDescription) return } print("VideoWriter status is completed") self.saveRecordingToPhotoLibrary() self.videoWriterInput = nil self.videoWriter = nil } } } }I'm getting AVFoundation error -11800 and the writer is failing for some unknown reason. I'm streaming an h264/mp4 video from some non-apple product. The video is decoding and displaying properly but not recording. The append operation fails and fails and I can't determine why from the error.
5
0
2.7k
Dec ’21
Crash When Exporting Video with Text Overlay
I am putting together a simple video editor app for iOS. The videos are exported with a "watermark" in the form of a text overlay (e.g. "This video was made with XYZ").The app (still a prototype) was working until around February this year. Then I got busy, moved to other projects and stopped working on it for a while.About a months ago, I resumed work on the app but suddenly noticed that it was crashing whenever I attempted to export any video.The crash looks like this:libxpc.dylib`_xpc_api_misuse: 0x7fff51c53154 <+0>: pushq %rbp 0x7fff51c53155 <+1>: movq %rsp, %rbp 0x7fff51c53158 <+4>: pushq %rbx 0x7fff51c53159 <+5>: subq $0xa8, %rsp 0x7fff51c53160 <+12>: movq %rdi, %r9 0x7fff51c53163 <+15>: movaps 0xdba6(%rip), %xmm0 ; __xpcVersionNumber + 160 0x7fff51c5316a <+22>: leaq -0xb0(%rbp), %rbx 0x7fff51c53171 <+29>: movaps %xmm0, 0x90(%rbx) 0x7fff51c53178 <+36>: movaps %xmm0, 0x80(%rbx) 0x7fff51c5317f <+43>: movaps %xmm0, 0x70(%rbx) 0x7fff51c53183 <+47>: movaps %xmm0, 0x60(%rbx) 0x7fff51c53187 <+51>: movaps %xmm0, 0x50(%rbx) 0x7fff51c5318b <+55>: movaps %xmm0, 0x40(%rbx) 0x7fff51c5318f <+59>: movaps %xmm0, 0x30(%rbx) 0x7fff51c53193 <+63>: movaps %xmm0, 0x20(%rbx) 0x7fff51c53197 <+67>: movaps %xmm0, 0x10(%rbx) 0x7fff51c5319b <+71>: movaps %xmm0, (%rbx) 0x7fff51c5319e <+74>: leaq 0x1150d(%rip), %r8 ; "XPC API Misuse: %s" 0x7fff51c531a5 <+81>: movl $0xa0, %esi 0x7fff51c531aa <+86>: movl $0xa0, %ecx 0x7fff51c531af <+91>: movq %rbx, %rdi 0x7fff51c531b2 <+94>: movl $0x0, %edx 0x7fff51c531b7 <+99>: xorl %eax, %eax 0x7fff51c531b9 <+101>: callq 0x7fff51c5fe18 ; symbol stub for: __snprintf_chk 0x7fff51c531be <+106>: movq %rbx, 0x380787c3(%rip) ; gCRAnnotations + 8 0x7fff51c531c5 <+113>: leaq 0x114f9(%rip), %rax ; "API Misuse" 0x7fff51c531cc <+120>: movq %rax, 0x380787bd(%rip) ; gCRAnnotations + 16 -> 0x7fff51c531d3 <+127>: ud2 < Thread 55: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)After experimenting a bit by eliminating features, I found out that the app crashes only if the exported video compositions contain the text overlay: if I comment out the code responsible for overlaying the text layer, the issue resolves.This is the code I am using to export the video composition:func export(completion: @escaping (() -> Void), failure: @escaping ((Error) -> Void)) { let exportQuality = AVAssetExportPresetHighestQuality guard let exporter = AVAssetExportSession(asset: composition, presetName: exportQuality) else { return failure(ProjectError.failedToCreateExportSession) } guard let documents = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else { return failure(ProjectError.temporaryOutputDirectoryNotFound) } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd_HHmmss" let fileName = dateFormatter.string(from: Date()) let fileExtension = "mov" let fileURL = documents.appendingPathComponent(fileName).appendingPathExtension(fileExtension) exporter.outputURL = fileURL exporter.outputFileType = AVFileType.mov exporter.shouldOptimizeForNetworkUse = true if shouldAddWatermark { // Watermark overlay: let frame = CGRect(origin: .zero, size: videoComposition.renderSize) let watermark = WatermarkLayer(frame: frame) let parentLayer = CALayer() let videoLayer = CALayer() parentLayer.frame = frame videoLayer.frame = frame parentLayer.addSublayer(videoLayer) parentLayer.addSublayer(watermark) videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer) } exporter.videoComposition = videoComposition exporter.exportAsynchronously { if exporter.status == .completed { /* Composition was successfully saved to the documents folder. Now create a new asset in the device's camera roll (i.e. photo library): */ AssetLibrary.saveVideo(at: fileURL, completion: { completion() }, failure: {(error) in failure(ProjectError.failedToExportToPhotoLibrary(detail: error?.localizedDescription ?? "Unknown")) }) } else { DispatchQueue.main.async { failure(ProjectError.failedToExportComposition(detail: exporter.error?.localizedDescription ?? "Unknown")) } } } }The WatermarkLayer class used above is defined as follows:class WatermarkLayer: CATextLayer { // MARK: - Constants private let defaultFontSize: CGFloat = 48 private let rightMargin: CGFloat = 10 private let bottomMargin: CGFloat = 10 // MARK: - Initialization init(frame: CGRect) { super.init() guard let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String else { fatalError("!!!") } self.foregroundColor = CGColor.srgb(r: 255, g: 255, b: 255, a: 0.5) self.backgroundColor = CGColor.clear self.string = String(format: String.watermarkFormat, appName) self.font = CTFontCreateWithName(String.watermarkFontName as CFString, defaultFontSize, nil) self.fontSize = defaultFontSize self.shadowOpacity = 0.75 self.alignmentMode = .right self.frame = frame } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented. Use init(frame:) instead.") } // MARK: - CALayer override func draw(in ctx: CGContext) { let height = self.bounds.size.height let fontSize = self.fontSize //let yDiff = (height-fontSize)/2 - fontSize/10 // Center let yDiff = (height-fontSize) - fontSize/10 - bottomMargin // Bottom (minus margin) ctx.saveGState() ctx.translateBy(x: -rightMargin, y: yDiff) super.draw(in: ctx) ctx.restoreGState() } }What's going on? Which API is being "misused"?
12
3
5.8k
Jun ’23
AVAudioSession activation failed after emergency alert
Hi,I'm developing a VoIP application using CallKit.The AVAudioSession activated by my application has been muted after emergency alert.This issue happens on Google Duo / Facebook Messenger / Zoom also.This issue is 100% reproducible running on iOS 13.3 ~ 13.5.1.2 kinds of audio interruption "AVAudioSessionInterruptionTypeBegan" and "AVAudioSessionInterruptionTypeEnded" events placed at exact time.And my application tries to activate audio session after "AVAudioSessionInterruptionTypeEnded" event, but it fails every time.**** Error Logs ****Error Domain=NSOSStatusErrorDomain Code=1701737535 "(null)" --> AVAudioSessionErrorCodeMissingEntitlementPlease let me know if you can give me some tip or hint to overcome this issue.Best Regards.
2
0
3.1k
Dec ’22
AudioOutputUnitStart returns 1852797029
We are using AudioUnit and AUGraph to provide recording feature for millions of users. For a long time, we have been receiving user feedbacks about recording failures. Most of user logs show that AudioOutputUnitStart returns 1852797029 (kAudioCodecIllegalOperationError).It seems that once this error happens, AudioOutputUnitStart will always return this error code unit rebooting device or sometimes rebooting won't do the trick. Does anyone experience this error code or know the possible cause of it
4
1
6.5k
Feb ’22
Random 561015905 on AVAudioSession setActive
I'm trying to make an app that plays audio when push is received, even while the ringer is silent.I have the audio background mode enabled and the app works (usually) fine, but sometimes i get a mysterious 561015905 error.The error isAVAudioSession.ErrorCode.cannotStartPlayingAnd docs indicate:This error type can occur if the app’s Information property list doesn’t permit audio use. It can also occur if the app is in the background and using a category that doesn’t allow background audio.https://developer.apple.com/documentation/avfoundation/avaudiosession/errorcode/cannotstartplayingHowever, the audio mode is definitely enabled and the category is always playback that should allow background playing.(this works 95-99% of times)So, with intesnse testing i have found that once every 20-100 incoming pushes i get this error:Error: Error Domain=NSOSStatusErrorDomain Code=561015905 "(null)"Why?
4
2
3k
Jul ’23
Microphone crashing when change input source
I am using the microphone, and found a lot of issues that crashes the app when the input source did change. The error was always something like: ** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate. Now I have fixed this issue, forcing the input-source to be always the builtin microphone and using AVAudioFoundation entities at different moments. But I am still not confident about this solution. For example, I still having some inconsistencies while transmitting the device screen on macOS through QuickTime. So my question around this: How to prevent app-crashes with this kind of error? I saw a lot of similar errors just changing the property of the format. How can I avoid these kinds of errors? There is a Swift-way to handle the error instead of using an exception catcher from Objective-c?
3
0
2.7k
Jun ’23
Testing installTap(onBus:bufferSize:format:block:)
To write an automated test to validate if the installTap(onBus bus:bufferSize:format:block:) function is calling our logics, I created an abstraction. This abstraction, instead of always installing a tap at inputNode from an AVAudioEngine instance. I inject an input node (AVAudioNode) where the install tap will be executed. At production code, I inject the microphone node, but on tests, I inject an AVAudioPlayerNode instance that produce some AVAudioBuffers. But, the test is pretty flaky, and sometimes fails because we got an exception with -10851 error code, which means kAudioUnitErr_InvalidPropertyValue. How can I write automated tests to installTap?
1
0
1.1k
Dec ’21
How to cache an HLS video while playing it
Hi, I'm working on an app where a user can scroll through a feed of short videos (a bit like TikTok). I do some pre-fetching of videos a couple positions ahead of the user's scroll position, so the video can start playing as soon as he or she scrolls to the video. Currently, I just pre-fetch by initializing a few AVPlayers. However, I'd like to add a better caching system. I'm looking for the best way to: get videos to start playing as possible, while making sure to minimize re-downloading of videos if a user scrolls away from a video and back to it. Is there a way that I can cache the contents of an AVPlayer that has loaded an HLS video? Alternatively, I've explored using AVAssetDownloadTask to download the HLS videos. My issue is that I can't download the full video and then play it - I need to start playing the video as soon as the user scrolls to it, even if it's not done downloading. Is there a way to start an HLS download with an AVAssetDownloadTask, and then start playing the video while it continues downloading? Thank you!
10
0
10k
Oct ’23
the first index of Partial segment when package LL-HLS contents
Hi, The first index of Partial segment is 0 according to Protocol Extension for Low-Latency HLS (Preliminary Specification) and draft-pantos-hls-rfc8216bis-07. My Apple LL-HLS packager use this rule. But it seems apple LL-HLS origin sample use 1 for first index. This is the error log when I use AVPlayer in IOS 14 beta to playback our content. This error always are reproduced when AVPlayer query progindex.m3u8 with HLSpart=6. The last index is 5 if first index is 0. Is this a already issue in AVPlayer? 2020-07-13 09:56:11.872200+0800 HLSCatalog[411:14251] Perf – Playback started in 0.33 seconds 2020-07-13 09:56:14.182182+0800 HLSCatalog[411:14081] [] [09:56:14.182] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.182489+0800 HLSCatalog[411:14081] [] [09:56:14.182] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.183973+0800 HLSCatalog[411:14081] [] [09:56:14.184] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.184215+0800 HLSCatalog[411:14081] [] [09:56:14.184] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.192352+0800 HLSCatalog[411:14081] [] [09:56:14.192] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.192484+0800 HLSCatalog[411:14081] [] [09:56:14.192] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.192656+0800 HLSCatalog[411:14081] [] [09:56:14.193] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.193736+0800 HLSCatalog[411:14081] [] [09:56:14.194] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.194567+0800 HLSCatalog[411:14081] [] [09:56:14.195] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 Error 1: Optional("Cannot Complete Action") 2020-07-13 09:56:14.203863+0800 HLSCatalog[411:14250] [] [09:56:14.204] remoteXPCPlayerGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:580 2020-07-13 09:56:14.206323+0800 HLSCatalog[411:14250] [] [09:56:14.206] remoteXPCPlayerGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:580
0
0
871
Nov ’22
Writing MP4 metadata with AVFoundation
I have been banging my head against the wall for days trying to find any solution that will allow me to write arbitrary metadata into an MP4 using AVFoundation. Both AVAssetWriter and AVAssetExportSession have metadata API that look for all to see like they should do the trick of writing metadata, but having tried and tried again to add metadata via these APIs, the metadata is never written. Are they any examples of actually successfully writing metadata to an MP4 with AVFoundation? Here's an example that seems like it should work, but doesn't:         let myMetadata = AVMutableMetadataItem()         myMetadata.identifier = AVMetadataIdentifier(rawValue: "udta/GPMF")         myMetadata.value = "Yo, dawg, I'm metadata" as NSString         myMetadata.dataType = kCMMetadataBaseDataType_RawData as String         exporter?.metadata = [myMetadata] // export.exportAsynchronously()... And this doesn't work either: let foo = AVMutableMetadataItem() foo.value = gpmf.dataValue! as NSData // this is copying data directly from AVMetadataItem taken from an AVAsset I have which already has metadata assetWriter.metadata = [foo] assetWriter.startWriting() // assetWriter.finishWriting
2
3
2.3k
Feb ’22
AVPlayer doesn't work in app
Hello: I am adding a video file to my MAC application. Before I create an archive, the video plays perfectly but when I run a copy of the archive, when I click on the button to start the video, NOTHING HAPPENS. No error message, Nothing. Any help to resolve this issue will be appreciated. Here is the code: This code: @IBAction func AVSegue(_ sender: Any) { let mainStoryboard = NSStoryboard(name: "Main", bundle: Bundle.main) guard let avPlayerViewController = mainStoryboard.instantiateController (withIdentifier: "AVID") as? AVPlayerViewController else { print("Couldn't find viewController" )         return         } presentAsModalWindow(avPlayerViewController)   } triggers the ViewController with the AV Player: import Cocoa import AVKit import AVFoundation class AVPlayerViewController: NSViewController {     @IBOutlet weak var playerView: AVPlayerView!         override func viewDidLoad() { super.viewDidLoad()             let url = URL(fileURLWithPath: Bundle.main.path(forResource:"SMRIntro",ofType: "mp4")!)             let player = AVPlayer(url: url)             playerView.player = player             player.play()           } }
4
0
4.3k
Aug ’22
Picture in Picture does not start by default when you minimise your app in case of AVPlayerLayer
Adopting Picture in Picture in a Custom Player https://developer.apple.com/documentation/avkit/adopting_picture_in_picture_in_a_custom_player I have implemented PIP by following this link when I tap Pip button it works fine but when I am playing any video If I minimise app Picture in Picture does not start .In my case I have used AVPlayerLayer and I have set AVAudiosession category as playback .I am on iOS 14 beta 4
1
0
1.4k
Mar ’23
Audio Delay
Hi, I am facing a really strange issue.I have a wordpress website in which I have used html 5 audio tag .Whenever I play audio it delays it takes 2-3 sec to start on Safari. On other browsers it is working fine.I have done lot's of research and tried many things JS scripts but nothing worked.Can you please check and let me know any solution for this. page link : dev.one-button.de/create-your-song-with-name/ Thanks
2
0
845
Apr ’22
AVPlayer freezes when seeking between 2 videos
Hi everyone! Me and my team have an issue that we can't fix for few weeks now. When we seek forward between two videos in AVComposition - the preview freezes. It gets stuck on last frame of first video. It doesn’t freeze if it’s a simple playback (not a seek) or if seek is quick. Here is screen recording of what's happening: https://www.icloud.com/iclouddrive/0651H_IA679ENDk9fLANNvwXA#AVCompositionFreezeScreenRecording It feels like we tried everything, and nothing helps. When adding second video, we ask AVMutableComposition for a compatible track, and it returns us existing track, thus we conclude that both assetTrack's are compatible. All the ranges and duration checked many times. It fails both when videoComposition is set on playerItem and when not. My current theory is even tho composition says that existing compositionTrack is compatible for second video, we can’t just put second video in it for some reason, maybe the transform is incompatible or I don’t know.  One more note - if we take range of source videoAssetTrack with duration that is shorter than videoAssetTrack.timeRange.duration - then everything works. Maybe some issue with segment time mapping, but anything that we tried with it failed. I tried to minimize the amount of code needed to demonstrate the issue, so hopefully it will be easy to see what I’m talking about. Just seek slowly from end of video1 to start of video2 and it will get stuck. https://www.icloud.com/iclouddrive/0tDFgcQHKsIS7obiCA9yMHAEA#AVCompositionFreezeDemo Thanks very much in advance, any help would be much appreciated!
14
1
5.6k
Nov ’22
Cinematic Extended/Cinematic stabilization AV Sync with AVAssetWriter
When using AVCaptureVideoDataOutput/AVCaptureAudioDataOutput & AVAsset writer to record video with cinematic extended video stabilization, the audio lags video upto 1-1.5 seconds and as a result in the video recording, video playback is frozen in the last 1-1.5 seconds. This does not happen when using AVCaptureMovieFileOutput. I want to know if this can be fixed or there is a workaround to synchronize audio/video frames? How does AVCaptureMovieFileOutput handle it?
1
0
1.4k
Aug ’21
AVAudioEngine stops running when changing input to AirPods
I have trouble understanding AVAudioEngine's behaviour when switching audio input sources. Expected Behaviour When switching input sources, AVAudioEngine's inputNode should adopt the new input source seamlessly. Actual Behaviour When switching from AirPods to the iPhone speaker, AVAudioEngine stops working. No audio is routed through anymore. Querying engine.isRunning still returns true. When subsequently switching back to AirPods, it still isn't working, but now engine.isRunning returns false. Stopping and starting the engine on a route change does not help. Neither does calling reset(). Disconnecting and reconnecting the input node does not help, either. The only thing that reliably helps is discarding the whole engine and creating a new one. OS This is on iOS 14, beta 5. I can't test this on previous versions I'm afraid; I only have one device around. Code to Reproduce Here is a minimum code example. Create a simple app project in Xcode (doesn't matter whether you choose SwiftUI or Storyboard), and give it permissions to access the microphone in Info.plist. Create the following file Conductor.swift: import AVFoundation class Conductor { 		static let shared: Conductor = Conductor() 		 		private let _engine = AVAudioEngine? 		 		init() { 				// Session 				let session = AVAudioSession.sharedInstance() 				try? session.setActive(false) 				try! session.setCategory(.playAndRecord, options: [.defaultToSpeaker, 																													 .allowBluetooth, 																													 .allowAirPlay]) 				try! session.setActive(true) 				_engine.connect(_engine.inputNode, to: _engine.mainMixerNode, format: nil) 				_engine.prepare() 		} 		func start() { _engine.start() } } And in AppDelegate, call: Conductor.shared.start() This example will route the input straight to the output. If you don't have headphones, it will trigger a feedback loop. Question What am I missing here? Is this expected behaviour? If so, it does not seem to be documented anywhere.
2
1
2.6k
Feb ’22
AirPods Problem on Big Sur
While I have developer's beta iOS 14 on both my iPhone and Mac a recurrent problem has being happening to me where when I connect my AirPods to my computer it only recognizes one and uses one for audio. Whereas on my phone both work fine. So the problem is not the AirPods. Hope that on the next beta update it is resolve.
63
0
21k
Mar ’22
Unable to decode mp4 video using AVFoundation on iPhone 11 Pro
Basic Information Please provide a descriptive title for your feedback: Unable to decode mp4 video using AVFoundation on iPhone 11 Pro Which area are you seeing an issue with? AVFoundation What type of feedback are you reporting? Incorrect/Unexpected Behavior Description Please describe the issue and what steps we can take to reproduce it: Receiving decoderNotFound -11833 when trying to decode a 1 second mp4 video using iPhone 11 Pro currently on iOS14 beta 5. On other devices it works without a problem. It happens specifically on iPhone 11 Pro and iPhone XR. Have 1 second mp4 video use copyNextSampleBuffer check the status of assetReader; it will be .failed Expected to see images on screen The image is not displayed. Everything is grey More details Error Domain=AVFoundationErrorDomain Code=-11833 "Cannot Decode" UserInfo={NSUnderlyingError=0x280c94510 {Error Domain=NSOSStatusErrorDomain Code=-12906 "(null)"}, NSLocalizedFailureReason=The decoder required for this media was not found., AVErrorMediaTypeKey=vide, NSLocalizedDescription=Cannot Decode}
8
0
3.3k
Mar ’22
AVAssetExportSession trims audio with some error
Hi there!My goal is to trim audio quite precisely. I'm facing some strange issue when exporting it using AVAssetExportSession.The code is pretty straightforward.import UIKit import AVFoundation import PlaygroundSupport let asset: AVURLAsset = AVURLAsset(url: Bundle.main.url(forResource: "tmp", withExtension: "aac")!) print(asset) let timeRange = CMTimeRange( start: CMTime(seconds: 20.0, preferredTimescale: asset.duration.timescale), end: CMTime(seconds: 25.0, preferredTimescale: asset.duration.timescale) ) let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough)! exportSession.outputFileType = .m4a let fm = FileManager.default let tmpDirURL = FileManager.default.temporaryDirectory.appendingPathComponent("cut.m4a") try? fm.removeItem(at: tmpDirURL) exportSession.outputURL = tmpDirURL print(tmpDirURL) exportSession.timeRange = timeRange exportSession.exportAsynchronously { switch exportSession.status { case .completed: print("completed") default: print("exportSession: \(exportSession.error?.localizedDescription ?? "error")") } }When I started analyzing results in the Audacity, I see that file is trimmed with some error which is very critical.If I align it by peaks (on the eye) I see ~500 ms error in this particular case. Error varies and repeats for different files I've tried.I've tried it with AVMutableComposition. Same result.Maybe I'm doing something wrong? Or am I missing something? I want files to be cut exactly by the time I set timeRange property of AVAssetExportSession.
Replies
1
Boosts
0
Views
1.5k
Activity
Oct ’21
Why is my AVAssetWriterInput failing to append CMSampleBuffers?
The beginRecording() func and the endRecording() func matter the most. InterpretRawFrameData is just decoding the video stream the entire time and i want to record parts of the stream. In the decodeFrameData func i attempt and fail to append a CMSampleBuffer to my AVAssetWriterInput objectimport Foundation import ************ import AVFoundation import Photos typealias FrameData = Array protocol VideoFrameDecoderDelegate { func receivedDisplayableFrame(_ frame: CVPixelBuffer) } class VideoFrameDecoder { static var delegate: VideoFrameDecoderDelegate? private var formatDesc: CMVideoFormatDescription? private var decompressionSession: VTDecompressionSession? var isRecording: Bool = false { didSet { isRecording ? beginRecording() : endRecording() } } var outputURL: URL? var path = "" var videoWriter: AVAssetWriter? var videoWriterInput: AVAssetWriterInput? func interpretRawFrameData(_ frameData: inout FrameData) { var naluType = frameData[4] & 0x1F if naluType != 7 && formatDesc == nil { return } // Replace start code with the size var frameSize = CFSwapInt32HostToBig(UInt32(frameData.count - 4)) memcpy(&frameData, &frameSize, 4) // The start indices for nested packets. Default to 0. var ppsStartIndex = 0 var frameStartIndex = 0 var sps: Array? var pps: Array? // SPS parameters if naluType == 7 { for i in 4..<40 { if frameData[i] == 0 && frameData[i+1] == 0 && frameData[i+2] == 0 && frameData[i+3] == 1 { ppsStartIndex = i // Includes the start header sps = Array(frameData[4..<i]) // Set naluType to the nested packet's NALU type naluType = frameData[i + 4] & 0x1F break } } } // PPS parameters if naluType == 8 { for i in ppsStartIndex+4..<ppsstartindex+34 {<br=""> if frameData[i] == 0 && frameData[i+1] == 0 && frameData[i+2] == 0 && frameData[i+3] == 1 { frameStartIndex = i pps = Array(frameData[ppsStartIndex+4..<i]) // Set naluType to the nested packet's NALU type naluType = frameData[i+4] & 0x1F break } } guard let sps = sps, let pps = pps, createFormatDescription(sps: sps, pps: pps) else { print("===== ===== Failed to create formatDesc") return } guard createDecompressionSession() else { print("===== ===== Failed to create decompressionSession") return } } if (naluType == 1 || naluType == 5) && decompressionSession != nil { // If this is successful, the callback will be called // The callback will send the full decoded and decompressed frame to the delegate decodeFrameData(Array(frameData[frameStartIndex...frameData.count - 1])) } } private func decodeFrameData(_ frameData: FrameData) { let bufferPointer = UnsafeMutableRawPointer(mutating: frameData) // Replace the start code with the size of the NALU var frameSize = CFSwapInt32HostToBig(UInt32(frameData.count - 4)) memcpy(bufferPointer, &frameSize, 4) // Create a memory location to store the processed image var outputBuffer: CVPixelBuffer? var blockBuffer: CMBlockBuffer? var status = CMBlockBufferCreateWithMemoryBlock( allocator: kCFAllocatorDefault, memoryBlock: bufferPointer, blockLength: frameData.count, blockAllocator: kCFAllocatorNull, customBlockSource: nil, offsetToData: 0, dataLength: frameData.count, flags: 0, blockBufferOut: &blockBuffer) // Return if there was an error allocating processed image location guard status == kCMBlockBufferNoErr else { return } // Do some image processing var sampleBuffer: CMSampleBuffer? let sampleSizeArray = [frameData.count] status = CMSampleBufferCreateReady( allocator: kCFAllocatorDefault, dataBuffer: blockBuffer, formatDescription: formatDesc, sampleCount: 1, sampleTimingEntryCount: 0, sampleTimingArray: nil, sampleSizeEntryCount: 1, sampleSizeArray: sampleSizeArray, sampleBufferOut: &sampleBuffer) // Return if there was an error if let buffer = sampleBuffer, status == kCMBlockBufferNoErr { let attachments: CFArray? = CMSampleBufferGetSampleAttachmentsArray(buffer, createIfNecessary: true) if let attachmentsArray = attachments { let dic = unsafeBitCast(CFArrayGetValueAtIndex(attachmentsArray, 0), to: CFMutableDictionary.self) CFDictionarySetValue( dic, Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(), Unmanaged.passUnretained(kCFBooleanTrue).toOpaque()) // Decompress with ************ var flagOut = VTDecodeInfoFlags(rawValue: 0) status = VTDecompressionSessionDecodeFrame( decompressionSession!, sampleBuffer: buffer, flags: [], frameRefcon: &outputBuffer, infoFlagsOut: &flagOut) // Record CMSampleBuffer with AVFoundation if isRecording, let vidInput = videoWriterInput, vidInput.isReadyForMoreMediaData { print("Appended: \(vidInput.append(buffer))") } } } } private func createFormatDescription(sps: [UInt8], pps: [UInt8]) -> Bool { let pointerSPS = UnsafePointer(sps) let pointerPPS = UnsafePointer(pps) let dataParamArray = [pointerSPS, pointerPPS] let parameterSetPointers = UnsafePointer(dataParamArray) let sizeParamArray = [sps.count, pps.count] let parameterSetSizes = UnsafePointer(sizeParamArray) let status = CMVideoFormatDescriptionCreateFromH264ParameterSets( allocator: kCFAllocatorDefault, parameterSetCount: 2, parameterSetPointers: parameterSetPointers, parameterSetSizes: parameterSetSizes, nalUnitHeaderLength: 4, formatDescriptionOut: &formatDesc) return status == noErr } private func createDecompressionSession() -> Bool { guard let desc = formatDesc else { return false } if let session = decompressionSession { VTDecompressionSessionInvalidate(session) decompressionSession = nil } let decoderParameters = NSMutableDictionary() let destinationPixelBufferAttributes = NSMutableDictionary() var outputCallback = VTDecompressionOutputCallbackRecord() outputCallback.decompressionOutputCallback = callback outputCallback.decompressionOutputRefCon = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) let status = VTDecompressionSessionCreate( allocator: kCFAllocatorDefault, formatDescription: desc, decoderSpecification: decoderParameters, imageBufferAttributes: destinationPixelBufferAttributes, outputCallback: &outputCallback, decompressionSessionOut: &decompressionSession) return status == noErr } private var callback: VTDecompressionOutputCallback = {( decompressionOutputRefCon: UnsafeMutableRawPointer?, sourceFrameRefCon: UnsafeMutableRawPointer?, status: OSStatus, infoFlags: VTDecodeInfoFlags, imageBuffer: CVPixelBuffer?, presentationTimeStamp: CMTime, duration: CMTime) in guard let newImage = imageBuffer, status == noErr else { // -12909 is Bad Video Error, nothing too bad unless there's no feed if status != -12909 { print("===== Failed to decompress. VT Error \(status)") } return } // print("===== Image successfully decompressed") delegate?.receivedDisplayableFrame(imageBuffer!) } private func handlePhotoLibraryAuth() { if PHPhotoLibrary.authorizationStatus() != .authorized { PHPhotoLibrary.requestAuthorization { _ in } } } private func createFilePath() { let fileManager = FileManager.default let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask) guard let documentDirectory: NSURL = urls.first as NSURL? else { fatalError("documentDir Error") } guard let videoOutputURL = documentDirectory.appendingPathComponent("iTello-\(Date()).mp4") else { return } outputURL = videoOutputURL path = videoOutputURL.path if FileManager.default.fileExists(atPath: path) { do { try FileManager.default.removeItem(atPath: path) } catch { print("Unable to delete file: \(error) : \(#function).") return } } } private func beginRecording() { handlePhotoLibraryAuth() createFilePath() guard let videoOutputURL = outputURL, let vidWriter = try? AVAssetWriter(outputURL: videoOutputURL, fileType: AVFileType.mp4) else { fatalError("AVAssetWriter error") } if formatDesc == nil { print("Warning: No Format For Video") } let vidInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: nil, sourceFormatHint: formatDesc) guard vidWriter.canAdd(vidInput) else { print("Error: Cant add video writer input") return } vidInput.expectsMediaDataInRealTime = true vidWriter.add(vidInput) guard vidWriter.startWriting() else { print("Error: Cant write with vid writer") return } vidWriter.startSession(atSourceTime: CMTime.zero) self.videoWriter = vidWriter self.videoWriterInput = vidInput print("Recording Video Stream") } private func saveRecordingToPhotoLibrary() { let fileManager = FileManager.default guard fileManager.fileExists(atPath: self.path) else { print("Error: The file: \(self.path) not exists, so cannot move this file camera roll") return } print("The file: \(self.path) has been save into documents folder, and is ready to be moved to camera roll") PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: self.path)) }) { completed, error in guard completed else { print ("Error: Cannot move the video \(self.path) to camera roll, error: \(String(describing: error?.localizedDescription))") return } print("Video \(self.path) has been moved to camera roll") } } private func endRecording() { guard let vidInput = videoWriterInput, let vidWriter = videoWriter else { print("Error, no video writer or video input") return } vidInput.markAsFinished() if !vidInput.isReadyForMoreMediaData { vidWriter.finishWriting { print("Finished Recording") guard vidWriter.status == .completed else { print("Warning: The Video Writer status is not completed, status: \(vidWriter.status.rawValue)") print(vidWriter.error.debugDescription) return } print("VideoWriter status is completed") self.saveRecordingToPhotoLibrary() self.videoWriterInput = nil self.videoWriter = nil } } } }I'm getting AVFoundation error -11800 and the writer is failing for some unknown reason. I'm streaming an h264/mp4 video from some non-apple product. The video is decoding and displaying properly but not recording. The append operation fails and fails and I can't determine why from the error.
Replies
5
Boosts
0
Views
2.7k
Activity
Dec ’21
Crash When Exporting Video with Text Overlay
I am putting together a simple video editor app for iOS. The videos are exported with a "watermark" in the form of a text overlay (e.g. "This video was made with XYZ").The app (still a prototype) was working until around February this year. Then I got busy, moved to other projects and stopped working on it for a while.About a months ago, I resumed work on the app but suddenly noticed that it was crashing whenever I attempted to export any video.The crash looks like this:libxpc.dylib`_xpc_api_misuse: 0x7fff51c53154 <+0>: pushq %rbp 0x7fff51c53155 <+1>: movq %rsp, %rbp 0x7fff51c53158 <+4>: pushq %rbx 0x7fff51c53159 <+5>: subq $0xa8, %rsp 0x7fff51c53160 <+12>: movq %rdi, %r9 0x7fff51c53163 <+15>: movaps 0xdba6(%rip), %xmm0 ; __xpcVersionNumber + 160 0x7fff51c5316a <+22>: leaq -0xb0(%rbp), %rbx 0x7fff51c53171 <+29>: movaps %xmm0, 0x90(%rbx) 0x7fff51c53178 <+36>: movaps %xmm0, 0x80(%rbx) 0x7fff51c5317f <+43>: movaps %xmm0, 0x70(%rbx) 0x7fff51c53183 <+47>: movaps %xmm0, 0x60(%rbx) 0x7fff51c53187 <+51>: movaps %xmm0, 0x50(%rbx) 0x7fff51c5318b <+55>: movaps %xmm0, 0x40(%rbx) 0x7fff51c5318f <+59>: movaps %xmm0, 0x30(%rbx) 0x7fff51c53193 <+63>: movaps %xmm0, 0x20(%rbx) 0x7fff51c53197 <+67>: movaps %xmm0, 0x10(%rbx) 0x7fff51c5319b <+71>: movaps %xmm0, (%rbx) 0x7fff51c5319e <+74>: leaq 0x1150d(%rip), %r8 ; "XPC API Misuse: %s" 0x7fff51c531a5 <+81>: movl $0xa0, %esi 0x7fff51c531aa <+86>: movl $0xa0, %ecx 0x7fff51c531af <+91>: movq %rbx, %rdi 0x7fff51c531b2 <+94>: movl $0x0, %edx 0x7fff51c531b7 <+99>: xorl %eax, %eax 0x7fff51c531b9 <+101>: callq 0x7fff51c5fe18 ; symbol stub for: __snprintf_chk 0x7fff51c531be <+106>: movq %rbx, 0x380787c3(%rip) ; gCRAnnotations + 8 0x7fff51c531c5 <+113>: leaq 0x114f9(%rip), %rax ; "API Misuse" 0x7fff51c531cc <+120>: movq %rax, 0x380787bd(%rip) ; gCRAnnotations + 16 -> 0x7fff51c531d3 <+127>: ud2 < Thread 55: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)After experimenting a bit by eliminating features, I found out that the app crashes only if the exported video compositions contain the text overlay: if I comment out the code responsible for overlaying the text layer, the issue resolves.This is the code I am using to export the video composition:func export(completion: @escaping (() -> Void), failure: @escaping ((Error) -> Void)) { let exportQuality = AVAssetExportPresetHighestQuality guard let exporter = AVAssetExportSession(asset: composition, presetName: exportQuality) else { return failure(ProjectError.failedToCreateExportSession) } guard let documents = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else { return failure(ProjectError.temporaryOutputDirectoryNotFound) } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd_HHmmss" let fileName = dateFormatter.string(from: Date()) let fileExtension = "mov" let fileURL = documents.appendingPathComponent(fileName).appendingPathExtension(fileExtension) exporter.outputURL = fileURL exporter.outputFileType = AVFileType.mov exporter.shouldOptimizeForNetworkUse = true if shouldAddWatermark { // Watermark overlay: let frame = CGRect(origin: .zero, size: videoComposition.renderSize) let watermark = WatermarkLayer(frame: frame) let parentLayer = CALayer() let videoLayer = CALayer() parentLayer.frame = frame videoLayer.frame = frame parentLayer.addSublayer(videoLayer) parentLayer.addSublayer(watermark) videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer) } exporter.videoComposition = videoComposition exporter.exportAsynchronously { if exporter.status == .completed { /* Composition was successfully saved to the documents folder. Now create a new asset in the device's camera roll (i.e. photo library): */ AssetLibrary.saveVideo(at: fileURL, completion: { completion() }, failure: {(error) in failure(ProjectError.failedToExportToPhotoLibrary(detail: error?.localizedDescription ?? "Unknown")) }) } else { DispatchQueue.main.async { failure(ProjectError.failedToExportComposition(detail: exporter.error?.localizedDescription ?? "Unknown")) } } } }The WatermarkLayer class used above is defined as follows:class WatermarkLayer: CATextLayer { // MARK: - Constants private let defaultFontSize: CGFloat = 48 private let rightMargin: CGFloat = 10 private let bottomMargin: CGFloat = 10 // MARK: - Initialization init(frame: CGRect) { super.init() guard let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String else { fatalError("!!!") } self.foregroundColor = CGColor.srgb(r: 255, g: 255, b: 255, a: 0.5) self.backgroundColor = CGColor.clear self.string = String(format: String.watermarkFormat, appName) self.font = CTFontCreateWithName(String.watermarkFontName as CFString, defaultFontSize, nil) self.fontSize = defaultFontSize self.shadowOpacity = 0.75 self.alignmentMode = .right self.frame = frame } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented. Use init(frame:) instead.") } // MARK: - CALayer override func draw(in ctx: CGContext) { let height = self.bounds.size.height let fontSize = self.fontSize //let yDiff = (height-fontSize)/2 - fontSize/10 // Center let yDiff = (height-fontSize) - fontSize/10 - bottomMargin // Bottom (minus margin) ctx.saveGState() ctx.translateBy(x: -rightMargin, y: yDiff) super.draw(in: ctx) ctx.restoreGState() } }What's going on? Which API is being "misused"?
Replies
12
Boosts
3
Views
5.8k
Activity
Jun ’23
AVAudioSession activation failed after emergency alert
Hi,I'm developing a VoIP application using CallKit.The AVAudioSession activated by my application has been muted after emergency alert.This issue happens on Google Duo / Facebook Messenger / Zoom also.This issue is 100% reproducible running on iOS 13.3 ~ 13.5.1.2 kinds of audio interruption "AVAudioSessionInterruptionTypeBegan" and "AVAudioSessionInterruptionTypeEnded" events placed at exact time.And my application tries to activate audio session after "AVAudioSessionInterruptionTypeEnded" event, but it fails every time.**** Error Logs ****Error Domain=NSOSStatusErrorDomain Code=1701737535 "(null)" --> AVAudioSessionErrorCodeMissingEntitlementPlease let me know if you can give me some tip or hint to overcome this issue.Best Regards.
Replies
2
Boosts
0
Views
3.1k
Activity
Dec ’22
AudioOutputUnitStart returns 1852797029
We are using AudioUnit and AUGraph to provide recording feature for millions of users. For a long time, we have been receiving user feedbacks about recording failures. Most of user logs show that AudioOutputUnitStart returns 1852797029 (kAudioCodecIllegalOperationError).It seems that once this error happens, AudioOutputUnitStart will always return this error code unit rebooting device or sometimes rebooting won't do the trick. Does anyone experience this error code or know the possible cause of it
Replies
4
Boosts
1
Views
6.5k
Activity
Feb ’22
Random 561015905 on AVAudioSession setActive
I'm trying to make an app that plays audio when push is received, even while the ringer is silent.I have the audio background mode enabled and the app works (usually) fine, but sometimes i get a mysterious 561015905 error.The error isAVAudioSession.ErrorCode.cannotStartPlayingAnd docs indicate:This error type can occur if the app’s Information property list doesn’t permit audio use. It can also occur if the app is in the background and using a category that doesn’t allow background audio.https://developer.apple.com/documentation/avfoundation/avaudiosession/errorcode/cannotstartplayingHowever, the audio mode is definitely enabled and the category is always playback that should allow background playing.(this works 95-99% of times)So, with intesnse testing i have found that once every 20-100 incoming pushes i get this error:Error: Error Domain=NSOSStatusErrorDomain Code=561015905 "(null)"Why?
Replies
4
Boosts
2
Views
3k
Activity
Jul ’23
Microphone crashing when change input source
I am using the microphone, and found a lot of issues that crashes the app when the input source did change. The error was always something like: ** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate. Now I have fixed this issue, forcing the input-source to be always the builtin microphone and using AVAudioFoundation entities at different moments. But I am still not confident about this solution. For example, I still having some inconsistencies while transmitting the device screen on macOS through QuickTime. So my question around this: How to prevent app-crashes with this kind of error? I saw a lot of similar errors just changing the property of the format. How can I avoid these kinds of errors? There is a Swift-way to handle the error instead of using an exception catcher from Objective-c?
Replies
3
Boosts
0
Views
2.7k
Activity
Jun ’23
Testing installTap(onBus:bufferSize:format:block:)
To write an automated test to validate if the installTap(onBus bus:bufferSize:format:block:) function is calling our logics, I created an abstraction. This abstraction, instead of always installing a tap at inputNode from an AVAudioEngine instance. I inject an input node (AVAudioNode) where the install tap will be executed. At production code, I inject the microphone node, but on tests, I inject an AVAudioPlayerNode instance that produce some AVAudioBuffers. But, the test is pretty flaky, and sometimes fails because we got an exception with -10851 error code, which means kAudioUnitErr_InvalidPropertyValue. How can I write automated tests to installTap?
Replies
1
Boosts
0
Views
1.1k
Activity
Dec ’21
How to cache an HLS video while playing it
Hi, I'm working on an app where a user can scroll through a feed of short videos (a bit like TikTok). I do some pre-fetching of videos a couple positions ahead of the user's scroll position, so the video can start playing as soon as he or she scrolls to the video. Currently, I just pre-fetch by initializing a few AVPlayers. However, I'd like to add a better caching system. I'm looking for the best way to: get videos to start playing as possible, while making sure to minimize re-downloading of videos if a user scrolls away from a video and back to it. Is there a way that I can cache the contents of an AVPlayer that has loaded an HLS video? Alternatively, I've explored using AVAssetDownloadTask to download the HLS videos. My issue is that I can't download the full video and then play it - I need to start playing the video as soon as the user scrolls to it, even if it's not done downloading. Is there a way to start an HLS download with an AVAssetDownloadTask, and then start playing the video while it continues downloading? Thank you!
Replies
10
Boosts
0
Views
10k
Activity
Oct ’23
How to make AVCapturePhotoOutput invokes the AVCapturePhotoCaptureDelegate callbacks on a common dispatch queue, not in the main queue
I use "capturePhotoWithSettings:delegate:" to capture still image. how to make sure the callback invokes in a common queue, not in main queue?
Replies
1
Boosts
0
Views
803
Activity
Nov ’21
the first index of Partial segment when package LL-HLS contents
Hi, The first index of Partial segment is 0 according to Protocol Extension for Low-Latency HLS (Preliminary Specification) and draft-pantos-hls-rfc8216bis-07. My Apple LL-HLS packager use this rule. But it seems apple LL-HLS origin sample use 1 for first index. This is the error log when I use AVPlayer in IOS 14 beta to playback our content. This error always are reproduced when AVPlayer query progindex.m3u8 with HLSpart=6. The last index is 5 if first index is 0. Is this a already issue in AVPlayer? 2020-07-13 09:56:11.872200+0800 HLSCatalog[411:14251] Perf – Playback started in 0.33 seconds 2020-07-13 09:56:14.182182+0800 HLSCatalog[411:14081] [] [09:56:14.182] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.182489+0800 HLSCatalog[411:14081] [] [09:56:14.182] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.183973+0800 HLSCatalog[411:14081] [] [09:56:14.184] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.184215+0800 HLSCatalog[411:14081] [] [09:56:14.184] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.192352+0800 HLSCatalog[411:14081] [] [09:56:14.192] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.192484+0800 HLSCatalog[411:14081] [] [09:56:14.192] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.192656+0800 HLSCatalog[411:14081] [] [09:56:14.193] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.193736+0800 HLSCatalog[411:14081] [] [09:56:14.194] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 2020-07-13 09:56:14.194567+0800 HLSCatalog[411:14081] [] [09:56:14.195] remoteXPCItemGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:475 Error 1: Optional("Cannot Complete Action") 2020-07-13 09:56:14.203863+0800 HLSCatalog[411:14250] [] [09:56:14.204] remoteXPCPlayerGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:580 2020-07-13 09:56:14.206323+0800 HLSCatalog[411:14250] [] [09:56:14.206] remoteXPCPlayerGetObjectID signalled err=-17221 (kFigPlayerErrorServerConnectionLost) (Server connection was lost) at /Library/Caches/com.apple.xbs/Sources/EmbeddedCoreMedia/EmbeddedCoreMedia-2737.4.1.1/Prototypes/Player/ClientServer/FigPlayerRemoteXPC.m:580
Replies
0
Boosts
0
Views
871
Activity
Nov ’22
Writing MP4 metadata with AVFoundation
I have been banging my head against the wall for days trying to find any solution that will allow me to write arbitrary metadata into an MP4 using AVFoundation. Both AVAssetWriter and AVAssetExportSession have metadata API that look for all to see like they should do the trick of writing metadata, but having tried and tried again to add metadata via these APIs, the metadata is never written. Are they any examples of actually successfully writing metadata to an MP4 with AVFoundation? Here's an example that seems like it should work, but doesn't:         let myMetadata = AVMutableMetadataItem()         myMetadata.identifier = AVMetadataIdentifier(rawValue: "udta/GPMF")         myMetadata.value = "Yo, dawg, I'm metadata" as NSString         myMetadata.dataType = kCMMetadataBaseDataType_RawData as String         exporter?.metadata = [myMetadata] // export.exportAsynchronously()... And this doesn't work either: let foo = AVMutableMetadataItem() foo.value = gpmf.dataValue! as NSData // this is copying data directly from AVMetadataItem taken from an AVAsset I have which already has metadata assetWriter.metadata = [foo] assetWriter.startWriting() // assetWriter.finishWriting
Replies
2
Boosts
3
Views
2.3k
Activity
Feb ’22
AVPlayer doesn't work in app
Hello: I am adding a video file to my MAC application. Before I create an archive, the video plays perfectly but when I run a copy of the archive, when I click on the button to start the video, NOTHING HAPPENS. No error message, Nothing. Any help to resolve this issue will be appreciated. Here is the code: This code: @IBAction func AVSegue(_ sender: Any) { let mainStoryboard = NSStoryboard(name: "Main", bundle: Bundle.main) guard let avPlayerViewController = mainStoryboard.instantiateController (withIdentifier: "AVID") as? AVPlayerViewController else { print("Couldn't find viewController" )         return         } presentAsModalWindow(avPlayerViewController)   } triggers the ViewController with the AV Player: import Cocoa import AVKit import AVFoundation class AVPlayerViewController: NSViewController {     @IBOutlet weak var playerView: AVPlayerView!         override func viewDidLoad() { super.viewDidLoad()             let url = URL(fileURLWithPath: Bundle.main.path(forResource:"SMRIntro",ofType: "mp4")!)             let player = AVPlayer(url: url)             playerView.player = player             player.play()           } }
Replies
4
Boosts
0
Views
4.3k
Activity
Aug ’22
Picture in Picture does not start by default when you minimise your app in case of AVPlayerLayer
Adopting Picture in Picture in a Custom Player https://developer.apple.com/documentation/avkit/adopting_picture_in_picture_in_a_custom_player I have implemented PIP by following this link when I tap Pip button it works fine but when I am playing any video If I minimise app Picture in Picture does not start .In my case I have used AVPlayerLayer and I have set AVAudiosession category as playback .I am on iOS 14 beta 4
Replies
1
Boosts
0
Views
1.4k
Activity
Mar ’23
Audio Delay
Hi, I am facing a really strange issue.I have a wordpress website in which I have used html 5 audio tag .Whenever I play audio it delays it takes 2-3 sec to start on Safari. On other browsers it is working fine.I have done lot's of research and tried many things JS scripts but nothing worked.Can you please check and let me know any solution for this. page link : dev.one-button.de/create-your-song-with-name/ Thanks
Replies
2
Boosts
0
Views
845
Activity
Apr ’22
AVPlayer freezes when seeking between 2 videos
Hi everyone! Me and my team have an issue that we can't fix for few weeks now. When we seek forward between two videos in AVComposition - the preview freezes. It gets stuck on last frame of first video. It doesn’t freeze if it’s a simple playback (not a seek) or if seek is quick. Here is screen recording of what's happening: https://www.icloud.com/iclouddrive/0651H_IA679ENDk9fLANNvwXA#AVCompositionFreezeScreenRecording It feels like we tried everything, and nothing helps. When adding second video, we ask AVMutableComposition for a compatible track, and it returns us existing track, thus we conclude that both assetTrack's are compatible. All the ranges and duration checked many times. It fails both when videoComposition is set on playerItem and when not. My current theory is even tho composition says that existing compositionTrack is compatible for second video, we can’t just put second video in it for some reason, maybe the transform is incompatible or I don’t know.  One more note - if we take range of source videoAssetTrack with duration that is shorter than videoAssetTrack.timeRange.duration - then everything works. Maybe some issue with segment time mapping, but anything that we tried with it failed. I tried to minimize the amount of code needed to demonstrate the issue, so hopefully it will be easy to see what I’m talking about. Just seek slowly from end of video1 to start of video2 and it will get stuck. https://www.icloud.com/iclouddrive/0tDFgcQHKsIS7obiCA9yMHAEA#AVCompositionFreezeDemo Thanks very much in advance, any help would be much appreciated!
Replies
14
Boosts
1
Views
5.6k
Activity
Nov ’22
Cinematic Extended/Cinematic stabilization AV Sync with AVAssetWriter
When using AVCaptureVideoDataOutput/AVCaptureAudioDataOutput & AVAsset writer to record video with cinematic extended video stabilization, the audio lags video upto 1-1.5 seconds and as a result in the video recording, video playback is frozen in the last 1-1.5 seconds. This does not happen when using AVCaptureMovieFileOutput. I want to know if this can be fixed or there is a workaround to synchronize audio/video frames? How does AVCaptureMovieFileOutput handle it?
Replies
1
Boosts
0
Views
1.4k
Activity
Aug ’21
AVAudioEngine stops running when changing input to AirPods
I have trouble understanding AVAudioEngine's behaviour when switching audio input sources. Expected Behaviour When switching input sources, AVAudioEngine's inputNode should adopt the new input source seamlessly. Actual Behaviour When switching from AirPods to the iPhone speaker, AVAudioEngine stops working. No audio is routed through anymore. Querying engine.isRunning still returns true. When subsequently switching back to AirPods, it still isn't working, but now engine.isRunning returns false. Stopping and starting the engine on a route change does not help. Neither does calling reset(). Disconnecting and reconnecting the input node does not help, either. The only thing that reliably helps is discarding the whole engine and creating a new one. OS This is on iOS 14, beta 5. I can't test this on previous versions I'm afraid; I only have one device around. Code to Reproduce Here is a minimum code example. Create a simple app project in Xcode (doesn't matter whether you choose SwiftUI or Storyboard), and give it permissions to access the microphone in Info.plist. Create the following file Conductor.swift: import AVFoundation class Conductor { 		static let shared: Conductor = Conductor() 		 		private let _engine = AVAudioEngine? 		 		init() { 				// Session 				let session = AVAudioSession.sharedInstance() 				try? session.setActive(false) 				try! session.setCategory(.playAndRecord, options: [.defaultToSpeaker, 																													 .allowBluetooth, 																													 .allowAirPlay]) 				try! session.setActive(true) 				_engine.connect(_engine.inputNode, to: _engine.mainMixerNode, format: nil) 				_engine.prepare() 		} 		func start() { _engine.start() } } And in AppDelegate, call: Conductor.shared.start() This example will route the input straight to the output. If you don't have headphones, it will trigger a feedback loop. Question What am I missing here? Is this expected behaviour? If so, it does not seem to be documented anywhere.
Replies
2
Boosts
1
Views
2.6k
Activity
Feb ’22
AirPods Problem on Big Sur
While I have developer's beta iOS 14 on both my iPhone and Mac a recurrent problem has being happening to me where when I connect my AirPods to my computer it only recognizes one and uses one for audio. Whereas on my phone both work fine. So the problem is not the AirPods. Hope that on the next beta update it is resolve.
Replies
63
Boosts
0
Views
21k
Activity
Mar ’22
Unable to decode mp4 video using AVFoundation on iPhone 11 Pro
Basic Information Please provide a descriptive title for your feedback: Unable to decode mp4 video using AVFoundation on iPhone 11 Pro Which area are you seeing an issue with? AVFoundation What type of feedback are you reporting? Incorrect/Unexpected Behavior Description Please describe the issue and what steps we can take to reproduce it: Receiving decoderNotFound -11833 when trying to decode a 1 second mp4 video using iPhone 11 Pro currently on iOS14 beta 5. On other devices it works without a problem. It happens specifically on iPhone 11 Pro and iPhone XR. Have 1 second mp4 video use copyNextSampleBuffer check the status of assetReader; it will be .failed Expected to see images on screen The image is not displayed. Everything is grey More details Error Domain=AVFoundationErrorDomain Code=-11833 "Cannot Decode" UserInfo={NSUnderlyingError=0x280c94510 {Error Domain=NSOSStatusErrorDomain Code=-12906 "(null)"}, NSLocalizedFailureReason=The decoder required for this media was not found., AVErrorMediaTypeKey=vide, NSLocalizedDescription=Cannot Decode}
Replies
8
Boosts
0
Views
3.3k
Activity
Mar ’22