summaryrefslogtreecommitdiffstats
path: root/macosx/HBVideo.m
blob: 73a3e8c7ea784195ddde194b7abadb0126533aa3 (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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
/*  HBVideo.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 "HBVideo.h"
#import "NSCodingMacro.h"
#include "hb.h"

@interface HBVideo ()

@property (nonatomic, readwrite) double qualityMinValue;
@property (nonatomic, readwrite) double qualityMaxValue;

@property (nonatomic, readwrite) NSUInteger mediumPresetIndex;

@end

@implementation HBVideo

- (instancetype)init
{
    self = [super init];
    if (self) {
        _encoder = HB_VCODEC_X264;
        _avgBitrate = 1000;
        _quality = 18.0;
        _qualityMaxValue = 51.0f;

        _widthForUnparse = 1;
        _heightForUnparse = 1;

        [self updateQualityBounds];
    }
    return self;
}

#pragma mark - Setters

/**
 *  Updates the min/max quality values
 */
- (void)updateQualityBounds
{
    // Get the current slider maxValue to check for a change in slider scale
    // later so that we can choose a new similar value on the new slider scale
    double previousMaxValue             = self.qualityMaxValue;
    double previousPercentOfSliderScale = (self.quality / (self.qualityMaxValue - self.qualityMinValue + 1));

    int direction;
    float minValue, maxValue, granularity;
    hb_video_quality_get_limits(self.encoder,
                                &minValue, &maxValue, &granularity, &direction);

    self.qualityMinValue = minValue;
    self.qualityMaxValue = maxValue;

    // check to see if we have changed slider scales
    if (previousMaxValue != maxValue)
    {
        // if so, convert the old setting to the new scale as close as possible
        // based on percentages
        self.quality = floor((maxValue - minValue + 1.) * (previousPercentOfSliderScale));
    }
}

- (void)setEncoder:(int)encoder
{
    _encoder = encoder;
    [self updateQualityBounds];
    [self validatePresetsSettings];
    [self validateAdvancedOptions];
}

- (void)setContainer:(int)container
{
    _container = container;

    BOOL encoderSupported = NO;

    for (const hb_encoder_t *video_encoder = hb_video_encoder_get_next(NULL);
         video_encoder != NULL;
         video_encoder  = hb_video_encoder_get_next(video_encoder))
    {
        if (video_encoder->muxers & self.container)
        {
            if (video_encoder->codec == self.encoder)
            {
                encoderSupported = YES;
            }
        }
    }

    if (!encoderSupported)
    {
        self.encoder = HB_VCODEC_X264;
    }
}

- (void)setTune:(NSString *)tune
{
    [_tune autorelease];

    if (![tune isEqualToString:@"none"])
    {
        _tune = [tune copy];
    }
    else
    {
        _tune = @"";
    }
}

- (void)validatePresetsSettings
{
    NSArray *presets = self.presets;
    if (presets.count && ![presets containsObject:self.preset]) {
        self.preset = presets[self.mediumPresetIndex];
    }

    NSArray *tunes = self.tunes;
    if (tunes.count && ![tunes containsObject:self.tune]) {
        self.tune = tunes.firstObject;
    }

    NSArray *profiles = self.profiles;
    if (profiles.count && ![profiles containsObject:self.profile]) {
        self.profile = profiles.firstObject;
    }

    NSArray *levels = self.levels;
    if (levels.count && ![levels containsObject:self.level]) {
        self.level = levels.firstObject;
    }
}

- (void)validateAdvancedOptions
{
    if (self.encoder != HB_VCODEC_H264_MASK)
    {
        self.advancedOptions = NO;
    }
}

#pragma mark - Possible values

- (NSArray *)encoders
{
    NSMutableArray *encoders = [NSMutableArray array];
    for (const hb_encoder_t *video_encoder = hb_video_encoder_get_next(NULL);
         video_encoder != NULL;
         video_encoder  = hb_video_encoder_get_next(video_encoder))
    {
        if (video_encoder->muxers & self.container)
        {
            [encoders addObject:@(video_encoder->name)];
        }
    }
    return [[encoders copy] autorelease];
}

- (NSArray *)frameRates
{
    NSMutableArray *framerates = [NSMutableArray array];

    [framerates addObject:NSLocalizedString(@"Same as source", @"")];

    for (const hb_rate_t *video_framerate = hb_video_framerate_get_next(NULL);
         video_framerate != NULL;
         video_framerate  = hb_video_framerate_get_next(video_framerate))
    {
        NSString *itemTitle;
        if (!strcmp(video_framerate->name, "23.976"))
        {
            itemTitle = @"23.976 (NTSC Film)";
        }
        else if (!strcmp(video_framerate->name, "25"))
        {
            itemTitle = @"25 (PAL Film/Video)";
        }
        else if (!strcmp(video_framerate->name, "29.97"))
        {
            itemTitle = @"29.97 (NTSC Video)";
        }
        else
        {
            itemTitle = @(video_framerate->name);
        }

        [framerates addObject:itemTitle];
    }
    return [[framerates copy] autorelease];
}

- (NSArray *)presets
{
    NSMutableArray *temp = [NSMutableArray array];

    const char * const *presets = hb_video_encoder_get_presets(self.encoder);
    for (int i = 0; presets != NULL && presets[i] != NULL; i++)
    {
        [temp addObject:@(presets[i])];
        if (!strcasecmp(presets[i], "medium"))
        {
            self.mediumPresetIndex = i;
        }
    }

    return [[temp copy] autorelease];
}

- (NSArray *)tunes
{
    NSMutableArray *temp = [NSMutableArray array];

    [temp addObject:@"none"];

    const char * const *tunes = hb_video_encoder_get_tunes(self.encoder);

    for (int i = 0; tunes != NULL && tunes[i] != NULL; i++)
    {
        // we filter out "fastdecode" as we have a dedicated checkbox for it
        if (strcasecmp(tunes[i], "fastdecode") != 0)
        {
            [temp addObject:@(tunes[i])];
        }
    }

    return [[temp copy] autorelease];
}

- (NSArray *)profiles
{
    NSMutableArray *temp = [NSMutableArray array];

    const char * const *profiles = hb_video_encoder_get_profiles(self.encoder);
    for (int i = 0; profiles != NULL && profiles[i] != NULL; i++)
    {
        [temp addObject:@(profiles[i])];
    }

    return [[temp copy] autorelease];
}

- (NSArray *)levels
{
    NSMutableArray *temp = [NSMutableArray array];

    const char * const *levels = hb_video_encoder_get_levels(self.encoder);
    for (int i = 0; levels != NULL && levels[i] != NULL; i++)
    {
        [temp addObject:@(levels[i])];
    }
    if (!temp.count)
    {
        [temp addObject:@"auto"];
    }

    return [[temp copy] autorelease];
}

- (BOOL)fastDecodeSupported
{
    return (self.encoder == HB_VCODEC_X264);
}

/**
 *  This is called everytime a x264 widget in the video tab is changed to
 *  display the expanded options in a text field via outlet fDisplayX264PresetsUnparseTextField
 */
- (NSString *)unparseOptions
{
    if (self.encoder != HB_VCODEC_X264)
    {
        return @"";
    }

    /* API reference:
     *
     * char * hb_x264_param_unparse(const char *x264_preset,
     *                              const char *x264_tune,
     *                              const char *x264_encopts,
     *                              const char *h264_profile,
     *                              const char *h264_level,
     *                              int width, int height);
     */
    NSString   *tmpString;
    const char *x264_preset   = [self.preset UTF8String];
    const char *x264_tune     = NULL;
    const char *advanced_opts = NULL;
    const char *h264_profile  = NULL;
    const char *h264_level    = NULL;

    tmpString = self.tune;
    if (self.fastDecode)
    {
        if (self.tune.length)
        {
            tmpString = [tmpString stringByAppendingString: @","];
        }
        tmpString = [tmpString stringByAppendingString: @"fastdecode"];
    }

    // prepare the tune, advanced options, profile and level
    if ([tmpString length])
    {
        x264_tune = [tmpString UTF8String];
    }
    if ([(tmpString = self.videoOptionExtra) length])
    {
        advanced_opts = [tmpString UTF8String];
    }
    if ([(tmpString = self.profile) length])
    {
        h264_profile = [tmpString UTF8String];
    }
    if ([(tmpString = self.level) length])
    {
        h264_level = [tmpString UTF8String];
    }

    // now, unparse
    char *fX264PresetsUnparsedUTF8String = hb_x264_param_unparse(x264_preset,
                                                           x264_tune,
                                                           advanced_opts,
                                                           h264_profile,
                                                           h264_level,
                                                           _widthForUnparse, _heightForUnparse);
    // update the text field
    if (fX264PresetsUnparsedUTF8String != NULL)
    {
        tmpString = [NSString stringWithUTF8String:fX264PresetsUnparsedUTF8String];
        free(fX264PresetsUnparsedUTF8String);
    }
    else
    {
        tmpString = @"";
    }

    return tmpString;
}

+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
    NSSet *retval = nil;

    // Tell KVO to reload the presets settings
    // after a change to the encoder.
    if ([key isEqualToString:@"presets"] ||
        [key isEqualToString:@"tunes"] ||
        [key isEqualToString:@"profiles"] ||
        [key isEqualToString:@"levels"])
    {
        retval = [NSSet setWithObjects:@"encoder", nil];
    }

    // Tell KVO to reload the x264 unparse string
    // after values changes.
    if ([key isEqualToString:@"unparseOptions"])
    {
        retval = [NSSet setWithObjects:@"encoder", @"preset", @"tune", @"profile", @"level",
                  @"videoOptionExtra", @"fastDecode", @"widthForUnparse", @"heightForUnparse", nil];
    }

    if ([key isEqualToString:@"encoders"])
    {
        retval = [NSSet setWithObjects:@"container", nil];
    }

    if ([key isEqualToString:@"fastDecodeSupported"])
    {
        retval = [NSSet setWithObjects:@"encoder", nil];
    }

    return retval;
}

#pragma mark - NSCoding

- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeInt:1 forKey:@"HBVideoVersion"];

    encodeInt(_encoder);

    encodeInt(_qualityType);
    encodeInt(_avgBitrate);
    encodeDouble(_quality);

    encodeInt(_frameRate);
    encodeInt(_frameRateMode);

    encodeBool(_twoPass);
    encodeBool(_turboTwoPass);

    encodeBool(_turboTwoPass);

    encodeInt(_advancedOptions);
    encodeObject(_preset);
    encodeObject(_tune);
    encodeObject(_profile);
    encodeObject(_level);

    encodeObject(_videoOptionExtra);

    encodeBool(_fastDecode);
}

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];

    decodeInt(_encoder);

    decodeInt(_qualityType);
    decodeInt(_avgBitrate);
    decodeDouble(_quality);

    decodeInt(_frameRate);
    decodeInt(_frameRateMode);

    decodeBool(_twoPass);
    decodeBool(_turboTwoPass);

    decodeBool(_turboTwoPass);

    decodeInt(_advancedOptions);
    decodeObject(_preset);
    decodeObject(_tune);
    decodeObject(_profile);
    decodeObject(_level);

    decodeObject(_videoOptionExtra);

    decodeBool(_fastDecode);

    return self;
}

#pragma mark - Various conversion methods from dict/preset/queue/etc

- (void)applySettingsFromPreset:(NSDictionary *)preset
{
    // map legacy encoder names via libhb.
    const char *strValue = hb_video_encoder_sanitize_name([preset[@"VideoEncoder"] UTF8String]);
    self.encoder = hb_video_encoder_get_from_name(strValue);

    if (self.encoder == HB_VCODEC_X264 || self.encoder == HB_VCODEC_X265)
    {
        if (self.encoder == HB_VCODEC_X264 &&
            (!preset[@"x264UseAdvancedOptions"] ||
             [preset[@"x264UseAdvancedOptions"] intValue]))
        {
            // preset does not use the x264 preset system, reset the widgets.
            self.preset = @"medium";
            self.tune = nil;
            self.profile = nil;
            self.level = nil;

            // x264UseAdvancedOptions is not set (legacy preset)
            // or set to 1 (enabled), so we use the old advanced panel.
            if (preset[@"x264Option"])
            {
                // we set the advanced options string here if applicable.
                self.videoOptionExtra = preset[@"x264Option"];
                self.advancedOptions = YES;
            }
            else
            {
                self.videoOptionExtra = nil;
            }
        }
        else
        {
            // x264UseAdvancedOptions is set to 0 (disabled),
            // so we use the new preset system and
            // disable the advanced panel
            self.advancedOptions = NO;

            if (preset[@"x264Preset"])
            {
                // Read the old x264 preset keys
                self.preset = preset[@"x264Preset"];
                self.tune   = preset[@"x264Tune"];
                self.videoOptionExtra = preset[@"x264OptionExtra"];
                self.profile = preset[@"h264Profile"];
                self.level   = preset[@"h264Level"];
            }
            else
            {
                // Read the new preset keys (0.10)
                self.preset = preset[@"VideoPreset"];
                self.tune   = preset[@"VideoTune"];
                self.videoOptionExtra = preset[@"VideoOptionExtra"];
                self.profile = preset[@"VideoProfile"];
                self.level   = preset[@"VideoLevel"];
            }
        }
    }
    else
    {
        if (preset[@"lavcOption"])
        {
            // Load the old format
            self.videoOptionExtra = preset[@"lavcOption"];
        }
        else
        {
            self.videoOptionExtra = preset[@"VideoOptionExtra"];
        }
    }

    int qualityType = [preset[@"VideoQualityType"] intValue] - 1;
    /* Note since the removal of Target Size encoding, the possible values for VideoQuality type are 0 - 1.
     * Therefore any preset that uses the old 2 for Constant Quality would now use 1 since there is one less index
     * for the fVidQualityMatrix. It should also be noted that any preset that used the deprecated Target Size
     * setting of 0 would set us to 0 or ABR since ABR is now tagged 0. Fortunately this does not affect any built-in
     * presets since they all use Constant Quality or Average Bitrate.*/
    if (qualityType == -1)
    {
        qualityType = 0;
    }
    self.qualityType = qualityType;

    self.avgBitrate = [preset[@"VideoAvgBitrate"] intValue];
    self.quality = [preset[@"VideoQualitySlider"] floatValue];

    // Video framerate
    if ([preset[@"VideoFramerate"] isEqualToString:@"Same as source"])
    {
        // Now set the Video Frame Rate Mode to either vfr or cfr according to the preset.
        if (!preset[@"VideoFramerateMode"] ||
            [preset[@"VideoFramerateMode"] isEqualToString:@"vfr"])
        {
            self.frameRateMode = 0; // we want vfr
        }
        else
        {
            self.frameRateMode = 1; // we want cfr
        }
    }
    else
    {
        // Now set the Video Frame Rate Mode to either pfr or cfr according to the preset.
        if ([preset[@"VideoFramerateMode"] isEqualToString:@"pfr"] ||
            [preset[@"VideoFrameratePFR"]  intValue] == 1)
        {
            self.frameRateMode = 0; // we want pfr
        }
        else
        {
            self.frameRateMode = 1; // we want cfr
        }
    }
    // map legacy names via libhb.
    int intValue = hb_video_framerate_get_from_name([preset[@"VideoFramerate"] UTF8String]);
    if (intValue == -1)
    {
        intValue = 0;
    }
    self.frameRate = intValue;

    // 2 Pass Encoding.
    self.twoPass = [preset[@"VideoTwoPass"] intValue];

    // Turbo 1st pass for 2 Pass Encoding.
    self.turboTwoPass = [preset[@"VideoTurboTwoPass"] intValue];
}

- (void)prepareVideoForPreset:(NSMutableDictionary *)preset
{
    preset[@"VideoEncoder"] = @(hb_video_encoder_get_name(self.encoder));

    // x264 Options, this will either be advanced panel or the video tabs x264 presets panel with modded option string
    if (self.advancedOptions)
    {
        // use the old advanced panel.
        preset[@"x264UseAdvancedOptions"] = @1;
        preset[@"x264Option"] = self.videoOptionExtra;
    }
    else if (self.encoder == HB_VCODEC_X264 || self.encoder == HB_VCODEC_X265)
    {
        // use the new preset system.
        preset[@"x264UseAdvancedOptions"] = @0;
        preset[@"VideoPreset"]      = self.preset;
        preset[@"VideoTune"]        = self.tune;
        preset[@"VideoOptionExtra"] = self.videoOptionExtra;
        preset[@"VideoProfile"]     = self.profile;
        preset[@"VideoLevel"]       = self.level;
    }
    else
    {
        // FFmpeg (lavc) Option String
        preset[@"VideoOptionExtra"] = self.videoOptionExtra;
    }

    /* though there are actually only 0 - 1 types available in the ui we need to map to the old 0 - 2
     * set of indexes from when we had 0 == Target , 1 == Abr and 2 == Constant Quality for presets
     * to take care of any legacy presets. */
    preset[@"VideoQualityType"] = @(self.qualityType + 1);
    preset[@"VideoAvgBitrate"] = @(self.avgBitrate);
    preset[@"VideoQualitySlider"] = @(self.quality);

    /* Video framerate and framerate mode */
    if (self.frameRateMode == 1)
    {
        preset[@"VideoFramerateMode"] = @"cfr";
    }
    if (self.frameRate == 0) // Same as source is selected
    {
        preset[@"VideoFramerate"] = @"Same as source";

        if (self.frameRateMode == 0)
        {
            preset[@"VideoFramerateMode"] = @"vfr";
        }
    }
    else // translate the rate (selected item's tag) to the official libhb name
    {
        preset[@"VideoFramerate"] = [NSString stringWithFormat:@"%s",
                                     hb_video_framerate_get_name((int)self.frameRate)];

        if (self.frameRateMode == 0)
        {
            preset[@"VideoFramerateMode"] = @"pfr";
        }
    }

    preset[@"VideoTwoPass"] = @(self.twoPass);
    preset[@"VideoTurboTwoPass"] = @(self.turboTwoPass);
}

- (void)applyVideoSettingsFromQueue:(NSDictionary *)queueToApply
{
    // Video encoder
    self.encoder = [queueToApply[@"JobVideoEncoderVcodec"] intValue];

    // Advanced x264 options
    if ([queueToApply[@"x264UseAdvancedOptions"] intValue])
    {
        // we are using the advanced panel
        self.preset = @"medium";
        self.tune = nil;
        self.profile = nil;
        self.level = nil;
        self.videoOptionExtra = queueToApply[@"x264Option"];
        self.advancedOptions = YES;
    }
    else if (self.encoder == HB_VCODEC_X264 || self.encoder == HB_VCODEC_X265)
    {
        // we are using the x264 preset system
        self.preset = queueToApply[@"VideoPreset"];
        self.tune = queueToApply[@"VideoTune"];
        self.videoOptionExtra = queueToApply[@"VideoOptionExtra"];
        self.profile = queueToApply[@"VideoProfile"];
        self.level = queueToApply[@"VideoLevel"];
    }
    else
    {
        self.videoOptionExtra = queueToApply[@"VideoOptionExtra"];
    }

    self.qualityType = [queueToApply[@"VideoQualityType"] intValue] - 1;

    self.avgBitrate = [queueToApply[@"VideoAvgBitrate"] intValue];
    self.quality = [queueToApply[@"VideoQualitySlider"] doubleValue];

    // Video framerate
    if ([queueToApply[@"JobIndexVideoFramerate"] intValue] == 0)
    {
        // Now set the Video Frame Rate Mode to either vfr or cfr according to the preset
        if ([queueToApply[@"VideoFramerateMode"] isEqualToString:@"vfr"])
        {
            self.frameRateMode = 0; // we want vfr
        }
        else
        {
            self.frameRateMode = 1; // we want cfr
        }
    }
    else
    {
        // Now set the Video Frame Rate Mode to either pfr or cfr according to the preset
        if ([queueToApply[@"VideoFramerateMode"] isEqualToString:@"pfr"])
        {
            self.frameRateMode = 0; // we want pfr
        }
        else
        {
            self.frameRateMode = 1; // we want cfr
        }
    }

    self.frameRate = hb_video_framerate_get_from_name([queueToApply[@"VideoFramerate"] UTF8String]);

    self.twoPass = [queueToApply[@"VideoTwoPass"] intValue];
    self.turboTwoPass = [queueToApply[@"VideoTurboTwoPass"] intValue];
}

- (void)prepareVideoForQueueFileJob:(NSMutableDictionary *)queueFileJob
{
    // Video encoder.
    queueFileJob[@"VideoEncoder"] = @(hb_video_encoder_get_name(self.encoder));
    queueFileJob[@"JobVideoEncoderVcodec"] = @(self.encoder);

    // x264 advanced options.
    if (self.advancedOptions)
    {
        // we are using the advanced panel
        queueFileJob[@"x264UseAdvancedOptions"] = @1;
        queueFileJob[@"x264Option"] = self.videoOptionExtra;
     }
     else if (self.encoder == HB_VCODEC_X264 || self.encoder == HB_VCODEC_X265)
     {
         // we are using the x264/x265 preset system.
         queueFileJob[@"x264UseAdvancedOptions"] = @0;
         queueFileJob[@"VideoPreset"] = self.preset;
         queueFileJob[@"VideoTune"] = self.tune;
         queueFileJob[@"VideoOptionExtra"] = self.videoOptionExtra;
         queueFileJob[@"VideoProfile"] = self.profile;
         queueFileJob[@"VideoLevel"] = self.level;
     }
     else
     {
         // FFmpeg (lavc) Option String.
         queueFileJob[@"VideoOptionExtra"] = self.videoOptionExtra;
     }

    queueFileJob[@"VideoQualityType"] = @(self.qualityType + 1);
    queueFileJob[@"VideoAvgBitrate"] = @(self.avgBitrate);
    queueFileJob[@"VideoQualitySlider"] = @(self.quality);

    // Framerate
    if (self.frameRate)
    {
        queueFileJob[@"VideoFramerate"] = @(hb_video_framerate_get_name(self.frameRate));
    }
    else
    {
        queueFileJob[@"VideoFramerate"] = @"Same as source";
    }
    queueFileJob[@"JobIndexVideoFramerate"] = @(self.frameRate);

    // Frame Rate Mode
    if (self.frameRateMode == 1) // if selected we are cfr regardless of the frame rate popup
    {
        queueFileJob[@"VideoFramerateMode"] = @"cfr";
    }
    else
    {
        if (self.frameRate == 0) // Same as source frame rate
        {
            queueFileJob[@"VideoFramerateMode"] = @"vfr";
        }
        else
        {
            queueFileJob[@"VideoFramerateMode"] = @"pfr";
        }
    }

    // 2 Pass Encoding
    queueFileJob[@"VideoTwoPass"] = @(self.twoPass);
    queueFileJob[@"VideoTurboTwoPass"] = @(self.turboTwoPass);
}

@end

#pragma mark - Value Trasformers

@implementation HBVideoEncoderTransformer

+ (Class)transformedValueClass
{
    return [NSString class];
}

- (id)transformedValue:(id)value
{
    const char *name = hb_video_encoder_get_name([value intValue]);
    if (name)
    {
        return @(name);
    }
    else
    {
        return nil;
    }
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)reverseTransformedValue:(id)value
{
    return @(hb_video_encoder_get_from_name([value UTF8String]));
}

@end

@implementation HBFrameRateTransformer

+ (Class)transformedValueClass
{
    return [NSString class];
}

- (id)transformedValue:(id)value
{
    const char *name = hb_video_framerate_get_name([value intValue]);
    if (name)
    {
        if (!strcmp(name, "23.976"))
        {
            return @"23.976 (NTSC Film)";
        }
        else if (!strcmp(name, "25"))
        {
            return @"25 (PAL Film/Video)";
        }
        else if (!strcmp(name, "29.97"))
        {
            return @"29.97 (NTSC Video)";
        }
        else
        {
            return @(name);
        }
    }
    else
    {
        return NSLocalizedString(@"Same as source", @"");
    }
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)reverseTransformedValue:(id)value
{
    if ([value isEqualTo:NSLocalizedString(@"Same as source", @"")])
    {
        return @0;
    }
    else
    {
        return @(hb_video_framerate_get_from_name([value UTF8String]));
    }
}

@end

@implementation HBPresetsTransformer
{
    int _encoder;
}

- (instancetype)initWithEncoder:(int)encoder
{
    self = [super init];
    if (self)
    {
        _encoder = encoder;
    }
    return self;
}

+ (Class)transformedValueClass
{
    return [NSNumber class];
}

- (id)transformedValue:(id)value
{
    if (value)
    {
        const char * const *presets = hb_video_encoder_get_presets(_encoder);
        for (int i = 0; presets != NULL && presets[i] != NULL; i++)
        {
            if (!strcasecmp(presets[i], [value UTF8String]))
            {
                return @(i);
            }
        }
    }

    return @(-1);
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)reverseTransformedValue:(id)value
{
    const char * const *presets = hb_video_encoder_get_presets(_encoder);
    for (int i = 0; presets != NULL && presets[i] != NULL; i++)
    {
        if (i == [value intValue])
        {
            return @(presets[i]);
        }
    }

    return @"none";
}

@end

@implementation HBQualityTransformer
{
    BOOL _reverse;
    double _min;
    double _max;
}

- (instancetype)initWithReversedDirection:(BOOL)reverse min:(double)min max:(double)max
{
    self = [super init];
    if (self)
    {
        _reverse = reverse;
        _min = min;
        _max = max;
    }

    return self;
}

+ (Class)transformedValueClass
{
    return [NSNumber class];
}

- (id)transformedValue:(id)value
{
    if (_reverse)
    {
        double inverseValue = _min + _max - [value doubleValue];
        return @(inverseValue);
    }
    else
    {
        return value;
    }
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)reverseTransformedValue:(id)value
{
    if (_reverse)
    {
        double inverseValue = _min + _max - [value doubleValue];
        return @(inverseValue);
    }
    else
    {
        return value;
    }
}

@end