diff --git a/Classes/AppDelegate.swift b/Classes/AppDelegate.swift index 10e7e79..d666719 100644 --- a/Classes/AppDelegate.swift +++ b/Classes/AppDelegate.swift @@ -236,13 +236,13 @@ extension AppDelegate { } } - @objc(items) func items() -> [SBQueueItem] { + @objc(items) func items() -> [QueueItem] { let queue = QueueController.shared let indexes = IndexSet(integersIn: 0.. Bool in return item.status != .completed && item.status != .failed @@ -205,29 +208,29 @@ class Queue { //MARK: Item management - func append(_ item: SBQueueItem) { + func append(_ item: QueueItem) { arrayQueue.sync { items.append(item) } } - func item(at index: Int) -> SBQueueItem { - var result: SBQueueItem? + func item(at index: Int) -> QueueItem { + var result: QueueItem? arrayQueue.sync { result = items[index] } return result! } - func items(at indexes: IndexSet) -> [SBQueueItem] { - var result: [SBQueueItem] = Array() + func items(at indexes: IndexSet) -> [QueueItem] { + var result: [QueueItem] = Array() arrayQueue.sync { result = items.enumerated().filter { indexes.contains($0.offset) == true } .map { $0.element } } return result } - func index(of item: SBQueueItem) -> Int { + func index(of item: QueueItem) -> Int { var index = -1 arrayQueue.sync { index = items.firstIndex(of: item) ?? -1 @@ -235,7 +238,7 @@ class Queue { return index } - func indexesOfItems(with status: SBQueueItemStatus) -> IndexSet { + func indexesOfItems(with status: QueueItem.Status) -> IndexSet { var indexes: [Int] = Array() arrayQueue.sync { indexes = items.enumerated().filter { $0.element.status == status } .map { $0.offset } @@ -243,7 +246,7 @@ class Queue { return IndexSet(indexes) } - func insert(_ item: SBQueueItem, at index: Int) { + func insert(_ item: QueueItem, at index: Int) { arrayQueue.sync { items.insert(item, at: index) } @@ -261,7 +264,7 @@ class Queue { } } - func remove(_ item: SBQueueItem) { + func remove(_ item: QueueItem) { arrayQueue.sync { if let index = items.firstIndex(of: item) { items.remove(at: index) diff --git a/Classes/QueueAction.swift b/Classes/QueueAction.swift index e26c608..c669963 100644 --- a/Classes/QueueAction.swift +++ b/Classes/QueueAction.swift @@ -8,22 +8,34 @@ import Foundation import MP42Foundation -/// SBQueue actions protocol, actions can be run by the queue's items. -//@objc(SBQueueActionProtocol) protocol QueueActionProtocol: NSSecureCoding { -// @objc func runAction(_ item: SBQueueItem) -> Bool -// @objc var localizedDescription: String { get } -//} +@objc enum QueueActionType: Int { + case pre + case post +} + +/** + * Queue actions protocol, actions can be run by + * the queue's items. + */ +@objc protocol QueueActionProtocol: NSSecureCoding { + + func runAction(_ item: QueueItem) -> Bool + + var localizedDescription: String { get } + + var type: QueueActionType { get } +} /// An action to remove existing metadata. -@objc(SBQueueClearExistingMetadataAction) class QueueClearExistingMetadataAction: NSObject, SBQueueActionProtocol { +@objc(SBQueueClearExistingMetadataAction) class QueueClearExistingMetadataAction: NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Clearing Metadata", comment: "Action localized description.") } override var description: String { return NSLocalizedString("Clear Metadata", comment: "Action description.") } @objc override init() {} - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { if let metadata = item.mp4File?.metadata { let dataTypes: UInt = MP42MetadataItemDataType.string.rawValue | MP42MetadataItemDataType.stringArray.rawValue | MP42MetadataItemDataType.bool.rawValue | MP42MetadataItemDataType.integer.rawValue | MP42MetadataItemDataType.integerArray.rawValue | MP42MetadataItemDataType.date.rawValue | MP42MetadataItemDataType.image.rawValue @@ -39,15 +51,15 @@ import MP42Foundation } /// An action that set a formatted file name. -@objc(SBQueueSetOutputFilenameAction) class QueueSetOutputFilenameAction: NSObject, SBQueueActionProtocol { +@objc(SBQueueSetOutputFilenameAction) class QueueSetOutputFilenameAction: NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Setting Name", comment: "Action localized description.") } override var description: String { return NSLocalizedString("Set Name", comment: "Action description.") } @objc override init() {} - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { if let formattedName = item.mp4File?.formattedFileName() { let pathExtension = item.destURL.pathExtension let destURL = item.destURL.deletingLastPathComponent().appendingPathComponent(formattedName).appendingPathExtension(pathExtension) @@ -63,9 +75,9 @@ import MP42Foundation } /// An action that search in the item source directory for additionals srt subtitles. -@objc(SBQueueSubtitlesAction) class QueueSubtitlesAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueSubtitlesAction) class QueueSubtitlesAction : NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Loading subtitles", comment: "Action localized description.") } override var description: String { return NSLocalizedString("Load Subtitles", comment: "Action description.") } @@ -92,7 +104,7 @@ import MP42Foundation return importers } - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { let subtitlesImporters = loadExternalSubtitles(url: item.fileURL) for importer in subtitlesImporters { @@ -113,7 +125,7 @@ import MP42Foundation } /// An action that applies a preset to the item. -@objc(SBQueueSetAction) class QueueSetAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueSetAction) class QueueSetAction : NSObject, QueueActionProtocol { private let preset: MetadataPreset @@ -121,11 +133,11 @@ import MP42Foundation self.preset = preset.copy() as! MetadataPreset } - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return String.localizedStringWithFormat(NSLocalizedString("Applying %@ preset", comment: "Action localized description."), preset.title) } override var description: String { return String.localizedStringWithFormat(NSLocalizedString("Apply %@ preset", comment: "Action description"), preset.title) } - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { guard let metadata = item.mp4File?.metadata else { return false } let dataTypes: UInt = MP42MetadataItemDataType.string.rawValue | MP42MetadataItemDataType.stringArray.rawValue | MP42MetadataItemDataType.bool.rawValue | MP42MetadataItemDataType.integer.rawValue | @@ -192,7 +204,7 @@ extension Array where Element == Artwork { } /// An action that fetches metadata online. -@objc(SBQueueMetadataAction) class QueueMetadataAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueMetadataAction) class QueueMetadataAction : NSObject, QueueActionProtocol { private let movieLanguage: String private let movieProvider: String @@ -202,7 +214,7 @@ extension Array where Element == Artwork { private let preferredArtwork: ArtworkType - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Searching metadata", comment: "Action localized description.") } override var description: String { return NSLocalizedString("Search Metadata", comment: "Action description.") } @@ -283,7 +295,7 @@ extension Array where Element == Artwork { return nil } - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { if let file = item.mp4File { let searchTerms = file.extractSearchTerms(fallbackURL: item.fileURL) if let metadata = searchMetadata(terms: searchTerms) { @@ -333,15 +345,15 @@ extension Array where Element == Artwork { } /// An action that organize the item tracks' groups. -@objc(SBQueueOrganizeGroupsAction) class QueueOrganizeGroupsAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueOrganizeGroupsAction) class QueueOrganizeGroupsAction : NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Organizing groups", comment: "Organize Groups action local description") } override var description: String { return NSLocalizedString("Organize Groups", comment: "Organize Groups action description") } @objc override init() {} - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { item.mp4File?.organizeAlternateGroups() item.mp4File?.inferMediaCharacteristics() return true @@ -356,15 +368,15 @@ extension Array where Element == Artwork { } /// An action that fix the item tracks' fallbacks. -@objc(SBQueueFixFallbacksAction) class QueueFixFallbacksAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueFixFallbacksAction) class QueueFixFallbacksAction : NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Fixing Fallbacks", comment: "Action localized description.") } override var description: String { return NSLocalizedString("Fix Fallbacks", comment: "Action description.") } @objc override init() {} - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { item.mp4File?.setAutoFallback() return true } @@ -378,9 +390,9 @@ extension Array where Element == Artwork { } /// An action that set unknown language tracks to preferred one. -@objc(SBQueueSetLanguageAction) class QueueSetLanguageAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueSetLanguageAction) class QueueSetLanguageAction : NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Setting tracks language", comment: "Set Language action local description") } override var description: String { return NSLocalizedString("Set tracks language", comment: "Set Language action description") } @@ -390,7 +402,7 @@ extension Array where Element == Artwork { self.language = language } - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { if let tracks = item.mp4File?.tracks { for track in tracks { if track.language == "und" { @@ -416,15 +428,15 @@ extension Array where Element == Artwork { } /// An action that remove the tracks names. -@objc(SBQueueClearTrackNameAction) class QueueClearTrackNameAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueClearTrackNameAction) class QueueClearTrackNameAction : NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Clearing tracks names", comment: "Action localized description") } override var description: String { return NSLocalizedString("Clear tracks names", comment: "Action description") } @objc override init() {} - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { if let tracks = item.mp4File?.tracks { for track in tracks { track.name = "" @@ -451,9 +463,9 @@ extension Array where Element == Artwork { } /// An action that set the video track color space. -@objc(SBQueueColorSpaceAction) class QueueColorSpaceAction : NSObject, SBQueueActionProtocol { +@objc(SBQueueColorSpaceAction) class QueueColorSpaceAction : NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .pre } + var type: QueueActionType { return .pre } var localizedDescription: String { return NSLocalizedString("Setting color space", comment: "Set track color space action local description") } override var description: String { return NSLocalizedString("Set color space", comment: "Set track color space action description") } @@ -490,7 +502,7 @@ extension Array where Element == Artwork { } } - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { if let tracks = item.mp4File?.tracks(withMediaType: kMP42MediaType_Video) as? [MP42VideoTrack] { for track in tracks { if track.format == kMP42VideoCodecType_H264 || @@ -523,15 +535,15 @@ extension Array where Element == Artwork { } -@objc(SBQueueOptimizeAction) class QueueOptimizeAction: NSObject, SBQueueActionProtocol { +@objc(SBQueueOptimizeAction) class QueueOptimizeAction: NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .post } + var type: QueueActionType { return .post } var localizedDescription: String { return NSLocalizedString("Optimizing", comment: "Action localized description.") } override var description: String { return NSLocalizedString("Optimize", comment: "Action description.") } @objc override init() {} - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { return item.mp4File?.optimize() ?? false } @@ -540,15 +552,15 @@ extension Array where Element == Artwork { static var supportsSecureCoding: Bool { return true } } -@objc(SBQueueSendToiTunesAction) class QueueSendToiTunesAction: NSObject, SBQueueActionProtocol { +@objc(SBQueueSendToiTunesAction) class QueueSendToiTunesAction: NSObject, QueueActionProtocol { - var type: SBQueueActionType { return .post } + var type: QueueActionType { return .post } var localizedDescription: String { return NSLocalizedString("Sending to iTunes", comment: "Action localized description.") } override var description: String { return NSLocalizedString("Send to iTunes", comment: "Action description.") } @objc override init() {} - func runAction(_ item: SBQueueItem) -> Bool { + func runAction(_ item: QueueItem) -> Bool { let workspace = NSWorkspace.shared if let appPath = workspace.fullPath(forApplication: "iTunes") { return workspace.openFile(item.destURL.path, withApplication: appPath) diff --git a/Classes/QueueController.swift b/Classes/QueueController.swift index 7cf74af..6991437 100644 --- a/Classes/QueueController.swift +++ b/Classes/QueueController.swift @@ -167,14 +167,14 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, try queue.saveToDisk() } - internal func edit(item: SBQueueItem) { + internal func edit(item: QueueItem) { let originalStatus = item.status - item.status = SBQueueItemStatus.working + item.status = .working updateUI() DispatchQueue.global().async { - if originalStatus != SBQueueItemStatus.completed { + if originalStatus != .completed { do { try item.prepare() } catch { @@ -187,7 +187,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, DispatchQueue.main.async { do { var doc: Document? - if originalStatus == SBQueueItemStatus.completed { + if originalStatus == .completed { try doc = Document(contentsOf: item.destURL, ofType: "") } else if let mp4 = item.mp4File { doc = Document(mp4: mp4) @@ -214,10 +214,25 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, //MARK: Items creation - /// Creates a new SBQueueItem from an NSURL, + private func destination(for url: URL) -> URL { + let value = try? url.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey]) + + if let destination = prefs.destination { + return destination.appendingPathComponent(url.lastPathComponent).deletingPathExtension().appendingPathExtension(prefs.fileType) + } else if let type = value?.typeIdentifier, UTTypeConformsTo(type as CFString, "public.mpeg-4" as CFString) { + return url + } else { + return url.deletingPathExtension().appendingPathExtension(prefs.fileType) + } + + } + + /// Creates a new QueueItem from an NSURL, /// and adds the current actions to it. - private func createItem(url: URL) -> SBQueueItem { - let item = SBQueueItem(url: url) + private func createItem(url: URL) -> QueueItem { + + let destURL = destination(for: url) + let item = QueueItem(fileURL: url, destination: destURL) if prefs.clearExistingMetadata { item.addAction(QueueClearExistingMetadataAction()) @@ -256,16 +271,6 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, item.addAction(QueueSendToiTunesAction()) } - let value = try? url.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey]) - - if let destination = prefs.destination { - item.destURL = destination.appendingPathComponent(url.lastPathComponent).deletingPathExtension().appendingPathExtension(prefs.fileType) - } else if let type = value?.typeIdentifier, UTTypeConformsTo(type as CFString, "public.mpeg-4" as CFString) { - item.destURL = url - } else { - item.destURL = url.deletingPathExtension().appendingPathExtension(prefs.fileType) - } - return item } @@ -283,16 +288,16 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - func items(at indexes: IndexSet) -> [SBQueueItem] { + func items(at indexes: IndexSet) -> [QueueItem] { return queue.items(at: indexes) } - /// Adds a SBQueueItem to the queue - func add(_ item: SBQueueItem) { + /// Adds a QueueItem to the queue + func add(_ item: QueueItem) { insert(items: [item], at: IndexSet(integer: IndexSet.Element(queue.count))) } - func add(_ item: SBQueueItem, applyPreset: Bool) { + func add(_ item: QueueItem, applyPreset: Bool) { //WHY APPLY PRESET? if prefs.optimize { item.addAction(QueueOptimizeAction()) @@ -300,14 +305,14 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, add(item) } - private func add(_ items: [SBQueueItem], at index: Int) { + private func add(_ items: [QueueItem], at index: Int) { let indexes = IndexSet(integersIn: index ..< (index + items.count)) insert(items: items, at: indexes) } - /// Adds an array of SBQueueItem to the queue. + /// Adds an array of QueueItem to the queue. /// Implements the undo manager. - func insert(items: [SBQueueItem], at indexes: IndexSet) { + func insert(items: [QueueItem], at indexes: IndexSet) { if items.isEmpty { return } guard let firstIndex = indexes.first else { fatalError() } @@ -378,7 +383,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - private func move(items: [SBQueueItem], at index: Int) { + private func move(items: [QueueItem], at index: Int) { var currentIndex = index var source: [Int] = Array() var dest: [Int] = Array() @@ -460,8 +465,8 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } } - /// Creates a popover with a SBQueueItem - private func createItemPopover(_ item: SBQueueItem) { + /// Creates a popover with a QueueItem + private func createItemPopover(_ item: QueueItem) { let p = NSPopover() let view = ItemViewController(item: item, delegate: self) @@ -583,8 +588,8 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, //MARK: Open - private func itemsFrom(url: URL) -> [SBQueueItem] { - var items: [SBQueueItem] = Array() + private func itemsFrom(url: URL) -> [QueueItem] { + var items: [QueueItem] = Array() let supportedFileFormats = MP42FileImporter.supportedFileFormats() let value = try? url.resourceValues(forKeys: [URLResourceKey.isDirectoryKey]) @@ -609,7 +614,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, } func addItemsFrom(urls: [URL], at index: Int) { - var items: [SBQueueItem] = Array() + var items: [QueueItem] = Array() for url in urls { let itemsFromURL = itemsFrom(url: url) @@ -663,10 +668,7 @@ class QueueController : NSWindowController, NSWindowDelegate, NSPopoverDelegate, cell?.imageView?.image = NSImage(named: "EncodeCanceled") case .cancelled: cell?.imageView?.image = NSImage(named: "EncodeCanceled") - case .ready, - .unknown: - cell?.imageView?.image = docImg - @unknown default: + case .ready: cell?.imageView?.image = docImg } diff --git a/Classes/QueueItem.swift b/Classes/QueueItem.swift new file mode 100644 index 0000000..929a858 --- /dev/null +++ b/Classes/QueueItem.swift @@ -0,0 +1,422 @@ +// +// QueueItem.swift +// Subler +// +// Created by Damiano Galassi on 28/01/2019. +// + +import Foundation +import MP42Foundation + +class QueueItem: NSObject, NSSecureCoding { + + @objc enum Status: Int { + case ready + case editing + case working + case completed + case failed + case cancelled + } + + @objc dynamic let fileURL: URL + @objc dynamic var destURL: URL + + var mp4File: MP42File? + var localizedWorkingDescription: String? + + weak var delegate: Queue? + + private var statusInternal: Status + private let uniqueID: String + private var attributes: [String : Any] + private var actionsInternal: [QueueActionProtocol] + + private var cancelled: Bool + private let queue: DispatchQueue + + private init(fileURL: URL, destURL: URL) { + statusInternal = .ready + uniqueID = UUID().uuidString + actionsInternal = [] + attributes = [:] + cancelled = false + self.fileURL = fileURL + self.destURL = destURL + queue = DispatchQueue(label: "org.subler.itemQueue") + } + + convenience init(fileURL: URL, destination: URL) { + self.init(fileURL: fileURL, destURL: destination) + + var url = fileURL + url.removeCachedResourceValue(forKey: URLResourceKey.fileSizeKey) + let value = try? url.resourceValues(forKeys: [URLResourceKey.fileSizeKey]) + + if let fileSize = value?.fileSize, fileSize > 3800000000 { + attributes[MP4264BitData] = true + } + + if UserDefaults.standard.bool(forKey: "chaptersPreviewTrack") { + attributes[MP42GenerateChaptersPreviewTrack] = true + attributes[MP42ChaptersPreviewPosition] = UserDefaults.standard.float(forKey: "SBChaptersPreviewPosition") + } + } + + convenience init(mp4: MP42File) { + self.init(fileURL: mp4.url!, destURL: mp4.url!) + mp4File = mp4 + + if UserDefaults.standard.bool(forKey: "chaptersPreviewTrack") { + attributes[MP42GenerateChaptersPreviewTrack] = true + attributes[MP42ChaptersPreviewPosition] = UserDefaults.standard.float(forKey: "SBChaptersPreviewPosition") + } + } + + convenience init(mp4: MP42File, destURL: URL, attributes: [String : Any] = [:], optimize: Bool = false) { + self.init(fileURL: destURL, destURL: destURL) + self.mp4File = mp4 + self.attributes = attributes + + if optimize { + addAction(QueueOptimizeAction()) + } + } + + // MARK: Public properties + + @objc dynamic var status: Status { + get { + var status: Status = .ready + queue.sync { + status = statusInternal + } + return status + } + set (newStatus) { + queue.sync { + statusInternal = newStatus + } + } + } + + // MARK: Actions + + @objc dynamic var actions: [QueueActionProtocol] { + get { + var result: [QueueActionProtocol] = [] + queue.sync { + result = actionsInternal + } + return result + } + } + + func addAction(_ action: QueueActionProtocol) { + queue.sync { + actionsInternal.append(action) + } + } + + func removeAction(at index: Int) { + _ = queue.sync { + actionsInternal.remove(at: index) + } + } + + // MARK: Item processing + + enum ProcessError: Error { + case fileExists + case fileNotFound + case outOfDiskSpace + case optimizationFailure + } + + private func checkDiskSpace(at url: URL) -> Int { + var directoryURL = url + directoryURL.removeCachedResourceValue(forKey: .volumeAvailableCapacityKey) + let value = try? directoryURL.resourceValues(forKeys: [.volumeAvailableCapacityKey]) + if let availableCapacity = value?.volumeAvailableCapacity { + return availableCapacity + } else { + return 0 + } + } + + private func configureAudio(track: MP42AudioTrack, mp4: MP42File) { + var conversionNeeded = false + + let ud = UserDefaults.standard + let bitrate = ud.integer(forKey: "SBAudioBitrate") + let drc = ud.float(forKey: "SBAudioDRC") + let mixdown = Int64(ud.integer(forKey: "SBAudioMixdown")) + + // AC-3 track, we might need to do the aac + ac3 trick. + if track.format == kMP42AudioCodecType_AC3 || + track.format == kMP42AudioCodecType_EnhancedAC3 { + + if ud.bool(forKey: "SBAudioConvertAC3") { + if ud.bool(forKey: "SBAudioKeepAC3") && track.fallbackTrack == nil { + let copy = track.copy() as! MP42AudioTrack + let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: UInt(bitrate), mixDown: mixdown, drc: drc) + copy.conversionSettings = settings + + track.fallbackTrack = copy + track.isEnabled = false + + mp4.addTrack(copy) + } else { + conversionNeeded = true + } + } + } + // DTS -> convert only if specified in the prefs. + else if track.format == kMP42AudioCodecType_DTS { + if ud.bool(forKey: "SBAudioConvertDts") { + switch ud.integer(forKey: "SBAudioDtsOptions") { + case 1: // Convert to AC-3 + + let copy = track.copy() as! MP42AudioTrack + let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: UInt(bitrate), mixDown: mixdown, drc: drc) + copy.conversionSettings = settings + + track.fallbackTrack = copy + track.isEnabled = false + + // Wouldn't it be better to use pref settings too instead of 640/Multichannel and the drc from the prefs? + track.conversionSettings = MP42AudioConversionSettings(format: kMP42AudioCodecType_AC3, bitRate: 640, mixDown: kMP42AudioMixdown_None, drc: drc) + + mp4.addTrack(copy) + + case 2: // Keep DTS + + let copy = track.copy() as! MP42AudioTrack + let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: UInt(bitrate), mixDown: mixdown, drc: drc) + copy.conversionSettings = settings + + track.fallbackTrack = copy + track.isEnabled = false + + mp4.addTrack(copy) + + default: + conversionNeeded = true + } + } + } + + // If an audio track needs to be converted, apply the mixdown from the preferences. + if trackNeedConversion(track.format) || conversionNeeded { + let settings = MP42AudioConversionSettings(format: kMP42AudioCodecType_MPEG4AAC, bitRate: UInt(bitrate), mixDown: mixdown, drc: drc) + track.conversionSettings = settings + } + } + + private func configureSubtitles(track: MP42SubtitleTrack, mp4: MP42File) { + // VobSub -> only if specified in the prefs. + if track.format == kMP42SubtitleCodecType_VobSub && UserDefaults.standard.bool(forKey: "SBSubtitleConvertBitmap") { + let settings = MP42ConversionSettings.subtitlesConversion() + track.conversionSettings = settings + } else if trackNeedConversion(track.format) { + let settings = MP42ConversionSettings.subtitlesConversion() + track.conversionSettings = settings + } + } + + func prepare() throws { + + defer { + localizedWorkingDescription = nil + delegate?.updateProgress(0) + } + + if FileManager.default.fileExists(atPath: fileURL.path) == false { + throw ProcessError.fileNotFound + } + + if mp4File == nil { + let value = try? fileURL.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey]) + + if let type = value?.typeIdentifier, type == "com.apple.m4a-audio" || type == "com.apple.m4v-video" || type == "public.mpeg-4" { + mp4File = try MP42File(url: fileURL) + } else { + let mp4 = MP42File() + let importer = try MP42FileImporter(url: fileURL) + let activeTracks = importer.tracks.filter { isTrackMuxable($0.format) || trackNeedConversion($0.format) } + + mp4.metadata.merge(importer.metadata) + + for track in activeTracks { + + if let track = track as? MP42AudioTrack { + configureAudio(track: track, mp4: mp4) + } else if let track = track as? MP42SubtitleTrack { + configureSubtitles(track: track, mp4: mp4) + } + + mp4.addTrack(track) + } + } + } + + for action in actions.filter({ $0.type == .pre }) { + localizedWorkingDescription = action.localizedDescription + delegate?.updateProgress(0) + _ = action.runAction(self) + } + } + + func process() throws { + + guard let filePathURL = (fileURL as NSURL?)?.filePathURL else { return } + + #if SB_SANDBOX + destURL?.startAccessingSecurityScopedResource() + #endif + + defer { + mp4File?.progressHandler = nil + mp4File = nil + + #if SB_SANDBOX + destURL?.stopAccessingSecurityScopedResource() + #endif + } + + // The file has been added directly to the queue + if mp4File == nil { + try prepare() + } + + guard let mp4 = mp4File else { return } + + weak var weakSelf = self + mp4.progressHandler = { (progress) in + weakSelf?.delegate?.updateProgress(progress) + } + + // Check if there is enough space on the destination disk + if filePathURL != destURL { + let availableCapacity = checkDiskSpace(at: destURL.deletingLastPathComponent()) + if mp4.dataSize > availableCapacity { + throw ProcessError.outOfDiskSpace + } + } + + if cancelled == false { + if filePathURL == destURL && mp4.hasFileRepresentation { + // We have an existing mp4 file, update it + try mp4.update(options: attributes) + } else { + // Write the new file to disk + try mp4.write(to: destURL, options: attributes) + } + } + + // Optimize the file + if cancelled == false { + if let action = actions.first(where: { $0.type == .post }) { + localizedWorkingDescription = action.localizedDescription + delegate?.updateProgress(0) + let result = action.runAction(self) + if result == false { + throw ProcessError.optimizationFailure + } + } + localizedWorkingDescription = nil + } + } + + func cancel() { + queue.sync { + self.cancelled = true + mp4File?.cancel() + } + } + + // MARK: AppleScript + + @objc func name() -> String { + return destURL.lastPathComponent + } + + @objc func sourcePath() -> String { + return fileURL.path + } + + @objc func destinationPath() -> String { + return destURL.path + } + + override var objectSpecifier: NSScriptObjectSpecifier? { + get { + let appDescription = NSApp.classDescription + return NSUniqueIDSpecifier(containerClassDescription: appDescription as! NSScriptClassDescription, containerSpecifier: nil, key: "items", uniqueID: uniqueID) + } + } + + // MARK: Secure coding + + static var supportsSecureCoding: Bool { return true } + + func encode(with aCoder: NSCoder) { + aCoder.encode(5, forKey: "SBQueueItemTagEncodeVersion") + + aCoder.encode(uniqueID, forKey: "SBQueueItemID") + aCoder.encode(mp4File, forKey: "SBQueueItemMp4File") + aCoder.encode(fileURL, forKey: "SBQueueItemFileURL") + aCoder.encode(destURL, forKey: "SBQueueItemDestURL") + aCoder.encode(attributes, forKey: "SBQueueItemAttributes") + aCoder.encode(actionsInternal, forKey: "SBQueueItemActions") + + aCoder.encode(statusInternal.rawValue, forKey: "SBQueueItemStatus") + } + + required init?(coder aDecoder: NSCoder) { + cancelled = false + queue = DispatchQueue(label: "org.subler.itemQueue") + + statusInternal = QueueItem.Status(rawValue: Int(aDecoder.decodeInt32(forKey: "SBQueueItemStatus"))) ?? .failed + mp4File = aDecoder.decodeObject(of: [MP42File.classForCoder()], forKey: "SBQueueItemMp4File") as? MP42File + uniqueID = aDecoder.decodeObject(of: [NSString.classForCoder()], forKey: "SBQueueItemID") as! String + attributes = aDecoder.decodeObject(of: [NSDictionary.classForCoder()], forKey: "SBQueueItemAttributes") as! [String : Any] + fileURL = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemFileURL") as! URL + destURL = aDecoder.decodeObject(of: [NSURL.classForCoder()], forKey: "SBQueueItemDestURL") as! URL + actionsInternal = aDecoder.decodeObject(of: [NSArray.classForCoder(), QueueSetAction.classForCoder(), + QueueMetadataAction.classForCoder(), QueueSubtitlesAction.classForCoder(), + QueueSetLanguageAction.classForCoder(), QueueFixFallbacksAction.classForCoder(), + QueueClearTrackNameAction.classForCoder(), QueueOrganizeGroupsAction.classForCoder(), + QueueColorSpaceAction.classForCoder(), QueueSetOutputFilenameAction.classForCoder(), + QueueClearExistingMetadataAction.classForCoder(), QueueOptimizeAction.classForCoder(), + QueueSendToiTunesAction.classForCoder()], forKey: "SBQueueItemActions") as! [QueueActionProtocol] + } +} + +extension QueueItem.ProcessError: LocalizedError { + var errorDescription: String? { + switch self { + case .fileNotFound: + return NSLocalizedString("File not found.", comment: "QueueItem Error") + case .fileExists: + return NSLocalizedString("A file already exists at the destination.", comment: "QueueItem Error") + case .outOfDiskSpace: + return NSLocalizedString("Not enough disk space.", comment: "QueueItem Error") + case .optimizationFailure: + return NSLocalizedString("The file couldn't be optimized.", comment: "QueueItem Error") + } + } + + var recoverySuggestion: String? { + switch self { + case .fileNotFound: + return NSLocalizedString("The source file couldn't be found.", comment: "My error") + case .fileExists: + return NSLocalizedString("Try to use another name for the destination file.", comment: "QueueItem Error") + case .outOfDiskSpace: + return NSLocalizedString("Please free some space on the destination disk.", comment: "QueueItem Error") + case .optimizationFailure: + return NSLocalizedString("An error occurred while optimizing the file.", comment: "QueueItem Error") + } + } +} diff --git a/Classes/SBQueueItem.h b/Classes/SBQueueItem.h deleted file mode 100755 index 5977bea..0000000 --- a/Classes/SBQueueItem.h +++ /dev/null @@ -1,72 +0,0 @@ -// -// SBQueueItem.h -// Subler -// -// Created by Damiano Galassi on 16/08/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class MP42File; -@class SBQueueItem; - -typedef NS_ENUM(NSUInteger, SBQueueActionType) { - SBQueueActionTypePre = 0, - SBQueueActionTypePost -}; - -/** - * SBQueue actions protocol, actions can be run by - * the queue's items. - */ -@protocol SBQueueActionProtocol -- (BOOL)runAction:(SBQueueItem *)item; -@property (nonatomic, readonly) NSString *localizedDescription; -@property (nonatomic, readonly) SBQueueActionType type; -@end - - -typedef NS_ENUM(NSUInteger, SBQueueItemStatus) { - SBQueueItemStatusUnknown = 0, - SBQueueItemStatusReady, - SBQueueItemStatusEditing, - SBQueueItemStatusWorking, - SBQueueItemStatusCompleted, - SBQueueItemStatusFailed, - SBQueueItemStatusCancelled, -}; - -@interface SBQueueItem : NSObject - -@property (nonatomic, readwrite) SBQueueItemStatus status; -@property (nonatomic, readonly, nullable) NSString *localizedWorkingDescription; - -@property (nonatomic, readonly, nullable) MP42File *mp4File; - -@property (nonatomic, readonly) NSURL *fileURL; -@property (nonatomic, copy) NSURL *destURL; - -@property (nonatomic, readonly) NSArray> *actions; -@property (nonatomic, readonly) NSDictionary *attributes; - -@property (nonatomic, weak, nullable) id delegate; - -+ (instancetype)itemWithURL:(NSURL *)URL; - -+ (instancetype)itemWithMP4:(MP42File *)MP4; -+ (instancetype)itemWithMP4:(MP42File *)MP4 destinationURL:(NSURL *)destURL attributes:(NSDictionary *)dict; -+ (instancetype)itemWithMP4:(MP42File *)MP4 destinationURL:(NSURL *)destURL attributes:(NSDictionary *)dict optimize:(BOOL)optimize; - -- (void)addAction:(id)action; -- (void)removeAction:(id)action; - -- (BOOL)prepare:(NSError * __autoreleasing *)outError; -- (BOOL)process:(NSError * __autoreleasing *)outError; -- (void)cancel; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Classes/SBQueueItem.m b/Classes/SBQueueItem.m deleted file mode 100755 index aa43663..0000000 --- a/Classes/SBQueueItem.m +++ /dev/null @@ -1,519 +0,0 @@ -// -// SBQueueItem.m -// Subler -// -// Created by Damiano Galassi on 16/08/11. -// Copyright 2011 __MyCompanyName__. All rights reserved. -// - -#import "SBQueueItem.h" - -#import -#import -#import - -#import "Subler-Swift.h" - -#define ALMOST_4GiB 4000000000 - -@interface SBQueueItem () - -@property (nonatomic) NSString *uniqueID; - -@property (nonatomic) NSMutableArray> *actionsInternal; -@property (nonatomic) NSString *localizedWorkingDescription; - -@property (nonatomic, nullable) MP42File *mp4File; - -@property (nonatomic) dispatch_queue_t queue; -@property (nonatomic) _Atomic int32_t cancelled; - -@end - -@implementation SBQueueItem { - SBQueueItemStatus _status; - NSURL *_fileURL; -} - -#pragma mark Initializers - -- (instancetype)init { - self = [super init]; - if (self) { - _uniqueID = [[NSUUID UUID] UUIDString]; - _actionsInternal = [[NSMutableArray alloc] init]; - _status = SBQueueItemStatusReady; - _queue = dispatch_queue_create("org.subler.itemQueue", DISPATCH_QUEUE_SERIAL); - } - return self; -} - -- (instancetype)initWithURL:(NSURL *)URL { - self = [self init]; - if (self) { - _fileURL = URL.filePathURL; - - NSFileManager *fileManager = [NSFileManager defaultManager]; - unsigned long long originalFileSize = [[[fileManager attributesOfItemAtPath:_fileURL.path error:nil] valueForKey:NSFileSize] unsignedLongLongValue]; - - NSMutableDictionary *attributes = [NSMutableDictionary dictionary]; - - if (originalFileSize > ALMOST_4GiB) { - attributes[MP4264BitData] = @YES; - } - - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"chaptersPreviewTrack"]) { - attributes[MP42GenerateChaptersPreviewTrack] = @YES; - attributes[MP42ChaptersPreviewPosition] = @([[NSUserDefaults standardUserDefaults] floatForKey:@"SBChaptersPreviewPosition"]); - } - - _attributes = [attributes copy]; - } - - return self; -} - -+ (instancetype)itemWithURL:(NSURL *)URL { - return [[SBQueueItem alloc] initWithURL:URL]; -} - -- (instancetype)initWithMP4:(MP42File *)MP4 { - self = [self init]; - if (self) { - _mp4File = MP4; - - _fileURL = [NSURL fileURLWithPath:MP4.URL.path]; - _destURL = [NSURL fileURLWithPath:MP4.URL.path]; - - NSMutableDictionary *attributes = [NSMutableDictionary dictionary]; - - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"chaptersPreviewTrack"]) { - attributes[MP42GenerateChaptersPreviewTrack] = @YES; - attributes[MP42ChaptersPreviewPosition] = @([[NSUserDefaults standardUserDefaults] floatForKey:@"SBChaptersPreviewPosition"]); - } - - _attributes = [attributes copy]; - } - - return self; -} - -+ (instancetype)itemWithMP4:(MP42File *)MP4 { - return [[SBQueueItem alloc] initWithMP4:MP4]; -} - -- (instancetype)initWithMP4:(MP42File *)MP4 url:(NSURL *)URL attributes:(NSDictionary *)dict { - if (self = [self init]) { - _mp4File = MP4; - - _fileURL = [URL copy]; - _destURL = [URL copy]; - - _attributes = [dict copy]; - } - - return self; -} - -+ (instancetype)itemWithMP4:(MP42File *)MP4 destinationURL:(NSURL *)destURL attributes:(NSDictionary *)dict { - return [[SBQueueItem alloc] initWithMP4:MP4 url:destURL attributes:dict]; -} - -- (instancetype)initWithMP4:(MP42File *)MP4 destinationURL:(NSURL *)destURL attributes:(NSDictionary *)dict optimize:(BOOL)optimize { - if (self = [self initWithMP4:MP4 url:destURL attributes:dict]) { - if (optimize) { - [_actionsInternal addObject:[[SBQueueOptimizeAction alloc] init]]; - } - } - return self; -} - -+ (instancetype)itemWithMP4:(MP42File *)MP4 destinationURL:(NSURL *)destURL attributes:(NSDictionary *)dict optimize:(BOOL)optimize { - return [[SBQueueItem alloc] initWithMP4:MP4 destinationURL:destURL attributes:dict optimize:optimize]; -} - -#pragma mark KVO - -+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey { - BOOL automatic = NO; - if ([theKey isEqualToString:@"actions"]) { - automatic = NO; - } else { - automatic = [super automaticallyNotifiesObserversForKey:theKey]; - } - return automatic; -} - -#pragma mark Public methods - -- (void)setStatus:(SBQueueItemStatus)status { - dispatch_sync(_queue, ^{ - self->_status = status; - if (self->_status == SBQueueItemStatusCompleted) { - self.mp4File = nil; - } - }); -} - -- (SBQueueItemStatus)status { - __block SBQueueItemStatus status; - dispatch_sync(_queue, ^{ - status = self->_status; - }); - return status; -} - -- (void)setFileURL:(NSURL * _Nonnull)fileURL { - dispatch_sync(_queue, ^{ - self->_fileURL = fileURL; - }); -} - -- (NSURL *)fileURL { - __block NSURL *fileURL; - dispatch_sync(_queue, ^{ - fileURL = self->_fileURL; - }); - return fileURL; -} - -- (void)addAction:(id)action { - if (self.status != SBQueueItemStatusWorking) { - [self willChangeValueForKey:@"actions"]; - [self.actionsInternal addObject:action]; - [self didChangeValueForKey:@"actions"]; - } -} - -- (void)removeAction:(id)action { - if (self.status != SBQueueItemStatusWorking) { - [self willChangeValueForKey:@"actions"]; - if ([self.actionsInternal containsObject:action]) { - [self.actionsInternal removeObject:action]; - } - [self didChangeValueForKey:@"actions"]; - } -} - -- (NSArray *)actions { - return [self.actionsInternal copy]; -} - -#pragma mark Item processing - -- (BOOL)prepare:(NSError * __autoreleasing *)outError { - if (![[NSFileManager defaultManager] fileExistsAtPath:self.fileURL.path]) { - if (outError) { - NSDictionary *errorDetail = @{ NSLocalizedDescriptionKey : @"File not found", - NSLocalizedRecoverySuggestionErrorKey : @"The source file couldn't be found." }; - *outError = [NSError errorWithDomain:@"SBQueueItemError" code:10 userInfo:errorDetail]; - } - return NO; - } - - NSString *type; - [self.fileURL getResourceValue:&type forKey:NSURLTypeIdentifierKey error:outError]; - - if (self.mp4File) { - // Do nothing - } - else if ([type isEqualToString:@"com.apple.m4a-audio"] || [type isEqualToString:@"com.apple.m4v-video"] || [type isEqualToString:@"public.mpeg-4"]) { - self.mp4File = [[MP42File alloc] initWithURL:self.fileURL error:NULL]; - } else { - self.mp4File = [[MP42File alloc] init]; - MP42FileImporter *fileImporter = [[MP42FileImporter alloc] initWithURL:self.fileURL error:outError]; - [self.mp4File.metadata mergeMetadata:fileImporter.metadata]; - - NSUInteger bitRate = [[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioBitrate"] integerValue]; - float drc = [[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioDRC"] floatValue]; - NSInteger mixdownType = [[[NSUserDefaults standardUserDefaults] - valueForKey:@"SBAudioMixdown"] integerValue]; - MP42AudioMixdown mixdown = mixdownType; - - for (MP42Track *track in fileImporter.tracks) { - - if (!(isTrackMuxable(track.format) || trackNeedConversion(track.format))) { - continue; - } - - BOOL conversionNeeded = NO; - - // AC-3 track, we might need to do the aac + ac3 trick. - if (track.format == kMP42AudioCodecType_AC3 || - track.format == kMP42AudioCodecType_EnhancedAC3) { - if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioConvertAC3"] boolValue]) { - if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioKeepAC3"] boolValue] && !((MP42AudioTrack *)track).fallbackTrack) { - MP42AudioTrack *copy = [track copy]; - MP42ConversionSettings *settings = [MP42AudioConversionSettings audioConversionWithBitRate:bitRate - mixDown:mixdown - drc:drc]; - copy.conversionSettings = settings; - - ((MP42AudioTrack *)track).fallbackTrack = copy; - track.enabled = NO; - - [self.mp4File addTrack:copy]; - } - else { - conversionNeeded = YES; - } - } - } - // DTS -> convert only if specified in the prefs. - else if (track.format == kMP42AudioCodecType_DTS) { - if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioConvertDts"] boolValue]) { - switch ([[[NSUserDefaults standardUserDefaults] valueForKey:@"SBAudioDtsOptions"] integerValue]) { - case 1: { // Convert to AC-3 - MP42AudioTrack *copy = [track copy]; - MP42ConversionSettings *settings = [MP42AudioConversionSettings audioConversionWithBitRate:bitRate - mixDown:mixdown - drc:drc]; - copy.conversionSettings = settings; - - ((MP42AudioTrack *)track).fallbackTrack = copy; - track.enabled = NO; - // Wouldn't it be better to use pref settings too instead of 640/Multichannel and the drc from the prefs? - track.conversionSettings = [[MP42AudioConversionSettings alloc] initWithFormat:kMP42AudioCodecType_AC3 - bitRate:640 - mixDown:kMP42AudioMixdown_None - drc:drc]; - [self.mp4File addTrack:copy]; - break; - } - case 2: { // Keep DTS - MP42AudioTrack *copy = [track copy]; - MP42ConversionSettings *settings = [MP42AudioConversionSettings audioConversionWithBitRate:bitRate - mixDown:mixdown - drc:drc]; - copy.conversionSettings = settings; - - ((MP42AudioTrack *)track).fallbackTrack = copy; - track.enabled = NO; - - [self.mp4File addTrack:copy]; - break; - } - default: - conversionNeeded = YES; - break; - } - } - } - - // If an audio track needs to be converted, apply the mixdown from the preferences. - if (([track isMemberOfClass:[MP42AudioTrack class]] && trackNeedConversion(track.format)) || conversionNeeded) { - MP42AudioTrack *audioTrack = (MP42AudioTrack *)track; - MP42ConversionSettings *settings = [MP42AudioConversionSettings audioConversionWithBitRate:bitRate - mixDown:mixdown - drc:drc]; - audioTrack.conversionSettings = settings; - - } - - // VobSub -> only if specified in the prefs. - if ((track.format == kMP42SubtitleCodecType_VobSub && - [[[NSUserDefaults standardUserDefaults] valueForKey:@"SBSubtitleConvertBitmap"] boolValue])) { - MP42ConversionSettings *settings = [MP42ConversionSettings subtitlesConversion]; - track.conversionSettings = settings; - } - else if ([track isMemberOfClass:[MP42SubtitleTrack class]] && trackNeedConversion(track.format)) { - MP42ConversionSettings *settings = [MP42ConversionSettings subtitlesConversion]; - track.conversionSettings = settings; - } - - [self.mp4File addTrack:track]; - } - } - - for (id action in self.actions) { - if (action.type == SBQueueActionTypePre) { - self.localizedWorkingDescription = action.localizedDescription; - [self progressStatus:0]; - [action runAction:self]; - } - } - - self.localizedWorkingDescription = nil; - - return YES; -} - -- (BOOL)process:(NSError * __autoreleasing *)outError { - BOOL noErr = YES; - -#ifdef SB_SANDBOX - [self.destURL startAccessingSecurityScopedResource]; -#endif - - // The file has been added directly to the queue - if (!self.mp4File && self.fileURL) { - noErr = [self prepare:outError]; - } - - NSURL *filePathURL = self.fileURL.filePathURL; - - if (!noErr) { goto bail; } - - { - __weak SBQueueItem *weakSelf = self; - self.mp4File.progressHandler = ^(double progress){ - [weakSelf progressStatus:progress]; - }; - - // Check if there is enough space on the destination disk - if (![filePathURL isEqualTo:self.destURL]) { - NSDictionary *dict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:self.destURL.URLByDeletingLastPathComponent.path error:NULL]; - NSNumber *freeSpace = dict[NSFileSystemFreeSize]; - if (freeSpace && self.mp4File.dataSize > freeSpace.longLongValue) { - noErr = NO; - if (outError) { - NSDictionary *errorDetail = @{ NSLocalizedDescriptionKey : @"Not enough disk space", - NSLocalizedRecoverySuggestionErrorKey : @"" }; - *outError = [NSError errorWithDomain:@"SBQueueItemError" code:12 userInfo:errorDetail]; - } - goto bail; - } - } - - if (!self.cancelled) { - if ([filePathURL isEqualTo:self.destURL] && self.mp4File.hasFileRepresentation) { - // We have an existing mp4 file, update it - noErr = [self.mp4File updateMP4FileWithOptions:self.attributes error:outError]; - } - else { - // Write the new file to disk - noErr = [self.mp4File writeToUrl:self.destURL - options:self.attributes - error:outError]; - } - } - } - - if (!noErr) { goto bail; } - - { - // Optimize the file - if (!self.cancelled) { - for (id action in self.actions) { - if (action.type == SBQueueActionTypePost) { - self.localizedWorkingDescription = action.localizedDescription; - [self progressStatus:0]; - noErr = [action runAction:self]; - } - } - self.localizedWorkingDescription = nil; - } - - if (!noErr) { - if (outError) { - NSDictionary *errorDetail = @{ NSLocalizedDescriptionKey : @"The file couldn't be optimized", - NSLocalizedRecoverySuggestionErrorKey : @"An error occurred while optimizing the file." }; - *outError = [NSError errorWithDomain:@"SBQueueItemError" code:11 userInfo:errorDetail]; - } - goto bail; - } - } - -bail: - self.mp4File.progressHandler = nil; - self.mp4File = nil; - - // Convert from a file reference url to a normal url - // the file will be replaced if optimized, and the reference url - // may point to nil - self.fileURL = filePathURL; - -#ifdef SB_SANDBOX - [self.destURL stopAccessingSecurityScopedResource]; -#endif - - return noErr; -} - -- (void)cancel { - self.cancelled = YES; - [self.mp4File cancel]; -} - -- (void)progressStatus:(double)progress { - [self updateProgress:progress]; -} - -#pragma mark NSSecureCoding - -#define SBQUEUEITEM_VERSION 4 - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeInt:SBQUEUEITEM_VERSION forKey:@"SBQueueItemTagEncodeVersion"]; - - [coder encodeObject:_uniqueID forKey:@"SBQueueItemID"]; - [coder encodeObject:_mp4File forKey:@"SBQueueItemMp4File"]; - [coder encodeObject:_fileURL forKey:@"SBQueueItemFileURL"]; - [coder encodeObject:_destURL forKey:@"SBQueueItemDestURL"]; - [coder encodeObject:_attributes forKey:@"SBQueueItemAttributes"]; - [coder encodeObject:_actionsInternal forKey:@"SBQueueItemActions"]; - - [coder encodeInt:_status forKey:@"SBQueueItemStatus"]; -} - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [self init]; - - if (self) { - - NSInteger version = [decoder decodeIntForKey:@"SBQueueItemTagEncodeVersion"]; - if (version < SBQUEUEITEM_VERSION) { - return nil; - } - - _uniqueID = [decoder decodeObjectOfClass:[NSString class] forKey:@"SBQueueItemID"]; - _mp4File = [decoder decodeObjectOfClass:[MP42File class] forKey:@"SBQueueItemMp4File"]; - - _fileURL = [decoder decodeObjectOfClass:[NSURL class] forKey:@"SBQueueItemFileURL"]; - _destURL = [decoder decodeObjectOfClass:[NSURL class] forKey:@"SBQueueItemDestURL"]; - _attributes = [decoder decodeObjectOfClass:[NSDictionary class] forKey:@"SBQueueItemAttributes"]; - _actionsInternal = [decoder decodeObjectOfClasses:[NSSet setWithObjects:[NSMutableArray class], [SBQueueSetAction class], - [SBQueueMetadataAction class], [SBQueueSubtitlesAction class], - [SBQueueSetLanguageAction class], [SBQueueFixFallbacksAction class], - [SBQueueClearTrackNameAction class], [SBQueueOrganizeGroupsAction class], - [SBQueueColorSpaceAction class], [SBQueueSetOutputFilenameAction class], - [SBQueueClearExistingMetadataAction class], [SBQueueOptimizeAction class], - [SBQueueSendToiTunesAction class], nil] - forKey:@"SBQueueItemActions"]; - - _status = [decoder decodeIntForKey:@"SBQueueItemStatus"]; - } - return self; -} - -#pragma mark AppleScript - -- (NSString *)name -{ - return self.destURL.lastPathComponent; -} - -- (NSString *)sourcePath -{ - return self.fileURL.path; -} - -- (NSString *)destinationPath -{ - return self.destURL.path; -} - -- (NSUniqueIDSpecifier *)objectSpecifier { - - NSScriptClassDescription *appDescription = (NSScriptClassDescription *)[NSApp classDescription]; - return [[NSUniqueIDSpecifier alloc] initWithContainerClassDescription:appDescription - containerSpecifier:nil - key:@"items" - uniqueID:self.uniqueID]; -} - -@end diff --git a/Subler-Bridging-Header.h b/Subler-Bridging-Header.h index 1e6a6e9..37d5838 100644 --- a/Subler-Bridging-Header.h +++ b/Subler-Bridging-Header.h @@ -2,5 +2,4 @@ // Use this file to import your target's public headers that you would like to expose to Swift. // -#import "SBQueueItem.h" #import "SBMovieViewController.h" diff --git a/Subler.xcodeproj/project.pbxproj b/Subler.xcodeproj/project.pbxproj index 6e89d5c..ba3f39e 100644 --- a/Subler.xcodeproj/project.pbxproj +++ b/Subler.xcodeproj/project.pbxproj @@ -57,7 +57,6 @@ A979B3862025C8BF00468362 /* DocumentWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A979B3842025C8BF00468362 /* DocumentWindowController.swift */; }; A97C3AA5204F18C90007AD38 /* TokenCellView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A97C3AA4204F18C90007AD38 /* TokenCellView.swift */; }; A97FBE3C21FC7F1C00F1FD35 /* QueueController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A97FBE3B21FC7F1C00F1FD35 /* QueueController.swift */; }; - A982D0C0140AB66400B92357 /* SBQueueItem.m in Sources */ = {isa = PBXBuildFile; fileRef = A982D0BF140AB66400B92357 /* SBQueueItem.m */; }; A984DB4B0F52D644001A20B2 /* Sparkle.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A984DB4A0F52D644001A20B2 /* Sparkle.framework */; }; A984DB530F52D679001A20B2 /* Sparkle.framework in Copy Files */ = {isa = PBXBuildFile; fileRef = A984DB4A0F52D644001A20B2 /* Sparkle.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; A984DB740F52DD4B001A20B2 /* dsa_pub.pem in Resources */ = {isa = PBXBuildFile; fileRef = A984DB730F52DD4B001A20B2 /* dsa_pub.pem */; }; @@ -122,6 +121,7 @@ A9ECA05D2029A11500D5F30C /* DetailsViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9ECA05F2029A11500D5F30C /* DetailsViewController.xib */; }; A9ECA0602029A13800D5F30C /* OffsetViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9ECA0622029A13800D5F30C /* OffsetViewController.xib */; }; A9EEA5F818D654B9008B54B4 /* QueueOptions.xib in Resources */ = {isa = PBXBuildFile; fileRef = A9EEA5F618D654B9008B54B4 /* QueueOptions.xib */; }; + A9EFB8CC21FF40C500129FDD /* QueueItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9EFB8CB21FF40C500129FDD /* QueueItem.swift */; }; A9F2A2662026EACD00C4B69A /* DetailsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F2A2642026EACD00C4B69A /* DetailsViewController.swift */; }; A9F4FF4B1FB708FB004473A8 /* SoundViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9F4FF4A1FB708FB004473A8 /* SoundViewController.swift */; }; A9F5820C1DCC861F005F3E92 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A9F5820B1DCC861F005F3E92 /* Assets.xcassets */; }; @@ -265,8 +265,6 @@ A979B3842025C8BF00468362 /* DocumentWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DocumentWindowController.swift; path = Classes/DocumentWindowController.swift; sourceTree = ""; }; A97C3AA4204F18C90007AD38 /* TokenCellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = TokenCellView.swift; path = Classes/TokenCellView.swift; sourceTree = ""; }; A97FBE3B21FC7F1C00F1FD35 /* QueueController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = QueueController.swift; path = Classes/QueueController.swift; sourceTree = ""; }; - A982D0BE140AB66400B92357 /* SBQueueItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SBQueueItem.h; path = Classes/SBQueueItem.h; sourceTree = ""; }; - A982D0BF140AB66400B92357 /* SBQueueItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SBQueueItem.m; path = Classes/SBQueueItem.m; sourceTree = ""; }; A984DB4A0F52D644001A20B2 /* Sparkle.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = Sparkle.framework; sourceTree = ""; }; A984DB730F52DD4B001A20B2 /* dsa_pub.pem */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = dsa_pub.pem; sourceTree = ""; }; A98542D620D197D300EB9803 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/ArtworkSelector.xib; sourceTree = ""; }; @@ -345,6 +343,7 @@ A9ECA05E2029A11500D5F30C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/DetailsViewController.xib; sourceTree = ""; }; A9ECA0612029A13800D5F30C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/OffsetViewController.xib; sourceTree = ""; }; A9ED7B21180067A2008FD3A8 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; }; + A9EFB8CB21FF40C500129FDD /* QueueItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = QueueItem.swift; path = Classes/QueueItem.swift; sourceTree = ""; }; A9F2A2642026EACD00C4B69A /* DetailsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = DetailsViewController.swift; path = Classes/DetailsViewController.swift; sourceTree = ""; }; A9F4FF4A1FB708FB004473A8 /* SoundViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SoundViewController.swift; path = Classes/PropertyView/SoundViewController.swift; sourceTree = ""; }; A9F5820B1DCC861F005F3E92 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; @@ -579,8 +578,7 @@ A9676A331FB6EAAD00C1E300 /* ItemViewController.swift */, A9BC410618D9ABC000F8C92C /* QueueItem.xib */, A98D6BAA21FDC62800F0D886 /* Queue.swift */, - A982D0BE140AB66400B92357 /* SBQueueItem.h */, - A982D0BF140AB66400B92357 /* SBQueueItem.m */, + A9EFB8CB21FF40C500129FDD /* QueueItem.swift */, A91B196B1F2B0DCB0008675F /* QueueAction.swift */, A932C9F2205C268A004E52FE /* QueueScriptCommand.swift */, ); @@ -851,6 +849,7 @@ A9C09C7C1F99F460007939EE /* ExceptionAlertController.swift in Sources */, A9A91B5D1FB6FBB700250D93 /* ChapterViewController.swift in Sources */, A9676A301FB6E85300C1E300 /* LanguageTransformer.swift in Sources */, + A9EFB8CC21FF40C500129FDD /* QueueItem.swift in Sources */, A97FBE3C21FC7F1C00F1FD35 /* QueueController.swift in Sources */, A9907E192063DAA000DB992E /* VideoViewController.swift in Sources */, A98D98461F0280CB00A77ABC /* TheMovieDB.swift in Sources */, @@ -899,7 +898,6 @@ A92BBAB41F557CC0007EA182 /* PresetEditorViewController.swift in Sources */, A9FC6FF61EF2E3280034CCED /* TheTVDBService.swift in Sources */, A9C3E44A205C07F4004DE24E /* OptionsViewController.swift in Sources */, - A982D0C0140AB66400B92357 /* SBQueueItem.m in Sources */, A90057C01F99E35300FA4ED1 /* PopUpCellView.swift in Sources */, A91B196C1F2B0DCB0008675F /* QueueAction.swift in Sources */, A9AF2D1D206116680088CE91 /* SectionsTableView.swift in Sources */,