Advertisement
Guest User

Untitled

a guest
May 26th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.37 KB | None | 0 0
  1. //
  2. // SVNPlayer.swift
  3. // WYNDR
  4. //
  5. // Created by Aaron Dean Bikis on 5/24/17.
  6. // Copyright © 2017 7apps. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import AudioToolbox
  11.  
  12. class SVNPlayer: SVNPlayback {
  13. var queue: AudioQueueRef?
  14. var audioFormat: AudioStreamBasicDescription!
  15. var playbackFile: AudioFileID?
  16. var packetDesc: AudioStreamPacketDescription!
  17. var isDone = false
  18. var packetPosition: Int64 = 0
  19. var numPacketsToRead = UInt32()
  20.  
  21. private let callback: AudioQueueOutputCallback = { aqData, inAQ, inBuffer in
  22.  
  23. guard let userData = aqData else { return }
  24. let audioPlayer = Unmanaged<SVNPlayer>.fromOpaque(userData).takeUnretainedValue()
  25. var buffer = inBuffer.pointee
  26. if audioPlayer.isDone { return }
  27. var numBytes: UInt32 = 0
  28. var nPackets = audioPlayer.numPacketsToRead
  29.  
  30. var code = AudioFileReadPacketData(audioPlayer.playbackFile!, false, &numBytes, &audioPlayer.packetDesc!, audioPlayer.packetPosition, &nPackets, buffer.mAudioData)
  31. // code = AudioFileReadPackets(audioPlayer.playbackFile!, false, &numBytes, nil, audioPlayer.packetPosition!, &nPackets, buffer.mAudioData)
  32. print(code)
  33.  
  34. if nPackets > 0 {
  35. buffer.mAudioDataByteSize = numBytes
  36. AudioQueueEnqueueBuffer(inAQ, &buffer, nPackets, &audioPlayer.packetDesc!)
  37. audioPlayer.packetPosition += Int64(nPackets)
  38. } else {
  39. AudioQueueStop(inAQ, false)
  40. audioPlayer.isDone = true
  41. }
  42. }
  43.  
  44. func prepareToPlayback(with fileURL: URL) throws {
  45.  
  46. let pointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) // get an unmananged reference to self
  47.  
  48. var format = AudioStreamBasicDescription()
  49.  
  50. var formatSize = UInt32(MemoryLayout<AudioStreamBasicDescription>.stride)
  51.  
  52. var audioFileID: AudioFileID? // open the recorded file
  53.  
  54. try osStatus { AudioFileOpenURL(fileURL as CFURL, AudioFilePermissions.readPermission, 0, &audioFileID) }
  55.  
  56. playbackFile = audioFileID // get the full audio data format from the file
  57.  
  58. try osStatus { AudioFileGetProperty(playbackFile!, kAudioFilePropertyDataFormat, &formatSize, &format) }
  59.  
  60. try osStatus { AudioQueueNewOutput(&format, callback, pointer, nil, nil, 0, &queue) }
  61.  
  62. var bufferByteSize = UInt32()
  63. var numPacketsToRead = UInt32()
  64. try deriveBufferByteSize(with: playbackFile!,
  65. format: format,
  66. duration: 0.5,
  67. outBufferByteSize: &bufferByteSize,
  68. outNumPackets: &numPacketsToRead)
  69. let isFormatVBR = format.mBytesPerPacket == 0 || format.mFramesPerPacket == 0
  70. if isFormatVBR {
  71. packetDesc = AudioStreamPacketDescription(mStartOffset: 0, mVariableFramesInPacket: numPacketsToRead, mDataByteSize: UInt32(MemoryLayout<AudioStreamPacketDescription>.stride)) // this may fail i dunno
  72. } // we don't provide packet descriptions for constant bit rate formats (like linear PCM)
  73. packetDesc = AudioStreamPacketDescription()
  74.  
  75. try copyEncoderCookieToQueue(with: playbackFile!, queue: &queue!)
  76.  
  77. var bufferRef: AudioQueueBufferRef?
  78. isDone = false
  79. packetPosition = 0
  80. for _ in 0..<3 {
  81.  
  82. try osStatus { AudioQueueAllocateBuffer(queue!, bufferByteSize, &bufferRef) }
  83.  
  84. guard let buffer = bufferRef else { print("couldn't get buffer"); return }
  85. callback(pointer, queue!, buffer)
  86. if isDone {
  87. break
  88. }
  89. }
  90. }
  91.  
  92. func start() throws {
  93. try osStatus { AudioQueueStart(queue!, nil) }
  94.  
  95. repeat {
  96. CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.25, false)
  97. } while !isDone
  98.  
  99. CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 2, false)
  100. isDone = true
  101. AudioQueueStop(queue!, true)
  102. //clean up
  103. AudioQueueDispose(queue!, true)
  104. AudioFileClose(playbackFile!)
  105.  
  106. }
  107.  
  108. // we only use time here as a guideline
  109. // we're really trying to get somewhere between 16K and 64K buffers, but not allocate too much if we don't need it
  110. func deriveBufferByteSize(with file: AudioFileID, format: AudioStreamBasicDescription, duration: Double, outBufferByteSize: inout UInt32, outNumPackets: inout UInt32) throws {
  111. // we need to calculate how many packets we read at a time, and how big a buffer we need.
  112. // we base this on the size of the packets in the file and an approximate duration for each buffer.
  113. //
  114. // first check to see what the max size of a packet is, if it is bigger than our default
  115. // allocation size, that needs to become larger
  116.  
  117. var maxPacketSize: UInt32 = 0
  118. var propertySize = UInt32(MemoryLayout<UInt32>.size(ofValue: maxPacketSize))
  119.  
  120. try osStatus { AudioFileGetProperty(file, kAudioFilePropertyPacketSizeUpperBound, &propertySize, &maxPacketSize) }
  121.  
  122. let maxBufferSize: Int = 0x10000
  123. let minBufferSize: Int = 0x4000
  124. let uMaxBufferSize = UInt32(maxBufferSize)
  125. let uMinBufferSize = UInt32(minBufferSize)
  126.  
  127. if format.mFramesPerPacket == 0 {
  128. let numPacketesForTime = format.mSampleRate / Double(format.mFramesPerPacket) * duration
  129. outBufferByteSize = UInt32(numPacketesForTime) * maxPacketSize
  130. } else {
  131. // if frames per packet is zero, then the codec has no predictable packet == time
  132. // so we can't tailor this (we don't know how many Packets represent a time period
  133. // we'll just return a default buffer size
  134. outBufferByteSize = uMaxBufferSize > maxPacketSize ? uMaxBufferSize : maxPacketSize
  135. }
  136.  
  137. // limit the size to our default
  138. if outBufferByteSize > uMaxBufferSize && outBufferByteSize > maxPacketSize {
  139. outBufferByteSize = uMaxBufferSize
  140. }
  141. // make sure it doesnt get too small - we dont want to save small chunks to disk
  142. else if outBufferByteSize < uMinBufferSize {
  143. outBufferByteSize = uMinBufferSize
  144. }
  145. outNumPackets = outBufferByteSize / maxPacketSize
  146. }
  147.  
  148. func copyEncoderCookieToQueue(with file: AudioFileID, queue: inout AudioQueueRef) throws {
  149. var propertySize = UInt32()
  150.  
  151. try osStatus { AudioFileGetPropertyInfo(file, kAudioFilePropertyMagicCookieData, &propertySize, nil) }
  152.  
  153. if propertySize > 0 {
  154. var magicCookie = UInt8(MemoryLayout<UInt8>.size(ofValue: UInt8(propertySize)))
  155. try osStatus { AudioFileGetProperty(file, kAudioFilePropertyMagicCookieData, &propertySize, &magicCookie) }
  156. try osStatus { AudioQueueSetProperty(queue, kAudioQueueProperty_MagicCookie, &magicCookie, propertySize) }
  157. }
  158. }
  159. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement