OSDN Git Service

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