Rewrite SBQueueItem to Swift.

This commit is contained in:
Damiano Galassi committed 2019-01-28 18:50:50 +01:00
1 parent 3778909a69
commit cd36f3349c
11 files changed
+563 -718

No files matched your search

+2 -2
View File
@@ -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..<Int(queue.count))
return queue.items(at: indexes)
}
@objc(insertObject:inItemsAtIndex:) func insert(object: SBQueueItem, inItemsAtIndex index: UInt) {
@objc(insertObject:inItemsAtIndex:) func insert(object: QueueItem, inItemsAtIndex index: UInt) {
QueueController.shared.insert(items: [object], at: IndexSet(integer: IndexSet.Element(index)))
}
+2 -2
View File
@@ -207,7 +207,7 @@ import MP42Foundation
let queue = QueueController.shared
if mp4.hasFileRepresentation {
let item = SBQueueItem(mp4: mp4)
let item = QueueItem(mp4: mp4)
queue.add(item, applyPreset: true)
close()
}
@@ -218,7 +218,7 @@ import MP42Foundation
let handler = { (response: NSApplication.ModalResponse) in
if response == NSApplication.ModalResponse.OK, let url = panel.url {
let options = self.saveOptions()
let item = SBQueueItem(mp4: self.mp4, destinationURL: url, attributes: options, optimize: self.optimize)
let item = QueueItem(mp4: self.mp4, destURL: url, attributes: options, optimize: self.optimize)
queue.add(item)
self.releaseSavePanel()
self.close()
+4 -4
View File
@@ -8,12 +8,12 @@
import Cocoa
protocol ItemViewDelegate: AnyObject {
func edit(item: SBQueueItem)
func edit(item: QueueItem)
}
class ItemViewController : NSViewController {
@objc let item: SBQueueItem
@objc let item: QueueItem
var delegate: ItemViewDelegate
@@ -28,7 +28,7 @@ class ItemViewController : NSViewController {
return "QueueItem"
}
init(item: SBQueueItem, delegate: ItemViewDelegate) {
init(item: QueueItem, delegate: ItemViewDelegate) {
self.item = item
self.delegate = delegate
super.init(nibName: nil, bundle: nil)
@@ -45,7 +45,7 @@ class ItemViewController : NSViewController {
statusObserver = item.observe(\.status, options: [.initial, .new]) { [weak self] observed, change in
guard let s = self else { return }
DispatchQueue.main.async {
if observed.status == SBQueueItemStatus.ready || observed.status == SBQueueItemStatus.completed {
if observed.status == .ready || observed.status == .completed {
s.editButton.isEnabled = true
} else {
s.editButton.isEnabled = false
+40 -37
View File
@@ -8,15 +8,6 @@
import Foundation
import IOKit
extension SBQueueItem {
@objc func updateProgress(_ progress: Double) {
if let queue = delegate as? Queue {
queue.updateProgress(progress)
}
}
}
class Queue {
static let Working = NSNotification.Name(rawValue: "QueueWorkingNotification")
@@ -30,10 +21,10 @@ class Queue {
private var sleepAssertion: IOPMAssertionID = IOPMAssertionID(0)
private var sleepAssertionSuccess: IOReturn = kIOReturnInvalid
private var items: [SBQueueItem]
private var items: [QueueItem]
private var cancelled: Bool
private var currentItem: SBQueueItem?
private var currentItem: QueueItem?
private let url: URL
@@ -55,7 +46,7 @@ class Queue {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
unarchiver.requiresSecureCoding = true
items = unarchiver.decodeObject(of: [NSArray.classForCoder(), NSMutableArray.classForCoder(), SBQueueItem.classForCoder()], forKey: NSKeyedArchiveRootObjectKey) as! [SBQueueItem]
items = unarchiver.decodeObject(of: [NSArray.classForCoder(), NSMutableArray.classForCoder(), QueueItem.classForCoder()], forKey: NSKeyedArchiveRootObjectKey) as! [QueueItem]
unarchiver.finishDecoding()
} else {
items = Array()
@@ -112,15 +103,37 @@ class Queue {
self.handleSBStatusWorking(progress: 0, index: currentIndex)
do {
try currentItem.process()
var cancelled = false
self.arrayQueue.sync {
cancelled = self.cancelled
}
if cancelled {
currentItem.status = .cancelled
self.handleSBStatusCancelled()
break
} else {
currentItem.status = .completed
completed += 1
}
self.handleSBStatusWorking(progress: 100, index: currentIndex)
} catch {
currentItem.status = .failed
failed += 1
self.handleSBStatusFailed(error: error)
}
var cancelled = false
self.arrayQueue.sync {
cancelled = self.cancelled
var cancelled = false
self.arrayQueue.sync {
cancelled = self.cancelled
}
if cancelled {
self.handleSBStatusCancelled()
break
}
}
currentItem.delegate = nil
@@ -128,16 +141,6 @@ class Queue {
self.currentItem = nil
}
if cancelled {
currentItem.status = .cancelled
self.handleSBStatusCancelled()
break
} else {
currentItem.status = .completed
completed += 1
}
self.handleSBStatusWorking(progress: 100, index: currentIndex)
} else {
break
}
@@ -190,9 +193,9 @@ class Queue {
}
}
private var firstItemInQueue: SBQueueItem? {
private var firstItemInQueue: QueueItem? {
get {
var first: SBQueueItem?
var first: QueueItem?
arrayQueue.sync {
first = items.first(where: { (item) -> 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)
+53 -41
View File
@@ -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)
+36 -34
View File
@@ -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
}
+422
View File
@@ -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")
}
}
}
-72
View File
@@ -1,72 +0,0 @@
//
// SBQueueItem.h
// Subler
//
// Created by Damiano Galassi on 16/08/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
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 <NSObject, NSSecureCoding>
- (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 <NSSecureCoding>
@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<id<SBQueueActionProtocol>> *actions;
@property (nonatomic, readonly) NSDictionary<NSString *, id> *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<SBQueueActionProtocol>)action;
- (void)removeAction:(id<SBQueueActionProtocol>)action;
- (BOOL)prepare:(NSError * __autoreleasing *)outError;
- (BOOL)process:(NSError * __autoreleasing *)outError;
- (void)cancel;
@end
NS_ASSUME_NONNULL_END
-519
View File
@@ -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 <MP42Foundation/MP42File.h>
#import <MP42Foundation/MP42FileImporter.h>
#import <MP42Foundation/MP42Utilities.h>
#import "Subler-Swift.h"
#define ALMOST_4GiB 4000000000
@interface SBQueueItem ()
@property (nonatomic) NSString *uniqueID;
@property (nonatomic) NSMutableArray<id<SBQueueActionProtocol>> *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<SBQueueActionProtocol>)action {
if (self.status != SBQueueItemStatusWorking) {
[self willChangeValueForKey:@"actions"];
[self.actionsInternal addObject:action];
[self didChangeValueForKey:@"actions"];
}
}
- (void)removeAction:(id<SBQueueActionProtocol>)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<SBQueueActionProtocol> 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<SBQueueActionProtocol> 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