OSDN Git Service

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