OSDN Git Service

WinGui:
[handbrake-jp/handbrake-jp-git.git] / macosx / Controller.mm
1 /* $Id: Controller.mm,v 1.79 2005/11/04 19:41:32 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.m0k.org/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #include "Controller.h"
8 #include "a52dec/a52.h"
9 #import "HBOutputPanelController.h"
10 #import "HBPreferencesController.h"
11 /* Added to integrate scanning into HBController */
12 #include <IOKit/IOKitLib.h>
13 #include <IOKit/storage/IOMedia.h>
14 #include <IOKit/storage/IODVDMedia.h>
15 #include "HBDVDDetector.h"
16 #include "dvdread/dvd_reader.h"
17
18 #define _(a) NSLocalizedString(a,NULL)
19
20 static int FormatSettings[4][10] =
21   { { HB_MUX_MP4 | HB_VCODEC_FFMPEG | HB_ACODEC_FAAC,
22           HB_MUX_MP4 | HB_VCODEC_X264   | HB_ACODEC_FAAC,
23           0,
24           0},
25     { HB_MUX_AVI | HB_VCODEC_FFMPEG | HB_ACODEC_LAME,
26           HB_MUX_AVI | HB_VCODEC_FFMPEG | HB_ACODEC_AC3,
27           HB_MUX_AVI | HB_VCODEC_X264   | HB_ACODEC_LAME,
28           HB_MUX_AVI | HB_VCODEC_X264   | HB_ACODEC_AC3},
29     { HB_MUX_OGM | HB_VCODEC_FFMPEG | HB_ACODEC_VORBIS,
30           HB_MUX_OGM | HB_VCODEC_FFMPEG | HB_ACODEC_LAME,
31           0,
32           0 },
33     { HB_MUX_MKV | HB_VCODEC_FFMPEG | HB_ACODEC_FAAC,
34           HB_MUX_MKV | HB_VCODEC_FFMPEG | HB_ACODEC_AC3,
35           HB_MUX_MKV | HB_VCODEC_FFMPEG | HB_ACODEC_LAME,
36           HB_MUX_MKV | HB_VCODEC_FFMPEG | HB_ACODEC_VORBIS,
37           HB_MUX_MKV | HB_VCODEC_X264   | HB_ACODEC_FAAC,
38           HB_MUX_MKV | HB_VCODEC_X264   | HB_ACODEC_AC3,
39           HB_MUX_MKV | HB_VCODEC_X264   | HB_ACODEC_LAME,
40           HB_MUX_MKV | HB_VCODEC_X264   | HB_ACODEC_VORBIS,
41           0,
42           0 } };
43
44
45 /* We setup the toolbar values here */
46 static NSString *        ToggleDrawerIdentifier             = @"Toggle Drawer Item Identifier";
47 static NSString *        StartEncodingIdentifier            = @"Start Encoding Item Identifier";
48 static NSString *        PauseEncodingIdentifier            = @"Pause Encoding Item Identifier";
49 static NSString *        ShowQueueIdentifier                = @"Show Queue Item Identifier";
50 static NSString *        AddToQueueIdentifier               = @"Add to Queue Item Identifier";
51 static NSString *        ShowActivityIdentifier             = @"Debug Output Item Identifier";
52 static NSString *        ChooseSourceIdentifier             = @"Choose Source Item Identifier";
53
54
55 /*******************************
56  * HBController implementation *
57  *******************************/
58 @implementation HBController
59
60 - init
61 {
62     self = [super init];
63     [HBPreferencesController registerUserDefaults];
64     fHandle = NULL;
65     outputPanel = [[HBOutputPanelController alloc] init];
66     fPictureController = [[PictureController alloc] initWithDelegate:self];
67     fQueueController = [[HBQueueController alloc] init];
68     fAdvancedOptions = [[HBAdvancedController alloc] init];
69     fPreferencesController = [[HBPreferencesController alloc] init];
70     return self;
71 }
72
73 - (void) applicationDidFinishLaunching: (NSNotification *) notification
74 {
75     int    build;
76     char * version;
77
78     // Init libhb
79         int debugLevel = [[NSUserDefaults standardUserDefaults] boolForKey:@"ShowVerboseOutput"] ? HB_DEBUG_ALL : HB_DEBUG_NONE;
80     fHandle = hb_init(debugLevel, [[NSUserDefaults standardUserDefaults] boolForKey:@"CheckForUpdates"]);
81
82         // Set the Growl Delegate
83     [GrowlApplicationBridge setGrowlDelegate: self];    
84     /* Init others controllers */
85     [fPictureController SetHandle: fHandle];
86     [fQueueController   setHandle: fHandle];
87     [fQueueController   setHBController: self];
88         
89     fChapterTitlesDelegate = [[ChapterTitles alloc] init];
90     [fChapterTable setDataSource:fChapterTitlesDelegate];
91
92      /* Call UpdateUI every 1/2 sec */
93     [[NSRunLoop currentRunLoop] addTimer: [NSTimer
94         scheduledTimerWithTimeInterval: 0.5 target: self
95         selector: @selector( updateUI: ) userInfo: NULL repeats: YES]
96         forMode: NSEventTrackingRunLoopMode];
97
98     if( ( build = hb_check_update( fHandle, &version ) ) > -1 )
99     {
100         /* Update available - tell the user */
101         
102         NSBeginInformationalAlertSheet( _( @"Update is available" ),
103             _( @"Go get it!" ), _( @"Discard" ), NULL, fWindow, self,
104             @selector( updateAlertDone:returnCode:contextInfo: ),
105             NULL, NULL, [NSString stringWithFormat:
106             _( @"HandBrake %s (build %d) is now available for download." ),
107             version, build] );
108         return;
109
110     }
111
112     // Open debug output window now if it was visible when HB was closed
113     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
114         [self showDebugOutputPanel:nil];
115
116     // Open queue window now if it was visible when HB was closed
117     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
118         [self showQueueWindow:nil];
119
120         [self openMainWindow:nil];
121         
122     /* Show scan panel ASAP */
123     [self performSelectorOnMainThread: @selector(showScanPanel:)
124         withObject: NULL waitUntilDone: NO];
125 }
126
127 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
128 {
129     // Warn if encoding a movie
130     hb_state_t s;
131     hb_get_state( fHandle, &s );
132     hb_job_t * job = hb_current_job( fHandle );
133     if ( job && ( s.state != HB_STATE_IDLE ) )
134     {
135         hb_job_t * job = hb_current_job( fHandle );
136         int result = NSRunCriticalAlertPanel(
137                 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
138                 NSLocalizedString(@"%@ is currently encoding. If you quit HandBrake, your movie will be lost. Do you want to quit anyway?", nil),
139                 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil,
140                 job ? [NSString stringWithUTF8String:job->title->name] : @"A movie" );
141         
142         if (result == NSAlertDefaultReturn)
143         {
144             [self doCancelCurrentJob];
145             return NSTerminateNow;
146         }
147         else
148             return NSTerminateCancel;
149     }
150     
151     // Warn if items still in the queue
152     else if ( hb_count( fHandle ) > 0 )
153     {
154         int result = NSRunCriticalAlertPanel(
155                 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
156                 NSLocalizedString(@"One or more encodes are queued for encoding. Do you want to quit anyway?", nil),
157                 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
158         
159         if ( result == NSAlertDefaultReturn )
160             return NSTerminateNow;
161         else
162             return NSTerminateCancel;
163     }
164     
165     return NSTerminateNow;
166 }
167
168 - (void)applicationWillTerminate:(NSNotification *)aNotification
169 {
170         [outputPanel release];
171         [fQueueController release];
172         hb_close(&fHandle);
173 }
174
175
176 - (void) awakeFromNib
177 {
178     [fWindow center];
179     [fWindow setExcludedFromWindowsMenu:YES];
180     [fAdvancedOptions setView:fAdvancedView];
181
182     /* Initialize currentScanCount so HB can use it to
183                 evaluate successive scans */
184         currentScanCount = 0;
185         
186     /* Init UserPresets .plist */
187         [self loadPresets];
188                 
189         fRipIndicatorShown = NO;  // initially out of view in the nib
190         
191         /* Show/Dont Show Presets drawer upon launch based
192                 on user preference DefaultPresetsDrawerShow*/
193         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0)
194         {
195                 [fPresetDrawer open];
196         }
197         
198         
199     /* Destination box*/
200     [fDstFormatPopUp removeAllItems];
201     [fDstFormatPopUp addItemWithTitle: _( @"MP4 file" )];
202     [fDstFormatPopUp addItemWithTitle: _( @"AVI file" )];
203     [fDstFormatPopUp addItemWithTitle: _( @"OGM file" )];
204         [fDstFormatPopUp addItemWithTitle: _( @"MKV file" )];
205     [fDstFormatPopUp selectItemAtIndex: 0];
206         
207     [self formatPopUpChanged: NULL];
208     
209         /* We enable the create chapters checkbox here since we are .mp4 */     
210         [fCreateChapterMarkers setEnabled: YES];
211         if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
212         {
213                 [fCreateChapterMarkers setState: NSOnState];
214         }
215         
216         
217         
218         
219     [fDstFile2Field setStringValue: [NSString stringWithFormat:
220         @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
221         
222     /* Video encoder */
223     [fVidEncoderPopUp removeAllItems];
224     [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
225     [fVidEncoderPopUp addItemWithTitle: @"XviD"];
226         
227     
228         
229     /* Video quality */
230     [fVidTargetSizeField setIntValue: 700];
231         [fVidBitrateField    setIntValue: 1000];
232         
233     [fVidQualityMatrix   selectCell: fVidBitrateCell];
234     [self videoMatrixChanged: NULL];
235         
236     /* Video framerate */
237     [fVidRatePopUp removeAllItems];
238         [fVidRatePopUp addItemWithTitle: _( @"Same as source" )];
239     for( int i = 0; i < hb_video_rates_count; i++ )
240     {
241         if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
242                 {
243                         [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
244                                 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
245                 }
246                 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
247                 {
248                         [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
249                                 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
250                 }
251                 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
252                 {
253                         [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
254                                 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
255                 }
256                 else
257                 {
258                         [fVidRatePopUp addItemWithTitle:
259                                 [NSString stringWithCString: hb_video_rates[i].string]];
260                 }
261     }
262     [fVidRatePopUp selectItemAtIndex: 0];
263         
264         /* Picture Settings */
265         [fPicLabelPAROutputX setStringValue: @""];
266         [fPicSettingPARWidth setStringValue: @""];
267         [fPicSettingPARHeight setStringValue:  @""];
268         
269         /* Set Auto Crop to On at launch */
270     [fPictureController setAutoCrop:YES];
271         
272         /* Audio bitrate */
273     [fAudBitratePopUp removeAllItems];
274     for( int i = 0; i < hb_audio_bitrates_count; i++ )
275     {
276         [fAudBitratePopUp addItemWithTitle:
277                                 [NSString stringWithCString: hb_audio_bitrates[i].string]];
278
279     }
280     [fAudBitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
281         
282     /* Audio samplerate */
283     [fAudRatePopUp removeAllItems];
284     for( int i = 0; i < hb_audio_rates_count; i++ )
285     {
286         [fAudRatePopUp addItemWithTitle:
287             [NSString stringWithCString: hb_audio_rates[i].string]];
288     }
289     [fAudRatePopUp selectItemAtIndex: hb_audio_rates_default];
290         
291     /* Bottom */
292     [fStatusField setStringValue: @""];
293         
294     [self enableUI: NO];
295         [self setupToolbar];
296         
297         [fPresetsActionButton setMenu:fPresetsActionMenu];
298         
299         /* We disable the Turbo 1st pass checkbox since we are not x264 */
300         [fVidTurboPassCheck setEnabled: NO];
301         [fVidTurboPassCheck setState: NSOffState];
302         
303         
304         /* lets get our default prefs here */
305         [self getDefaultPresets: NULL];
306         /* lets initialize the current successful scancount here to 0 */
307         currentSuccessfulScanCount = 0;
308     
309 }
310
311 - (void) loadPresets {
312         /* We declare the default NSFileManager into fileManager */
313         NSFileManager * fileManager = [NSFileManager defaultManager];
314         /* we set the files and support paths here */
315         AppSupportDirectory = @"~/Library/Application Support/HandBrake";
316     AppSupportDirectory = [AppSupportDirectory stringByExpandingTildeInPath];
317     //UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
318     //UserPresetsFile = [UserPresetsFile stringByExpandingTildeInPath];
319         /* We check for the app support directory for handbrake */
320         if ([fileManager fileExistsAtPath:AppSupportDirectory] == 0) 
321         {
322                 // If it doesnt exist yet, we create it here 
323                 [fileManager createDirectoryAtPath:AppSupportDirectory attributes:nil];
324         }
325         /* We check for the presets.plist here */
326         if ([fileManager fileExistsAtPath:UserPresetsFile] == 0) 
327         {
328                 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
329         }
330         UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
331         UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
332         
333         UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
334         if (nil == UserPresets) 
335         {
336                 UserPresets = [[NSMutableArray alloc] init];
337                 [self addFactoryPresets:NULL];
338         }
339         
340 }
341
342 // ============================================================
343 // NSToolbar Related Methods
344 // ============================================================
345
346 - (void) setupToolbar {
347     toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
348     
349     [toolbar setAllowsUserCustomization: YES];
350     [toolbar setAutosavesConfiguration: YES];
351     [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
352     
353     [toolbar setDelegate: self];
354     
355     [fWindow setToolbar: toolbar];
356 }
357
358 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
359     (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
360     NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: itemIdent];
361     
362     if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
363     {
364         [item setLabel: @"Toggle Presets"];
365         [item setPaletteLabel: @"Toggler Presets"];
366         [item setToolTip: @"Open/Close Preset Drawer"];
367         [item setImage: [NSImage imageNamed: @"Drawer"]];
368         [item setTarget: self];
369         [item setAction: @selector(toggleDrawer:)];
370         [item setAutovalidates: NO];
371     }
372     else if ([itemIdent isEqualToString: StartEncodingIdentifier])
373     {
374         [item setLabel: @"Start"];
375         [item setPaletteLabel: @"Start Encoding"];
376         [item setToolTip: @"Start Encoding"];
377         [item setImage: [NSImage imageNamed: @"Play"]];
378         [item setTarget: self];
379         [item setAction: @selector(Rip:)];
380     }
381     else if ([itemIdent isEqualToString: ShowQueueIdentifier])
382     {
383         [item setLabel: @"Show Queue"];
384         [item setPaletteLabel: @"Show Queue"];
385         [item setToolTip: @"Show Queue"];
386         [item setImage: [NSImage imageNamed: @"Queue"]];
387         [item setTarget: self];
388         [item setAction: @selector(showQueueWindow:)];
389         [item setAutovalidates: NO];
390     }
391     else if ([itemIdent isEqualToString: AddToQueueIdentifier])
392     {
393         [item setLabel: @"Add to Queue"];
394         [item setPaletteLabel: @"Add to Queue"];
395         [item setToolTip: @"Add to Queue"];
396         [item setImage: [NSImage imageNamed: @"AddToQueue"]];
397         [item setTarget: self];
398         [item setAction: @selector(addToQueue:)];
399     }
400     else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
401     {
402         [item setLabel: @"Pause"];
403         [item setPaletteLabel: @"Pause Encoding"];
404         [item setToolTip: @"Pause Encoding"];
405         [item setImage: [NSImage imageNamed: @"Pause"]];
406         [item setTarget: self];
407         [item setAction: @selector(Pause:)];
408     }
409     else if ([itemIdent isEqualToString: ShowActivityIdentifier]) {
410         [item setLabel: @"Activity Window"];
411         [item setPaletteLabel: @"Show Activity Window"];
412         [item setToolTip: @"Show Activity Window"];
413         [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
414         [item setTarget: self];
415         [item setAction: @selector(showDebugOutputPanel:)];
416         [item setAutovalidates: NO];
417     }
418     else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
419     {
420         [item setLabel: @"Source"];
421         [item setPaletteLabel: @"Source"];
422         [item setToolTip: @"Choose Video Source"];
423         [item setImage: [NSImage imageNamed: @"Source"]];
424         [item setTarget: self];
425         [item setAction: @selector(showScanPanel:)];
426     }
427     else
428     {
429         [item release];
430         return nil;
431     }
432
433     return item;
434 }
435
436 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
437 {
438     return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
439         PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier, 
440                 NSToolbarSpaceItemIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
441 }
442
443 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
444 {
445     return [NSArray arrayWithObjects:  StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
446         ChooseSourceIdentifier, ShowQueueIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
447         NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
448         NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
449 }
450
451 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
452 {
453     NSString * ident = [toolbarItem itemIdentifier];
454         
455     if (fHandle)
456     {
457         hb_state_t s;
458         hb_get_state2( fHandle, &s );
459         
460         if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
461         {
462             if ([ident isEqualToString: StartEncodingIdentifier])
463             {
464                 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
465                 [toolbarItem setLabel: @"Stop"];
466                 [toolbarItem setPaletteLabel: @"Stop"];
467                 [toolbarItem setToolTip: @"Stop Encoding"];
468                 return YES;
469             }
470             if ([ident isEqualToString: PauseEncodingIdentifier])
471             {
472                 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
473                 [toolbarItem setLabel: @"Pause"];
474                 [toolbarItem setPaletteLabel: @"Pause Encoding"];
475                 [toolbarItem setToolTip: @"Pause Encoding"];
476                 return YES;
477             }
478             if (SuccessfulScan)
479                 if ([ident isEqualToString: AddToQueueIdentifier])
480                     return YES;
481         }
482         else if (s.state == HB_STATE_PAUSED)
483         {
484             if ([ident isEqualToString: PauseEncodingIdentifier])
485             {
486                 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
487                 [toolbarItem setLabel: @"Resume"];
488                 [toolbarItem setPaletteLabel: @"Resume Encoding"];
489                 [toolbarItem setToolTip: @"Resume Encoding"];
490                 return YES;
491             }
492             if ([ident isEqualToString: StartEncodingIdentifier])
493                 return YES;
494             if ([ident isEqualToString: AddToQueueIdentifier])
495                 return YES;
496         }
497         else if (s.state == HB_STATE_SCANNING)
498             return NO;
499         else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
500         {
501             if ([ident isEqualToString: StartEncodingIdentifier])
502             {
503                 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
504                 if (hb_count(fHandle) > 0)
505                     [toolbarItem setLabel: @"Start Queue"];
506                 else
507                     [toolbarItem setLabel: @"Start"];
508                 [toolbarItem setPaletteLabel: @"Start Encoding"];
509                 [toolbarItem setToolTip: @"Start Encoding"];
510                 return YES;
511             }
512             if ([ident isEqualToString: AddToQueueIdentifier])
513                 return YES;
514         }
515
516     }
517     
518     if ([ident isEqualToString: ShowQueueIdentifier])
519         return YES;
520     if ([ident isEqualToString: ToggleDrawerIdentifier])
521         return YES;
522     if ([ident isEqualToString: ChooseSourceIdentifier])
523         return YES;
524     if ([ident isEqualToString: ShowActivityIdentifier])
525         return YES;
526     
527     return NO;
528 }
529
530 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
531 {
532     SEL action = [menuItem action];
533     
534     hb_state_t s;
535     hb_get_state2( fHandle, &s );
536     
537     if (fHandle)
538     {
539         if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
540             return SuccessfulScan && [fWindow attachedSheet] == nil;
541         
542         if (action == @selector(showScanPanel:))
543         {
544             if (s.state == HB_STATE_SCANNING)
545                 return NO;
546             else
547                 return [fWindow attachedSheet] == nil;
548         }
549         if (action == @selector(selectDefaultPreset:))
550             return [tableView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
551         if (action == @selector(Pause:))
552         {
553             if (s.state == HB_STATE_WORKING)
554             {
555                 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
556                     [menuItem setTitle:@"Pause Encoding"];
557                 return YES;
558             }
559             else if (s.state == HB_STATE_PAUSED)
560             {
561                 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
562                     [menuItem setTitle:@"Resume Encoding"];
563                 return YES;
564             }
565             else
566                 return NO;
567         }
568         if (action == @selector(Rip:))
569             if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
570             {
571                 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
572                     [menuItem setTitle:@"Stop Encoding"];
573                 return YES;
574             }
575             else if (SuccessfulScan)
576             {
577                 if(![[menuItem title] isEqualToString:@"Start Encoding"])
578                     [menuItem setTitle:@"Start Encoding"];
579                 return [fWindow attachedSheet] == nil;
580             }
581             else
582                 return NO;
583         }
584     
585     return YES;
586 }
587
588
589 // register a test notification and make
590 // it enabled by default
591 #define SERVICE_NAME @"Encode Done"
592 - (NSDictionary *)registrationDictionaryForGrowl 
593
594     NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys: 
595     [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL, 
596     [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT, 
597     nil]; 
598
599     return registrationDictionary; 
600
601
602 - (void) TranslateStrings
603 {
604     [fSrcTitleField     setStringValue: _( @"Title:" )];
605     [fSrcChapterField   setStringValue: _( @"Chapters:" )];
606     [fSrcChapterToField setStringValue: _( @"to" )];
607     [fSrcDuration1Field setStringValue: _( @"Duration:" )];
608
609     [fDstFormatField    setStringValue: _( @"Format:" )];
610     [fDstCodecsField    setStringValue: _( @"Codecs:" )];
611     [fDstFile1Field     setStringValue: _( @"File:" )];
612     [fDstBrowseButton   setTitle:       _( @"Browse" )];
613
614     [fVidRateField      setStringValue: _( @"Framerate (fps):" )];
615     [fVidEncoderField   setStringValue: _( @"Encoder:" )];
616     [fVidQualityField   setStringValue: _( @"Quality:" )];
617 }
618
619 /***********************************************************************
620  * UpdateDockIcon
621  ***********************************************************************
622  * Shows a progression bar on the dock icon, filled according to
623  * 'progress' (0.0 <= progress <= 1.0).
624  * Called with progress < 0.0 or progress > 1.0, restores the original
625  * icon.
626  **********************************************************************/
627 - (void) UpdateDockIcon: (float) progress
628 {
629     NSImage * icon;
630     NSData * tiff;
631     NSBitmapImageRep * bmp;
632     uint32_t * pen;
633     uint32_t black = htonl( 0x000000FF );
634     uint32_t red   = htonl( 0xFF0000FF );
635     uint32_t white = htonl( 0xFFFFFFFF );
636     int row_start, row_end;
637     int i, j;
638
639     /* Get application original icon */
640     icon = [NSImage imageNamed: @"NSApplicationIcon"];
641
642     if( progress < 0.0 || progress > 1.0 )
643     {
644         [NSApp setApplicationIconImage: icon];
645         return;
646     }
647
648     /* Get it in a raw bitmap form */
649     tiff = [icon TIFFRepresentationUsingCompression:
650             NSTIFFCompressionNone factor: 1.0];
651     bmp = [NSBitmapImageRep imageRepWithData: tiff];
652     
653     /* Draw the progression bar */
654     /* It's pretty simple (ugly?) now, but I'm no designer */
655
656     row_start = 3 * (int) [bmp size].height / 4;
657     row_end   = 7 * (int) [bmp size].height / 8;
658
659     for( i = row_start; i < row_start + 2; i++ )
660     {
661         pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
662         for( j = 0; j < (int) [bmp size].width; j++ )
663         {
664             pen[j] = black;
665         }
666     }
667     for( i = row_start + 2; i < row_end - 2; i++ )
668     {
669         pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
670         pen[0] = black;
671         pen[1] = black;
672         for( j = 2; j < (int) [bmp size].width - 2; j++ )
673         {
674             if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
675             {
676                 pen[j] = red;
677             }
678             else
679             {
680                 pen[j] = white;
681             }
682         }
683         pen[j]   = black;
684         pen[j+1] = black;
685     }
686     for( i = row_end - 2; i < row_end; i++ )
687     {
688         pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
689         for( j = 0; j < (int) [bmp size].width; j++ )
690         {
691             pen[j] = black;
692         }
693     }
694
695     /* Now update the dock icon */
696     tiff = [bmp TIFFRepresentationUsingCompression:
697             NSTIFFCompressionNone factor: 1.0];
698     icon = [[NSImage alloc] initWithData: tiff];
699     [NSApp setApplicationIconImage: icon];
700     [icon release];
701 }
702
703 - (void) updateUI: (NSTimer *) timer
704 {
705
706     hb_list_t  * list;
707     list = hb_get_titles( fHandle );    
708     /* check to see if there has been a new scan done
709         this bypasses the constraints of HB_STATE_WORKING
710         not allowing setting a newly scanned source */
711         int checkScanCount = hb_get_scancount( fHandle );
712         if (checkScanCount > currentScanCount)
713         {
714                 
715                 currentScanCount = checkScanCount;
716                 //[fScanController Cancel: NULL];
717                 [fScanIndicator setIndeterminate: NO];
718                 [fScanIndicator setDoubleValue: 0.0];
719                 [fScanIndicator setHidden: YES];
720
721                 [self showNewScan: NULL];
722         }
723         
724     hb_state_t s;
725     hb_get_state( fHandle, &s );
726         
727         
728     switch( s.state )
729     {
730         case HB_STATE_IDLE:
731                 break;
732 #define p s.param.scanning                      
733         case HB_STATE_SCANNING:
734                 {
735             [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
736                 _( @"Scanning title %d of %d..." ),
737                 p.title_cur, p.title_count]];
738             [fScanIndicator setIndeterminate: NO];
739                         [fScanIndicator setDoubleValue: 100.0 * ( p.title_cur - 1 ) /
740                 p.title_count];
741             break;
742                 }
743 #undef p
744         
745 #define p s.param.scandone
746         case HB_STATE_SCANDONE:
747         {
748                         
749                         [fScanIndicator setIndeterminate: NO];
750             [fScanIndicator setDoubleValue: 0.0];
751                         [fScanIndicator setHidden: YES];
752                         [self showNewScan: NULL];
753             [toolbar validateVisibleItems];
754                         break;
755         }
756 #undef p
757                         
758 #define p s.param.working
759         case HB_STATE_WORKING:
760         {
761             float progress_total;
762             NSMutableString * string;
763                         /* Currently, p.job_cur and p.job_count get screwed up when adding
764                                 jobs during encoding, if they cannot be fixed in libhb, will implement a
765                                 nasty but working cocoa solution */
766                         /* Update text field */
767                         string = [NSMutableString stringWithFormat: _( @"Encoding: task %d of %d, %.2f %%" ), p.job_cur, p.job_count, 100.0 * p.progress];
768             
769                         if( p.seconds > -1 )
770             {
771                 [string appendFormat:
772                     _( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)" ),
773                     p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
774             }
775             [fStatusField setStringValue: string];
776                         
777             /* Update slider */
778                         progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
779             [fRipIndicator setIndeterminate: NO];
780             [fRipIndicator setDoubleValue: 100.0 * progress_total];
781                         
782             // If progress bar hasn't been revealed at the bottom of the window, do
783             // that now. This code used to be in doRip. I moved it to here to handle
784             // the case where hb_start is called by HBQueueController and not from
785             // HBController.
786             if (!fRipIndicatorShown)
787             {
788                 NSRect frame = [fWindow frame];
789                 if (frame.size.width <= 591)
790                     frame.size.width = 591;
791                 frame.size.height += 36;
792                 frame.origin.y -= 36;
793                 [fWindow setFrame:frame display:YES animate:YES];
794                 fRipIndicatorShown = YES;
795                 /* We check to see if we need to warn the user that the computer will go to sleep
796                    or shut down when encoding is finished */
797                 [self remindUserOfSleepOrShutdown];
798             }
799
800             /* Update dock icon */
801             [self UpdateDockIcon: progress_total];
802                         
803             // Has current job changed? That means the queue has probably changed as
804                         // well so update it
805             if (fLastKnownCurrentJob != hb_current_job(fHandle))
806             {
807                 fLastKnownCurrentJob = hb_current_job(fHandle);
808                 [fQueueController updateQueueUI];
809             }
810             [fQueueController updateCurrentJobUI];
811             
812             break;
813         }
814 #undef p
815                         
816 #define p s.param.muxing
817         case HB_STATE_MUXING:
818         {
819             NSMutableString * string;
820                         
821             /* Update text field */
822             string = [NSMutableString stringWithFormat:
823                 _( @"Muxing..." )];
824             [fStatusField setStringValue: string];
825                         
826             /* Update slider */
827             [fRipIndicator setIndeterminate: YES];
828             [fRipIndicator startAnimation: nil];
829                         
830             /* Update dock icon */
831             [self UpdateDockIcon: 1.0];
832                         
833                         // Pass along the info to HBQueueController
834             [fQueueController updateCurrentJobUI];
835                         
836             break;
837         }
838 #undef p
839                         
840         case HB_STATE_PAUSED:
841                     [fStatusField setStringValue: _( @"Paused" )];
842             
843                         // Pass along the info to HBQueueController
844             [fQueueController updateCurrentJobUI];
845
846             break;
847                         
848         case HB_STATE_WORKDONE:
849         {
850             // HB_STATE_WORKDONE happpens as a result of hblib finishing all its jobs
851             // or someone calling hb_stop. In the latter case, hb_stop does not clear
852             // out the remaining passes/jobs in the queue. We'll do that here.
853                         
854             // Delete all remaining scans of this job, ie, delete whole encodes.
855             hb_job_t * job;
856             while( ( job = hb_job( fHandle, 0 ) ) && (job->sequence_id != 0) )
857                 hb_rem( fHandle, job );
858
859             // Start processing back up if jobs still left in queue
860             if (hb_count(fHandle) > 0)
861             {
862                 hb_start(fHandle);
863                 fEncodeState = 1;
864                 // Validate the toolbar (hack). The toolbar will usually get autovalidated
865                 // before we had the chance to restart the queue, hence it will now be in
866                 // the wrong state.
867                 [toolbar validateVisibleItems];
868                 break;
869             }
870
871             [fStatusField setStringValue: _( @"Done." )];
872             [fRipIndicator setIndeterminate: NO];
873             [fRipIndicator setDoubleValue: 0.0];
874             [toolbar validateVisibleItems];
875
876             /* Restore dock icon */
877             [self UpdateDockIcon: -1.0];
878
879             if (fRipIndicatorShown)
880             {
881                 NSRect frame = [fWindow frame];
882                 if (frame.size.width <= 591)
883                                     frame.size.width = 591;
884                 frame.size.height += -36;
885                 frame.origin.y -= -36;
886                 [fWindow setFrame:frame display:YES animate:YES];
887                                 fRipIndicatorShown = NO;
888                         }
889                         
890             // Queue has been modified so update the UI
891                         fLastKnownCurrentJob = nil;
892             [fQueueController updateQueueUI];
893             [fQueueController updateCurrentJobUI];
894                         
895             /* Check to see if the encode state has not been cancelled
896                                 to determine if we should check for encode done notifications */
897                         if (fEncodeState != 2)                  {
898                                 /* If Growl Notification or Window and Growl has been selected */
899                                 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] || 
900                                         [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
901                 {
902                                         /*Growl Notification*/
903                                         [self showGrowlDoneNotification: NULL];
904                 }
905                 /* If Alert Window or Window and Growl has been selected */
906                                 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] || 
907                                         [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
908                 {
909                                         /*On Screen Notification*/
910                                         int status;
911                                         NSBeep();
912                                         status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake encode is done!", @"OK", nil, nil);
913                                         [NSApp requestUserAttention:NSCriticalRequest];
914                                         if ( status == NSAlertDefaultReturn ) 
915                                         {
916                                                 [self enableUI: YES];
917                                         }
918                 }
919                                 else
920                                 {
921                                         [self enableUI: YES];
922                                 }
923                                    /* If sleep has been selected */ 
924             if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"]) 
925                 { 
926                /* Sleep */ 
927                NSDictionary* errorDict; 
928                NSAppleEventDescriptor* returnDescriptor = NULL; 
929                NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource: 
930                         @"tell application \"Finder\" to sleep"]; 
931                returnDescriptor = [scriptObject executeAndReturnError: &errorDict]; 
932                [scriptObject release]; 
933                [self enableUI: YES]; 
934                 } 
935             /* If Shutdown has been selected */ 
936             if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"]) 
937                 { 
938                /* Shut Down */ 
939                NSDictionary* errorDict; 
940                NSAppleEventDescriptor* returnDescriptor = NULL; 
941                NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource: 
942                         @"tell application \"Finder\" to shut down"]; 
943                returnDescriptor = [scriptObject executeAndReturnError: &errorDict]; 
944                [scriptObject release]; 
945                [self enableUI: YES]; 
946                 }
947                         
948                                                 // MetaX insertion via AppleScript
949                         if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
950                         {
951                         NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", [fDstFile2Field stringValue], @"\")"]];
952                         [myScript executeAndReturnError: nil];
953                         [myScript release];
954                         }
955                         
956                         
957                         }
958                         else
959                         {
960                                 [self enableUI: YES];
961                         }
962             break;
963         }
964     }
965         
966     /* Lets show the queue status here in the main window */
967         int queue_count = hb_count( fHandle );
968         if( queue_count )
969         {
970                 [fQueueStatus setStringValue: [NSString stringWithFormat:
971                         @"%d pass%s in the queue",
972                                                  queue_count, ( queue_count > 1 ) ? "es" : ""]];
973         }
974         else
975         {
976                 [fQueueStatus setStringValue: @""];
977         }
978 }
979
980 - (IBAction) showNewScan:(id)sender
981 {
982         hb_list_t  * list;
983         hb_title_t * title;
984         int indxpri=0;    // Used to search the longuest title (default in combobox)
985         int longuestpri=0; // Used to search the longuest title (default in combobox)
986         
987         list = hb_get_titles( fHandle );
988         
989         if( !hb_list_count( list ) )
990         {
991                 /* We display a message if a valid dvd source was not chosen */
992                 [fSrcDVD2Field setStringValue: @"No Valid Title Found"];
993         SuccessfulScan = 0;
994         }
995         else
996         {
997      /* We increment the successful scancount here by one,
998                    which we use at the end of this function to tell the gui
999                    if this is the first successful scan since launch and whether
1000                    or not we should set all settings to the defaults */
1001                 
1002         currentSuccessfulScanCount++;
1003
1004         [toolbar validateVisibleItems];
1005                 
1006                 [fSrcTitlePopUp removeAllItems];
1007                 for( int i = 0; i < hb_list_count( list ); i++ )
1008                 {
1009                         title = (hb_title_t *) hb_list_item( list, i );
1010                         
1011             currentSource = [NSString stringWithUTF8String: title->dvd];
1012             
1013             /* To get the source name as well as the default output name, first we check to see if
1014                the selected directory is the VIDEO_TS Directory */
1015             if ([[currentSource lastPathComponent] isEqualToString: @"VIDEO_TS"])
1016             {
1017             /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name */
1018             sourceDisplayName = [NSString stringWithFormat:[[currentSource stringByDeletingLastPathComponent] lastPathComponent]];
1019             }
1020             else
1021             {
1022             /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1023             sourceDisplayName = [NSString stringWithFormat:[currentSource lastPathComponent]];
1024             }
1025                         /*Set DVD Name at top of window*/
1026                         [fSrcDVD2Field setStringValue:[NSString stringWithFormat: @"%@", sourceDisplayName]];
1027                         
1028                         /* Use the dvd name in the default output field here 
1029                                 May want to add code to remove blank spaces for some dvd names*/
1030                         /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1031                         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1032                         {
1033                                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1034                                         @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],sourceDisplayName]];
1035                         }
1036                         else
1037                         {
1038                                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1039                                         @"%@/Desktop/%@.mp4", NSHomeDirectory(),sourceDisplayName]];
1040                         }
1041                         
1042                         
1043                         if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1044                         {
1045                                 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1046                                 indxpri=i;
1047                         }
1048                         
1049                         
1050                         int format = [fDstFormatPopUp indexOfSelectedItem];
1051                         char * ext = NULL;
1052                         switch( format )
1053                         {
1054                                 case 0:
1055                                         
1056                                         /*Get Default MP4 File Extension for mpeg4 (.mp4 or .m4v) from prefs*/
1057                                         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
1058                                         {
1059                                                 ext = "m4v";
1060                                         }
1061                                         else
1062                                         {
1063                                                 ext = "mp4";
1064                                         }
1065                                         break;
1066                                 case 1: 
1067                                         ext = "avi";
1068                                         break;
1069                                 case 2:
1070                                         ext = "ogm";
1071                                         break;
1072                                 case 3:
1073                                         ext = "mkv";
1074                                         break;
1075                         }
1076                         
1077                         
1078                         NSString * string = [fDstFile2Field stringValue];
1079                         /* Add/replace File Output name to the correct extension*/
1080                         if( [string characterAtIndex: [string length] - 4] == '.' )
1081                         {
1082                                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1083                                         @"%@.%s", [string substringToIndex: [string length] - 4],
1084                                         ext]];
1085                         }
1086                         else
1087                         {
1088                                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1089                                         @"%@.%s", string, ext]];
1090                         }
1091                         
1092                         
1093                         [fSrcTitlePopUp addItemWithTitle: [NSString
1094                     stringWithFormat: @"%d - %02dh%02dm%02ds",
1095                                 title->index, title->hours, title->minutes,
1096                                 title->seconds]];
1097                         
1098                 }
1099                 // Select the longuest title
1100                 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1101                 [self titlePopUpChanged: NULL];
1102                 
1103                 
1104         SuccessfulScan = 1;
1105                 [self enableUI: YES];
1106                 
1107                 /* if its the initial successful scan after awakeFromNib */
1108            if (currentSuccessfulScanCount == 1)
1109            {
1110            [self selectDefaultPreset: NULL];
1111            /* if Deinterlace upon launch is specified in the prefs, then set to 1 for "Fast",
1112            if not, then set to 0 for none */
1113            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultDeinterlaceOn"] > 0)
1114                [fPictureController setDeinterlace:1];
1115            else
1116                [fPictureController setDeinterlace:0];
1117            }
1118        
1119         }
1120 }
1121
1122 -(IBAction)showGrowlDoneNotification:(id)sender
1123 {
1124   [GrowlApplicationBridge 
1125           notifyWithTitle:@"Put down that cocktail..." 
1126               description:@"your HandBrake encode is done!" 
1127          notificationName:SERVICE_NAME
1128                  iconData:nil 
1129                  priority:0 
1130                  isSticky:1 
1131              clickContext:nil];
1132 }
1133
1134 - (void) enableUI: (bool) b
1135 {
1136     NSControl * controls[] =
1137       { fSrcTitleField, fSrcTitlePopUp,
1138         fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
1139         fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
1140         fDstFormatField, fDstFormatPopUp, fDstCodecsField,
1141         fDstCodecsPopUp, fDstFile1Field, fDstFile2Field,
1142         fDstBrowseButton, fVidRateField, fVidRatePopUp,
1143         fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
1144         fVidQualityMatrix, fVidGrayscaleCheck, fSubField, fSubPopUp,
1145         fAudLang1Field, fAudLang1PopUp, fAudLang2Field, fAudLang2PopUp,
1146         fAudTrack1MixLabel, fAudTrack1MixPopUp, fAudTrack2MixLabel, fAudTrack2MixPopUp,
1147         fAudRateField, fAudRatePopUp, fAudBitrateField,
1148         fAudBitratePopUp, fPictureButton,fQueueStatus, 
1149                 fPicSrcWidth,fPicSrcHeight,fPicSettingWidth,fPicSettingHeight,fPicSettingARkeep,
1150                 fPicSettingDeinterlace,fPicLabelSettings,fPicLabelSrc,fPicLabelOutp,
1151                 fPicLabelAr,fPicLabelDeinterlace,fPicLabelSrcX,fPicLabelOutputX,
1152                 fPicLabelPAROutputX,fPicSettingPARWidth,fPicSettingPARHeight,
1153                 fPicSettingPAR,fPicLabelAnamorphic,tableView,fPresetsAdd,fPresetsDelete,
1154                 fCreateChapterMarkers,fVidTurboPassCheck,fDstMpgLargeFileCheck,fPicLabelAutoCrop,
1155                 fPicSettingAutoCrop,fPicSettingDetelecine,fPicLabelDetelecine,fPicLabelDenoise,fPicSettingDenoise,fSubForcedCheck,};
1156
1157     for( unsigned i = 0;
1158          i < sizeof( controls ) / sizeof( NSControl * ); i++ )
1159     {
1160         if( [[controls[i] className] isEqualToString: @"NSTextField"] )
1161         {
1162             NSTextField * tf = (NSTextField *) controls[i];
1163             if( ![tf isBezeled] )
1164             {
1165                 [tf setTextColor: b ? [NSColor controlTextColor] :
1166                     [NSColor disabledControlTextColor]];
1167                 continue;
1168             }
1169         }
1170         [controls[i] setEnabled: b];
1171
1172     }
1173         
1174         if (b) {
1175
1176         /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
1177         /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
1178         [self setEnabledStateOfAudioMixdownControls: NULL];
1179         
1180         } else {
1181
1182                 [tableView setEnabled: NO];
1183         
1184         }
1185
1186     [self videoMatrixChanged: NULL];
1187     [fAdvancedOptions enableUI:b];
1188 }
1189
1190 - (IBAction) showScanPanel: (id) sender
1191 {
1192     [self enableUI: NO];
1193         
1194         [self browseSources:NULL];
1195 }
1196
1197 - (void) browseSources: (id) sender
1198 {
1199     NSOpenPanel * panel;
1200         
1201     panel = [NSOpenPanel openPanel];
1202     [panel setAllowsMultipleSelection: NO];
1203     [panel setCanChooseFiles: YES];
1204     [panel setCanChooseDirectories: YES ];
1205     NSString * sourceDirectory;
1206         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1207         {
1208                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1209         }
1210         else
1211         {
1212                 sourceDirectory = @"~/Desktop";
1213                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1214         }
1215    [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1216                                    modalForWindow: fWindow modalDelegate: self
1217                                    didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1218                                           contextInfo: nil];
1219 }
1220
1221 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1222                  returnCode: (int) returnCode contextInfo: (void *) contextInfo
1223 {
1224     /* User selected a file to open */
1225         if( returnCode == NSOKButton )
1226     {
1227         [fSrcDVD2Field setStringValue: _( @"Opening a new source ..." )];
1228                 [fScanIndicator setHidden: NO];
1229             [fScanIndicator setIndeterminate: YES];
1230         [fScanIndicator startAnimation: nil];
1231                 
1232                 /* we set the last source directory in the prefs here */
1233                 NSString *sourceDirectory = [[[sheet filenames] objectAtIndex: 0] stringByDeletingLastPathComponent];
1234                 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1235                 
1236         NSString *path = [[sheet filenames] objectAtIndex: 0];
1237         HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1238         if( [detector isVideoDVD] )
1239         {
1240             // The chosen path was actually on a DVD, so use the raw block
1241             // device path instead.
1242             path = [detector devicePath];
1243         }
1244                 
1245                 hb_scan( fHandle, [path UTF8String], 0 );
1246         }
1247         else // User clicked Cancel in browse window
1248         {
1249                 /* if we have a title loaded up */
1250                 if ([[fSrcDVD2Field stringValue] length] > 0)
1251                 {
1252             [self enableUI: YES];
1253         }
1254         }
1255 }
1256
1257 - (IBAction) openMainWindow: (id) sender
1258 {
1259     [fWindow  makeKeyAndOrderFront:nil];
1260     [fWindow setReleasedWhenClosed: YES];
1261 }
1262
1263 - (BOOL) windowShouldClose: (id) sender
1264 {
1265     [fWindow setReleasedWhenClosed: NO];
1266     return YES;
1267 }
1268
1269 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1270 {
1271     if( !flag ) {
1272         [fWindow  makeKeyAndOrderFront:nil];
1273         [fWindow setReleasedWhenClosed: YES];
1274         
1275         return YES;
1276     }
1277     
1278     return NO;
1279 }
1280
1281 - (IBAction) videoMatrixChanged: (id) sender;
1282 {
1283     bool target, bitrate, quality;
1284
1285     target = bitrate = quality = false;
1286     if( [fVidQualityMatrix isEnabled] )
1287     {
1288         switch( [fVidQualityMatrix selectedRow] )
1289         {
1290             case 0:
1291                 target = true;
1292                 break;
1293             case 1:
1294                 bitrate = true;
1295                 break;
1296             case 2:
1297                 quality = true;
1298                 break;
1299         }
1300     }
1301     [fVidTargetSizeField  setEnabled: target];
1302     [fVidBitrateField     setEnabled: bitrate];
1303     [fVidQualitySlider    setEnabled: quality];
1304     [fVidTwoPassCheck     setEnabled: !quality &&
1305         [fVidQualityMatrix isEnabled]];
1306     if( quality )
1307     {
1308         [fVidTwoPassCheck setState: NSOffState];
1309                 [fVidTurboPassCheck setHidden: YES];
1310                 [fVidTurboPassCheck setState: NSOffState];
1311     }
1312
1313     [self qualitySliderChanged: sender];
1314     [self calculateBitrate: sender];
1315         [self customSettingUsed: sender];
1316 }
1317
1318 - (IBAction) qualitySliderChanged: (id) sender
1319 {
1320     [fVidConstantCell setTitle: [NSString stringWithFormat:
1321         _( @"Constant quality: %.0f %%" ), 100.0 *
1322         [fVidQualitySlider floatValue]]];
1323                 [self customSettingUsed: sender];
1324 }
1325
1326 - (IBAction) browseFile: (id) sender
1327 {
1328     /* Open a panel to let the user choose and update the text field */
1329     NSSavePanel * panel = [NSSavePanel savePanel];
1330         /* We get the current file name and path from the destination field here */
1331         [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1332                                    modalForWindow: fWindow modalDelegate: self
1333                                    didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1334                                           contextInfo: NULL];
1335 }
1336
1337 - (void) browseFileDone: (NSSavePanel *) sheet
1338     returnCode: (int) returnCode contextInfo: (void *) contextInfo
1339 {
1340     if( returnCode == NSOKButton )
1341     {
1342         [fDstFile2Field setStringValue: [sheet filename]];
1343     }
1344 }
1345
1346 - (IBAction) showPicturePanel: (id) sender
1347 {
1348         hb_list_t  * list  = hb_get_titles( fHandle );
1349     hb_title_t * title = (hb_title_t *) hb_list_item( list,
1350             [fSrcTitlePopUp indexOfSelectedItem] );
1351     [fPictureController showPanelInWindow:fWindow forTitle:title];
1352 }
1353
1354 - (void)pictureSettingsDidChange {
1355         [self calculatePictureSizing: NULL];
1356 }
1357
1358 - (void) PrepareJob
1359 {
1360     hb_list_t  * list  = hb_get_titles( fHandle );
1361     hb_title_t * title = (hb_title_t *) hb_list_item( list,
1362             [fSrcTitlePopUp indexOfSelectedItem] );
1363     hb_job_t * job = title->job;
1364     //int i;
1365
1366     /* Chapter selection */
1367     job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
1368     job->chapter_end   = [fSrcChapterEndPopUp   indexOfSelectedItem] + 1;
1369         
1370     /* Format and codecs */
1371     int format = [fDstFormatPopUp indexOfSelectedItem];
1372     int codecs = [fDstCodecsPopUp indexOfSelectedItem];
1373     job->mux    = FormatSettings[format][codecs] & HB_MUX_MASK;
1374     job->vcodec = FormatSettings[format][codecs] & HB_VCODEC_MASK;
1375     job->acodec = FormatSettings[format][codecs] & HB_ACODEC_MASK;
1376     /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
1377         if ([fDstFormatPopUp indexOfSelectedItem] == 0)
1378         {
1379         /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
1380                 mpeg4 and the checkbox being checked 
1381                 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
1382                 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"AllowLargeFiles"] > 0 && [fDstMpgLargeFileCheck state] == NSOnState)
1383                 {
1384                         job->largeFileSize = 1;
1385                 }
1386                 else
1387                 {
1388                         job->largeFileSize = 0;
1389                 }
1390         }
1391         if ([fDstFormatPopUp indexOfSelectedItem] == 0 || [fDstFormatPopUp indexOfSelectedItem] == 3)
1392         {
1393           /* We set the chapter marker extraction here based on the format being
1394                 mpeg4 or mkv and the checkbox being checked */
1395                 if ([fCreateChapterMarkers state] == NSOnState)
1396                 {
1397                         job->chapter_markers = 1;
1398                 }
1399                 else
1400                 {
1401                         job->chapter_markers = 0;
1402                 }
1403         }
1404         if( ( job->vcodec & HB_VCODEC_FFMPEG ) &&
1405         [fVidEncoderPopUp indexOfSelectedItem] > 0 )
1406     {
1407         job->vcodec = HB_VCODEC_XVID;
1408     }
1409     if( job->vcodec & HB_VCODEC_X264 )
1410     {
1411                 if ([fVidEncoderPopUp indexOfSelectedItem] > 0 )
1412             {
1413                         /* Just use new Baseline Level 3.0 
1414                         Lets Deprecate Baseline Level 1.3h264_level*/
1415                         job->h264_level = 30;
1416                         job->mux = HB_MUX_IPOD;
1417                         /* move sanity check for iPod Encoding here */
1418                         job->pixel_ratio = 0 ;
1419                         
1420                 }
1421                 
1422                 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
1423                 Currently only used with Constant Quality setting*/
1424                 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
1425                 {
1426                 job->crf = 1;
1427                 }
1428                 
1429                 /* Below Sends x264 options to the core library if x264 is selected*/
1430                 /* Lets use this as per Nyx, Thanks Nyx!*/
1431                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
1432                 /* Turbo first pass if two pass and Turbo First pass is selected */
1433                 if( [fVidTwoPassCheck state] == NSOnState && [fVidTurboPassCheck state] == NSOnState )
1434                 {
1435                         /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
1436                         NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0";
1437                         /* append the "Turbo" string variable to the existing opts string.
1438                         Note: the "Turbo" string must be appended, not prepended to work properly*/
1439                         NSString *firstPassOptStringCombined = [[fAdvancedOptions optionsString] stringByAppendingString:firstPassOptStringTurbo];
1440                         strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
1441                 }
1442                 else
1443                 {
1444                         strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
1445                 }
1446                 
1447         job->h264_13 = [fVidEncoderPopUp indexOfSelectedItem];
1448     }
1449
1450     /* Video settings */
1451     if( [fVidRatePopUp indexOfSelectedItem] > 0 )
1452     {
1453         job->vrate      = 27000000;
1454         job->vrate_base = hb_video_rates[[fVidRatePopUp
1455             indexOfSelectedItem]-1].rate;
1456     }
1457     else
1458     {
1459         job->vrate      = title->rate;
1460         job->vrate_base = title->rate_base;
1461     }
1462
1463     switch( [fVidQualityMatrix selectedRow] )
1464     {
1465         case 0:
1466             /* Target size.
1467                Bitrate should already have been calculated and displayed
1468                in fVidBitrateField, so let's just use it */
1469         case 1:
1470             job->vquality = -1.0;
1471             job->vbitrate = [fVidBitrateField intValue];
1472             break;
1473         case 2:
1474             job->vquality = [fVidQualitySlider floatValue];
1475             job->vbitrate = 0;
1476             break;
1477     }
1478
1479     job->grayscale = ( [fVidGrayscaleCheck state] == NSOnState );
1480
1481     /* Subtitle settings */
1482     job->subtitle = [fSubPopUp indexOfSelectedItem] - 2;
1483
1484     /* Audio tracks and mixdowns */
1485     /* check for the condition where track 2 has an audio selected, but track 1 does not */
1486     /* we will use track 2 as track 1 in this scenario */
1487     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
1488     {
1489         job->audios[0] = [fAudLang1PopUp indexOfSelectedItem] - 1;
1490         job->audios[1] = [fAudLang2PopUp indexOfSelectedItem] - 1; /* will be -1 if "none" is selected */
1491         job->audios[2] = -1;
1492         job->audio_mixdowns[0] = [[fAudTrack1MixPopUp selectedItem] tag];
1493         job->audio_mixdowns[1] = [[fAudTrack2MixPopUp selectedItem] tag];
1494     }
1495     else if ([fAudLang2PopUp indexOfSelectedItem] > 0)
1496     {
1497         job->audios[0] = [fAudLang2PopUp indexOfSelectedItem] - 1;
1498         job->audio_mixdowns[0] = [[fAudTrack2MixPopUp selectedItem] tag];
1499         job->audios[1] = -1;
1500     }
1501     else
1502     {
1503         job->audios[0] = -1;
1504     }
1505
1506     /* Audio settings */
1507     job->arate = hb_audio_rates[[fAudRatePopUp
1508                      indexOfSelectedItem]].rate;
1509     job->abitrate = [[fAudBitratePopUp selectedItem] tag];
1510     
1511     job->filters = hb_list_init();
1512    
1513         /* Detelecine */
1514     if ([fPictureController detelecine])
1515     {
1516         hb_list_add( job->filters, &hb_filter_detelecine );
1517     }
1518    
1519     /* Deinterlace */
1520     if ([fPictureController deinterlace] == 1)
1521     {
1522         /* Run old deinterlacer by default */
1523         hb_filter_deinterlace.settings = "-1"; 
1524         hb_list_add( job->filters, &hb_filter_deinterlace );
1525     }
1526     else if ([fPictureController deinterlace] == 2)
1527     {
1528         /* Yadif mode 0 (1-pass with spatial deinterlacing.) */
1529         hb_filter_deinterlace.settings = "0"; 
1530         hb_list_add( job->filters, &hb_filter_deinterlace );            
1531     }
1532     else if ([fPictureController deinterlace] == 3)
1533     {
1534         /* Yadif (1-pass w/o spatial deinterlacing) and Mcdeint */
1535         hb_filter_deinterlace.settings = "2:-1:1"; 
1536         hb_list_add( job->filters, &hb_filter_deinterlace );            
1537     }
1538     else if ([fPictureController deinterlace] == 4)
1539     {
1540         /* Yadif (2-pass w/ spatial deinterlacing) and Mcdeint*/
1541         hb_filter_deinterlace.settings = "1:-1:1"; 
1542         hb_list_add( job->filters, &hb_filter_deinterlace );            
1543     }
1544         
1545         /* Denoise */
1546         
1547         if ([fPictureController denoise] == 1) // Weak in popup
1548         {
1549                 hb_filter_denoise.settings = "2:1:2:3"; 
1550         hb_list_add( job->filters, &hb_filter_denoise );        
1551         }
1552         else if ([fPictureController denoise] == 2) // Medium in popup
1553         {
1554                 hb_filter_denoise.settings = "3:2:2:3"; 
1555         hb_list_add( job->filters, &hb_filter_denoise );        
1556         }
1557         else if ([fPictureController denoise] == 3) // Strong in popup
1558         {
1559                 hb_filter_denoise.settings = "7:7:5:5"; 
1560         hb_list_add( job->filters, &hb_filter_denoise );        
1561         }
1562
1563 }
1564
1565
1566
1567 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
1568 */
1569 - (IBAction) addToQueue: (id) sender
1570 {
1571         /* We get the destination directory from the destination field here */
1572         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1573         /* We check for a valid destination here */
1574         if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
1575         {
1576                 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
1577         return;
1578         }
1579
1580     /* We check for duplicate name here */
1581         if( [[NSFileManager defaultManager] fileExistsAtPath:
1582             [fDstFile2Field stringValue]] )
1583     {
1584         NSBeginCriticalAlertSheet( _( @"File already exists" ),
1585             _( @"Cancel" ), _( @"Overwrite" ), NULL, fWindow, self,
1586             @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
1587             NULL, NULL, [NSString stringWithFormat:
1588             _( @"Do you want to overwrite %@?" ),
1589             [fDstFile2Field stringValue]] );
1590         // overwriteAddToQueueAlertDone: will be called when the alert is dismissed.
1591     }
1592     else
1593     {
1594         [self doAddToQueue];
1595     }
1596 }
1597
1598 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
1599    the user if they want to overwrite an exiting movie file.
1600 */
1601 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
1602     returnCode: (int) returnCode contextInfo: (void *) contextInfo
1603 {
1604     if( returnCode == NSAlertAlternateReturn )
1605         [self doAddToQueue];
1606 }
1607
1608 - (void) doAddToQueue
1609 {
1610     hb_list_t  * list  = hb_get_titles( fHandle );
1611     hb_title_t * title = (hb_title_t *) hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
1612     hb_job_t * job = title->job;
1613
1614     // Assign a sequence number, starting at zero, to each job added so they can
1615     // be lumped together in the UI.
1616     job->sequence_id = -1;
1617
1618     [self PrepareJob];
1619
1620     /* Destination file */
1621     job->file = [[fDstFile2Field stringValue] UTF8String];
1622
1623     if( [fSubForcedCheck state] == NSOnState )
1624         job->subtitle_force = 1;
1625     else
1626         job->subtitle_force = 0;
1627
1628     /*
1629     * subtitle of -1 is a scan
1630     */
1631     if( job->subtitle == -1 )
1632     {
1633         char *x264opts_tmp;
1634
1635         /*
1636         * When subtitle scan is enabled do a fast pre-scan job
1637         * which will determine which subtitles to enable, if any.
1638         */
1639         job->pass = -1;
1640         x264opts_tmp = job->x264opts;
1641         job->subtitle = -1;
1642
1643         job->x264opts = NULL;
1644
1645         job->indepth_scan = 1;  
1646
1647         job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
1648         *(job->select_subtitle) = NULL;
1649
1650         /*
1651         * Add the pre-scan job
1652         */
1653         job->sequence_id++; // for job grouping
1654         hb_add( fHandle, job );
1655
1656         job->x264opts = x264opts_tmp;
1657     }
1658     else
1659         job->select_subtitle = NULL;
1660
1661     /* No subtitle were selected, so reset the subtitle to -1 (which before
1662     * this point meant we were scanning
1663     */
1664     if( job->subtitle == -2 )
1665         job->subtitle = -1;
1666
1667     if( [fVidTwoPassCheck state] == NSOnState )
1668     {
1669         hb_subtitle_t **subtitle_tmp = job->select_subtitle;
1670         job->indepth_scan = 0;
1671
1672         job->pass = 1;
1673         job->sequence_id++; // for job grouping
1674         hb_add( fHandle, job );
1675
1676         job->pass = 2;
1677         job->sequence_id++; // for job grouping
1678
1679         job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */  
1680         strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
1681
1682         job->select_subtitle = subtitle_tmp;
1683
1684         hb_add( fHandle, job );
1685     }
1686     else
1687     {
1688         job->indepth_scan = 0;
1689         job->pass = 0;
1690         job->sequence_id++; // for job grouping
1691         hb_add( fHandle, job );
1692     }
1693         
1694     NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1695         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1696         /* Lets try to update stuff, taken from remove in the queue controller */
1697         [fQueueController performSelectorOnMainThread: @selector( updateQueueUI )
1698         withObject: NULL waitUntilDone: NO];
1699 }
1700
1701 /* Rip: puts up an alert before ultimately calling doRip
1702 */
1703 - (IBAction) Rip: (id) sender
1704 {
1705     /* Rip or Cancel ? */
1706     hb_state_t s;
1707     hb_get_state2( fHandle, &s );
1708
1709     if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
1710         {
1711         [self Cancel: sender];
1712         return;
1713     }
1714     
1715     // If there are jobs in the queue, then this is a rip the queue
1716     
1717     if (hb_count( fHandle ) > 0)
1718     {
1719         [self doRip];
1720         return;
1721     }
1722
1723     // Before adding jobs to the queue, check for a valid destination.
1724
1725     NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1726     if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
1727     {
1728         NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
1729         return;
1730     }
1731
1732     /* We check for duplicate name here */
1733     if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
1734     {
1735         NSBeginCriticalAlertSheet( _( @"File already exists" ),
1736             _( @"Cancel" ), _( @"Overwrite" ), NULL, fWindow, self,
1737             @selector( overWriteAlertDone:returnCode:contextInfo: ),
1738             NULL, NULL, [NSString stringWithFormat:
1739             _( @"Do you want to overwrite %@?" ),
1740             [fDstFile2Field stringValue]] );
1741             
1742         // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
1743     }
1744     else
1745     {
1746         /* if there are no jobs in the queue, then add this one to the queue and rip 
1747         otherwise, just rip the queue */
1748         if( hb_count( fHandle ) == 0)
1749         {
1750             [self doAddToQueue];
1751         }
1752
1753         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1754         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1755         [self doRip];
1756     }
1757 }
1758
1759 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
1760    want to overwrite an exiting movie file.
1761 */
1762 - (void) overWriteAlertDone: (NSWindow *) sheet
1763     returnCode: (int) returnCode contextInfo: (void *) contextInfo
1764 {
1765     if( returnCode == NSAlertAlternateReturn )
1766     {
1767         /* if there are no jobs in the queue, then add this one to the queue and rip 
1768         otherwise, just rip the queue */
1769         if( hb_count( fHandle ) == 0 )
1770         {
1771             [self doAddToQueue];
1772         }
1773
1774         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1775         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1776         [self doRip];
1777     }
1778 }
1779
1780 - (void) updateAlertDone: (NSWindow *) sheet
1781     returnCode: (int) returnCode contextInfo: (void *) contextInfo
1782 {
1783     if( returnCode == NSAlertAlternateReturn )
1784     {
1785         /* Show scan panel */
1786         [self performSelectorOnMainThread: @selector(showScanPanel:)
1787             withObject: NULL waitUntilDone: NO];
1788         return;
1789     }
1790
1791     /* Go to HandBrake homepage and exit */
1792     [self openHomepage: NULL];
1793     [NSApp terminate: self];
1794 }
1795
1796 - (void) remindUserOfSleepOrShutdown
1797 {
1798        if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
1799        {
1800                /*Warn that computer will sleep after encoding*/
1801                int reminduser;
1802                NSBeep();
1803                reminduser = NSRunAlertPanel(@"The computer will sleep after encoding is done.",@"You have selected to sleep the computer after encoding. To turn off sleeping, go to the HandBrake preferences.", @"OK", @"Preferences...", nil);
1804                [NSApp requestUserAttention:NSCriticalRequest];
1805                if ( reminduser == NSAlertAlternateReturn ) 
1806                {
1807                        [self showPreferencesWindow:NULL];
1808                }
1809        } 
1810        else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
1811        {
1812                /*Warn that computer will shut down after encoding*/
1813                int reminduser;
1814                NSBeep();
1815                reminduser = NSRunAlertPanel(@"The computer will shut down after encoding is done.",@"You have selected to shut down the computer after encoding. To turn off shut down, go to the HandBrake preferences.", @"OK", @"Preferences...", nil);
1816                [NSApp requestUserAttention:NSCriticalRequest];
1817                if ( reminduser == NSAlertAlternateReturn ) 
1818                {
1819                        [self showPreferencesWindow:NULL];
1820                }
1821        }
1822
1823 }
1824
1825
1826 - (void) doRip
1827 {
1828     /* Let libhb do the job */
1829     hb_start( fHandle );
1830         /*set the fEncodeState State */
1831         fEncodeState = 1;
1832 }
1833
1834
1835
1836
1837 //------------------------------------------------------------------------------------
1838 // Removes all jobs from the queue. Does not cancel the current processing job.
1839 //------------------------------------------------------------------------------------
1840 - (void) doDeleteQueuedJobs
1841 {
1842     hb_job_t * job;
1843     while( ( job = hb_job( fHandle, 0 ) ) )
1844         hb_rem( fHandle, job );
1845 }
1846
1847 //------------------------------------------------------------------------------------
1848 // Cancels the current job and proceeds with the next one in the queue.
1849 //------------------------------------------------------------------------------------
1850 - (void) doCancelCurrentJob
1851 {
1852     // Stop the current job. hb_stop will only cancel the current pass and then set
1853     // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
1854     // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
1855     // remaining passes of the job and then start the queue back up if there are any
1856     // remaining jobs.
1857      
1858     hb_stop( fHandle );
1859     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
1860     
1861 }
1862
1863 //------------------------------------------------------------------------------------
1864 // Displays an alert asking user if the want to cancel encoding of current job.
1865 // Cancel: returns immediately after posting the alert. Later, when the user
1866 // acknowledges the alert, doCancelCurrentJob is called.
1867 //------------------------------------------------------------------------------------
1868 - (IBAction)Cancel: (id)sender
1869 {
1870     if (!fHandle) return;
1871     
1872     hb_job_t * job = hb_current_job(fHandle);
1873     if (!job) return;
1874
1875     NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"Do you want to stop encoding of %@?", nil),
1876             [NSString stringWithUTF8String:job->title->name]];
1877     
1878     // Which window to attach the sheet to?
1879     NSWindow * docWindow;
1880     if ([sender respondsToSelector: @selector(window)])
1881         docWindow = [sender window];
1882     else
1883         docWindow = fWindow;
1884         
1885     NSBeginCriticalAlertSheet(
1886             alertTitle,
1887             NSLocalizedString(@"Keep Encoding", nil),
1888             NSLocalizedString(@"Delete All", nil),
1889             NSLocalizedString(@"Stop Encoding", nil),
1890             docWindow, self,
1891             nil, @selector(didDimissCancelCurrentJob:returnCode:contextInfo:), nil,
1892             NSLocalizedString(@"Your movie will be lost if you don't continue encoding.", nil),
1893             [NSString stringWithUTF8String:job->title->name]);
1894     
1895     // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
1896
1897     // N.B.: didDimissCancelCurrentJob:returnCode:contextInfo: is designated as the dismiss
1898     // selector to prevent a crash. As a dismiss selector, the alert window will
1899     // have already be dismissed. If we don't do it this way, the dismissing of
1900     // the alert window will cause the table view to be redrawn at a point where
1901     // current job has been deleted by hblib but we don't know about it yet. This
1902     // is a prime example of wy we need to NOT be relying on hb_current_job!!!!
1903 }
1904
1905 - (void) didDimissCancelCurrentJob: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
1906 {
1907     if (returnCode == NSAlertOtherReturn)
1908         [self doCancelCurrentJob];
1909     else if (returnCode == NSAlertAlternateReturn)
1910     {
1911         [self doDeleteQueuedJobs];
1912         [self doCancelCurrentJob];
1913     }
1914 }
1915
1916
1917
1918
1919
1920 - (IBAction) Pause: (id) sender
1921 {
1922     hb_state_t s;
1923     hb_get_state2( fHandle, &s );
1924
1925     if( s.state == HB_STATE_PAUSED )
1926     {
1927         hb_resume( fHandle );
1928     }
1929     else
1930     {
1931         hb_pause( fHandle );
1932     }
1933 }
1934
1935 - (IBAction) titlePopUpChanged: (id) sender
1936 {
1937     hb_list_t  * list  = hb_get_titles( fHandle );
1938     hb_title_t * title = (hb_title_t*)
1939         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
1940                 
1941                 
1942     /* If Auto Naming is on. We create an output filename of dvd name - title number */
1943     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0)
1944         {
1945                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1946                         @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
1947                         [NSString stringWithUTF8String: title->name],
1948                           title->index,
1949                         [[fDstFile2Field stringValue] pathExtension]]]; 
1950         }
1951
1952     /* Update chapter popups */
1953     [fSrcChapterStartPopUp removeAllItems];
1954     [fSrcChapterEndPopUp   removeAllItems];
1955     for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
1956     {
1957         [fSrcChapterStartPopUp addItemWithTitle: [NSString
1958             stringWithFormat: @"%d", i + 1]];
1959         [fSrcChapterEndPopUp addItemWithTitle: [NSString
1960             stringWithFormat: @"%d", i + 1]];
1961     }
1962     [fSrcChapterStartPopUp selectItemAtIndex: 0];
1963     [fSrcChapterEndPopUp   selectItemAtIndex:
1964         hb_list_count( title->list_chapter ) - 1];
1965     [self chapterPopUpChanged: NULL];
1966
1967 /* Start Get and set the initial pic size for display */
1968         hb_job_t * job = title->job;
1969         fTitle = title; 
1970         /* Turn Deinterlace on/off depending on the preference */
1971         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultDeinterlaceOn"] > 0)
1972         {
1973                 [fPictureController setDeinterlace:1];
1974         }
1975         else
1976         {
1977                 [fPictureController setDeinterlace:0];
1978         }
1979         
1980         /* Pixel Ratio Setting */
1981         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PixelRatio"])
1982     {
1983                 job->pixel_ratio = 1 ;
1984         }
1985         else
1986         {
1987                 job->pixel_ratio = 0 ;
1988         }
1989         /*Set Source Size Fields Here */
1990         [fPicSrcWidth setStringValue: [NSString stringWithFormat:
1991                                                          @"%d", fTitle->width]];
1992         [fPicSrcHeight setStringValue: [NSString stringWithFormat:
1993                                                          @"%d", fTitle->height]];
1994                                                          
1995         /* Set Auto Crop to on upon selecting a new title */
1996     [fPictureController setAutoCrop:YES];
1997     
1998         /* We get the originial output picture width and height and put them
1999         in variables for use with some presets later on */
2000         PicOrigOutputWidth = job->width;
2001         PicOrigOutputHeight = job->height;
2002         AutoCropTop = job->crop[0];
2003         AutoCropBottom = job->crop[1];
2004         AutoCropLeft = job->crop[2];
2005         AutoCropRight = job->crop[3];
2006         /* we test getting the max output value for pic sizing here to be used later*/
2007         [fPicSettingWidth setStringValue: [NSString stringWithFormat:
2008                 @"%d", PicOrigOutputWidth]];
2009         [fPicSettingHeight setStringValue: [NSString stringWithFormat:
2010                 @"%d", PicOrigOutputHeight]];
2011         /* we run the picture size values through
2012         calculatePictureSizing to get all picture size
2013         information*/
2014         [self calculatePictureSizing: NULL];
2015         /* Run Through encoderPopUpChanged to see if there
2016                 needs to be any pic value modifications based on encoder settings */
2017         //[self encoderPopUpChanged: NULL];
2018         /* END Get and set the initial pic size for display */ 
2019
2020     /* Update subtitle popups */
2021     hb_subtitle_t * subtitle;
2022     [fSubPopUp removeAllItems];
2023     [fSubPopUp addItemWithTitle: @"None"];
2024     [fSubPopUp addItemWithTitle: @"Autoselect"];
2025     for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
2026     {
2027         subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
2028
2029         /* We cannot use NSPopUpButton's addItemWithTitle because
2030            it checks for duplicate entries */
2031         [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
2032             subtitle->lang] action: NULL keyEquivalent: @""];
2033     }
2034     [fSubPopUp selectItemAtIndex: 0];
2035         
2036         [self subtitleSelectionChanged: NULL];
2037     
2038     /* Update chapter table */
2039     [fChapterTitlesDelegate resetWithTitle:title];
2040     [fChapterTable reloadData];
2041
2042     /* Update audio popups */
2043     [self addAllAudioTracksToPopUp: fAudLang1PopUp];
2044     [self addAllAudioTracksToPopUp: fAudLang2PopUp];
2045     /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
2046         NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
2047         [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
2048     [self selectAudioTrackInPopUp: fAudLang2PopUp searchPrefixString: NULL selectIndexIfNotFound: 0];
2049         
2050         /* changing the title may have changed the audio channels on offer, */
2051         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
2052         [self audioTrackPopUpChanged: fAudLang1PopUp];
2053         [self audioTrackPopUpChanged: fAudLang2PopUp];
2054         /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
2055         [self tableViewSelected:NULL];
2056 }
2057
2058 - (IBAction) chapterPopUpChanged: (id) sender
2059 {
2060     
2061         /* If start chapter popup is greater than end chapter popup,
2062         we set the end chapter popup to the same as start chapter popup */
2063         if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
2064         {
2065                 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
2066     }
2067
2068                 
2069         hb_list_t  * list  = hb_get_titles( fHandle );
2070     hb_title_t * title = (hb_title_t *)
2071         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
2072
2073     hb_chapter_t * chapter;
2074     int64_t        duration = 0;
2075     for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
2076          i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
2077     {
2078         chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
2079         duration += chapter->duration;
2080     }
2081     
2082     duration /= 90000; /* pts -> seconds */
2083     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
2084         @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
2085         duration % 60]];
2086
2087     [self calculateBitrate: sender];
2088 }
2089
2090 - (IBAction) formatPopUpChanged: (id) sender
2091 {
2092     NSString * string = [fDstFile2Field stringValue];
2093     NSString * selectedCodecs = [fDstCodecsPopUp titleOfSelectedItem];
2094     int format = [fDstFormatPopUp indexOfSelectedItem];
2095     char * ext = NULL;
2096         /* Initially set the large file (64 bit formatting) output checkbox to hidden */
2097     [fDstMpgLargeFileCheck setHidden: YES];
2098     /* Update the codecs popup */
2099     [fDstCodecsPopUp removeAllItems];
2100     switch( format )
2101     {
2102         case 0:
2103                         /*Get Default MP4 File Extension*/
2104                         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
2105                         {
2106                                 ext = "m4v";
2107                         }
2108                         else
2109                         {
2110                                 ext = "mp4";
2111                         }
2112             [fDstCodecsPopUp addItemWithTitle:
2113                 _( @"MPEG-4 Video / AAC Audio" )];
2114             [fDstCodecsPopUp addItemWithTitle:
2115                 _( @"AVC/H.264 Video / AAC Audio" )];
2116                         /* We enable the create chapters checkbox here since we are .mp4*/
2117                         [fCreateChapterMarkers setEnabled: YES];
2118                         /* We show the Large File (64 bit formatting) checkbox since we are .mp4 
2119                         if we have enabled the option in the global preferences*/
2120                         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"AllowLargeFiles"] > 0)
2121                         {
2122                                 [fDstMpgLargeFileCheck setHidden: NO];
2123                         }
2124                                 else
2125                                 {
2126                                         /* if not enable in global preferences, we additionaly sanity check that the
2127                                         hidden checkbox is set to off. */
2128                                         [fDstMpgLargeFileCheck setState: NSOffState];
2129                                 }
2130                                 break;
2131         case 1: 
2132             ext = "avi";
2133             [fDstCodecsPopUp addItemWithTitle:
2134                 _( @"MPEG-4 Video / MP3 Audio" )];
2135             [fDstCodecsPopUp addItemWithTitle:
2136                 _( @"MPEG-4 Video / AC-3 Audio" )];
2137             [fDstCodecsPopUp addItemWithTitle:
2138                 _( @"AVC/H.264 Video / MP3 Audio" )];
2139             [fDstCodecsPopUp addItemWithTitle:
2140                 _( @"AVC/H.264 Video / AC-3 Audio" )];
2141                         /* We disable the create chapters checkbox here since we are NOT .mp4 
2142                         and make sure it is unchecked*/
2143                         [fCreateChapterMarkers setEnabled: NO];
2144                         [fCreateChapterMarkers setState: NSOffState];
2145                         break;
2146         case 2:
2147             ext = "ogm";
2148             [fDstCodecsPopUp addItemWithTitle:
2149                 _( @"MPEG-4 Video / Vorbis Audio" )];
2150             [fDstCodecsPopUp addItemWithTitle:
2151                 _( @"MPEG-4 Video / MP3 Audio" )];
2152             /* We disable the create chapters checkbox here since we are NOT .mp4 
2153                         and make sure it is unchecked*/
2154                         [fCreateChapterMarkers setEnabled: NO];
2155                         [fCreateChapterMarkers setState: NSOffState];
2156                         break;
2157                 case 3:
2158             ext = "mkv";
2159             [fDstCodecsPopUp addItemWithTitle:
2160                 _( @"MPEG-4 Video / AAC Audio" )];
2161                                 [fDstCodecsPopUp addItemWithTitle:
2162                 _( @"MPEG-4 Video / AC-3 Audio" )];
2163                         [fDstCodecsPopUp addItemWithTitle:
2164                 _( @"MPEG-4 Video / MP3 Audio" )];
2165                         [fDstCodecsPopUp addItemWithTitle:
2166                 _( @"MPEG-4 Video / Vorbis Audio" )];
2167             
2168                         [fDstCodecsPopUp addItemWithTitle:
2169                 _( @"AVC/H.264 Video / AAC Audio" )];
2170                         [fDstCodecsPopUp addItemWithTitle:
2171                 _( @"AVC/H.264 Video / AC-3 Audio" )];
2172                         [fDstCodecsPopUp addItemWithTitle:
2173                 _( @"AVC/H.264 Video / MP3 Audio" )];
2174                         [fDstCodecsPopUp addItemWithTitle:
2175                 _( @"AVC/H.264 Video / Vorbis Audio" )];
2176             /* We enable the create chapters checkbox here since */
2177                         [fCreateChapterMarkers setEnabled: YES];
2178                         break;
2179     }
2180     if ( SuccessfulScan ) {
2181         [fDstCodecsPopUp selectItemWithTitle:selectedCodecs];
2182         if ( [fDstCodecsPopUp selectedItem] == NULL )
2183             [fDstCodecsPopUp selectItemAtIndex:0];
2184         }
2185     [self codecsPopUpChanged: NULL];
2186
2187     /* Add/replace to the correct extension */
2188     if( [string characterAtIndex: [string length] - 4] == '.' )
2189     {
2190         [fDstFile2Field setStringValue: [NSString stringWithFormat:
2191             @"%@.%s", [string substringToIndex: [string length] - 4],
2192             ext]];
2193     }
2194     else
2195     {
2196         [fDstFile2Field setStringValue: [NSString stringWithFormat:
2197             @"%@.%s", string, ext]];
2198     }
2199
2200         /* changing the format may mean that we can / can't offer mono or 6ch, */
2201         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
2202         [self audioTrackPopUpChanged: fAudLang1PopUp];
2203         [self audioTrackPopUpChanged: fAudLang2PopUp];
2204         /* We call the method to properly enable/disable turbo 2 pass */
2205         [self twoPassCheckboxChanged: sender];
2206         /* We call method method to change UI to reflect whether a preset is used or not*/
2207         [self customSettingUsed: sender];       
2208         
2209 }
2210
2211 - (IBAction) codecsPopUpChanged: (id) sender
2212 {
2213     int format = [fDstFormatPopUp indexOfSelectedItem];
2214     int codecs = [fDstCodecsPopUp indexOfSelectedItem];
2215         
2216     [fAdvancedOptions setHidden:YES];
2217
2218     /* Update the encoder popup*/
2219     if( ( FormatSettings[format][codecs] & HB_VCODEC_X264 ) )
2220     {
2221         /* MPEG-4 -> H.264 */
2222         [fVidEncoderPopUp removeAllItems];
2223                 [fVidEncoderPopUp addItemWithTitle: @"x264 (h.264 Main)"];
2224                 [fVidEncoderPopUp addItemWithTitle: @"x264 (h.264 iPod)"];
2225                 [fVidEncoderPopUp selectItemAtIndex: 0];
2226         [fAdvancedOptions setHidden:NO];
2227     }
2228     
2229     else if( ( FormatSettings[format][codecs] & HB_VCODEC_FFMPEG ) )
2230     {
2231         /* H.264 -> MPEG-4 */
2232         [fVidEncoderPopUp removeAllItems];
2233         [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
2234         [fVidEncoderPopUp addItemWithTitle: @"XviD"];
2235         [fVidEncoderPopUp selectItemAtIndex: 0];
2236                                 
2237     }
2238
2239     if( FormatSettings[format][codecs] & HB_ACODEC_AC3 )
2240     {
2241         /* AC-3 pass-through: disable samplerate and bitrate */
2242         [fAudRatePopUp    setEnabled: NO];
2243         [fAudBitratePopUp setEnabled: NO];
2244     }
2245     else
2246     {
2247         [fAudRatePopUp    setEnabled: YES];
2248         [fAudBitratePopUp setEnabled: YES];
2249     }
2250     /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
2251         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
2252         [self audioTrackPopUpChanged: fAudLang1PopUp];
2253         [self audioTrackPopUpChanged: fAudLang2PopUp];
2254
2255     [self calculateBitrate: sender];
2256     [self twoPassCheckboxChanged: sender];
2257 }
2258
2259 - (IBAction) encoderPopUpChanged: (id) sender
2260 {
2261     
2262         /* Check to see if we need to modify the job pic values based on x264 (iPod) encoder selection */
2263     if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [fDstCodecsPopUp indexOfSelectedItem] == 1 && [fVidEncoderPopUp indexOfSelectedItem] == 1)
2264     {
2265                 hb_job_t * job = fTitle->job;
2266                 job->pixel_ratio = 0 ;
2267                 
2268                 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPicSizeAutoiPod"] > 0)
2269                 {
2270                         
2271                         if (job->width > 640)
2272                         {
2273                                 job->width = 640;
2274                         }
2275                         job->keep_ratio = 1;
2276                         hb_fix_aspect( job, HB_KEEP_WIDTH );
2277                         
2278                 }
2279                 /* Make sure the 64bit formatting checkbox is off */
2280                 [fDstMpgLargeFileCheck setState: NSOffState];
2281         }
2282     
2283         [self calculatePictureSizing: sender];
2284         [self twoPassCheckboxChanged: sender];
2285 }
2286
2287 - (IBAction) twoPassCheckboxChanged: (id) sender
2288 {
2289         /* check to see if x264 is chosen */
2290         int format = [fDstFormatPopUp indexOfSelectedItem];
2291     int codecs = [fDstCodecsPopUp indexOfSelectedItem];
2292         if( ( FormatSettings[format][codecs] & HB_VCODEC_X264 ) )
2293     {
2294                 if( [fVidTwoPassCheck state] == NSOnState)
2295                 {
2296                         [fVidTurboPassCheck setHidden: NO];
2297                 }
2298                 else
2299                 {
2300                         [fVidTurboPassCheck setHidden: YES];
2301                         [fVidTurboPassCheck setState: NSOffState];
2302                 }
2303                 /* Make sure Two Pass is checked if Turbo is checked */
2304                 if( [fVidTurboPassCheck state] == NSOnState)
2305                 {
2306                         [fVidTwoPassCheck setState: NSOnState];
2307                 }
2308         }
2309         else
2310         {
2311                 [fVidTurboPassCheck setHidden: YES];
2312                 [fVidTurboPassCheck setState: NSOffState];
2313         }
2314         
2315         /* We call method method to change UI to reflect whether a preset is used or not*/
2316         [self customSettingUsed: sender];
2317 }
2318
2319 - (IBAction ) videoFrameRateChanged: (id) sender
2320 {
2321     /* We call method method to calculatePictureSizing to error check detelecine*/
2322     [self calculatePictureSizing: sender];
2323
2324     /* We call method method to change UI to reflect whether a preset is used or not*/
2325         [self customSettingUsed: sender];
2326 }
2327
2328 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
2329 {
2330
2331     /* enable/disable the mixdown text and popupbutton for audio track 1 */
2332     [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
2333     [fAudTrack1MixLabel setTextColor: ([fAudLang1PopUp indexOfSelectedItem] == 0) ?
2334         [NSColor disabledControlTextColor] : [NSColor controlTextColor]];
2335
2336     /* enable/disable the mixdown text and popupbutton for audio track 2 */
2337     [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
2338     [fAudTrack2MixLabel setTextColor: ([fAudLang2PopUp indexOfSelectedItem] == 0) ?
2339         [NSColor disabledControlTextColor] : [NSColor controlTextColor]];
2340
2341 }
2342
2343 - (IBAction) addAllAudioTracksToPopUp: (id) sender
2344 {
2345
2346     hb_list_t  * list  = hb_get_titles( fHandle );
2347     hb_title_t * title = (hb_title_t*)
2348         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
2349
2350         hb_audio_t * audio;
2351
2352     [sender removeAllItems];
2353     [sender addItemWithTitle: _( @"None" )];
2354     for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
2355     {
2356         audio = (hb_audio_t *) hb_list_item( title->list_audio, i );
2357         [[sender menu] addItemWithTitle:
2358             [NSString stringWithCString: audio->lang]
2359             action: NULL keyEquivalent: @""];
2360     }
2361     [sender selectItemAtIndex: 0];
2362
2363 }
2364
2365 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
2366 {
2367
2368     /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
2369     /* e.g. to find the first French track, pass in an NSString * of "Francais" */
2370     /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
2371     /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
2372     
2373         if (searchPrefixString != NULL) 
2374         {
2375
2376         for( int i = 0; i < [sender numberOfItems]; i++ )
2377         {
2378             /* Try to find the desired search string */
2379             if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
2380             {
2381                 [sender selectItemAtIndex: i];
2382                 return;
2383             }
2384         }
2385         /* couldn't find the string, so select the requested "search string not found" item */
2386         /* index of 0 means select the "none" item */
2387         /* index of 1 means select the first audio track */
2388         [sender selectItemAtIndex: selectIndexIfNotFound];
2389         }
2390     else
2391     {
2392         /* if no search string is provided, then select the selectIndexIfNotFound item */
2393         [sender selectItemAtIndex: selectIndexIfNotFound];
2394     }
2395
2396 }
2397
2398 - (IBAction) audioTrackPopUpChanged: (id) sender
2399 {
2400     /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
2401     [self audioTrackPopUpChanged: sender mixdownToUse: 0];
2402 }
2403
2404 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
2405 {
2406
2407     /* make sure we have a selected title before continuing */
2408     if (fTitle == NULL) return;
2409
2410     /* find out if audio track 1 or 2 was changed - this is passed to us in the tag of the sender */
2411     /* the sender will have been either fAudLang1PopUp (tag = 0) or fAudLang2PopUp (tag = 1) */
2412     int thisAudio = [sender tag];
2413
2414     /* get the index of the selected audio */
2415     int thisAudioIndex = [sender indexOfSelectedItem] - 1;
2416
2417     /* Handbrake can't currently cope with ripping the same source track twice */
2418     /* So, if this audio is also selected in the other audio track popup, set that popup's selection to "none" */
2419     /* get a reference to the two audio track popups */
2420     NSPopUpButton * thisAudioPopUp  = (thisAudio == 1 ? fAudLang2PopUp : fAudLang1PopUp);
2421     NSPopUpButton * otherAudioPopUp = (thisAudio == 1 ? fAudLang1PopUp : fAudLang2PopUp);
2422     /* if the same track is selected in the other audio popup, then select "none" in that popup */
2423     /* unless, of course, both are selected as "none!" */
2424     if ([thisAudioPopUp indexOfSelectedItem] != 0 && [thisAudioPopUp indexOfSelectedItem] == [otherAudioPopUp indexOfSelectedItem]) {
2425         [otherAudioPopUp selectItemAtIndex: 0];
2426         [self audioTrackPopUpChanged: otherAudioPopUp];
2427     }
2428
2429     /* pointer for the hb_audio_s struct we will use later on */
2430     hb_audio_t * audio;
2431
2432     /* find out what the currently-selected output audio codec is */
2433     int format = [fDstFormatPopUp indexOfSelectedItem];
2434     int codecs = [fDstCodecsPopUp indexOfSelectedItem];
2435     int acodec = FormatSettings[format][codecs] & HB_ACODEC_MASK;
2436
2437     /* pointer to this track's mixdown NSPopUpButton */
2438     NSTextField   * mixdownTextField;
2439     NSPopUpButton * mixdownPopUp;
2440
2441     /* find our mixdown NSTextField and NSPopUpButton */
2442     if (thisAudio == 0)
2443     {
2444         mixdownTextField = fAudTrack1MixLabel;
2445         mixdownPopUp = fAudTrack1MixPopUp;
2446     }
2447     else
2448     {
2449         mixdownTextField = fAudTrack2MixLabel;
2450         mixdownPopUp = fAudTrack2MixPopUp;
2451     }
2452
2453     /* delete the previous audio mixdown options */
2454     [mixdownPopUp removeAllItems];
2455
2456     /* check if the audio mixdown controls need their enabled state changing */
2457     [self setEnabledStateOfAudioMixdownControls: NULL];
2458
2459     if (thisAudioIndex != -1)
2460     {
2461
2462         /* get the audio */
2463         audio = (hb_audio_t *) hb_list_item( fTitle->list_audio, thisAudioIndex );
2464         if (audio != NULL)
2465         {
2466
2467             /* find out if our selected output audio codec supports mono and / or 6ch */
2468             /* we also check for an input codec of AC3 or DCA,
2469                as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
2470             /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
2471                but this may change in the future, so they are separated for flexibility */
2472             int audioCodecsSupportMono = ((audio->codec == HB_ACODEC_AC3 ||
2473                 audio->codec == HB_ACODEC_DCA) && acodec == HB_ACODEC_FAAC);
2474             int audioCodecsSupport6Ch =  ((audio->codec == HB_ACODEC_AC3 ||
2475                 audio->codec == HB_ACODEC_DCA) && (acodec == HB_ACODEC_FAAC ||
2476                 acodec == HB_ACODEC_VORBIS));
2477
2478             /* check for AC-3 passthru */
2479             if (audio->codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
2480             {
2481                     [[mixdownPopUp menu] addItemWithTitle:
2482                         [NSString stringWithCString: "AC3 Passthru"]
2483                         action: NULL keyEquivalent: @""];
2484             }
2485             else
2486             {
2487
2488                 /* add the appropriate audio mixdown menuitems to the popupbutton */
2489                 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
2490                    so that we can reference the mixdown later */
2491
2492                 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
2493                 int minMixdownUsed = 0;
2494                 int maxMixdownUsed = 0;
2495                 
2496                 /* get the input channel layout without any lfe channels */
2497                 int layout = audio->input_channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
2498
2499                 /* do we want to add a mono option? */
2500                 if (audioCodecsSupportMono == 1) {
2501                     id<NSMenuItem> menuItem = [[mixdownPopUp menu] addItemWithTitle:
2502                         [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
2503                         action: NULL keyEquivalent: @""];
2504                     [menuItem setTag: hb_audio_mixdowns[0].amixdown];
2505                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
2506                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
2507                 }
2508
2509                 /* do we want to add a stereo option? */
2510                 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
2511                 /* also offer stereo if we have a stereo-or-better source */
2512                 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO) {
2513                     id<NSMenuItem> menuItem = [[mixdownPopUp menu] addItemWithTitle:
2514                         [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
2515                         action: NULL keyEquivalent: @""];
2516                     [menuItem setTag: hb_audio_mixdowns[1].amixdown];
2517                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
2518                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
2519                 }
2520
2521                 /* do we want to add a dolby surround (DPL1) option? */
2522                 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY) {
2523                     id<NSMenuItem> menuItem = [[mixdownPopUp menu] addItemWithTitle:
2524                         [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
2525                         action: NULL keyEquivalent: @""];
2526                     [menuItem setTag: hb_audio_mixdowns[2].amixdown];
2527                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
2528                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
2529                 }
2530
2531                 /* do we want to add a dolby pro logic 2 (DPL2) option? */
2532                 if (layout == HB_INPUT_CH_LAYOUT_3F2R) {
2533                     id<NSMenuItem> menuItem = [[mixdownPopUp menu] addItemWithTitle:
2534                         [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
2535                         action: NULL keyEquivalent: @""];
2536                     [menuItem setTag: hb_audio_mixdowns[3].amixdown];
2537                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
2538                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
2539                 }
2540
2541                 /* do we want to add a 6-channel discrete option? */
2542                 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->input_channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE)) {
2543                     id<NSMenuItem> menuItem = [[mixdownPopUp menu] addItemWithTitle:
2544                         [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
2545                         action: NULL keyEquivalent: @""];
2546                     [menuItem setTag: hb_audio_mixdowns[4].amixdown];
2547                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
2548                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
2549                 }
2550
2551                 /* auto-select the best mixdown based on our saved mixdown preference */
2552                 
2553                 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
2554                 /* ultimately this should be a prefs option */
2555                 int useMixdown;
2556                 
2557                 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
2558                 if (mixdownToUse > 0)
2559                 {
2560                     useMixdown = mixdownToUse;
2561                 }
2562                 else
2563                 {
2564                     useMixdown = HB_AMIXDOWN_DOLBYPLII;
2565                 }
2566                 
2567                 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
2568                 if (useMixdown > maxMixdownUsed) useMixdown = maxMixdownUsed;
2569
2570                 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
2571                 if (useMixdown < minMixdownUsed) useMixdown = minMixdownUsed;
2572
2573                 /* select the (possibly-amended) preferred mixdown */
2574                 [mixdownPopUp selectItemWithTag: useMixdown];
2575                                 
2576                                 /* lets call the audioTrackMixdownChanged method here to determine appropriate bitrates, etc. */
2577                 [self audioTrackMixdownChanged: NULL];
2578             }
2579
2580         }
2581         
2582     }
2583
2584         /* see if the new audio track choice will change the bitrate we need */
2585     [self calculateBitrate: sender];    
2586
2587 }
2588 - (IBAction) audioTrackMixdownChanged: (id) sender
2589 {
2590
2591     /* find out what the currently-selected output audio codec is */
2592     int format = [fDstFormatPopUp indexOfSelectedItem];
2593     int codecs = [fDstCodecsPopUp indexOfSelectedItem];
2594     int acodec = FormatSettings[format][codecs] & HB_ACODEC_MASK;
2595     
2596     /* storage variable for the min and max bitrate allowed for this codec */
2597     int minbitrate;
2598     int maxbitrate;
2599     
2600     switch( acodec )
2601     {
2602         case HB_ACODEC_FAAC:
2603             /* check if we have a 6ch discrete conversion in either audio track */
2604             if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_AMIXDOWN_6CH || [[fAudTrack2MixPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
2605             {
2606                 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
2607                 minbitrate = 32;
2608                 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
2609                 maxbitrate = 384;
2610                 break;
2611             }
2612             else
2613             {
2614                 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
2615                 minbitrate = 32;
2616                 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
2617                 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
2618                 maxbitrate = 160;
2619                 break;
2620             }
2621
2622         case HB_ACODEC_LAME:
2623             /* Lame is happy using our min bitrate of 32 kbps */
2624             minbitrate = 32;
2625             /* Lame won't encode if the bitrate is higher than 320 kbps */
2626             maxbitrate = 320;
2627             break;
2628
2629         case HB_ACODEC_VORBIS:
2630         if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_AMIXDOWN_6CH || [[fAudTrack2MixPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
2631             {
2632                 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
2633                 minbitrate = 192;
2634                 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
2635                 maxbitrate = 384;
2636                 break;
2637             }
2638             else
2639             {
2640             /* Vorbis causes a crash if we use a bitrate below 48 kbps */
2641             minbitrate = 48;
2642             /* Vorbis can cope with 384 kbps quite happily, even for stereo */
2643             maxbitrate = 384;
2644             break;
2645             }
2646
2647         default:
2648             /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
2649             minbitrate = 32;
2650             maxbitrate = 384;
2651         
2652     }
2653
2654     [fAudBitratePopUp removeAllItems];
2655
2656     for( int i = 0; i < hb_audio_bitrates_count; i++ )
2657     {
2658         if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
2659         {
2660             /* add a new menuitem for this bitrate */
2661             id<NSMenuItem> menuItem = [[fAudBitratePopUp menu] addItemWithTitle:
2662                 [NSString stringWithCString: hb_audio_bitrates[i].string]
2663                 action: NULL keyEquivalent: @""];
2664             /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
2665             [menuItem setTag: hb_audio_bitrates[i].rate];
2666         }
2667     }
2668
2669     /* select the default bitrate (but use 384 for 6-ch AAC) */
2670     if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_AMIXDOWN_6CH || [[fAudTrack2MixPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
2671     {
2672         [fAudBitratePopUp selectItemWithTag: 384];
2673     }
2674     else
2675     {
2676         [fAudBitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
2677     }
2678
2679 }
2680
2681 - (IBAction) subtitleSelectionChanged: (id) sender
2682 {
2683         if ([fSubPopUp indexOfSelectedItem] == 0)
2684         {
2685         [fSubForcedCheck setState: NSOffState];
2686         [fSubForcedCheck setEnabled: NO];       
2687         }
2688         else
2689         {
2690         [fSubForcedCheck setEnabled: YES];      
2691         }
2692         
2693 }
2694
2695 /* lets set the picture size back to the max from right after title scan
2696    Lets use an IBAction here as down the road we could always use a checkbox
2697    in the gui to easily take the user back to max. Remember, the compiler
2698    resolves IBActions down to -(void) during compile anyway */
2699 - (IBAction) revertPictureSizeToMax: (id) sender
2700 {
2701         hb_job_t * job = fTitle->job;
2702         /* We use the output picture width and height
2703         as calculated from libhb right after title is set
2704         in TitlePopUpChanged */
2705         job->width = PicOrigOutputWidth;
2706         job->height = PicOrigOutputHeight;
2707     [fPictureController setAutoCrop:YES];
2708         /* Here we use the auto crop values determined right after scan */
2709         job->crop[0] = AutoCropTop;
2710         job->crop[1] = AutoCropBottom;
2711         job->crop[2] = AutoCropLeft;
2712         job->crop[3] = AutoCropRight;
2713                                 
2714                                 
2715                                 [self calculatePictureSizing: sender];
2716                                 /* We call method method to change UI to reflect whether a preset is used or not*/    
2717                                 [self customSettingUsed: sender];
2718 }
2719
2720
2721 /* Get and Display Current Pic Settings in main window */
2722 - (IBAction) calculatePictureSizing: (id) sender
2723 {
2724         [fPicSettingWidth setStringValue: [NSString stringWithFormat:@"%d", fTitle->job->width]];
2725         [fPicSettingHeight setStringValue: [NSString stringWithFormat:@"%d", fTitle->job->height]];
2726                 
2727         if (fTitle->job->pixel_ratio == 1)
2728         {
2729         int titlewidth = fTitle->width-fTitle->job->crop[2]-fTitle->job->crop[3];
2730         int arpwidth = fTitle->job->pixel_aspect_width;
2731         int arpheight = fTitle->job->pixel_aspect_height;
2732         int displayparwidth = titlewidth * arpwidth / arpheight;
2733         int displayparheight = fTitle->height-fTitle->job->crop[0]-fTitle->job->crop[1];
2734         
2735         [fPicSettingWidth setStringValue: [NSString stringWithFormat:@"%d", titlewidth]];
2736         [fPicSettingHeight setStringValue: [NSString stringWithFormat:@"%d", displayparheight]];
2737         [fPicLabelPAROutputX setStringValue: @"x"];
2738         [fPicSettingPARWidth setStringValue: [NSString stringWithFormat:@"%d", displayparwidth]];
2739         [fPicSettingPARHeight setStringValue: [NSString stringWithFormat:@"%d", displayparheight]];
2740         
2741         fTitle->job->keep_ratio = 0;
2742         }
2743         else
2744         {
2745         [fPicLabelPAROutputX setStringValue: @""];
2746         [fPicSettingPARWidth setStringValue: @""];
2747         [fPicSettingPARHeight setStringValue:  @""];
2748         }
2749                                 
2750         /* Set ON/Off values for the deinterlace/keep aspect ratio according to boolean */      
2751         if (fTitle->job->keep_ratio > 0)
2752         {
2753                 [fPicSettingARkeep setStringValue: @"On"];
2754         }
2755         else
2756         {
2757                 [fPicSettingARkeep setStringValue: @"Off"];
2758         }       
2759     /* Detelecine */
2760     if ([fPictureController detelecine]) {
2761         [fPicSettingDetelecine setStringValue: @"Yes"];
2762     }
2763     else {
2764         [fPicSettingDetelecine setStringValue: @"No"];
2765     }
2766
2767         /* Deinterlace */
2768         if ([fPictureController deinterlace] == 0)
2769         {
2770                 [fPicSettingDeinterlace setStringValue: @"Off"];
2771         }
2772         else if ([fPictureController deinterlace] == 1)
2773         {
2774                 [fPicSettingDeinterlace setStringValue: @"Fast"];
2775         }
2776         else if ([fPictureController deinterlace] == 2)
2777         {
2778                 [fPicSettingDeinterlace setStringValue: @"Slow"];
2779         }
2780         else if ([fPictureController deinterlace] == 3)
2781         {
2782                 [fPicSettingDeinterlace setStringValue: @"Slower"];
2783         }
2784         else if ([fPictureController deinterlace] ==4)
2785         {
2786                 [fPicSettingDeinterlace setStringValue: @"Slowest"];
2787         }
2788         /* Denoise */
2789         if ([fPictureController denoise] == 0)
2790         {
2791                 [fPicSettingDenoise setStringValue: @"Off"];
2792         }
2793         else if ([fPictureController denoise] == 1)
2794         {
2795                 [fPicSettingDenoise setStringValue: @"Weak"];
2796         }
2797         else if ([fPictureController denoise] == 2)
2798         {
2799                 [fPicSettingDenoise setStringValue: @"Medium"];
2800         }
2801         else if ([fPictureController denoise] == 3)
2802         {
2803                 [fPicSettingDenoise setStringValue: @"Strong"];
2804         }
2805         
2806         if (fTitle->job->pixel_ratio > 0)
2807         {
2808                 [fPicSettingPAR setStringValue: @""];
2809         }
2810         else
2811         {
2812                 [fPicSettingPAR setStringValue: @"Off"];
2813         }
2814         /* Set the display field for crop as per boolean */
2815         if (![fPictureController autoCrop])
2816         {
2817             [fPicSettingAutoCrop setStringValue: @"Custom"];
2818         }
2819         else
2820         {
2821                 [fPicSettingAutoCrop setStringValue: @"Auto"];
2822         }       
2823         /* check video framerate and turn off detelecine if necessary */
2824         if (fTitle->rate_base == 1126125 || [[fVidRatePopUp titleOfSelectedItem] isEqualToString: @"23.976 (NTSC Film)"])
2825         {
2826                 [fPictureController setDetelecine:0];
2827         }
2828         
2829         
2830         
2831         /* below will trigger the preset, if selected, to be
2832         changed to "Custom". Lets comment out for now until
2833         we figure out a way to determine if the picture values
2834         changed modify the preset values */     
2835         //[self customSettingUsed: sender];
2836 }
2837
2838 - (IBAction) calculateBitrate: (id) sender
2839 {
2840     if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
2841     {
2842         return;
2843     }
2844
2845     hb_list_t  * list  = hb_get_titles( fHandle );
2846     hb_title_t * title = (hb_title_t *) hb_list_item( list,
2847             [fSrcTitlePopUp indexOfSelectedItem] );
2848     hb_job_t * job = title->job;
2849
2850     [self PrepareJob];
2851
2852     [fVidBitrateField setIntValue: hb_calc_bitrate( job,
2853             [fVidTargetSizeField intValue] )];
2854 }
2855
2856 /* Method to determine if we should change the UI
2857 To reflect whether or not a Preset is being used or if
2858 the user is using "Custom" settings by determining the sender*/
2859 - (IBAction) customSettingUsed: (id) sender
2860 {
2861         if ([sender stringValue] != NULL)
2862         {
2863                 /* Deselect the currently selected Preset if there is one*/
2864                 [tableView deselectRow:[tableView selectedRow]];
2865                 [[fPresetsActionMenu itemAtIndex:0] setEnabled: NO];
2866                 /* Change UI to show "Custom" settings are being used */
2867                 [fPresetSelectedDisplay setStringValue: @"Custom"];
2868                 
2869                 curUserPresetChosenNum = nil;
2870         }
2871
2872 }
2873
2874    /* We use this method to recreate new, updated factory
2875    presets */
2876 - (IBAction)addFactoryPresets:(id)sender
2877 {
2878     /* First, we delete any existing built in presets */
2879     [self deleteFactoryPresets: sender];
2880     /* Then, we re-create new built in presets programmatically CreateIpodOnlyPreset*/
2881     [UserPresets addObject:[self createNormalPreset]];
2882     [UserPresets addObject:[self createClassicPreset]];
2883     [UserPresets addObject:[self createQuickTimePreset]];
2884         [UserPresets addObject:[self createIpodLowPreset]];
2885         [UserPresets addObject:[self createIpodHighPreset]];
2886         [UserPresets addObject:[self createAppleTVPreset]];
2887     [UserPresets addObject:[self createiPhonePreset]];
2888         [UserPresets addObject:[self createPSThreePreset]];
2889         [UserPresets addObject:[self createPSPPreset]];
2890         [UserPresets addObject:[self createFilmPreset]];
2891     [UserPresets addObject:[self createTelevisionPreset]];
2892     [UserPresets addObject:[self createAnimationPreset]];
2893     [UserPresets addObject:[self createBedlamPreset]];
2894     [UserPresets addObject:[self createDeuxSixQuatrePreset]];
2895     [UserPresets addObject:[self createBrokePreset]];
2896     [UserPresets addObject:[self createBlindPreset]];
2897     [UserPresets addObject:[self createCRFPreset]];
2898     
2899     [self addPreset];
2900 }
2901 - (IBAction)deleteFactoryPresets:(id)sender
2902 {
2903     //int status;
2904     NSEnumerator *enumerator = [UserPresets objectEnumerator];
2905         id tempObject;
2906     
2907         //NSNumber *index;
2908     NSMutableArray *tempArray;
2909
2910
2911         tempArray = [NSMutableArray array];
2912         /* we look here to see if the preset is we move on to the next one */
2913         while ( tempObject = [enumerator nextObject] )  
2914                 {
2915                         /* if the preset is "Factory" then we put it in the array of
2916                         presets to delete */
2917                         if ([[tempObject objectForKey:@"Type"] intValue] == 0)
2918                         {
2919                                 [tempArray addObject:tempObject];
2920                         }
2921         }
2922         
2923         [UserPresets removeObjectsInArray:tempArray];
2924         [tableView reloadData];
2925         [self savePreset];   
2926
2927 }
2928
2929 - (IBAction) showAddPresetPanel: (id) sender
2930 {
2931     /* Deselect the currently selected Preset if there is one*/
2932     [tableView deselectRow:[tableView selectedRow]];
2933
2934     /* Populate the preset picture settings popup here */
2935     [fPresetNewPicSettingsPopUp removeAllItems];
2936     [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
2937     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
2938     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
2939     [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];  
2940         
2941     /* Erase info from the input fields fPresetNewDesc*/
2942         [fPresetNewName setStringValue: @""];
2943         [fPresetNewDesc setStringValue: @""];
2944         /* Show the panel */
2945         [NSApp beginSheet: fAddPresetPanel modalForWindow: fWindow modalDelegate: NULL didEndSelector: NULL contextInfo: NULL];
2946 }
2947
2948 - (IBAction) closeAddPresetPanel: (id) sender
2949 {
2950     [NSApp endSheet: fAddPresetPanel];
2951     [fAddPresetPanel orderOut: self];
2952 }
2953
2954 - (IBAction)addUserPreset:(id)sender
2955 {
2956     if (![[fPresetNewName stringValue] length])
2957             NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
2958     else
2959     {
2960         /* Here we create a custom user preset */
2961         [UserPresets addObject:[self createPreset]];
2962         [self addPreset];
2963         
2964         [self closeAddPresetPanel:NULL];
2965     }
2966 }
2967 - (void)addPreset
2968 {
2969
2970         
2971         /* We Sort the Presets By Factory or Custom */
2972         NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type" 
2973                                                     ascending:YES] autorelease];
2974         /* We Sort the Presets Alphabetically by name */
2975         NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName" 
2976                                                     ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
2977         NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
2978         NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
2979         [UserPresets setArray:sortedArray];
2980         
2981         
2982         /* We Reload the New Table data for presets */
2983     [tableView reloadData];
2984    /* We save all of the preset data here */
2985     [self savePreset];
2986 }
2987
2988 - (IBAction)insertPreset:(id)sender
2989 {
2990     int index = [tableView selectedRow];
2991     [UserPresets insertObject:[self createPreset] atIndex:index];
2992     [tableView reloadData];
2993     [self savePreset];
2994 }
2995
2996 - (NSDictionary *)createPreset
2997 {
2998     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
2999         /* Get the New Preset Name from the field in the AddPresetPanel */
3000     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
3001         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3002         [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
3003         /*Set whether or not this is default, at creation set to 0*/
3004         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3005         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3006         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
3007         /* Get New Preset Description from the field in the AddPresetPanel*/
3008         [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
3009         /* File Format */
3010     [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
3011         /* Chapter Markers fCreateChapterMarkers*/
3012         [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
3013         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
3014         [preset setObject:[NSNumber numberWithInt:[fDstMpgLargeFileCheck state]] forKey:@"Mp4LargeFile"];
3015         /* Codecs */
3016         [preset setObject:[fDstCodecsPopUp titleOfSelectedItem] forKey:@"FileCodecs"];
3017         /* Video encoder */
3018         [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
3019         /* x264 Option String */
3020         [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
3021         
3022         [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
3023         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3024         [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
3025         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3026         
3027         /* Video framerate */
3028         [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
3029         /* GrayScale */
3030         [preset setObject:[NSNumber numberWithInt:[fVidGrayscaleCheck state]] forKey:@"VideoGrayScale"];
3031         /* 2 Pass Encoding */
3032         [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
3033         /* Turbo 2 pass Encoding fVidTurboPassCheck*/
3034         [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
3035         /*Picture Settings*/
3036         hb_job_t * job = fTitle->job;
3037         /* Basic Picture Settings */
3038         /* Use Max Picture settings for whatever the dvd is.*/
3039         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
3040         [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
3041         [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
3042         [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
3043         [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
3044         [preset setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
3045         [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
3046         [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"]; 
3047         /* Set crop settings here */
3048         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3049         [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
3050
3051         [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
3052     [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
3053         [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
3054         [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
3055         
3056         /*Audio*/
3057         /* Audio Sample Rate*/
3058         [preset setObject:[fAudRatePopUp titleOfSelectedItem] forKey:@"AudioSampleRate"];
3059         /* Audio Bitrate Rate*/
3060         [preset setObject:[fAudBitratePopUp titleOfSelectedItem] forKey:@"AudioBitRate"];
3061         /* Subtitles*/
3062         [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
3063         
3064
3065     [preset autorelease];
3066     return preset;
3067
3068 }
3069
3070 - (NSDictionary *)createIpodLowPreset
3071 {
3072     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3073         /* Get the New Preset Name from the field in the AddPresetPanel */
3074     [preset setObject:@"iPod Low-Rez" forKey:@"PresetName"];
3075         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3076         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3077         /*Set whether or not this is default, at creation set to 0*/
3078         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3079         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3080         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3081         /* Get the New Preset Description from the field in the AddPresetPanel */
3082     [preset setObject:@"HandBrake's low resolution settings for the iPod. Optimized for great playback on the iPod screen, with smaller file size." forKey:@"PresetDescription"];
3083         /* File Format */
3084     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3085         /* Chapter Markers*/
3086          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3087     /* Codecs */
3088         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3089         /* Video encoder */
3090         [preset setObject:@"x264 (h.264 iPod)" forKey:@"VideoEncoder"];
3091         /* x264 Option String */
3092         [preset setObject:@"keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=768:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1" forKey:@"x264Option"];
3093         /* Video quality */
3094         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3095         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3096         [preset setObject:@"700" forKey:@"VideoAvgBitrate"];
3097         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3098         
3099         /* Video framerate */
3100         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3101         /* GrayScale */
3102         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3103         /* 2 Pass Encoding */
3104         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
3105         
3106         /*Picture Settings*/
3107         //hb_job_t * job = fTitle->job;
3108         /* Basic Picture Settings */
3109         /* Use Max Picture settings for whatever the dvd is.*/
3110         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
3111         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3112         [preset setObject:[NSNumber numberWithInt:320] forKey:@"PictureWidth"];
3113         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3114         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
3115         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3116         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
3117         /* Set crop settings here */
3118         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3119         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3120     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3121         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3122         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3123         
3124         /*Audio*/
3125         /* Audio Sample Rate*/
3126         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3127         /* Audio Bitrate Rate*/
3128         [preset setObject:@"160" forKey:@"AudioBitRate"];
3129         /* Subtitles*/
3130         [preset setObject:@"None" forKey:@"Subtitles"];
3131         
3132
3133     [preset autorelease];
3134     return preset;
3135
3136 }
3137
3138
3139 - (NSDictionary *)createIpodHighPreset
3140 {
3141     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3142         /* Get the New Preset Name from the field in the AddPresetPanel */
3143     [preset setObject:@"iPod High-Rez" forKey:@"PresetName"];
3144         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3145         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3146         /*Set whether or not this is default, at creation set to 0*/
3147         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3148         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3149         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3150         /* Get the New Preset Description from the field in the AddPresetPanel */
3151     [preset setObject:@"HandBrake's high resolution settings for the iPod. Good video quality, great for viewing on a TV using your iPod" forKey:@"PresetDescription"];
3152         /* File Format */
3153     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3154         /* Chapter Markers*/
3155          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3156     /* Codecs */
3157         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3158         /* Video encoder */
3159         [preset setObject:@"x264 (h.264 iPod)" forKey:@"VideoEncoder"];
3160         /* x264 Option String */
3161         [preset setObject:@"keyint=300:keyint-min=30:bframes=0:cabac=0:ref=1:vbv-maxrate=1500:vbv-bufsize=2000:analyse=all:me=umh:subme=6:no-fast-pskip=1" forKey:@"x264Option"];
3162         /* Video quality */
3163         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3164         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3165         [preset setObject:@"1500" forKey:@"VideoAvgBitrate"];
3166         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3167         
3168         /* Video framerate */
3169         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3170         /* GrayScale */
3171         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3172         /* 2 Pass Encoding */
3173         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
3174         
3175         /*Picture Settings*/
3176         //hb_job_t * job = fTitle->job;
3177         /* Basic Picture Settings */
3178         /* Use Max Picture settings for whatever the dvd is.*/
3179         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
3180         [preset setObject:[NSNumber numberWithInt:640] forKey:@"PictureWidth"];
3181         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3182         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
3183         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3184         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
3185         /* Set crop settings here */
3186         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3187         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3188         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3189     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3190         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3191         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3192         
3193         /*Audio*/
3194         /* Audio Sample Rate*/
3195         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3196         /* Audio Bitrate Rate*/
3197         [preset setObject:@"160" forKey:@"AudioBitRate"];
3198         /* Subtitles*/
3199         [preset setObject:@"None" forKey:@"Subtitles"];
3200         
3201
3202     [preset autorelease];
3203     return preset;
3204
3205 }
3206
3207 - (NSDictionary *)createAppleTVPreset
3208 {
3209     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3210         /* Get the New Preset Name from the field in the AddPresetPanel */
3211     [preset setObject:@"AppleTV" forKey:@"PresetName"];
3212         /*Set whether or not this is a user preset where 0 is factory, 1 is user*/
3213         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3214         /*Set whether or not this is default, at creation set to 0*/
3215         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3216         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3217         [preset setObject:[NSNumber numberWithInt:2] forKey:@"UsesPictureSettings"];
3218         /* Get the New Preset Description from the field in the AddPresetPanel */
3219     [preset setObject:@"HandBrake's settings for the AppleTV. Provides a good balance between quality and file size, and optimizes performance." forKey:@"PresetDescription"];
3220         /* File Format */
3221     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3222         /* Chapter Markers*/
3223          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3224         /* Codecs */
3225         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3226         /* Video encoder */
3227         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3228         /* x264 Option String (We can use this to tweak the appleTV output)*/
3229         [preset setObject:@"bframes=3:ref=1:subme=5:me=umh:no-fast-pskip=1:trellis=2:cabac=0" forKey:@"x264Option"];
3230         /* Video quality */
3231         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3232         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3233         [preset setObject:@"2500" forKey:@"VideoAvgBitrate"];
3234         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3235         
3236         /* Video framerate */
3237         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3238         /* GrayScale */
3239         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3240         /* 2 Pass Encoding */
3241         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
3242         
3243         /*Picture Settings*/
3244         /* For AppleTV we only want to retain UsesMaxPictureSettings
3245         which depend on the source dvd picture settings, so we don't
3246         record the current dvd's picture info since it will vary from
3247         source to source*/
3248         //hb_job_t * job = fTitle->job;
3249         //hb_job_t * job = title->job;
3250         /* Basic Picture Settings */
3251         /* Use Max Picture settings for whatever the dvd is.*/
3252         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3253         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3254         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3255         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
3256         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3257         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
3258         /* Set crop settings here */
3259         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3260         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3261     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3262         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3263         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3264         
3265         /*Audio*/
3266         /* Audio Sample Rate*/
3267         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3268         /* Audio Bitrate Rate*/
3269         [preset setObject:@"160" forKey:@"AudioBitRate"];
3270         /* Subtitles*/
3271         [preset setObject:@"None" forKey:@"Subtitles"];
3272         
3273
3274     [preset autorelease];
3275     return preset;
3276
3277 }
3278
3279 - (NSDictionary *)createPSThreePreset
3280 {
3281     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3282         /* Get the New Preset Name from the field in the AddPresetPanel */
3283     [preset setObject:@"PS3" forKey:@"PresetName"];
3284         /*Set whether or not this is a user preset where 0 is factory, 1 is user*/
3285         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3286         /*Set whether or not this is default, at creation set to 0*/
3287         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3288         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3289         [preset setObject:[NSNumber numberWithInt:2] forKey:@"UsesPictureSettings"];
3290         /* Get the New Preset Description from the field in the AddPresetPanel */
3291     [preset setObject:@"HandBrake's settings for the Sony PlayStation 3." forKey:@"PresetDescription"];
3292         /* File Format */
3293     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3294         /* Chapter Markers*/
3295          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3296         /* Codecs */
3297         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3298         /* Video encoder */
3299         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3300         /* x264 Option String (We can use this to tweak the appleTV output)*/
3301         [preset setObject:@"level=41:subme=5:me=umh" forKey:@"x264Option"];
3302         /* Video quality */
3303         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3304         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3305         [preset setObject:@"2500" forKey:@"VideoAvgBitrate"];
3306         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3307         
3308         /* Video framerate */
3309         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3310         /* GrayScale */
3311         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3312         /* 2 Pass Encoding */
3313         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
3314         
3315         /*Picture Settings*/
3316         /* For PS3 we only want to retain UsesMaxPictureSettings
3317         which depend on the source dvd picture settings, so we don't
3318         record the current dvd's picture info since it will vary from
3319         source to source*/
3320         /* Use Max Picture settings for whatever the dvd is.*/
3321         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3322         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3323         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3324         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
3325         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3326         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
3327         /* Set crop settings here */
3328         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3329         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3330     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3331         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3332         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3333         
3334         /*Audio*/
3335         /* Audio Sample Rate*/
3336         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3337         /* Audio Bitrate Rate*/
3338         [preset setObject:@"160" forKey:@"AudioBitRate"];
3339         /* Subtitles*/
3340         [preset setObject:@"None" forKey:@"Subtitles"];
3341         
3342
3343     [preset autorelease];
3344     return preset;
3345
3346 }
3347 - (NSDictionary *)createPSPPreset
3348 {
3349     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3350         /* Get the New Preset Name from the field in the AddPresetPanel */
3351     [preset setObject:@"PSP" forKey:@"PresetName"];
3352         /*Set whether or not this is a user preset where 0 is factory, 1 is user*/
3353         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3354         /*Set whether or not this is default, at creation set to 0*/
3355         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3356         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3357         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3358         /* Get the New Preset Description from the field in the AddPresetPanel */
3359     [preset setObject:@"HandBrake's settings for the Sony PlayStation Portable." forKey:@"PresetDescription"];
3360         /* File Format */
3361     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3362         /* Chapter Markers*/
3363          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3364         /* Codecs */
3365         [preset setObject:@"MPEG-4 Video / AAC Audio" forKey:@"FileCodecs"];
3366         /* Video encoder */
3367         [preset setObject:@"FFmpeg" forKey:@"VideoEncoder"];
3368         /* x264 Option String (We can use this to tweak the appleTV output)*/
3369         [preset setObject:@"" forKey:@"x264Option"];
3370         /* Video quality */
3371         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3372         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3373         [preset setObject:@"1024" forKey:@"VideoAvgBitrate"];
3374         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3375         
3376         /* Video framerate */
3377         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3378         /* GrayScale */
3379         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3380         /* 2 Pass Encoding */
3381         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
3382         
3383         /*Picture Settings*/
3384         /* For PS3 we only want to retain UsesMaxPictureSettings
3385         which depend on the source dvd picture settings, so we don't
3386         record the current dvd's picture info since it will vary from
3387         source to source*/
3388         /* Use Max Picture settings for whatever the dvd is.*/
3389         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
3390         [preset setObject:@"368" forKey:@"PictureWidth"];
3391         [preset setObject:@"208" forKey:@"PictureHeight"];
3392         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
3393         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3394         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
3395         /* Set crop settings here */
3396         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3397         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3398         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3399     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3400         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3401         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3402         
3403         /*Audio*/
3404         /* Audio Sample Rate*/
3405         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3406         /* Audio Bitrate Rate*/
3407         [preset setObject:@"128" forKey:@"AudioBitRate"];
3408         /* Subtitles*/
3409         [preset setObject:@"None" forKey:@"Subtitles"];
3410         
3411
3412     [preset autorelease];
3413     return preset;
3414
3415 }
3416
3417 - (NSDictionary *)createNormalPreset
3418 {
3419     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3420         /* Get the New Preset Name from the field in the AddPresetPanel */
3421     [preset setObject:@"Normal" forKey:@"PresetName"];
3422         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3423         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3424         /*Set whether or not this is default, at creation set to 0*/
3425         [preset setObject:[NSNumber numberWithInt:1] forKey:@"Default"];
3426         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3427         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3428         /* Get the New Preset Description from the field in the AddPresetPanel */
3429     [preset setObject:@"HandBrake's normal, default settings." forKey:@"PresetDescription"];
3430         /* File Format */
3431     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3432         /* Chapter Markers*/
3433          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3434     /* Codecs */
3435         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3436         /* Video encoder */
3437         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3438         /* x264 Option String */
3439         [preset setObject:@"ref=2:bframes=2:subme=5:me=umh" forKey:@"x264Option"];
3440         /* Video quality */
3441         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3442         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3443         [preset setObject:@"1500" forKey:@"VideoAvgBitrate"];
3444         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3445         
3446         /* Video framerate */
3447         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3448         /* GrayScale */
3449         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3450         /* 2 Pass Encoding */
3451         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
3452         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
3453         
3454         /*Picture Settings*/
3455         //hb_job_t * job = fTitle->job;
3456         /* Basic Picture Settings */
3457         /* Use Max Picture settings for whatever the dvd is.*/
3458         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3459         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3460         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3461         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3462         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
3463         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3464         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
3465         /* Set crop settings here */
3466         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3467         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3468     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3469         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3470         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3471         
3472         /*Audio*/
3473         /* Audio Sample Rate*/
3474         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3475         /* Audio Bitrate Rate*/
3476         [preset setObject:@"160" forKey:@"AudioBitRate"];
3477         /* Subtitles*/
3478         [preset setObject:@"None" forKey:@"Subtitles"];
3479         
3480
3481     [preset autorelease];
3482     return preset;
3483
3484 }
3485
3486 - (NSDictionary *)createClassicPreset
3487 {
3488     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3489         /* Get the New Preset Name from the field in the AddPresetPanel */
3490     [preset setObject:@"Classic" forKey:@"PresetName"];
3491         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3492         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3493         /*Set whether or not this is default, at creation set to 0*/
3494         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3495         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3496         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3497         /* Get the New Preset Description from the field in the AddPresetPanel */
3498     [preset setObject:@"HandBrake's traditional, faster, lower-quality settings." forKey:@"PresetDescription"];
3499         /* File Format */
3500     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3501         /* Chapter Markers*/
3502          [preset setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
3503     /* Codecs */
3504         [preset setObject:@"MPEG-4 Video / AAC Audio" forKey:@"FileCodecs"];
3505         /* Video encoder */
3506         [preset setObject:@"FFmpeg" forKey:@"VideoEncoder"];
3507         /* x264 Option String */
3508         [preset setObject:@"" forKey:@"x264Option"];
3509         /* Video quality */
3510         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3511         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3512         [preset setObject:@"1000" forKey:@"VideoAvgBitrate"];
3513         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3514         
3515         /* Video framerate */
3516         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3517         /* GrayScale */
3518         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3519         /* 2 Pass Encoding */
3520         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
3521         
3522         /*Picture Settings*/
3523         //hb_job_t * job = fTitle->job;
3524         /* Basic Picture Settings */
3525         /* Use Max Picture settings for whatever the dvd is.*/
3526         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3527         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3528         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3529         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3530         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
3531         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3532         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
3533         /* Set crop settings here */
3534         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3535         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3536     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3537         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3538         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3539         
3540         /*Audio*/
3541         /* Audio Sample Rate*/
3542         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3543         /* Audio Bitrate Rate*/
3544         [preset setObject:@"160" forKey:@"AudioBitRate"];
3545         /* Subtitles*/
3546         [preset setObject:@"None" forKey:@"Subtitles"];
3547         
3548
3549     [preset autorelease];
3550     return preset;
3551
3552 }
3553
3554 - (NSDictionary *)createFilmPreset
3555 {
3556     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3557         /* Get the New Preset Name from the field in the AddPresetPanel */
3558     [preset setObject:@"Film" forKey:@"PresetName"];
3559         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3560         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3561         /*Set whether or not this is default, at creation set to 0*/
3562         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3563         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3564         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3565         /* Get the New Preset Description from the field in the AddPresetPanel */
3566     [preset setObject:@"HandBrake's preset for feature films." forKey:@"PresetDescription"];
3567         /* File Format */
3568     [preset setObject:@"MKV file" forKey:@"FileFormat"];
3569         /* Chapter Markers*/
3570          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3571     /* Codecs */
3572         [preset setObject:@"AVC/H.264 Video / AC-3 Audio" forKey:@"FileCodecs"];
3573         /* Video encoder */
3574         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3575         /* x264 Option String */
3576         [preset setObject:@"ref=3:mixed-refs:bframes=3:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:no-fast-pskip" forKey:@"x264Option"];
3577         /* Video quality */
3578         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3579         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3580         [preset setObject:@"2000" forKey:@"VideoAvgBitrate"];
3581         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3582         
3583         /* Video framerate */
3584         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3585         /* GrayScale */
3586         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3587         /* 2 Pass Encoding */
3588         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
3589         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
3590         
3591         /*Picture Settings*/
3592         //hb_job_t * job = fTitle->job;
3593         /* Basic Picture Settings */
3594         /* Use Max Picture settings for whatever the dvd is.*/
3595         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3596         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3597         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3598         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3599         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
3600         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3601         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
3602         /* Set crop settings here */
3603         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3604         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3605     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3606         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3607         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3608         
3609         /*Audio*/
3610         /* Audio Sample Rate*/
3611         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3612         /* Audio Bitrate Rate*/
3613         [preset setObject:@"160" forKey:@"AudioBitRate"];
3614         /* Subtitles*/
3615         [preset setObject:@"None" forKey:@"Subtitles"];
3616         
3617
3618     [preset autorelease];
3619     return preset;
3620
3621 }
3622
3623 - (NSDictionary *)createTelevisionPreset
3624 {
3625     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3626         /* Get the New Preset Name from the field in the AddPresetPanel */
3627     [preset setObject:@"Television" forKey:@"PresetName"];
3628         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3629         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3630         /*Set whether or not this is default, at creation set to 0*/
3631         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3632         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3633         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3634         /* Get the New Preset Description from the field in the AddPresetPanel */
3635     [preset setObject:@"HandBrake's settings for video from television." forKey:@"PresetDescription"];
3636         /* File Format */
3637     [preset setObject:@"MKV file" forKey:@"FileFormat"];
3638         /* Chapter Markers*/
3639          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3640     /* Codecs */
3641         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3642         /* Video encoder */
3643         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3644         /* x264 Option String */
3645         [preset setObject:@"ref=3:mixed-refs:bframes=6:bime:weightb:direct=auto:b-pyramid:me=umh:subme=6:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip" forKey:@"x264Option"];
3646         /* Video quality */
3647         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3648         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3649         [preset setObject:@"1300" forKey:@"VideoAvgBitrate"];
3650         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3651         
3652         /* Video framerate */
3653         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3654         /* GrayScale */
3655         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3656         /* 2 Pass Encoding */
3657         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
3658         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
3659         
3660         /*Picture Settings*/
3661         //hb_job_t * job = fTitle->job;
3662         /* Basic Picture Settings */
3663         /* Use Max Picture settings for whatever the dvd is.*/
3664         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3665         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3666         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3667         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3668         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
3669         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureDeinterlace"];
3670         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
3671         /* Set crop settings here */
3672         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3673         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3674     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3675         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3676         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3677         
3678         /*Audio*/
3679         /* Audio Sample Rate*/
3680         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3681         /* Audio Bitrate Rate*/
3682         [preset setObject:@"160" forKey:@"AudioBitRate"];
3683         /* Subtitles*/
3684         [preset setObject:@"None" forKey:@"Subtitles"];
3685         
3686
3687     [preset autorelease];
3688     return preset;
3689
3690 }
3691
3692 - (NSDictionary *)createAnimationPreset
3693 {
3694     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3695         /* Get the New Preset Name from the field in the AddPresetPanel */
3696     [preset setObject:@"Animation" forKey:@"PresetName"];
3697         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3698         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3699         /*Set whether or not this is default, at creation set to 0*/
3700         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3701         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3702         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3703         /* Get the New Preset Description from the field in the AddPresetPanel */
3704     [preset setObject:@"HandBrake's settings for cartoons, anime, and CGI." forKey:@"PresetDescription"];
3705         /* File Format */
3706     [preset setObject:@"MKV file" forKey:@"FileFormat"];
3707         /* Chapter Markers*/
3708          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3709     /* Codecs */
3710         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3711         /* Video encoder */
3712         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3713         /* x264 Option String */
3714         [preset setObject:@"ref=5:mixed-refs:bframes=6:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=5:analyse=all:8x8dct:trellis=1:nr=150:no-fast-pskip:filter=2,2" forKey:@"x264Option"];
3715         /* Video quality */
3716         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3717         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3718         [preset setObject:@"1000" forKey:@"VideoAvgBitrate"];
3719         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3720         
3721         /* Video framerate */
3722         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3723         /* GrayScale */
3724         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3725         /* 2 Pass Encoding */
3726         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
3727         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
3728         
3729         /*Picture Settings*/
3730         //hb_job_t * job = fTitle->job;
3731         /* Basic Picture Settings */
3732         /* Use Max Picture settings for whatever the dvd is.*/
3733         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3734         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3735         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3736         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3737         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
3738         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureDeinterlace"];
3739         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
3740         /* Set crop settings here */
3741         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3742         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3743     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3744         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3745         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3746         
3747         /*Audio*/
3748         /* Audio Sample Rate*/
3749         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3750         /* Audio Bitrate Rate*/
3751         [preset setObject:@"160" forKey:@"AudioBitRate"];
3752         /* Subtitles*/
3753         [preset setObject:@"None" forKey:@"Subtitles"];
3754         
3755
3756     [preset autorelease];
3757     return preset;
3758
3759 }
3760
3761 - (NSDictionary *)createQuickTimePreset
3762 {
3763     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3764         /* Get the New Preset Name from the field in the AddPresetPanel */
3765     [preset setObject:@"QuickTime" forKey:@"PresetName"];
3766         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3767         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3768         /*Set whether or not this is default, at creation set to 0*/
3769         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3770         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3771         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3772         /* Get the New Preset Description from the field in the AddPresetPanel */
3773     [preset setObject:@"HandBrake's high quality settings for use with QuickTime. It can be slow, so use it when the Normal preset doesn't look good enough." forKey:@"PresetDescription"];
3774         /* File Format */
3775     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3776         /* Chapter Markers*/
3777          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3778     /* Codecs */
3779         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3780         /* Video encoder */
3781         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3782         /* x264 Option String */
3783         [preset setObject:@"ref=3:mixed-refs:bframes=3:bime:weightb:b-rdo:direct=auto:me=umh:subme=5:analyse=all:8x8dct:trellis=1:no-fast-pskip" forKey:@"x264Option"];
3784         /* Video quality */
3785         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3786         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3787         [preset setObject:@"2000" forKey:@"VideoAvgBitrate"];
3788         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3789         
3790         /* Video framerate */
3791         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3792         /* GrayScale */
3793         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3794         /* 2 Pass Encoding */
3795         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
3796         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
3797         
3798         /*Picture Settings*/
3799         //hb_job_t * job = fTitle->job;
3800         /* Basic Picture Settings */
3801         /* Use Max Picture settings for whatever the dvd is.*/
3802         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3803         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3804         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3805         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3806         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
3807         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3808         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
3809         /* Set crop settings here */
3810         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3811         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3812     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3813         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3814         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3815         
3816         /*Audio*/
3817         /* Audio Sample Rate*/
3818         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3819         /* Audio Bitrate Rate*/
3820         [preset setObject:@"160" forKey:@"AudioBitRate"];
3821         /* Subtitles*/
3822         [preset setObject:@"None" forKey:@"Subtitles"];
3823         
3824
3825     [preset autorelease];
3826     return preset;
3827
3828 }
3829
3830 - (NSDictionary *)createBedlamPreset
3831 {
3832     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3833         /* Get the New Preset Name from the field in the AddPresetPanel */
3834     [preset setObject:@"Bedlam" forKey:@"PresetName"];
3835         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3836         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3837         /*Set whether or not this is default, at creation set to 0*/
3838         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3839         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3840         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3841         /* Get the New Preset Description from the field in the AddPresetPanel */
3842     [preset setObject:@"HandBrake's settings maxed out for slowest encoding and highest quality. Use at your own risk. So slow it's not just insane...it's a trip to the looney bin." forKey:@"PresetDescription"];
3843         /* File Format */
3844     [preset setObject:@"MKV file" forKey:@"FileFormat"];
3845         /* Chapter Markers*/
3846          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3847     /* Codecs */
3848         [preset setObject:@"AVC/H.264 Video / AC-3 Audio" forKey:@"FileCodecs"];
3849         /* Video encoder */
3850         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3851         /* x264 Option String */
3852         [preset setObject:@"ref=16:mixed-refs:bframes=6:bime:weightb:b-rdo:direct=auto:b-pyramid:me=umh:subme=7:me-range=64:analyse=all:8x8dct:trellis=2:no-fast-pskip:no-dct-decimate:filter=-2,-1" forKey:@"x264Option"];
3853         /* Video quality */
3854         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3855         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3856         [preset setObject:@"1800" forKey:@"VideoAvgBitrate"];
3857         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3858         
3859         /* Video framerate */
3860         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3861         /* GrayScale */
3862         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3863         /* 2 Pass Encoding */
3864         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
3865         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
3866         
3867         /*Picture Settings*/
3868         //hb_job_t * job = fTitle->job;
3869         /* Basic Picture Settings */
3870         /* Use Max Picture settings for whatever the dvd is.*/
3871         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
3872         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3873         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
3874         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3875         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
3876         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3877         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
3878         /* Set crop settings here */
3879         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3880         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3881     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3882         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3883         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3884         
3885         /*Audio*/
3886         /* Audio Sample Rate*/
3887         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3888         /* Audio Bitrate Rate*/
3889         [preset setObject:@"160" forKey:@"AudioBitRate"];
3890         /* Subtitles*/
3891         [preset setObject:@"None" forKey:@"Subtitles"];
3892         
3893
3894     [preset autorelease];
3895     return preset;
3896
3897 }
3898
3899 - (NSDictionary *)createiPhonePreset
3900 {
3901     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3902         /* Get the New Preset Name from the field in the AddPresetPanel */
3903     [preset setObject:@"iPhone" forKey:@"PresetName"];
3904         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3905         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3906         /*Set whether or not this is default, at creation set to 0*/
3907         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3908         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3909         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3910         /* Get the New Preset Description from the field in the AddPresetPanel */
3911     [preset setObject:@"HandBrake's settings for the iPhone." forKey:@"PresetDescription"];
3912         /* File Format */
3913     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
3914         /* Chapter Markers*/
3915          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3916     /* Codecs */
3917         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
3918         /* Video encoder */
3919         [preset setObject:@"x264 (h.264 iPod)" forKey:@"VideoEncoder"];
3920         /* x264 Option String */
3921         [preset setObject:@"cabac=0:ref=1:analyse=all:me=umh:subme=6:no-fast-pskip=1:trellis=1" forKey:@"x264Option"];
3922         /* Video quality */
3923         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3924         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3925         [preset setObject:@"960" forKey:@"VideoAvgBitrate"];
3926         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3927         
3928         /* Video framerate */
3929         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3930         /* GrayScale */
3931         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
3932         /* 2 Pass Encoding */
3933         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
3934         
3935         /*Picture Settings*/
3936         //hb_job_t * job = fTitle->job;
3937         /* Basic Picture Settings */
3938         /* Use Max Picture settings for whatever the dvd is.*/
3939         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
3940         [preset setObject:[NSNumber numberWithInt:480] forKey:@"PictureWidth"];
3941         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
3942         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
3943         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
3944         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
3945         /* Set crop settings here */
3946         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
3947         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
3948         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
3949     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
3950         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
3951         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
3952         
3953         /*Audio*/
3954         /* Audio Sample Rate*/
3955         [preset setObject:@"48" forKey:@"AudioSampleRate"];
3956         /* Audio Bitrate Rate*/
3957         [preset setObject:@"128" forKey:@"AudioBitRate"];
3958         /* Subtitles*/
3959         [preset setObject:@"None" forKey:@"Subtitles"];
3960         
3961
3962     [preset autorelease];
3963     return preset;
3964
3965 }
3966
3967 - (NSDictionary *)createDeuxSixQuatrePreset
3968 {
3969     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
3970         /* Get the New Preset Name from the field in the AddPresetPanel */
3971     [preset setObject:@"Deux Six Quatre" forKey:@"PresetName"];
3972         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
3973         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
3974         /*Set whether or not this is default, at creation set to 0*/
3975         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
3976         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
3977         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
3978         /* Get the New Preset Description from the field in the AddPresetPanel */
3979     [preset setObject:@"HandBrake's preset for true high profile x264 quality. A good balance of quality and speed, based on community standards found in the wild. This preset will give you a much better sense of x264's capabilities than vanilla main profile." forKey:@"PresetDescription"];
3980         /* File Format */
3981     [preset setObject:@"MKV file" forKey:@"FileFormat"];
3982         /* Chapter Markers*/
3983          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
3984     /* Codecs */
3985         [preset setObject:@"AVC/H.264 Video / AC-3 Audio" forKey:@"FileCodecs"];
3986         /* Video encoder */
3987         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
3988         /* x264 Option String */
3989         [preset setObject:@"ref=5:mixed-refs:bframes=3:bime:weightb:b-rdo:b-pyramid:me=umh:subme=7:trellis=1:analyse=all:8x8dct:no-fast-pskip" forKey:@"x264Option"];
3990         /* Video quality */
3991         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
3992         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
3993         [preset setObject:@"1600" forKey:@"VideoAvgBitrate"];
3994         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
3995         
3996         /* Video framerate */
3997         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
3998         /* GrayScale */
3999         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
4000         /* 2 Pass Encoding */
4001         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
4002         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
4003         
4004         /*Picture Settings*/
4005         //hb_job_t * job = fTitle->job;
4006         /* Basic Picture Settings */
4007         /* Use Max Picture settings for whatever the dvd is.*/
4008         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
4009         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
4010         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
4011         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
4012         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
4013         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
4014         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
4015         /* Set crop settings here */
4016         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
4017         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
4018     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
4019         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
4020         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
4021         
4022         /*Audio*/
4023         /* Audio Sample Rate*/
4024         [preset setObject:@"48" forKey:@"AudioSampleRate"];
4025         /* Audio Bitrate Rate*/
4026         [preset setObject:@"160" forKey:@"AudioBitRate"];
4027         /* Subtitles*/
4028         [preset setObject:@"None" forKey:@"Subtitles"];
4029         
4030
4031     [preset autorelease];
4032     return preset;
4033
4034 }
4035
4036 - (NSDictionary *)createBrokePreset
4037 {
4038     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
4039         /* Get the New Preset Name from the field in the AddPresetPanel */
4040     [preset setObject:@"Broke" forKey:@"PresetName"];
4041         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
4042         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
4043         /*Set whether or not this is default, at creation set to 0*/
4044         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
4045         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
4046         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
4047         /* Get the New Preset Description from the field in the AddPresetPanel */
4048     [preset setObject:@"HandBrake's preset for people without a lot of money to waste on hard drives. Tries to maximize quality for burning to CDs, so you can party like it's 1999." forKey:@"PresetDescription"];
4049         /* File Format */
4050     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
4051         /* Chapter Markers*/
4052          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
4053     /* Codecs */
4054         [preset setObject:@"AVC/H.264 Video / AAC Audio" forKey:@"FileCodecs"];
4055         /* Video encoder */
4056         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
4057         /* x264 Option String */
4058         [preset setObject:@"ref=3:mixed-refs:bframes=6:bime:weightb:b-rdo:b-pyramid:direct=auto:me=umh:subme=6:trellis=1:analyse=all:8x8dct:no-fast-pskip" forKey:@"x264Option"];
4059         /* Video quality */
4060         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoQualityType"];
4061         [preset setObject:@"695" forKey:@"VideoTargetSize"];
4062         [preset setObject:@"1600" forKey:@"VideoAvgBitrate"];
4063         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
4064         
4065         /* Video framerate */
4066         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
4067         /* GrayScale */
4068         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
4069         /* 2 Pass Encoding */
4070         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTwoPass"];
4071         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoTurboTwoPass"];
4072         
4073         /*Picture Settings*/
4074         //hb_job_t * job = fTitle->job;
4075         /* Basic Picture Settings */
4076         /* Use Max Picture settings for whatever the dvd is.*/
4077         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
4078         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
4079         [preset setObject:[NSNumber numberWithInt:640] forKey:@"PictureWidth"];
4080         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
4081         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
4082         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
4083         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
4084         /* Set crop settings here */
4085         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
4086         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
4087     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
4088         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
4089         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
4090         
4091         /*Audio*/
4092         /* Audio Sample Rate*/
4093         [preset setObject:@"48" forKey:@"AudioSampleRate"];
4094         /* Audio Bitrate Rate*/
4095         [preset setObject:@"128" forKey:@"AudioBitRate"];
4096         /* Subtitles*/
4097         [preset setObject:@"None" forKey:@"Subtitles"];
4098         
4099
4100     [preset autorelease];
4101     return preset;
4102
4103 }
4104
4105 - (NSDictionary *)createBlindPreset
4106 {
4107     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
4108         /* Get the New Preset Name from the field in the AddPresetPanel */
4109     [preset setObject:@"Blind" forKey:@"PresetName"];
4110         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
4111         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
4112         /*Set whether or not this is default, at creation set to 0*/
4113         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
4114         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
4115         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
4116         /* Get the New Preset Description from the field in the AddPresetPanel */
4117     [preset setObject:@"HandBrake's preset for impatient people who don't care about picture quality." forKey:@"PresetDescription"];
4118         /* File Format */
4119     [preset setObject:@"MP4 file" forKey:@"FileFormat"];
4120         /* Chapter Markers*/
4121          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
4122     /* Codecs */
4123         [preset setObject:@"MPEG-4 Video / AAC Audio" forKey:@"FileCodecs"];
4124         /* Video encoder */
4125         [preset setObject:@"FFmpeg" forKey:@"VideoEncoder"];
4126         /* x264 Option String */
4127         [preset setObject:@"" forKey:@"x264Option"];
4128         /* Video quality */
4129         [preset setObject:[NSNumber numberWithInt:1] forKey:@"VideoQualityType"];
4130         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
4131         [preset setObject:@"512" forKey:@"VideoAvgBitrate"];
4132         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
4133         
4134         /* Video framerate */
4135         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
4136         /* GrayScale */
4137         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
4138         /* 2 Pass Encoding */
4139         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
4140         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTurboTwoPass"];
4141         
4142         /*Picture Settings*/
4143         //hb_job_t * job = fTitle->job;
4144         /* Basic Picture Settings */
4145         /* Use Max Picture settings for whatever the dvd is.*/
4146         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
4147         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
4148         [preset setObject:[NSNumber numberWithInt:512] forKey:@"PictureWidth"];
4149         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
4150         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureKeepRatio"];
4151         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
4152         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PicturePAR"];
4153         /* Set crop settings here */
4154         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
4155         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
4156     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
4157         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
4158         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
4159         
4160         /*Audio*/
4161         /* Audio Sample Rate*/
4162         [preset setObject:@"48" forKey:@"AudioSampleRate"];
4163         /* Audio Bitrate Rate*/
4164         [preset setObject:@"128" forKey:@"AudioBitRate"];
4165         /* Subtitles*/
4166         [preset setObject:@"None" forKey:@"Subtitles"];
4167         
4168
4169     [preset autorelease];
4170     return preset;
4171
4172 }
4173
4174 - (NSDictionary *)createCRFPreset
4175 {
4176     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
4177         /* Get the New Preset Name from the field in the AddPresetPanel */
4178     [preset setObject:@"Constant Quality Rate" forKey:@"PresetName"];
4179         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
4180         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Type"];
4181         /*Set whether or not this is default, at creation set to 0*/
4182         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
4183         /*Get the whether or not to apply pic settings in the AddPresetPanel*/
4184         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesPictureSettings"];
4185         /* Get the New Preset Description from the field in the AddPresetPanel */
4186     [preset setObject:@"HandBrake's preset for consistently excellent quality in one pass, with the downside of entirely unpredictable file sizes and bitrates." forKey:@"PresetDescription"];
4187         /* File Format */
4188     [preset setObject:@"MKV file" forKey:@"FileFormat"];
4189         /* Chapter Markers*/
4190          [preset setObject:[NSNumber numberWithInt:1] forKey:@"ChapterMarkers"];
4191     /* Codecs */
4192         [preset setObject:@"AVC/H.264 Video / AC-3 Audio" forKey:@"FileCodecs"];
4193         /* Video encoder */
4194         [preset setObject:@"x264 (h.264 Main)" forKey:@"VideoEncoder"];
4195         /* x264 Option String */
4196         [preset setObject:@"ref=3:mixed-refs:bframes=3:b-pyramid:b-rdo:bime:weightb:filter=-2,-1:subme=6:trellis=1:analyse=all:8x8dct:me=umh" forKey:@"x264Option"];
4197         /* Video quality */
4198         [preset setObject:[NSNumber numberWithInt:2] forKey:@"VideoQualityType"];
4199         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
4200         [preset setObject:@"2000" forKey:@"VideoAvgBitrate"];
4201         [preset setObject:[NSNumber numberWithFloat:0.6471] forKey:@"VideoQualitySlider"];
4202         
4203         /* Video framerate */
4204         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
4205         /* GrayScale */
4206         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoGrayScale"];
4207         /* 2 Pass Encoding */
4208         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTwoPass"];
4209         [preset setObject:[NSNumber numberWithInt:0] forKey:@"VideoTurboTwoPass"];
4210         
4211         /*Picture Settings*/
4212         //hb_job_t * job = fTitle->job;
4213         /* Basic Picture Settings */
4214         /* Use Max Picture settings for whatever the dvd is.*/
4215         [preset setObject:[NSNumber numberWithInt:1] forKey:@"UsesMaxPictureSettings"];
4216         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PictureAutoCrop"];
4217         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureWidth"];
4218         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureHeight"];
4219         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureKeepRatio"];
4220         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureDeinterlace"];
4221         [preset setObject:[NSNumber numberWithInt:1] forKey:@"PicturePAR"];
4222         /* Set crop settings here */
4223         /* The Auto Crop Matrix in the Picture Window autodetects differences in crop settings */
4224         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureTopCrop"];
4225     [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureBottomCrop"];
4226         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureLeftCrop"];
4227         [preset setObject:[NSNumber numberWithInt:0] forKey:@"PictureRightCrop"];
4228         
4229         /*Audio*/
4230         /* Audio Sample Rate*/
4231         [preset setObject:@"48" forKey:@"AudioSampleRate"];
4232         /* Audio Bitrate Rate*/
4233         [preset setObject:@"160" forKey:@"AudioBitRate"];
4234         /* Subtitles*/
4235         [preset setObject:@"None" forKey:@"Subtitles"];
4236         
4237
4238     [preset autorelease];
4239     return preset;
4240
4241 }
4242
4243
4244 - (IBAction)deletePreset:(id)sender
4245 {
4246     int status;
4247     NSEnumerator *enumerator;
4248     NSNumber *index;
4249     NSMutableArray *tempArray;
4250     id tempObject;
4251     
4252     if ( [tableView numberOfSelectedRows] == 0 )
4253         return;
4254     /* Alert user before deleting preset */
4255         /* Comment out for now, tie to user pref eventually */
4256
4257     //NSBeep();
4258     status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
4259     
4260     if ( status == NSAlertDefaultReturn ) {
4261         enumerator = [tableView selectedRowEnumerator];
4262         tempArray = [NSMutableArray array];
4263         
4264         while ( (index = [enumerator nextObject]) ) {
4265             tempObject = [UserPresets objectAtIndex:[index intValue]];
4266             [tempArray addObject:tempObject];
4267         }
4268         
4269         [UserPresets removeObjectsInArray:tempArray];
4270         [tableView reloadData];
4271         [self savePreset];   
4272     }
4273 }
4274
4275 - (IBAction)getDefaultPresets:(id)sender
4276 {
4277         int i = 0;
4278     NSEnumerator *enumerator = [UserPresets objectEnumerator];
4279         id tempObject;
4280         while (tempObject = [enumerator nextObject])
4281         {
4282                 NSDictionary *thisPresetDict = tempObject;
4283                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
4284                 {
4285                         presetHbDefault = i;    
4286                 }
4287                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
4288                 {
4289                         presetUserDefault = i;  
4290                 }
4291                 i++;
4292         }
4293 }
4294
4295 - (IBAction)setDefaultPreset:(id)sender
4296 {
4297     int i = 0;
4298     NSEnumerator *enumerator = [UserPresets objectEnumerator];
4299         id tempObject;
4300         /* First make sure the old user specified default preset is removed */
4301         while (tempObject = [enumerator nextObject])
4302         {
4303                 /* make sure we are not removing the default HB preset */
4304                 if ([[[UserPresets objectAtIndex:i] objectForKey:@"Default"] intValue] != 1) // 1 is HB default
4305                 {
4306                         [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
4307                 }
4308                 i++;
4309         }
4310         /* Second, go ahead and set the appropriate user specfied preset */
4311         /* we get the chosen preset from the UserPresets array */
4312         if ([[[UserPresets objectAtIndex:[tableView selectedRow]] objectForKey:@"Default"] intValue] != 1) // 1 is HB default
4313         {
4314                 [[UserPresets objectAtIndex:[tableView selectedRow]] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
4315         }
4316         presetUserDefault = [tableView selectedRow];
4317         
4318         /* We save all of the preset data here */
4319     [self savePreset];
4320         /* We Reload the New Table data for presets */
4321     [tableView reloadData];
4322 }
4323
4324 - (IBAction)selectDefaultPreset:(id)sender
4325 {
4326         /* if there is a user specified default, we use it */
4327         if (presetUserDefault)
4328         {
4329         [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:presetUserDefault] byExtendingSelection:NO];
4330         [self tableViewSelected:NULL];
4331         }
4332         else if (presetHbDefault) //else we use the built in default presetHbDefault
4333         {
4334         [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:presetHbDefault] byExtendingSelection:NO];
4335         [self tableViewSelected:NULL];
4336         }
4337 }
4338
4339 - (IBAction)tableViewSelected:(id)sender
4340 {
4341     /* Since we cannot disable the presets tableView in terms of clickability
4342            we will use the enabled state of the add presets button to determine whether
4343            or not clicking on a preset will do anything */
4344         if ([fPresetsAdd isEnabled])
4345         {
4346                 if ([tableView selectedRow] >= 0)
4347                 {       
4348                         /* we get the chosen preset from the UserPresets array */
4349                         chosenPreset = [UserPresets objectAtIndex:[tableView selectedRow]];
4350                         curUserPresetChosenNum = [sender selectedRow];
4351                         /* we set the preset display field in main window here */
4352                         [fPresetSelectedDisplay setStringValue: [NSString stringWithFormat: @"%@",[chosenPreset valueForKey:@"PresetName"]]];
4353                         if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
4354                         {
4355                                 [fPresetSelectedDisplay setStringValue: [NSString stringWithFormat: @"%@ (Default)",[chosenPreset valueForKey:@"PresetName"]]];
4356                         }
4357                         else
4358                         {
4359                                 [fPresetSelectedDisplay setStringValue: [NSString stringWithFormat: @"%@",[chosenPreset valueForKey:@"PresetName"]]];
4360                         }
4361                         /* File Format */
4362                         [fDstFormatPopUp selectItemWithTitle: [NSString stringWithFormat:[chosenPreset valueForKey:@"FileFormat"]]];
4363                         [self formatPopUpChanged: NULL];
4364                         
4365                         /* Chapter Markers*/
4366                         [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
4367                         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
4368                         [fDstMpgLargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
4369                         /* Codecs */
4370                         [fDstCodecsPopUp selectItemWithTitle: [NSString stringWithFormat:[chosenPreset valueForKey:@"FileCodecs"]]];
4371                         [self codecsPopUpChanged: NULL];
4372                         /* Video encoder */
4373                         [fVidEncoderPopUp selectItemWithTitle: [NSString stringWithFormat:[chosenPreset valueForKey:@"VideoEncoder"]]];
4374                         
4375                         /* We can show the preset options here in the gui if we want to
4376                                 so we check to see it the user has specified it in the prefs */
4377                         [fAdvancedOptions setOptions: [NSString stringWithFormat:[chosenPreset valueForKey:@"x264Option"]]];
4378                         
4379                         /* Lets run through the following functions to get variables set there */
4380                         [self encoderPopUpChanged: NULL];
4381                         
4382                         [self calculateBitrate: NULL];
4383                         
4384                         /* Video quality */
4385                         [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
4386                         
4387                         [fVidTargetSizeField setStringValue: [NSString stringWithFormat:[chosenPreset valueForKey:@"VideoTargetSize"]]];
4388                         [fVidBitrateField setStringValue: [NSString stringWithFormat:[chosenPreset valueForKey:@"VideoAvgBitrate"]]];
4389                         
4390                         [fVidQualitySlider setFloatValue: [[chosenPreset valueForKey:@"VideoQualitySlider"] floatValue]];
4391                         [self videoMatrixChanged: NULL];
4392                         
4393                         /* Video framerate */
4394                         [fVidRatePopUp selectItemWithTitle: [NSString stringWithFormat:[chosenPreset valueForKey:@"VideoFramerate"]]];
4395                         
4396                         /* GrayScale */
4397                         [fVidGrayscaleCheck setState:[[chosenPreset objectForKey:@"VideoGrayScale"] intValue]];
4398                         
4399                         /* 2 Pass Encoding */
4400                         [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
4401                         [self twoPassCheckboxChanged: NULL];
4402                         /* Turbo 1st pass for 2 Pass Encoding */
4403                         [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
4404                         
4405                         /*Audio*/
4406                         
4407                         /* Audio Sample Rate*/
4408                         [fAudRatePopUp selectItemWithTitle: [NSString stringWithFormat:[chosenPreset valueForKey:@"AudioSampleRate"]]];
4409                         /* Audio Bitrate Rate*/
4410                         [fAudBitratePopUp selectItemWithTitle: [NSString stringWithFormat:[chosenPreset valueForKey:@"AudioBitRate"]]];
4411                         /*Subtitles*/
4412                         [fSubPopUp selectItemWithTitle: [NSString stringWithFormat:[chosenPreset valueForKey:@"Subtitles"]]];
4413                         
4414                         /* Picture Settings */
4415                         /* Look to see if we apply these here in objectForKey:@"UsesPictureSettings"] */
4416                         if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] > 0)
4417                         {
4418                                 hb_job_t * job = fTitle->job;
4419                                 /* Check to see if we should use the max picture setting for the current title*/
4420                                 if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"]  intValue] == 1)
4421                                 {
4422                                         /* Use Max Picture settings for whatever the dvd is.*/
4423                                         [self revertPictureSizeToMax: NULL];
4424                                         job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
4425                                         if (job->keep_ratio == 1)
4426                                         {
4427                                                 hb_fix_aspect( job, HB_KEEP_WIDTH );
4428                                                 if( job->height > fTitle->height )
4429                                                 {
4430                                                         job->height = fTitle->height;
4431                                                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
4432                                                 }
4433                                         }
4434                                         job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
4435                                 }
4436                                 else // Apply picture settings that were in effect at the time the preset was saved
4437                                 {
4438                                         job->width = [[chosenPreset objectForKey:@"PictureWidth"]  intValue];
4439                                         job->height = [[chosenPreset objectForKey:@"PictureHeight"]  intValue];
4440                                         job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
4441                                         if (job->keep_ratio == 1)
4442                                         {
4443                                                 hb_fix_aspect( job, HB_KEEP_WIDTH );
4444                                                 if( job->height > fTitle->height )
4445                                                 {
4446                                                         job->height = fTitle->height;
4447                                                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
4448                                                 }
4449                                         }
4450                                         job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
4451                     [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
4452                                         
4453                                         if ([chosenPreset objectForKey:@"PictureDetelecine"])
4454                                         {
4455                         [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
4456                                         }
4457                                         if ([chosenPreset objectForKey:@"PictureDenoise"])
4458                                         {
4459                         [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
4460                                         }
4461                                         /* If Cropping is set to custom, then recall all four crop values from
4462                                                 when the preset was created and apply them */
4463                                         if ([[chosenPreset objectForKey:@"PictureAutoCrop"]  intValue] == 0)
4464                                         {
4465                         [fPictureController setAutoCrop:NO];
4466                                                 
4467                                                 /* Here we use the custom crop values saved at the time the preset was saved */
4468                                                 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"]  intValue];
4469                                                 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"]  intValue];
4470                                                 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"]  intValue];
4471                                                 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"]  intValue];
4472                                                 
4473                                         }
4474                                         else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
4475                                         {
4476                         [fPictureController setAutoCrop:YES];
4477                         /* Here we use the auto crop values determined right after scan */
4478                                                 job->crop[0] = AutoCropTop;
4479                                                 job->crop[1] = AutoCropBottom;
4480                                                 job->crop[2] = AutoCropLeft;
4481                                                 job->crop[3] = AutoCropRight;
4482                                                 
4483                                         }
4484                                 }
4485                                 [self calculatePictureSizing: NULL]; 
4486                         }
4487                         
4488                         
4489                         [[fPresetsActionMenu itemAtIndex:0] setEnabled: YES];
4490                         }
4491 }
4492 }
4493
4494
4495
4496 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
4497 {
4498     return [UserPresets count];
4499 }
4500
4501 /* we use this to determine display characteristics for
4502 each table cell based on content currently only used to
4503 show the built in presets in a blue font. */
4504 - (void)tableView:(NSTableView *)aTableView
4505  willDisplayCell:(id)aCell 
4506  forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex
4507 {
4508     NSDictionary *userPresetDict = [UserPresets objectAtIndex:rowIndex];
4509         NSFont *txtFont;
4510         NSColor *fontColor;
4511         NSColor *shadowColor;
4512         txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
4513         /* First, we check to see if its a selected row, if so, we use white since its highlighted in blue */
4514         if ([[aTableView selectedRowIndexes] containsIndex:rowIndex] && ([tableView editedRow] != rowIndex))
4515         {
4516                 
4517                 fontColor = [NSColor whiteColor];
4518                 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
4519         }
4520         else
4521         {
4522                 /* We set the properties of unselected rows */
4523                 /* if built-in preset (defined by "type" == 0) we use a blue font */
4524                 if ([[userPresetDict objectForKey:@"Type"] intValue] == 0)
4525                 {
4526                         fontColor = [NSColor blueColor];
4527                 }
4528                 else // User created preset, use a black font
4529                 {
4530                         fontColor = [NSColor blackColor];
4531                 }
4532                 shadowColor = nil;
4533         }
4534         /* We check to see if this is the HB default, if so, color it appropriately */
4535         if (!presetUserDefault && presetHbDefault && rowIndex == presetHbDefault)
4536         {
4537         txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
4538         }
4539         /* We check to see if this is the User Specified default, if so, color it appropriately */
4540         if (presetUserDefault && rowIndex == presetUserDefault)
4541         {
4542         txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
4543         }
4544         
4545         [aCell setTextColor:fontColor];
4546         [aCell setFont:txtFont];
4547         /* this shadow stuff (like mail app) for some reason looks crappy, commented out
4548         temporarily in case we want to resurrect it */
4549         /*
4550         NSShadow *shadow = [[NSShadow alloc] init];
4551         NSSize shadowOffset = { width: 1.0, height: -1.5};
4552         [shadow setShadowOffset:shadowOffset];
4553         [shadow setShadowColor:shadowColor];
4554         [shadow set];
4555         */
4556         
4557 }
4558 /* Method to display tooltip with the description for each preset, if available */
4559 - (NSString *)tableView:(NSTableView *)aTableView toolTipForCell:(NSCell *)aCell 
4560                    rect:(NSRectPointer)aRect tableColumn:(NSTableColumn *)aTableColumn
4561                     row:(int)rowIndex mouseLocation:(NSPoint)aPos
4562 {
4563      /* initialize the tooltip contents variable */
4564          NSString *loc_tip;
4565      /* if there is a description for the preset, we show it in the tooltip */
4566          if ([[UserPresets objectAtIndex:rowIndex] valueForKey:@"PresetDescription"])
4567          {
4568         loc_tip = [NSString stringWithFormat: @"%@",[[UserPresets objectAtIndex:rowIndex] valueForKey:@"PresetDescription"]];
4569         return (loc_tip);
4570          }
4571          else
4572          {
4573         loc_tip = @"No description available";
4574          }
4575          return (loc_tip);
4576
4577 }
4578
4579 - (id)tableView:(NSTableView *)aTableView
4580       objectValueForTableColumn:(NSTableColumn *)aTableColumn
4581       row:(int)rowIndex
4582 {
4583 id theRecord, theValue;
4584     
4585     theRecord = [UserPresets objectAtIndex:rowIndex];
4586     theValue = [theRecord objectForKey:[aTableColumn identifier]];
4587     return theValue;
4588 }
4589
4590 // NSTableDataSource method that we implement to edit values directly in the table...
4591 - (void)tableView:(NSTableView *)aTableView
4592         setObjectValue:(id)anObject
4593         forTableColumn:(NSTableColumn *)aTableColumn
4594         row:(int)rowIndex
4595 {
4596     id theRecord;
4597     
4598     theRecord = [UserPresets objectAtIndex:rowIndex];
4599     [theRecord setObject:anObject forKey:@"PresetName"];
4600     /* We Sort the Presets By Factory or Custom */
4601         NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type" 
4602                                                     ascending:YES] autorelease];
4603                 /* We Sort the Presets Alphabetically by name */
4604         NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName" 
4605                                                     ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
4606         NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
4607     NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
4608         [UserPresets setArray:sortedArray];
4609         /* We Reload the New Table data for presets */
4610     [tableView reloadData];
4611    /* We save all of the preset data here */
4612     [self savePreset];
4613 }
4614
4615 - (void)savePreset
4616 {
4617     [UserPresets writeToFile:UserPresetsFile atomically:YES];
4618         /* We get the default preset in case it changed */
4619         [self getDefaultPresets: NULL];
4620
4621 }
4622
4623 - (void) controlTextDidChange: (NSNotification *) notification
4624 {
4625     [self calculateBitrate: NULL];
4626 }
4627
4628 - (IBAction) openHomepage: (id) sender
4629 {
4630     [[NSWorkspace sharedWorkspace] openURL: [NSURL
4631         URLWithString:@"http://handbrake.m0k.org/"]];
4632 }
4633
4634 - (IBAction) openForums: (id) sender
4635 {
4636     [[NSWorkspace sharedWorkspace] openURL: [NSURL
4637         URLWithString:@"http://handbrake.m0k.org/forum/"]];
4638 }
4639 - (IBAction) openUserGuide: (id) sender
4640 {
4641     [[NSWorkspace sharedWorkspace] openURL: [NSURL
4642         URLWithString:@"http://handbrake.m0k.org/trac/wiki/HandBrakeGuide"]];
4643 }
4644
4645 /**
4646  * Shows debug output window.
4647  */
4648 - (IBAction)showDebugOutputPanel:(id)sender
4649 {
4650     [outputPanel showOutputPanel:sender];
4651 }
4652
4653 /**
4654  * Shows preferences window modally.
4655  */
4656 - (IBAction) showPreferencesWindow: (id) sender
4657 {
4658     NSWindow * window = [fPreferencesController window];
4659     if (![window isVisible])
4660         [window center];
4661
4662     [window makeKeyAndOrderFront: nil];
4663 }
4664
4665 /**
4666  * Shows queue window.
4667  */
4668 - (IBAction) showQueueWindow:(id)sender
4669 {
4670     [fQueueController showQueueWindow:sender];
4671 }
4672
4673
4674 - (IBAction) toggleDrawer:(id)sender {
4675     [fPresetDrawer toggle:self];
4676 }
4677
4678 @end