cog/Playlist/PlaylistLoader.m

563 lines
15 KiB
Matlab
Raw Normal View History

2007-03-07 01:26:50 +00:00
//
// PlaylistLoader.m
// Cog
//
// Created by Vincent Spader on 3/05/07.
// Copyright 2007 Vincent Spader All rights reserved.
//
#include <objc/runtime.h>
#include <mach/semaphore.h>
2007-03-07 01:26:50 +00:00
#import "PlaylistLoader.h"
#import "PlaylistController.h"
#import "PlaylistEntry.h"
#import "FilePlaylistEntry.h"
#import "AppController.h"
2007-03-07 01:26:50 +00:00
#import "NSFileHandle+CreateFile.h"
#import "CogAudio/AudioPlayer.h"
#import "CogAudio/AudioContainer.h"
#import "CogAudio/AudioPropertiesReader.h"
#import "CogAudio/AudioMetadataReader.h"
#import "XMlContainer.h"
#import "NSData+MD5.h"
#import "Logging.h"
2007-03-07 01:26:50 +00:00
@implementation PlaylistLoader
- (id)init
{
self = [super init];
if (self)
{
[self initDefaults];
queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];
}
return self;
}
- (void)initDefaults
{
NSDictionary *defaultsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], @"readCueSheetsInFolders",
nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDictionary];
}
2007-03-07 01:26:50 +00:00
- (BOOL)save:(NSString *)filename
{
NSString *ext = [filename pathExtension];
if ([ext isEqualToString:@"pls"])
{
return [self save:filename asType:kPlaylistPls];
}
else
{
return [self save:filename asType:kPlaylistM3u];
}
}
- (BOOL)save:(NSString *)filename asType:(PlaylistType)type
{
if (type == kPlaylistM3u)
{
return [self saveM3u:filename];
}
else if (type == kPlaylistPls)
{
return [self savePls:filename];
}
else if (type == kPlaylistXml)
{
return [self saveXml:filename];
}
2007-03-07 01:26:50 +00:00
return NO;
}
- (NSString *)relativePathFrom:(NSString *)filename toURL:(NSURL *)entryURL
2007-03-07 01:26:50 +00:00
{
NSString *basePath = [[[filename stringByStandardizingPath] stringByDeletingLastPathComponent] stringByAppendingString:@"/"];
if ([entryURL isFileURL]) {
2007-03-07 01:26:50 +00:00
//We want relative paths.
NSMutableString *entryPath = [[[entryURL path] stringByStandardizingPath] mutableCopy];
2007-03-07 01:26:50 +00:00
[entryPath replaceOccurrencesOfString:basePath withString:@"" options:(NSAnchoredSearch | NSLiteralSearch | NSCaseInsensitiveSearch) range:NSMakeRange(0, [entryPath length])];
if ([entryURL fragment])
{
[entryPath appendString:@"#"];
[entryPath appendString:[entryURL fragment]];
}
2007-03-07 01:26:50 +00:00
return entryPath;
}
else {
//Write [entryURL absoluteString] to file
return [entryURL absoluteString];
}
}
- (BOOL)saveM3u:(NSString *)filename
{
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filename createFile:YES];
2007-03-07 01:26:50 +00:00
if (!fileHandle) {
ALog(@"Error saving m3u!");
return NO;
2007-03-07 01:26:50 +00:00
}
[fileHandle truncateFileAtOffset:0];
for (PlaylistEntry *pe in [playlistController arrangedObjects])
2007-03-07 01:26:50 +00:00
{
2008-02-20 00:44:40 +00:00
NSString *path = [self relativePathFrom:filename toURL:[pe URL]];
2007-03-07 01:26:50 +00:00
[fileHandle writeData:[[path stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[fileHandle closeFile];
2007-03-07 01:26:50 +00:00
return YES;
}
- (BOOL)savePls:(NSString *)filename
{
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filename createFile:YES];
2007-03-07 01:26:50 +00:00
if (!fileHandle) {
return NO;
}
[fileHandle truncateFileAtOffset:0];
[fileHandle writeData:[[NSString stringWithFormat:@"[playlist]\nnumberOfEntries=%lu\n\n",(unsigned long)[[playlistController content] count]] dataUsingEncoding:NSUTF8StringEncoding]];
2007-03-07 01:26:50 +00:00
int i = 1;
for (PlaylistEntry *pe in [playlistController arrangedObjects])
2007-03-07 01:26:50 +00:00
{
2008-02-20 00:44:40 +00:00
NSString *path = [self relativePathFrom:filename toURL:[pe URL]];
2007-03-07 01:26:50 +00:00
NSString *entry = [NSString stringWithFormat:@"File%i=%@\n",i,path];
[fileHandle writeData:[entry dataUsingEncoding:NSUTF8StringEncoding]];
i++;
2007-03-07 01:26:50 +00:00
}
[fileHandle writeData:[@"\nVERSION=2" dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
2007-03-07 01:26:50 +00:00
return YES;
}
NSMutableDictionary * dictionaryWithPropertiesOfObject(id obj, NSArray * filterList)
{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
Class class = [obj class];
do {
unsigned count;
objc_property_t *properties = class_copyPropertyList(class, &count);
for (int i = 0; i < count; i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
if ([filterList containsObject:key]) continue;
Class classObject = NSClassFromString([key capitalizedString]);
if (classObject) {
id subObj = dictionaryWithPropertiesOfObject([obj valueForKey:key], filterList);
[dict setObject:subObj forKey:key];
}
else
{
id value = [obj valueForKey:key];
if(value) [dict setObject:value forKey:key];
}
}
free(properties);
2014-09-17 01:27:14 +00:00
if (count) break;
class = [class superclass];
} while (class);
return dict;
}
- (BOOL)saveXml:(NSString *)filename
{
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filename createFile:YES];
if (!fileHandle) {
return NO;
}
[fileHandle truncateFileAtOffset:0];
2014-12-04 06:34:13 +00:00
NSArray * filterList = [NSArray arrayWithObjects:@"display", @"length", @"path", @"filename", @"status", @"statusMessage", @"spam", @"lengthText", @"positionText", @"stopAfter", @"shuffleIndex", @"index", @"current", @"queued", @"currentPosition", @"queuePosition", @"error", @"removed", @"URL", @"albumArt", nil];
NSMutableDictionary * albumArtSet = [[NSMutableDictionary alloc] init];
NSMutableArray * topLevel = [[NSMutableArray alloc] init];
for (PlaylistEntry *pe in [playlistController arrangedObjects])
{
BOOL error = [pe error];
NSMutableDictionary * dict = dictionaryWithPropertiesOfObject(pe, filterList);
NSString *path = [self relativePathFrom:filename toURL:[pe URL]];
[dict setObject:path forKey:@"URL"];
NSData * albumArt = [dict objectForKey:@"albumArtInternal"];
if (albumArt)
{
[dict removeObjectForKey:@"albumArtInternal"];
NSString * hash = [albumArt MD5];
if (![albumArtSet objectForKey:hash])
[albumArtSet setObject:albumArt forKey:hash];
[dict setObject:hash forKey:@"albumArt"];
}
if (error)
[dict removeObjectForKey:@"metadataLoaded"];
[topLevel addObject:dict];
}
NSMutableArray * queueList = [[NSMutableArray alloc] init];
for (PlaylistEntry *pe in [playlistController queueList])
{
[queueList addObject:[NSNumber numberWithInt:pe.index]];
}
NSDictionary * dictionary = [NSDictionary dictionaryWithObjectsAndKeys:albumArtSet, @"albumArt", queueList, @"queue", topLevel, @"items", nil];
NSData * data = [NSPropertyListSerialization dataWithPropertyList:dictionary format:NSPropertyListXMLFormat_v1_0 options:0 error:0];
[fileHandle writeData:data];
[fileHandle closeFile];
return YES;
}
- (NSArray *)fileURLsAtPath:(NSString *)path
{
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray *urls = [NSMutableArray array];
NSArray *subpaths = [manager subpathsAtPath:path];
2008-03-01 15:04:46 +00:00
for (NSString *subpath in subpaths)
{
NSString *absoluteSubpath = [NSString pathWithComponents:[NSArray arrayWithObjects:path,subpath,nil]];
BOOL isDir;
if ( [manager fileExistsAtPath:absoluteSubpath isDirectory:&isDir] && isDir == NO)
{
if ([[absoluteSubpath pathExtension] caseInsensitiveCompare:@"cue"] != NSOrderedSame ||
[[NSUserDefaults standardUserDefaults] boolForKey:@"readCueSheetsInFolders"])
{
[urls addObject:[NSURL fileURLWithPath:absoluteSubpath]];
}
}
}
return urls;
}
- (NSArray*)insertURLs:(NSArray *)urls atIndex:(int)index sort:(BOOL)sort
{
2007-05-28 14:58:08 +00:00
NSMutableSet *uniqueURLs = [NSMutableSet set];
NSMutableArray *expandedURLs = [NSMutableArray array];
2007-10-19 02:23:10 +00:00
NSMutableArray *containedURLs = [NSMutableArray array];
NSMutableArray *fileURLs = [NSMutableArray array];
2007-05-28 14:58:08 +00:00
NSMutableArray *validURLs = [NSMutableArray array];
NSDictionary *xmlData = nil;
if (!urls)
return [NSArray array];
if (index < 0)
index = 0;
NSURL *url;
for (url in urls)
{
if ([url isFileURL]) {
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path] isDirectory:&isDir])
{
if (isDir == YES)
{
//Get subpaths
2007-05-28 14:58:08 +00:00
[expandedURLs addObjectsFromArray:[self fileURLsAtPath:[url path]]];
}
else
{
2007-05-28 14:58:08 +00:00
[expandedURLs addObject:url];
}
}
}
else
{
//Non-file URL..
2007-05-28 14:58:08 +00:00
[expandedURLs addObject:url];
}
}
2007-10-19 02:23:10 +00:00
DLog(@"Expanded urls: %@", expandedURLs);
2007-05-28 14:58:08 +00:00
NSArray *sortedURLs;
if (sort == YES)
{
sortedURLs = [expandedURLs sortedArrayUsingSelector:@selector(finderCompare:)];
// sortedURLs = [expandedURLs sortedArrayUsingSelector:@selector(compareTrackNumbers:)];
2007-05-28 14:58:08 +00:00
}
else
{
2009-02-28 17:41:37 +00:00
sortedURLs = expandedURLs;
2007-05-28 14:58:08 +00:00
}
for (url in sortedURLs)
2007-05-28 14:58:08 +00:00
{
2007-10-20 03:22:13 +00:00
//Container vs non-container url
if ([[self acceptableContainerTypes] containsObject:[[url pathExtension] lowercaseString]]) {
2007-10-20 03:22:13 +00:00
[containedURLs addObjectsFromArray:[AudioContainer urlsForContainerURL:url]];
2007-10-20 03:22:13 +00:00
//Make sure the container isn't added twice.
[uniqueURLs addObject:url];
2007-05-28 14:58:08 +00:00
}
else if ([[[url pathExtension] lowercaseString] isEqualToString:@"xml"])
{
xmlData = [XmlContainer entriesForContainerURL:url];
}
2007-05-28 14:58:08 +00:00
else
{
2007-10-19 02:23:10 +00:00
[fileURLs addObject:url];
2007-05-28 14:58:08 +00:00
}
}
DLog(@"File urls: %@", fileURLs);
2007-10-19 02:23:10 +00:00
DLog(@"Contained urls: %@", containedURLs);
2007-10-19 02:23:10 +00:00
for (url in fileURLs)
{
if (![[AudioPlayer schemes] containsObject:[url scheme]])
continue;
NSString *ext = [[url pathExtension] lowercaseString];
//Need a better way to determine acceptable file types than basing it on extensions.
if ([url isFileURL] && ![[AudioPlayer fileTypes] containsObject:ext])
continue;
if (![uniqueURLs containsObject:url])
{
[validURLs addObject:url];
[uniqueURLs addObject:url];
}
}
2007-10-19 02:23:10 +00:00
DLog(@"Valid urls: %@", validURLs);
2007-10-19 02:23:10 +00:00
for (url in containedURLs)
2007-10-19 02:23:10 +00:00
{
if (![[AudioPlayer schemes] containsObject:[url scheme]])
continue;
//Need a better way to determine acceptable file types than basing it on extensions.
if ([url isFileURL] && ![[AudioPlayer fileTypes] containsObject:[[url pathExtension] lowercaseString]])
2007-10-19 02:23:10 +00:00
continue;
[validURLs addObject:url];
}
//Create actual entries
int count = (int) [validURLs count];
if (xmlData) count += [[xmlData objectForKey:@"entries"] count];
int i = 0;
NSMutableArray *entries = [NSMutableArray arrayWithCapacity:count];
for (NSURL *url in validURLs)
{
PlaylistEntry *pe;
if ([url isFileURL])
pe = [[FilePlaylistEntry alloc] init];
else
pe = [[PlaylistEntry alloc] init];
pe.URL = url;
2008-02-23 19:46:23 +00:00
pe.index = index+i;
pe.title = [[url path] lastPathComponent];
pe.queuePosition = -1;
[entries addObject:pe];
++i;
}
int j = index + i;
if (xmlData)
{
for (NSDictionary *entry in [xmlData objectForKey:@"entries"])
{
PlaylistEntry *pe;
if ([[entry objectForKey:@"URL"] isFileURL])
pe = [[FilePlaylistEntry alloc] init];
else
pe = [[PlaylistEntry alloc] init];
[pe setValuesForKeysWithDictionary:entry];
pe.index = index+i;
pe.queuePosition = -1;
[entries addObject:pe];
++i;
}
}
NSIndexSet *is = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index, [entries count])];
[playlistController insertObjects:entries atArrangedObjectIndexes:is];
if (xmlData && [[xmlData objectForKey:@"queue"] count])
{
[playlistController emptyQueueList:self];
i = 0;
for (NSNumber *index in [xmlData objectForKey:@"queue"])
{
int indexVal = [index intValue] + j;
PlaylistEntry *pe = [entries objectAtIndex:indexVal];
pe.queuePosition = i;
pe.queued = YES;
[[playlistController queueList] addObject:pe];
++i;
}
}
//Clear the selection
[playlistController setSelectionIndexes:[NSIndexSet indexSet]];
[self performSelectorInBackground:@selector(loadInfoForEntries:) withObject:entries];
return entries;
}
- (void)loadInfoForEntries:(NSArray *)entries
{
long batchCount = ([entries count] / 16) + ([entries count] % 16 ? 1 : 0);
NSMutableArray *array = [[NSMutableArray alloc] init];
long i;
for (i = 0; i < batchCount; ++i)
{
[array addObject:[[NSMutableArray alloc] init]];
}
i = 0;
for (PlaylistEntry *pe in entries)
{
if ([pe metadataLoaded]) continue;
[[array objectAtIndex:i / 16] addObject:pe];
++i;
}
if (!i) return;
semaphore_t info_sem;
semaphore_create( mach_task_self(), &info_sem, SYNC_POLICY_FIFO, (int) -i + 1 );
__block semaphore_t weak_sem = info_sem;
for (NSArray *a in array)
{
if (![a count]) continue;
__block NSArray *weakA = a;
2016-07-02 09:58:38 +00:00
NSBlockOperation *op = [[NSBlockOperation alloc] init];
[op addExecutionBlock:^{
for (PlaylistEntry *pe in weakA)
{
__block PlaylistEntry *weakPe = pe;
__block NSMutableDictionary *entryInfo = [NSMutableDictionary dictionaryWithCapacity:20];
NSDictionary *entryProperties = [AudioPropertiesReader propertiesForURL:pe.URL];
if (entryProperties == nil)
continue;
[entryInfo addEntriesFromDictionary:entryProperties];
[entryInfo addEntriesFromDictionary:[AudioMetadataReader metadataForURL:pe.URL]];
dispatch_async(dispatch_get_main_queue(), ^{
[weakPe setMetadata:entryInfo];
semaphore_signal(weak_sem);
});
}
}];
[queue addOperation:op];
}
[queue waitUntilAllOperationsAreFinished];
semaphore_wait(info_sem);
semaphore_destroy(mach_task_self(), info_sem);
[playlistController performSelectorOnMainThread:@selector(updateTotalTime) withObject:nil waitUntilDone:NO];
}
- (void)clear:(id)sender
{
[playlistController clear:sender];
}
- (NSArray*)addURLs:(NSArray *)urls sort:(BOOL)sort
{
return [self insertURLs:urls atIndex:(int)[[playlistController content] count] sort:sort];
}
- (NSArray*)addURL:(NSURL *)url
{
return [self insertURLs:[NSArray arrayWithObject:url] atIndex:(int)[[playlistController content] count] sort:NO];
}
- (NSArray *)acceptableFileTypes
{
return [[self acceptableContainerTypes] arrayByAddingObjectsFromArray:[AudioPlayer fileTypes]];
}
- (NSArray *)acceptablePlaylistTypes
{
return [NSArray arrayWithObjects:@"m3u", @"pls", nil];
}
- (NSArray *)acceptableContainerTypes
2007-03-07 01:26:50 +00:00
{
return [AudioPlayer containerTypes];
2007-03-07 01:26:50 +00:00
}
2009-02-28 22:22:33 +00:00
- (void)willInsertURLs:(NSArray*)urls origin:(URLOrigin)origin
{
2009-02-28 22:22:33 +00:00
[playlistController willInsertURLs:urls origin:origin];
}
2009-02-28 22:22:33 +00:00
- (void)didInsertURLs:(NSArray*)urls origin:(URLOrigin)origin
{
2009-02-28 22:22:33 +00:00
[playlistController didInsertURLs:urls origin:origin];
}
2007-03-07 01:26:50 +00:00
@end