summaryrefslogtreecommitdiffstats
path: root/macosx/HBQueue.m
blob: 0d812b1d8381ea07b608568c0359d45ef8b1dafd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
/*  HBQueue.m $

 This file is part of the HandBrake source code.
 Homepage: <http://handbrake.fr/>.
 It may be used under the terms of the GNU General Public License. */

#import "HBQueue.h"
#import "HBRemoteCore.h"

#import "HBPreferencesKeys.h"
#import "NSArray+HBAdditions.h"
#import "HBJobOutputFileWriter.h"

static void *HBQueueContext = &HBQueueContext;
static void *HBQueueLogLevelContext = &HBQueueLogLevelContext;

NSString * const HBQueueDidChangeStateNotification = @"HBQueueDidChangeStateNotification";

NSString * const HBQueueDidAddItemNotification = @"HBQueueDidAddItemNotification";
NSString * const HBQueueDidRemoveItemNotification = @"HBQueueDidRemoveItemNotification";
NSString * const HBQueueDidChangeItemNotification = @"HBQueueDidChangeItemNotification";

NSString * const HBQueueItemNotificationIndexesKey = @"HBQueueReloadItemsNotification";

NSString * const HBQueueDidMoveItemNotification = @"HBQueueDidMoveItemNotification";
NSString * const HBQueueItemNotificationSourceIndexesKey = @"HBQueueItemNotificationSourceIndexesKey";
NSString * const HBQueueItemNotificationTargetIndexesKey = @"HBQueueItemNotificationTargetIndexesKey";

NSString * const HBQueueReloadItemsNotification = @"HBQueueReloadItemsNotification";

NSString * const HBQueueLowSpaceAlertNotification = @"HBQueueLowSpaceAlertNotification";

NSString * const HBQueueProgressNotification = @"HBQueueProgressNotification";
NSString * const HBQueueProgressNotificationPercentKey = @"HBQueueProgressNotificationPercentKey";
NSString * const HBQueueProgressNotificationHoursKey = @"HBQueueProgressNotificationHoursKey";
NSString * const HBQueueProgressNotificationMinutesKey = @"HBQueueProgressNotificationMinutesKey";
NSString * const HBQueueProgressNotificationSecondsKey = @"HBQueueProgressNotificationSecondsKey";
NSString * const HBQueueProgressNotificationInfoKey = @"HBQueueProgressNotificationInfoKey";

NSString * const HBQueueDidStartNotification = @"HBQueueDidStartNotification";
NSString * const HBQueueDidCompleteNotification = @"HBQueueDidCompleteNotification";

NSString * const HBQueueDidStartItemNotification = @"HBQueueDidStartItemNotification";
NSString * const HBQueueDidCompleteItemNotification = @"HBQueueDidCompleteItemNotification";
NSString * const HBQueueItemNotificationItemKey = @"HBQueueItemNotificationItemKey";

@interface HBQueue ()

@property (nonatomic, readonly) HBRemoteCore *core;
@property (nonatomic) BOOL stop;

@property (nonatomic, nullable) HBJobOutputFileWriter *currentLog;

@end

@implementation HBQueue

- (instancetype)initWithURL:(NSURL *)queueURL
{
    self = [super init];
    if (self)
    {
        NSInteger loggingLevel = [NSUserDefaults.standardUserDefaults integerForKey:HBLoggingLevel];

        // Init a separate instance of libhb for the queue
        _core = [[HBRemoteCore alloc] initWithLogLevel:loggingLevel name:@"QueueCore"];
        _core.automaticallyPreventSleep = NO;

        _items = [[HBDistributedArray alloc] initWithURL:queueURL class:[HBQueueItem class]];
        _undoManager = [[NSUndoManager alloc] init];

        // Set up the observers
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadQueue) name:HBDistributedArrayChanged object:_items];

        [self updateStats];

        // Set up observers
        [self.core addObserver:self forKeyPath:@"state"
                       options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial
                       context:HBQueueContext];

        [NSUserDefaultsController.sharedUserDefaultsController addObserver:self forKeyPath:@"values.LoggingLevel"
                                                                   options:0 context:HBQueueLogLevelContext];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == HBQueueContext)
    {
        [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidChangeStateNotification object:self];
    }
    else if (context == HBQueueLogLevelContext)
    {
        self.core.logLevel = [NSUserDefaults.standardUserDefaults integerForKey:HBLoggingLevel];
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc
{
    [self.core removeObserver:self forKeyPath:@"state"];
    [self.core invalidate];
}

#pragma mark - Public methods

- (void)addJob:(HBJob *)item
{
    NSParameterAssert(item);
    [self addJobs:@[item]];
}

- (void)addJobs:(NSArray<HBJob *> *)jobs
{
    NSParameterAssert(jobs);

    NSMutableArray<HBQueueItem *> *itemsToAdd = [NSMutableArray array];
    for (HBJob *job in jobs)
    {
        HBQueueItem *item = [[HBQueueItem alloc] initWithJob:job];
        [itemsToAdd addObject:item];
    }
    if (itemsToAdd.count)
    {
        NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(self.items.count, itemsToAdd.count)];
        [self addItems:itemsToAdd atIndexes:indexes];
    }
}

- (BOOL)itemExistAtURL:(NSURL *)url
{
    NSParameterAssert(url);

    for (HBQueueItem *item in self.items)
    {
        if ((item.state == HBQueueItemStateReady || item.state == HBQueueItemStateWorking)
            && [item.completeOutputURL isEqualTo:url])
        {
            return YES;
        }
    }
    return NO;
}

- (void)addItems:(NSArray<HBQueueItem *> *)items atIndexes:(NSIndexSet *)indexes
{
    NSParameterAssert(items);
    NSParameterAssert(indexes);
    [self.items beginTransaction];

    // Forward
    NSUInteger currentIndex = indexes.firstIndex;
    NSUInteger currentObjectIndex = 0;
    while (currentIndex != NSNotFound)
    {
        [self.items insertObject:items[currentObjectIndex] atIndex:currentIndex];
        currentIndex = [indexes indexGreaterThanIndex:currentIndex];
        currentObjectIndex++;
    }

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidAddItemNotification object:self userInfo:@{HBQueueItemNotificationIndexesKey: indexes}];

    NSUndoManager *undo = self.undoManager;
    [[undo prepareWithInvocationTarget:self] removeItemsAtIndexes:indexes];

    if (!undo.isUndoing)
    {
        if (items.count == 1)
        {
            [undo setActionName:NSLocalizedString(@"Add Job To Queue", @"Queue undo action name")];
        }
        else
        {
            [undo setActionName:NSLocalizedString(@"Add Jobs To Queue", @"Queue undo action name")];
        }
    }

    [self updateStats];
    [self.items commit];
}

- (void)removeItemAtIndex:(NSUInteger)index
{
    [self removeItemsAtIndexes:[NSIndexSet indexSetWithIndex:index]];
}

- (void)removeItemsAtIndexes:(NSIndexSet *)indexes
{
    NSParameterAssert(indexes);

    if (indexes.count == 0)
    {
        return;
    }

    [self.items beginTransaction];

    NSArray<HBQueueItem *> *removeItems = [self.items objectsAtIndexes:indexes];

    if (self.items.count > indexes.lastIndex)
    {
        [self.items removeObjectsAtIndexes:indexes];
    }

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidRemoveItemNotification object:self userInfo:@{HBQueueItemNotificationIndexesKey: indexes}];

    NSUndoManager *undo = self.undoManager;
    [[undo prepareWithInvocationTarget:self] addItems:removeItems atIndexes:indexes];

    if (!undo.isUndoing)
    {
        if (indexes.count == 1)
        {
            [undo setActionName:NSLocalizedString(@"Remove Job From Queue", @"Queue undo action name")];
        }
        else
        {
            [undo setActionName:NSLocalizedString(@"Remove Jobs From Queue", @"Queue undo action name")];
        }
    }

    [self updateStats];
    [self.items commit];
}

- (void)moveItems:(NSArray<HBQueueItem *> *)items toIndex:(NSUInteger)index
{
    [self.items beginTransaction];

    NSMutableArray<NSNumber *> *source = [NSMutableArray array];
    NSMutableArray<NSNumber *> *dest = [NSMutableArray array];

    for (id object in items.reverseObjectEnumerator)
    {
        NSUInteger sourceIndex = [self.items indexOfObject:object];
        [self.items removeObjectAtIndex:sourceIndex];

        if (sourceIndex < index)
        {
            index--;
        }

        [self.items insertObject:object atIndex:index];

        [source addObject:@(index)];
        [dest addObject:@(sourceIndex)];
    }

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidMoveItemNotification
                                                      object:self
                                                    userInfo:@{HBQueueItemNotificationSourceIndexesKey: dest,
                                                               HBQueueItemNotificationTargetIndexesKey: source}];

    NSUndoManager *undo = self.undoManager;
    [[undo prepareWithInvocationTarget:self] moveQueueItemsAtIndexes:source toIndexes:dest];

    if (!undo.isUndoing)
    {
        if (items.count == 1)
        {
            [undo setActionName:NSLocalizedString(@"Move Job in Queue", @"Queue undo action name")];
        }
        else
        {
            [undo setActionName:NSLocalizedString(@"Move Jobs in Queue", @"Queue undo action name")];
        }
    }

    [self.items commit];
}

- (void)moveQueueItemsAtIndexes:(NSArray *)source toIndexes:(NSArray *)dest
{
    [self.items beginTransaction];

    NSMutableArray<NSNumber *> *newSource = [NSMutableArray array];
    NSMutableArray<NSNumber *> *newDest = [NSMutableArray array];

    for (NSInteger idx = source.count - 1; idx >= 0; idx--)
    {
        NSUInteger sourceIndex = [source[idx] integerValue];
        NSUInteger destIndex = [dest[idx] integerValue];

        [newSource addObject:@(destIndex)];
        [newDest addObject:@(sourceIndex)];

        id obj = [self.items objectAtIndex:sourceIndex];
        [self.items removeObjectAtIndex:sourceIndex];
        [self.items insertObject:obj atIndex:destIndex];
    }

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidMoveItemNotification
                                                      object:self
                                                    userInfo:@{HBQueueItemNotificationSourceIndexesKey: newDest,
                                                               HBQueueItemNotificationTargetIndexesKey: newSource}];

    NSUndoManager *undo = self.undoManager;
    [[undo prepareWithInvocationTarget:self] moveQueueItemsAtIndexes:newSource toIndexes:newDest];

    if (!undo.isUndoing)
    {
        if (source.count == 1)
        {
            [undo setActionName:NSLocalizedString(@"Move Job in Queue", @"Queue undo action name")];
        }
        else
        {
            [undo setActionName:NSLocalizedString(@"Move Jobs in Queue", @"Queue undo action name")];
        }
    }

    [self.items commit];
}

/**
 * This method will clear the queue of any encodes that are not still pending
 * this includes both successfully completed encodes as well as canceled encodes
 */
- (void)removeCompletedAndCancelledItems
{
    [self.items beginTransaction];
    NSIndexSet *indexes = [self.items indexesOfObjectsUsingBlock:^BOOL(HBQueueItem *item) {
        return (item.state == HBQueueItemStateCompleted || item.state == HBQueueItemStateCanceled);
    }];
    [self removeItemsAtIndexes:indexes];
    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidRemoveItemNotification object:self userInfo:@{@"indexes": indexes}];
    [self.items commit];
}

/**
 * This method will clear the queue of all encodes. effectively creating an empty queue
 */
- (void)removeAllItems
{
    [self.items beginTransaction];
    [self removeItemsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.items.count)]];
    [self.items commit];
}

- (void)removeNotWorkingItems
{
    [self.items beginTransaction];
    NSIndexSet *indexes = [self.items indexesOfObjectsUsingBlock:^BOOL(HBQueueItem *item) {
        return (item.state != HBQueueItemStateWorking);
    }];
    [self removeItemsAtIndexes:indexes];
    [self.items commit];
}

- (void)removeCompletedItems
{
    [self.items beginTransaction];
    NSIndexSet *indexes = [self.items indexesOfObjectsUsingBlock:^BOOL(HBQueueItem *item) {
        return (item.state == HBQueueItemStateCompleted);
    }];
    [self removeItemsAtIndexes:indexes];
    [self.items commit];
}

- (void)resetItemsAtIndexes:(NSIndexSet *)indexes
{
    if ([self.items beginTransaction] == HBDistributedArrayContentReload)
    {
        // Do not execute the action if the array changed.
        [self.items commit];
        return;
    }

    NSMutableIndexSet *updatedIndexes = [NSMutableIndexSet indexSet];

    NSUInteger currentIndex =  indexes.firstIndex;
    while (currentIndex != NSNotFound) {
        HBQueueItem *item = self.items[currentIndex];

        if (item.state == HBQueueItemStateCanceled || item.state == HBQueueItemStateCompleted || item.state == HBQueueItemStateFailed)
        {
            item.state = HBQueueItemStateReady;
            [updatedIndexes addIndex:currentIndex];
        }
        currentIndex = [indexes indexGreaterThanIndex:currentIndex];
    }

    [self updateStats];
    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidChangeItemNotification object:self userInfo:@{HBQueueItemNotificationIndexesKey: indexes}];
    [self.items commit];
}

- (void)resetAllItems
{
    [self.items beginTransaction];
    NSIndexSet *indexes = [self.items indexesOfObjectsUsingBlock:^BOOL(HBQueueItem *item) {
        return (item.state != HBQueueItemStateWorking);
    }];
    [self resetItemsAtIndexes:indexes];
    [self.items commit];
}

- (void)resetFailedItems
{
    [self.items beginTransaction];
    NSIndexSet *indexes = [self.items indexesOfObjectsUsingBlock:^BOOL(HBQueueItem *item) {
        return (item.state == HBQueueItemStateFailed);
    }];
    [self resetItemsAtIndexes:indexes];
    [self.items commit];
}

/**
 * This method will set any item marked as encoding back to pending
 * currently used right after a queue reload
 */
- (void)setEncodingJobsAsPending
{
    [self.items beginTransaction];

    NSMutableIndexSet *indexes = [NSMutableIndexSet indexSet];
    NSUInteger idx = 0;
    for (HBQueueItem *item in self.items)
    {
        // We want to keep any queue item that is pending or was previously being encoded
        if (item.state == HBQueueItemStateWorking)
        {
            item.state = HBQueueItemStateReady;
            [indexes addIndex:idx];
        }
        idx++;
    }

    [self updateStats];
    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidChangeItemNotification object:self userInfo:@{HBQueueItemNotificationIndexesKey: indexes}];
    [self.items commit];
}

- (BOOL)canEncode
{
    return self.pendingItemsCount > 0 && ![self isEncoding];
}

- (BOOL)isEncoding
{
    HBState s = self.core.state;
    return self.currentItem || (s == HBStateScanning) || (s == HBStatePaused) || (s == HBStateWorking) || (s == HBStateMuxing) || (s == HBStateSearching);
}

- (BOOL)canPause
{
    HBState s = self.core.state;
    return (s == HBStateWorking || s == HBStateMuxing);
}

- (void)pause
{
    [self.currentItem pausedAtDate:[NSDate date]];
    [self.core pause];
    [self.core allowSleep];
}

- (BOOL)canResume
{
    return self.core.state == HBStatePaused;
}

- (void)resume
{
    [self.currentItem resumedAtDate:[NSDate date]];
    [self.core resume];
    [self.core preventSleep];
}

#pragma mark - Private queue editing methods

/**
 *  Reloads the queue, this is called
 *  when another HandBrake instance modifies the queue
 */
- (void)reloadQueue
{
    [self updateStats];
    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueReloadItemsNotification object:self];
}

- (void)updateStats
{
    NSUInteger pendingCount = 0, failedCount = 0, completedCount = 0;

    for (HBQueueItem *item in self.items)
    {
        if (item.state == HBQueueItemStateReady)
        {
            pendingCount++;
        }
        else if (item.state == HBQueueItemStateCompleted)
        {
            completedCount++;
        }
        else if (item.state == HBQueueItemStateFailed)
        {
            failedCount++;
        }
    }

    self.pendingItemsCount = pendingCount;
    self.failedItemsCount = failedCount;
    self.completedItemsCount = completedCount;

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidChangeStateNotification object:self];
}

- (BOOL)isDiskSpaceLowAtURL:(NSURL *)url
{
    if ([NSUserDefaults.standardUserDefaults boolForKey:HBQueuePauseIfLowSpace])
    {
        NSURL *volumeURL = nil;
        NSDictionary<NSURLResourceKey, id> *attrs = [url resourceValuesForKeys:@[NSURLIsVolumeKey, NSURLVolumeURLKey] error:NULL];
        long long minCapacity = [[NSUserDefaults.standardUserDefaults stringForKey:HBQueueMinFreeSpace] longLongValue] * 1000000000;

        volumeURL = [attrs[NSURLIsVolumeKey] boolValue] ? url : attrs[NSURLVolumeURLKey];

        if (volumeURL)
        {
            [volumeURL removeCachedResourceValueForKey:NSURLVolumeAvailableCapacityKey];
            attrs = [volumeURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityKey] error:NULL];

            if (attrs[NSURLVolumeAvailableCapacityKey])
            {
                if ([attrs[NSURLVolumeAvailableCapacityKey] longLongValue] < minCapacity)
                {
                    return YES;
                }
            }
        }
    }

    return NO;
}

/**
 * Used to get the next pending queue item and return it if found
 */
- (HBQueueItem *)getNextPendingQueueItem
{
    for (HBQueueItem *item in self.items)
    {
        if (item.state == HBQueueItemStateReady)
        {
            return item;
        }
    }
    return nil;
}

- (void)start
{
    if (self.canEncode)
    {
        [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidStartNotification object:self];
        [self.core preventSleep];
        [self encodeNextQueueItem];
    }
}

/**
 *  Starts the queue
 */
- (void)encodeNextQueueItem
{
    [self.items beginTransaction];

    // since we have completed an encode, we go to the next
    if (self.stop)
    {
        [HBUtilities writeToActivityLog:"Queue manually stopped"];

        self.stop = NO;
        [self.core allowSleep];

        [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidCompleteNotification object:self];
    }
    else
    {
        // Check to see if there are any more pending items in the queue
        HBQueueItem *nextItem = [self getNextPendingQueueItem];

        if (nextItem && [self isDiskSpaceLowAtURL:nextItem.outputURL])
        {
            // Disk space is low, show an alert
            [HBUtilities writeToActivityLog:"Queue Stopped, low space on destination disk"];
            [self.core allowSleep];

            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidCompleteNotification object:self];
            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueLowSpaceAlertNotification object:self];
        }
        // If we still have more pending items in our queue, lets go to the next one
        else if (nextItem)
        {
            // now we mark the queue item as working so another instance can not come along and try to scan it while we are scanning
            nextItem.startedDate = [NSDate date];
            nextItem.state = HBQueueItemStateWorking;

            // Tell HB to output a new activity log file for this encode
            self.currentLog = [[HBJobOutputFileWriter alloc] initWithJob:nextItem.job];
            if (self.currentLog)
            {
                dispatch_queue_t mainQueue = dispatch_get_main_queue();
                [self.core.stderrRedirect addListener:self.currentLog queue:mainQueue];
                [self.core.stdoutRedirect addListener:self.currentLog queue:mainQueue];
            }

            self.currentItem = nextItem;
            NSIndexSet *indexes = [NSIndexSet indexSetWithIndex:[self.items indexOfObject:nextItem]];

            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidStartItemNotification object:self userInfo:@{HBQueueItemNotificationItemKey: nextItem,
                                                                                                                            HBQueueItemNotificationIndexesKey: indexes}];

            [self updateStats];

            // now we can go ahead and scan the new pending queue item
            [self encodeItem:nextItem];

            // erase undo manager history
            [self.undoManager removeAllActions];
        }
        else
        {
            [HBUtilities writeToActivityLog:"Queue Done, there are no more pending encodes"];
            [self.core allowSleep];

            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidCompleteNotification object:self];
        }
    }

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidChangeStateNotification object:self];

    [self.items commit];
}

- (void)completedItem:(HBQueueItem *)item result:(HBCoreResult)result
{
    NSParameterAssert(item);
    [self.items beginTransaction];

    item.endedDate = [NSDate date];

    // Since we are done with this encode, tell output to stop writing to the
    // individual encode log.
    [self.core.stderrRedirect removeListener:self.currentLog];
    [self.core.stdoutRedirect removeListener:self.currentLog];

    self.currentLog = nil;

    // Mark the encode just finished
    switch (result) {
        case HBCoreResultDone:
            item.state = HBQueueItemStateCompleted;
            break;
        case HBCoreResultCanceled:
            item.state = HBQueueItemStateCanceled;
            break;
        default:
            item.state = HBQueueItemStateFailed;
            break;
    }

    // Update UI
    NSString *info = nil;
    switch (result) {
        case HBCoreResultDone:
            info = NSLocalizedString(@"Encode Finished.", @"Queue status");
            break;
        case HBCoreResultCanceled:
            info = NSLocalizedString(@"Encode Canceled.", @"Queue status");
            break;
        default:
            info = NSLocalizedString(@"Encode Failed.", @"Queue status");
            break;
    }

    self.currentItem = nil;

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueProgressNotification object:self userInfo:@{HBQueueProgressNotificationPercentKey: @1.0,
                                                                                                                HBQueueProgressNotificationInfoKey: info}];

    NSUInteger index = [self.items indexOfObject:item];
    NSIndexSet *indexes = index != NSNotFound ? [NSIndexSet indexSetWithIndex:index] : [NSIndexSet indexSet];
    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueDidCompleteItemNotification object:self userInfo:@{HBQueueItemNotificationItemKey: item,
                                                                                                                       HBQueueItemNotificationIndexesKey: indexes}];

    [self.items commit];
}

/**
 * Here we actually tell hb_scan to perform the source scan, using the path to source and title number
 */
- (void)encodeItem:(HBQueueItem *)item
{
    NSParameterAssert(item);

    // Progress handler
    void (^progressHandler)(HBState state, HBProgress progress, NSString *info) = ^(HBState state, HBProgress progress, NSString *info)
    {
        [NSNotificationCenter.defaultCenter postNotificationName:HBQueueProgressNotification object:self userInfo:@{HBQueueProgressNotificationPercentKey: @0,
                                                                                                                    HBQueueProgressNotificationInfoKey: info}];
    };

    // Completion handler
    void (^completionHandler)(HBCoreResult result) = ^(HBCoreResult result)
    {
        if (result == HBCoreResultDone)
        {
            [self realEncodeItem:item];
        }
        else
        {
            [self completedItem:item result:result];
            [self encodeNextQueueItem];
        }
    };

    // Only scan 10 previews before an encode - additional previews are
    // only useful for autocrop and static previews, which are already taken care of at this point
    [self.core scanURL:item.fileURL
            titleIndex:item.job.titleIdx
              previews:10
           minDuration:0
          keepPreviews:NO
       progressHandler:progressHandler
     completionHandler:completionHandler];
}

/**
 * This assumes that we have re-scanned and loaded up a new queue item to send to libhb
 */
- (void)realEncodeItem:(HBQueueItem *)item
{
    NSParameterAssert(item);

    HBJob *job = item.job;

    NSParameterAssert(job);

    // Progress handler
    void (^progressHandler)(HBState state, HBProgress progress, NSString *info) = ^(HBState state, HBProgress progress, NSString *info)
    {
        if (state == HBStateMuxing)
        {
            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueProgressNotification
                                                              object:self
                                                            userInfo:@{HBQueueProgressNotificationPercentKey: @1,
                                                                       HBQueueProgressNotificationInfoKey: info}];
        }
        else
        {
            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueProgressNotification
                                                              object:self
                                                            userInfo:@{HBQueueProgressNotificationPercentKey: @(progress.percent),
                                                                       HBQueueProgressNotificationHoursKey: @(progress.hours),
                                                                       HBQueueProgressNotificationMinutesKey: @(progress.minutes),
                                                                       HBQueueProgressNotificationSecondsKey: @(progress.seconds),
                                                                       HBQueueProgressNotificationInfoKey: info}];
        }
    };

    // Completion handler
    void (^completionHandler)(HBCoreResult result) = ^(HBCoreResult result)
    {
        [self completedItem:item result:result];

        if ([NSUserDefaults.standardUserDefaults boolForKey:HBQueueAutoClearCompletedItems])
        {
            [self removeCompletedItems];
        }

        [self encodeNextQueueItem];
    };

    // We should be all setup so let 'er rip
    [self.core encodeJob:job progressHandler:progressHandler completionHandler:completionHandler];
}

/**
 * Cancels the current job
 */
- (void)doCancelCurrentItem
{
    if (self.core.state == HBStateScanning)
    {
        [self.core cancelScan];
    }
    else
    {
        [self.core cancelEncode];
    }
}

/**
 * Cancels the current job and starts processing the next in queue.
 */
- (void)cancelCurrentItemAndContinue
{
    [self doCancelCurrentItem];
}

/**
 * Cancels the current job and stops libhb from processing the remaining encodes.
 */
- (void)cancelCurrentItemAndStop
{
    if (self.core.state != HBStateIdle)
    {
        self.stop = YES;
        [self doCancelCurrentItem];
    }
}

/**
 * Finishes the current job and stops libhb from processing the remaining encodes.
 */
- (void)finishCurrentAndStop
{
    if (self.core.state != HBStateIdle)
    {
        self.stop = YES;
    }
}

@end