TPAACAudioConverter.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. //
  2. // TPAACAudioConverter.m
  3. //
  4. // Created by Michael Tyson on 02/04/2011.
  5. // Copyright 2011 A Tasty Pixel. All rights reserved.
  6. //
  7. #import "TPAACAudioConverter.h"
  8. #import <AudioToolbox/AudioToolbox.h>
  9. #import <AVFoundation/AVFoundation.h>
  10. #if !__has_feature(objc_arc)
  11. #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  12. #endif
  13. NSString * TPAACAudioConverterWillSwitchAudioSessionCategoryNotification = @"TPAACAudioConverterWillSwitchAudioSessionCategoryNotification";
  14. NSString * TPAACAudioConverterDidRestoreAudioSessionCategoryNotification = @"TPAACAudioConverterDidRestoreAudioSessionCategoryNotification";
  15. NSString * TPAACAudioConverterErrorDomain = @"com.atastypixel.TPAACAudioConverterErrorDomain";
  16. #define checkResult(result,operation) (_checkResultLite((result),(operation),__FILE__,__LINE__))
  17. static inline BOOL _checkResultLite(OSStatus result, const char *operation, const char* file, int line) {
  18. if ( result != noErr ) {
  19. NSLog(@"%s:%d: %s result %d %08X %4.4s\n", file, line, operation, (int)result, (int)result, (char*)&result);
  20. return NO;
  21. }
  22. return YES;
  23. }
  24. @interface TPAACAudioConverter () {
  25. BOOL _processing;
  26. BOOL _cancelled;
  27. BOOL _interrupted;
  28. AVAudioSessionCategoryOptions _priorCategoryOptions;
  29. }
  30. @property (nonatomic, readwrite, strong) NSString *source;
  31. @property (nonatomic, readwrite, strong) NSString *destination;
  32. @property (nonatomic, weak) id<TPAACAudioConverterDelegate> delegate;
  33. @property (nonatomic, strong) id<TPAACAudioConverterDataSource> dataSource;
  34. @property (nonatomic, strong) NSCondition *condition;
  35. @end
  36. @implementation TPAACAudioConverter
  37. + (BOOL)AACConverterAvailable {
  38. #if TARGET_IPHONE_SIMULATOR
  39. return YES;
  40. #else
  41. static BOOL available;
  42. static BOOL available_set = NO;
  43. if ( available_set ) return available;
  44. // get an array of AudioClassDescriptions for all installed encoders for the given format
  45. // the specifier is the format that we are interested in - this is 'aac ' in our case
  46. UInt32 encoderSpecifier = kAudioFormatMPEG4AAC;
  47. UInt32 size;
  48. if ( !checkResult(AudioFormatGetPropertyInfo(kAudioFormatProperty_Encoders, sizeof(encoderSpecifier), &encoderSpecifier, &size),
  49. "AudioFormatGetPropertyInfo(kAudioFormatProperty_Encoders") ) return NO;
  50. UInt32 numEncoders = size / sizeof(AudioClassDescription);
  51. AudioClassDescription encoderDescriptions[numEncoders];
  52. if ( !checkResult(AudioFormatGetProperty(kAudioFormatProperty_Encoders, sizeof(encoderSpecifier), &encoderSpecifier, &size, encoderDescriptions),
  53. "AudioFormatGetProperty(kAudioFormatProperty_Encoders") ) {
  54. available_set = YES;
  55. available = NO;
  56. return NO;
  57. }
  58. for (UInt32 i=0; i < numEncoders; ++i) {
  59. if ( encoderDescriptions[i].mSubType == kAudioFormatMPEG4AAC ) {
  60. available_set = YES;
  61. available = YES;
  62. return YES;
  63. }
  64. }
  65. available_set = YES;
  66. available = NO;
  67. return NO;
  68. #endif
  69. }
  70. - (id)initWithDelegate:(id<TPAACAudioConverterDelegate>)delegate source:(NSString*)source destination:(NSString*)destination {
  71. if ( !(self = [super init]) ) return nil;
  72. self.delegate = delegate;
  73. self.source = source;
  74. self.destination = destination;
  75. _condition = [[NSCondition alloc] init];
  76. return self;
  77. }
  78. - (id)initWithDelegate:(id<TPAACAudioConverterDelegate>)delegate dataSource:(id<TPAACAudioConverterDataSource>)dataSource
  79. audioFormat:(AudioStreamBasicDescription)audioFormat destination:(NSString*)destination {
  80. if ( !(self = [super init]) ) return nil;
  81. self.delegate = delegate;
  82. self.dataSource = dataSource;
  83. self.destination = destination;
  84. _audioFormat = audioFormat;
  85. _condition = [[NSCondition alloc] init];
  86. return self;
  87. }
  88. - (void)start {
  89. AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  90. _priorCategoryOptions = audioSession.categoryOptions;
  91. if ( _priorCategoryOptions & AVAudioSessionCategoryOptionMixWithOthers ) {
  92. NSError *error = nil;
  93. if ( ![audioSession setCategory:audioSession.category
  94. withOptions:_priorCategoryOptions & ~AVAudioSessionCategoryOptionMixWithOthers
  95. error:&error] ) {
  96. NSLog(@"Couldn't disable mix with others Audio Session option for AAC conversion: %@", error.localizedDescription);
  97. }
  98. }
  99. _cancelled = NO;
  100. _processing = YES;
  101. [self performSelectorInBackground:@selector(processingThread) withObject:nil];
  102. }
  103. - (void)cancel {
  104. _cancelled = YES;
  105. while ( _processing ) {
  106. [NSThread sleepForTimeInterval:0.01];
  107. }
  108. if ( _priorCategoryOptions & AVAudioSessionCategoryOptionMixWithOthers ) {
  109. NSError *error = nil;
  110. if ( ![[AVAudioSession sharedInstance] setCategory:[AVAudioSession sharedInstance].category
  111. withOptions:_priorCategoryOptions
  112. error:&error] ) {
  113. NSLog(@"Couldn't reinstate Audio Session options for AAC conversion: %@", error.localizedDescription);
  114. }
  115. }
  116. }
  117. - (void)interrupt {
  118. [_condition lock];
  119. _interrupted = YES;
  120. [_condition unlock];
  121. }
  122. - (void)resume {
  123. [_condition lock];
  124. _interrupted = NO;
  125. [_condition signal];
  126. [_condition unlock];
  127. }
  128. - (void)reportProgress:(NSNumber*)progress {
  129. if ( _cancelled ) return;
  130. [_delegate AACAudioConverter:self didMakeProgress:[progress floatValue]];
  131. }
  132. - (void)reportCompletion {
  133. if ( _cancelled ) return;
  134. [_delegate AACAudioConverterDidFinishConversion:self];
  135. if ( _priorCategoryOptions & AVAudioSessionCategoryOptionMixWithOthers ) {
  136. NSError *error = nil;
  137. if ( ![[AVAudioSession sharedInstance] setCategory:[AVAudioSession sharedInstance].category
  138. withOptions:_priorCategoryOptions
  139. error:&error] ) {
  140. NSLog(@"Couldn't reinstate Audio Session options for AAC conversion: %@", error.localizedDescription);
  141. }
  142. }
  143. }
  144. - (void)reportErrorAndCleanup:(NSError*)error {
  145. if ( _cancelled ) return;
  146. [[NSFileManager defaultManager] removeItemAtPath:_destination error:NULL];
  147. if ( _priorCategoryOptions & AVAudioSessionCategoryOptionMixWithOthers ) {
  148. NSError *error = nil;
  149. if ( ![[AVAudioSession sharedInstance] setCategory:[AVAudioSession sharedInstance].category
  150. withOptions:_priorCategoryOptions
  151. error:&error] ) {
  152. NSLog(@"Couldn't reinstate Audio Session options for AAC conversion: %@", error.localizedDescription);
  153. }
  154. }
  155. [_delegate AACAudioConverter:self didFailWithError:error];
  156. }
  157. - (void)processingThread {
  158. [[NSThread currentThread] setThreadPriority:0.9];
  159. ExtAudioFileRef sourceFile = NULL;
  160. AudioStreamBasicDescription sourceFormat;
  161. if ( _source ) {
  162. if ( !checkResult(ExtAudioFileOpenURL((__bridge CFURLRef)[NSURL fileURLWithPath:_source], &sourceFile), "ExtAudioFileOpenURL") ) {
  163. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  164. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  165. code:TPAACAudioConverterFileError
  166. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Couldn't open the source file", @"Error message") forKey:NSLocalizedDescriptionKey]]
  167. waitUntilDone:NO];
  168. _processing = NO;
  169. return;
  170. }
  171. UInt32 size = sizeof(sourceFormat);
  172. if ( !checkResult(ExtAudioFileGetProperty(sourceFile, kExtAudioFileProperty_FileDataFormat, &size, &sourceFormat),
  173. "ExtAudioFileGetProperty(kExtAudioFileProperty_FileDataFormat)") ) {
  174. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  175. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  176. code:TPAACAudioConverterFormatError
  177. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Couldn't read the source file", @"Error message") forKey:NSLocalizedDescriptionKey]]
  178. waitUntilDone:NO];
  179. _processing = NO;
  180. return;
  181. }
  182. } else {
  183. sourceFormat = _audioFormat;
  184. }
  185. AudioStreamBasicDescription destinationFormat;
  186. memset(&destinationFormat, 0, sizeof(destinationFormat));
  187. destinationFormat.mChannelsPerFrame = sourceFormat.mChannelsPerFrame;
  188. destinationFormat.mFormatID = kAudioFormatMPEG4AAC;
  189. UInt32 size = sizeof(destinationFormat);
  190. if ( !checkResult(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &size, &destinationFormat),
  191. "AudioFormatGetProperty(kAudioFormatProperty_FormatInfo)") ) {
  192. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  193. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  194. code:TPAACAudioConverterFormatError
  195. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Couldn't setup destination format", @"Error message") forKey:NSLocalizedDescriptionKey]]
  196. waitUntilDone:NO];
  197. _processing = NO;
  198. return;
  199. }
  200. ExtAudioFileRef destinationFile;
  201. if ( !checkResult(ExtAudioFileCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:_destination],
  202. kAudioFileM4AType,
  203. &destinationFormat,
  204. NULL,
  205. kAudioFileFlags_EraseFile,
  206. &destinationFile), "ExtAudioFileCreateWithURL") ) {
  207. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  208. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  209. code:TPAACAudioConverterFileError
  210. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Couldn't open the destination file", @"Error message") forKey:NSLocalizedDescriptionKey]]
  211. waitUntilDone:NO];
  212. _processing = NO;
  213. return;
  214. }
  215. AudioStreamBasicDescription clientFormat;
  216. if ( sourceFormat.mFormatID == kAudioFormatLinearPCM ) {
  217. clientFormat = sourceFormat;
  218. } else {
  219. memset(&clientFormat, 0, sizeof(clientFormat));
  220. clientFormat.mFormatID = kAudioFormatLinearPCM;
  221. clientFormat.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved;
  222. clientFormat.mChannelsPerFrame = sourceFormat.mChannelsPerFrame;
  223. clientFormat.mBytesPerPacket = sizeof(float);
  224. clientFormat.mFramesPerPacket = 1;
  225. clientFormat.mBytesPerFrame = sizeof(float);
  226. clientFormat.mBitsPerChannel = 8 * sizeof(float);
  227. clientFormat.mSampleRate = sourceFormat.mSampleRate;
  228. }
  229. size = sizeof(clientFormat);
  230. if ( (sourceFile && !checkResult(ExtAudioFileSetProperty(sourceFile, kExtAudioFileProperty_ClientDataFormat, size, &clientFormat),
  231. "ExtAudioFileSetProperty(sourceFile, kExtAudioFileProperty_ClientDataFormat")) ||
  232. !checkResult(ExtAudioFileSetProperty(destinationFile, kExtAudioFileProperty_ClientDataFormat, size, &clientFormat),
  233. "ExtAudioFileSetProperty(destinationFile, kExtAudioFileProperty_ClientDataFormat")) {
  234. if ( sourceFile ) ExtAudioFileDispose(sourceFile);
  235. ExtAudioFileDispose(destinationFile);
  236. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  237. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  238. code:TPAACAudioConverterFormatError
  239. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Couldn't setup intermediate conversion format", @"Error message") forKey:NSLocalizedDescriptionKey]]
  240. waitUntilDone:NO];
  241. _processing = NO;
  242. return;
  243. }
  244. BOOL canResumeFromInterruption = YES;
  245. AudioConverterRef converter;
  246. size = sizeof(converter);
  247. if ( checkResult(ExtAudioFileGetProperty(destinationFile, kExtAudioFileProperty_AudioConverter, &size, &converter),
  248. "ExtAudioFileGetProperty(kExtAudioFileProperty_AudioConverter;)") ) {
  249. UInt32 canResume = 0;
  250. size = sizeof(canResume);
  251. if ( AudioConverterGetProperty(converter, kAudioConverterPropertyCanResumeFromInterruption, &size, &canResume) == noErr ) {
  252. canResumeFromInterruption = (BOOL)canResume;
  253. }
  254. }
  255. SInt64 lengthInFrames = 0;
  256. if ( sourceFile ) {
  257. size = sizeof(lengthInFrames);
  258. ExtAudioFileGetProperty(sourceFile, kExtAudioFileProperty_FileLengthFrames, &size, &lengthInFrames);
  259. }
  260. UInt32 bufferByteSize = 32768;
  261. char srcBuffer[bufferByteSize];
  262. SInt64 sourceFrameOffset = 0;
  263. BOOL reportProgress = lengthInFrames > 0 && [_delegate respondsToSelector:@selector(AACAudioConverter:didMakeProgress:)];
  264. NSTimeInterval lastProgressReport = [NSDate timeIntervalSinceReferenceDate];
  265. while ( !_cancelled ) {
  266. AudioBufferList fillBufList;
  267. fillBufList.mNumberBuffers = 1;
  268. fillBufList.mBuffers[0].mNumberChannels = clientFormat.mChannelsPerFrame;
  269. fillBufList.mBuffers[0].mDataByteSize = bufferByteSize;
  270. fillBufList.mBuffers[0].mData = srcBuffer;
  271. UInt32 numFrames = bufferByteSize / clientFormat.mBytesPerFrame;
  272. if ( sourceFile ) {
  273. if ( !checkResult(ExtAudioFileRead(sourceFile, &numFrames, &fillBufList), "ExtAudioFileRead") ) {
  274. ExtAudioFileDispose(sourceFile);
  275. ExtAudioFileDispose(destinationFile);
  276. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  277. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  278. code:TPAACAudioConverterFormatError
  279. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Error reading the source file", @"Error message") forKey:NSLocalizedDescriptionKey]]
  280. waitUntilDone:NO];
  281. _processing = NO;
  282. return;
  283. }
  284. } else {
  285. NSUInteger length = bufferByteSize;
  286. [_dataSource AACAudioConverter:self nextBytes:srcBuffer length:&length];
  287. numFrames = (UInt32)length / clientFormat.mBytesPerFrame;
  288. fillBufList.mBuffers[0].mDataByteSize = (UInt32)length;
  289. }
  290. if ( !numFrames ) {
  291. break;
  292. }
  293. sourceFrameOffset += numFrames;
  294. [_condition lock];
  295. BOOL wasInterrupted = _interrupted;
  296. while ( _interrupted ) {
  297. [_condition wait];
  298. }
  299. [_condition unlock];
  300. if ( wasInterrupted && !canResumeFromInterruption ) {
  301. if ( sourceFile ) ExtAudioFileDispose(sourceFile);
  302. ExtAudioFileDispose(destinationFile);
  303. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  304. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  305. code:TPAACAudioConverterUnrecoverableInterruptionError
  306. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Interrupted", @"Error message") forKey:NSLocalizedDescriptionKey]]
  307. waitUntilDone:NO];
  308. _processing = NO;
  309. return;
  310. }
  311. OSStatus status = ExtAudioFileWrite(destinationFile, numFrames, &fillBufList);
  312. if ( status == kExtAudioFileError_CodecUnavailableInputConsumed) {
  313. /*
  314. Returned when ExtAudioFileWrite was interrupted. You must stop calling
  315. ExtAudioFileWrite. If the underlying audio converter can resume after an
  316. interruption (see kAudioConverterPropertyCanResumeFromInterruption), you must
  317. wait for an EndInterruption notification from AudioSession, and call AudioSessionSetActive(true)
  318. before resuming. In this situation, the buffer you provided to ExtAudioFileWrite was successfully
  319. consumed and you may proceed to the next buffer
  320. */
  321. } else if ( status == kExtAudioFileError_CodecUnavailableInputNotConsumed ) {
  322. /*
  323. Returned when ExtAudioFileWrite was interrupted. You must stop calling
  324. ExtAudioFileWrite. If the underlying audio converter can resume after an
  325. interruption (see kAudioConverterPropertyCanResumeFromInterruption), you must
  326. wait for an EndInterruption notification from AudioSession, and call AudioSessionSetActive(true)
  327. before resuming. In this situation, the buffer you provided to ExtAudioFileWrite was not
  328. successfully consumed and you must try to write it again
  329. */
  330. // seek back to last offset before last read so we can try again after the interruption
  331. sourceFrameOffset -= numFrames;
  332. if ( sourceFile ) {
  333. checkResult(ExtAudioFileSeek(sourceFile, sourceFrameOffset), "ExtAudioFileSeek");
  334. } else if ( [_dataSource respondsToSelector:@selector(AACAudioConverter:seekToPosition:)] ) {
  335. [_dataSource AACAudioConverter:self seekToPosition:sourceFrameOffset * clientFormat.mBytesPerFrame];
  336. }
  337. } else if ( !checkResult(status, "ExtAudioFileWrite") ) {
  338. if ( sourceFile ) ExtAudioFileDispose(sourceFile);
  339. ExtAudioFileDispose(destinationFile);
  340. [self performSelectorOnMainThread:@selector(reportErrorAndCleanup:)
  341. withObject:[NSError errorWithDomain:TPAACAudioConverterErrorDomain
  342. code:TPAACAudioConverterFormatError
  343. userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Error writing the destination file", @"Error message") forKey:NSLocalizedDescriptionKey]]
  344. waitUntilDone:NO];
  345. _processing = NO;
  346. return;
  347. }
  348. if ( reportProgress && [NSDate timeIntervalSinceReferenceDate]-lastProgressReport > 0.1 ) {
  349. lastProgressReport = [NSDate timeIntervalSinceReferenceDate];
  350. [self performSelectorOnMainThread:@selector(reportProgress:) withObject:[NSNumber numberWithDouble:(double)sourceFrameOffset/lengthInFrames] waitUntilDone:NO];
  351. }
  352. }
  353. if ( sourceFile ) ExtAudioFileDispose(sourceFile);
  354. ExtAudioFileDispose(destinationFile);
  355. if ( _cancelled ) {
  356. [[NSFileManager defaultManager] removeItemAtPath:_destination error:NULL];
  357. } else {
  358. [self performSelectorOnMainThread:@selector(reportCompletion) withObject:nil waitUntilDone:NO];
  359. }
  360. _processing = NO;
  361. }
  362. @end