summaryrefslogtreecommitdiffstats
path: root/macosx/HBQueueWorker.m
blob: d7ddde8ce8e3dc296d8afffb4658eb1b13c178f4 (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
/*  HBQueueWorker.h

 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 "HBQueueWorker.h"

#import "HBRemoteCore.h"
#import "HBJobOutputFileWriter.h"
#import "HBPreferencesKeys.h"

static void *HBQueueWorkerContext = &HBQueueWorkerContext;
static void *HBQueueWorkerLogLevelContext = &HBQueueWorkerLogLevelContext;

NSString * const HBQueueWorkerDidChangeStateNotification = @"HBQueueWorkerDidChangeStateNotification";

NSString * const HBQueueWorkerProgressNotification = @"HBQueueWorkerProgressNotification";
NSString * const HBQueueWorkerProgressNotificationPercentKey = @"HBQueueWorkerProgressNotificationPercentKey";
NSString * const HBQueueWorkerProgressNotificationHoursKey = @"HBQueueWorkerProgressNotificationHoursKey";
NSString * const HBQueueWorkerProgressNotificationMinutesKey = @"HBQueueWorkerProgressNotificationMinutesKey";
NSString * const HBQueueWorkerProgressNotificationSecondsKey = @"HBQueueWorkerProgressNotificationSecondsKey";
NSString * const HBQueueWorkerProgressNotificationInfoKey = @"HBQueueWorkerProgressNotificationInfoKey";

NSString * const HBQueueWorkerDidStartItemNotification = @"HBQueueWorkerDidStartItemNotification";
NSString * const HBQueueWorkerDidCompleteItemNotification = @"HBQueueWorkerDidCompleteItemNotification";
NSString * const HBQueueWorkerItemNotificationItemKey = @"HBQueueWorkerItemNotificationItemKey";

@interface HBQueueWorker ()

@property (nonatomic, readonly) HBRemoteCore *core;

@property (nonatomic, nullable) HBQueueJobItem *item;
@property (nonatomic, nullable) HBJobOutputFileWriter *currentLog;

@end

@implementation HBQueueWorker

- (instancetype)initWithXPCServiceName:(NSString *)serviceName
{
    self = [super init];
    if (self)
    {
        NSInteger loggingLevel = [NSUserDefaults.standardUserDefaults integerForKey:HBLoggingLevel];
        _core = [[HBRemoteCore alloc] initWithLogLevel:loggingLevel name:serviceName serviceName:serviceName];
        _core.automaticallyPreventSleep = NO;

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

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

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == HBQueueWorkerContext)
    {
        [NSNotificationCenter.defaultCenter postNotificationName:HBQueueWorkerDidChangeStateNotification object:self];
    }
    else if (context == HBQueueWorkerLogLevelContext)
    {
        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" context:HBQueueWorkerContext];
    [NSUserDefaultsController.sharedUserDefaultsController removeObserver:self forKeyPath:@"values.LoggingLevel" context:HBQueueWorkerLogLevelContext];
    [self.core invalidate];
}

- (BOOL)canEncode
{
    return self.item == nil;
}

- (BOOL)isEncoding
{
    return self.item != nil;
}

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

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

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

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

- (void)completedItem:(HBQueueJobItem *)item result:(HBCoreResult)result
{
    NSParameterAssert(item);

    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;
    }

    self.item = nil;

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueWorkerProgressNotification
                                                      object:self
                                                    userInfo:@{HBQueueWorkerProgressNotificationPercentKey: @1.0,
                                                               HBQueueWorkerProgressNotificationInfoKey: @""}];

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueWorkerDidCompleteItemNotification
                                                      object:self
                                                    userInfo:@{HBQueueWorkerItemNotificationItemKey: item}];
}

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

    // now we mark the queue item as working so another instance can not come along and try to scan it while we are scanning
    item.startedDate = [NSDate date];
    item.state = HBQueueItemStateWorking;

    self.item = item;

    [NSNotificationCenter.defaultCenter postNotificationName:HBQueueWorkerDidStartItemNotification
                                                      object:self
                                                    userInfo:@{HBQueueWorkerItemNotificationItemKey: item}];

    // Tell HB to output a new activity log file for this encode
    self.currentLog = [[HBJobOutputFileWriter alloc] initWithJob:item.job];
    if (self.currentLog)
    {
        item.activityLogURL = self.currentLog.url;

        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        [self.core.stderrRedirect addListener:self.currentLog queue:mainQueue];
        [self.core.stdoutRedirect addListener:self.currentLog queue:mainQueue];
    }

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

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

    [item.job refreshSecurityScopedResources];

    // 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:(HBQueueJobItem *)item
{
    HBJob *job = item.job;

    // Progress handler
    void (^progressHandler)(HBState state, HBProgress progress, NSString *info) = ^(HBState state, HBProgress progress, NSString *info)
    {
        if (state == HBStateMuxing)
        {
            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueWorkerProgressNotification
                                                              object:self
                                                            userInfo:@{HBQueueWorkerProgressNotificationPercentKey: @1,
                                                                       HBQueueWorkerProgressNotificationInfoKey: info}];
        }
        else
        {
            [NSNotificationCenter.defaultCenter postNotificationName:HBQueueWorkerProgressNotification
                                                              object:self
                                                            userInfo:@{HBQueueWorkerProgressNotificationPercentKey: @(progress.percent),
                                                                       HBQueueWorkerProgressNotificationHoursKey: @(progress.hours),
                                                                       HBQueueWorkerProgressNotificationMinutesKey: @(progress.minutes),
                                                                       HBQueueWorkerProgressNotificationSecondsKey: @(progress.seconds),
                                                                       HBQueueWorkerProgressNotificationInfoKey: info}];
        }
    };

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

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

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

@end