You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

359 lines
14KB

  1. /*
  2. ==============================================================================
  3. This file is part of the dRowAudio JUCE module
  4. Copyright 2004-13 by dRowAudio.
  5. ------------------------------------------------------------------------------
  6. dRowAudio is provided under the terms of The MIT License (MIT):
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in all
  14. copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. ==============================================================================
  23. */
  24. #if JUCE_IOS
  25. } // namespace drow
  26. #include <AudioToolbox/AudioToolbox.h>
  27. #include <AVFoundation/AVFoundation.h>
  28. namespace drow {
  29. //==============================================================================
  30. namespace
  31. {
  32. const char* const AVAssetAudioFormatName = "AVAsset supported file";
  33. StringArray findFileExtensionsForCoreAudioCodecs()
  34. {
  35. StringArray extensionsArray;
  36. CFMutableArrayRef extensions = CFArrayCreateMutable (0, 0, 0);
  37. UInt32 sizeOfArray = sizeof (CFMutableArrayRef);
  38. if (AudioFileGetGlobalInfo (kAudioFileGlobalInfo_AllExtensions, 0, 0, &sizeOfArray, &extensions) == noErr)
  39. {
  40. const CFIndex numValues = CFArrayGetCount (extensions);
  41. for (CFIndex i = 0; i < numValues; ++i)
  42. extensionsArray.add ("." + String::fromCFString ((CFStringRef) CFArrayGetValueAtIndex (extensions, i)));
  43. }
  44. return extensionsArray;
  45. }
  46. String nsStringToJuce (NSString* s)
  47. {
  48. return CharPointer_UTF8 ([s UTF8String]);
  49. }
  50. NSString* juceStringToNS (const String& s)
  51. {
  52. return [NSString stringWithUTF8String: s.toUTF8()];
  53. }
  54. }
  55. //==============================================================================
  56. class AVAssetAudioReader : public AudioFormatReader
  57. {
  58. public:
  59. AVAssetAudioReader (NSURL* assetURL)
  60. : AudioFormatReader (nullptr, TRANS (AVAssetAudioFormatName)),
  61. ok (false),
  62. lastReadPosition (0),
  63. fifoBuffer (2 * 8196 * 2),
  64. tempBlockSize (256),
  65. tempInterleavedBlock (tempBlockSize),
  66. tempDeinterleavedBlock(tempBlockSize)
  67. {
  68. @autoreleasepool {
  69. usesFloatingPointData = true;
  70. songAsset = [AVURLAsset URLAssetWithURL: assetURL options: nil];
  71. avAssetTrack = [songAsset.tracks objectAtIndex: 0];
  72. [songAsset retain];
  73. [avAssetTrack retain];
  74. NSError* status = nil;
  75. assetReader = [AVAssetReader assetReaderWithAsset: songAsset // dont need to retain as a new one
  76. error: &status]; // will be created in updateReadPosition()
  77. [assetReader retain];
  78. assetReaderOutput = nil;
  79. if (! status)
  80. {
  81. // fill in format information
  82. CMAudioFormatDescriptionRef formatDescription = (CMAudioFormatDescriptionRef) [avAssetTrack.formatDescriptions objectAtIndex: 0];
  83. const AudioStreamBasicDescription* audioDesc = CMAudioFormatDescriptionGetStreamBasicDescription (formatDescription);
  84. if (audioDesc != nullptr)
  85. {
  86. numChannels = audioDesc->mChannelsPerFrame;
  87. bitsPerSample = audioDesc->mBitsPerChannel;
  88. sampleRate = audioDesc->mSampleRate;
  89. lengthInSamples = avAssetTrack.timeRange.duration.value;
  90. outputSettings = [[NSDictionary dictionaryWithObjectsAndKeys:
  91. [NSNumber numberWithInt: kAudioFormatLinearPCM], AVFormatIDKey,
  92. // [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
  93. // [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey,
  94. // [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
  95. [NSNumber numberWithBool: NO], AVLinearPCMIsNonInterleaved,
  96. [NSNumber numberWithBool: YES], AVLinearPCMIsFloatKey,
  97. [NSNumber numberWithInt: 32], AVLinearPCMBitDepthKey,
  98. // [NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,
  99. nil]
  100. retain];
  101. ok = updateReadPosition (0);
  102. }
  103. }}
  104. }
  105. ~AVAssetAudioReader()
  106. {
  107. [songAsset release];
  108. [avAssetTrack release];
  109. [outputSettings release];
  110. [assetReader release];
  111. [assetReaderOutput release];
  112. }
  113. //==============================================================================
  114. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  115. int64 startSampleInFile, int numSamples)
  116. {
  117. jassert (destSamples != nullptr);
  118. jassert (numDestChannels == numChannels);
  119. @autoreleasepool // not sure if there is a better method than this
  120. {
  121. const int numBufferSamplesNeeded = numChannels * numSamples;
  122. // check if position has changed
  123. if (lastReadPosition != startSampleInFile)
  124. {
  125. updateReadPosition (startSampleInFile);
  126. lastReadPosition = startSampleInFile;
  127. }
  128. // get next block if we need to
  129. if (fifoBuffer.getNumAvailable() < numBufferSamplesNeeded
  130. && assetReader.status == AVAssetReaderStatusReading)
  131. {
  132. CMSampleBufferRef sampleRef = [assetReaderOutput copyNextSampleBuffer];
  133. if (sampleRef != NULL)
  134. {
  135. CMBlockBufferRef bufferRef = CMSampleBufferGetDataBuffer (sampleRef);
  136. size_t lengthAtOffset;
  137. size_t totalLength;
  138. char* dataPointer;
  139. CMBlockBufferGetDataPointer (bufferRef,
  140. 0,
  141. &lengthAtOffset,
  142. &totalLength,
  143. &dataPointer);
  144. if (bufferRef != NULL)
  145. {
  146. const int samplesExpected = (int) CMSampleBufferGetNumSamples (sampleRef);
  147. const int numSamplesNeeded = fifoBuffer.getNumAvailable() + (samplesExpected * numChannels);
  148. if (numSamplesNeeded > fifoBuffer.getSize()) //*** need to keep existing
  149. fifoBuffer.setSize (numSamplesNeeded);
  150. fifoBuffer.writeSamples ((float*) dataPointer, samplesExpected * numChannels);
  151. }
  152. CFRelease (sampleRef);
  153. }
  154. }
  155. // deinterleave
  156. if (tempBlockSize < numBufferSamplesNeeded)
  157. {
  158. tempInterleavedBlock.malloc (numBufferSamplesNeeded);
  159. tempDeinterleavedBlock.malloc (numBufferSamplesNeeded);
  160. tempBlockSize = numBufferSamplesNeeded;
  161. }
  162. fifoBuffer.readSamples (tempInterleavedBlock, numBufferSamplesNeeded);
  163. float* deinterleavedSamples[numChannels];
  164. for (int i = 0; i < numChannels; i++)
  165. deinterleavedSamples[i] = &tempDeinterleavedBlock[i * numSamples];
  166. AudioDataConverters::deinterleaveSamples (tempInterleavedBlock, deinterleavedSamples,
  167. numSamples, numChannels);
  168. for (int i = 0; i < numChannels; i++)
  169. memcpy (destSamples[i] + startOffsetInDestBuffer, deinterleavedSamples[i], sizeof (float) * numSamples);
  170. lastReadPosition += numSamples;
  171. }
  172. return true;
  173. }
  174. bool ok;
  175. private:
  176. //==============================================================================
  177. NSAutoreleasePool* pool;
  178. AVURLAsset* songAsset;
  179. AVAssetTrack* avAssetTrack;
  180. NSDictionary* outputSettings;
  181. AVAssetReader* assetReader;
  182. AVAssetReaderTrackOutput* assetReaderOutput;
  183. CMTime startCMTime;
  184. CMTimeRange playbackCMTimeRange;
  185. int64 lastReadPosition;
  186. FifoBuffer<float> fifoBuffer;
  187. int tempBlockSize;
  188. HeapBlock<float> tempInterleavedBlock, tempDeinterleavedBlock;
  189. //==============================================================================
  190. /* Annoyingly we can't just re-position the stream so we have to create an entire new one.
  191. */
  192. bool updateReadPosition (int64 startSample)
  193. {
  194. [assetReader cancelReading];
  195. [assetReader release];
  196. [assetReaderOutput release];
  197. NSError* error = nil;
  198. assetReader = [AVAssetReader assetReaderWithAsset: songAsset
  199. error: &error];
  200. [assetReader retain];
  201. if (error == nil)
  202. {
  203. assetReaderOutput = [[AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack: avAssetTrack
  204. outputSettings: outputSettings]
  205. retain];
  206. assetReaderOutput.alwaysCopiesSampleData = NO;
  207. if ([assetReader canAddOutput: assetReaderOutput])
  208. {
  209. [assetReader addOutput: assetReaderOutput];
  210. startCMTime = CMTimeMake (startSample, sampleRate);
  211. playbackCMTimeRange = CMTimeRangeMake (startCMTime, kCMTimePositiveInfinity);
  212. assetReader.timeRange = playbackCMTimeRange;
  213. if ([assetReader startReading])
  214. {
  215. return true;
  216. }
  217. }
  218. }
  219. return false;
  220. }
  221. //==============================================================================
  222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AVAssetAudioReader);
  223. };
  224. //==============================================================================
  225. AVAssetAudioFormat::AVAssetAudioFormat()
  226. : AudioFormat (TRANS (AVAssetAudioFormatName), findFileExtensionsForCoreAudioCodecs())
  227. {
  228. }
  229. AVAssetAudioFormat::~AVAssetAudioFormat() {}
  230. MemoryInputStream* AVAssetAudioFormat::avAssetUrlStringToStream (const String& avAssetUrlString)
  231. {
  232. const CharPointer_UTF8 urlUTF8 (avAssetUrlString.toUTF8());
  233. return new MemoryInputStream (urlUTF8.getAddress(), urlUTF8.sizeInBytes(), false);
  234. }
  235. Array<int> AVAssetAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  236. Array<int> AVAssetAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  237. bool AVAssetAudioFormat::canDoStereo() { return true; }
  238. bool AVAssetAudioFormat::canDoMono() { return true; }
  239. //==============================================================================
  240. AudioFormatReader* AVAssetAudioFormat::createReaderFor (String assetNSURLAsString)
  241. {
  242. NSString* assetNSString = [NSString stringWithUTF8String:assetNSURLAsString.toUTF8()];
  243. NSURL* assetNSURL = [NSURL URLWithString:assetNSString];
  244. ScopedPointer<AVAssetAudioReader> r (new AVAssetAudioReader (assetNSURL));
  245. [assetNSString release];
  246. [assetNSURL release];
  247. if (r->ok)
  248. return r.release();
  249. return nullptr;
  250. }
  251. AudioFormatReader* AVAssetAudioFormat::createReaderFor (InputStream* sourceStream,
  252. bool deleteStreamIfOpeningFails)
  253. {
  254. if (sourceStream != nullptr)
  255. {
  256. const String nsUrlString (sourceStream->readString());
  257. if (nsUrlString.startsWith ("ipod-library://"))
  258. {
  259. NSURL* sourceUrl = [NSURL URLWithString: juceStringToNS (nsUrlString)];
  260. ScopedPointer<AVAssetAudioReader> r (new AVAssetAudioReader (sourceUrl));
  261. if (r->ok)
  262. return r.release();
  263. if (! deleteStreamIfOpeningFails)
  264. r->input = nullptr;
  265. }
  266. }
  267. return nullptr;
  268. jassertfalse;
  269. /* Can't read from a stream, has to be from an AVURLAsset compatible string.
  270. see createReaderFor (String assetNSURLAsString).
  271. */
  272. return nullptr;
  273. }
  274. AudioFormatWriter* AVAssetAudioFormat::createWriterFor (OutputStream* streamToWriteTo,
  275. double sampleRateToUse,
  276. unsigned int numberOfChannels,
  277. int bitsPerSample,
  278. const StringPairArray& metadataValues,
  279. int qualityOptionIndex)
  280. {
  281. jassertfalse; // not yet implemented!
  282. return nullptr;
  283. }
  284. #endif