-
Notifications
You must be signed in to change notification settings - Fork 1
/
SPExporter.mm
881 lines (678 loc) · 27.9 KB
/
SPExporter.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
#import "SPExporter.h"
#import "SPExportController.h"
#import "SPPlayerWindow.h"
#import "PlayerLibSidplay.h"
#import "SongLengthDatabase.h"
#import "SPCollectionUtilities.h"
#import "SPPreferencesController.h"
#include "TargetConditionals.h"
#include "lame.h"
static NSString* exportFileTypeExtensions[NUM_EXPORT_TYPES] =
{
@"mp3",
@"m4a",
@"m4a",
@"aiff",
@"prg",
@"sid"
};
static AudioFileTypeID exportAudioFileIDs[NUM_EXPORT_TYPES] =
{
kAudioFileMP3Type,
kAudioFileM4AType,
kAudioFileM4AType,
kAudioFileAIFFType,
0,
0
};
@implementation SPExporter
// ----------------------------------------------------------------------------
- (id) initWithItem:(SPExportItem*)item withController:(SPExportController*)theController andWindow:(SPPlayerWindow*)window loadNow:(BOOL)loadItem
// ----------------------------------------------------------------------------
{
self = [super init];
if (self != nil)
{
controller = theController;
ownerWindow = window;
outputFileRef = NULL;
exportSettings = [controller exportSettings];
samplesRemaining = 0;
samplesCompleted = 0;
fileName = nil;
exportProgress = 0.0f;
fileIcon = nil;
exportItemLoaded = NO;
exportInProgress = NO;
[self setExportStopped:NO];
[self setExportProgressIsIndeterminate:NO];
psid64Task = nil;
player = new PlayerLibSidplay;
exportItem = item;
title = [item title];
author = [item author];
if (loadItem)
{
BOOL itemIsValid = [self loadExportItem];
if (!itemIsValid)
return nil;
}
destinationPath = nil;
}
return self;
}
// ----------------------------------------------------------------------------
- (BOOL) loadExportItem
// ----------------------------------------------------------------------------
{
if (exportItemLoaded)
return NO;
settings = gPreferences.mPlaybackSettings;
NSString* path = [exportItem path];
int subtune = [exportItem subtune];
bool success = player->loadTuneByPath([path cStringUsingEncoding:NSUTF8StringEncoding], subtune, &settings);
if (!success)
return NO;
exportSettings.mTimeInSeconds = [[SongLengthDatabase sharedInstance] getSongLengthByPath:path andSubtune:subtune];
if (exportSettings.mTimeInSeconds == 0)
exportSettings.mTimeInSeconds = gPreferences.mDefaultPlayTime;
if ([exportItem loopCount] > 0)
exportSettings.mTimeInSeconds *= [exportItem loopCount];
releaseInfo = [NSString stringWithCString:player->getCurrentReleaseInfo() encoding:NSISOLatin1StringEncoding];
exportItemLoaded = YES;
return YES;
}
// ----------------------------------------------------------------------------
- (void) unloadExportItem
// ----------------------------------------------------------------------------
{
if (!exportItemLoaded)
return;
exportItemLoaded = NO;
}
// ----------------------------------------------------------------------------
- (ExportSettings) exportSettings
// ----------------------------------------------------------------------------
{
return exportSettings;
}
// ----------------------------------------------------------------------------
- (void) setExportSettings:(ExportSettings)theExportSettings
// ----------------------------------------------------------------------------
{
exportSettings = theExportSettings;
}
// ----------------------------------------------------------------------------
- (void) determineExportFilePath:(NSString*)directoryPath
// ----------------------------------------------------------------------------
{
NSString* suggestedFilename = [self suggestedFilename];
NSString* suggestedFilenameWithoutExtension = [suggestedFilename stringByDeletingPathExtension];
NSString* suggestedExtension = [self suggestedFileExtension];
NSString* filename = [suggestedFilenameWithoutExtension stringByAppendingPathExtension:suggestedExtension];
NSString* destinationFile = [directoryPath stringByAppendingPathComponent:filename];
int retryCount = 1;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:destinationFile];
while (exists)
{
filename = [suggestedFilenameWithoutExtension stringByAppendingFormat:@" %d", retryCount];
filename = [filename stringByAppendingPathExtension:suggestedExtension];
destinationFile = [directoryPath stringByAppendingPathComponent:filename];
retryCount++;
exists = [[NSFileManager defaultManager] fileExistsAtPath:destinationFile];
}
[self setDestinationPath:destinationFile];
}
// ----------------------------------------------------------------------------
- (NSString*) suggestedFileExtension
// ----------------------------------------------------------------------------
{
return exportFileTypeExtensions[exportSettings.mFileType];
}
// ----------------------------------------------------------------------------
- (NSString*) suggestedFilename
// ----------------------------------------------------------------------------
{
NSRange slashRange = [author rangeOfString:@"/"];
NSString* authorWithoutGroup = nil;
if (slashRange.location == NSNotFound)
authorWithoutGroup = author;
else
authorWithoutGroup = [author substringToIndex:slashRange.location];
authorWithoutGroup = [authorWithoutGroup stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString* titleWithoutSlashes = [title stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
return [NSString stringWithFormat:@"%@ - %@ (song %d).%@", authorWithoutGroup, titleWithoutSlashes, [exportItem subtune], exportFileTypeExtensions[exportSettings.mFileType]];
}
// ----------------------------------------------------------------------------
- (void) setFileName:(NSString*)name
// ----------------------------------------------------------------------------
{
fileName = name;
}
// ----------------------------------------------------------------------------
- (NSString*) fileName
// ----------------------------------------------------------------------------
{
return fileName;
}
// ----------------------------------------------------------------------------
- (void) setDestinationPath:(NSString*)path
// ----------------------------------------------------------------------------
{
destinationPath = path;
[self setFileName:[path lastPathComponent]];
}
// ----------------------------------------------------------------------------
- (PlayerLibSidplay*) player
// ----------------------------------------------------------------------------
{
return player;
}
// ----------------------------------------------------------------------------
- (NSImage*) fileIcon
// ----------------------------------------------------------------------------
{
return fileIcon;
}
// ----------------------------------------------------------------------------
- (void) setFileIcon:(NSImage*)icon
// ----------------------------------------------------------------------------
{
fileIcon = icon;
}
// ----------------------------------------------------------------------------
- (BOOL) exportInProgress
// ----------------------------------------------------------------------------
{
return exportInProgress;
}
// ----------------------------------------------------------------------------
- (BOOL) exportStopped
// ----------------------------------------------------------------------------
{
return exportStopped;
}
// ----------------------------------------------------------------------------
- (void) setExportStopped:(BOOL)stopped
// ----------------------------------------------------------------------------
{
exportStopped = stopped;
}
// ----------------------------------------------------------------------------
- (float) exportProgress
// ----------------------------------------------------------------------------
{
return exportProgress;
}
// ----------------------------------------------------------------------------
- (void) setExportProgress:(float)progress
// ----------------------------------------------------------------------------
{
exportProgress = progress;
}
// ----------------------------------------------------------------------------
- (BOOL) exportProgressIsIndeterminate
// ----------------------------------------------------------------------------
{
return exportProgressIsIndeterminate;
}
// ----------------------------------------------------------------------------
- (void) setExportProgressIsIndeterminate:(BOOL)indeterminate
// ----------------------------------------------------------------------------
{
exportProgressIsIndeterminate = indeterminate;
}
// ----------------------------------------------------------------------------
- (void) startExport
// ----------------------------------------------------------------------------
{
samplesRemaining = exportSettings.mTimeInSeconds * settings.mFrequency;
samplesCompleted = 0;
exportProgress = 0.0f;
[self setExportStopped:NO];
exportInProgress = YES;
if (exportSettings.mFileType == EXPORT_TYPE_MP3)
[NSThread detachNewThreadSelector:@selector(exportUsingLameThread:) toTarget:self withObject:nil];
else if (exportSettings.mFileType == EXPORT_TYPE_PRG)
[self exportUsingPsid64];
else
[NSThread detachNewThreadSelector:@selector(exportUsingExtAudioFileThread:) toTarget:self withObject:nil];
}
// ----------------------------------------------------------------------------
- (void) stopExport
// ----------------------------------------------------------------------------
{
[self setExportStopped:YES];
if (!exportInProgress)
[controller exportFinished:self];
}
// ----------------------------------------------------------------------------
- (void) revealExportFile
// ----------------------------------------------------------------------------
{
if (destinationPath != nil)
{
NSWorkspace* workSpace = [NSWorkspace sharedWorkspace];
[workSpace selectFile:destinationPath inFileViewerRootedAtPath:@""];
}
}
// ----------------------------------------------------------------------------
- (void) exportUsingPsid64
// ----------------------------------------------------------------------------
{
[self setExportProgressIsIndeterminate:YES];
NSString* psid64ExecutablePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"psid64"];
NSMutableArray* psid64Arguments = [NSMutableArray arrayWithCapacity:3];
if (exportSettings.mBlankScreen)
[psid64Arguments addObject:@"-b"];
if (exportSettings.mIncludeStilComment)
[psid64Arguments addObject:@"-g"];
if (exportSettings.mCompressOutputFile)
[psid64Arguments addObject:@"-c"];
[psid64Arguments addObject:@"-v"];
[psid64Arguments addObject:[NSString stringWithFormat:@"-i %d", [exportItem subtune]]];
//[psid64Arguments addObject:[NSString stringWithFormat:@"-r %@", [[SPCollectionUtilities sharedInstance] rootPath]]];
[psid64Arguments addObject:[NSString stringWithFormat:@"-s %@", [[SongLengthDatabase sharedInstance] databasePath]]];
[psid64Arguments addObject:[NSString stringWithFormat:@"-o%@", destinationPath]];
[psid64Arguments addObject:[exportItem path]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(psid64TaskFinished:) name:NSTaskDidTerminateNotification object:nil];
psid64Task = [[NSTask alloc] init];
[psid64Task setLaunchPath:psid64ExecutablePath];
[psid64Task setCurrentDirectoryPath:[[NSBundle mainBundle] resourcePath]];
[psid64Task setArguments:psid64Arguments];
[psid64Task launch];
}
// ----------------------------------------------------------------------------
- (void) psid64TaskFinished:(NSNotification*)aNotification
// ----------------------------------------------------------------------------
{
NSTask* task = (NSTask*) [aNotification object];
if (task != psid64Task)
return;
psid64Task = nil;
NSNumber* creatorCode = [NSNumber numberWithUnsignedLong:'C=64'];
NSNumber* typeCode = [NSNumber numberWithUnsignedLong:'C64F'];
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:creatorCode, NSFileHFSCreatorCode, typeCode, NSFileHFSTypeCode, nil];
[[NSFileManager defaultManager] changeFileAttributes:attributes atPath:destinationPath];
NSImage* icon = [[NSWorkspace sharedWorkspace] iconForFile:destinationPath];
[icon setScalesWhenResized:NO];
[icon setSize:NSMakeSize(32, 32)];
[self setFileIcon:icon];
exportInProgress = NO;
[self setExportStopped:YES];
[controller exportFinished:self];
[self setExportProgressIsIndeterminate:NO];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
// ----------------------------------------------------------------------------
- (void) exportUsingExtAudioFileThread:(id)inObject
// ----------------------------------------------------------------------------
{
OSStatus err = noErr;
[NSThread setThreadPriority:[NSThread threadPriority]+.1];
// create the file
if (outputFileRef == NULL)
{
NSString* directory = [destinationPath stringByDeletingLastPathComponent];
NSString* filename = [[NSString alloc] initWithString:[destinationPath lastPathComponent]];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:destinationPath];
if (exists)
[[NSFileManager defaultManager] removeFileAtPath:destinationPath handler:nil];
FSRef directoryFileRef;
err = FSPathMakeRef((const UInt8*)[directory fileSystemRepresentation], &directoryFileRef, NULL);
// The format in which we render the SID output
inputFormat.mChannelsPerFrame = 1;
inputFormat.mSampleRate = settings.mFrequency;
inputFormat.mFormatID = kAudioFormatLinearPCM;
#if TARGET_RT_LITTLE_ENDIAN
inputFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
#else
inputFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked | kAudioFormatFlagIsBigEndian;
#endif
inputFormat.mBytesPerPacket = sizeof(short) * inputFormat.mChannelsPerFrame;
inputFormat.mFramesPerPacket = 1;
inputFormat.mBytesPerFrame = sizeof(short) * inputFormat.mChannelsPerFrame;
inputFormat.mBitsPerChannel = 16;
// The format for the output file
UInt32 size = sizeof(outputFormat);
outputFormat.mSampleRate = settings.mFrequency;
outputFormat.mChannelsPerFrame = 1;
switch (exportSettings.mFileType)
{
case EXPORT_TYPE_AAC:
outputFormat.mFormatID = kAudioFormatMPEG4AAC;
outputFormat.mFormatFlags = 0;
err = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &size, &outputFormat);
break;
case EXPORT_TYPE_ALAC:
outputFormat.mFormatID = kAudioFormatAppleLossless;
outputFormat.mFormatFlags = 0;
err = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &size, &outputFormat);
break;
case EXPORT_TYPE_AIFF:
default:
outputFormat.mFormatID = kAudioFormatLinearPCM;
outputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsPacked;
outputFormat.mBytesPerPacket = sizeof(short) * outputFormat.mChannelsPerFrame;
outputFormat.mFramesPerPacket = 1;
outputFormat.mBytesPerFrame = sizeof(short) * outputFormat.mChannelsPerFrame;
outputFormat.mBitsPerChannel = 16;
}
err = ExtAudioFileCreateNew(&directoryFileRef, (__bridge CFStringRef)filename, exportAudioFileIDs[exportSettings.mFileType], &outputFormat, NULL, &outputFileRef);
NSImage* icon = [[NSWorkspace sharedWorkspace] iconForFile:destinationPath];
[icon setScalesWhenResized:NO];
[icon setSize:NSMakeSize(32, 32)];
[self performSelectorOnMainThread:@selector(setFileIcon:) withObject:icon waitUntilDone:NO];
err = ExtAudioFileSetProperty(outputFileRef, kExtAudioFileProperty_ClientDataFormat, sizeof(AudioStreamBasicDescription), &inputFormat);
/*
UInt32 size = sizeof(AudioFileID);
AudioFileID audioFileId;
err = ExtAudioFileGetProperty(outputFileRef, kExtAudioFileProperty_AudioFile, &size, &audioFileId);
NSString* year = [releaseInfo substringWithRange:NSMakeRange(0, 4)];
const char* yearCString = [year cStringUsingEncoding:NSISOLatin1StringEncoding];
const char* titleCString = [title cStringUsingEncoding:NSISOLatin1StringEncoding];
const char* authorCString = [author cStringUsingEncoding:NSISOLatin1StringEncoding];
const char* commentCString = "Exported with SIDPLAY/Mac";
UInt32 nameType = 0xa96e616d;
UInt32 artistType = 0xa9415254;
UInt32 dayType = 0xa9646179;
UInt32 commentType = 0xa9636d74;
size = sizeof(CFStringRef);
err = AudioFileSetUserData(audioFileId, nameType , 0, size, (CFStringRef)title);
err = AudioFileSetUserData(audioFileId, nameType , 0, strlen(titleCString) + 1, titleCString);
err = AudioFileSetUserData(audioFileId, artistType, 0, strlen(authorCString) + 1, authorCString);
err = AudioFileSetUserData(audioFileId, dayType, 0, strlen(yearCString) + 1, yearCString);
err = AudioFileSetUserData(audioFileId, commentType, 0, strlen(commentCString) + 1, commentCString);
*/
if (exportSettings.mFileType == EXPORT_TYPE_AAC)
{
size = sizeof(AudioConverterRef);
AudioConverterRef converterRef;
err = ExtAudioFileGetProperty(outputFileRef, kExtAudioFileProperty_AudioConverter, &size, &converterRef);
UInt32 mode = exportSettings.mUseVBR ? kAudioCodecBitRateFormat_VBR : kAudioCodecBitRateFormat_CBR;
err = AudioConverterSetProperty(converterRef, kAudioCodecBitRateFormat, sizeof(mode), &mode);
/*
err = AudioConverterGetPropertyInfo(converterRef, kAudioConverterApplicableEncodeBitRates, &size, NULL);
AudioValueRange* bitRates = (AudioValueRange*) new char[size];
err = AudioConverterGetProperty(converterRef, kAudioConverterApplicableEncodeBitRates, &size, bitRates);
if(err == noErr)
{
ssize_t bitRateCount = size / sizeof(AudioValueRange);
for(int i = 0; i < bitRateCount; i++)
NSLog(@"bitrate %d: %f/%f\n", i, bitRates[i].mMinimum, bitRates[i].mMaximum);
delete[] bitRates;
}
*/
UInt32 bitRate = exportSettings.mBitRate * 1000;
err = AudioConverterSetProperty(converterRef, kAudioConverterEncodeBitRate, sizeof(UInt32), &bitRate);
UInt32 codecQuality = kAudioConverterQuality_Medium;
int quality = exportSettings.mQuality * 4;
switch (quality)
{
case 0:
codecQuality = kAudioConverterQuality_Min;
break;
case 1:
codecQuality = kAudioConverterQuality_Low;
break;
case 2:
codecQuality = kAudioConverterQuality_Medium;
break;
case 3:
codecQuality = kAudioConverterQuality_High;
break;
case 4:
codecQuality = kAudioConverterQuality_Max;
break;
}
err = AudioConverterSetProperty(converterRef, kAudioConverterCodecQuality, sizeof(UInt32), &codecQuality);
}
err = ExtAudioFileWriteAsync(outputFileRef, 0, NULL);
}
const int maxSamplesPerSlice = 64 * 1024;
const int fadeTimeInSamples = exportSettings.mFadeOutTime * settings.mFrequency;
AudioBufferList outputBufferList;
UInt32 renderBufferSize = (maxSamplesPerSlice * inputFormat.mBytesPerFrame);
char* renderBuffer = new char[renderBufferSize];
outputBufferList.mNumberBuffers = inputFormat.mChannelsPerFrame;
outputBufferList.mBuffers[0].mData = renderBuffer;
outputBufferList.mBuffers[0].mDataByteSize = renderBufferSize;
// loop until stopped from an external event, or finished the entire extraction
while (!exportStopped)
{
if (samplesRemaining == 0)
break;
// progress update
NSNumber* progress = [NSNumber numberWithFloat:(float)samplesCompleted / float(samplesCompleted + samplesRemaining)];
[self performSelectorOnMainThread:@selector(exportInProgressNotification:) withObject:progress waitUntilDone:NO];
UInt32 numSamplesThisSlice = samplesRemaining;
if (numSamplesThisSlice > maxSamplesPerSlice)
numSamplesThisSlice = maxSamplesPerSlice;
// write it to the file
if (numSamplesThisSlice > 0)
{
player->fillBuffer(outputBufferList.mBuffers[0].mData, outputBufferList.mBuffers[0].mDataByteSize);
if (exportSettings.mWithFadeOut && (samplesRemaining - numSamplesThisSlice) < fadeTimeInSamples)
{
short* sampleBuffer = (short*) renderBuffer;
for(int i = 0; i < numSamplesThisSlice; i++)
{
if ((samplesRemaining - i) < fadeTimeInSamples)
{
float fadeOutFactor = float(samplesRemaining - i) / float(fadeTimeInSamples);
short sample = fadeOutFactor * sampleBuffer[i];
sampleBuffer[i] = sample;
}
}
}
err = ExtAudioFileWriteAsync(outputFileRef, numSamplesThisSlice, &outputBufferList);
if (err != noErr)
break;
}
samplesRemaining -= numSamplesThisSlice;
samplesCompleted += numSamplesThisSlice;
}
delete[] renderBuffer;
if (outputFileRef != NULL)
ExtAudioFileDispose(outputFileRef);
//NSLog(@"file written!\n");
[self performSelectorOnMainThread:@selector(exportCompletedNotification:)
withObject:(id)[NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]
waitUntilDone:NO];
}
// ----------------------------------------------------------------------------
- (void) exportUsingLameThread:(id)inObject
// ----------------------------------------------------------------------------
{
[NSThread setThreadPriority:[NSThread threadPriority]+.1];
OSStatus err = noErr;
FILE* outputFileHandle = fopen([destinationPath fileSystemRepresentation], "wb");
NSImage* icon = [[NSWorkspace sharedWorkspace] iconForFile:destinationPath];
[icon setScalesWhenResized:NO];
[icon setSize:NSMakeSize(32, 32)];
[self performSelectorOnMainThread:@selector(setFileIcon:) withObject:icon waitUntilDone:NO];
lame_global_flags *lameState;
lameState = lame_init();
lame_set_mode(lameState, MONO);
lame_set_in_samplerate(lameState, settings.mFrequency);
if (exportSettings.mUseVBR)
{
lame_set_VBR(lameState, vbr_default);
lame_set_brate(lameState, exportSettings.mBitRate);
}
else
{
lame_set_VBR(lameState, vbr_off);
lame_set_brate(lameState, exportSettings.mBitRate);
}
int lameQuality = (int) ((1.0f - exportSettings.mQuality) * 9.0f);
lame_set_quality(lameState, lameQuality);
id3tag_init(lameState);
id3tag_add_v2(lameState);
id3tag_set_title(lameState, [title cStringUsingEncoding:NSISOLatin1StringEncoding]);
id3tag_set_artist(lameState, [author cStringUsingEncoding:NSISOLatin1StringEncoding]);
if ([releaseInfo length] > 3)
{
NSString* year = [releaseInfo substringWithRange:NSMakeRange(0, 4)];
id3tag_set_year(lameState, [year cStringUsingEncoding:NSISOLatin1StringEncoding]);
}
id3tag_set_comment(lameState, "Exported with SIDPLAY/Mac");
int rc = lame_init_params(lameState);
const int maxSamplesPerSlice = 64 * 1024;
const int fadeTimeInSamples = exportSettings.mFadeOutTime * settings.mFrequency;
UInt32 renderBufferSize = (maxSamplesPerSlice * sizeof(short));
char* renderBuffer = new char[renderBufferSize];
int mp3BufferSize = (int) (1.25f * maxSamplesPerSlice + 7200);
unsigned char* mp3Buffer = new unsigned char[mp3BufferSize];
while (!exportStopped)
{
if (samplesRemaining == 0)
break;
// progress update
NSNumber* progress = [NSNumber numberWithFloat:(float)samplesCompleted / float(samplesCompleted + samplesRemaining)];
[self performSelectorOnMainThread:@selector(exportInProgressNotification:) withObject:progress waitUntilDone:NO];
UInt32 numSamplesThisSlice = samplesRemaining;
if (numSamplesThisSlice > maxSamplesPerSlice)
numSamplesThisSlice = maxSamplesPerSlice;
// write it to the file
if (numSamplesThisSlice > 0)
{
player->fillBuffer(renderBuffer, renderBufferSize);
if (exportSettings.mWithFadeOut && (samplesRemaining - numSamplesThisSlice) < fadeTimeInSamples)
{
short* sampleBuffer = (short*) renderBuffer;
for(int i = 0; i < numSamplesThisSlice; i++)
{
if ((samplesRemaining - i) < fadeTimeInSamples)
{
float fadeOutFactor = float(samplesRemaining - i) / float(fadeTimeInSamples);
short sample = fadeOutFactor * sampleBuffer[i];
sampleBuffer[i] = sample;
}
}
}
rc = lame_encode_buffer(lameState, (short int*)renderBuffer, (short int*)renderBuffer, numSamplesThisSlice, mp3Buffer, mp3BufferSize);
if (rc > 0)
fwrite(mp3Buffer, 1, rc, outputFileHandle);
}
samplesRemaining -= numSamplesThisSlice;
samplesCompleted += numSamplesThisSlice;
}
rc = lame_encode_flush(lameState, mp3Buffer, mp3BufferSize);
fwrite(mp3Buffer, 1, rc, outputFileHandle);
lame_close(lameState);
delete[] renderBuffer;
delete[] mp3Buffer;
if (outputFileHandle != NULL)
fclose(outputFileHandle);
//NSLog(@"file written using lame!\n");
[self performSelectorOnMainThread:@selector(exportCompletedNotification:)
withObject:(id)[NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]
waitUntilDone:NO];
}
// ----------------------------------------------------------------------------
- (void) exportCompletedNotification:(NSError *)error
// ----------------------------------------------------------------------------
{
//NSLog(@"export stopped with error: %@\n", error);
exportInProgress = NO;
[self setExportStopped:YES];
[controller exportFinished:self];
}
// ----------------------------------------------------------------------------
- (void) exportInProgressNotification:(id)progress
// ----------------------------------------------------------------------------
{
[self setExportProgress:[progress floatValue]];
}
@end
@implementation SPExportItem
// ----------------------------------------------------------------------------
- (id) initWithPath:(NSString*)filePath andTitle:(NSString*)titleString andAuthor:(NSString*)authorString andSubtune:(int)subtuneIndex andLoopCount:(int)loops
// ----------------------------------------------------------------------------
{
self = [super init];
if (self != nil)
{
path = filePath;
title = titleString;
author = authorString;
subtune = subtuneIndex;
loopCount = loops;
exporter = nil;
}
return self;
}
// ----------------------------------------------------------------------------
- (NSString*) path
// ----------------------------------------------------------------------------
{
return path;
}
// ----------------------------------------------------------------------------
- (void) setPath:(NSString*)filePath
// ----------------------------------------------------------------------------
{
path = filePath;
}
// ----------------------------------------------------------------------------
- (NSString*) title
// ----------------------------------------------------------------------------
{
return title;
}
// ----------------------------------------------------------------------------
- (void) setTitle:(NSString*)titleString
// ----------------------------------------------------------------------------
{
title = titleString;
}
// ----------------------------------------------------------------------------
- (NSString*) author
// ----------------------------------------------------------------------------
{
return author;
}
// ----------------------------------------------------------------------------
- (void) setAuthor:(NSString*)authorString
// ----------------------------------------------------------------------------
{
author = authorString;
}
// ----------------------------------------------------------------------------
- (int) subtune
// ----------------------------------------------------------------------------
{
return subtune;
}
// ----------------------------------------------------------------------------
- (void) setSubtune:(int)subtuneIndex
// ----------------------------------------------------------------------------
{
subtune = subtuneIndex;
}
// ----------------------------------------------------------------------------
- (int) loopCount
// ----------------------------------------------------------------------------
{
return loopCount;
}
// ----------------------------------------------------------------------------
- (void) setLoopCount:(int)loops
// ----------------------------------------------------------------------------
{
loopCount = loops;
}
// ----------------------------------------------------------------------------
- (SPExporter*) exporter
// ----------------------------------------------------------------------------
{
return exporter;
}
// ----------------------------------------------------------------------------
- (void) setExporter:(SPExporter*)theExporter
// ----------------------------------------------------------------------------
{
exporter = theExporter;
}
@end