OSDN Git Service

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