OSDN Git Service

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