OSDN Git Service

MacGui: uncomment line commented for testing for editing queue item modulus from...
[handbrake-jp/handbrake-jp-git.git] / macosx / Controller.m
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.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 #import "Controller.h"
8 #import "HBOutputPanelController.h"
9 #import "HBPreferencesController.h"
10 #import "HBDVDDetector.h"
11 #import "HBPresets.h"
12 #import "HBPreviewController.h"
13
14 #define DragDropSimplePboardType        @"MyCustomOutlineViewPboardType"
15
16 /* We setup the toolbar values here ShowPreviewIdentifier */
17 static NSString *        ToggleDrawerIdentifier             = @"Toggle Drawer Item Identifier";
18 static NSString *        StartEncodingIdentifier            = @"Start Encoding Item Identifier";
19 static NSString *        PauseEncodingIdentifier            = @"Pause Encoding Item Identifier";
20 static NSString *        ShowQueueIdentifier                = @"Show Queue Item Identifier";
21 static NSString *        AddToQueueIdentifier               = @"Add to Queue Item Identifier";
22 static NSString *        ShowPictureIdentifier             = @"Show Picture Window Item Identifier";
23 static NSString *        ShowPreviewIdentifier             = @"Show Preview Window Item Identifier";
24 static NSString *        ShowActivityIdentifier             = @"Debug Output Item Identifier";
25 static NSString *        ChooseSourceIdentifier             = @"Choose Source Item Identifier";
26
27
28 /*******************************
29  * HBController implementation *
30  *******************************/
31 @implementation HBController
32
33 - (id)init
34 {
35     self = [super init];
36     if( !self )
37     {
38         return nil;
39     }
40
41     /* replace bundled app icon with one which is 32/64-bit savvy */
42 #if defined( __LP64__ )
43     fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
44 #else
45     fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
46 #endif
47     if( fApplicationIcon != nil )
48         [NSApp setApplicationIconImage:fApplicationIcon];
49     
50     [HBPreferencesController registerUserDefaults];
51     fHandle = NULL;
52     fQueueEncodeLibhb = NULL;
53     /* Check for check for the app support directory here as
54      * outputPanel needs it right away, as may other future methods
55      */
56     NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
57                                                                 NSUserDomainMask,
58                                                                 YES ) objectAtIndex:0];
59     AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
60                            stringByAppendingPathComponent:@"HandBrake"];
61     if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
62     {
63         [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
64                                                    attributes:nil];
65     }
66     /* Check for and create the App Support Preview directory if necessary */
67     NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
68     if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
69     {
70         [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
71                                                    attributes:nil];
72     }                                                            
73     outputPanel = [[HBOutputPanelController alloc] init];
74     fPictureController = [[PictureController alloc] init];
75     fQueueController = [[HBQueueController alloc] init];
76     fAdvancedOptions = [[HBAdvancedController alloc] init];
77     /* we init the HBPresets class which currently is only used
78      * for updating built in presets, may move more functionality
79      * there in the future
80      */
81     fPresetsBuiltin = [[HBPresets alloc] init];
82     fPreferencesController = [[HBPreferencesController alloc] init];
83     /* Lets report the HandBrake version number here to the activity log and text log file */
84     NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
85     [self writeToActivityLog: "%s", [versionStringFull UTF8String]];    
86     
87     return self;
88 }
89
90
91 - (void) applicationDidFinishLaunching: (NSNotification *) notification
92 {
93     /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
94     int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
95     fHandle = hb_init(loggingLevel, 0);
96     /* Optional dvd nav UseDvdNav*/
97     hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
98     /* Init a separate instance of libhb for user scanning and setting up jobs */
99     fQueueEncodeLibhb = hb_init(loggingLevel, 0);
100     
101         // Set the Growl Delegate
102     [GrowlApplicationBridge setGrowlDelegate: self];
103     /* Init others controllers */
104     [fPictureController SetHandle: fHandle];
105     [fPictureController   setHBController: self];
106     
107     [fQueueController   setHandle: fQueueEncodeLibhb];
108     [fQueueController   setHBController: self];
109
110     fChapterTitlesDelegate = [[ChapterTitles alloc] init];
111     [fChapterTable setDataSource:fChapterTitlesDelegate];
112     [fChapterTable setDelegate:fChapterTitlesDelegate];
113     
114     /* setup the subtitles delegate and connections to table */
115     fSubtitlesDelegate = [[HBSubtitles alloc] init];
116     [fSubtitlesTable setDataSource:fSubtitlesDelegate];
117     [fSubtitlesTable setDelegate:fSubtitlesDelegate];
118     [fSubtitlesTable setRowHeight:25.0];
119     
120     [fPresetsOutlineView setAutosaveName:@"Presets View"];
121     [fPresetsOutlineView setAutosaveExpandedItems:YES];
122     
123     dockIconProgress = 0;
124
125     /* Call UpdateUI every 1/2 sec */
126     [[NSRunLoop currentRunLoop] addTimer:[NSTimer
127                                           scheduledTimerWithTimeInterval:0.5 target:self
128                                           selector:@selector(updateUI:) userInfo:nil repeats:YES]
129                                  forMode:NSDefaultRunLoopMode];
130
131     // Open debug output window now if it was visible when HB was closed
132     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
133         [self showDebugOutputPanel:nil];
134
135     // Open queue window now if it was visible when HB was closed
136     if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
137         [self showQueueWindow:nil];
138
139         [self openMainWindow:nil];
140     
141     /* We have to set the bool to tell hb what to do after a scan
142      * Initially we set it to NO until we start processing the queue
143      */
144      applyQueueToScan = NO;
145     
146     /* Now we re-check the queue array to see if there are
147      * any remaining encodes to be done in it and ask the
148      * user if they want to reload the queue */
149     if ([QueueFileArray count] > 0)
150         {
151         /* run  getQueueStats to see whats in the queue file */
152         [self getQueueStats];
153         /* this results in these values
154          * fEncodingQueueItem = 0;
155          * fPendingCount = 0;
156          * fCompletedCount = 0;
157          * fCanceledCount = 0;
158          * fWorkingCount = 0;
159          */
160         
161         /*On Screen Notification*/
162         NSString * alertTitle;
163         
164         /* We check to see if there is already another instance of hb running.
165          * Note: hbInstances == 1 means we are the only instance of HandBrake.app
166          */
167         if ([self hbInstances] > 1)
168         {
169         alertTitle = [NSString stringWithFormat:
170                          NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
171         NSBeginCriticalAlertSheet(
172                                       alertTitle,
173                                       NSLocalizedString(@"Reload Queue", nil),
174                                       nil,
175                                       nil,
176                                       fWindow, self,
177                                       nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
178                                       NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));    
179         }
180         else
181         {
182             if (fWorkingCount > 0)
183             {
184                 alertTitle = [NSString stringWithFormat:
185                               NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
186                               fWorkingCount,fPendingCount];
187             }
188             else
189             {
190                 alertTitle = [NSString stringWithFormat:
191                               NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
192                               fPendingCount];
193             }
194             
195             NSBeginCriticalAlertSheet(
196                                       alertTitle,
197                                       NSLocalizedString(@"Reload Queue", nil),
198                                       nil,
199                                       NSLocalizedString(@"Empty Queue", nil),
200                                       fWindow, self,
201                                       nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
202                                       NSLocalizedString(@" Do you want to reload them ?", nil));
203         }
204         
205     }
206     else
207     {
208         /* We show whichever open source window specified in LaunchSourceBehavior preference key */
209         if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
210         {
211             [self browseSources:nil];
212         }
213         
214         if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
215         {
216             [self browseSources:(id)fOpenSourceTitleMMenu];
217         }
218     }
219 }
220
221 - (int) hbInstances
222 {
223     /* check to see if another instance of HandBrake.app is running */
224     NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
225     NSDictionary *aDictionary;
226     int hbInstances = 0;
227     for (aDictionary in runningAppDictionaries)
228         {
229         if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
230                 {
231             hbInstances++;
232                 }
233         }
234     return hbInstances;
235 }
236
237 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
238 {
239     if (returnCode == NSAlertOtherReturn)
240     {
241         [self clearQueueAllItems];
242         /* We show whichever open source window specified in LaunchSourceBehavior preference key */
243         if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
244         {
245             [self browseSources:nil];
246         }
247         
248         if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
249         {
250             [self browseSources:(id)fOpenSourceTitleMMenu];
251         }
252     }
253     else
254     {
255         if ([self hbInstances] == 1)
256         {
257             [self setQueueEncodingItemsAsPending];
258         }
259         [self showQueueWindow:NULL];
260     }
261 }
262
263 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
264 {
265     /* if we are in preview full screen mode, we need to go to
266      * windowed mode and release the display before we terminate.
267      * We do it here (instead of applicationWillTerminate) so we 
268      * release the displays and can then see the alerts below.
269      */
270     if ([fPictureController previewFullScreenMode] == YES)
271     {
272         [fPictureController previewGoWindowed:nil];
273     }
274     
275     hb_state_t s;
276     hb_get_state( fQueueEncodeLibhb, &s );
277     
278     if ( s.state != HB_STATE_IDLE )
279     {
280         int result = NSRunCriticalAlertPanel(
281                                              NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
282                                              NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
283                                              NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
284         
285         if (result == NSAlertDefaultReturn)
286         {
287             return NSTerminateNow;
288         }
289         else
290             return NSTerminateCancel;
291     }
292     
293     // Warn if items still in the queue
294     else if ( fPendingCount > 0 )
295     {
296         int result = NSRunCriticalAlertPanel(
297                                              NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
298                                              NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
299                                              NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
300         
301         if ( result == NSAlertDefaultReturn )
302             return NSTerminateNow;
303         else
304             return NSTerminateCancel;
305     }
306     
307     return NSTerminateNow;
308 }
309
310 - (void)applicationWillTerminate:(NSNotification *)aNotification
311 {
312     
313     [browsedSourceDisplayName release];
314     [outputPanel release];
315         [fQueueController release];
316     [fPreviewController release];
317     [fPictureController release];
318     [fApplicationIcon release];
319
320         hb_close(&fHandle);
321     hb_close(&fQueueEncodeLibhb);
322 }
323
324
325 - (void) awakeFromNib
326 {
327     [fWindow center];
328     [fWindow setExcludedFromWindowsMenu:YES];
329     [fAdvancedOptions setView:fAdvancedView];
330     
331     /* lets setup our presets drawer for drag and drop here */
332     [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
333     [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
334     [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
335     
336     /* Initialize currentScanCount so HB can use it to
337      evaluate successive scans */
338         currentScanCount = 0;
339     
340     
341     /* Init UserPresets .plist */
342         [self loadPresets];
343     
344     /* Init QueueFile .plist */
345     [self loadQueueFile];
346         
347     fRipIndicatorShown = NO;  // initially out of view in the nib
348     
349     /* For 64 bit builds, the threaded animation in the progress
350      * indicators conflicts with the animation in the advanced tab
351      * for reasons not completely clear. jbrjake found a note in the
352      * 10.5 dev notes regarding this possiblility. It was also noted
353      * that unless specified, setUsesThreadedAnimation defaults to true.
354      * So, at least for now we set the indicator animation to NO for
355      * both the scan and regular progress indicators for both 32 and 64 bit
356      * as it test out fine on both and there is no reason our progress indicators
357      * should require their own thread.
358      */
359
360     [fScanIndicator setUsesThreadedAnimation:NO];
361     [fRipIndicator setUsesThreadedAnimation:NO];
362   
363     
364     
365         /* Show/Dont Show Presets drawer upon launch based
366      on user preference DefaultPresetsDrawerShow*/
367         if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
368         {
369         [fPresetDrawer setDelegate:self];
370         NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults] 
371                                                stringForKey:@"Drawer Size"] );
372         if( drawerSize.width )
373             [fPresetDrawer setContentSize: drawerSize];
374                 [fPresetDrawer open];
375         }
376     
377     /* Initially set the dvd angle widgets to hidden (dvdnav only) */
378     [fSrcAngleLabel setHidden:YES];
379     [fSrcAnglePopUp setHidden:YES];
380     
381     /* Setup the start / stop popup */
382     [fEncodeStartStopPopUp removeAllItems];
383     [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
384     [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
385     [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
386     /* Align the start / stop widgets with the chapter popups */
387     [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
388     [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
389     
390     [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
391     [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
392     
393     /* Destination box*/
394     NSMenuItem *menuItem;
395     [fDstFormatPopUp removeAllItems];
396     // MP4 file
397     menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
398     [menuItem setTag: HB_MUX_MP4];
399         // MKV file
400     menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
401     [menuItem setTag: HB_MUX_MKV];
402     
403     [fDstFormatPopUp selectItemAtIndex: 0];
404     
405     [self formatPopUpChanged:nil];
406     
407         /* We enable the create chapters checkbox here since we are .mp4 */
408         [fCreateChapterMarkers setEnabled: YES];
409         if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
410         {
411                 [fCreateChapterMarkers setState: NSOnState];
412         }
413     
414     
415     
416     
417     [fDstFile2Field setStringValue: [NSString stringWithFormat:
418                                      @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
419     
420     /* Video encoder */
421     [fVidEncoderPopUp removeAllItems];
422     [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
423     
424     
425     /* Video quality */
426     [fVidTargetSizeField setIntValue: 700];
427         [fVidBitrateField    setIntValue: 1000];
428     
429     [fVidQualityMatrix   selectCell: fVidBitrateCell];
430     [self videoMatrixChanged:nil];
431     
432     /* Video framerate */
433     [fVidRatePopUp removeAllItems];
434         [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
435     for( int i = 0; i < hb_video_rates_count; i++ )
436     {
437         if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
438                 {
439                         [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
440                                              [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
441                 }
442                 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
443                 {
444                         [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
445                                              [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
446                 }
447                 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
448                 {
449                         [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
450                                              [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
451                 }
452                 else
453                 {
454                         [fVidRatePopUp addItemWithTitle:
455              [NSString stringWithUTF8String: hb_video_rates[i].string]];
456                 }
457     }
458     [fVidRatePopUp selectItemAtIndex: 0];
459         
460         /* Set Auto Crop to On at launch */
461     [fPictureController setAutoCrop:YES];
462         
463         /* Audio bitrate */
464     [fAudTrack1BitratePopUp removeAllItems];
465     for( int i = 0; i < hb_audio_bitrates_count; i++ )
466     {
467         [fAudTrack1BitratePopUp addItemWithTitle:
468          [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
469         
470     }
471     [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
472         
473     /* Audio samplerate */
474     [fAudTrack1RatePopUp removeAllItems];
475     for( int i = 0; i < hb_audio_rates_count; i++ )
476     {
477         [fAudTrack1RatePopUp addItemWithTitle:
478          [NSString stringWithUTF8String: hb_audio_rates[i].string]];
479     }
480     [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
481         
482     /* Bottom */
483     [fStatusField setStringValue: @""];
484     
485     [self enableUI: NO];
486         [self setupToolbar];
487     
488         /* We disable the Turbo 1st pass checkbox since we are not x264 */
489         [fVidTurboPassCheck setEnabled: NO];
490         [fVidTurboPassCheck setState: NSOffState];
491     
492     
493         /* lets get our default prefs here */
494         [self getDefaultPresets:nil];
495         /* lets initialize the current successful scancount here to 0 */
496         currentSuccessfulScanCount = 0;
497     
498     
499 }
500
501 - (void) enableUI: (bool) b
502 {
503     NSControl * controls[] =
504     { fSrcTitleField, fSrcTitlePopUp,
505         fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
506         fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
507         fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
508         fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
509         fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
510         fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
511         fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
512         fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
513         fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
514         fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
515         fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
516         fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
517         fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
518         fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
519         fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
520                 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
521         fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
522         fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,fSrcFrameEndEncodingField};
523     
524     for( unsigned i = 0;
525         i < sizeof( controls ) / sizeof( NSControl * ); i++ )
526     {
527         if( [[controls[i] className] isEqualToString: @"NSTextField"] )
528         {
529             NSTextField * tf = (NSTextField *) controls[i];
530             if( ![tf isBezeled] )
531             {
532                 [tf setTextColor: b ? [NSColor controlTextColor] :
533                  [NSColor disabledControlTextColor]];
534                 continue;
535             }
536         }
537         [controls[i] setEnabled: b];
538         
539     }
540     
541         if (b) {
542         
543         /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
544         /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
545         [self setEnabledStateOfAudioMixdownControls:nil];
546         /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
547         [self calculatePictureSizing:nil];
548         
549         } else {
550         
551                 [fPresetsOutlineView setEnabled: NO];
552         
553         }
554     
555     [self videoMatrixChanged:nil];
556     [fAdvancedOptions enableUI:b];
557 }
558
559
560 /***********************************************************************
561  * UpdateDockIcon
562  ***********************************************************************
563  * Shows a progression bar on the dock icon, filled according to
564  * 'progress' (0.0 <= progress <= 1.0).
565  * Called with progress < 0.0 or progress > 1.0, restores the original
566  * icon.
567  **********************************************************************/
568 - (void) UpdateDockIcon: (float) progress
569 {
570     NSData * tiff;
571     NSBitmapImageRep * bmp;
572     uint32_t * pen;
573     uint32_t black = htonl( 0x000000FF );
574     uint32_t red   = htonl( 0xFF0000FF );
575     uint32_t white = htonl( 0xFFFFFFFF );
576     int row_start, row_end;
577     int i, j;
578
579     if( progress < 0.0 || progress > 1.0 )
580     {
581         [NSApp setApplicationIconImage: fApplicationIcon];
582         return;
583     }
584
585     /* Get it in a raw bitmap form */
586     tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
587             NSTIFFCompressionNone factor: 1.0];
588     bmp = [NSBitmapImageRep imageRepWithData: tiff];
589     
590     /* Draw the progression bar */
591     /* It's pretty simple (ugly?) now, but I'm no designer */
592
593     row_start = 3 * (int) [bmp size].height / 4;
594     row_end   = 7 * (int) [bmp size].height / 8;
595
596     for( i = row_start; i < row_start + 2; i++ )
597     {
598         pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
599         for( j = 0; j < (int) [bmp size].width; j++ )
600         {
601             pen[j] = black;
602         }
603     }
604     for( i = row_start + 2; i < row_end - 2; i++ )
605     {
606         pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
607         pen[0] = black;
608         pen[1] = black;
609         for( j = 2; j < (int) [bmp size].width - 2; j++ )
610         {
611             if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
612             {
613                 pen[j] = red;
614             }
615             else
616             {
617                 pen[j] = white;
618             }
619         }
620         pen[j]   = black;
621         pen[j+1] = black;
622     }
623     for( i = row_end - 2; i < row_end; i++ )
624     {
625         pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
626         for( j = 0; j < (int) [bmp size].width; j++ )
627         {
628             pen[j] = black;
629         }
630     }
631
632     /* Now update the dock icon */
633     tiff = [bmp TIFFRepresentationUsingCompression:
634             NSTIFFCompressionNone factor: 1.0];
635     NSImage* icon = [[NSImage alloc] initWithData: tiff];
636     [NSApp setApplicationIconImage: icon];
637     [icon release];
638 }
639
640 - (void) updateUI: (NSTimer *) timer
641 {
642     
643     /* Update UI for fHandle (user scanning instance of libhb ) */
644     
645     hb_list_t  * list;
646     list = hb_get_titles( fHandle );
647     /* check to see if there has been a new scan done
648      this bypasses the constraints of HB_STATE_WORKING
649      not allowing setting a newly scanned source */
650         int checkScanCount = hb_get_scancount( fHandle );
651         if( checkScanCount > currentScanCount )
652         {
653                 currentScanCount = checkScanCount;
654         [fScanIndicator setIndeterminate: NO];
655         [fScanIndicator setDoubleValue: 0.0];
656         [fScanIndicator setHidden: YES];
657                 [self showNewScan:nil];
658         }
659     
660     hb_state_t s;
661     hb_get_state( fHandle, &s );
662     
663     switch( s.state )
664     {
665         case HB_STATE_IDLE:
666             break;
667 #define p s.param.scanning
668         case HB_STATE_SCANNING:
669                 {
670             [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
671                                             NSLocalizedString( @"Scanning title %d of %d...", @"" ),
672                                             p.title_cur, p.title_count]];
673             [fScanIndicator setHidden: NO];
674             [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
675             break;
676                 }
677 #undef p
678             
679 #define p s.param.scandone
680         case HB_STATE_SCANDONE:
681         {
682             [fScanIndicator setIndeterminate: NO];
683             [fScanIndicator setDoubleValue: 0.0];
684             [fScanIndicator setHidden: YES];
685                         [self writeToActivityLog:"ScanDone state received from fHandle"];
686             [self showNewScan:nil];
687             [[fWindow toolbar] validateVisibleItems];
688             
689                         break;
690         }
691 #undef p
692             
693 #define p s.param.working
694         case HB_STATE_WORKING:
695         {
696             
697             break;
698         }
699 #undef p
700             
701 #define p s.param.muxing
702         case HB_STATE_MUXING:
703         {
704             
705             break;
706         }
707 #undef p
708             
709         case HB_STATE_PAUSED:
710             break;
711             
712         case HB_STATE_WORKDONE:
713         {
714             break;
715         }
716     }
717     
718     
719     /* Update UI for fQueueEncodeLibhb */
720     // hb_list_t  * list;
721     // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
722     /* check to see if there has been a new scan done
723      this bypasses the constraints of HB_STATE_WORKING
724      not allowing setting a newly scanned source */
725         
726     checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
727         if( checkScanCount > currentScanCount )
728         {
729                 currentScanCount = checkScanCount;
730         }
731     
732     //hb_state_t s;
733     hb_get_state( fQueueEncodeLibhb, &s );
734     
735     switch( s.state )
736     {
737         case HB_STATE_IDLE:
738             break;
739 #define p s.param.scanning
740         case HB_STATE_SCANNING:
741                 {
742             [fStatusField setStringValue: [NSString stringWithFormat:
743                                            NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
744                                            p.title_cur, p.title_count]];
745             
746             /* Set the status string in fQueueController as well */                               
747             [fQueueController setQueueStatusString: [NSString stringWithFormat:
748                                                      NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
749                                                      p.title_cur, p.title_count]];
750             break;
751                 }
752 #undef p
753             
754 #define p s.param.scandone
755         case HB_STATE_SCANDONE:
756         {
757                         [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
758             [self processNewQueueEncode];
759             [[fWindow toolbar] validateVisibleItems];
760             
761                         break;
762         }
763 #undef p
764
765             
766 #define p s.param.working
767         
768         case HB_STATE_SEARCHING:
769                 {
770             NSMutableString * string;
771             NSString * pass_desc;
772             
773             /* Update text field */
774             pass_desc = @"";
775             //string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
776             /* For now, do not announce "pass x of x for the search phase ... */
777             string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... :  %.2f %%", @"" ), 100.0 * p.progress];
778             
779                         if( p.seconds > -1 )
780             {
781                 [string appendFormat:
782                  NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
783             }
784             
785             [fStatusField setStringValue: string];
786             /* Set the status string in fQueueController as well */
787             [fQueueController setQueueStatusString: string];
788             /* Update slider */
789             CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
790             [fRipIndicator setIndeterminate: NO];
791             [fRipIndicator setDoubleValue:100.0 * progress_total];
792             
793             // If progress bar hasn't been revealed at the bottom of the window, do
794             // that now. This code used to be in doRip. I moved it to here to handle
795             // the case where hb_start is called by HBQueueController and not from
796             // HBController.
797             if( !fRipIndicatorShown )
798             {
799                 NSRect frame = [fWindow frame];
800                 if( frame.size.width <= 591 )
801                     frame.size.width = 591;
802                 frame.size.height += 36;
803                 frame.origin.y -= 36;
804                 [fWindow setFrame:frame display:YES animate:YES];
805                 fRipIndicatorShown = YES;
806                 
807             }
808             
809             /* Update dock icon */
810             /* Note not done yet */
811             break;  
812         }
813             
814
815         case HB_STATE_WORKING:
816         {
817             NSMutableString * string;
818             NSString * pass_desc;
819                         /* Update text field */
820             if (p.job_cur == 1 && p.job_count > 1)
821             {
822                 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
823                 {
824                     pass_desc = @"(subtitle scan)";   
825                 }
826                 else
827                 {
828                     pass_desc = @"";
829                 }
830             }
831             else
832             {
833                 pass_desc = @"";
834             }
835             
836                         string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
837             
838                         if( p.seconds > -1 )
839             {
840                 [string appendFormat:
841                  NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
842                  p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
843             }
844             
845             [fStatusField setStringValue: string];
846             /* Set the status string in fQueueController as well */
847             [fQueueController setQueueStatusString: string];
848             /* Update slider */
849             CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
850             [fRipIndicator setIndeterminate: NO];
851             [fRipIndicator setDoubleValue:100.0 * progress_total];
852             
853             // If progress bar hasn't been revealed at the bottom of the window, do
854             // that now. This code used to be in doRip. I moved it to here to handle
855             // the case where hb_start is called by HBQueueController and not from
856             // HBController.
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 = YES;
866                 
867             }
868
869             /* Update dock icon */
870             if( dockIconProgress < 100.0 * progress_total )
871             {
872                 [self UpdateDockIcon: progress_total];
873                 dockIconProgress += 5;
874             }
875
876             break;
877         }
878 #undef p
879             
880 #define p s.param.muxing
881         case HB_STATE_MUXING:
882         {
883             /* Update text field */
884             [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
885             /* Set the status string in fQueueController as well */
886             [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
887             /* Update slider */
888             [fRipIndicator setIndeterminate: YES];
889             [fRipIndicator startAnimation: nil];
890             
891             /* Update dock icon */
892             [self UpdateDockIcon: 1.0];
893             
894                         break;
895         }
896 #undef p
897             
898         case HB_STATE_PAUSED:
899                     [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
900             [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
901             
902                         break;
903             
904         case HB_STATE_WORKDONE:
905         {
906             // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
907             // or someone calling hb_stop. In the latter case, hb_stop does not clear
908             // out the remaining passes/jobs in the queue. We'll do that here.
909             
910             // Delete all remaining jobs of this encode.
911             [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
912             /* Set the status string in fQueueController as well */
913             [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
914             [fRipIndicator setIndeterminate: NO];
915             [fRipIndicator stopAnimation: nil];
916             [fRipIndicator setDoubleValue: 0.0];
917             [[fWindow toolbar] validateVisibleItems];
918             
919             /* Restore dock icon */
920             [self UpdateDockIcon: -1.0];
921             dockIconProgress = 0;
922             
923             if( fRipIndicatorShown )
924             {
925                 NSRect frame = [fWindow frame];
926                 if( frame.size.width <= 591 )
927                                     frame.size.width = 591;
928                 frame.size.height += -36;
929                 frame.origin.y -= -36;
930                 [fWindow setFrame:frame display:YES animate:YES];
931                                 fRipIndicatorShown = NO;
932                         }
933             /* Since we are done with this encode, tell output to stop writing to the
934              * individual encode log
935              */
936                         [outputPanel endEncodeLog];
937             /* Check to see if the encode state has not been cancelled
938              to determine if we should check for encode done notifications */
939                         if( fEncodeState != 2 )
940             {
941                 NSString *pathOfFinishedEncode;
942                 /* Get the output file name for the finished encode */
943                 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
944                 
945                 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
946                 /* Growl alert */
947                 [self showGrowlDoneNotification:pathOfFinishedEncode];
948                 /* Send to MetaX */
949                 [self sendToMetaX:pathOfFinishedEncode];
950                 
951                 /* since we have successfully completed an encode, we increment the queue counter */
952                 [self incrementQueueItemDone:nil]; 
953                 
954                 /* all end of queue actions below need to be done after all queue encodes have finished 
955                  * and there are no pending jobs left to process
956                  */
957                 if (fPendingCount == 0)
958                 {
959                     /* If Alert Window or Window and Growl has been selected */
960                     if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
961                        [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
962                     {
963                         /*On Screen Notification*/
964                         int status;
965                         NSBeep();
966                         status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
967                         [NSApp requestUserAttention:NSCriticalRequest];
968                     }
969                     
970                     /* If sleep has been selected */
971                     if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
972                     {
973                         /* Sleep */
974                         NSDictionary* errorDict;
975                         NSAppleEventDescriptor* returnDescriptor = nil;
976                         NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
977                                                        @"tell application \"Finder\" to sleep"];
978                         returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
979                         [scriptObject release];
980                     }
981                     /* If Shutdown has been selected */
982                     if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
983                     {
984                         /* Shut Down */
985                         NSDictionary* errorDict;
986                         NSAppleEventDescriptor* returnDescriptor = nil;
987                         NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
988                                                        @"tell application \"Finder\" to shut down"];
989                         returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
990                         [scriptObject release];
991                     }
992                     
993                 }
994                 
995                 
996             }
997             
998             break;
999         }
1000     }
1001     
1002 }
1003
1004 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1005 - (void) writeToActivityLog:(const char *) format, ...
1006 {
1007     va_list args;
1008     va_start(args, format);
1009     if (format != nil)
1010     {
1011         char str[1024];
1012         vsnprintf( str, 1024, format, args );
1013
1014         time_t _now = time( NULL );
1015         struct tm * now  = localtime( &_now );
1016         fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1017     }
1018     va_end(args);
1019 }
1020
1021 #pragma mark -
1022 #pragma mark Toolbar
1023 // ============================================================
1024 // NSToolbar Related Methods
1025 // ============================================================
1026
1027 - (void) setupToolbar {
1028     NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1029
1030     [toolbar setAllowsUserCustomization: YES];
1031     [toolbar setAutosavesConfiguration: YES];
1032     [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1033
1034     [toolbar setDelegate: self];
1035
1036     [fWindow setToolbar: toolbar];
1037 }
1038
1039 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1040     (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1041     NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1042
1043     if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1044     {
1045         [item setLabel: @"Toggle Presets"];
1046         [item setPaletteLabel: @"Toggler Presets"];
1047         [item setToolTip: @"Open/Close Preset Drawer"];
1048         [item setImage: [NSImage imageNamed: @"Drawer"]];
1049         [item setTarget: self];
1050         [item setAction: @selector(toggleDrawer:)];
1051         [item setAutovalidates: NO];
1052     }
1053     else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1054     {
1055         [item setLabel: @"Start"];
1056         [item setPaletteLabel: @"Start Encoding"];
1057         [item setToolTip: @"Start Encoding"];
1058         [item setImage: [NSImage imageNamed: @"Play"]];
1059         [item setTarget: self];
1060         [item setAction: @selector(Rip:)];
1061     }
1062     else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1063     {
1064         [item setLabel: @"Show Queue"];
1065         [item setPaletteLabel: @"Show Queue"];
1066         [item setToolTip: @"Show Queue"];
1067         [item setImage: [NSImage imageNamed: @"Queue"]];
1068         [item setTarget: self];
1069         [item setAction: @selector(showQueueWindow:)];
1070         [item setAutovalidates: NO];
1071     }
1072     else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1073     {
1074         [item setLabel: @"Add to Queue"];
1075         [item setPaletteLabel: @"Add to Queue"];
1076         [item setToolTip: @"Add to Queue"];
1077         [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1078         [item setTarget: self];
1079         [item setAction: @selector(addToQueue:)];
1080     }
1081     else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1082     {
1083         [item setLabel: @"Pause"];
1084         [item setPaletteLabel: @"Pause Encoding"];
1085         [item setToolTip: @"Pause Encoding"];
1086         [item setImage: [NSImage imageNamed: @"Pause"]];
1087         [item setTarget: self];
1088         [item setAction: @selector(Pause:)];
1089     }
1090     else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1091     {
1092         [item setLabel: @"Picture Settings"];
1093         [item setPaletteLabel: @"Show Picture Settings"];
1094         [item setToolTip: @"Show Picture Settings"];
1095         [item setImage: [NSImage imageNamed: @"pref-picture"]];
1096         [item setTarget: self];
1097         [item setAction: @selector(showPicturePanel:)];
1098     }
1099     else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1100     {
1101         [item setLabel: @"Preview Window"];
1102         [item setPaletteLabel: @"Show Preview"];
1103         [item setToolTip: @"Show Preview"];
1104         //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1105         [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1106         [item setTarget: self];
1107         [item setAction: @selector(showPreviewWindow:)];
1108     }
1109     else if ([itemIdent isEqualToString: ShowActivityIdentifier]) 
1110     {
1111         [item setLabel: @"Activity Window"];
1112         [item setPaletteLabel: @"Show Activity Window"];
1113         [item setToolTip: @"Show Activity Window"];
1114         [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1115         [item setTarget: self];
1116         [item setAction: @selector(showDebugOutputPanel:)];
1117         [item setAutovalidates: NO];
1118     }
1119     else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1120     {
1121         [item setLabel: @"Source"];
1122         [item setPaletteLabel: @"Source"];
1123         [item setToolTip: @"Choose Video Source"];
1124         [item setImage: [NSImage imageNamed: @"Source"]];
1125         [item setTarget: self];
1126         [item setAction: @selector(browseSources:)];
1127     }
1128     else
1129     {
1130         return nil;
1131     }
1132
1133     return item;
1134 }
1135
1136 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1137 {
1138     return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1139         PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier, 
1140                 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1141 }
1142
1143 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1144 {
1145     return [NSArray arrayWithObjects:  StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1146         ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1147         NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1148         NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1149 }
1150
1151 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1152 {
1153     NSString * ident = [toolbarItem itemIdentifier];
1154         
1155     if (fHandle)
1156     {
1157         hb_state_t s;
1158         
1159         hb_get_state( fHandle, &s );
1160         if (s.state == HB_STATE_SCANNING)
1161         {
1162             
1163             if ([ident isEqualToString: ChooseSourceIdentifier])
1164             {
1165                 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1166                 [toolbarItem setLabel: @"Cancel Scan"];
1167                 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1168                 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1169                 return YES;
1170             }
1171             
1172             if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1173                 return NO;
1174         }
1175         else
1176         {
1177             if ([ident isEqualToString: ChooseSourceIdentifier])
1178             {
1179                 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1180                 [toolbarItem setLabel: @"Source"];
1181                 [toolbarItem setPaletteLabel: @"Source"];
1182                 [toolbarItem setToolTip: @"Choose Video Source"];
1183                 return YES;
1184             }
1185         }
1186
1187         hb_get_state2( fQueueEncodeLibhb, &s );
1188         
1189         if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1190         {
1191             if ([ident isEqualToString: StartEncodingIdentifier])
1192             {
1193                 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1194                 [toolbarItem setLabel: @"Stop"];
1195                 [toolbarItem setPaletteLabel: @"Stop"];
1196                 [toolbarItem setToolTip: @"Stop Encoding"];
1197                 return YES;
1198             }
1199             if ([ident isEqualToString: PauseEncodingIdentifier])
1200             {
1201                 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1202                 [toolbarItem setLabel: @"Pause"];
1203                 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1204                 [toolbarItem setToolTip: @"Pause Encoding"];
1205                 return YES;
1206             }
1207             if (SuccessfulScan)
1208             {
1209                 if ([ident isEqualToString: AddToQueueIdentifier])
1210                     return YES;
1211                 if ([ident isEqualToString: ShowPictureIdentifier])
1212                     return YES;
1213                 if ([ident isEqualToString: ShowPreviewIdentifier])
1214                     return YES;
1215             }
1216         }
1217         else if (s.state == HB_STATE_PAUSED)
1218         {
1219             if ([ident isEqualToString: PauseEncodingIdentifier])
1220             {
1221                 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1222                 [toolbarItem setLabel: @"Resume"];
1223                 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1224                 [toolbarItem setToolTip: @"Resume Encoding"];
1225                 return YES;
1226             }
1227             if ([ident isEqualToString: StartEncodingIdentifier])
1228                 return YES;
1229             if ([ident isEqualToString: AddToQueueIdentifier])
1230                 return YES;
1231             if ([ident isEqualToString: ShowPictureIdentifier])
1232                 return YES;
1233             if ([ident isEqualToString: ShowPreviewIdentifier])
1234                 return YES;
1235         }
1236         else if (s.state == HB_STATE_SCANNING)
1237             return NO;
1238         else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1239         {
1240             if ([ident isEqualToString: StartEncodingIdentifier])
1241             {
1242                 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1243                 if (hb_count(fHandle) > 0)
1244                     [toolbarItem setLabel: @"Start Queue"];
1245                 else
1246                     [toolbarItem setLabel: @"Start"];
1247                 [toolbarItem setPaletteLabel: @"Start Encoding"];
1248                 [toolbarItem setToolTip: @"Start Encoding"];
1249                 return YES;
1250             }
1251             if ([ident isEqualToString: AddToQueueIdentifier])
1252                 return YES;
1253             if ([ident isEqualToString: ShowPictureIdentifier])
1254                 return YES;
1255             if ([ident isEqualToString: ShowPreviewIdentifier])
1256                 return YES;
1257         }
1258
1259     }
1260     /* If there are any pending queue items, make sure the start/stop button is active */
1261     if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1262         return YES;
1263     if ([ident isEqualToString: ShowQueueIdentifier])
1264         return YES;
1265     if ([ident isEqualToString: ToggleDrawerIdentifier])
1266         return YES;
1267     if ([ident isEqualToString: ChooseSourceIdentifier])
1268         return YES;
1269     if ([ident isEqualToString: ShowActivityIdentifier])
1270         return YES;
1271     
1272     return NO;
1273 }
1274
1275 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1276 {
1277     SEL action = [menuItem action];
1278     
1279     hb_state_t s;
1280     hb_get_state2( fHandle, &s );
1281     
1282     if (fHandle)
1283     {
1284         if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1285             return SuccessfulScan && [fWindow attachedSheet] == nil;
1286         
1287         if (action == @selector(browseSources:))
1288         {
1289             if (s.state == HB_STATE_SCANNING)
1290                 return NO;
1291             else
1292                 return [fWindow attachedSheet] == nil;
1293         }
1294         if (action == @selector(selectDefaultPreset:))
1295             return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1296         if (action == @selector(Pause:))
1297         {
1298             if (s.state == HB_STATE_WORKING)
1299             {
1300                 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1301                     [menuItem setTitle:@"Pause Encoding"];
1302                 return YES;
1303             }
1304             else if (s.state == HB_STATE_PAUSED)
1305             {
1306                 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1307                     [menuItem setTitle:@"Resume Encoding"];
1308                 return YES;
1309             }
1310             else
1311                 return NO;
1312         }
1313         if (action == @selector(Rip:))
1314         {
1315             if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1316             {
1317                 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1318                     [menuItem setTitle:@"Stop Encoding"];
1319                 return YES;
1320             }
1321             else if (SuccessfulScan)
1322             {
1323                 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1324                     [menuItem setTitle:@"Start Encoding"];
1325                 return [fWindow attachedSheet] == nil;
1326             }
1327             else
1328                 return NO;
1329         }
1330     }
1331     if( action == @selector(setDefaultPreset:) )
1332     {
1333         return [fPresetsOutlineView selectedRow] != -1;
1334     }
1335
1336     return YES;
1337 }
1338
1339 #pragma mark -
1340 #pragma mark Encode Done Actions
1341 // register a test notification and make
1342 // it enabled by default
1343 #define SERVICE_NAME @"Encode Done"
1344 - (NSDictionary *)registrationDictionaryForGrowl 
1345
1346     NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys: 
1347     [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL, 
1348     [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT, 
1349     nil]; 
1350
1351     return registrationDictionary; 
1352
1353
1354 -(void)showGrowlDoneNotification:(NSString *) filePath
1355 {
1356     /* This end of encode action is called as each encode rolls off of the queue */
1357     NSString * finishedEncode = filePath;
1358     /* strip off the path to just show the file name */
1359     finishedEncode = [finishedEncode lastPathComponent];
1360     if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] || 
1361         [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1362     {
1363         NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1364         [GrowlApplicationBridge 
1365          notifyWithTitle:@"Put down that cocktail..." 
1366          description:growlMssg 
1367          notificationName:SERVICE_NAME
1368          iconData:nil 
1369          priority:0 
1370          isSticky:1 
1371          clickContext:nil];
1372     }
1373     
1374 }
1375 -(void)sendToMetaX:(NSString *) filePath
1376 {
1377     /* This end of encode action is called as each encode rolls off of the queue */
1378     if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1379     {
1380         NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1381         if (![sendToApp isEqualToString:@"None"])
1382         {
1383             [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1384             NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1385             [myScript executeAndReturnError: nil];
1386             [myScript release];
1387         }
1388         
1389     }
1390 }
1391 #pragma mark -
1392 #pragma mark Get New Source
1393
1394 /*Opens the source browse window, called from Open Source widgets */
1395 - (IBAction) browseSources: (id) sender
1396 {
1397     
1398     hb_state_t s;
1399     hb_get_state( fHandle, &s );
1400     if (s.state == HB_STATE_SCANNING)
1401     {
1402         [self cancelScanning:nil];
1403         return;
1404     }
1405     
1406     
1407     NSOpenPanel * panel;
1408         
1409     panel = [NSOpenPanel openPanel];
1410     [panel setAllowsMultipleSelection: NO];
1411     [panel setCanChooseFiles: YES];
1412     [panel setCanChooseDirectories: YES ];
1413     NSString * sourceDirectory;
1414         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1415         {
1416                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1417         }
1418         else
1419         {
1420                 sourceDirectory = @"~/Desktop";
1421                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1422         }
1423     /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1424         * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1425         */
1426     [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1427                    modalForWindow: fWindow modalDelegate: self
1428                    didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1429                       contextInfo: sender]; 
1430 }
1431
1432 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1433                 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1434 {
1435     /* we convert the sender content of contextInfo back into a variable called sender
1436      * mostly just for consistency for evaluation later
1437      */
1438     id sender = (id)contextInfo;
1439     /* User selected a file to open */
1440         if( returnCode == NSOKButton )
1441     {
1442             /* Free display name allocated previously by this code */
1443         [browsedSourceDisplayName release];
1444        
1445         NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1446         /* we set the last searched source directory in the prefs here */
1447         NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1448         [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1449         /* we order out sheet, which is the browse window as we need to open
1450          * the title selection sheet right away
1451          */
1452         [sheet orderOut: self];
1453         
1454         if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1455         {
1456             /* We put the chosen source path in the source display text field for the
1457              * source title selection sheet in which the user specifies the specific title to be
1458              * scanned  as well as the short source name in fSrcDsplyNameTitleScan just for display
1459              * purposes in the title panel
1460              */
1461             /* Full Path */
1462             [fScanSrcTitlePathField setStringValue:scanPath];
1463             NSString *displayTitlescanSourceName;
1464
1465             if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1466             {
1467                 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1468                  we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1469                 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1470             }
1471             else
1472             {
1473                 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1474                 displayTitlescanSourceName = [scanPath lastPathComponent];
1475             }
1476             /* we set the source display name in the title selection dialogue */
1477             [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1478             /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1479             browsedSourceDisplayName = [displayTitlescanSourceName retain];
1480             /* We show the actual sheet where the user specifies the title to be scanned
1481              * as we are going to do a title specific scan
1482              */
1483             [self showSourceTitleScanPanel:nil];
1484         }
1485         else
1486         {
1487             /* We are just doing a standard full source scan, so we specify "0" to libhb */
1488             NSString *path = [[sheet filenames] objectAtIndex: 0];
1489             
1490             /* We check to see if the chosen file at path is a package */
1491             if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1492             {
1493                 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1494                 /* We check to see if this is an .eyetv package */
1495                 if ([[path pathExtension] isEqualToString: @"eyetv"])
1496                 {
1497                     [self writeToActivityLog:"trying to open eyetv package"];
1498                     /* We're looking at an EyeTV package - try to open its enclosed
1499                      .mpg media file */
1500                      browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1501                     NSString *mpgname;
1502                     int n = [[path stringByAppendingString: @"/"]
1503                              completePathIntoString: &mpgname caseSensitive: YES
1504                              matchesIntoArray: nil
1505                              filterTypes: [NSArray arrayWithObject: @"mpg"]];
1506                     if (n > 0)
1507                     {
1508                         /* Found an mpeg inside the eyetv package, make it our scan path 
1509                         and call performScan on the enclosed mpeg */
1510                         path = mpgname;
1511                         [self writeToActivityLog:"found mpeg in eyetv package"];
1512                         [self performScan:path scanTitleNum:0];
1513                     }
1514                     else
1515                     {
1516                         /* We did not find an mpeg file in our package, so we do not call performScan */
1517                         [self writeToActivityLog:"no valid mpeg in eyetv package"];
1518                     }
1519                 }
1520                 /* We check to see if this is a .dvdmedia package */
1521                 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1522                 {
1523                     /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1524                     browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1525                     [self writeToActivityLog:"trying to open dvdmedia package"];
1526                     [self performScan:path scanTitleNum:0];
1527                 }
1528                 else
1529                 {
1530                     /* The package is not an eyetv package, so we do not call performScan */
1531                     [self writeToActivityLog:"unable to open package"];
1532                 }
1533             }
1534             else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1535             {
1536                 /* path is not a package, so we call perform scan directly on our file */
1537                 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1538                 {
1539                     [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1540                     /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1541                     browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1542                 }
1543                 else
1544                 {
1545                     [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1546                     /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1547                     /* make sure we remove any path extension as this can also be an '.mpg' file */
1548                     browsedSourceDisplayName = [[path lastPathComponent] retain];
1549                 }
1550                 applyQueueToScan = NO;
1551                 [self performScan:path scanTitleNum:0];
1552             }
1553
1554         }
1555
1556     }
1557 }
1558
1559 - (IBAction)showAboutPanel:(id)sender
1560 {
1561     NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1562         fApplicationIcon, @"ApplicationIcon",
1563         nil ];
1564     [NSApp orderFrontStandardAboutPanelWithOptions:d];
1565     [d release];
1566 }
1567
1568 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1569 - (IBAction) showSourceTitleScanPanel: (id) sender
1570 {
1571     /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1572     * user changes it
1573     */
1574     [fScanSrcTitleNumField setStringValue: @"0"];
1575         /* Show the panel */
1576         [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1577 }
1578
1579 - (IBAction) closeSourceTitleScanPanel: (id) sender
1580 {
1581     [NSApp endSheet: fScanSrcTitlePanel];
1582     [fScanSrcTitlePanel orderOut: self];
1583     
1584     if(sender == fScanSrcTitleOpenButton)
1585     {
1586         /* We setup the scan status in the main window to indicate a source title scan */
1587         [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1588                 [fScanIndicator setHidden: NO];
1589         [fScanIndicator setIndeterminate: YES];
1590         [fScanIndicator startAnimation: nil];
1591                 
1592         /* We use the performScan method to actually perform the specified scan passing the path and the title
1593          * to be scanned
1594          */
1595         applyQueueToScan = NO;
1596         [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1597     }
1598 }
1599
1600 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1601 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1602 {
1603     
1604     /* use a bool to determine whether or not we can decrypt using vlc */
1605     BOOL cancelScanDecrypt = 0;
1606     BOOL vlcFound = 0;
1607     NSString *path = scanPath;
1608     HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1609     
1610     // Notify ChapterTitles that there's no title
1611     [fChapterTitlesDelegate resetWithTitle:nil];
1612     [fChapterTable reloadData];
1613     
1614     // Notify Subtitles that there's no title
1615     [fSubtitlesDelegate resetWithTitle:nil];
1616     [fSubtitlesTable reloadData];
1617     
1618     [self enableUI: NO];
1619     
1620     if( [detector isVideoDVD] )
1621     {
1622         int hb_arch;
1623 #if defined( __LP64__ )
1624         /* we are 64 bit */
1625         hb_arch = 64;
1626 #else
1627         /* we are 32 bit */
1628         hb_arch = 32;
1629 #endif 
1630         
1631         
1632         // The chosen path was actually on a DVD, so use the raw block
1633         // device path instead.
1634         path = [detector devicePath];
1635         [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1636         
1637         /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1638         NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1639         NSFileManager * fileManager = [NSFileManager defaultManager];
1640             if ([fileManager fileExistsAtPath:vlcPath] == 0) 
1641             {
1642             /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1643             cancelScanDecrypt = 1;
1644             [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1645             int status;
1646             status = NSRunAlertPanel(@"HandBrake could not find VLC or your VLC is out of date.",@"Please download and install VLC media player in your /Applications folder if you wish to read encrypted DVDs.", @"Get VLC", @"Cancel Scan", @"Attempt Scan Anyway");
1647             [NSApp requestUserAttention:NSCriticalRequest];
1648             
1649             if (status == NSAlertDefaultReturn)
1650             {
1651                 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1652                 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1653             }
1654             else if (status == NSAlertAlternateReturn)
1655             {
1656                 /* User chose to cancel the scan */
1657                 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1658             }
1659             else
1660             {
1661                 /* User chose to override our warning and scan the physical dvd anyway, at their own peril. on an encrypted dvd this produces massive log files and fails */
1662                 cancelScanDecrypt = 0;
1663                 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1664             }
1665             
1666         }
1667         else
1668         {
1669             /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1670             [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1671             vlcFound = 1;
1672         }
1673         /* test for architecture of the vlc app */
1674         NSArray *vlc_architecturesArray = [[NSBundle bundleWithPath:@"/Applications/VLC.app"] executableArchitectures];
1675         BOOL vlcIntel32bit = NO;
1676         BOOL vlcIntel64bit = NO;
1677         BOOL vlcPPC32bit = NO;
1678         BOOL vlcPPC64bit = NO;
1679         /* check the available architectures for vlc and note accordingly */
1680         NSEnumerator *enumerator = [vlc_architecturesArray objectEnumerator];
1681         id tempObject;
1682         while (tempObject = [enumerator nextObject])
1683         {
1684             
1685             if ([tempObject intValue] == NSBundleExecutableArchitectureI386)
1686             {
1687                 vlcIntel32bit = YES;   
1688             }
1689             if ([tempObject intValue] == NSBundleExecutableArchitectureX86_64)
1690             {
1691                 vlcIntel64bit = YES;   
1692             }
1693             if ([tempObject intValue] == NSBundleExecutableArchitecturePPC)
1694             {
1695                 vlcPPC32bit = YES;   
1696             }
1697             if ([tempObject intValue] == NSBundleExecutableArchitecturePPC64)
1698             {
1699                 vlcPPC64bit = YES;   
1700             }
1701             
1702         }
1703         /* Write vlc architecture findings to activity window */
1704         if (vlcIntel32bit)
1705         {
1706             [self writeToActivityLog: " 32-Bit VLC app found for decrypting physical dvd"];
1707         }
1708         if (vlcIntel64bit)
1709         {
1710             [self writeToActivityLog: " 64-Bit VLC app found for decrypting physical dvd"];
1711         }
1712         
1713         
1714         
1715         if (vlcFound && hb_arch == 64 && !vlcIntel64bit && cancelScanDecrypt != 1)
1716         {
1717             
1718             /* we are 64 bit */
1719             
1720             /* Appropriate VLC not found, so cancel */
1721             cancelScanDecrypt = 1;
1722             [self writeToActivityLog: "This version of HandBrake is 64 bit, 64 bit version of vlc not found, scan cancelled"];
1723             /*On Screen Notification*/
1724             int status;
1725             NSBeep();
1726             status = NSRunAlertPanel(@"This version of HandBrake is 64 bit, VLC found but not 64 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 64 bit VLC", nil);
1727             [NSApp requestUserAttention:NSCriticalRequest];
1728             
1729             if (status == NSAlertDefaultReturn)
1730             {
1731                 /* User chose to cancel the scan */
1732                 [self writeToActivityLog: "cannot open physical dvd VLC found but not 64 bit, scan cancelled"];
1733                 cancelScanDecrypt = 1;
1734             }
1735             else if (status == NSAlertAlternateReturn)
1736             {
1737                 [self writeToActivityLog: "user overrode 64-bit warning trying to open physical dvd without proper decryption"];
1738                 cancelScanDecrypt = 0;
1739             }
1740             else
1741             {
1742                 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1743                 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1744             }
1745             
1746         }    
1747         else if (vlcFound && hb_arch == 32 && !vlcIntel32bit && cancelScanDecrypt != 1)
1748         {
1749             /* we are 32 bit */
1750             /* Appropriate VLC not found, so cancel */
1751             cancelScanDecrypt = 1;
1752             [self writeToActivityLog: "This version of HandBrake is 32 bit, 32 bit version of vlc not found, scan cancelled"];
1753             /*On Screen Notification*/
1754             int status;
1755             NSBeep();
1756             status = NSRunAlertPanel(@"This version of HandBrake is 32 bit, VLC found but not 32 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 32 bit VLC", nil);
1757             [NSApp requestUserAttention:NSCriticalRequest];
1758             
1759             if (status == NSAlertDefaultReturn)
1760             {
1761                 /* User chose to cancel the scan */
1762                 [self writeToActivityLog: "cannot open physical dvd VLC found but not 32 bit, scan cancelled"];
1763                 cancelScanDecrypt = 1;
1764             }
1765             else if (status == NSAlertAlternateReturn)
1766             {
1767                 [self writeToActivityLog: "user overrode 32-bit warning trying to open physical dvd without proper decryption"];
1768                 cancelScanDecrypt = 0;
1769             }
1770             else
1771             {
1772                 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1773                 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1774             }
1775             
1776         } 
1777     }
1778     
1779     if (cancelScanDecrypt == 0)
1780     {
1781         /* we actually pass the scan off to libhb here */
1782         /* If there is no title number passed to scan, we use "0"
1783          * which causes the default behavior of a full source scan
1784          */
1785         if (!scanTitleNum)
1786         {
1787             scanTitleNum = 0;
1788         }
1789         if (scanTitleNum > 0)
1790         {
1791             [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1792         }
1793         /* We use our advance pref to determine how many previews to scan */
1794         int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1795         /* set title to NULL */
1796         fTitle = NULL;
1797         hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1798         [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1799     }
1800 }
1801
1802 - (IBAction) cancelScanning:(id)sender
1803 {
1804     hb_scan_stop(fHandle);
1805 }
1806
1807 - (IBAction) showNewScan:(id)sender
1808 {
1809     hb_list_t  * list;
1810         hb_title_t * title;
1811         int indxpri=0;    // Used to search the longuest title (default in combobox)
1812         int longuestpri=0; // Used to search the longuest title (default in combobox)
1813     
1814
1815         list = hb_get_titles( fHandle );
1816         
1817         if( !hb_list_count( list ) )
1818         {
1819             /* We display a message if a valid dvd source was not chosen */
1820             [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1821             SuccessfulScan = NO;
1822             
1823             // Notify ChapterTitles that there's no title
1824             [fSubtitlesDelegate resetWithTitle:nil];
1825             [fSubtitlesTable reloadData];
1826             
1827             // Notify Subtitles that there's no title
1828             [fChapterTitlesDelegate resetWithTitle:nil];
1829             [fChapterTable reloadData];
1830         }
1831         else
1832         {
1833             if (applyQueueToScan == YES)
1834             {
1835                 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1836                 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1837                 
1838             }
1839             else if (applyQueueToScan == NO)
1840             {
1841                 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1842             }
1843             else
1844             {
1845                 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1846             }
1847             
1848               /* We increment the successful scancount here by one,
1849              which we use at the end of this function to tell the gui
1850              if this is the first successful scan since launch and whether
1851              or not we should set all settings to the defaults */
1852             currentSuccessfulScanCount++;
1853             
1854             [[fWindow toolbar] validateVisibleItems];
1855             
1856             [fSrcTitlePopUp removeAllItems];
1857             for( int i = 0; i < hb_list_count( list ); i++ )
1858             {
1859                 title = (hb_title_t *) hb_list_item( list, i );
1860                 
1861                 currentSource = [NSString stringWithUTF8String: title->name];
1862                 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1863                 if (!browsedSourceDisplayName)
1864                 {
1865                     browsedSourceDisplayName = @"NoNameDetected";
1866                 }
1867                 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1868                 
1869                 /* If its a queue rescan for edit, get the queue item output path */
1870                 /* if not, its a new source scan. */
1871                 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1872                 if (applyQueueToScan == YES)
1873                 {
1874                     [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1875                 }
1876                 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1877                 {
1878                     [fDstFile2Field setStringValue: [NSString stringWithFormat:
1879                                                      @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1880                 }
1881                 else
1882                 {
1883                     [fDstFile2Field setStringValue: [NSString stringWithFormat:
1884                                                      @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1885                 }
1886                 
1887                 
1888                 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1889                 {
1890                     longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1891                     indxpri=i;
1892                 }
1893                 
1894                 [fSrcTitlePopUp addItemWithTitle: [NSString
1895                                                    stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1896                                                    title->name,title->index, title->hours, title->minutes,
1897                                                    title->seconds]];
1898             }
1899             
1900             /* if we are a stream, select the first title */
1901             if (title->type == HB_STREAM_TYPE)
1902             {
1903                 [fSrcTitlePopUp selectItemAtIndex: 0];
1904             }
1905             else
1906             {
1907                 /* if not then select the longest title (dvd) */
1908                 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1909             }
1910             [self titlePopUpChanged:nil];
1911             
1912             SuccessfulScan = YES;
1913             [self enableUI: YES];
1914
1915             /* if its the initial successful scan after awakeFromNib */
1916             if (currentSuccessfulScanCount == 1)
1917             {
1918                 [self encodeStartStopPopUpChanged:nil];
1919                 
1920                 [self selectDefaultPreset:nil];
1921                 
1922                 // Open preview window now if it was visible when HB was closed
1923                 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1924                     [self showPreviewWindow:nil];
1925                 
1926                 // Open picture sizing window now if it was visible when HB was closed
1927                 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1928                     [self showPicturePanel:nil];
1929                 
1930             }
1931             if (applyQueueToScan == YES)
1932             {
1933                 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1934                 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1935                 [self applyQueueSettingsToMainWindow:nil];
1936                 
1937             }
1938
1939             
1940         }
1941
1942 }
1943
1944
1945 #pragma mark -
1946 #pragma mark New Output Destination
1947
1948 - (IBAction) browseFile: (id) sender
1949 {
1950     /* Open a panel to let the user choose and update the text field */
1951     NSSavePanel * panel = [NSSavePanel savePanel];
1952         /* We get the current file name and path from the destination field here */
1953         [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1954                                    modalForWindow: fWindow modalDelegate: self
1955                                    didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1956                                           contextInfo: NULL];
1957 }
1958
1959 - (void) browseFileDone: (NSSavePanel *) sheet
1960              returnCode: (int) returnCode contextInfo: (void *) contextInfo
1961 {
1962     if( returnCode == NSOKButton )
1963     {
1964         [fDstFile2Field setStringValue: [sheet filename]];
1965         /* Save this path to the prefs so that on next browse destination window it opens there */
1966         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1967         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];   
1968     }
1969 }
1970
1971
1972 #pragma mark -
1973 #pragma mark Main Window Control
1974
1975 - (IBAction) openMainWindow: (id) sender
1976 {
1977     [fWindow  makeKeyAndOrderFront:nil];
1978 }
1979
1980 - (BOOL) windowShouldClose: (id) sender
1981 {
1982     return YES;
1983 }
1984
1985 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1986 {
1987     if( !flag ) {
1988         [fWindow  makeKeyAndOrderFront:nil];
1989                 
1990         return YES;
1991     }
1992     
1993     return NO;
1994 }
1995
1996 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1997         [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1998         return contentSize;
1999 }
2000
2001 #pragma mark -
2002 #pragma mark Queue File
2003
2004 - (void) loadQueueFile {
2005         /* We declare the default NSFileManager into fileManager */
2006         NSFileManager * fileManager = [NSFileManager defaultManager];
2007         /*We define the location of the user presets file */
2008     QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
2009         QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
2010     /* We check for the presets.plist */
2011         if ([fileManager fileExistsAtPath:QueueFile] == 0)
2012         {
2013                 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
2014         }
2015
2016         QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
2017         /* lets check to see if there is anything in the queue file .plist */
2018     if (nil == QueueFileArray)
2019         {
2020         /* if not, then lets initialize an empty array */
2021                 QueueFileArray = [[NSMutableArray alloc] init];
2022         
2023      /* Initialize our curQueueEncodeIndex to 0
2024      * so we can use it to track which queue
2025      * item is to be used to track our encodes */
2026      /* NOTE: this should be changed if and when we
2027       * are able to get the last unfinished encode
2028       * in the case of a crash or shutdown */
2029     
2030         }
2031     else
2032     {
2033     [self clearQueueEncodedItems];
2034     }
2035     currentQueueEncodeIndex = 0;
2036 }
2037
2038 - (void)addQueueFileItem
2039 {
2040         [QueueFileArray addObject:[self createQueueFileItem]];
2041         [self saveQueueFileItem];
2042
2043 }
2044
2045 - (void) removeQueueFileItem:(int) queueItemToRemove
2046 {
2047    
2048    /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
2049    if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
2050     {
2051     /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
2052      * by one to keep in sync with the queue array
2053      */
2054     currentQueueEncodeIndex--;
2055     [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
2056     }
2057     [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2058     [self saveQueueFileItem];
2059
2060 }
2061
2062 - (void)saveQueueFileItem
2063 {
2064     [QueueFileArray writeToFile:QueueFile atomically:YES];
2065     [fQueueController setQueueArray: QueueFileArray];
2066     [self getQueueStats];
2067 }
2068
2069 - (void)getQueueStats
2070 {
2071 /* lets get the stats on the status of the queue array */
2072
2073 fEncodingQueueItem = 0;
2074 fPendingCount = 0;
2075 fCompletedCount = 0;
2076 fCanceledCount = 0;
2077 fWorkingCount = 0;
2078
2079     /* We use a number system to set the encode status of the queue item
2080      * in controller.mm
2081      * 0 == already encoded
2082      * 1 == is being encoded
2083      * 2 == is yet to be encoded
2084      * 3 == cancelled
2085      */
2086
2087         int i = 0;
2088     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2089         id tempObject;
2090         while (tempObject = [enumerator nextObject])
2091         {
2092                 NSDictionary *thisQueueDict = tempObject;
2093                 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2094                 {
2095                         fCompletedCount++;      
2096                 }
2097                 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2098                 {
2099                         fWorkingCount++;
2100             fEncodingQueueItem = i;     
2101                 }
2102         if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending          
2103         {
2104                         fPendingCount++;
2105                 }
2106         if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled                
2107         {
2108                         fCanceledCount++;
2109                 }
2110                 i++;
2111         }
2112
2113     /* Set the queue status field in the main window */
2114     NSMutableString * string;
2115     if (fPendingCount == 1)
2116     {
2117         string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2118     }
2119     else
2120     {
2121         string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2122     }
2123     [fQueueStatus setStringValue:string];
2124 }
2125
2126 /* This method will set any item marked as encoding back to pending
2127  * currently used right after a queue reload
2128  */
2129 - (void) setQueueEncodingItemsAsPending
2130 {
2131     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2132         id tempObject;
2133     NSMutableArray *tempArray;
2134     tempArray = [NSMutableArray array];
2135     /* we look here to see if the preset is we move on to the next one */
2136     while ( tempObject = [enumerator nextObject] )  
2137     {
2138         /* If the queue item is marked as "encoding" (1)
2139          * then change its status back to pending (2) which effectively
2140          * puts it back into the queue to be encoded
2141          */
2142         if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2143         {
2144             [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2145         }
2146         [tempArray addObject:tempObject];
2147     }
2148     
2149     [QueueFileArray setArray:tempArray];
2150     [self saveQueueFileItem];
2151 }
2152
2153
2154 /* This method will clear the queue of any encodes that are not still pending
2155  * this includes both successfully completed encodes as well as cancelled encodes */
2156 - (void) clearQueueEncodedItems
2157 {
2158     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2159         id tempObject;
2160     NSMutableArray *tempArray;
2161     tempArray = [NSMutableArray array];
2162     /* we look here to see if the preset is we move on to the next one */
2163     while ( tempObject = [enumerator nextObject] )  
2164     {
2165         /* If the queue item is either completed (0) or cancelled (3) from the
2166          * last session, then we put it in tempArray to be deleted from QueueFileArray.
2167          * NOTE: this means we retain pending (2) and also an item that is marked as
2168          * still encoding (1). If the queue has an item that is still marked as encoding
2169          * from a previous session, we can conlude that HB was either shutdown, or crashed
2170          * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2171          */
2172         if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2173         {
2174             [tempArray addObject:tempObject];
2175         }
2176     }
2177     
2178     [QueueFileArray removeObjectsInArray:tempArray];
2179     [self saveQueueFileItem];
2180 }
2181
2182 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2183 - (void) clearQueueAllItems
2184 {
2185     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2186         id tempObject;
2187     NSMutableArray *tempArray;
2188     tempArray = [NSMutableArray array];
2189     /* we look here to see if the preset is we move on to the next one */
2190     while ( tempObject = [enumerator nextObject] )  
2191     {
2192         [tempArray addObject:tempObject];
2193     }
2194     
2195     [QueueFileArray removeObjectsInArray:tempArray];
2196     [self saveQueueFileItem];
2197 }
2198
2199 /* This method will duplicate prepareJob however into the
2200  * queue .plist instead of into the job structure so it can
2201  * be recalled later */
2202 - (NSDictionary *)createQueueFileItem
2203 {
2204     NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2205     
2206        hb_list_t  * list  = hb_get_titles( fHandle );
2207     hb_title_t * title = (hb_title_t *) hb_list_item( list,
2208             [fSrcTitlePopUp indexOfSelectedItem] );
2209     hb_job_t * job = title->job;
2210     
2211     
2212     
2213     /* We use a number system to set the encode status of the queue item
2214      * 0 == already encoded
2215      * 1 == is being encoded
2216      * 2 == is yet to be encoded
2217      * 3 == cancelled
2218      */
2219     [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2220     /* Source and Destination Information */
2221     
2222     [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2223     [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2224     [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2225     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2226     
2227     /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2228     if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2229     {
2230         [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];    
2231     }
2232     else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2233     {
2234         [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];   
2235     }
2236     else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2237     {
2238         [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2239     }
2240     /* Chapter encode info */
2241     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2242     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2243     /* Time (pts) encode info */
2244     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2245     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2246     /* Frame number encode info */
2247     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2248     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2249     
2250     
2251     /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2252         int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2253     [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2254     
2255     [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2256     
2257     /* Lets get the preset info if there is any */
2258     [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2259     [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2260     
2261     [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2262     /* Chapter Markers*/
2263     /* If we have only one chapter or a title without chapters, set chapter markers to off */
2264     if ([fSrcChapterStartPopUp indexOfSelectedItem] ==  [fSrcChapterEndPopUp indexOfSelectedItem])
2265     {
2266         [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2267     }
2268     else
2269     {
2270         [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2271     }
2272         
2273     /* We need to get the list of chapter names to put into an array and store 
2274      * in our queue, so they can be reapplied in prepareJob when this queue
2275      * item comes up if Chapter Markers is set to on.
2276      */
2277      int i;
2278      NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2279      int chaptercount = hb_list_count( fTitle->list_chapter );
2280      for( i = 0; i < chaptercount; i++ )
2281     {
2282         hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2283         if( chapter != NULL )
2284         {
2285           [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2286         }
2287     }
2288     [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2289     [ChapterNamesArray autorelease];
2290     
2291     /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2292         [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2293     /* Mux mp4 with http optimization */
2294     [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2295     /* Add iPod uuid atom */
2296     [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2297     
2298     /* Codecs */
2299         /* Video encoder */
2300         [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2301         /* x264 Option String */
2302         [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2303
2304         [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2305         [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2306         [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2307         [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2308     /* Framerate */
2309     [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2310     
2311         /* 2 Pass Encoding */
2312         [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2313         /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2314         [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2315     
2316         /* Picture Sizing */
2317         /* Use Max Picture settings for whatever the dvd is.*/
2318         [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2319         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2320         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2321         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2322         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2323     [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2324     /* if we are custom anamorphic, store the exact storage, par and display dims */
2325     if (fTitle->job->anamorphic.mode == 3)
2326     {
2327         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2328         
2329         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2330         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2331         
2332         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2333         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2334         
2335         [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2336         [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2337
2338     }
2339     NSString * pictureSummary;
2340     pictureSummary = [fPictureSizeField stringValue];
2341     [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];                 
2342     /* Set crop settings here */
2343         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2344     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2345     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2346         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2347         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2348     
2349     /* Picture Filters */
2350     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2351     [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2352     
2353     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2354     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2355     [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2356     
2357     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2358     [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2359     
2360     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2361     [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2362     
2363     [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2364     
2365     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2366     
2367     /*Audio*/
2368     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2369     {
2370         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2371         [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2372         [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2373         [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2374         [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2375         [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2376         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2377     }
2378     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2379     {
2380         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2381         [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2382         [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2383         [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2384         [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2385         [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2386         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2387     }
2388     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2389     {
2390         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2391         [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2392         [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2393         [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2394         [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2395         [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2396         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2397     }
2398     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2399     {
2400         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2401         [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2402         [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2403         [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2404         [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2405         [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2406         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2407     }
2408     
2409         /* Subtitles*/
2410     NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2411     [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2412     [subtitlesArray autorelease];
2413
2414     /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2415      
2416     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2417     
2418     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2419     
2420     
2421     [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2422     
2423     /* Codecs */
2424         /* Video encoder */
2425         [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2426         
2427     /* Framerate */
2428     [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2429     [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2430     [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2431         
2432     /* Picture Sizing */
2433         /* Use Max Picture settings for whatever the dvd is.*/
2434         [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2435         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2436         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2437         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2438         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2439     
2440     /* Set crop settings here */
2441         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2442     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2443     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2444         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2445         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2446     
2447     
2448     /*Audio*/
2449     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2450     {
2451         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2452         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2453         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2454         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2455         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2456      }
2457     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2458     {
2459         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2460         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2461         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2462         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2463         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2464     }
2465     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2466     {
2467         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2468         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2469         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2470         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2471         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2472     }
2473     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2474     {
2475         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2476         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2477         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2478         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2479         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2480     }
2481
2482  
2483     /* we need to auto relase the queueFileJob and return it */
2484     [queueFileJob autorelease];
2485     return queueFileJob;
2486
2487 }
2488
2489 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2490 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2491 {
2492     NSUInteger index = [indexSet lastIndex];
2493     NSUInteger aboveInsertIndexCount = 0;
2494     
2495     
2496     NSUInteger removeIndex;
2497         
2498     if (index >= insertIndex)
2499     {
2500         removeIndex = index + aboveInsertIndexCount;
2501         aboveInsertIndexCount++;
2502     }
2503     else
2504     {
2505         removeIndex = index;
2506         insertIndex--;
2507     }
2508
2509     id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2510     [QueueFileArray removeObjectAtIndex:removeIndex];
2511     [QueueFileArray insertObject:object atIndex:insertIndex];
2512     [object release];
2513         
2514     index = [indexSet indexLessThanIndex:index];
2515
2516    /* We save all of the Queue data here 
2517     * and it also gets sent back to the queue controller*/
2518     [self saveQueueFileItem]; 
2519     
2520 }
2521
2522
2523 #pragma mark -
2524 #pragma mark Queue Job Processing
2525
2526 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2527 {
2528     int i = currentQueueEncodeIndex;
2529     [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2530         
2531     /* We save all of the Queue data here */
2532     [self saveQueueFileItem];
2533         /* We Reload the New Table data for presets */
2534     //[fPresetsOutlineView reloadData];
2535
2536     /* Since we have now marked a queue item as done
2537      * we can go ahead and increment currentQueueEncodeIndex 
2538      * so that if there is anything left in the queue we can
2539      * go ahead and move to the next item if we want to */
2540     currentQueueEncodeIndex++ ;
2541     [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2542     int queueItems = [QueueFileArray count];
2543     /* If we still have more items in our queue, lets go to the next one */
2544     if (currentQueueEncodeIndex < queueItems)
2545     {
2546     [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2547     [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2548     }
2549     else
2550     {
2551         [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2552     }
2553 }
2554
2555 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2556 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2557 {
2558    /* Tell HB to output a new activity log file for this encode */
2559     [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2560     
2561     
2562      /* use a bool to determine whether or not we can decrypt using vlc */
2563     BOOL cancelScanDecrypt = 0;
2564     /* set the bool so that showNewScan knows to apply the appropriate queue
2565     * settings as this is a queue rescan
2566     */
2567     //applyQueueToScan = YES;
2568     NSString *path = scanPath;
2569     HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2570     
2571     if( [detector isVideoDVD] )
2572     {
2573         // The chosen path was actually on a DVD, so use the raw block
2574         // device path instead.
2575         path = [detector devicePath];
2576         [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2577
2578         /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2579         NSString *vlcPath = @"/Applications/VLC.app";
2580         NSFileManager * fileManager = [NSFileManager defaultManager];
2581             if ([fileManager fileExistsAtPath:vlcPath] == 0) 
2582             {
2583             /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2584             cancelScanDecrypt = 1;
2585             [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2586             int status;
2587             status = NSRunAlertPanel(@"HandBrake could not find VLC.",@"Please download and install VLC media player in your /Applications folder if you wish to read encrypted DVDs.", @"Get VLC", @"Cancel Scan", @"Attempt Scan Anyway");
2588             [NSApp requestUserAttention:NSCriticalRequest];
2589             
2590             if (status == NSAlertDefaultReturn)
2591             {
2592                 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2593                 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2594             }
2595             else if (status == NSAlertAlternateReturn)
2596             {
2597             /* User chose to cancel the scan */
2598             [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2599             }
2600             else
2601             {
2602             /* User chose to override our warning and scan the physical dvd anyway, at their own peril. on an encrypted dvd this produces massive log files and fails */
2603             cancelScanDecrypt = 0;
2604             [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2605             }
2606
2607         }
2608         else
2609         {
2610             /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2611             [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2612         }
2613     }
2614
2615     if (cancelScanDecrypt == 0)
2616     {
2617         /* we actually pass the scan off to libhb here */
2618         /* If there is no title number passed to scan, we use "0"
2619          * which causes the default behavior of a full source scan
2620          */
2621         if (!scanTitleNum)
2622         {
2623             scanTitleNum = 0;
2624         }
2625         if (scanTitleNum > 0)
2626         {
2627             [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2628         }
2629         
2630         [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2631         /* We use our advance pref to determine how many previews to scan */
2632         int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2633         hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2634     }
2635 }
2636
2637 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2638 - (void) processNewQueueEncode
2639 {
2640     hb_list_t  * list  = hb_get_titles( fQueueEncodeLibhb );
2641     hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2642     hb_job_t * job = title->job;
2643     
2644     if( !hb_list_count( list ) )
2645     {
2646         [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2647     }
2648     
2649     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2650     [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2651     [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2652     job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2653     //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2654     [self prepareJob];
2655     
2656     /*
2657      * If scanning we need to do some extra setup of the job.
2658      */
2659     if( job->indepth_scan == 1 )
2660     {
2661         char *x264opts_tmp;
2662         
2663         /*
2664          * When subtitle scan is enabled do a fast pre-scan job
2665          * which will determine which subtitles to enable, if any.
2666          */
2667         job->pass = -1;
2668         x264opts_tmp = job->x264opts;
2669         
2670         job->x264opts = NULL;
2671         
2672         job->indepth_scan = 1;  
2673
2674         
2675         /*
2676          * Add the pre-scan job
2677          */
2678         hb_add( fQueueEncodeLibhb, job );
2679         job->x264opts = x264opts_tmp;
2680     }
2681
2682     
2683     if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2684     {
2685         job->indepth_scan = 0;
2686         
2687
2688         
2689         job->pass = 1;
2690         
2691         hb_add( fQueueEncodeLibhb, job );
2692         
2693         job->pass = 2;
2694         
2695         job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */  
2696         strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2697         
2698         hb_add( fQueueEncodeLibhb, job );
2699         
2700     }
2701     else
2702     {
2703         job->indepth_scan = 0;
2704         job->pass = 0;
2705         
2706         hb_add( fQueueEncodeLibhb, job );
2707     }
2708         
2709     NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2710         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2711         /* Lets mark our new encode as 1 or "Encoding" */
2712     [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2713     [self saveQueueFileItem];
2714     
2715     /* we need to clean up the subtitle tracks after the job(s) have been set  */
2716     int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2717     int ii;
2718     for(ii = 0; ii < num_subtitle_tracks; ii++)
2719     {
2720         hb_subtitle_t * subtitle;
2721         subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2722         
2723
2724         hb_list_rem(job->list_subtitle, subtitle);
2725         free(subtitle);
2726     }
2727     
2728     
2729     /* We should be all setup so let 'er rip */   
2730     [self doRip];
2731 }
2732
2733
2734
2735 #pragma mark -
2736 #pragma mark Queue Item Editing
2737
2738 /* Rescans the chosen queue item back into the main window */
2739 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2740 {
2741     fqueueEditRescanItemNum = selectedQueueItem;
2742     [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2743     applyQueueToScan = YES;
2744     /* Set the browsedSourceDisplayName for showNewScan */
2745     browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2746     [self performScan:scanPath scanTitleNum:scanTitleNum];
2747 }
2748
2749
2750 /* We use this method after a queue item rescan for edit.
2751  * it largely mirrors -selectPreset in terms of structure.
2752  * Assumes that a queue item has been reloaded into the main window.
2753  */
2754 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2755 {
2756     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2757     hb_job_t * job = fTitle->job;
2758     if (queueToApply)
2759     {
2760         [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2761     }
2762     /* Set title number and chapters */
2763     /* since the queue only scans a single title, we really don't need to pick a title */
2764     [fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2765     
2766     [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2767     [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2768     
2769     /* File Format */
2770     [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2771     [self formatPopUpChanged:nil];
2772     
2773     /* Chapter Markers*/
2774     [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2775     /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2776     [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2777     /* Mux mp4 with http optimization */
2778     [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2779     
2780     /* Video encoder */
2781     /* We set the advanced opt string here if applicable*/
2782     [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2783     [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2784     
2785     /* Lets run through the following functions to get variables set there */
2786     [self videoEncoderPopUpChanged:nil];
2787     /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2788     [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2789     [self calculateBitrate:nil];
2790     
2791     /* Video quality */
2792     [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2793     
2794     [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2795     [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2796     /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2797      * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2798      * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2799      * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2800      * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2801     if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2802     {
2803         /* For the quality slider we need to convert the old percent's to the new rf scales */
2804         float rf =  (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2805         [fVidQualitySlider setFloatValue:rf];
2806         
2807     }
2808     else
2809     {
2810         /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2811         if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2812         {
2813             [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2814         }
2815         else
2816         {
2817             /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2818             [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2819         }
2820     }
2821     
2822     [self videoMatrixChanged:nil];
2823     [self writeToActivityLog: "applyQueueSettingsToMainWindow: video matrix changed"];    
2824     /* Video framerate */
2825     /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2826      detected framerate in the fVidRatePopUp so we use index 0*/
2827     if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2828     {
2829         [fVidRatePopUp selectItemAtIndex: 0];
2830     }
2831     else
2832     {
2833         [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2834     }
2835     
2836     /* 2 Pass Encoding */
2837     [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2838     [self twoPassCheckboxChanged:nil];
2839     /* Turbo 1st pass for 2 Pass Encoding */
2840     [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2841     
2842     /*Audio*/
2843     
2844     
2845     /* Now lets add our new tracks to the audio list here */
2846     if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2847     {
2848         [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2849         [self audioTrackPopUpChanged: fAudLang1PopUp];
2850         [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2851         [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2852         
2853         [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2854         
2855         [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2856         [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2857         
2858         [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2859         [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2860     }
2861     else
2862     {
2863         [fAudLang1PopUp selectItemAtIndex: 0];
2864         [self audioTrackPopUpChanged: fAudLang1PopUp];
2865     }
2866     if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2867     {
2868         [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2869         [self audioTrackPopUpChanged: fAudLang2PopUp];
2870         [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2871         [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2872         
2873         [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2874         
2875         [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2876         [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2877         
2878         [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2879         [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2880     }
2881     else
2882     {
2883         [fAudLang2PopUp selectItemAtIndex: 0];
2884         [self audioTrackPopUpChanged: fAudLang2PopUp];
2885     }
2886     if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2887     {
2888         [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2889         [self audioTrackPopUpChanged: fAudLang3PopUp];
2890         [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2891         [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2892         
2893         [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2894         
2895         [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2896         [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2897         
2898         [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2899         [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2900     }
2901     else
2902     {
2903         [fAudLang3PopUp selectItemAtIndex: 0];
2904         [self audioTrackPopUpChanged: fAudLang3PopUp];
2905     }
2906     if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2907     {
2908         [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2909         [self audioTrackPopUpChanged: fAudLang4PopUp];
2910         [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2911         [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2912         
2913         [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2914         
2915         [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2916         [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2917         
2918         [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2919         [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2920     }
2921     else
2922     {
2923         [fAudLang4PopUp selectItemAtIndex: 0];
2924         [self audioTrackPopUpChanged: fAudLang4PopUp];
2925     }
2926     
2927     [self writeToActivityLog: "applyQueueSettingsToMainWindow: audio set up"];
2928     /*Subtitles*/
2929     /* Crashy crashy right now, working on it */
2930     [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2931     [fSubtitlesTable reloadData];  
2932     /* Picture Settings */
2933     
2934     /* If Cropping is set to custom, then recall all four crop values from
2935      when the preset was created and apply them */
2936     if ([[queueToApply objectForKey:@"PictureAutoCrop"]  intValue] == 0)
2937     {
2938         [fPictureController setAutoCrop:NO];
2939         
2940         /* Here we use the custom crop values saved at the time the preset was saved */
2941         job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
2942         job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
2943         job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
2944         job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
2945         
2946     }
2947     else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2948     {
2949         [fPictureController setAutoCrop:YES];
2950         /* Here we use the auto crop values determined right after scan */
2951         job->crop[0] = AutoCropTop;
2952         job->crop[1] = AutoCropBottom;
2953         job->crop[2] = AutoCropLeft;
2954         job->crop[3] = AutoCropRight;
2955         
2956     }
2957     
2958     job->modulus = [[queueToApply objectForKey:@"PictureModulus"]  intValue];
2959     
2960     /* we check to make sure the presets width/height does not exceed the sources width/height */
2961     if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"]  intValue])
2962     {
2963         /* if so, then we use the sources height and width to avoid scaling up */
2964         //job->width = fTitle->width;
2965         //job->height = fTitle->height;
2966         [self revertPictureSizeToMax:nil];
2967     }
2968     else // source width/height is >= the preset height/width
2969     {
2970         /* we can go ahead and use the presets values for height and width */
2971         job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
2972         job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
2973     }
2974     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
2975     if (job->keep_ratio == 1)
2976     {
2977         hb_fix_aspect( job, HB_KEEP_WIDTH );
2978         if( job->height > fTitle->height )
2979         {
2980             job->height = fTitle->height;
2981             hb_fix_aspect( job, HB_KEEP_HEIGHT );
2982         }
2983     }
2984     job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
2985     job->modulus = [[queueToApply objectForKey:@"PictureModulus"]  intValue];
2986     
2987     [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture sizing set up"];
2988     
2989     
2990     /* Filters */
2991     
2992     /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2993      * also, older presets may not have this key, in which case we also check to see if that preset had  PictureDecomb
2994      * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2995      * sane.
2996      */
2997     [fPictureController setUseDecomb:1];
2998     [fPictureController setDecomb:0];
2999     [fPictureController setDeinterlace:0];
3000     if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3001     {
3002         /* we are using decomb */
3003         /* Decomb */
3004         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3005         {
3006             [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3007             
3008             /* if we are using "Custom" in the decomb setting, also set the custom string*/
3009             if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3010             {
3011                 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];    
3012             }
3013         }
3014     }
3015     else
3016     {
3017         /* We are using Deinterlace */
3018         /* Deinterlace */
3019         if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3020         {
3021             [fPictureController setUseDecomb:0];
3022             [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3023             /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3024             if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3025             {
3026                 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];    
3027             }
3028         }
3029     }
3030     
3031     
3032     /* Detelecine */
3033     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3034     {
3035         [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3036         /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3037         if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3038         {
3039             [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];    
3040         }
3041     }
3042     else
3043     {
3044         [fPictureController setDetelecine:0];
3045     }
3046     
3047     /* Denoise */
3048     if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3049     {
3050         [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3051         /* if we are using "Custom" in the denoise setting, also set the custom string*/
3052         if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3053         {
3054             [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];    
3055         }
3056     }
3057     else
3058     {
3059         [fPictureController setDenoise:0];
3060     }   
3061     
3062     /* Deblock */
3063     if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3064     {
3065         /* if its a one, then its the old on/off deblock, set on to 5*/
3066         [fPictureController setDeblock:5];
3067     }
3068     else
3069     {
3070         /* use the settings intValue */
3071         [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3072     }
3073     
3074     if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3075     {
3076         [fPictureController setGrayscale:1];
3077     }
3078     else
3079     {
3080         [fPictureController setGrayscale:0];
3081     }
3082     
3083     /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3084     [fPictureController SetTitle:fTitle];
3085     [self calculatePictureSizing:nil];
3086     
3087     [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture filters set up"];
3088     /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3089     //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3090     //    [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3091     if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3092         {
3093                 /* Deselect the currently selected Preset if there is one*/
3094         //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3095         //[self selectPreset:nil];
3096                 
3097         //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3098                 /* Change UI to show "Custom" settings are being used */
3099                 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3100         
3101                 curUserPresetChosenNum = nil;
3102         }
3103     else
3104     {
3105         /* Deselect the currently selected Preset if there is one*/
3106                 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3107                 /* Change UI to show "Custom" settings are being used */
3108                 [fPresetSelectedDisplay setStringValue: @"Custom"];
3109         
3110                 //curUserPresetChosenNum = nil;
3111     }
3112     
3113     /* We need to set this bool back to NO, in case the user wants to do a scan */
3114     //applyQueueToScan = NO;
3115     
3116     /* Not that source is loaded and settings applied, delete the queue item from the queue */
3117     [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3118     [self removeQueueFileItem:fqueueEditRescanItemNum];
3119 }
3120
3121
3122
3123 #pragma mark -
3124 #pragma mark Live Preview
3125 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3126  * can encode to its temp preview directory and playback. This is *not* used for any actual user
3127  * encodes
3128  */
3129 - (void) prepareJobForPreview
3130 {
3131     hb_list_t  * list  = hb_get_titles( fHandle );
3132     hb_title_t * title = (hb_title_t *) hb_list_item( list,
3133             [fSrcTitlePopUp indexOfSelectedItem] );
3134     hb_job_t * job = title->job;
3135     hb_audio_config_t * audio;
3136     /* set job->angle for libdvdnav */
3137     job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3138     /* Chapter selection */
3139     job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3140     job->chapter_end   = [fSrcChapterEndPopUp   indexOfSelectedItem] + 1;
3141         
3142     /* Format (Muxer) and Video Encoder */
3143     job->mux = [[fDstFormatPopUp selectedItem] tag];
3144     job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3145
3146     job->chapter_markers = 0;
3147     
3148         if( job->vcodec & HB_VCODEC_X264 )
3149     {
3150                 
3151                 /* Below Sends x264 options to the core library if x264 is selected*/
3152                 /* Lets use this as per Nyx, Thanks Nyx!*/
3153                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3154                 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3155                 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3156
3157         
3158     }
3159
3160     /* Video settings */
3161    /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3162      * and detelecine is on, so we handle that in the logic below
3163      */
3164     job->vfr = 0;
3165     if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3166     {
3167         /* a specific framerate has been chosen */
3168         job->vrate      = 27000000;
3169         job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3170         /* We are not same as source so we set job->cfr to 1 
3171          * to enable constant frame rate since user has specified
3172          * a specific framerate*/
3173         job->cfr = 1;
3174     }
3175     else
3176     {
3177         /* We are same as source (variable) */
3178         job->vrate      = title->rate;
3179         job->vrate_base = title->rate_base;
3180         /* We are same as source so we set job->cfr to 0 
3181          * to enable true same as source framerate */
3182         job->cfr = 0;
3183         /* If we are same as source and we have detelecine on, we need to turn on
3184          * job->vfr
3185          */
3186         if ([fPictureController detelecine] == 1)
3187         {
3188             job->vfr = 1;
3189         }
3190     }
3191
3192     switch( [fVidQualityMatrix selectedRow] )
3193     {
3194         case 0:
3195             /* Target size.
3196                Bitrate should already have been calculated and displayed
3197                in fVidBitrateField, so let's just use it */
3198         case 1:
3199             job->vquality = -1.0;
3200             job->vbitrate = [fVidBitrateField intValue];
3201             break;
3202         case 2:
3203             job->vquality = [fVidQualityRFField floatValue];
3204             job->vbitrate = 0;
3205             break;
3206     }
3207
3208     /* Subtitle settings */
3209     NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3210     
3211     
3212 int subtitle = nil;
3213 int force;
3214 int burned;
3215 int def;
3216 bool one_burned = FALSE;
3217
3218     int i = 0;
3219     NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3220     id tempObject;
3221     while (tempObject = [enumerator nextObject])
3222     {
3223         
3224         subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3225         force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3226         burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3227         def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3228         
3229         /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3230          * we want to ignore it for display as well as encoding.
3231          */
3232         if (subtitle > 0)
3233         {
3234             /* if i is 0, then we are in the first item of the subtitles which we need to 
3235              * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3236              * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3237              */
3238             
3239             /* if we are on the first track and using "Foreign Audio Search" */ 
3240             if (i == 0 && subtitle == 1)
3241             {
3242                 /* NOTE: Currently foreign language search is borked for preview.
3243                  * Commented out but left in for initial commit. */
3244                 
3245                 
3246                 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3247                 
3248                 job->indepth_scan = 1;
3249                 if (burned == 1 || job->mux != HB_MUX_MP4)
3250                 {
3251                     if (burned != 1 && job->mux == HB_MUX_MKV)
3252                     {
3253                         job->select_subtitle_config.dest = PASSTHRUSUB;
3254                     }
3255                     else
3256                     {
3257                         job->select_subtitle_config.dest = RENDERSUB;
3258                     }
3259                     
3260                     job->select_subtitle_config.force = force;
3261                     job->select_subtitle_config.default_track = def;
3262                     
3263                 }
3264                 
3265                 
3266             }
3267             else
3268             {
3269                 
3270                 /* for the actual source tracks, we must subtract the non source entries so 
3271                  * that the menu index matches the source subtitle_list index for convenience */
3272                 if (i == 0)
3273                 {
3274                     /* for the first track, the source tracks start at menu index 2 ( None is 0,
3275                      * Foreign Language Search is 1) so subtract 2 */
3276                     subtitle = subtitle - 2;
3277                 }
3278                 else
3279                 {
3280                     /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3281                      * so subtract 1. */
3282                     
3283                     subtitle = subtitle - 1;
3284                 }
3285                 
3286                 /* We are setting a source subtitle so access the source subtitle info */  
3287                 hb_subtitle_t * subt;
3288                 
3289                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3290                 
3291                 /* if we are getting the subtitles from an external srt file */
3292                 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3293                 {
3294                     hb_subtitle_config_t sub_config;
3295                     
3296                     sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3297                     
3298                     /* we need to srncpy file path and char code */
3299                     strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3300                     strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3301                     
3302                     sub_config.force = 0;
3303                     sub_config.dest = PASSTHRUSUB;
3304                     sub_config.default_track = def;
3305                     
3306                     hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3307                 }
3308                 
3309                 if (subt != NULL)
3310                 {
3311                     hb_subtitle_config_t sub_config = subt->config;
3312                     
3313                     if (!burned && job->mux == HB_MUX_MKV && 
3314                         subt->format == PICTURESUB)
3315                     {
3316                         sub_config.dest = PASSTHRUSUB;
3317                     }
3318                     else if (!burned && job->mux == HB_MUX_MP4 && 
3319                              subt->format == PICTURESUB)
3320                     {
3321                         // Skip any non-burned vobsubs when output is mp4
3322                         continue;
3323                     }
3324                     else if ( burned && subt->format == PICTURESUB )
3325                     {
3326                         // Only allow one subtitle to be burned into the video
3327                         if (one_burned)
3328                             continue;
3329                         one_burned = TRUE;
3330                     }
3331                     sub_config.force = force;
3332                     sub_config.default_track = def;
3333                     hb_subtitle_add( job, &sub_config, subtitle );
3334                 }   
3335                 
3336             }
3337         }
3338         i++;
3339     }
3340    
3341     
3342     
3343 [subtitlesArray autorelease];    
3344     
3345     
3346     /* Audio tracks and mixdowns */
3347     /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3348     int audiotrack_count = hb_list_count(job->list_audio);
3349     for( int i = 0; i < audiotrack_count;i++)
3350     {
3351         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3352         hb_list_rem(job->list_audio, temp_audio);
3353     }
3354     /* Now lets add our new tracks to the audio list here */
3355     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3356     {
3357         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3358         hb_audio_config_init(audio);
3359         audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3360         /* We go ahead and assign values to our audio->out.<properties> */
3361         audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3362         audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3363         audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3364         audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3365         audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3366         audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3367         
3368         hb_audio_add( job, audio );
3369         free(audio);
3370     }  
3371     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3372     {
3373         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3374         hb_audio_config_init(audio);
3375         audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3376         /* We go ahead and assign values to our audio->out.<properties> */
3377         audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3378         audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3379         audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3380         audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3381         audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3382         audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3383         
3384         hb_audio_add( job, audio );
3385         free(audio);
3386         
3387     }
3388     
3389     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3390     {
3391         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3392         hb_audio_config_init(audio);
3393         audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3394         /* We go ahead and assign values to our audio->out.<properties> */
3395         audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3396         audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3397         audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3398         audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3399         audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3400         audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3401         
3402         hb_audio_add( job, audio );
3403         free(audio);
3404         
3405     }
3406
3407     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3408     {
3409         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3410         hb_audio_config_init(audio);
3411         audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3412         /* We go ahead and assign values to our audio->out.<properties> */
3413         audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3414         audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3415         audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3416         audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3417         audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3418         audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3419         
3420         hb_audio_add( job, audio );
3421         free(audio);
3422         
3423     }
3424
3425     
3426     
3427     /* Filters */
3428     
3429     /* Though Grayscale is not really a filter, per se
3430      * we put it here since its in the filters panel
3431      */
3432      
3433     if ([fPictureController grayscale])
3434     {
3435         job->grayscale = 1;
3436     }
3437     else
3438     {
3439         job->grayscale = 0;
3440     }
3441     
3442     /* Initialize the filters list */
3443     job->filters = hb_list_init();
3444     
3445     /* Now lets call the filters if applicable.
3446     * The order of the filters is critical
3447     */
3448     
3449         /* Detelecine */
3450     if ([fPictureController detelecine] == 1)
3451     {
3452         /* use a custom detelecine string */
3453         hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3454         hb_list_add( job->filters, &hb_filter_detelecine );
3455     }
3456     if ([fPictureController detelecine] == 2)
3457     {
3458         /* Default */
3459         hb_list_add( job->filters, &hb_filter_detelecine );
3460     }
3461     
3462     
3463     
3464     if ([fPictureController useDecomb] == 1)
3465     {
3466         /* Decomb */
3467         /* we add the custom string if present */
3468         if ([fPictureController decomb] == 1)
3469         {
3470             /* use a custom decomb string */
3471             hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3472             hb_list_add( job->filters, &hb_filter_decomb );
3473         }
3474         if ([fPictureController decomb] == 2)
3475         {
3476             /* Run old deinterlacer fd by default */
3477             //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3478             hb_list_add( job->filters, &hb_filter_decomb );
3479         }
3480     }
3481     else
3482     {
3483         
3484         /* Deinterlace */
3485         if ([fPictureController deinterlace] == 1)
3486         {
3487             /* we add the custom string if present */
3488             hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3489             hb_list_add( job->filters, &hb_filter_deinterlace );            
3490         }
3491         else if ([fPictureController deinterlace] == 2)
3492         {
3493             /* Run old deinterlacer fd by default */
3494             hb_filter_deinterlace.settings = "-1"; 
3495             hb_list_add( job->filters, &hb_filter_deinterlace );
3496         }
3497         else if ([fPictureController deinterlace] == 3)
3498         {
3499             /* Yadif mode 0 (without spatial deinterlacing.) */
3500             hb_filter_deinterlace.settings = "2"; 
3501             hb_list_add( job->filters, &hb_filter_deinterlace );            
3502         }
3503         else if ([fPictureController deinterlace] == 4)
3504         {
3505             /* Yadif (with spatial deinterlacing) */
3506             hb_filter_deinterlace.settings = "0"; 
3507             hb_list_add( job->filters, &hb_filter_deinterlace );            
3508         }
3509         
3510         }
3511     
3512     /* Denoise */
3513         if ([fPictureController denoise] == 1) // custom in popup
3514         {
3515                 /* we add the custom string if present */
3516         hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String]; 
3517         hb_list_add( job->filters, &hb_filter_denoise );        
3518         }
3519     else if ([fPictureController denoise] == 2) // Weak in popup
3520         {
3521                 hb_filter_denoise.settings = "2:1:2:3"; 
3522         hb_list_add( job->filters, &hb_filter_denoise );        
3523         }
3524         else if ([fPictureController denoise] == 3) // Medium in popup
3525         {
3526                 hb_filter_denoise.settings = "3:2:2:3"; 
3527         hb_list_add( job->filters, &hb_filter_denoise );        
3528         }
3529         else if ([fPictureController denoise] == 4) // Strong in popup
3530         {
3531                 hb_filter_denoise.settings = "7:7:5:5"; 
3532         hb_list_add( job->filters, &hb_filter_denoise );        
3533         }
3534     
3535     
3536     /* Deblock  (uses pp7 default) */
3537     /* NOTE: even though there is a valid deblock setting of 0 for the filter, for 
3538      * the macgui's purposes a value of 0 actually means to not even use the filter
3539      * current hb_filter_deblock.settings valid ranges are from 5 - 15 
3540      */
3541     if ([fPictureController deblock] != 0)
3542     {
3543         NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3544         hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3545         hb_list_add( job->filters, &hb_filter_deblock );
3546     }
3547
3548 }
3549
3550
3551 #pragma mark -
3552 #pragma mark Job Handling
3553
3554
3555 - (void) prepareJob
3556 {
3557     
3558     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3559     hb_list_t  * list  = hb_get_titles( fQueueEncodeLibhb );
3560     hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3561     hb_job_t * job = title->job;
3562     hb_audio_config_t * audio;
3563     /* Title Angle for dvdnav */
3564     job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3565     
3566     if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3567     {
3568         /* Chapter selection */
3569         [self writeToActivityLog: "Start / Stop set to chapters"];
3570         job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3571         job->chapter_end   = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3572     }
3573     else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3574     {
3575         /* we are pts based start / stop */
3576         [self writeToActivityLog: "Start / Stop set to seconds ..."];
3577         
3578         /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3579          * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3580          */
3581         /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3582         /* get the start seconds from the start seconds field */
3583         int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3584         //job->start_at_preview = start_seconds;
3585         /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3586         //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3587         job->pts_to_start = start_seconds * 90000LL;
3588         /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3589         int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3590         job->pts_to_stop = stop_seconds * 90000LL;
3591
3592         /* A bunch of verbose activity log messages to check on what should be expected */
3593         [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3594         [self writeToActivityLog: "point a to b should start at (hh:mm:ss): %d:%d:%d", start_seconds / 3600, ( start_seconds / 60 ) % 60,start_seconds % 60];
3595         [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3596         [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3597         [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3598         [self writeToActivityLog: "point a to b should end at (hh:mm:ss): %d:%d:%d", (start_seconds + stop_seconds) / 3600, ( (start_seconds + stop_seconds) / 60 ) % 60,(start_seconds + stop_seconds) % 60];
3599     }
3600     else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3601     {
3602         /* we are frame based start / stop */
3603         [self writeToActivityLog: "Start / Stop set to frames ..."];
3604         
3605         /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3606          * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3607          */
3608         /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3609         /* get the start seconds from the start seconds field */
3610         int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3611         //job->start_at_preview = start_seconds;
3612         /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3613         //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3614         job->frame_to_start = start_frame;
3615         /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3616         int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3617         job->frame_to_stop = stop_frame;
3618
3619         /* A bunch of verbose activity log messages to check on what should be expected */
3620         [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3621         [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3622         [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3623     }
3624
3625         
3626         
3627     
3628     /* Format (Muxer) and Video Encoder */
3629     job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3630     job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3631     
3632     
3633     /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3634     if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3635     {
3636         job->largeFileSize = 1;
3637     }
3638     else
3639     {
3640         job->largeFileSize = 0;
3641     }
3642     /* We set http optimized mp4 here */
3643     if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3644     {
3645         job->mp4_optimize = 1;
3646     }
3647     else
3648     {
3649         job->mp4_optimize = 0;
3650     }
3651
3652         
3653     /* We set the chapter marker extraction here based on the format being
3654      mpeg4 or mkv and the checkbox being checked */
3655     if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3656     {
3657         job->chapter_markers = 1;
3658         
3659         /* now lets get our saved chapter names out the array in the queue file
3660          * and insert them back into the title chapter list. We have it here,
3661          * because unless we are inserting chapter markers there is no need to
3662          * spend the overhead of iterating through the chapter names array imo
3663          * Also, note that if for some reason we don't apply chapter names, the
3664          * chapters just come out 001, 002, etc. etc.
3665          */
3666          
3667         NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3668         int i = 0;
3669         NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3670         id tempObject;
3671         while (tempObject = [enumerator nextObject])
3672         {
3673             hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3674             if( chapter != NULL )
3675             {
3676                 strncpy( chapter->title, [tempObject UTF8String], 1023);
3677                 chapter->title[1023] = '\0';
3678             }
3679             i++;
3680         }
3681     }
3682     else
3683     {
3684         job->chapter_markers = 0;
3685     }
3686     
3687     if( job->vcodec & HB_VCODEC_X264 )
3688     {
3689                 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3690             {
3691             job->ipod_atom = 1;
3692                 }
3693         else
3694         {
3695             job->ipod_atom = 0;
3696         }
3697                 
3698                 
3699                 /* Below Sends x264 options to the core library if x264 is selected*/
3700                 /* Lets use this as per Nyx, Thanks Nyx!*/
3701                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3702                 /* Turbo first pass if two pass and Turbo First pass is selected */
3703                 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3704                 {
3705                         /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3706                         NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3707                         /* append the "Turbo" string variable to the existing opts string.
3708              Note: the "Turbo" string must be appended, not prepended to work properly*/
3709                         NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3710                         strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3711                 }
3712                 else
3713                 {
3714                         strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3715                 }
3716         
3717     }
3718     
3719     
3720     /* Picture Size Settings */
3721     job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
3722     job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
3723     
3724     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
3725     job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
3726     job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3727     if ([[queueToApply objectForKey:@"PicturePAR"]  intValue] == 3)
3728     {
3729         /* insert our custom values here for capuj */
3730         job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"]  intValue];
3731         job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"]  intValue];
3732         
3733         job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3734         
3735         job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"]  intValue];
3736         job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"]  intValue];
3737         
3738         job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"]  floatValue];
3739         job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"]  floatValue];
3740     }
3741     
3742     /* Here we use the crop values saved at the time the preset was saved */
3743     job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
3744     job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
3745     job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
3746     job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
3747     
3748     /* Video settings */
3749     /* Framerate */
3750     
3751     /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3752      * and detelecine is on, so we handle that in the logic below
3753      */
3754     job->vfr = 0;
3755     if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3756     {
3757         /* a specific framerate has been chosen */
3758         job->vrate      = 27000000;
3759         job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3760         /* We are not same as source so we set job->cfr to 1 
3761          * to enable constant frame rate since user has specified
3762          * a specific framerate*/
3763         job->cfr = 1;
3764     }
3765     else
3766     {
3767         /* We are same as source (variable) */
3768         job->vrate      = [[queueToApply objectForKey:@"JobVrate"] intValue];
3769         job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3770         /* We are same as source so we set job->cfr to 0 
3771          * to enable true same as source framerate */
3772         job->cfr = 0;
3773         /* If we are same as source and we have detelecine on, we need to turn on
3774          * job->vfr
3775          */
3776         if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3777         {
3778             job->vfr = 1;
3779         }
3780     }
3781     
3782     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3783     {
3784         /* Target size.
3785          Bitrate should already have been calculated and displayed
3786          in fVidBitrateField, so let's just use it same as abr*/
3787         job->vquality = -1.0;
3788         job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3789     }
3790     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3791     {
3792         job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3793         job->vbitrate = 0;
3794         
3795     }
3796     
3797     job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3798     
3799
3800
3801 #pragma mark -
3802 #pragma mark Process Subtitles to libhb
3803
3804 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3805  * which means that we need to account for the offset of non source language settings in from
3806  * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3807  * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3808  * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3809  * to the source tracks position in title->list_subtitle.
3810  */
3811
3812 int subtitle = nil;
3813 int force;
3814 int burned;
3815 int def;
3816 bool one_burned = FALSE;
3817
3818     int i = 0;
3819     NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3820     id tempObject;
3821     while (tempObject = [enumerator nextObject])
3822     {
3823         
3824         subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3825         force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3826         burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3827         def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3828         
3829         /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3830          * we want to ignore it for display as well as encoding.
3831          */
3832         if (subtitle > 0)
3833         {
3834             /* if i is 0, then we are in the first item of the subtitles which we need to 
3835              * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3836              * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3837              */
3838             
3839             /* if we are on the first track and using "Foreign Audio Search" */ 
3840             if (i == 0 && subtitle == 1)
3841             {
3842                 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3843                 
3844                 job->indepth_scan = 1;
3845                 if (burned == 1 || job->mux != HB_MUX_MP4)
3846                 {
3847                     if (burned != 1 && job->mux == HB_MUX_MKV)
3848                     {
3849                         job->select_subtitle_config.dest = PASSTHRUSUB;
3850                     }
3851                     else
3852                     {
3853                         job->select_subtitle_config.dest = RENDERSUB;
3854                     }
3855                     
3856                     job->select_subtitle_config.force = force;
3857                     job->select_subtitle_config.default_track = def;
3858                 }
3859                 
3860                 
3861             }
3862             else
3863             {
3864                 
3865                 /* for the actual source tracks, we must subtract the non source entries so 
3866                  * that the menu index matches the source subtitle_list index for convenience */
3867                 if (i == 0)
3868                 {
3869                     /* for the first track, the source tracks start at menu index 2 ( None is 0,
3870                      * Foreign Language Search is 1) so subtract 2 */
3871                     subtitle = subtitle - 2;
3872                 }
3873                 else
3874                 {
3875                     /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3876                      * so subtract 1. */
3877                     
3878                     subtitle = subtitle - 1;
3879                 }
3880                 
3881                 /* We are setting a source subtitle so access the source subtitle info */  
3882                 hb_subtitle_t * subt;
3883                 
3884                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3885                 
3886                 /* if we are getting the subtitles from an external srt file */
3887                 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3888                 {
3889                     hb_subtitle_config_t sub_config;
3890                     
3891                     sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3892                     
3893                     /* we need to srncpy file name and codeset */
3894                     strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3895                     strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3896                     
3897                     sub_config.force = 0;
3898                     sub_config.dest = PASSTHRUSUB;
3899                     sub_config.default_track = def;
3900                     
3901                     hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3902                 }
3903                 
3904                 
3905                 if (subt != NULL)
3906                 {
3907                     hb_subtitle_config_t sub_config = subt->config;
3908                     
3909                     if (!burned && job->mux == HB_MUX_MKV && 
3910                         subt->format == PICTURESUB)
3911                     {
3912                         sub_config.dest = PASSTHRUSUB;
3913                     }
3914                     else if (!burned && job->mux == HB_MUX_MP4 && 
3915                              subt->format == PICTURESUB)
3916                     {
3917                         // Skip any non-burned vobsubs when output is mp4
3918                         continue;
3919                     }
3920                     else if ( burned && subt->format == PICTURESUB )
3921                     {
3922                         // Only allow one subtitle to be burned into the video
3923                         if (one_burned)
3924                             continue;
3925                         one_burned = TRUE;
3926                     }
3927                     sub_config.force = force;
3928                     sub_config.default_track = def;
3929                     hb_subtitle_add( job, &sub_config, subtitle );
3930                 }   
3931                 
3932             }
3933         }
3934         i++;
3935     }
3936
3937 #pragma mark -
3938
3939    
3940     /* Audio tracks and mixdowns */
3941     /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3942     int audiotrack_count = hb_list_count(job->list_audio);
3943     for( int i = 0; i < audiotrack_count;i++)
3944     {
3945         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3946         hb_list_rem(job->list_audio, temp_audio);
3947     }
3948     /* Now lets add our new tracks to the audio list here */
3949     if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3950     {
3951         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3952         hb_audio_config_init(audio);
3953         audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3954         /* We go ahead and assign values to our audio->out.<properties> */
3955         audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3956         audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3957         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3958         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3959         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3960         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3961         
3962         hb_audio_add( job, audio );
3963         free(audio);
3964     }  
3965     if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3966     {
3967         
3968         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3969         hb_audio_config_init(audio);
3970         audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3971         [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3972         /* We go ahead and assign values to our audio->out.<properties> */
3973         audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3974         audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3975         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3976         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3977         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3978         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3979         
3980         hb_audio_add( job, audio );
3981         free(audio);
3982     }
3983     
3984     if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3985     {
3986         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3987         hb_audio_config_init(audio);
3988         audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3989         /* We go ahead and assign values to our audio->out.<properties> */
3990         audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3991         audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3992         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3993         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3994         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3995         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3996         
3997         hb_audio_add( job, audio );
3998         free(audio);        
3999     }
4000     
4001     if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
4002     {
4003         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4004         hb_audio_config_init(audio);
4005         audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4006         /* We go ahead and assign values to our audio->out.<properties> */
4007         audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4008         audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
4009         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
4010         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
4011         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
4012         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
4013         
4014         hb_audio_add( job, audio );
4015         
4016
4017     }
4018     
4019     /* Filters */ 
4020     job->filters = hb_list_init();
4021     
4022     /* Now lets call the filters if applicable.
4023      * The order of the filters is critical
4024      */
4025     /* Detelecine */
4026     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4027     {
4028         /* use a custom detelecine string */
4029         hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4030         hb_list_add( job->filters, &hb_filter_detelecine );
4031     }
4032     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4033     {
4034         /* Use libhb's default values */
4035         hb_list_add( job->filters, &hb_filter_detelecine );
4036     }
4037     
4038     if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4039     {
4040         /* Decomb */
4041         /* we add the custom string if present */
4042         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4043         {
4044             /* use a custom decomb string */
4045             hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4046             hb_list_add( job->filters, &hb_filter_decomb );
4047         }
4048         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4049         {
4050             /* Use libhb default */
4051             hb_list_add( job->filters, &hb_filter_decomb );
4052         }
4053         
4054     }
4055     else
4056     {
4057         
4058         /* Deinterlace */
4059         if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4060         {
4061             /* we add the custom string if present */
4062             hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4063             hb_list_add( job->filters, &hb_filter_deinterlace );            
4064         }
4065         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4066         {
4067             /* Run old deinterlacer fd by default */
4068             hb_filter_deinterlace.settings = "-1"; 
4069             hb_list_add( job->filters, &hb_filter_deinterlace );
4070         }
4071         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4072         {
4073             /* Yadif mode 0 (without spatial deinterlacing.) */
4074             hb_filter_deinterlace.settings = "2"; 
4075             hb_list_add( job->filters, &hb_filter_deinterlace );            
4076         }
4077         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4078         {
4079             /* Yadif (with spatial deinterlacing) */
4080             hb_filter_deinterlace.settings = "0"; 
4081             hb_list_add( job->filters, &hb_filter_deinterlace );            
4082         }
4083         
4084         
4085     }
4086     /* Denoise */
4087         if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4088         {
4089                 /* we add the custom string if present */
4090         hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4091         hb_list_add( job->filters, &hb_filter_denoise );        
4092         }
4093     else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4094         {
4095                 hb_filter_denoise.settings = "2:1:2:3"; 
4096         hb_list_add( job->filters, &hb_filter_denoise );        
4097         }
4098         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4099         {
4100                 hb_filter_denoise.settings = "3:2:2:3"; 
4101         hb_list_add( job->filters, &hb_filter_denoise );        
4102         }
4103         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4104         {
4105                 hb_filter_denoise.settings = "7:7:5:5"; 
4106         hb_list_add( job->filters, &hb_filter_denoise );        
4107         }
4108     
4109     
4110     /* Deblock  (uses pp7 default) */
4111     /* NOTE: even though there is a valid deblock setting of 0 for the filter, for 
4112      * the macgui's purposes a value of 0 actually means to not even use the filter
4113      * current hb_filter_deblock.settings valid ranges are from 5 - 15 
4114      */
4115     if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4116     {
4117         hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4118         hb_list_add( job->filters, &hb_filter_deblock );
4119     }
4120 [self writeToActivityLog: "prepareJob exiting"];    
4121 }
4122
4123
4124
4125 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4126 */
4127 - (IBAction) addToQueue: (id) sender
4128 {
4129         /* We get the destination directory from the destination field here */
4130         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4131         /* We check for a valid destination here */
4132         if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
4133         {
4134                 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4135         return;
4136         }
4137     
4138     BOOL fileExists;
4139     fileExists = NO;
4140     
4141     BOOL fileExistsInQueue;
4142     fileExistsInQueue = NO;
4143     
4144     /* We check for and existing file here */
4145     if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4146     {
4147         fileExists = YES;
4148     }
4149     
4150     /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4151     int i = 0;
4152     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4153         id tempObject;
4154         while (tempObject = [enumerator nextObject])
4155         {
4156                 NSDictionary *thisQueueDict = tempObject;
4157                 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4158                 {
4159                         fileExistsInQueue = YES;        
4160                 }
4161         i++;
4162         }
4163     
4164     
4165         if(fileExists == YES)
4166     {
4167         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4168                                   NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4169                                   @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4170                                   NULL, NULL, [NSString stringWithFormat:
4171                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4172                                                [fDstFile2Field stringValue]] );
4173     }
4174     else if (fileExistsInQueue == YES)
4175     {
4176     NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4177                                   NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4178                                   @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4179                                   NULL, NULL, [NSString stringWithFormat:
4180                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4181                                                [fDstFile2Field stringValue]] );
4182     }
4183     else
4184     {
4185         [self doAddToQueue];
4186     }
4187 }
4188
4189 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4190    the user if they want to overwrite an exiting movie file.
4191 */
4192 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4193     returnCode: (int) returnCode contextInfo: (void *) contextInfo
4194 {
4195     if( returnCode == NSAlertAlternateReturn )
4196         [self doAddToQueue];
4197 }
4198
4199 - (void) doAddToQueue
4200 {
4201     [self addQueueFileItem ];
4202 }
4203
4204
4205
4206 /* Rip: puts up an alert before ultimately calling doRip
4207 */
4208 - (IBAction) Rip: (id) sender
4209 {
4210     [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4211     /* Rip or Cancel ? */
4212     hb_state_t s;
4213     hb_get_state2( fQueueEncodeLibhb, &s );
4214     
4215     if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4216         {
4217         [self Cancel: sender];
4218         return;
4219     }
4220     
4221     /* We check to see if we need to warn the user that the computer will go to sleep
4222                  or shut down when encoding is finished */
4223                 [self remindUserOfSleepOrShutdown];
4224     
4225     // If there are pending jobs in the queue, then this is a rip the queue
4226     if (fPendingCount > 0)
4227     {
4228         /* here lets start the queue with the first pending item */
4229         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4230         
4231         return;
4232     }
4233     
4234     // Before adding jobs to the queue, check for a valid destination.
4235     
4236     NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4237     if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
4238     {
4239         NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4240         return;
4241     }
4242     
4243     /* We check for duplicate name here */
4244     if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4245     {
4246         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4247                                   NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4248                                   @selector( overWriteAlertDone:returnCode:contextInfo: ),
4249                                   NULL, NULL, [NSString stringWithFormat:
4250                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4251                                                [fDstFile2Field stringValue]] );
4252         
4253         // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4254     }
4255     else
4256     {
4257         /* if there are no pending jobs in the queue, then add this one to the queue and rip
4258          otherwise, just rip the queue */
4259         if(fPendingCount == 0)
4260         {
4261             [self doAddToQueue];
4262         }
4263         
4264         /* go right to processing the new queue encode */
4265         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4266         
4267     }
4268 }
4269
4270 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4271    want to overwrite an exiting movie file.
4272 */
4273 - (void) overWriteAlertDone: (NSWindow *) sheet
4274     returnCode: (int) returnCode contextInfo: (void *) contextInfo
4275 {
4276     if( returnCode == NSAlertAlternateReturn )
4277     {
4278         /* if there are no jobs in the queue, then add this one to the queue and rip 
4279         otherwise, just rip the queue */
4280         if( fPendingCount == 0 )
4281         {
4282             [self doAddToQueue];
4283         }
4284
4285         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4286         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4287         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4288       
4289     }
4290 }
4291
4292 - (void) remindUserOfSleepOrShutdown
4293 {
4294        if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4295        {
4296                /*Warn that computer will sleep after encoding*/
4297                int reminduser;
4298                NSBeep();
4299                reminduser = NSRunAlertPanel(@"The computer will sleep after encoding is done.",@"You have selected to sleep the computer after encoding. To turn off sleeping, go to the HandBrake preferences.", @"OK", @"Preferences...", nil);
4300                [NSApp requestUserAttention:NSCriticalRequest];
4301                if ( reminduser == NSAlertAlternateReturn )
4302                {
4303                        [self showPreferencesWindow:nil];
4304                }
4305        }
4306        else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4307        {
4308                /*Warn that computer will shut down after encoding*/
4309                int reminduser;
4310                NSBeep();
4311                reminduser = NSRunAlertPanel(@"The computer will shut down after encoding is done.",@"You have selected to shut down the computer after encoding. To turn off shut down, go to the HandBrake preferences.", @"OK", @"Preferences...", nil);
4312                [NSApp requestUserAttention:NSCriticalRequest];
4313                if ( reminduser == NSAlertAlternateReturn )
4314                {
4315                        [self showPreferencesWindow:nil];
4316                }
4317        }
4318
4319 }
4320
4321
4322 - (void) doRip
4323 {
4324     /* Let libhb do the job */
4325     hb_start( fQueueEncodeLibhb );
4326     /*set the fEncodeState State */
4327         fEncodeState = 1;
4328 }
4329
4330
4331 //------------------------------------------------------------------------------------
4332 // Displays an alert asking user if the want to cancel encoding of current job.
4333 // Cancel: returns immediately after posting the alert. Later, when the user
4334 // acknowledges the alert, doCancelCurrentJob is called.
4335 //------------------------------------------------------------------------------------
4336 - (IBAction)Cancel: (id)sender
4337 {
4338     if (!fQueueController) return;
4339     
4340   hb_pause( fQueueEncodeLibhb );
4341     NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4342    
4343     // Which window to attach the sheet to?
4344     NSWindow * docWindow;
4345     if ([sender respondsToSelector: @selector(window)])
4346         docWindow = [sender window];
4347     else
4348         docWindow = fWindow;
4349         
4350     NSBeginCriticalAlertSheet(
4351             alertTitle,
4352             NSLocalizedString(@"Continue Encoding", nil),
4353             NSLocalizedString(@"Cancel Current and Stop", nil),
4354             NSLocalizedString(@"Cancel Current and Continue", nil),
4355             docWindow, self,
4356             nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4357             NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4358     
4359     // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4360 }
4361
4362 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4363 {
4364    hb_resume( fQueueEncodeLibhb );
4365      if (returnCode == NSAlertOtherReturn)
4366     {
4367         [self doCancelCurrentJob];  // <- this also stops libhb
4368     }
4369     if (returnCode == NSAlertAlternateReturn)
4370     {
4371     [self doCancelCurrentJobAndStop];
4372     }
4373 }
4374
4375 //------------------------------------------------------------------------------------
4376 // Cancels and deletes the current job and stops libhb from processing the remaining
4377 // encodes.
4378 //------------------------------------------------------------------------------------
4379 - (void) doCancelCurrentJob
4380 {
4381     // Stop the current job. hb_stop will only cancel the current pass and then set
4382     // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4383     // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4384     // remaining passes of the job and then start the queue back up if there are any
4385     // remaining jobs.
4386      
4387     
4388     hb_stop( fQueueEncodeLibhb );
4389     
4390     // Delete all remaining jobs since libhb doesn't do this on its own.
4391             hb_job_t * job;
4392             while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4393                 hb_rem( fQueueEncodeLibhb, job );
4394                 
4395     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
4396     
4397     // now that we've stopped the currently encoding job, lets mark it as cancelled
4398     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4399     // and as always, save it in the queue .plist...
4400     /* We save all of the Queue data here */
4401     [self saveQueueFileItem];
4402     // so now lets move to 
4403     currentQueueEncodeIndex++ ;
4404     // ... and see if there are more items left in our queue
4405     int queueItems = [QueueFileArray count];
4406     /* If we still have more items in our queue, lets go to the next one */
4407     if (currentQueueEncodeIndex < queueItems)
4408     {
4409     [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4410     [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4411     
4412     [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4413     }
4414     else
4415     {
4416         [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4417     }
4418
4419 }
4420
4421 - (void) doCancelCurrentJobAndStop
4422 {
4423     hb_stop( fQueueEncodeLibhb );
4424     
4425     // Delete all remaining jobs since libhb doesn't do this on its own.
4426             hb_job_t * job;
4427             while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4428                 hb_rem( fQueueEncodeLibhb, job );
4429                 
4430                 
4431     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
4432     
4433     // now that we've stopped the currently encoding job, lets mark it as cancelled
4434     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4435     // and as always, save it in the queue .plist...
4436     /* We save all of the Queue data here */
4437     [self saveQueueFileItem];
4438     // so now lets move to 
4439     currentQueueEncodeIndex++ ;
4440     [self writeToActivityLog: "cancelling current job and stopping the queue"];
4441 }
4442 - (IBAction) Pause: (id) sender
4443 {
4444     hb_state_t s;
4445     hb_get_state2( fQueueEncodeLibhb, &s );
4446
4447     if( s.state == HB_STATE_PAUSED )
4448     {
4449         hb_resume( fQueueEncodeLibhb );
4450     }
4451     else
4452     {
4453         hb_pause( fQueueEncodeLibhb );
4454     }
4455 }
4456
4457 #pragma mark -
4458 #pragma mark GUI Controls Changed Methods
4459
4460 - (IBAction) titlePopUpChanged: (id) sender
4461 {
4462     hb_list_t  * list  = hb_get_titles( fHandle );
4463     hb_title_t * title = (hb_title_t*)
4464         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4465
4466     /* If we are a stream type, grok the output file name from title->name upon title change */
4467     if (title->type == HB_STREAM_TYPE)
4468     {
4469         /* we set the default name according to the new title->name */
4470         [fDstFile2Field setStringValue: [NSString stringWithFormat:
4471                                          @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4472                                          [NSString stringWithUTF8String: title->name],
4473                                          [[fDstFile2Field stringValue] pathExtension]]];
4474         /* If we have more than one title and are stream then we have a batch, change the source to read out the parent folder also */
4475         if ( hb_list_count( list ) > 1 )
4476         {                                  
4477             [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4478         }
4479     }
4480     
4481     /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4482     int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4483     [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4484     [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4485     /* For point a to point b frame encoding, set the start and end fields to 0 and the title duration * announced fps in seconds respectively */
4486     [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4487     //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4488     [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];    
4489     
4490     /* If Auto Naming is on. We create an output filename of dvd name - title number */
4491     if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4492         {
4493                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4494                         @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4495                         [browsedSourceDisplayName stringByDeletingPathExtension],
4496             title->index,
4497                         [[fDstFile2Field stringValue] pathExtension]]]; 
4498         }
4499     /* Update encode start / stop variables */
4500      
4501     
4502     
4503     /* Update chapter popups */
4504     [fSrcChapterStartPopUp removeAllItems];
4505     [fSrcChapterEndPopUp   removeAllItems];
4506     for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4507     {
4508         [fSrcChapterStartPopUp addItemWithTitle: [NSString
4509             stringWithFormat: @"%d", i + 1]];
4510         [fSrcChapterEndPopUp addItemWithTitle: [NSString
4511             stringWithFormat: @"%d", i + 1]];
4512     }
4513
4514     [fSrcChapterStartPopUp selectItemAtIndex: 0];
4515     [fSrcChapterEndPopUp   selectItemAtIndex:
4516         hb_list_count( title->list_chapter ) - 1];
4517     [self chapterPopUpChanged:nil];
4518     
4519     /* if using dvd nav, show the angle widget */
4520     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4521     {
4522         [fSrcAngleLabel setHidden:NO];
4523         [fSrcAnglePopUp setHidden:NO];
4524         
4525         [fSrcAnglePopUp removeAllItems];
4526         for( int i = 0; i < title->angle_count; i++ )
4527         {
4528             [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4529         }
4530         [fSrcAnglePopUp selectItemAtIndex: 0];
4531     }
4532     else
4533     {
4534         [fSrcAngleLabel setHidden:YES];
4535         [fSrcAnglePopUp setHidden:YES];
4536     }
4537     
4538     /* Start Get and set the initial pic size for display */
4539         hb_job_t * job = title->job;
4540         fTitle = title;
4541     
4542     /* Set Auto Crop to on upon selecting a new title  */
4543     [fPictureController setAutoCrop:YES];
4544     
4545         /* We get the originial output picture width and height and put them
4546         in variables for use with some presets later on */
4547         PicOrigOutputWidth = job->width;
4548         PicOrigOutputHeight = job->height;
4549         AutoCropTop = job->crop[0];
4550         AutoCropBottom = job->crop[1];
4551         AutoCropLeft = job->crop[2];
4552         AutoCropRight = job->crop[3];
4553
4554         /* Reset the new title in fPictureController &&  fPreviewController*/
4555     [fPictureController SetTitle:title];
4556
4557         
4558     /* Update Subtitle Table */
4559     [fSubtitlesDelegate resetWithTitle:title];
4560     [fSubtitlesTable reloadData];
4561     
4562
4563     /* Update chapter table */
4564     [fChapterTitlesDelegate resetWithTitle:title];
4565     [fChapterTable reloadData];
4566
4567    /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4568     int audiotrack_count = hb_list_count(job->list_audio);
4569     for( int i = 0; i < audiotrack_count;i++)
4570     {
4571         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4572         hb_list_rem(job->list_audio, temp_audio);
4573     }
4574
4575     /* Update audio popups */
4576     [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4577     [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4578     [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4579     [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4580     /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4581         NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4582         [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4583     [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4584     [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4585     [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4586
4587         /* changing the title may have changed the audio channels on offer, */
4588         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4589         [self audioTrackPopUpChanged: fAudLang1PopUp];
4590         [self audioTrackPopUpChanged: fAudLang2PopUp];
4591     [self audioTrackPopUpChanged: fAudLang3PopUp];
4592     [self audioTrackPopUpChanged: fAudLang4PopUp];
4593
4594     [fVidRatePopUp selectItemAtIndex: 0];
4595
4596     /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4597         [self calculatePictureSizing:nil];
4598
4599    /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4600     [self selectPreset:nil];
4601 }
4602
4603 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4604 {
4605     if( [fEncodeStartStopPopUp isEnabled] )
4606     {
4607         /* We are chapters */
4608         if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4609         {
4610             [fSrcChapterStartPopUp  setHidden: NO];
4611             [fSrcChapterEndPopUp  setHidden: NO];
4612             
4613             [fSrcTimeStartEncodingField  setHidden: YES];
4614             [fSrcTimeEndEncodingField  setHidden: YES];
4615             
4616             [fSrcFrameStartEncodingField  setHidden: YES];
4617             [fSrcFrameEndEncodingField  setHidden: YES];
4618             
4619                [self chapterPopUpChanged:nil];   
4620         }
4621         /* We are time based (seconds) */
4622         else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4623         {
4624             [fSrcChapterStartPopUp  setHidden: YES];
4625             [fSrcChapterEndPopUp  setHidden: YES];
4626             
4627             [fSrcTimeStartEncodingField  setHidden: NO];
4628             [fSrcTimeEndEncodingField  setHidden: NO];
4629             
4630             [fSrcFrameStartEncodingField  setHidden: YES];
4631             [fSrcFrameEndEncodingField  setHidden: YES];
4632             
4633             [self startEndSecValueChanged:nil];
4634         }
4635         /* We are frame based */
4636         else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4637         {
4638             [fSrcChapterStartPopUp  setHidden: YES];
4639             [fSrcChapterEndPopUp  setHidden: YES];
4640             
4641             [fSrcTimeStartEncodingField  setHidden: YES];
4642             [fSrcTimeEndEncodingField  setHidden: YES];
4643             
4644             [fSrcFrameStartEncodingField  setHidden: NO];
4645             [fSrcFrameEndEncodingField  setHidden: NO];
4646             
4647             [self startEndFrameValueChanged:nil];
4648         }
4649     }
4650 }
4651
4652 - (IBAction) chapterPopUpChanged: (id) sender
4653 {
4654
4655         /* If start chapter popup is greater than end chapter popup,
4656         we set the end chapter popup to the same as start chapter popup */
4657         if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4658         {
4659                 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4660     }
4661
4662                 
4663         hb_list_t  * list  = hb_get_titles( fHandle );
4664     hb_title_t * title = (hb_title_t *)
4665         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4666
4667     hb_chapter_t * chapter;
4668     int64_t        duration = 0;
4669     for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4670          i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4671     {
4672         chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4673         duration += chapter->duration;
4674     }
4675     
4676     duration /= 90000; /* pts -> seconds */
4677     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4678         @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4679         duration % 60]];
4680     
4681     [self calculateBitrate: sender];
4682     
4683     if ( [fSrcChapterStartPopUp indexOfSelectedItem] ==  [fSrcChapterEndPopUp indexOfSelectedItem] )
4684     {
4685     /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4686     [fCreateChapterMarkers setEnabled: NO];
4687     [fCreateChapterMarkers setState: NSOffState];
4688     }
4689     else
4690     {
4691     [fCreateChapterMarkers setEnabled: YES];
4692     }
4693 }
4694
4695 - (IBAction) startEndSecValueChanged: (id) sender
4696 {
4697
4698         int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4699     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4700         @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4701         duration % 60]];
4702     
4703     //[self calculateBitrate: sender];
4704     
4705 }
4706
4707 - (IBAction) startEndFrameValueChanged: (id) sender
4708 {
4709     hb_list_t  * list  = hb_get_titles( fHandle );
4710     hb_title_t * title = (hb_title_t*)
4711     hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4712     
4713     int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4714     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4715                                          @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4716                                          duration % 60]];
4717     
4718     //[self calculateBitrate: sender];
4719 }
4720
4721
4722 - (IBAction) formatPopUpChanged: (id) sender
4723 {
4724     NSString * string = [fDstFile2Field stringValue];
4725     int format = [fDstFormatPopUp indexOfSelectedItem];
4726     char * ext = NULL;
4727         /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4728     [fDstMp4LargeFileCheck setHidden: YES];
4729     [fDstMp4HttpOptFileCheck setHidden: YES];
4730     [fDstMp4iPodFileCheck setHidden: YES];
4731     
4732     /* Update the Video Codec PopUp */
4733     /* lets get the tag of the currently selected item first so we might reset it later */
4734     int selectedVidEncoderTag;
4735     selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4736     
4737     /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4738     [fVidEncoderPopUp removeAllItems];
4739     NSMenuItem *menuItem;
4740     /* These video encoders are available to all of our current muxers, so lets list them once here */
4741     menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4742     [menuItem setTag: HB_VCODEC_FFMPEG];
4743     
4744     switch( format )
4745     {
4746         case 0:
4747                         /*Get Default MP4 File Extension*/
4748                         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4749                         {
4750                                 ext = "m4v";
4751                         }
4752                         else
4753                         {
4754                                 ext = "mp4";
4755                         }
4756             /* Add additional video encoders here */
4757             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4758             [menuItem setTag: HB_VCODEC_X264];
4759             /* We show the mp4 option checkboxes here since we are mp4 */
4760             [fCreateChapterMarkers setEnabled: YES];
4761                         [fDstMp4LargeFileCheck setHidden: NO];
4762                         [fDstMp4HttpOptFileCheck setHidden: NO];
4763             [fDstMp4iPodFileCheck setHidden: NO];
4764             break;
4765             
4766             case 1:
4767             ext = "mkv";
4768             /* Add additional video encoders here */
4769             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4770             [menuItem setTag: HB_VCODEC_X264];
4771             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4772             [menuItem setTag: HB_VCODEC_THEORA];
4773             /* We enable the create chapters checkbox here */
4774                         [fCreateChapterMarkers setEnabled: YES];
4775                         break;
4776             
4777
4778     }
4779     /* tell fSubtitlesDelegate we have a new video container */
4780     
4781     [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4782     [fSubtitlesTable reloadData];
4783     /* if we have a previously selected vid encoder tag, then try to select it */
4784     if (selectedVidEncoderTag)
4785     {
4786         [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4787     }
4788     else
4789     {
4790         [fVidEncoderPopUp selectItemAtIndex: 0];
4791     }
4792
4793     [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4794     [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4795     [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4796     [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4797
4798     if( format == 0 )
4799         [self autoSetM4vExtension: sender];
4800     else
4801         [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4802
4803     if( SuccessfulScan )
4804     {
4805         /* Add/replace to the correct extension */
4806         [self audioTrackPopUpChanged: fAudLang1PopUp];
4807         [self audioTrackPopUpChanged: fAudLang2PopUp];
4808         [self audioTrackPopUpChanged: fAudLang3PopUp];
4809         [self audioTrackPopUpChanged: fAudLang4PopUp];
4810
4811         if( [fVidEncoderPopUp selectedItem] == nil )
4812         {
4813
4814             [fVidEncoderPopUp selectItemAtIndex:0];
4815             [self videoEncoderPopUpChanged:nil];
4816
4817             /* changing the format may mean that we can / can't offer mono or 6ch, */
4818             /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4819
4820             /* We call the method to properly enable/disable turbo 2 pass */
4821             [self twoPassCheckboxChanged: sender];
4822             /* We call method method to change UI to reflect whether a preset is used or not*/
4823         }
4824     }
4825         [self customSettingUsed: sender];
4826 }
4827
4828 - (IBAction) autoSetM4vExtension: (id) sender
4829 {
4830     if ( [fDstFormatPopUp indexOfSelectedItem] )
4831         return;
4832
4833     NSString * extension = @"mp4";
4834
4835     if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4836                                                         [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4837                                                         [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4838                                                         [fCreateChapterMarkers state] == NSOnState ||
4839                                                         [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4840     {
4841         extension = @"m4v";
4842     }
4843
4844     if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4845         return;
4846     else
4847         [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4848                                     [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4849 }
4850
4851 /* Method to determine if we should change the UI
4852 To reflect whether or not a Preset is being used or if
4853 the user is using "Custom" settings by determining the sender*/
4854 - (IBAction) customSettingUsed: (id) sender
4855 {
4856         if ([sender stringValue])
4857         {
4858                 /* Deselect the currently selected Preset if there is one*/
4859                 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4860                 /* Change UI to show "Custom" settings are being used */
4861                 [fPresetSelectedDisplay setStringValue: @"Custom"];
4862
4863                 curUserPresetChosenNum = nil;
4864         }
4865 [self calculateBitrate:nil];
4866 }
4867
4868
4869 #pragma mark -
4870 #pragma mark - Video
4871
4872 - (IBAction) videoEncoderPopUpChanged: (id) sender
4873 {
4874     hb_job_t * job = fTitle->job;
4875     int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4876     
4877     [fAdvancedOptions setHidden:YES];
4878     /* If we are using x264 then show the x264 advanced panel*/
4879     if (videoEncoder == HB_VCODEC_X264)
4880     {
4881         [fAdvancedOptions setHidden:NO];
4882         [self autoSetM4vExtension: sender];
4883     }
4884
4885     if (videoEncoder == HB_VCODEC_FFMPEG)
4886     {
4887         /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4888          container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4889          anything other than MP4.
4890          */ 
4891         [fDstMp4iPodFileCheck setEnabled: NO];
4892         [fDstMp4iPodFileCheck setState: NSOffState];
4893     }
4894     else
4895     {
4896         [fDstMp4iPodFileCheck setEnabled: YES];
4897     }
4898     [self setupQualitySlider];
4899         [self calculatePictureSizing: sender];
4900         [self twoPassCheckboxChanged: sender];
4901 }
4902
4903
4904 - (IBAction) twoPassCheckboxChanged: (id) sender
4905 {
4906         /* check to see if x264 is chosen */
4907         if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4908     {
4909                 if( [fVidTwoPassCheck state] == NSOnState)
4910                 {
4911                         [fVidTurboPassCheck setHidden: NO];
4912                 }
4913                 else
4914                 {
4915                         [fVidTurboPassCheck setHidden: YES];
4916                         [fVidTurboPassCheck setState: NSOffState];
4917                 }
4918                 /* Make sure Two Pass is checked if Turbo is checked */
4919                 if( [fVidTurboPassCheck state] == NSOnState)
4920                 {
4921                         [fVidTwoPassCheck setState: NSOnState];
4922                 }
4923         }
4924         else
4925         {
4926                 [fVidTurboPassCheck setHidden: YES];
4927                 [fVidTurboPassCheck setState: NSOffState];
4928         }
4929         
4930         /* We call method method to change UI to reflect whether a preset is used or not*/
4931         [self customSettingUsed: sender];
4932 }
4933
4934 - (IBAction ) videoFrameRateChanged: (id) sender
4935 {
4936     /* We call method method to calculatePictureSizing to error check detelecine*/
4937     [self calculatePictureSizing: sender];
4938
4939     /* We call method method to change UI to reflect whether a preset is used or not*/
4940         [self customSettingUsed: sender];
4941 }
4942 - (IBAction) videoMatrixChanged: (id) sender;
4943 {
4944     bool target, bitrate, quality;
4945
4946     target = bitrate = quality = false;
4947     if( [fVidQualityMatrix isEnabled] )
4948     {
4949         switch( [fVidQualityMatrix selectedRow] )
4950         {
4951             case 0:
4952                 target = true;
4953                 break;
4954             case 1:
4955                 bitrate = true;
4956                 break;
4957             case 2:
4958                 quality = true;
4959                 break;
4960         }
4961     }
4962     [fVidTargetSizeField  setEnabled: target];
4963     [fVidBitrateField     setEnabled: bitrate];
4964     [fVidQualitySlider    setEnabled: quality];
4965     [fVidQualityRFField   setEnabled: quality];
4966     [fVidQualityRFLabel    setEnabled: quality];
4967     [fVidTwoPassCheck     setEnabled: !quality &&
4968         [fVidQualityMatrix isEnabled]];
4969     if( quality )
4970     {
4971         [fVidTwoPassCheck setState: NSOffState];
4972                 [fVidTurboPassCheck setHidden: YES];
4973                 [fVidTurboPassCheck setState: NSOffState];
4974     }
4975
4976     [self qualitySliderChanged: sender];
4977     [self calculateBitrate: sender];
4978         [self customSettingUsed: sender];
4979 }
4980
4981 /* Use this method to setup the quality slider for cq/rf values depending on
4982  * the video encoder selected.
4983  */
4984 - (void) setupQualitySlider
4985 {
4986     /* Get the current slider maxValue to check for a change in slider scale later
4987      * so that we can choose a new similar value on the new slider scale */
4988     float previousMaxValue = [fVidQualitySlider maxValue];
4989     float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4990     NSString * qpRFLabelString = @"QP:";
4991     /* x264 0-51 */
4992     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4993     {
4994         [fVidQualitySlider setMinValue:0.0];
4995         [fVidQualitySlider setMaxValue:51.0];
4996         /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4997         int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4998         [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4999         qpRFLabelString = @"RF:";
5000     }
5001     /* ffmpeg  1-31 */
5002     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
5003     {
5004         [fVidQualitySlider setMinValue:1.0];
5005         [fVidQualitySlider setMaxValue:31.0];
5006         [fVidQualitySlider setNumberOfTickMarks:31];
5007     }
5008     /* Theora 0-63 */
5009     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5010     {
5011         [fVidQualitySlider setMinValue:0.0];
5012         [fVidQualitySlider setMaxValue:63.0];
5013         [fVidQualitySlider setNumberOfTickMarks:64];
5014     }
5015     [fVidQualityRFLabel setStringValue:qpRFLabelString];
5016     
5017     /* check to see if we have changed slider scales */
5018     if (previousMaxValue != [fVidQualitySlider maxValue])
5019     {
5020         /* if so, convert the old setting to the new scale as close as possible based on percentages */
5021         float rf =  ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
5022         [fVidQualitySlider setFloatValue:rf];
5023     }
5024     
5025     [self qualitySliderChanged:nil];
5026 }
5027
5028 - (IBAction) qualitySliderChanged: (id) sender
5029 {
5030     /* Our constant quality slider is in a range based
5031      * on each encoders qp/rf values. The range depends
5032      * on the encoder. Also, the range is inverse of quality
5033      * for all of the encoders *except* for theora
5034      * (ie. as the "quality" goes up, the cq or rf value
5035      * actually goes down). Since the IB sliders always set
5036      * their max value at the right end of the slider, we
5037      * will calculate the inverse, so as the slider floatValue
5038      * goes up, we will show the inverse in the rf field
5039      * so, the floatValue at the right for x264 would be 51
5040      * and our rf field needs to show 0 and vice versa.
5041      */
5042     
5043     float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5044     /* If the encoder is theora, use the float, otherwise use the inverse float*/
5045     //float sliderRfToPercent;
5046     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5047     {
5048         [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];   
5049     }
5050     else
5051     {
5052         [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5053     }
5054     [self customSettingUsed: sender];
5055 }
5056
5057 - (void) controlTextDidChange: (NSNotification *) notification
5058 {
5059     [self calculateBitrate:nil];
5060 }
5061
5062 - (IBAction) calculateBitrate: (id) sender
5063 {
5064     if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5065     {
5066         return;
5067     }
5068
5069     hb_list_t  * list  = hb_get_titles( fHandle );
5070     hb_title_t * title = (hb_title_t *) hb_list_item( list,
5071             [fSrcTitlePopUp indexOfSelectedItem] );
5072     hb_job_t * job = title->job;
5073     hb_audio_config_t * audio;
5074     /* For  hb_calc_bitrate in addition to the Target Size in MB out of the
5075      * Target Size Field, we also need the job info for the Muxer, the Chapters
5076      * as well as all of the audio track info.
5077      * This used to be accomplished by simply calling prepareJob here, however
5078      * since the resilient queue sets the queue array values instead of the job
5079      * values directly, we duplicate the old prepareJob code here for the variables
5080      * needed
5081      */
5082     job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5083     job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1; 
5084     job->mux = [[fDstFormatPopUp selectedItem] tag];
5085     
5086     /* Audio goes here */
5087     int audiotrack_count = hb_list_count(job->list_audio);
5088     for( int i = 0; i < audiotrack_count;i++)
5089     {
5090         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5091         hb_list_rem(job->list_audio, temp_audio);
5092     }
5093     /* Now we need our audio info here for each track if applicable */
5094     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5095     {
5096         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5097         hb_audio_config_init(audio);
5098         audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5099         /* We go ahead and assign values to our audio->out.<properties> */
5100         audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5101         audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5102         audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5103         audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5104         audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5105         audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5106         
5107         hb_audio_add( job, audio );
5108         free(audio);
5109     }  
5110     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5111     {
5112         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5113         hb_audio_config_init(audio);
5114         audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5115         /* We go ahead and assign values to our audio->out.<properties> */
5116         audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5117         audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5118         audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5119         audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5120         audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5121         audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5122         
5123         hb_audio_add( job, audio );
5124         free(audio);
5125         
5126     }
5127     
5128     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5129     {
5130         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5131         hb_audio_config_init(audio);
5132         audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5133         /* We go ahead and assign values to our audio->out.<properties> */
5134         audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5135         audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5136         audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5137         audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5138         audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5139         audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5140         
5141         hb_audio_add( job, audio );
5142         free(audio);
5143         
5144     }
5145
5146     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5147     {
5148         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5149         hb_audio_config_init(audio);
5150         audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5151         /* We go ahead and assign values to our audio->out.<properties> */
5152         audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5153         audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5154         audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5155         audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5156         audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5157         audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5158         
5159         hb_audio_add( job, audio );
5160         free(audio);
5161         
5162     }
5163        
5164 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5165 }
5166
5167 #pragma mark -
5168 #pragma mark - Picture
5169
5170 /* lets set the picture size back to the max from right after title scan
5171    Lets use an IBAction here as down the road we could always use a checkbox
5172    in the gui to easily take the user back to max. Remember, the compiler
5173    resolves IBActions down to -(void) during compile anyway */
5174 - (IBAction) revertPictureSizeToMax: (id) sender
5175 {
5176         hb_job_t * job = fTitle->job;
5177         /* Here we apply the title source and height */
5178     job->width = fTitle->width;
5179     job->height = fTitle->height;
5180     
5181     [self calculatePictureSizing: sender];
5182     /* We call method to change UI to reflect whether a preset is used or not*/    
5183     [self customSettingUsed: sender];
5184 }
5185
5186 /**
5187  * Registers changes made in the Picture Settings Window.
5188  */
5189
5190 - (void)pictureSettingsDidChange 
5191 {
5192         [self calculatePictureSizing:nil];
5193 }
5194
5195 /* Get and Display Current Pic Settings in main window */
5196 - (IBAction) calculatePictureSizing: (id) sender
5197 {
5198         if (fTitle->job->anamorphic.mode > 0)
5199         {
5200         fTitle->job->keep_ratio = 0;
5201         }
5202     
5203     if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5204         {
5205         [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5206     }
5207     else
5208     {
5209         [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5210     }
5211     NSString *picCropping;
5212     /* Set the display field for crop as per boolean */
5213         if (![fPictureController autoCrop])
5214         {
5215         picCropping =  @"Custom";
5216         }
5217         else
5218         {
5219                 picCropping =  @"Auto";
5220         }
5221     picCropping = [picCropping stringByAppendingString:[NSString stringWithFormat:@" %d/%d/%d/%d",fTitle->job->crop[0],fTitle->job->crop[1],fTitle->job->crop[2],fTitle->job->crop[3]]];
5222     
5223     [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5224     
5225     NSString *videoFilters;
5226     videoFilters = @"";
5227     /* Detelecine */
5228     if ([fPictureController detelecine] == 2) 
5229     {
5230         videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5231     }
5232     else if ([fPictureController detelecine] == 1) 
5233     {
5234         videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5235     }
5236     
5237     
5238     if ([fPictureController useDecomb] == 1)
5239     {
5240         /* Decomb */
5241         if ([fPictureController decomb] == 2)
5242         {
5243             videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5244         }
5245         else if ([fPictureController decomb] == 1)
5246         {
5247             videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5248         }
5249     }
5250     else
5251     {
5252         /* Deinterlace */
5253         if ([fPictureController deinterlace] > 0)
5254         {
5255             fTitle->job->deinterlace  = 1;
5256         }
5257         else
5258         {
5259             fTitle->job->deinterlace  = 0;
5260         }
5261         
5262         if ([fPictureController deinterlace] == 2)
5263         {
5264             videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5265         }
5266         else if ([fPictureController deinterlace] == 3)
5267         {
5268             videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5269         }
5270         else if ([fPictureController deinterlace] == 4)
5271         {
5272             videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5273         }
5274         else if ([fPictureController deinterlace] == 1)
5275         {
5276             videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5277         }
5278         }
5279     
5280     
5281     /* Denoise */
5282         if ([fPictureController denoise] == 2)
5283         {
5284                 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5285     }
5286         else if ([fPictureController denoise] == 3)
5287         {
5288                 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5289     }
5290         else if ([fPictureController denoise] == 4)
5291         {
5292                 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5293         }
5294     else if ([fPictureController denoise] == 1)
5295         {
5296                 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5297         }
5298     
5299     /* Deblock */
5300     if ([fPictureController deblock] > 0) 
5301     {
5302         videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5303     }
5304         
5305     /* Grayscale */
5306     if ([fPictureController grayscale]) 
5307     {
5308         videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5309     }
5310     [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5311     
5312     //[fPictureController reloadStillPreview]; 
5313 }
5314
5315
5316 #pragma mark -
5317 #pragma mark - Audio and Subtitles
5318 - (IBAction) audioCodecsPopUpChanged: (id) sender
5319 {
5320     
5321     NSPopUpButton * audiotrackPopUp;
5322     NSPopUpButton * sampleratePopUp;
5323     NSPopUpButton * bitratePopUp;
5324     NSPopUpButton * audiocodecPopUp;
5325     if (sender == fAudTrack1CodecPopUp)
5326     {
5327         audiotrackPopUp = fAudLang1PopUp;
5328         audiocodecPopUp = fAudTrack1CodecPopUp;
5329         sampleratePopUp = fAudTrack1RatePopUp;
5330         bitratePopUp = fAudTrack1BitratePopUp;
5331     }
5332     else if (sender == fAudTrack2CodecPopUp)
5333     {
5334         audiotrackPopUp = fAudLang2PopUp;
5335         audiocodecPopUp = fAudTrack2CodecPopUp;
5336         sampleratePopUp = fAudTrack2RatePopUp;
5337         bitratePopUp = fAudTrack2BitratePopUp;
5338     }
5339     else if (sender == fAudTrack3CodecPopUp)
5340     {
5341         audiotrackPopUp = fAudLang3PopUp;
5342         audiocodecPopUp = fAudTrack3CodecPopUp;
5343         sampleratePopUp = fAudTrack3RatePopUp;
5344         bitratePopUp = fAudTrack3BitratePopUp;
5345     }
5346     else
5347     {
5348         audiotrackPopUp = fAudLang4PopUp;
5349         audiocodecPopUp = fAudTrack4CodecPopUp;
5350         sampleratePopUp = fAudTrack4RatePopUp;
5351         bitratePopUp = fAudTrack4BitratePopUp;
5352     }
5353         
5354     /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5355         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5356     [self audioTrackPopUpChanged: audiotrackPopUp];
5357     
5358 }
5359
5360 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5361 {
5362     /* We will be setting the enabled/disabled state of each tracks audio controls based on
5363      * the settings of the source audio for that track. We leave the samplerate and bitrate
5364      * to audiotrackMixdownChanged
5365      */
5366     
5367     /* We will first verify that a lower track number has been selected before enabling each track
5368      * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5369      */
5370     if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5371     {
5372         [fAudLang2PopUp setEnabled: NO];
5373         [fAudLang2PopUp selectItemAtIndex: 0];
5374     }
5375     else
5376     {
5377         [fAudLang2PopUp setEnabled: YES];
5378     }
5379     
5380     if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5381     {
5382         [fAudLang3PopUp setEnabled: NO];
5383         [fAudLang3PopUp selectItemAtIndex: 0];
5384     }
5385     else
5386     {
5387         [fAudLang3PopUp setEnabled: YES];
5388     }
5389     if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5390     {
5391         [fAudLang4PopUp setEnabled: NO];
5392         [fAudLang4PopUp selectItemAtIndex: 0];
5393     }
5394     else
5395     {
5396         [fAudLang4PopUp setEnabled: YES];
5397     }
5398     /* enable/disable the mixdown text and popupbutton for audio track 1 */
5399     [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5400     [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5401     [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5402     [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5403     [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5404     [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5405     if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5406     {
5407         [fAudTrack1CodecPopUp removeAllItems];
5408         [fAudTrack1MixPopUp removeAllItems];
5409         [fAudTrack1RatePopUp removeAllItems];
5410         [fAudTrack1BitratePopUp removeAllItems];
5411         [fAudTrack1DrcSlider setFloatValue: 0.00];
5412         [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5413     }
5414     else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5415     {
5416         [fAudTrack1RatePopUp setEnabled: NO];
5417         [fAudTrack1BitratePopUp setEnabled: NO];
5418         [fAudTrack1DrcSlider setEnabled: NO];
5419         [fAudTrack1DrcField setEnabled: NO];
5420     }
5421     
5422     /* enable/disable the mixdown text and popupbutton for audio track 2 */
5423     [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5424     [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5425     [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5426     [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5427     [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5428     [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5429     if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5430     {
5431         [fAudTrack2CodecPopUp removeAllItems];
5432         [fAudTrack2MixPopUp removeAllItems];
5433         [fAudTrack2RatePopUp removeAllItems];
5434         [fAudTrack2BitratePopUp removeAllItems];
5435         [fAudTrack2DrcSlider setFloatValue: 0.00];
5436         [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5437     }
5438     else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5439     {
5440         [fAudTrack2RatePopUp setEnabled: NO];
5441         [fAudTrack2BitratePopUp setEnabled: NO];
5442         [fAudTrack2DrcSlider setEnabled: NO];
5443         [fAudTrack2DrcField setEnabled: NO];
5444     }
5445     
5446     /* enable/disable the mixdown text and popupbutton for audio track 3 */
5447     [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5448     [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5449     [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5450     [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5451     [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5452     [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5453     if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5454     {
5455         [fAudTrack3CodecPopUp removeAllItems];
5456         [fAudTrack3MixPopUp removeAllItems];
5457         [fAudTrack3RatePopUp removeAllItems];
5458         [fAudTrack3BitratePopUp removeAllItems];
5459         [fAudTrack3DrcSlider setFloatValue: 0.00];
5460         [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5461     }
5462     else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5463     {
5464         [fAudTrack3RatePopUp setEnabled: NO];
5465         [fAudTrack3BitratePopUp setEnabled: NO];
5466         [fAudTrack3DrcSlider setEnabled: NO];
5467         [fAudTrack3DrcField setEnabled: NO];
5468     }
5469     
5470     /* enable/disable the mixdown text and popupbutton for audio track 4 */
5471     [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5472     [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5473     [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5474     [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5475     [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5476     [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5477     if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5478     {
5479         [fAudTrack4CodecPopUp removeAllItems];
5480         [fAudTrack4MixPopUp removeAllItems];
5481         [fAudTrack4RatePopUp removeAllItems];
5482         [fAudTrack4BitratePopUp removeAllItems];
5483         [fAudTrack4DrcSlider setFloatValue: 0.00];
5484         [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5485     }
5486     else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5487     {
5488         [fAudTrack4RatePopUp setEnabled: NO];
5489         [fAudTrack4BitratePopUp setEnabled: NO];
5490         [fAudTrack4DrcSlider setEnabled: NO];
5491         [fAudTrack4DrcField setEnabled: NO];
5492     }
5493     
5494 }
5495
5496 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5497 {
5498
5499     hb_list_t  * list  = hb_get_titles( fHandle );
5500     hb_title_t * title = (hb_title_t*)
5501         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5502
5503         hb_audio_config_t * audio;
5504
5505     [sender removeAllItems];
5506     [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5507     for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5508     {
5509         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5510         [[sender menu] addItemWithTitle:
5511             [NSString stringWithUTF8String: audio->lang.description]
5512             action: NULL keyEquivalent: @""];
5513     }
5514     [sender selectItemAtIndex: 0];
5515
5516 }
5517
5518 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5519 {
5520
5521     /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5522     /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5523     /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5524     /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5525
5526         if (searchPrefixString)
5527         {
5528
5529         for( int i = 0; i < [sender numberOfItems]; i++ )
5530         {
5531             /* Try to find the desired search string */
5532             if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5533             {
5534                 [sender selectItemAtIndex: i];
5535                 return;
5536             }
5537         }
5538         /* couldn't find the string, so select the requested "search string not found" item */
5539         /* index of 0 means select the "none" item */
5540         /* index of 1 means select the first audio track */
5541         [sender selectItemAtIndex: selectIndexIfNotFound];
5542         }
5543     else
5544     {
5545         /* if no search string is provided, then select the selectIndexIfNotFound item */
5546         [sender selectItemAtIndex: selectIndexIfNotFound];
5547     }
5548
5549 }
5550 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5551 {
5552     int format = [fDstFormatPopUp indexOfSelectedItem];
5553     
5554     /* setup pointers to the appropriate popups for the correct track */
5555     NSPopUpButton * audiocodecPopUp;
5556     NSPopUpButton * audiotrackPopUp;
5557     if (sender == fAudTrack1CodecPopUp)
5558     {
5559         audiotrackPopUp = fAudLang1PopUp;
5560         audiocodecPopUp = fAudTrack1CodecPopUp;
5561     }
5562     else if (sender == fAudTrack2CodecPopUp)
5563     {
5564         audiotrackPopUp = fAudLang2PopUp;
5565         audiocodecPopUp = fAudTrack2CodecPopUp;
5566     }
5567     else if (sender == fAudTrack3CodecPopUp)
5568     {
5569         audiotrackPopUp = fAudLang3PopUp;
5570         audiocodecPopUp = fAudTrack3CodecPopUp;
5571     }
5572     else
5573     {
5574         audiotrackPopUp = fAudLang4PopUp;
5575         audiocodecPopUp = fAudTrack4CodecPopUp;
5576     }
5577     
5578     [audiocodecPopUp removeAllItems];
5579     /* Make sure "None" isnt selected in the source track */
5580     if ([audiotrackPopUp indexOfSelectedItem] > 0)
5581     {
5582         [audiocodecPopUp setEnabled:YES];
5583         NSMenuItem *menuItem;
5584         /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5585         switch( format )
5586         {
5587             case 0:
5588                 /* MP4 */
5589                 // FAAC
5590                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5591                 [menuItem setTag: HB_ACODEC_FAAC];
5592
5593                 // CA_AAC
5594                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5595                 [menuItem setTag: HB_ACODEC_CA_AAC];
5596
5597                 // AC3 Passthru
5598                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5599                 [menuItem setTag: HB_ACODEC_AC3];
5600                 break;
5601                 
5602             case 1:
5603                 /* MKV */
5604                 // FAAC
5605                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5606                 [menuItem setTag: HB_ACODEC_FAAC];
5607                 // CA_AAC
5608                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5609                 [menuItem setTag: HB_ACODEC_CA_AAC];
5610                 // AC3 Passthru
5611                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5612                 [menuItem setTag: HB_ACODEC_AC3];
5613                 // DTS Passthru
5614                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5615                 [menuItem setTag: HB_ACODEC_DCA];
5616                 // MP3
5617                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5618                 [menuItem setTag: HB_ACODEC_LAME];
5619                 // Vorbis
5620                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5621                 [menuItem setTag: HB_ACODEC_VORBIS];
5622                 break;
5623                 
5624             case 2: 
5625                 /* AVI */
5626                 // MP3
5627                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5628                 [menuItem setTag: HB_ACODEC_LAME];
5629                 // AC3 Passthru
5630                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5631                 [menuItem setTag: HB_ACODEC_AC3];
5632                 break;
5633                 
5634             case 3:
5635                 /* OGM */
5636                 // Vorbis
5637                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5638                 [menuItem setTag: HB_ACODEC_VORBIS];
5639                 // MP3
5640                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5641                 [menuItem setTag: HB_ACODEC_LAME];
5642                 break;
5643         }
5644         [audiocodecPopUp selectItemAtIndex:0];
5645     }
5646     else
5647     {
5648         [audiocodecPopUp setEnabled:NO];
5649     }
5650 }
5651
5652 - (IBAction) audioTrackPopUpChanged: (id) sender
5653 {
5654     /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5655     [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5656 }
5657
5658 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5659 {
5660     
5661     /* make sure we have a selected title before continuing */
5662     if (fTitle == NULL) return;
5663     /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5664     * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5665     */
5666     if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5667     {
5668         [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5669     }
5670     if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5671     {
5672         [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5673     }
5674     if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5675     {
5676         [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5677     }
5678     if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5679     {
5680         [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5681     }
5682     
5683     /* Now lets make the sender the appropriate Audio Track popup from this point on */
5684     if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5685     {
5686         sender = fAudLang1PopUp;
5687     }
5688     if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5689     {
5690         sender = fAudLang2PopUp;
5691     }
5692     if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5693     {
5694         sender = fAudLang3PopUp;
5695     }
5696     if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5697     {
5698         sender = fAudLang4PopUp;
5699     }
5700     
5701     /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5702     NSPopUpButton * mixdownPopUp;
5703     NSPopUpButton * audiocodecPopUp;
5704     NSPopUpButton * sampleratePopUp;
5705     NSPopUpButton * bitratePopUp;
5706     if (sender == fAudLang1PopUp)
5707     {
5708         mixdownPopUp = fAudTrack1MixPopUp;
5709         audiocodecPopUp = fAudTrack1CodecPopUp;
5710         sampleratePopUp = fAudTrack1RatePopUp;
5711         bitratePopUp = fAudTrack1BitratePopUp;
5712     }
5713     else if (sender == fAudLang2PopUp)
5714     {
5715         mixdownPopUp = fAudTrack2MixPopUp;
5716         audiocodecPopUp = fAudTrack2CodecPopUp;
5717         sampleratePopUp = fAudTrack2RatePopUp;
5718         bitratePopUp = fAudTrack2BitratePopUp;
5719     }
5720     else if (sender == fAudLang3PopUp)
5721     {
5722         mixdownPopUp = fAudTrack3MixPopUp;
5723         audiocodecPopUp = fAudTrack3CodecPopUp;
5724         sampleratePopUp = fAudTrack3RatePopUp;
5725         bitratePopUp = fAudTrack3BitratePopUp;
5726     }
5727     else
5728     {
5729         mixdownPopUp = fAudTrack4MixPopUp;
5730         audiocodecPopUp = fAudTrack4CodecPopUp;
5731         sampleratePopUp = fAudTrack4RatePopUp;
5732         bitratePopUp = fAudTrack4BitratePopUp;
5733     }
5734
5735     /* get the index of the selected audio Track*/
5736     int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5737
5738     /* pointer for the hb_audio_s struct we will use later on */
5739     hb_audio_config_t * audio;
5740
5741     int acodec;
5742     /* check if the audio mixdown controls need their enabled state changing */
5743     [self setEnabledStateOfAudioMixdownControls:nil];
5744
5745     if (thisAudioIndex != -1)
5746     {
5747
5748         /* get the audio */
5749         audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5750
5751         /* actually manipulate the proper mixdowns here */
5752         /* delete the previous audio mixdown options */
5753         [mixdownPopUp removeAllItems];
5754
5755         acodec = [[audiocodecPopUp selectedItem] tag];
5756
5757         if (audio != NULL)
5758         {
5759
5760             /* find out if our selected output audio codec supports mono and / or 6ch */
5761             /* we also check for an input codec of AC3 or DCA,
5762              as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5763             /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5764              but this may change in the future, so they are separated for flexibility */
5765             int audioCodecsSupportMono =
5766                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5767                     (acodec != HB_ACODEC_LAME);
5768             int audioCodecsSupport6Ch =
5769                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5770                     (acodec != HB_ACODEC_LAME);
5771             
5772             /* check for AC-3 passthru */
5773             if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5774             {
5775                 
5776             NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5777                  [NSString stringWithUTF8String: "AC3 Passthru"]
5778                                                action: NULL keyEquivalent: @""];
5779              [menuItem setTag: HB_ACODEC_AC3];   
5780             }
5781             else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5782             {
5783             NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5784                  [NSString stringWithUTF8String: "DTS Passthru"]
5785                                                action: NULL keyEquivalent: @""];
5786              [menuItem setTag: HB_ACODEC_DCA]; 
5787             }
5788             else
5789             {
5790                 
5791                 /* add the appropriate audio mixdown menuitems to the popupbutton */
5792                 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5793                  so that we can reference the mixdown later */
5794                 
5795                 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5796                 int minMixdownUsed = 0;
5797                 int maxMixdownUsed = 0;
5798                 
5799                 /* get the input channel layout without any lfe channels */
5800                 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5801                 
5802                 /* do we want to add a mono option? */
5803                 if (audioCodecsSupportMono == 1)
5804                 {
5805                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5806                                             [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5807                                                                           action: NULL keyEquivalent: @""];
5808                     [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5809                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5810                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5811                 }
5812                 
5813                 /* do we want to add a stereo option? */
5814                 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5815                 /* also offer stereo if we have a stereo-or-better source */
5816                 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5817                 {
5818                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5819                                             [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5820                                                                           action: NULL keyEquivalent: @""];
5821                     [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5822                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5823                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5824                 }
5825                 
5826                 /* do we want to add a dolby surround (DPL1) option? */
5827                 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5828                 {
5829                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5830                                             [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5831                                                                           action: NULL keyEquivalent: @""];
5832                     [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5833                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5834                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5835                 }
5836                 
5837                 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5838                 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5839                 {
5840                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5841                                             [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5842                                                                           action: NULL keyEquivalent: @""];
5843                     [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5844                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5845                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5846                 }
5847                 
5848                 /* do we want to add a 6-channel discrete option? */
5849                 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5850                 {
5851                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5852                                             [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5853                                                                           action: NULL keyEquivalent: @""];
5854                     [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5855                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5856                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5857                 }
5858                 
5859                 /* do we want to add an AC-3 passthrough option? */
5860                 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3) 
5861                 {
5862                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5863                                             [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5864                                                                           action: NULL keyEquivalent: @""];
5865                     [menuItem setTag: HB_ACODEC_AC3];
5866                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5867                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5868                 }
5869                 
5870                 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5871                 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA) 
5872                 {
5873                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5874                                             [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5875                                                                           action: NULL keyEquivalent: @""];
5876                     [menuItem setTag: HB_ACODEC_DCA];
5877                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5878                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5879                 }
5880                 
5881                 /* auto-select the best mixdown based on our saved mixdown preference */
5882                 
5883                 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5884                 /* ultimately this should be a prefs option */
5885                 int useMixdown;
5886                 
5887                 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5888                 if (mixdownToUse > 0)
5889                 {
5890                     useMixdown = mixdownToUse;
5891                 }
5892                 else
5893                 {
5894                     useMixdown = HB_AMIXDOWN_DOLBYPLII;
5895                 }
5896                 
5897                 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5898                 if (useMixdown > maxMixdownUsed)
5899                 { 
5900                     useMixdown = maxMixdownUsed;
5901                 }
5902                 
5903                 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5904                 if (useMixdown < minMixdownUsed)
5905                 { 
5906                     useMixdown = minMixdownUsed;
5907                 }
5908                 
5909                 /* select the (possibly-amended) preferred mixdown */
5910                 [mixdownPopUp selectItemWithTag: useMixdown];
5911
5912             }
5913             /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5914              * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5915              * other containers.
5916              */
5917             if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5918             {
5919                 /* If we are using the avi container, we select MP3 as there is no aac available*/
5920                 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5921                 {
5922                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5923                 }
5924                 else
5925                 {
5926                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5927                 }
5928             }
5929             
5930             /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5931              * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5932              * other containers.
5933              */
5934             if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5935             {
5936                 /* If we are using the avi container, we select MP3 as there is no aac available*/
5937                 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5938                 {
5939                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5940                 }
5941                 else
5942                 {
5943                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5944                 }
5945             }
5946             
5947             /* Setup our samplerate and bitrate popups we will need based on mixdown */
5948             [self audioTrackMixdownChanged: mixdownPopUp];             
5949         }
5950     
5951     }
5952     if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5953     {
5954         [self autoSetM4vExtension: sender];
5955     }
5956 }
5957
5958 - (IBAction) audioTrackMixdownChanged: (id) sender
5959 {
5960     
5961     int acodec;
5962     /* setup pointers to all of the other audio track controls
5963     * we will need later
5964     */
5965     NSPopUpButton * mixdownPopUp;
5966     NSPopUpButton * sampleratePopUp;
5967     NSPopUpButton * bitratePopUp;
5968     NSPopUpButton * audiocodecPopUp;
5969     NSPopUpButton * audiotrackPopUp;
5970     NSSlider * drcSlider;
5971     NSTextField * drcField;
5972     if (sender == fAudTrack1MixPopUp)
5973     {
5974         audiotrackPopUp = fAudLang1PopUp;
5975         audiocodecPopUp = fAudTrack1CodecPopUp;
5976         mixdownPopUp = fAudTrack1MixPopUp;
5977         sampleratePopUp = fAudTrack1RatePopUp;
5978         bitratePopUp = fAudTrack1BitratePopUp;
5979         drcSlider = fAudTrack1DrcSlider;
5980         drcField = fAudTrack1DrcField;
5981     }
5982     else if (sender == fAudTrack2MixPopUp)
5983     {
5984         audiotrackPopUp = fAudLang2PopUp;
5985         audiocodecPopUp = fAudTrack2CodecPopUp;
5986         mixdownPopUp = fAudTrack2MixPopUp;
5987         sampleratePopUp = fAudTrack2RatePopUp;
5988         bitratePopUp = fAudTrack2BitratePopUp;
5989         drcSlider = fAudTrack2DrcSlider;
5990         drcField = fAudTrack2DrcField;
5991     }
5992     else if (sender == fAudTrack3MixPopUp)
5993     {
5994         audiotrackPopUp = fAudLang3PopUp;
5995         audiocodecPopUp = fAudTrack3CodecPopUp;
5996         mixdownPopUp = fAudTrack3MixPopUp;
5997         sampleratePopUp = fAudTrack3RatePopUp;
5998         bitratePopUp = fAudTrack3BitratePopUp;
5999         drcSlider = fAudTrack3DrcSlider;
6000         drcField = fAudTrack3DrcField;
6001     }
6002     else
6003     {
6004         audiotrackPopUp = fAudLang4PopUp;
6005         audiocodecPopUp = fAudTrack4CodecPopUp;
6006         mixdownPopUp = fAudTrack4MixPopUp;
6007         sampleratePopUp = fAudTrack4RatePopUp;
6008         bitratePopUp = fAudTrack4BitratePopUp;
6009         drcSlider = fAudTrack4DrcSlider;
6010         drcField = fAudTrack4DrcField;
6011     }
6012     acodec = [[audiocodecPopUp selectedItem] tag];
6013     /* storage variable for the min and max bitrate allowed for this codec */
6014     int minbitrate;
6015     int maxbitrate;
6016     
6017     switch( acodec )
6018     {
6019         case HB_ACODEC_FAAC:
6020             /* check if we have a 6ch discrete conversion in either audio track */
6021             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6022             {
6023                 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
6024                 minbitrate = 192;
6025                 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
6026                 maxbitrate = 448;
6027                 break;
6028             }
6029             else
6030             {
6031                 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
6032                 minbitrate = 32;
6033                 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
6034                 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
6035                 maxbitrate = 160;
6036                 break;
6037             }
6038
6039         case HB_ACODEC_CA_AAC:
6040             /* check if we have a 6ch discrete conversion in either audio track */
6041             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6042             {
6043                 minbitrate = 128;
6044                 maxbitrate = 768;
6045                 break;
6046             }
6047             else
6048             {
6049                 minbitrate = 64;
6050                 maxbitrate = 320;
6051                 break;
6052             }
6053
6054             case HB_ACODEC_LAME:
6055             /* Lame is happy using our min bitrate of 32 kbps */
6056             minbitrate = 32;
6057             /* Lame won't encode if the bitrate is higher than 320 kbps */
6058             maxbitrate = 320;
6059             break;
6060             
6061             case HB_ACODEC_VORBIS:
6062             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6063             {
6064                 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6065                 minbitrate = 192;
6066                 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6067                 maxbitrate = 384;
6068                 break;
6069             }
6070             else
6071             {
6072                 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6073                 minbitrate = 48;
6074                 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6075                 maxbitrate = 384;
6076                 break;
6077             }
6078             
6079             default:
6080             /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6081             minbitrate = 32;
6082             maxbitrate = 384;
6083             
6084     }
6085     
6086     /* make sure we have a selected title before continuing */
6087     if (fTitle == NULL) return;
6088     /* get the audio so we can find out what input rates are*/
6089     hb_audio_config_t * audio;
6090     audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6091     int inputbitrate = audio->in.bitrate / 1000;
6092     int inputsamplerate = audio->in.samplerate;
6093     
6094     if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6095     {
6096         [bitratePopUp removeAllItems];
6097         
6098         for( int i = 0; i < hb_audio_bitrates_count; i++ )
6099         {
6100             if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6101             {
6102                 /* add a new menuitem for this bitrate */
6103                 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6104                                         [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6105                                                                       action: NULL keyEquivalent: @""];
6106                 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6107                 [menuItem setTag: hb_audio_bitrates[i].rate];
6108             }
6109         }
6110         
6111         /* select the default bitrate (but use 384 for 6-ch AAC) */
6112         if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6113         {
6114             [bitratePopUp selectItemWithTag: 384];
6115         }
6116         else
6117         {
6118             [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6119         }
6120     }
6121     /* populate and set the sample rate popup */
6122     /* Audio samplerate */
6123     [sampleratePopUp removeAllItems];
6124     /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6125     NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6126     [menuItem setTag: inputsamplerate];
6127     
6128     for( int i = 0; i < hb_audio_rates_count; i++ )
6129     {
6130         NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6131                                 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6132                                                                  action: NULL keyEquivalent: @""];
6133         [menuItem setTag: hb_audio_rates[i].rate];
6134     }
6135     /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6136     * and there is no compelling reason to use anything else as default, though the users default
6137     * preset will likely override any setting chosen here.
6138     */
6139     [sampleratePopUp selectItemWithTag: inputsamplerate];
6140     
6141     
6142     /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6143     * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6144     * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6145     */
6146     if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6147     {
6148         
6149         /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6150         [bitratePopUp removeAllItems];
6151         NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6152                                 [NSString stringWithFormat:@"%d", inputbitrate]
6153                                                               action: NULL keyEquivalent: @""];
6154         [menuItem setTag: inputbitrate];
6155         /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6156         [bitratePopUp setEnabled: NO];
6157         [sampleratePopUp setEnabled: NO];
6158         
6159         [drcSlider setFloatValue: 0.00];
6160         [self audioDRCSliderChanged: drcSlider];
6161         [drcSlider setEnabled: NO];
6162         [drcField setEnabled: NO];
6163     }
6164     else
6165     {
6166         [sampleratePopUp setEnabled: YES];
6167         [bitratePopUp setEnabled: YES];
6168         [drcSlider setEnabled: YES];
6169         [drcField setEnabled: YES];
6170     }
6171 [self calculateBitrate:nil];    
6172 }
6173
6174 - (IBAction) audioDRCSliderChanged: (id) sender
6175 {
6176     NSSlider * drcSlider;
6177     NSTextField * drcField;
6178     if (sender == fAudTrack1DrcSlider)
6179     {
6180         drcSlider = fAudTrack1DrcSlider;
6181         drcField = fAudTrack1DrcField;
6182     }
6183     else if (sender == fAudTrack2DrcSlider)
6184     {
6185         drcSlider = fAudTrack2DrcSlider;
6186         drcField = fAudTrack2DrcField;
6187     }
6188     else if (sender == fAudTrack3DrcSlider)
6189     {
6190         drcSlider = fAudTrack3DrcSlider;
6191         drcField = fAudTrack3DrcField;
6192     }
6193     else
6194     {
6195         drcSlider = fAudTrack4DrcSlider;
6196         drcField = fAudTrack4DrcField;
6197     }
6198     
6199     /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6200     if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6201     {
6202         [drcSlider setFloatValue:1.0];
6203     }
6204     
6205     
6206     [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6207     /* For now, do not call this until we have an intelligent way to determine audio track selections
6208     * compared to presets
6209     */
6210     //[self customSettingUsed: sender];
6211 }
6212
6213 #pragma mark -
6214
6215 - (IBAction) browseImportSrtFile: (id) sender
6216 {
6217
6218     NSOpenPanel * panel;
6219         
6220     panel = [NSOpenPanel openPanel];
6221     [panel setAllowsMultipleSelection: NO];
6222     [panel setCanChooseFiles: YES];
6223     [panel setCanChooseDirectories: NO ];
6224     NSString * sourceDirectory;
6225         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6226         {
6227                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6228         }
6229         else
6230         {
6231                 sourceDirectory = @"~/Desktop";
6232                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6233         }
6234     /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6235     NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6236     [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6237                    modalForWindow: fWindow modalDelegate: self
6238                    didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6239                       contextInfo: sender];
6240 }
6241
6242 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6243                      returnCode: (int) returnCode contextInfo: (void *) contextInfo
6244 {
6245     if( returnCode == NSOKButton )
6246     {
6247         NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6248         NSString *importSrtFilePath = [sheet filename];
6249         [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6250         
6251         /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6252         [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6253         
6254         [fSubtitlesTable reloadData];
6255         
6256     }
6257 }                                           
6258
6259 #pragma mark -
6260 #pragma mark Open New Windows
6261
6262 - (IBAction) openHomepage: (id) sender
6263 {
6264     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6265         URLWithString:@"http://handbrake.fr/"]];
6266 }
6267
6268 - (IBAction) openForums: (id) sender
6269 {
6270     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6271         URLWithString:@"http://handbrake.fr/forum/"]];
6272 }
6273 - (IBAction) openUserGuide: (id) sender
6274 {
6275     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6276         URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6277 }
6278
6279 /**
6280  * Shows debug output window.
6281  */
6282 - (IBAction)showDebugOutputPanel:(id)sender
6283 {
6284     [outputPanel showOutputPanel:sender];
6285 }
6286
6287 /**
6288  * Shows preferences window.
6289  */
6290 - (IBAction) showPreferencesWindow: (id) sender
6291 {
6292     NSWindow * window = [fPreferencesController window];
6293     if (![window isVisible])
6294         [window center];
6295
6296     [window makeKeyAndOrderFront: nil];
6297 }
6298
6299 /**
6300  * Shows queue window.
6301  */
6302 - (IBAction) showQueueWindow:(id)sender
6303 {
6304     [fQueueController showQueueWindow:sender];
6305 }
6306
6307
6308 - (IBAction) toggleDrawer:(id)sender {
6309     [fPresetDrawer toggle:self];
6310 }
6311
6312 /**
6313  * Shows Picture Settings Window.
6314  */
6315
6316 - (IBAction) showPicturePanel: (id) sender
6317 {
6318         [fPictureController showPictureWindow:sender];
6319 }
6320
6321 - (void) picturePanelFullScreen
6322 {
6323         [fPictureController setToFullScreenMode];
6324 }
6325
6326 - (void) picturePanelWindowed
6327 {
6328         [fPictureController setToWindowedMode];
6329 }
6330
6331 - (IBAction) showPreviewWindow: (id) sender
6332 {
6333         [fPictureController showPreviewWindow:sender];
6334 }
6335
6336 #pragma mark -
6337 #pragma mark Preset Outline View Methods
6338 #pragma mark - Required
6339 /* These are required by the NSOutlineView Datasource Delegate */
6340
6341
6342 /* used to specify the number of levels to show for each item */
6343 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6344 {
6345     /* currently use no levels to test outline view viability */
6346     if (item == nil) // for an outline view the root level of the hierarchy is always nil
6347     {
6348         return [UserPresets count];
6349     }
6350     else
6351     {
6352         /* we need to return the count of the array in ChildrenArray for this folder */
6353         NSArray *children = nil;
6354         children = [item objectForKey:@"ChildrenArray"];
6355         if ([children count] > 0)
6356         {
6357             return [children count];
6358         }
6359         else
6360         {
6361             return 0;
6362         }
6363     }
6364 }
6365
6366 /* We use this to deterimine children of an item */
6367 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6368 {
6369     
6370     /* we need to return the count of the array in ChildrenArray for this folder */
6371     NSArray *children = nil;
6372     if (item == nil)
6373     {
6374         children = UserPresets;
6375     }
6376     else
6377     {
6378         if ([item objectForKey:@"ChildrenArray"])
6379         {
6380             children = [item objectForKey:@"ChildrenArray"];
6381         }
6382     }   
6383     if ((children == nil) || ( [children count] <= (NSUInteger) index))
6384     {
6385         return nil;
6386     }
6387     else
6388     {
6389         return [children objectAtIndex:index];
6390     }
6391     
6392     
6393     // We are only one level deep, so we can't be asked about children
6394     //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6395     //return nil;
6396 }
6397
6398 /* We use this to determine if an item should be expandable */
6399 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6400 {
6401     
6402     /* we need to return the count of the array in ChildrenArray for this folder */
6403     NSArray *children= nil;
6404     if (item == nil)
6405     {
6406         children = UserPresets;
6407     }
6408     else
6409     {
6410         if ([item objectForKey:@"ChildrenArray"])
6411         {
6412             children = [item objectForKey:@"ChildrenArray"];
6413         }
6414     }   
6415     
6416     /* To deterimine if an item should show a disclosure triangle
6417      * we could do it by the children count as so:
6418      * if ([children count] < 1)
6419      * However, lets leave the triangle show even if there are no
6420      * children to help indicate a folder, just like folder in the
6421      * finder can show a disclosure triangle even when empty
6422      */
6423     
6424     /* We need to determine if the item is a folder */
6425    if ([[item objectForKey:@"Folder"] intValue] == 1)
6426    {
6427         return YES;
6428     }
6429     else
6430     {
6431         return NO;
6432     }
6433     
6434 }
6435
6436 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6437 {
6438     // Our outline view has no levels, but we can still expand every item. Doing so
6439     // just makes the row taller. See heightOfRowByItem below.
6440 //return ![(HBQueueOutlineView*)outlineView isDragging];
6441
6442 return YES;
6443 }
6444
6445
6446 /* Used to tell the outline view which information is to be displayed per item */
6447 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6448 {
6449         /* We have two columns right now, icon and PresetName */
6450         
6451     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6452     {
6453         return [item objectForKey:@"PresetName"];
6454     }
6455     else
6456     {
6457         //return @"";
6458         return nil;
6459     }
6460 }
6461
6462 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6463 {
6464     return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6465 }
6466 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6467 {
6468     return [NSKeyedArchiver archivedDataWithRootObject:item];
6469 }
6470
6471 #pragma mark - Added Functionality (optional)
6472 /* Use to customize the font and display characteristics of the title cell */
6473 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6474 {
6475     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6476     {
6477         NSFont *txtFont;
6478         NSColor *fontColor;
6479         NSColor *shadowColor;
6480         txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6481         /*check to see if its a selected row */
6482         if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6483         {
6484             
6485             fontColor = [NSColor blackColor];
6486             shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6487         }
6488         else
6489         {
6490             if ([[item objectForKey:@"Type"] intValue] == 0)
6491             {
6492                 fontColor = [NSColor blueColor];
6493             }
6494             else // User created preset, use a black font
6495             {
6496                 fontColor = [NSColor blackColor];
6497             }
6498             /* check to see if its a folder */
6499             //if ([[item objectForKey:@"Folder"] intValue] == 1)
6500             //{
6501             //fontColor = [NSColor greenColor];
6502             //}
6503             
6504             
6505         }
6506         /* We use Bold Text for the HB Default */
6507         if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6508         {
6509             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6510         }
6511         /* We use Bold Text for the User Specified Default */
6512         if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6513         {
6514             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6515         }
6516         
6517         
6518         [cell setTextColor:fontColor];
6519         [cell setFont:txtFont];
6520         
6521     }
6522 }
6523
6524 /* We use this to edit the name field in the outline view */
6525 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6526 {
6527     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6528     {
6529         id theRecord;
6530         
6531         theRecord = item;
6532         [theRecord setObject:object forKey:@"PresetName"];
6533         
6534         [self sortPresets];
6535         
6536         [fPresetsOutlineView reloadData];
6537         /* We save all of the preset data here */
6538         [self savePreset];
6539     }
6540 }
6541 /* We use this to provide tooltips for the items in the presets outline view */
6542 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6543 {
6544     //if ([[tc identifier] isEqualToString:@"PresetName"])
6545     //{
6546         /* initialize the tooltip contents variable */
6547         NSString *loc_tip;
6548         /* if there is a description for the preset, we show it in the tooltip */
6549         if ([item objectForKey:@"PresetDescription"])
6550         {
6551             loc_tip = [item objectForKey:@"PresetDescription"];
6552             return (loc_tip);
6553         }
6554         else
6555         {
6556             loc_tip = @"No description available";
6557         }
6558         return (loc_tip);
6559     //}
6560 }
6561
6562 #pragma mark -
6563 #pragma mark Preset Outline View Methods (dragging related)
6564
6565
6566 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6567 {
6568         // Dragging is only allowed for custom presets.
6569     //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6570         if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6571     {
6572         return NO;
6573     }
6574     // Don't retain since this is just holding temporaral drag information, and it is
6575     //only used during a drag!  We could put this in the pboard actually.
6576     fDraggedNodes = items;
6577     // Provide data for our custom type, and simple NSStrings.
6578     [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6579     
6580     // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6581     [pboard setData:[NSData data] forType:DragDropSimplePboardType]; 
6582     
6583     return YES;
6584 }
6585
6586 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6587 {
6588         
6589         // Don't allow dropping ONTO an item since they can't really contain any children.
6590     
6591     BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6592     if (isOnDropTypeProposal)
6593         return NSDragOperationNone;
6594     
6595     // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6596         if (item != nil)
6597         {
6598                 index = [fPresetsOutlineView rowForItem: item] + 1;
6599                 item = nil;
6600         }
6601     
6602     // Don't allow dropping into the Built In Presets.
6603     if (index < presetCurrentBuiltInCount)
6604     {
6605         return NSDragOperationNone;
6606         index = MAX (index, presetCurrentBuiltInCount);
6607         }    
6608         
6609     [outlineView setDropItem:item dropChildIndex:index];
6610     return NSDragOperationGeneric;
6611 }
6612
6613
6614
6615 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6616 {
6617     /* first, lets see if we are dropping into a folder */
6618     if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6619         {
6620     NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6621     childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6622     [childrenArray addObject:item];
6623     [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6624     [childrenArray autorelease];
6625     }
6626     else // We are not, so we just move the preset into the existing array 
6627     {
6628         NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6629         id obj;
6630         NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6631         while (obj = [enumerator nextObject])
6632         {
6633             [moveItems addIndex:[UserPresets indexOfObject:obj]];
6634         }
6635         // Successful drop, lets rearrange the view and save it all
6636         [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6637     }
6638     [fPresetsOutlineView reloadData];
6639     [self savePreset];
6640     return YES;
6641 }
6642
6643 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6644 {
6645     NSUInteger index = [indexSet lastIndex];
6646     NSUInteger aboveInsertIndexCount = 0;
6647     
6648     NSUInteger removeIndex;
6649
6650     if (index >= insertIndex)
6651     {
6652         removeIndex = index + aboveInsertIndexCount;
6653         aboveInsertIndexCount++;
6654     }
6655     else
6656     {
6657         removeIndex = index;
6658         insertIndex--;
6659     }
6660
6661     id object = [[array objectAtIndex:removeIndex] retain];
6662     [array removeObjectAtIndex:removeIndex];
6663     [array insertObject:object atIndex:insertIndex];
6664     [object release];
6665
6666     index = [indexSet indexLessThanIndex:index];
6667 }
6668
6669
6670
6671 #pragma mark - Functional Preset NSOutlineView Methods
6672
6673 - (IBAction)selectPreset:(id)sender
6674 {
6675     
6676     if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6677     {
6678         chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6679         [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6680         
6681         if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6682         {
6683             [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6684         }
6685         else
6686         {
6687             [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6688         }
6689         
6690         /* File Format */
6691         [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6692         [self formatPopUpChanged:nil];
6693         
6694         /* Chapter Markers*/
6695         [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6696         /* check to see if we have only one chapter */
6697         [self chapterPopUpChanged:nil];
6698         
6699         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6700         [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6701         /* Mux mp4 with http optimization */
6702         [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6703         
6704         /* Video encoder */
6705         [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6706         /* We set the advanced opt string here if applicable*/
6707         [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6708         
6709         /* Lets run through the following functions to get variables set there */
6710         [self videoEncoderPopUpChanged:nil];
6711         /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6712         [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6713         [self calculateBitrate:nil];
6714         
6715         /* Video quality */
6716         [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6717         
6718         [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6719         [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6720         
6721         /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6722          * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6723          * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6724          * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6725          * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6726         if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6727         {
6728             /* For the quality slider we need to convert the old percent's to the new rf scales */
6729             float rf =  (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6730             [fVidQualitySlider setFloatValue:rf];
6731             
6732         }
6733         else
6734         {
6735             /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6736             if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6737             {
6738                 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6739             }
6740             else
6741             {
6742                 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6743                 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6744             }
6745         }
6746         
6747         [self videoMatrixChanged:nil];
6748         
6749         /* Video framerate */
6750         /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6751          detected framerate in the fVidRatePopUp so we use index 0*/
6752         if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6753         {
6754             [fVidRatePopUp selectItemAtIndex: 0];
6755         }
6756         else
6757         {
6758             [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6759         }
6760         
6761         
6762         /* 2 Pass Encoding */
6763         [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6764         [self twoPassCheckboxChanged:nil];
6765         
6766         /* Turbo 1st pass for 2 Pass Encoding */
6767         [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6768         
6769         /*Audio*/
6770         /* First we check to see if we are using the current audio track layout based on AudioList array */
6771         if ([chosenPreset objectForKey:@"AudioList"])
6772         {
6773             
6774             /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6775             NSPopUpButton * trackLangPopUp = nil;
6776             NSPopUpButton * mixdownPopUp = nil;
6777             NSPopUpButton * audiocodecPopUp = nil;
6778             NSPopUpButton * sampleratePopUp = nil;
6779             NSPopUpButton * bitratePopUp = nil;
6780             NSSlider      * drcSlider = nil;
6781             
6782             
6783             /* Populate the audio widgets based on the contents of the AudioList array */
6784             int i = 0;
6785             NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6786             id tempObject;
6787             while (tempObject = [enumerator nextObject])
6788             {
6789                 i++;
6790                 if( i == 1 )
6791                 {
6792                     trackLangPopUp = fAudLang1PopUp;
6793                     mixdownPopUp = fAudTrack1MixPopUp;
6794                     audiocodecPopUp = fAudTrack1CodecPopUp;
6795                     sampleratePopUp = fAudTrack1RatePopUp;
6796                     bitratePopUp = fAudTrack1BitratePopUp;
6797                     drcSlider = fAudTrack1DrcSlider;
6798                 }
6799                 if( i == 2 )
6800                 {
6801                     trackLangPopUp = fAudLang2PopUp;
6802                     mixdownPopUp = fAudTrack2MixPopUp;
6803                     audiocodecPopUp = fAudTrack2CodecPopUp;
6804                     sampleratePopUp = fAudTrack2RatePopUp;
6805                     bitratePopUp = fAudTrack2BitratePopUp;
6806                     drcSlider = fAudTrack2DrcSlider;
6807                 }
6808                 if( i == 3 )
6809                 {
6810                     trackLangPopUp = fAudLang3PopUp;
6811                     mixdownPopUp = fAudTrack3MixPopUp;
6812                     audiocodecPopUp = fAudTrack3CodecPopUp;
6813                     sampleratePopUp = fAudTrack3RatePopUp;
6814                     bitratePopUp = fAudTrack3BitratePopUp;
6815                     drcSlider = fAudTrack3DrcSlider;
6816                 }
6817                 if( i == 4 )
6818                 {
6819                     trackLangPopUp = fAudLang4PopUp;
6820                     mixdownPopUp = fAudTrack4MixPopUp;
6821                     audiocodecPopUp = fAudTrack4CodecPopUp;
6822                     sampleratePopUp = fAudTrack4RatePopUp;
6823                     bitratePopUp = fAudTrack4BitratePopUp;
6824                     drcSlider = fAudTrack4DrcSlider;
6825                 }
6826                 
6827                 
6828                 if ([trackLangPopUp indexOfSelectedItem] == 0)
6829                 {
6830                     [trackLangPopUp selectItemAtIndex: 1];
6831                 }
6832                 [self audioTrackPopUpChanged: trackLangPopUp];
6833                 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6834                 /* check our pref for core audio and use it in place of faac if applicable */
6835                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6836                     [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6837                 {
6838                     [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6839                 }                    
6840                 
6841                 [self audioTrackPopUpChanged: audiocodecPopUp];
6842                 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6843                 [self audioTrackMixdownChanged: mixdownPopUp];
6844                 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6845                  * mixdown*/
6846                 if  ([mixdownPopUp selectedItem] == nil)
6847                 {
6848                     [self audioTrackPopUpChanged: audiocodecPopUp];
6849                     [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6850                 }
6851                 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6852                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6853                 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6854                 {
6855                     [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6856                     /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6857                      *default mixdown bitrate*/
6858                     if ([bitratePopUp selectedItem] == nil)
6859                     {
6860                         [self audioTrackMixdownChanged: mixdownPopUp];
6861                     }
6862                 }
6863                 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6864                 [self audioDRCSliderChanged: drcSlider];
6865                 
6866                 
6867                 /* If we are any track greater than 1 check to make sure we have a matching source codec is using ac3 passthru or dts passthru,
6868                  * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6869                 
6870                 if( i > 1 )
6871                 {
6872                     /* Check to see if the preset asks for a passhthru track (AC3 or DTS) and verify there is a matching source track if not, set the track to "None". */
6873                     if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])  && [trackLangPopUp indexOfSelectedItem] != 0)
6874                     {
6875                         hb_audio_config_t * audio;
6876                         /* get the audio source audio codec */
6877                         audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6878                         if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6879                             [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6880                         {
6881                             /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6882                             if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6883                             {
6884                                 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6885                             }
6886                             if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6887                             {
6888                                 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6889                             }
6890                             [self writeToActivityLog: "No matching source codec, setting track  %d to None", i];
6891                             [trackLangPopUp selectItemAtIndex: 0];
6892                             [self audioTrackPopUpChanged: trackLangPopUp]; 
6893                         }   
6894                     }
6895                 }
6896             }
6897             
6898             /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6899             
6900             if (i < 4)
6901             {
6902                 [fAudLang4PopUp selectItemAtIndex: 0];
6903                 [self audioTrackPopUpChanged: fAudLang4PopUp];
6904                 
6905                 if (i < 3)
6906                 {
6907                     [fAudLang3PopUp selectItemAtIndex: 0];
6908                     [self audioTrackPopUpChanged: fAudLang3PopUp];
6909                     
6910                     if (i < 2)
6911                     {
6912                         [fAudLang2PopUp selectItemAtIndex: 0];
6913                         [self audioTrackPopUpChanged: fAudLang2PopUp];
6914                     }
6915                 }
6916             }
6917             
6918         }
6919         else
6920         {
6921             if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6922             {
6923                 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6924                 {
6925                     [fAudLang1PopUp selectItemAtIndex: 1];
6926                 }
6927                 [self audioTrackPopUpChanged: fAudLang1PopUp];
6928                 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6929                 /* check our pref for core audio and use it in place of faac if applicable */
6930                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6931                     [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6932                 {
6933                     [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6934                 }
6935                 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6936                 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6937                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6938                  * mixdown*/
6939                 if  ([fAudTrack1MixPopUp selectedItem] == nil)
6940                 {
6941                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6942                 }
6943                 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6944                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6945                 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6946                 {
6947                     [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6948                 }
6949                 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6950                 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6951             }
6952             
6953             if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6954             {
6955                 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6956                 {
6957                     [fAudLang2PopUp selectItemAtIndex: 1];
6958                 }
6959                 [self audioTrackPopUpChanged: fAudLang2PopUp];
6960                 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6961                 /* check our pref for core audio and use it in place of faac if applicable */
6962                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6963                     [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6964                 {
6965                     [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6966                 }
6967                 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6968                 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6969                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6970                  * mixdown*/
6971                 if  ([fAudTrack2MixPopUp selectedItem] == nil)
6972                 {
6973                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6974                 }
6975                 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6976                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6977                 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6978                 {
6979                     [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6980                 }
6981                 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6982                 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6983             }
6984             if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6985             {
6986                 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6987                 {
6988                     [fAudLang3PopUp selectItemAtIndex: 1];
6989                 }
6990                 [self audioTrackPopUpChanged: fAudLang3PopUp];
6991                 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6992                 /* check our pref for core audio and use it in place of faac if applicable */
6993                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6994                     [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6995                 {
6996                     [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6997                 }
6998                 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6999                 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
7000                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7001                  * mixdown*/
7002                 if  ([fAudTrack3MixPopUp selectedItem] == nil)
7003                 {
7004                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
7005                 }
7006                 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
7007                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7008                 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
7009                 {
7010                     [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
7011                 }
7012                 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
7013                 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
7014             }
7015             if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
7016             {
7017                 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
7018                 {
7019                     [fAudLang4PopUp selectItemAtIndex: 1];
7020                 }
7021                 [self audioTrackPopUpChanged: fAudLang4PopUp];
7022                 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
7023                 /* check our pref for core audio and use it in place of faac if applicable */
7024                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
7025                     [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
7026                 {
7027                     [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
7028                 }
7029                 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7030                 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
7031                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7032                  * mixdown*/
7033                 if  ([fAudTrack4MixPopUp selectedItem] == nil)
7034                 {
7035                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7036                 }
7037                 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7038                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7039                 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7040                 {
7041                     [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7042                 }
7043                 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7044                 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7045             }
7046             
7047             /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7048             
7049             if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7050             {
7051                 [fAudLang2PopUp selectItemAtIndex: 0];
7052                 [self audioTrackPopUpChanged: fAudLang2PopUp];
7053             }
7054             if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7055             {
7056                 [fAudLang3PopUp selectItemAtIndex: 0];
7057                 [self audioTrackPopUpChanged: fAudLang3PopUp];
7058             }
7059             if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7060             {
7061                 [fAudLang4PopUp selectItemAtIndex: 0];
7062                 [self audioTrackPopUpChanged: fAudLang4PopUp];
7063             }
7064         }
7065         
7066         /*Subtitles*/
7067         [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7068         /* Forced Subtitles */
7069         [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7070         
7071         /* Picture Settings */
7072         /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7073          * height, width, keep ar, anamorphic and crop settings.
7074          * picture filters are handled separately below.
7075          */
7076         /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None" 
7077          * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the 
7078          * preset completely ignores any picture sizing values in the preset.
7079          */
7080         if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] > 0)
7081         {
7082             hb_job_t * job = fTitle->job;
7083             
7084             /* If Cropping is set to custom, then recall all four crop values from
7085              when the preset was created and apply them */
7086             if ([[chosenPreset objectForKey:@"PictureAutoCrop"]  intValue] == 0)
7087             {
7088                 [fPictureController setAutoCrop:NO];
7089                 
7090                 /* Here we use the custom crop values saved at the time the preset was saved */
7091                 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"]  intValue];
7092                 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"]  intValue];
7093                 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"]  intValue];
7094                 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"]  intValue];
7095                 
7096             }
7097             else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7098             {
7099                 [fPictureController setAutoCrop:YES];
7100                 /* Here we use the auto crop values determined right after scan */
7101                 job->crop[0] = AutoCropTop;
7102                 job->crop[1] = AutoCropBottom;
7103                 job->crop[2] = AutoCropLeft;
7104                 job->crop[3] = AutoCropRight;
7105                 
7106             }
7107             
7108             /* Set modulus */
7109             if ([chosenPreset objectForKey:@"PictureModulus"])
7110             {
7111                 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"]  intValue];
7112             }
7113             else
7114             {
7115                 job->modulus = 16;
7116             }
7117              
7118             /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7119             if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"]  intValue] == 1)
7120             {
7121                 /* Use Max Picture settings for whatever the dvd is.*/
7122                 [self revertPictureSizeToMax:nil];
7123                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
7124                 if (job->keep_ratio == 1)
7125                 {
7126                     hb_fix_aspect( job, HB_KEEP_WIDTH );
7127                     if( job->height > fTitle->height )
7128                     {
7129                         job->height = fTitle->height;
7130                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
7131                     }
7132                 }
7133                 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
7134             }
7135             else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7136             {
7137                 /* we check to make sure the presets width/height does not exceed the sources width/height */
7138                 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"]  intValue])
7139                 {
7140                     /* if so, then we use the sources height and width to avoid scaling up */
7141                     //job->width = fTitle->width;
7142                     //job->height = fTitle->height;
7143                     [self revertPictureSizeToMax:nil];
7144                 }
7145                 else // source width/height is >= the preset height/width
7146                 {
7147                     /* we can go ahead and use the presets values for height and width */
7148                     job->width = [[chosenPreset objectForKey:@"PictureWidth"]  intValue];
7149                     job->height = [[chosenPreset objectForKey:@"PictureHeight"]  intValue];
7150                 }
7151                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
7152                 if (job->keep_ratio == 1)
7153                 {
7154                     hb_fix_aspect( job, HB_KEEP_WIDTH );
7155                     if( job->height > fTitle->height )
7156                     {
7157                         job->height = fTitle->height;
7158                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
7159                     }
7160                 }
7161                 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
7162                 
7163             }
7164             
7165             
7166         }
7167         /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7168         if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"]  intValue] > 0)
7169         {
7170             /* Filters */
7171             
7172             /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7173              * also, older presets may not have this key, in which case we also check to see if that preset had  PictureDecomb
7174              * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7175              * sane.
7176              */
7177             [fPictureController setUseDecomb:1];
7178             [fPictureController setDecomb:0];
7179             [fPictureController setDeinterlace:0];
7180             if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7181             {
7182                 /* we are using decomb */
7183                 /* Decomb */
7184                 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7185                 {
7186                     [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7187                     
7188                     /* if we are using "Custom" in the decomb setting, also set the custom string*/
7189                     if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7190                     {
7191                         [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];    
7192                     }
7193                 }
7194              }
7195             else
7196             {
7197                 /* We are using Deinterlace */
7198                 /* Deinterlace */
7199                 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7200                 {
7201                     [fPictureController setUseDecomb:0];
7202                     [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7203                     /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7204                     if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7205                     {
7206                         [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];    
7207                     }
7208                 }
7209             }
7210             
7211             
7212             /* Detelecine */
7213             if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7214             {
7215                 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7216                 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7217                 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7218                 {
7219                     [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];    
7220                 }
7221             }
7222             else
7223             {
7224                 [fPictureController setDetelecine:0];
7225             }
7226             
7227             /* Denoise */
7228             if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7229             {
7230                 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7231                 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7232                 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7233                 {
7234                     [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];    
7235                 }
7236             }
7237             else
7238             {
7239                 [fPictureController setDenoise:0];
7240             }   
7241             
7242             /* Deblock */
7243             if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7244             {
7245                 /* if its a one, then its the old on/off deblock, set on to 5*/
7246                 [fPictureController setDeblock:5];
7247             }
7248             else
7249             {
7250                 /* use the settings intValue */
7251                 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7252             }
7253             
7254             if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7255             {
7256                 [fPictureController setGrayscale:1];
7257             }
7258             else
7259             {
7260                 [fPictureController setGrayscale:0];
7261             }
7262         }
7263         /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7264         [fPictureController SetTitle:fTitle];
7265         [fPictureController SetTitle:fTitle];
7266         [self calculatePictureSizing:nil];
7267     }
7268 }
7269
7270
7271 #pragma mark -
7272 #pragma mark Manage Presets
7273
7274 - (void) loadPresets {
7275         /* We declare the default NSFileManager into fileManager */
7276         NSFileManager * fileManager = [NSFileManager defaultManager];
7277         /*We define the location of the user presets file */
7278     UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7279         UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7280     /* We check for the presets.plist */
7281         if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7282         {
7283                 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7284         }
7285
7286         UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7287         if (nil == UserPresets)
7288         {
7289                 UserPresets = [[NSMutableArray alloc] init];
7290                 [self addFactoryPresets:nil];
7291         }
7292         [fPresetsOutlineView reloadData];
7293     
7294     [self checkBuiltInsForUpdates];
7295 }
7296
7297 - (void) checkBuiltInsForUpdates {
7298     
7299         BOOL updateBuiltInPresets = NO;
7300     int i = 0;
7301     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7302     id tempObject;
7303     while (tempObject = [enumerator nextObject])
7304     {
7305         /* iterate through the built in presets to see if any have an old build number */
7306         NSMutableDictionary *thisPresetDict = tempObject;
7307         /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7308         if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)              
7309         {
7310                         if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7311             {
7312                 updateBuiltInPresets = YES;
7313             }   
7314                 }
7315         i++;
7316     }
7317     /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7318     if ( updateBuiltInPresets == YES)
7319     {
7320         if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7321         {
7322             /* Show an alert window that built in presets will be updated */
7323             /*On Screen Notification*/
7324             int status;
7325             NSBeep();
7326             status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7327             [NSApp requestUserAttention:NSCriticalRequest];
7328         }
7329         /* when alert is dismissed, go ahead and update the built in presets */
7330         [self addFactoryPresets:nil];
7331     }
7332     
7333 }
7334
7335
7336 - (IBAction) showAddPresetPanel: (id) sender
7337 {
7338     /* Deselect the currently selected Preset if there is one*/
7339     [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7340
7341     /* Populate the preset picture settings popup here */
7342     [fPresetNewPicSettingsPopUp removeAllItems];
7343     [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7344     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7345     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7346     [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];  
7347     /* Uncheck the preset use filters checkbox */
7348     [fPresetNewPicFiltersCheck setState:NSOffState];
7349     // fPresetNewFolderCheck
7350     [fPresetNewFolderCheck setState:NSOffState];
7351     /* Erase info from the input fields*/
7352         [fPresetNewName setStringValue: @""];
7353         [fPresetNewDesc setStringValue: @""];
7354         /* Show the panel */
7355         [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7356 }
7357
7358 - (IBAction) closeAddPresetPanel: (id) sender
7359 {
7360     [NSApp endSheet: fAddPresetPanel];
7361     [fAddPresetPanel orderOut: self];
7362 }
7363
7364 - (IBAction)addUserPreset:(id)sender
7365 {
7366     if (![[fPresetNewName stringValue] length])
7367             NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7368     else
7369     {
7370         /* Here we create a custom user preset */
7371         [UserPresets addObject:[self createPreset]];
7372         [self addPreset];
7373
7374         [self closeAddPresetPanel:nil];
7375     }
7376 }
7377 - (void)addPreset
7378 {
7379
7380         
7381         /* We Reload the New Table data for presets */
7382     [fPresetsOutlineView reloadData];
7383    /* We save all of the preset data here */
7384     [self savePreset];
7385 }
7386
7387 - (void)sortPresets
7388 {
7389
7390         
7391         /* We Sort the Presets By Factory or Custom */
7392         NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type" 
7393                                                     ascending:YES] autorelease];
7394         /* We Sort the Presets Alphabetically by name  We do not use this now as we have drag and drop*/
7395         /*
7396     NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName" 
7397                                                     ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7398         //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7399     
7400     */
7401     /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7402     NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7403         NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7404         [UserPresets setArray:sortedArray];
7405         
7406
7407 }
7408
7409 - (IBAction)insertPreset:(id)sender
7410 {
7411     int index = [fPresetsOutlineView selectedRow];
7412     [UserPresets insertObject:[self createPreset] atIndex:index];
7413     [fPresetsOutlineView reloadData];
7414     [self savePreset];
7415 }
7416
7417 - (NSDictionary *)createPreset
7418 {
7419     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7420     /* Preset build number */
7421     [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7422     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7423         /* Get the New Preset Name from the field in the AddPresetPanel */
7424     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7425     /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7426     [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7427         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7428         [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7429         /*Set whether or not this is default, at creation set to 0*/
7430         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7431     if ([fPresetNewFolderCheck state] == YES)
7432     {
7433         /* initialize and set an empty array for children here since we are a new folder */
7434         NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7435         [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7436         [childrenArray autorelease];
7437     }
7438     else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7439     {
7440         /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7441         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7442         /* Get whether or not to use the current Picture Filter settings for the preset */
7443         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7444         
7445         /* Get New Preset Description from the field in the AddPresetPanel*/
7446         [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7447         /* File Format */
7448         [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7449         /* Chapter Markers fCreateChapterMarkers*/
7450         [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7451         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7452         [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7453         /* Mux mp4 with http optimization */
7454         [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7455         /* Add iPod uuid atom */
7456         [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7457         
7458         /* Codecs */
7459         /* Video encoder */
7460         [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7461         /* x264 Option String */
7462         [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7463         
7464         [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7465         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7466         [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7467         [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7468         
7469         /* Video framerate */
7470         if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7471         {
7472             [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7473         }
7474         else // we can record the actual titleOfSelectedItem
7475         {
7476             [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7477         }
7478         
7479         /* 2 Pass Encoding */
7480         [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7481         /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7482         [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7483         /*Picture Settings*/
7484         hb_job_t * job = fTitle->job;
7485         /* Picture Sizing */
7486         /* Use Max Picture settings for whatever the dvd is.*/
7487         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7488         [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7489         [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7490         [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7491         [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7492         [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7493         
7494         /* Set crop settings here */
7495         [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7496         [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7497         [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7498         [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7499         [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7500         
7501         /* Picture Filters */
7502         [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7503         [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7504         [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7505         [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7506         [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7507         [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7508         [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7509         [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"]; 
7510         [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7511         [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7512         [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7513         
7514         /*Audio*/
7515         NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7516         /* we actually call the methods for the nests here */
7517         if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7518         {
7519             NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7520             [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7521             [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7522             [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7523             [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7524             [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7525             [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7526             [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7527             [audioTrack1Array autorelease];
7528             [audioListArray addObject:audioTrack1Array];
7529         }
7530         
7531         if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7532         {
7533             NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7534             [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7535             [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7536             [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7537             [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7538             [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7539             [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7540             [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7541             [audioTrack2Array autorelease];
7542             [audioListArray addObject:audioTrack2Array];
7543         }
7544         
7545         if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7546         {
7547             NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7548             [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7549             [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7550             [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7551             [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7552             [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7553             [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7554             [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7555             [audioTrack3Array autorelease];
7556             [audioListArray addObject:audioTrack3Array];
7557         }
7558         
7559         if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7560         {
7561             NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7562             [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7563             [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7564             [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7565             [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7566             [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7567             [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7568             [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7569             [audioTrack4Array autorelease];
7570             [audioListArray addObject:audioTrack4Array];
7571         }
7572         
7573         
7574         [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7575
7576         
7577         /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7578          * subititle array code. */
7579         /* Subtitles*/
7580         //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7581         /* Forced Subtitles */
7582         //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7583     }
7584     [preset autorelease];
7585     return preset;
7586     
7587 }
7588
7589 - (void)savePreset
7590 {
7591     [UserPresets writeToFile:UserPresetsFile atomically:YES];
7592         /* We get the default preset in case it changed */
7593         [self getDefaultPresets:nil];
7594
7595 }
7596
7597 - (IBAction)deletePreset:(id)sender
7598 {
7599     
7600     
7601     if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7602     {
7603         return;
7604     }
7605     /* Alert user before deleting preset */
7606         int status;
7607     status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7608     
7609     if ( status == NSAlertDefaultReturn ) 
7610     {
7611         int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7612         NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7613         NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7614         
7615         NSEnumerator *enumerator;
7616         NSMutableArray *presetsArrayToMod;
7617         NSMutableArray *tempArray;
7618         id tempObject;
7619         /* If we are a root level preset, we are modding the UserPresets array */
7620         if (presetToModLevel == 0)
7621         {
7622             presetsArrayToMod = UserPresets;
7623         }
7624         else // We have a parent preset, so we modify the chidren array object for key
7625         {
7626             presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"]; 
7627         }
7628         
7629         enumerator = [presetsArrayToMod objectEnumerator];
7630         tempArray = [NSMutableArray array];
7631         
7632         while (tempObject = [enumerator nextObject]) 
7633         {
7634             NSDictionary *thisPresetDict = tempObject;
7635             if (thisPresetDict == presetToMod)
7636             {
7637                 [tempArray addObject:tempObject];
7638             }
7639         }
7640         
7641         [presetsArrayToMod removeObjectsInArray:tempArray];
7642         [fPresetsOutlineView reloadData];
7643         [self savePreset];   
7644     }
7645 }
7646
7647
7648 #pragma mark -
7649 #pragma mark Import Export Preset(s)
7650
7651 - (IBAction) browseExportPresetFile: (id) sender
7652 {
7653     /* Open a panel to let the user choose where and how to save the export file */
7654     NSSavePanel * panel = [NSSavePanel savePanel];
7655         /* We get the current file name and path from the destination field here */
7656     NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7657
7658         [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7659                                    modalForWindow: fWindow modalDelegate: self
7660                                    didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7661                                           contextInfo: NULL];
7662 }
7663
7664 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7665                    returnCode: (int) returnCode contextInfo: (void *) contextInfo
7666 {
7667     if( returnCode == NSOKButton )
7668     {
7669         NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7670         NSString *exportPresetsFile = [sheet filename];
7671         [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7672         /* We check for the presets.plist */
7673         if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7674         {
7675             [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7676         }
7677         NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7678         if (nil == presetsToExport)
7679         {
7680             presetsToExport = [[NSMutableArray alloc] init];
7681             
7682             /* now get and add selected presets to export */
7683             
7684         }
7685         if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7686         {
7687             [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7688             [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7689             
7690         }
7691         
7692     }
7693 }
7694
7695
7696 - (IBAction) browseImportPresetFile: (id) sender
7697 {
7698
7699     NSOpenPanel * panel;
7700         
7701     panel = [NSOpenPanel openPanel];
7702     [panel setAllowsMultipleSelection: NO];
7703     [panel setCanChooseFiles: YES];
7704     [panel setCanChooseDirectories: NO ];
7705     NSString * sourceDirectory;
7706         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7707         {
7708                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7709         }
7710         else
7711         {
7712                 sourceDirectory = @"~/Desktop";
7713                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7714         }
7715     /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7716         * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7717         */
7718     /* set this for allowed file types, not sure if we should allow xml or not */
7719     NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7720     [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7721                    modalForWindow: fWindow modalDelegate: self
7722                    didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7723                       contextInfo: sender];
7724 }
7725
7726 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7727                      returnCode: (int) returnCode contextInfo: (void *) contextInfo
7728 {
7729     if( returnCode == NSOKButton )
7730     {
7731         NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7732         NSString *importPresetsFile = [sheet filename];
7733         [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7734         /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file   */
7735         NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7736         /* iterate though the new array of presets to import and add them to our presets array */
7737         int i = 0;
7738         NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7739         id tempObject;
7740         while (tempObject = [enumerator nextObject])
7741         {
7742             /* make any changes to the incoming preset we see fit */
7743             /* make sure the incoming preset is not tagged as default */
7744             [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7745             /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7746             NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7747             [tempObject setObject:prependedName forKey:@"PresetName"];
7748             
7749             /* actually add the new preset to our presets array */
7750             [UserPresets addObject:tempObject];
7751             i++;
7752         }
7753         [presetsToImport autorelease];
7754         [self sortPresets];
7755         [self addPreset];
7756         
7757     }
7758 }
7759
7760 #pragma mark -
7761 #pragma mark Manage Default Preset
7762
7763 - (IBAction)getDefaultPresets:(id)sender
7764 {
7765         presetHbDefault = nil;
7766     presetUserDefault = nil;
7767     presetUserDefaultParent = nil;
7768     presetUserDefaultParentParent = nil;
7769     NSMutableDictionary *presetHbDefaultParent = nil;
7770     NSMutableDictionary *presetHbDefaultParentParent = nil;
7771     
7772     int i = 0;
7773     BOOL userDefaultFound = NO;
7774     presetCurrentBuiltInCount = 0;
7775     /* First we iterate through the root UserPresets array to check for defaults */
7776     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7777         id tempObject;
7778         while (tempObject = [enumerator nextObject])
7779         {
7780                 NSMutableDictionary *thisPresetDict = tempObject;
7781                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7782                 {
7783                         presetHbDefault = thisPresetDict;       
7784                 }
7785                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7786                 {
7787                         presetUserDefault = thisPresetDict;
7788             userDefaultFound = YES;
7789         }
7790         if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset               
7791         {
7792                         presetCurrentBuiltInCount++; // <--increment the current number of built in presets     
7793                 }
7794                 i++;
7795         
7796         /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7797         if ([thisPresetDict objectForKey:@"ChildrenArray"])
7798         {
7799             NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7800             NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7801             id tempObject;
7802             while (tempObject = [enumerator nextObject])
7803             {
7804                 NSMutableDictionary *thisPresetDict = tempObject;
7805                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7806                 {
7807                     presetHbDefault = thisPresetDict;
7808                     presetHbDefaultParent = thisPresetDictParent;
7809                 }
7810                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7811                 {
7812                     presetUserDefault = thisPresetDict;
7813                     presetUserDefaultParent = thisPresetDictParent;
7814                     userDefaultFound = YES;
7815                 }
7816                 
7817                 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7818                 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7819                 {
7820                     NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7821                     NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7822                     id tempObject;
7823                     while (tempObject = [enumerator nextObject])
7824                     {
7825                         NSMutableDictionary *thisPresetDict = tempObject;
7826                         if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7827                         {
7828                             presetHbDefault = thisPresetDict;
7829                             presetHbDefaultParent = thisPresetDictParent;
7830                             presetHbDefaultParentParent = thisPresetDictParentParent;   
7831                         }
7832                         if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7833                         {
7834                             presetUserDefault = thisPresetDict;
7835                             presetUserDefaultParent = thisPresetDictParent;
7836                             presetUserDefaultParentParent = thisPresetDictParentParent;
7837                             userDefaultFound = YES;     
7838                         }
7839                         
7840                     }
7841                 }
7842             }
7843         }
7844         
7845         }
7846     /* check to see if a user specified preset was found, if not then assign the parents for
7847      * the presetHbDefault so that we can open the parents for the nested presets
7848      */
7849     if (userDefaultFound == NO)
7850     {
7851         presetUserDefaultParent = presetHbDefaultParent;
7852         presetUserDefaultParentParent = presetHbDefaultParentParent;
7853     }
7854 }
7855
7856 - (IBAction)setDefaultPreset:(id)sender
7857 {
7858 /* We need to determine if the item is a folder */
7859    if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7860    {
7861    return;
7862    }
7863
7864     int i = 0;
7865     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7866         id tempObject;
7867         /* First make sure the old user specified default preset is removed */
7868     while (tempObject = [enumerator nextObject])
7869         {
7870                 NSMutableDictionary *thisPresetDict = tempObject;
7871                 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7872                 {
7873                         [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"]; 
7874                 }
7875                 
7876                 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7877         if ([thisPresetDict objectForKey:@"ChildrenArray"])
7878         {
7879             NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7880             id tempObject;
7881             int ii = 0;
7882             while (tempObject = [enumerator nextObject])
7883             {
7884                 NSMutableDictionary *thisPresetDict1 = tempObject;
7885                 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7886                 {
7887                     [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"]; 
7888                 }
7889                 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7890                 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7891                 {
7892                     NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7893                     id tempObject;
7894                     int iii = 0;
7895                     while (tempObject = [enumerator nextObject])
7896                     {
7897                         if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7898                         {
7899                             [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];       
7900                         }
7901                         iii++;
7902                     }
7903                 }
7904                 ii++;
7905             }
7906             
7907         }
7908         i++; 
7909         }
7910     
7911     
7912     int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7913     NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7914     NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7915     
7916     
7917     NSMutableArray *presetsArrayToMod;
7918     NSMutableArray *tempArray;
7919     
7920     /* If we are a root level preset, we are modding the UserPresets array */
7921     if (presetToModLevel == 0)
7922     {
7923         presetsArrayToMod = UserPresets;
7924     }
7925     else // We have a parent preset, so we modify the chidren array object for key
7926     {
7927         presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"]; 
7928     }
7929     
7930     enumerator = [presetsArrayToMod objectEnumerator];
7931     tempArray = [NSMutableArray array];
7932     int iiii = 0;
7933     while (tempObject = [enumerator nextObject]) 
7934     {
7935         NSDictionary *thisPresetDict = tempObject;
7936         if (thisPresetDict == presetToMod)
7937         {
7938             if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7939             {
7940                 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];        
7941             }
7942         }
7943      iiii++;
7944      }
7945     
7946     
7947     /* We save all of the preset data here */
7948     [self savePreset];
7949     /* We Reload the New Table data for presets */
7950     [fPresetsOutlineView reloadData];
7951 }
7952
7953 - (IBAction)selectDefaultPreset:(id)sender
7954 {
7955         NSMutableDictionary *presetToMod;
7956     /* if there is a user specified default, we use it */
7957         if (presetUserDefault)
7958         {
7959         presetToMod = presetUserDefault;
7960     }
7961         else if (presetHbDefault) //else we use the built in default presetHbDefault
7962         {
7963         presetToMod = presetHbDefault;
7964         }
7965     else
7966     {
7967     return;
7968     }
7969     
7970     if (presetUserDefaultParent != nil)
7971     {
7972         [fPresetsOutlineView expandItem:presetUserDefaultParent];
7973         
7974     }
7975     if (presetUserDefaultParentParent != nil)
7976     {
7977         [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7978         
7979     }
7980     
7981     [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7982         [self selectPreset:nil];
7983 }
7984
7985
7986 #pragma mark -
7987 #pragma mark Manage Built In Presets
7988
7989
7990 - (IBAction)deleteFactoryPresets:(id)sender
7991 {
7992     //int status;
7993     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7994         id tempObject;
7995     
7996         //NSNumber *index;
7997     NSMutableArray *tempArray;
7998
7999
8000         tempArray = [NSMutableArray array];
8001         /* we look here to see if the preset is we move on to the next one */
8002         while ( tempObject = [enumerator nextObject] )  
8003                 {
8004                         /* if the preset is "Factory" then we put it in the array of
8005                         presets to delete */
8006                         if ([[tempObject objectForKey:@"Type"] intValue] == 0)
8007                         {
8008                                 [tempArray addObject:tempObject];
8009                         }
8010         }
8011         
8012         [UserPresets removeObjectsInArray:tempArray];
8013         [fPresetsOutlineView reloadData];
8014         [self savePreset];   
8015
8016 }
8017
8018    /* We use this method to recreate new, updated factory presets */
8019 - (IBAction)addFactoryPresets:(id)sender
8020 {
8021     
8022     /* First, we delete any existing built in presets */
8023     [self deleteFactoryPresets: sender];
8024     /* Then we generate new built in presets programmatically with fPresetsBuiltin
8025      * which is all setup in HBPresets.h and  HBPresets.m*/
8026     [fPresetsBuiltin generateBuiltinPresets:UserPresets];
8027     /* update build number for built in presets */
8028     /* iterate though the new array of presets to import and add them to our presets array */
8029     int i = 0;
8030     NSEnumerator *enumerator = [UserPresets objectEnumerator];
8031     id tempObject;
8032     while (tempObject = [enumerator nextObject])
8033     {
8034         /* Record the apps current build number in the PresetBuildNumber key */
8035         if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset           
8036         {
8037             /* Preset build number */
8038             [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8039         }
8040         i++;
8041     }
8042     /* report the built in preset updating to the activity log */
8043     [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8044     
8045     [self sortPresets];
8046     [self addPreset];
8047     
8048 }
8049
8050
8051 @end
8052
8053 /*******************************
8054  * Subclass of the HBPresetsOutlineView *
8055  *******************************/
8056
8057 @implementation HBPresetsOutlineView
8058 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8059 {
8060     fIsDragging = YES;
8061
8062     // By default, NSTableView only drags an image of the first column. Change this to
8063     // drag an image of the queue's icon and PresetName columns.
8064     NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8065     return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8066 }
8067
8068
8069
8070 - (void) mouseDown:(NSEvent *)theEvent
8071 {
8072     [super mouseDown:theEvent];
8073         fIsDragging = NO;
8074 }
8075
8076
8077
8078 - (BOOL) isDragging;
8079 {
8080     return fIsDragging;
8081 }
8082 @end
8083
8084
8085