OSDN Git Service

MacGui: Audio fixes regarding CoreAudio as default.
[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, its already been selected in showNewScan
2764        so do not try to reset it here. However if we do decide to do full source scans on
2765        a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2766     //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2767     
2768     [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2769     [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2770     
2771     /* File Format */
2772     [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2773     [self formatPopUpChanged:nil];
2774     
2775     /* Chapter Markers*/
2776     [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2777     /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2778     [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2779     /* Mux mp4 with http optimization */
2780     [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2781     
2782     /* Video encoder */
2783     /* We set the advanced opt string here if applicable*/
2784     [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2785     [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2786     
2787     /* Lets run through the following functions to get variables set there */
2788     [self videoEncoderPopUpChanged:nil];
2789     /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2790     [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2791     [self calculateBitrate:nil];
2792     
2793     /* Video quality */
2794     [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2795     
2796     [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2797     [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2798     /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2799      * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2800      * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2801      * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2802      * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2803     if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2804     {
2805         /* For the quality slider we need to convert the old percent's to the new rf scales */
2806         float rf =  (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2807         [fVidQualitySlider setFloatValue:rf];
2808         
2809     }
2810     else
2811     {
2812         /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2813         if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2814         {
2815             [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2816         }
2817         else
2818         {
2819             /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2820             [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2821         }
2822     }
2823     
2824     [self videoMatrixChanged:nil];
2825     [self writeToActivityLog: "applyQueueSettingsToMainWindow: video matrix changed"];    
2826     /* Video framerate */
2827     /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2828      detected framerate in the fVidRatePopUp so we use index 0*/
2829     if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2830     {
2831         [fVidRatePopUp selectItemAtIndex: 0];
2832     }
2833     else
2834     {
2835         [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2836     }
2837     
2838     /* 2 Pass Encoding */
2839     [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2840     [self twoPassCheckboxChanged:nil];
2841     /* Turbo 1st pass for 2 Pass Encoding */
2842     [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2843     
2844     /*Audio*/
2845     
2846     
2847     /* Now lets add our new tracks to the audio list here */
2848     if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2849     {
2850         [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2851         [self audioTrackPopUpChanged: fAudLang1PopUp];
2852         [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2853         [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2854         
2855         [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2856         
2857         [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2858         [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2859         
2860         [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2861         [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2862     }
2863     else
2864     {
2865         [fAudLang1PopUp selectItemAtIndex: 0];
2866         [self audioTrackPopUpChanged: fAudLang1PopUp];
2867     }
2868     if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2869     {
2870         [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2871         [self audioTrackPopUpChanged: fAudLang2PopUp];
2872         [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2873         [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2874         
2875         [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2876         
2877         [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2878         [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2879         
2880         [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2881         [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2882     }
2883     else
2884     {
2885         [fAudLang2PopUp selectItemAtIndex: 0];
2886         [self audioTrackPopUpChanged: fAudLang2PopUp];
2887     }
2888     if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2889     {
2890         [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2891         [self audioTrackPopUpChanged: fAudLang3PopUp];
2892         [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2893         [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2894         
2895         [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2896         
2897         [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2898         [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2899         
2900         [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2901         [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2902     }
2903     else
2904     {
2905         [fAudLang3PopUp selectItemAtIndex: 0];
2906         [self audioTrackPopUpChanged: fAudLang3PopUp];
2907     }
2908     if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2909     {
2910         [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2911         [self audioTrackPopUpChanged: fAudLang4PopUp];
2912         [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2913         [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2914         
2915         [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2916         
2917         [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2918         [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2919         
2920         [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2921         [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2922     }
2923     else
2924     {
2925         [fAudLang4PopUp selectItemAtIndex: 0];
2926         [self audioTrackPopUpChanged: fAudLang4PopUp];
2927     }
2928     
2929     [self writeToActivityLog: "applyQueueSettingsToMainWindow: audio set up"];
2930     /*Subtitles*/
2931     /* Crashy crashy right now, working on it */
2932     [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2933     [fSubtitlesTable reloadData];  
2934     /* Picture Settings */
2935     
2936     /* If Cropping is set to custom, then recall all four crop values from
2937      when the preset was created and apply them */
2938     if ([[queueToApply objectForKey:@"PictureAutoCrop"]  intValue] == 0)
2939     {
2940         [fPictureController setAutoCrop:NO];
2941         
2942         /* Here we use the custom crop values saved at the time the preset was saved */
2943         job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
2944         job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
2945         job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
2946         job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
2947         
2948     }
2949     else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2950     {
2951         [fPictureController setAutoCrop:YES];
2952         /* Here we use the auto crop values determined right after scan */
2953         job->crop[0] = AutoCropTop;
2954         job->crop[1] = AutoCropBottom;
2955         job->crop[2] = AutoCropLeft;
2956         job->crop[3] = AutoCropRight;
2957         
2958     }
2959     
2960     job->modulus = [[queueToApply objectForKey:@"PictureModulus"]  intValue];
2961     
2962     /* we check to make sure the presets width/height does not exceed the sources width/height */
2963     if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"]  intValue])
2964     {
2965         /* if so, then we use the sources height and width to avoid scaling up */
2966         //job->width = fTitle->width;
2967         //job->height = fTitle->height;
2968         [self revertPictureSizeToMax:nil];
2969     }
2970     else // source width/height is >= the preset height/width
2971     {
2972         /* we can go ahead and use the presets values for height and width */
2973         job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
2974         job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
2975     }
2976     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
2977     if (job->keep_ratio == 1)
2978     {
2979         hb_fix_aspect( job, HB_KEEP_WIDTH );
2980         if( job->height > fTitle->height )
2981         {
2982             job->height = fTitle->height;
2983             hb_fix_aspect( job, HB_KEEP_HEIGHT );
2984         }
2985     }
2986     job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
2987     job->modulus = [[queueToApply objectForKey:@"PictureModulus"]  intValue];
2988     
2989     [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture sizing set up"];
2990     
2991     
2992     /* Filters */
2993     
2994     /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2995      * also, older presets may not have this key, in which case we also check to see if that preset had  PictureDecomb
2996      * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2997      * sane.
2998      */
2999     [fPictureController setUseDecomb:1];
3000     [fPictureController setDecomb:0];
3001     [fPictureController setDeinterlace:0];
3002     if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3003     {
3004         /* we are using decomb */
3005         /* Decomb */
3006         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3007         {
3008             [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3009             
3010             /* if we are using "Custom" in the decomb setting, also set the custom string*/
3011             if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3012             {
3013                 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];    
3014             }
3015         }
3016     }
3017     else
3018     {
3019         /* We are using Deinterlace */
3020         /* Deinterlace */
3021         if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3022         {
3023             [fPictureController setUseDecomb:0];
3024             [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3025             /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3026             if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3027             {
3028                 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];    
3029             }
3030         }
3031     }
3032     
3033     
3034     /* Detelecine */
3035     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3036     {
3037         [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3038         /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3039         if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3040         {
3041             [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];    
3042         }
3043     }
3044     else
3045     {
3046         [fPictureController setDetelecine:0];
3047     }
3048     
3049     /* Denoise */
3050     if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3051     {
3052         [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3053         /* if we are using "Custom" in the denoise setting, also set the custom string*/
3054         if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3055         {
3056             [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];    
3057         }
3058     }
3059     else
3060     {
3061         [fPictureController setDenoise:0];
3062     }   
3063     
3064     /* Deblock */
3065     if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3066     {
3067         /* if its a one, then its the old on/off deblock, set on to 5*/
3068         [fPictureController setDeblock:5];
3069     }
3070     else
3071     {
3072         /* use the settings intValue */
3073         [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3074     }
3075     
3076     if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3077     {
3078         [fPictureController setGrayscale:1];
3079     }
3080     else
3081     {
3082         [fPictureController setGrayscale:0];
3083     }
3084     
3085     /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3086     [fPictureController SetTitle:fTitle];
3087     [self calculatePictureSizing:nil];
3088     
3089     [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture filters set up"];
3090     /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3091     //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3092     //    [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3093     if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3094         {
3095                 /* Deselect the currently selected Preset if there is one*/
3096         //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3097         //[self selectPreset:nil];
3098                 
3099         //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3100                 /* Change UI to show "Custom" settings are being used */
3101                 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3102         
3103                 curUserPresetChosenNum = nil;
3104         }
3105     else
3106     {
3107         /* Deselect the currently selected Preset if there is one*/
3108                 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3109                 /* Change UI to show "Custom" settings are being used */
3110                 [fPresetSelectedDisplay setStringValue: @"Custom"];
3111         
3112                 //curUserPresetChosenNum = nil;
3113     }
3114     
3115     /* We need to set this bool back to NO, in case the user wants to do a scan */
3116     //applyQueueToScan = NO;
3117     
3118     /* Not that source is loaded and settings applied, delete the queue item from the queue */
3119     [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3120     [self removeQueueFileItem:fqueueEditRescanItemNum];
3121 }
3122
3123
3124
3125 #pragma mark -
3126 #pragma mark Live Preview
3127 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3128  * can encode to its temp preview directory and playback. This is *not* used for any actual user
3129  * encodes
3130  */
3131 - (void) prepareJobForPreview
3132 {
3133     hb_list_t  * list  = hb_get_titles( fHandle );
3134     hb_title_t * title = (hb_title_t *) hb_list_item( list,
3135             [fSrcTitlePopUp indexOfSelectedItem] );
3136     hb_job_t * job = title->job;
3137     hb_audio_config_t * audio;
3138     /* set job->angle for libdvdnav */
3139     job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3140     /* Chapter selection */
3141     job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3142     job->chapter_end   = [fSrcChapterEndPopUp   indexOfSelectedItem] + 1;
3143         
3144     /* Format (Muxer) and Video Encoder */
3145     job->mux = [[fDstFormatPopUp selectedItem] tag];
3146     job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3147
3148     job->chapter_markers = 0;
3149     
3150         if( job->vcodec & HB_VCODEC_X264 )
3151     {
3152                 
3153                 /* Below Sends x264 options to the core library if x264 is selected*/
3154                 /* Lets use this as per Nyx, Thanks Nyx!*/
3155                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3156                 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3157                 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3158
3159         
3160     }
3161
3162     /* Video settings */
3163    /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3164      * and detelecine is on, so we handle that in the logic below
3165      */
3166     job->vfr = 0;
3167     if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3168     {
3169         /* a specific framerate has been chosen */
3170         job->vrate      = 27000000;
3171         job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3172         /* We are not same as source so we set job->cfr to 1 
3173          * to enable constant frame rate since user has specified
3174          * a specific framerate*/
3175         job->cfr = 1;
3176     }
3177     else
3178     {
3179         /* We are same as source (variable) */
3180         job->vrate      = title->rate;
3181         job->vrate_base = title->rate_base;
3182         /* We are same as source so we set job->cfr to 0 
3183          * to enable true same as source framerate */
3184         job->cfr = 0;
3185         /* If we are same as source and we have detelecine on, we need to turn on
3186          * job->vfr
3187          */
3188         if ([fPictureController detelecine] == 1)
3189         {
3190             job->vfr = 1;
3191         }
3192     }
3193
3194     switch( [fVidQualityMatrix selectedRow] )
3195     {
3196         case 0:
3197             /* Target size.
3198                Bitrate should already have been calculated and displayed
3199                in fVidBitrateField, so let's just use it */
3200         case 1:
3201             job->vquality = -1.0;
3202             job->vbitrate = [fVidBitrateField intValue];
3203             break;
3204         case 2:
3205             job->vquality = [fVidQualityRFField floatValue];
3206             job->vbitrate = 0;
3207             break;
3208     }
3209
3210     /* Subtitle settings */
3211     NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3212     
3213     
3214 int subtitle = nil;
3215 int force;
3216 int burned;
3217 int def;
3218 bool one_burned = FALSE;
3219
3220     int i = 0;
3221     NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3222     id tempObject;
3223     while (tempObject = [enumerator nextObject])
3224     {
3225         
3226         subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3227         force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3228         burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3229         def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3230         
3231         /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3232          * we want to ignore it for display as well as encoding.
3233          */
3234         if (subtitle > 0)
3235         {
3236             /* if i is 0, then we are in the first item of the subtitles which we need to 
3237              * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3238              * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3239              */
3240             
3241             /* if we are on the first track and using "Foreign Audio Search" */ 
3242             if (i == 0 && subtitle == 1)
3243             {
3244                 /* NOTE: Currently foreign language search is borked for preview.
3245                  * Commented out but left in for initial commit. */
3246                 
3247                 
3248                 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3249                 
3250                 job->indepth_scan = 1;
3251                 if (burned == 1 || job->mux != HB_MUX_MP4)
3252                 {
3253                     if (burned != 1 && job->mux == HB_MUX_MKV)
3254                     {
3255                         job->select_subtitle_config.dest = PASSTHRUSUB;
3256                     }
3257                     else
3258                     {
3259                         job->select_subtitle_config.dest = RENDERSUB;
3260                     }
3261                     
3262                     job->select_subtitle_config.force = force;
3263                     job->select_subtitle_config.default_track = def;
3264                     
3265                 }
3266                 
3267                 
3268             }
3269             else
3270             {
3271                 
3272                 /* for the actual source tracks, we must subtract the non source entries so 
3273                  * that the menu index matches the source subtitle_list index for convenience */
3274                 if (i == 0)
3275                 {
3276                     /* for the first track, the source tracks start at menu index 2 ( None is 0,
3277                      * Foreign Language Search is 1) so subtract 2 */
3278                     subtitle = subtitle - 2;
3279                 }
3280                 else
3281                 {
3282                     /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3283                      * so subtract 1. */
3284                     
3285                     subtitle = subtitle - 1;
3286                 }
3287                 
3288                 /* We are setting a source subtitle so access the source subtitle info */  
3289                 hb_subtitle_t * subt;
3290                 
3291                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3292                 
3293                 /* if we are getting the subtitles from an external srt file */
3294                 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3295                 {
3296                     hb_subtitle_config_t sub_config;
3297                     
3298                     sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3299                     
3300                     /* we need to srncpy file path and char code */
3301                     strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3302                     strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3303                     
3304                     sub_config.force = 0;
3305                     sub_config.dest = PASSTHRUSUB;
3306                     sub_config.default_track = def;
3307                     
3308                     hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3309                 }
3310                 
3311                 if (subt != NULL)
3312                 {
3313                     hb_subtitle_config_t sub_config = subt->config;
3314                     
3315                     if (!burned && job->mux == HB_MUX_MKV && 
3316                         subt->format == PICTURESUB)
3317                     {
3318                         sub_config.dest = PASSTHRUSUB;
3319                     }
3320                     else if (!burned && job->mux == HB_MUX_MP4 && 
3321                              subt->format == PICTURESUB)
3322                     {
3323                         // Skip any non-burned vobsubs when output is mp4
3324                         continue;
3325                     }
3326                     else if ( burned && subt->format == PICTURESUB )
3327                     {
3328                         // Only allow one subtitle to be burned into the video
3329                         if (one_burned)
3330                             continue;
3331                         one_burned = TRUE;
3332                     }
3333                     sub_config.force = force;
3334                     sub_config.default_track = def;
3335                     hb_subtitle_add( job, &sub_config, subtitle );
3336                 }   
3337                 
3338             }
3339         }
3340         i++;
3341     }
3342    
3343     
3344     
3345 [subtitlesArray autorelease];    
3346     
3347     
3348     /* Audio tracks and mixdowns */
3349     /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3350     int audiotrack_count = hb_list_count(job->list_audio);
3351     for( int i = 0; i < audiotrack_count;i++)
3352     {
3353         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3354         hb_list_rem(job->list_audio, temp_audio);
3355     }
3356     /* Now lets add our new tracks to the audio list here */
3357     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3358     {
3359         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3360         hb_audio_config_init(audio);
3361         audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3362         /* We go ahead and assign values to our audio->out.<properties> */
3363         audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3364         audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3365         audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3366         audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3367         audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3368         audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3369         
3370         hb_audio_add( job, audio );
3371         free(audio);
3372     }  
3373     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3374     {
3375         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3376         hb_audio_config_init(audio);
3377         audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3378         /* We go ahead and assign values to our audio->out.<properties> */
3379         audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3380         audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3381         audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3382         audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3383         audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3384         audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3385         
3386         hb_audio_add( job, audio );
3387         free(audio);
3388         
3389     }
3390     
3391     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3392     {
3393         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3394         hb_audio_config_init(audio);
3395         audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3396         /* We go ahead and assign values to our audio->out.<properties> */
3397         audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3398         audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3399         audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3400         audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3401         audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3402         audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3403         
3404         hb_audio_add( job, audio );
3405         free(audio);
3406         
3407     }
3408
3409     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3410     {
3411         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3412         hb_audio_config_init(audio);
3413         audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3414         /* We go ahead and assign values to our audio->out.<properties> */
3415         audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3416         audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3417         audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3418         audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3419         audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3420         audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3421         
3422         hb_audio_add( job, audio );
3423         free(audio);
3424         
3425     }
3426
3427     
3428     
3429     /* Filters */
3430     
3431     /* Though Grayscale is not really a filter, per se
3432      * we put it here since its in the filters panel
3433      */
3434      
3435     if ([fPictureController grayscale])
3436     {
3437         job->grayscale = 1;
3438     }
3439     else
3440     {
3441         job->grayscale = 0;
3442     }
3443     
3444     /* Initialize the filters list */
3445     job->filters = hb_list_init();
3446     
3447     /* Now lets call the filters if applicable.
3448     * The order of the filters is critical
3449     */
3450     
3451         /* Detelecine */
3452     if ([fPictureController detelecine] == 1)
3453     {
3454         /* use a custom detelecine string */
3455         hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3456         hb_list_add( job->filters, &hb_filter_detelecine );
3457     }
3458     if ([fPictureController detelecine] == 2)
3459     {
3460         /* Default */
3461         hb_list_add( job->filters, &hb_filter_detelecine );
3462     }
3463     
3464     
3465     
3466     if ([fPictureController useDecomb] == 1)
3467     {
3468         /* Decomb */
3469         /* we add the custom string if present */
3470         if ([fPictureController decomb] == 1)
3471         {
3472             /* use a custom decomb string */
3473             hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3474             hb_list_add( job->filters, &hb_filter_decomb );
3475         }
3476         if ([fPictureController decomb] == 2)
3477         {
3478             /* Run old deinterlacer fd by default */
3479             //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3480             hb_list_add( job->filters, &hb_filter_decomb );
3481         }
3482     }
3483     else
3484     {
3485         
3486         /* Deinterlace */
3487         if ([fPictureController deinterlace] == 1)
3488         {
3489             /* we add the custom string if present */
3490             hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3491             hb_list_add( job->filters, &hb_filter_deinterlace );            
3492         }
3493         else if ([fPictureController deinterlace] == 2)
3494         {
3495             /* Run old deinterlacer fd by default */
3496             hb_filter_deinterlace.settings = "-1"; 
3497             hb_list_add( job->filters, &hb_filter_deinterlace );
3498         }
3499         else if ([fPictureController deinterlace] == 3)
3500         {
3501             /* Yadif mode 0 (without spatial deinterlacing.) */
3502             hb_filter_deinterlace.settings = "2"; 
3503             hb_list_add( job->filters, &hb_filter_deinterlace );            
3504         }
3505         else if ([fPictureController deinterlace] == 4)
3506         {
3507             /* Yadif (with spatial deinterlacing) */
3508             hb_filter_deinterlace.settings = "0"; 
3509             hb_list_add( job->filters, &hb_filter_deinterlace );            
3510         }
3511         
3512         }
3513     
3514     /* Denoise */
3515         if ([fPictureController denoise] == 1) // custom in popup
3516         {
3517                 /* we add the custom string if present */
3518         hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String]; 
3519         hb_list_add( job->filters, &hb_filter_denoise );        
3520         }
3521     else if ([fPictureController denoise] == 2) // Weak in popup
3522         {
3523                 hb_filter_denoise.settings = "2:1:2:3"; 
3524         hb_list_add( job->filters, &hb_filter_denoise );        
3525         }
3526         else if ([fPictureController denoise] == 3) // Medium in popup
3527         {
3528                 hb_filter_denoise.settings = "3:2:2:3"; 
3529         hb_list_add( job->filters, &hb_filter_denoise );        
3530         }
3531         else if ([fPictureController denoise] == 4) // Strong in popup
3532         {
3533                 hb_filter_denoise.settings = "7:7:5:5"; 
3534         hb_list_add( job->filters, &hb_filter_denoise );        
3535         }
3536     
3537     
3538     /* Deblock  (uses pp7 default) */
3539     /* NOTE: even though there is a valid deblock setting of 0 for the filter, for 
3540      * the macgui's purposes a value of 0 actually means to not even use the filter
3541      * current hb_filter_deblock.settings valid ranges are from 5 - 15 
3542      */
3543     if ([fPictureController deblock] != 0)
3544     {
3545         NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3546         hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3547         hb_list_add( job->filters, &hb_filter_deblock );
3548     }
3549
3550 }
3551
3552
3553 #pragma mark -
3554 #pragma mark Job Handling
3555
3556
3557 - (void) prepareJob
3558 {
3559     
3560     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3561     hb_list_t  * list  = hb_get_titles( fQueueEncodeLibhb );
3562     hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3563     hb_job_t * job = title->job;
3564     hb_audio_config_t * audio;
3565     /* Title Angle for dvdnav */
3566     job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3567     
3568     if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3569     {
3570         /* Chapter selection */
3571         [self writeToActivityLog: "Start / Stop set to chapters"];
3572         job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3573         job->chapter_end   = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3574     }
3575     else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3576     {
3577         /* we are pts based start / stop */
3578         [self writeToActivityLog: "Start / Stop set to seconds ..."];
3579         
3580         /* 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
3581          * 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.
3582          */
3583         /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3584         /* get the start seconds from the start seconds field */
3585         int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3586         //job->start_at_preview = start_seconds;
3587         /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3588         //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3589         job->pts_to_start = start_seconds * 90000LL;
3590         /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3591         int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3592         job->pts_to_stop = stop_seconds * 90000LL;
3593
3594         /* A bunch of verbose activity log messages to check on what should be expected */
3595         [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3596         [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];
3597         [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3598         [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3599         [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3600         [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];
3601     }
3602     else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3603     {
3604         /* we are frame based start / stop */
3605         [self writeToActivityLog: "Start / Stop set to frames ..."];
3606         
3607         /* 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
3608          * 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.
3609          */
3610         /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3611         /* get the start seconds from the start seconds field */
3612         int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3613         //job->start_at_preview = start_seconds;
3614         /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3615         //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3616         job->frame_to_start = start_frame;
3617         /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3618         int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3619         job->frame_to_stop = stop_frame;
3620
3621         /* A bunch of verbose activity log messages to check on what should be expected */
3622         [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3623         [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3624         [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3625     }
3626
3627         
3628         
3629     
3630     /* Format (Muxer) and Video Encoder */
3631     job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3632     job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3633     
3634     
3635     /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3636     if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3637     {
3638         job->largeFileSize = 1;
3639     }
3640     else
3641     {
3642         job->largeFileSize = 0;
3643     }
3644     /* We set http optimized mp4 here */
3645     if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3646     {
3647         job->mp4_optimize = 1;
3648     }
3649     else
3650     {
3651         job->mp4_optimize = 0;
3652     }
3653
3654         
3655     /* We set the chapter marker extraction here based on the format being
3656      mpeg4 or mkv and the checkbox being checked */
3657     if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3658     {
3659         job->chapter_markers = 1;
3660         
3661         /* now lets get our saved chapter names out the array in the queue file
3662          * and insert them back into the title chapter list. We have it here,
3663          * because unless we are inserting chapter markers there is no need to
3664          * spend the overhead of iterating through the chapter names array imo
3665          * Also, note that if for some reason we don't apply chapter names, the
3666          * chapters just come out 001, 002, etc. etc.
3667          */
3668          
3669         NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3670         int i = 0;
3671         NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3672         id tempObject;
3673         while (tempObject = [enumerator nextObject])
3674         {
3675             hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3676             if( chapter != NULL )
3677             {
3678                 strncpy( chapter->title, [tempObject UTF8String], 1023);
3679                 chapter->title[1023] = '\0';
3680             }
3681             i++;
3682         }
3683     }
3684     else
3685     {
3686         job->chapter_markers = 0;
3687     }
3688     
3689     if( job->vcodec & HB_VCODEC_X264 )
3690     {
3691                 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3692             {
3693             job->ipod_atom = 1;
3694                 }
3695         else
3696         {
3697             job->ipod_atom = 0;
3698         }
3699                 
3700                 
3701                 /* Below Sends x264 options to the core library if x264 is selected*/
3702                 /* Lets use this as per Nyx, Thanks Nyx!*/
3703                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3704                 /* Turbo first pass if two pass and Turbo First pass is selected */
3705                 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3706                 {
3707                         /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3708                         NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3709                         /* append the "Turbo" string variable to the existing opts string.
3710              Note: the "Turbo" string must be appended, not prepended to work properly*/
3711                         NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3712                         strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3713                 }
3714                 else
3715                 {
3716                         strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3717                 }
3718         
3719     }
3720     
3721     
3722     /* Picture Size Settings */
3723     job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
3724     job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
3725     
3726     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
3727     job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
3728     job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3729     if ([[queueToApply objectForKey:@"PicturePAR"]  intValue] == 3)
3730     {
3731         /* insert our custom values here for capuj */
3732         job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"]  intValue];
3733         job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"]  intValue];
3734         
3735         job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3736         
3737         job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"]  intValue];
3738         job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"]  intValue];
3739         
3740         job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"]  floatValue];
3741         job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"]  floatValue];
3742     }
3743     
3744     /* Here we use the crop values saved at the time the preset was saved */
3745     job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
3746     job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
3747     job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
3748     job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
3749     
3750     /* Video settings */
3751     /* Framerate */
3752     
3753     /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3754      * and detelecine is on, so we handle that in the logic below
3755      */
3756     job->vfr = 0;
3757     if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3758     {
3759         /* a specific framerate has been chosen */
3760         job->vrate      = 27000000;
3761         job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3762         /* We are not same as source so we set job->cfr to 1 
3763          * to enable constant frame rate since user has specified
3764          * a specific framerate*/
3765         job->cfr = 1;
3766     }
3767     else
3768     {
3769         /* We are same as source (variable) */
3770         job->vrate      = [[queueToApply objectForKey:@"JobVrate"] intValue];
3771         job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3772         /* We are same as source so we set job->cfr to 0 
3773          * to enable true same as source framerate */
3774         job->cfr = 0;
3775         /* If we are same as source and we have detelecine on, we need to turn on
3776          * job->vfr
3777          */
3778         if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3779         {
3780             job->vfr = 1;
3781         }
3782     }
3783     
3784     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3785     {
3786         /* Target size.
3787          Bitrate should already have been calculated and displayed
3788          in fVidBitrateField, so let's just use it same as abr*/
3789         job->vquality = -1.0;
3790         job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3791     }
3792     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3793     {
3794         job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3795         job->vbitrate = 0;
3796         
3797     }
3798     
3799     job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3800     
3801
3802
3803 #pragma mark -
3804 #pragma mark Process Subtitles to libhb
3805
3806 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3807  * which means that we need to account for the offset of non source language settings in from
3808  * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3809  * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3810  * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3811  * to the source tracks position in title->list_subtitle.
3812  */
3813
3814 int subtitle = nil;
3815 int force;
3816 int burned;
3817 int def;
3818 bool one_burned = FALSE;
3819
3820     int i = 0;
3821     NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3822     id tempObject;
3823     while (tempObject = [enumerator nextObject])
3824     {
3825         
3826         subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3827         force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3828         burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3829         def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3830         
3831         /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3832          * we want to ignore it for display as well as encoding.
3833          */
3834         if (subtitle > 0)
3835         {
3836             /* if i is 0, then we are in the first item of the subtitles which we need to 
3837              * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3838              * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3839              */
3840             
3841             /* if we are on the first track and using "Foreign Audio Search" */ 
3842             if (i == 0 && subtitle == 1)
3843             {
3844                 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3845                 
3846                 job->indepth_scan = 1;
3847                 if (burned == 1 || job->mux != HB_MUX_MP4)
3848                 {
3849                     if (burned != 1 && job->mux == HB_MUX_MKV)
3850                     {
3851                         job->select_subtitle_config.dest = PASSTHRUSUB;
3852                     }
3853                     else
3854                     {
3855                         job->select_subtitle_config.dest = RENDERSUB;
3856                     }
3857                     
3858                     job->select_subtitle_config.force = force;
3859                     job->select_subtitle_config.default_track = def;
3860                 }
3861                 
3862                 
3863             }
3864             else
3865             {
3866                 
3867                 /* for the actual source tracks, we must subtract the non source entries so 
3868                  * that the menu index matches the source subtitle_list index for convenience */
3869                 if (i == 0)
3870                 {
3871                     /* for the first track, the source tracks start at menu index 2 ( None is 0,
3872                      * Foreign Language Search is 1) so subtract 2 */
3873                     subtitle = subtitle - 2;
3874                 }
3875                 else
3876                 {
3877                     /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3878                      * so subtract 1. */
3879                     
3880                     subtitle = subtitle - 1;
3881                 }
3882                 
3883                 /* We are setting a source subtitle so access the source subtitle info */  
3884                 hb_subtitle_t * subt;
3885                 
3886                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3887                 
3888                 /* if we are getting the subtitles from an external srt file */
3889                 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3890                 {
3891                     hb_subtitle_config_t sub_config;
3892                     
3893                     sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3894                     
3895                     /* we need to srncpy file name and codeset */
3896                     strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3897                     strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3898                     
3899                     sub_config.force = 0;
3900                     sub_config.dest = PASSTHRUSUB;
3901                     sub_config.default_track = def;
3902                     
3903                     hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3904                 }
3905                 
3906                 
3907                 if (subt != NULL)
3908                 {
3909                     hb_subtitle_config_t sub_config = subt->config;
3910                     
3911                     if (!burned && job->mux == HB_MUX_MKV && 
3912                         subt->format == PICTURESUB)
3913                     {
3914                         sub_config.dest = PASSTHRUSUB;
3915                     }
3916                     else if (!burned && job->mux == HB_MUX_MP4 && 
3917                              subt->format == PICTURESUB)
3918                     {
3919                         // Skip any non-burned vobsubs when output is mp4
3920                         continue;
3921                     }
3922                     else if ( burned && subt->format == PICTURESUB )
3923                     {
3924                         // Only allow one subtitle to be burned into the video
3925                         if (one_burned)
3926                             continue;
3927                         one_burned = TRUE;
3928                     }
3929                     sub_config.force = force;
3930                     sub_config.default_track = def;
3931                     hb_subtitle_add( job, &sub_config, subtitle );
3932                 }   
3933                 
3934             }
3935         }
3936         i++;
3937     }
3938
3939 #pragma mark -
3940
3941    
3942     /* Audio tracks and mixdowns */
3943     /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3944     int audiotrack_count = hb_list_count(job->list_audio);
3945     for( int i = 0; i < audiotrack_count;i++)
3946     {
3947         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3948         hb_list_rem(job->list_audio, temp_audio);
3949     }
3950     /* Now lets add our new tracks to the audio list here */
3951     if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3952     {
3953         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3954         hb_audio_config_init(audio);
3955         audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3956         /* We go ahead and assign values to our audio->out.<properties> */
3957         audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3958         audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3959         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3960         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3961         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3962         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3963         
3964         hb_audio_add( job, audio );
3965         free(audio);
3966     }  
3967     if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3968     {
3969         
3970         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3971         hb_audio_config_init(audio);
3972         audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3973         [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3974         /* We go ahead and assign values to our audio->out.<properties> */
3975         audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3976         audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3977         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3978         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3979         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3980         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3981         
3982         hb_audio_add( job, audio );
3983         free(audio);
3984     }
3985     
3986     if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3987     {
3988         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3989         hb_audio_config_init(audio);
3990         audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3991         /* We go ahead and assign values to our audio->out.<properties> */
3992         audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3993         audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3994         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3995         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3996         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3997         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3998         
3999         hb_audio_add( job, audio );
4000         free(audio);        
4001     }
4002     
4003     if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
4004     {
4005         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4006         hb_audio_config_init(audio);
4007         audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4008         /* We go ahead and assign values to our audio->out.<properties> */
4009         audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4010         audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
4011         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
4012         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
4013         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
4014         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
4015         
4016         hb_audio_add( job, audio );
4017         
4018
4019     }
4020     
4021     /* Filters */ 
4022     job->filters = hb_list_init();
4023     
4024     /* Now lets call the filters if applicable.
4025      * The order of the filters is critical
4026      */
4027     /* Detelecine */
4028     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4029     {
4030         /* use a custom detelecine string */
4031         hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4032         hb_list_add( job->filters, &hb_filter_detelecine );
4033     }
4034     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4035     {
4036         /* Use libhb's default values */
4037         hb_list_add( job->filters, &hb_filter_detelecine );
4038     }
4039     
4040     if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4041     {
4042         /* Decomb */
4043         /* we add the custom string if present */
4044         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4045         {
4046             /* use a custom decomb string */
4047             hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4048             hb_list_add( job->filters, &hb_filter_decomb );
4049         }
4050         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4051         {
4052             /* Use libhb default */
4053             hb_list_add( job->filters, &hb_filter_decomb );
4054         }
4055         
4056     }
4057     else
4058     {
4059         
4060         /* Deinterlace */
4061         if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4062         {
4063             /* we add the custom string if present */
4064             hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4065             hb_list_add( job->filters, &hb_filter_deinterlace );            
4066         }
4067         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4068         {
4069             /* Run old deinterlacer fd by default */
4070             hb_filter_deinterlace.settings = "-1"; 
4071             hb_list_add( job->filters, &hb_filter_deinterlace );
4072         }
4073         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4074         {
4075             /* Yadif mode 0 (without spatial deinterlacing.) */
4076             hb_filter_deinterlace.settings = "2"; 
4077             hb_list_add( job->filters, &hb_filter_deinterlace );            
4078         }
4079         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4080         {
4081             /* Yadif (with spatial deinterlacing) */
4082             hb_filter_deinterlace.settings = "0"; 
4083             hb_list_add( job->filters, &hb_filter_deinterlace );            
4084         }
4085         
4086         
4087     }
4088     /* Denoise */
4089         if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4090         {
4091                 /* we add the custom string if present */
4092         hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4093         hb_list_add( job->filters, &hb_filter_denoise );        
4094         }
4095     else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4096         {
4097                 hb_filter_denoise.settings = "2:1:2:3"; 
4098         hb_list_add( job->filters, &hb_filter_denoise );        
4099         }
4100         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4101         {
4102                 hb_filter_denoise.settings = "3:2:2:3"; 
4103         hb_list_add( job->filters, &hb_filter_denoise );        
4104         }
4105         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4106         {
4107                 hb_filter_denoise.settings = "7:7:5:5"; 
4108         hb_list_add( job->filters, &hb_filter_denoise );        
4109         }
4110     
4111     
4112     /* Deblock  (uses pp7 default) */
4113     /* NOTE: even though there is a valid deblock setting of 0 for the filter, for 
4114      * the macgui's purposes a value of 0 actually means to not even use the filter
4115      * current hb_filter_deblock.settings valid ranges are from 5 - 15 
4116      */
4117     if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4118     {
4119         hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4120         hb_list_add( job->filters, &hb_filter_deblock );
4121     }
4122 [self writeToActivityLog: "prepareJob exiting"];    
4123 }
4124
4125
4126
4127 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4128 */
4129 - (IBAction) addToQueue: (id) sender
4130 {
4131         /* We get the destination directory from the destination field here */
4132         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4133         /* We check for a valid destination here */
4134         if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
4135         {
4136                 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4137         return;
4138         }
4139     
4140     BOOL fileExists;
4141     fileExists = NO;
4142     
4143     BOOL fileExistsInQueue;
4144     fileExistsInQueue = NO;
4145     
4146     /* We check for and existing file here */
4147     if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4148     {
4149         fileExists = YES;
4150     }
4151     
4152     /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4153     int i = 0;
4154     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4155         id tempObject;
4156         while (tempObject = [enumerator nextObject])
4157         {
4158                 NSDictionary *thisQueueDict = tempObject;
4159                 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4160                 {
4161                         fileExistsInQueue = YES;        
4162                 }
4163         i++;
4164         }
4165     
4166     
4167         if(fileExists == YES)
4168     {
4169         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4170                                   NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4171                                   @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4172                                   NULL, NULL, [NSString stringWithFormat:
4173                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4174                                                [fDstFile2Field stringValue]] );
4175     }
4176     else if (fileExistsInQueue == YES)
4177     {
4178     NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4179                                   NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4180                                   @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4181                                   NULL, NULL, [NSString stringWithFormat:
4182                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4183                                                [fDstFile2Field stringValue]] );
4184     }
4185     else
4186     {
4187         [self doAddToQueue];
4188     }
4189 }
4190
4191 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4192    the user if they want to overwrite an exiting movie file.
4193 */
4194 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4195     returnCode: (int) returnCode contextInfo: (void *) contextInfo
4196 {
4197     if( returnCode == NSAlertAlternateReturn )
4198         [self doAddToQueue];
4199 }
4200
4201 - (void) doAddToQueue
4202 {
4203     [self addQueueFileItem ];
4204 }
4205
4206
4207
4208 /* Rip: puts up an alert before ultimately calling doRip
4209 */
4210 - (IBAction) Rip: (id) sender
4211 {
4212     [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4213     /* Rip or Cancel ? */
4214     hb_state_t s;
4215     hb_get_state2( fQueueEncodeLibhb, &s );
4216     
4217     if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4218         {
4219         [self Cancel: sender];
4220         return;
4221     }
4222     
4223     /* We check to see if we need to warn the user that the computer will go to sleep
4224                  or shut down when encoding is finished */
4225                 [self remindUserOfSleepOrShutdown];
4226     
4227     // If there are pending jobs in the queue, then this is a rip the queue
4228     if (fPendingCount > 0)
4229     {
4230         /* here lets start the queue with the first pending item */
4231         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4232         
4233         return;
4234     }
4235     
4236     // Before adding jobs to the queue, check for a valid destination.
4237     
4238     NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4239     if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
4240     {
4241         NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4242         return;
4243     }
4244     
4245     /* We check for duplicate name here */
4246     if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4247     {
4248         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4249                                   NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4250                                   @selector( overWriteAlertDone:returnCode:contextInfo: ),
4251                                   NULL, NULL, [NSString stringWithFormat:
4252                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4253                                                [fDstFile2Field stringValue]] );
4254         
4255         // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4256     }
4257     else
4258     {
4259         /* if there are no pending jobs in the queue, then add this one to the queue and rip
4260          otherwise, just rip the queue */
4261         if(fPendingCount == 0)
4262         {
4263             [self doAddToQueue];
4264         }
4265         
4266         /* go right to processing the new queue encode */
4267         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4268         
4269     }
4270 }
4271
4272 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4273    want to overwrite an exiting movie file.
4274 */
4275 - (void) overWriteAlertDone: (NSWindow *) sheet
4276     returnCode: (int) returnCode contextInfo: (void *) contextInfo
4277 {
4278     if( returnCode == NSAlertAlternateReturn )
4279     {
4280         /* if there are no jobs in the queue, then add this one to the queue and rip 
4281         otherwise, just rip the queue */
4282         if( fPendingCount == 0 )
4283         {
4284             [self doAddToQueue];
4285         }
4286
4287         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4288         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4289         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4290       
4291     }
4292 }
4293
4294 - (void) remindUserOfSleepOrShutdown
4295 {
4296        if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4297        {
4298                /*Warn that computer will sleep after encoding*/
4299                int reminduser;
4300                NSBeep();
4301                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);
4302                [NSApp requestUserAttention:NSCriticalRequest];
4303                if ( reminduser == NSAlertAlternateReturn )
4304                {
4305                        [self showPreferencesWindow:nil];
4306                }
4307        }
4308        else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4309        {
4310                /*Warn that computer will shut down after encoding*/
4311                int reminduser;
4312                NSBeep();
4313                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);
4314                [NSApp requestUserAttention:NSCriticalRequest];
4315                if ( reminduser == NSAlertAlternateReturn )
4316                {
4317                        [self showPreferencesWindow:nil];
4318                }
4319        }
4320
4321 }
4322
4323
4324 - (void) doRip
4325 {
4326     /* Let libhb do the job */
4327     hb_start( fQueueEncodeLibhb );
4328     /*set the fEncodeState State */
4329         fEncodeState = 1;
4330 }
4331
4332
4333 //------------------------------------------------------------------------------------
4334 // Displays an alert asking user if the want to cancel encoding of current job.
4335 // Cancel: returns immediately after posting the alert. Later, when the user
4336 // acknowledges the alert, doCancelCurrentJob is called.
4337 //------------------------------------------------------------------------------------
4338 - (IBAction)Cancel: (id)sender
4339 {
4340     if (!fQueueController) return;
4341     
4342   hb_pause( fQueueEncodeLibhb );
4343     NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4344    
4345     // Which window to attach the sheet to?
4346     NSWindow * docWindow;
4347     if ([sender respondsToSelector: @selector(window)])
4348         docWindow = [sender window];
4349     else
4350         docWindow = fWindow;
4351         
4352     NSBeginCriticalAlertSheet(
4353             alertTitle,
4354             NSLocalizedString(@"Continue Encoding", nil),
4355             NSLocalizedString(@"Cancel Current and Stop", nil),
4356             NSLocalizedString(@"Cancel Current and Continue", nil),
4357             docWindow, self,
4358             nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4359             NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4360     
4361     // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4362 }
4363
4364 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4365 {
4366    hb_resume( fQueueEncodeLibhb );
4367      if (returnCode == NSAlertOtherReturn)
4368     {
4369         [self doCancelCurrentJob];  // <- this also stops libhb
4370     }
4371     if (returnCode == NSAlertAlternateReturn)
4372     {
4373     [self doCancelCurrentJobAndStop];
4374     }
4375 }
4376
4377 //------------------------------------------------------------------------------------
4378 // Cancels and deletes the current job and stops libhb from processing the remaining
4379 // encodes.
4380 //------------------------------------------------------------------------------------
4381 - (void) doCancelCurrentJob
4382 {
4383     // Stop the current job. hb_stop will only cancel the current pass and then set
4384     // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4385     // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4386     // remaining passes of the job and then start the queue back up if there are any
4387     // remaining jobs.
4388      
4389     
4390     hb_stop( fQueueEncodeLibhb );
4391     
4392     // Delete all remaining jobs since libhb doesn't do this on its own.
4393             hb_job_t * job;
4394             while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4395                 hb_rem( fQueueEncodeLibhb, job );
4396                 
4397     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
4398     
4399     // now that we've stopped the currently encoding job, lets mark it as cancelled
4400     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4401     // and as always, save it in the queue .plist...
4402     /* We save all of the Queue data here */
4403     [self saveQueueFileItem];
4404     // so now lets move to 
4405     currentQueueEncodeIndex++ ;
4406     // ... and see if there are more items left in our queue
4407     int queueItems = [QueueFileArray count];
4408     /* If we still have more items in our queue, lets go to the next one */
4409     if (currentQueueEncodeIndex < queueItems)
4410     {
4411     [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4412     [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4413     
4414     [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4415     }
4416     else
4417     {
4418         [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4419     }
4420
4421 }
4422
4423 - (void) doCancelCurrentJobAndStop
4424 {
4425     hb_stop( fQueueEncodeLibhb );
4426     
4427     // Delete all remaining jobs since libhb doesn't do this on its own.
4428             hb_job_t * job;
4429             while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4430                 hb_rem( fQueueEncodeLibhb, job );
4431                 
4432                 
4433     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
4434     
4435     // now that we've stopped the currently encoding job, lets mark it as cancelled
4436     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4437     // and as always, save it in the queue .plist...
4438     /* We save all of the Queue data here */
4439     [self saveQueueFileItem];
4440     // so now lets move to 
4441     currentQueueEncodeIndex++ ;
4442     [self writeToActivityLog: "cancelling current job and stopping the queue"];
4443 }
4444 - (IBAction) Pause: (id) sender
4445 {
4446     hb_state_t s;
4447     hb_get_state2( fQueueEncodeLibhb, &s );
4448
4449     if( s.state == HB_STATE_PAUSED )
4450     {
4451         hb_resume( fQueueEncodeLibhb );
4452     }
4453     else
4454     {
4455         hb_pause( fQueueEncodeLibhb );
4456     }
4457 }
4458
4459 #pragma mark -
4460 #pragma mark GUI Controls Changed Methods
4461
4462 - (IBAction) titlePopUpChanged: (id) sender
4463 {
4464     hb_list_t  * list  = hb_get_titles( fHandle );
4465     hb_title_t * title = (hb_title_t*)
4466         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4467
4468     /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4469     if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4470     {
4471         /* we set the default name according to the new title->name */
4472         [fDstFile2Field setStringValue: [NSString stringWithFormat:
4473                                          @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4474                                          [NSString stringWithUTF8String: title->name],
4475                                          [[fDstFile2Field stringValue] pathExtension]]];
4476         
4477         /* Change the source to read out the parent folder also */
4478         [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
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                 // CA_AAC
5590                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5591                 [menuItem setTag: HB_ACODEC_CA_AAC];
5592                 // FAAC
5593                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5594                 [menuItem setTag: HB_ACODEC_FAAC];
5595                 // AC3 Passthru
5596                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5597                 [menuItem setTag: HB_ACODEC_AC3];
5598                 break;
5599                 
5600             case 1:
5601                 /* MKV */
5602                 // CA_AAC
5603                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5604                 [menuItem setTag: HB_ACODEC_CA_AAC];
5605                 // FAAC
5606                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5607                 [menuItem setTag: HB_ACODEC_FAAC];
5608                 // AC3 Passthru
5609                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5610                 [menuItem setTag: HB_ACODEC_AC3];
5611                 // DTS Passthru
5612                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5613                 [menuItem setTag: HB_ACODEC_DCA];
5614                 // MP3
5615                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5616                 [menuItem setTag: HB_ACODEC_LAME];
5617                 // Vorbis
5618                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5619                 [menuItem setTag: HB_ACODEC_VORBIS];
5620                 break;
5621         }
5622         [audiocodecPopUp selectItemAtIndex:0];
5623     }
5624     else
5625     {
5626         [audiocodecPopUp setEnabled:NO];
5627     }
5628 }
5629
5630 - (IBAction) audioTrackPopUpChanged: (id) sender
5631 {
5632     /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5633     [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5634 }
5635
5636 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5637 {
5638     
5639     /* make sure we have a selected title before continuing */
5640     if (fTitle == NULL) return;
5641     /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5642     * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5643     */
5644     if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5645     {
5646         [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5647     }
5648     if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5649     {
5650         [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5651     }
5652     if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5653     {
5654         [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5655     }
5656     if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5657     {
5658         [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5659     }
5660     
5661     /* Now lets make the sender the appropriate Audio Track popup from this point on */
5662     if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5663     {
5664         sender = fAudLang1PopUp;
5665     }
5666     if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5667     {
5668         sender = fAudLang2PopUp;
5669     }
5670     if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5671     {
5672         sender = fAudLang3PopUp;
5673     }
5674     if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5675     {
5676         sender = fAudLang4PopUp;
5677     }
5678     
5679     /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5680     NSPopUpButton * mixdownPopUp;
5681     NSPopUpButton * audiocodecPopUp;
5682     NSPopUpButton * sampleratePopUp;
5683     NSPopUpButton * bitratePopUp;
5684     if (sender == fAudLang1PopUp)
5685     {
5686         mixdownPopUp = fAudTrack1MixPopUp;
5687         audiocodecPopUp = fAudTrack1CodecPopUp;
5688         sampleratePopUp = fAudTrack1RatePopUp;
5689         bitratePopUp = fAudTrack1BitratePopUp;
5690     }
5691     else if (sender == fAudLang2PopUp)
5692     {
5693         mixdownPopUp = fAudTrack2MixPopUp;
5694         audiocodecPopUp = fAudTrack2CodecPopUp;
5695         sampleratePopUp = fAudTrack2RatePopUp;
5696         bitratePopUp = fAudTrack2BitratePopUp;
5697     }
5698     else if (sender == fAudLang3PopUp)
5699     {
5700         mixdownPopUp = fAudTrack3MixPopUp;
5701         audiocodecPopUp = fAudTrack3CodecPopUp;
5702         sampleratePopUp = fAudTrack3RatePopUp;
5703         bitratePopUp = fAudTrack3BitratePopUp;
5704     }
5705     else
5706     {
5707         mixdownPopUp = fAudTrack4MixPopUp;
5708         audiocodecPopUp = fAudTrack4CodecPopUp;
5709         sampleratePopUp = fAudTrack4RatePopUp;
5710         bitratePopUp = fAudTrack4BitratePopUp;
5711     }
5712
5713     /* get the index of the selected audio Track*/
5714     int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5715
5716     /* pointer for the hb_audio_s struct we will use later on */
5717     hb_audio_config_t * audio;
5718
5719     int acodec;
5720     /* check if the audio mixdown controls need their enabled state changing */
5721     [self setEnabledStateOfAudioMixdownControls:nil];
5722
5723     if (thisAudioIndex != -1)
5724     {
5725
5726         /* get the audio */
5727         audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5728
5729         /* actually manipulate the proper mixdowns here */
5730         /* delete the previous audio mixdown options */
5731         [mixdownPopUp removeAllItems];
5732
5733         acodec = [[audiocodecPopUp selectedItem] tag];
5734
5735         if (audio != NULL)
5736         {
5737
5738             /* find out if our selected output audio codec supports mono and / or 6ch */
5739             /* we also check for an input codec of AC3 or DCA,
5740              as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5741             /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5742              but this may change in the future, so they are separated for flexibility */
5743             int audioCodecsSupportMono =
5744                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5745                     (acodec != HB_ACODEC_LAME);
5746             int audioCodecsSupport6Ch =
5747                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5748                     (acodec != HB_ACODEC_LAME);
5749             
5750             /* check for AC-3 passthru */
5751             if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5752             {
5753                 
5754             NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5755                  [NSString stringWithUTF8String: "AC3 Passthru"]
5756                                                action: NULL keyEquivalent: @""];
5757              [menuItem setTag: HB_ACODEC_AC3];   
5758             }
5759             else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5760             {
5761             NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5762                  [NSString stringWithUTF8String: "DTS Passthru"]
5763                                                action: NULL keyEquivalent: @""];
5764              [menuItem setTag: HB_ACODEC_DCA]; 
5765             }
5766             else
5767             {
5768                 
5769                 /* add the appropriate audio mixdown menuitems to the popupbutton */
5770                 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5771                  so that we can reference the mixdown later */
5772                 
5773                 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5774                 int minMixdownUsed = 0;
5775                 int maxMixdownUsed = 0;
5776                 
5777                 /* get the input channel layout without any lfe channels */
5778                 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5779                 
5780                 /* do we want to add a mono option? */
5781                 if (audioCodecsSupportMono == 1)
5782                 {
5783                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5784                                             [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5785                                                                           action: NULL keyEquivalent: @""];
5786                     [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5787                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5788                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5789                 }
5790                 
5791                 /* do we want to add a stereo option? */
5792                 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5793                 /* also offer stereo if we have a stereo-or-better source */
5794                 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5795                 {
5796                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5797                                             [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5798                                                                           action: NULL keyEquivalent: @""];
5799                     [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5800                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5801                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5802                 }
5803                 
5804                 /* do we want to add a dolby surround (DPL1) option? */
5805                 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5806                 {
5807                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5808                                             [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5809                                                                           action: NULL keyEquivalent: @""];
5810                     [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5811                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5812                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5813                 }
5814                 
5815                 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5816                 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5817                 {
5818                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5819                                             [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5820                                                                           action: NULL keyEquivalent: @""];
5821                     [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5822                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5823                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5824                 }
5825                 
5826                 /* do we want to add a 6-channel discrete option? */
5827                 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5828                 {
5829                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5830                                             [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5831                                                                           action: NULL keyEquivalent: @""];
5832                     [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5833                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5834                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5835                 }
5836                 
5837                 /* do we want to add an AC-3 passthrough option? */
5838                 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3) 
5839                 {
5840                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5841                                             [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5842                                                                           action: NULL keyEquivalent: @""];
5843                     [menuItem setTag: HB_ACODEC_AC3];
5844                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5845                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5846                 }
5847                 
5848                 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5849                 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA) 
5850                 {
5851                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5852                                             [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5853                                                                           action: NULL keyEquivalent: @""];
5854                     [menuItem setTag: HB_ACODEC_DCA];
5855                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5856                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5857                 }
5858                 
5859                 /* auto-select the best mixdown based on our saved mixdown preference */
5860                 
5861                 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5862                 /* ultimately this should be a prefs option */
5863                 int useMixdown;
5864                 
5865                 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5866                 if (mixdownToUse > 0)
5867                 {
5868                     useMixdown = mixdownToUse;
5869                 }
5870                 else
5871                 {
5872                     useMixdown = HB_AMIXDOWN_DOLBYPLII;
5873                 }
5874                 
5875                 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5876                 if (useMixdown > maxMixdownUsed)
5877                 { 
5878                     useMixdown = maxMixdownUsed;
5879                 }
5880                 
5881                 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5882                 if (useMixdown < minMixdownUsed)
5883                 { 
5884                     useMixdown = minMixdownUsed;
5885                 }
5886                 
5887                 /* select the (possibly-amended) preferred mixdown */
5888                 [mixdownPopUp selectItemWithTag: useMixdown];
5889
5890             }
5891             /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5892              * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5893              */
5894             if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5895             {
5896                 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5897             }
5898             
5899             /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5900              * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5901              */
5902             if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5903             {
5904                 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5905             }
5906             
5907             /* Setup our samplerate and bitrate popups we will need based on mixdown */
5908             [self audioTrackMixdownChanged: mixdownPopUp];             
5909         }
5910     
5911     }
5912     if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5913     {
5914         [self autoSetM4vExtension: sender];
5915     }
5916 }
5917
5918 - (IBAction) audioTrackMixdownChanged: (id) sender
5919 {
5920     
5921     int acodec;
5922     /* setup pointers to all of the other audio track controls
5923     * we will need later
5924     */
5925     NSPopUpButton * mixdownPopUp;
5926     NSPopUpButton * sampleratePopUp;
5927     NSPopUpButton * bitratePopUp;
5928     NSPopUpButton * audiocodecPopUp;
5929     NSPopUpButton * audiotrackPopUp;
5930     NSSlider * drcSlider;
5931     NSTextField * drcField;
5932     if (sender == fAudTrack1MixPopUp)
5933     {
5934         audiotrackPopUp = fAudLang1PopUp;
5935         audiocodecPopUp = fAudTrack1CodecPopUp;
5936         mixdownPopUp = fAudTrack1MixPopUp;
5937         sampleratePopUp = fAudTrack1RatePopUp;
5938         bitratePopUp = fAudTrack1BitratePopUp;
5939         drcSlider = fAudTrack1DrcSlider;
5940         drcField = fAudTrack1DrcField;
5941     }
5942     else if (sender == fAudTrack2MixPopUp)
5943     {
5944         audiotrackPopUp = fAudLang2PopUp;
5945         audiocodecPopUp = fAudTrack2CodecPopUp;
5946         mixdownPopUp = fAudTrack2MixPopUp;
5947         sampleratePopUp = fAudTrack2RatePopUp;
5948         bitratePopUp = fAudTrack2BitratePopUp;
5949         drcSlider = fAudTrack2DrcSlider;
5950         drcField = fAudTrack2DrcField;
5951     }
5952     else if (sender == fAudTrack3MixPopUp)
5953     {
5954         audiotrackPopUp = fAudLang3PopUp;
5955         audiocodecPopUp = fAudTrack3CodecPopUp;
5956         mixdownPopUp = fAudTrack3MixPopUp;
5957         sampleratePopUp = fAudTrack3RatePopUp;
5958         bitratePopUp = fAudTrack3BitratePopUp;
5959         drcSlider = fAudTrack3DrcSlider;
5960         drcField = fAudTrack3DrcField;
5961     }
5962     else
5963     {
5964         audiotrackPopUp = fAudLang4PopUp;
5965         audiocodecPopUp = fAudTrack4CodecPopUp;
5966         mixdownPopUp = fAudTrack4MixPopUp;
5967         sampleratePopUp = fAudTrack4RatePopUp;
5968         bitratePopUp = fAudTrack4BitratePopUp;
5969         drcSlider = fAudTrack4DrcSlider;
5970         drcField = fAudTrack4DrcField;
5971     }
5972     acodec = [[audiocodecPopUp selectedItem] tag];
5973     /* storage variable for the min and max bitrate allowed for this codec */
5974     int minbitrate;
5975     int maxbitrate;
5976     
5977     switch( acodec )
5978     {
5979         case HB_ACODEC_FAAC:
5980             /* check if we have a 6ch discrete conversion in either audio track */
5981             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5982             {
5983                 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5984                 minbitrate = 192;
5985                 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
5986                 maxbitrate = 448;
5987                 break;
5988             }
5989             else
5990             {
5991                 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5992                 minbitrate = 32;
5993                 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5994                 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5995                 maxbitrate = 160;
5996                 break;
5997             }
5998
5999         case HB_ACODEC_CA_AAC:
6000             /* check if we have a 6ch discrete conversion in either audio track */
6001             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6002             {
6003                 minbitrate = 128;
6004                 maxbitrate = 768;
6005                 break;
6006             }
6007             else
6008             {
6009                 minbitrate = 64;
6010                 maxbitrate = 320;
6011                 break;
6012             }
6013
6014             case HB_ACODEC_LAME:
6015             /* Lame is happy using our min bitrate of 32 kbps */
6016             minbitrate = 32;
6017             /* Lame won't encode if the bitrate is higher than 320 kbps */
6018             maxbitrate = 320;
6019             break;
6020             
6021             case HB_ACODEC_VORBIS:
6022             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6023             {
6024                 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6025                 minbitrate = 192;
6026                 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6027                 maxbitrate = 384;
6028                 break;
6029             }
6030             else
6031             {
6032                 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6033                 minbitrate = 48;
6034                 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6035                 maxbitrate = 384;
6036                 break;
6037             }
6038             
6039             default:
6040             /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6041             minbitrate = 32;
6042             maxbitrate = 384;
6043             
6044     }
6045     
6046     /* make sure we have a selected title before continuing */
6047     if (fTitle == NULL) return;
6048     /* get the audio so we can find out what input rates are*/
6049     hb_audio_config_t * audio;
6050     audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6051     int inputbitrate = audio->in.bitrate / 1000;
6052     int inputsamplerate = audio->in.samplerate;
6053     
6054     if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6055     {
6056         [bitratePopUp removeAllItems];
6057         
6058         for( int i = 0; i < hb_audio_bitrates_count; i++ )
6059         {
6060             if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6061             {
6062                 /* add a new menuitem for this bitrate */
6063                 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6064                                         [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6065                                                                       action: NULL keyEquivalent: @""];
6066                 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6067                 [menuItem setTag: hb_audio_bitrates[i].rate];
6068             }
6069         }
6070         
6071         /* select the default bitrate (but use 384 for 6-ch AAC) */
6072         if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6073         {
6074             [bitratePopUp selectItemWithTag: 384];
6075         }
6076         else
6077         {
6078             [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6079         }
6080     }
6081     /* populate and set the sample rate popup */
6082     /* Audio samplerate */
6083     [sampleratePopUp removeAllItems];
6084     /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6085     NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6086     [menuItem setTag: inputsamplerate];
6087     
6088     for( int i = 0; i < hb_audio_rates_count; i++ )
6089     {
6090         NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6091                                 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6092                                                                  action: NULL keyEquivalent: @""];
6093         [menuItem setTag: hb_audio_rates[i].rate];
6094     }
6095     /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6096     * and there is no compelling reason to use anything else as default, though the users default
6097     * preset will likely override any setting chosen here.
6098     */
6099     [sampleratePopUp selectItemWithTag: inputsamplerate];
6100     
6101     
6102     /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6103     * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6104     * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6105     */
6106     if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6107     {
6108         
6109         /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6110         [bitratePopUp removeAllItems];
6111         NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6112                                 [NSString stringWithFormat:@"%d", inputbitrate]
6113                                                               action: NULL keyEquivalent: @""];
6114         [menuItem setTag: inputbitrate];
6115         /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6116         [bitratePopUp setEnabled: NO];
6117         [sampleratePopUp setEnabled: NO];
6118         
6119         [drcSlider setFloatValue: 0.00];
6120         [self audioDRCSliderChanged: drcSlider];
6121         [drcSlider setEnabled: NO];
6122         [drcField setEnabled: NO];
6123     }
6124     else
6125     {
6126         [sampleratePopUp setEnabled: YES];
6127         [bitratePopUp setEnabled: YES];
6128         [drcSlider setEnabled: YES];
6129         [drcField setEnabled: YES];
6130     }
6131 [self calculateBitrate:nil];    
6132 }
6133
6134 - (IBAction) audioDRCSliderChanged: (id) sender
6135 {
6136     NSSlider * drcSlider;
6137     NSTextField * drcField;
6138     if (sender == fAudTrack1DrcSlider)
6139     {
6140         drcSlider = fAudTrack1DrcSlider;
6141         drcField = fAudTrack1DrcField;
6142     }
6143     else if (sender == fAudTrack2DrcSlider)
6144     {
6145         drcSlider = fAudTrack2DrcSlider;
6146         drcField = fAudTrack2DrcField;
6147     }
6148     else if (sender == fAudTrack3DrcSlider)
6149     {
6150         drcSlider = fAudTrack3DrcSlider;
6151         drcField = fAudTrack3DrcField;
6152     }
6153     else
6154     {
6155         drcSlider = fAudTrack4DrcSlider;
6156         drcField = fAudTrack4DrcField;
6157     }
6158     
6159     /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6160     if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6161     {
6162         [drcSlider setFloatValue:1.0];
6163     }
6164     
6165     
6166     [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6167     /* For now, do not call this until we have an intelligent way to determine audio track selections
6168     * compared to presets
6169     */
6170     //[self customSettingUsed: sender];
6171 }
6172
6173 #pragma mark -
6174
6175 - (IBAction) browseImportSrtFile: (id) sender
6176 {
6177
6178     NSOpenPanel * panel;
6179         
6180     panel = [NSOpenPanel openPanel];
6181     [panel setAllowsMultipleSelection: NO];
6182     [panel setCanChooseFiles: YES];
6183     [panel setCanChooseDirectories: NO ];
6184     NSString * sourceDirectory;
6185         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6186         {
6187                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6188         }
6189         else
6190         {
6191                 sourceDirectory = @"~/Desktop";
6192                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6193         }
6194     /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6195     NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6196     [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6197                    modalForWindow: fWindow modalDelegate: self
6198                    didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6199                       contextInfo: sender];
6200 }
6201
6202 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6203                      returnCode: (int) returnCode contextInfo: (void *) contextInfo
6204 {
6205     if( returnCode == NSOKButton )
6206     {
6207         NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6208         NSString *importSrtFilePath = [sheet filename];
6209         [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6210         
6211         /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6212         [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6213         
6214         [fSubtitlesTable reloadData];
6215         
6216     }
6217 }                                           
6218
6219 #pragma mark -
6220 #pragma mark Open New Windows
6221
6222 - (IBAction) openHomepage: (id) sender
6223 {
6224     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6225         URLWithString:@"http://handbrake.fr/"]];
6226 }
6227
6228 - (IBAction) openForums: (id) sender
6229 {
6230     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6231         URLWithString:@"http://handbrake.fr/forum/"]];
6232 }
6233 - (IBAction) openUserGuide: (id) sender
6234 {
6235     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6236         URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6237 }
6238
6239 /**
6240  * Shows debug output window.
6241  */
6242 - (IBAction)showDebugOutputPanel:(id)sender
6243 {
6244     [outputPanel showOutputPanel:sender];
6245 }
6246
6247 /**
6248  * Shows preferences window.
6249  */
6250 - (IBAction) showPreferencesWindow: (id) sender
6251 {
6252     NSWindow * window = [fPreferencesController window];
6253     if (![window isVisible])
6254         [window center];
6255
6256     [window makeKeyAndOrderFront: nil];
6257 }
6258
6259 /**
6260  * Shows queue window.
6261  */
6262 - (IBAction) showQueueWindow:(id)sender
6263 {
6264     [fQueueController showQueueWindow:sender];
6265 }
6266
6267
6268 - (IBAction) toggleDrawer:(id)sender {
6269     [fPresetDrawer toggle:self];
6270 }
6271
6272 /**
6273  * Shows Picture Settings Window.
6274  */
6275
6276 - (IBAction) showPicturePanel: (id) sender
6277 {
6278         [fPictureController showPictureWindow:sender];
6279 }
6280
6281 - (void) picturePanelFullScreen
6282 {
6283         [fPictureController setToFullScreenMode];
6284 }
6285
6286 - (void) picturePanelWindowed
6287 {
6288         [fPictureController setToWindowedMode];
6289 }
6290
6291 - (IBAction) showPreviewWindow: (id) sender
6292 {
6293         [fPictureController showPreviewWindow:sender];
6294 }
6295
6296 #pragma mark -
6297 #pragma mark Preset Outline View Methods
6298 #pragma mark - Required
6299 /* These are required by the NSOutlineView Datasource Delegate */
6300
6301
6302 /* used to specify the number of levels to show for each item */
6303 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6304 {
6305     /* currently use no levels to test outline view viability */
6306     if (item == nil) // for an outline view the root level of the hierarchy is always nil
6307     {
6308         return [UserPresets count];
6309     }
6310     else
6311     {
6312         /* we need to return the count of the array in ChildrenArray for this folder */
6313         NSArray *children = nil;
6314         children = [item objectForKey:@"ChildrenArray"];
6315         if ([children count] > 0)
6316         {
6317             return [children count];
6318         }
6319         else
6320         {
6321             return 0;
6322         }
6323     }
6324 }
6325
6326 /* We use this to deterimine children of an item */
6327 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6328 {
6329     
6330     /* we need to return the count of the array in ChildrenArray for this folder */
6331     NSArray *children = nil;
6332     if (item == nil)
6333     {
6334         children = UserPresets;
6335     }
6336     else
6337     {
6338         if ([item objectForKey:@"ChildrenArray"])
6339         {
6340             children = [item objectForKey:@"ChildrenArray"];
6341         }
6342     }   
6343     if ((children == nil) || ( [children count] <= (NSUInteger) index))
6344     {
6345         return nil;
6346     }
6347     else
6348     {
6349         return [children objectAtIndex:index];
6350     }
6351     
6352     
6353     // We are only one level deep, so we can't be asked about children
6354     //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6355     //return nil;
6356 }
6357
6358 /* We use this to determine if an item should be expandable */
6359 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6360 {
6361     
6362     /* we need to return the count of the array in ChildrenArray for this folder */
6363     NSArray *children= nil;
6364     if (item == nil)
6365     {
6366         children = UserPresets;
6367     }
6368     else
6369     {
6370         if ([item objectForKey:@"ChildrenArray"])
6371         {
6372             children = [item objectForKey:@"ChildrenArray"];
6373         }
6374     }   
6375     
6376     /* To deterimine if an item should show a disclosure triangle
6377      * we could do it by the children count as so:
6378      * if ([children count] < 1)
6379      * However, lets leave the triangle show even if there are no
6380      * children to help indicate a folder, just like folder in the
6381      * finder can show a disclosure triangle even when empty
6382      */
6383     
6384     /* We need to determine if the item is a folder */
6385    if ([[item objectForKey:@"Folder"] intValue] == 1)
6386    {
6387         return YES;
6388     }
6389     else
6390     {
6391         return NO;
6392     }
6393     
6394 }
6395
6396 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6397 {
6398     // Our outline view has no levels, but we can still expand every item. Doing so
6399     // just makes the row taller. See heightOfRowByItem below.
6400 //return ![(HBQueueOutlineView*)outlineView isDragging];
6401
6402 return YES;
6403 }
6404
6405
6406 /* Used to tell the outline view which information is to be displayed per item */
6407 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6408 {
6409         /* We have two columns right now, icon and PresetName */
6410         
6411     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6412     {
6413         return [item objectForKey:@"PresetName"];
6414     }
6415     else
6416     {
6417         //return @"";
6418         return nil;
6419     }
6420 }
6421
6422 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6423 {
6424     return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6425 }
6426 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6427 {
6428     return [NSKeyedArchiver archivedDataWithRootObject:item];
6429 }
6430
6431 #pragma mark - Added Functionality (optional)
6432 /* Use to customize the font and display characteristics of the title cell */
6433 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6434 {
6435     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6436     {
6437         NSFont *txtFont;
6438         NSColor *fontColor;
6439         NSColor *shadowColor;
6440         txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6441         /*check to see if its a selected row */
6442         if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6443         {
6444             
6445             fontColor = [NSColor blackColor];
6446             shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6447         }
6448         else
6449         {
6450             if ([[item objectForKey:@"Type"] intValue] == 0)
6451             {
6452                 fontColor = [NSColor blueColor];
6453             }
6454             else // User created preset, use a black font
6455             {
6456                 fontColor = [NSColor blackColor];
6457             }
6458             /* check to see if its a folder */
6459             //if ([[item objectForKey:@"Folder"] intValue] == 1)
6460             //{
6461             //fontColor = [NSColor greenColor];
6462             //}
6463             
6464             
6465         }
6466         /* We use Bold Text for the HB Default */
6467         if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6468         {
6469             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6470         }
6471         /* We use Bold Text for the User Specified Default */
6472         if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6473         {
6474             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6475         }
6476         
6477         
6478         [cell setTextColor:fontColor];
6479         [cell setFont:txtFont];
6480         
6481     }
6482 }
6483
6484 /* We use this to edit the name field in the outline view */
6485 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6486 {
6487     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6488     {
6489         id theRecord;
6490         
6491         theRecord = item;
6492         [theRecord setObject:object forKey:@"PresetName"];
6493         
6494         [self sortPresets];
6495         
6496         [fPresetsOutlineView reloadData];
6497         /* We save all of the preset data here */
6498         [self savePreset];
6499     }
6500 }
6501 /* We use this to provide tooltips for the items in the presets outline view */
6502 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6503 {
6504     //if ([[tc identifier] isEqualToString:@"PresetName"])
6505     //{
6506         /* initialize the tooltip contents variable */
6507         NSString *loc_tip;
6508         /* if there is a description for the preset, we show it in the tooltip */
6509         if ([item objectForKey:@"PresetDescription"])
6510         {
6511             loc_tip = [item objectForKey:@"PresetDescription"];
6512             return (loc_tip);
6513         }
6514         else
6515         {
6516             loc_tip = @"No description available";
6517         }
6518         return (loc_tip);
6519     //}
6520 }
6521
6522 #pragma mark -
6523 #pragma mark Preset Outline View Methods (dragging related)
6524
6525
6526 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6527 {
6528         // Dragging is only allowed for custom presets.
6529     //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6530         if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6531     {
6532         return NO;
6533     }
6534     // Don't retain since this is just holding temporaral drag information, and it is
6535     //only used during a drag!  We could put this in the pboard actually.
6536     fDraggedNodes = items;
6537     // Provide data for our custom type, and simple NSStrings.
6538     [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6539     
6540     // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6541     [pboard setData:[NSData data] forType:DragDropSimplePboardType]; 
6542     
6543     return YES;
6544 }
6545
6546 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6547 {
6548         
6549         // Don't allow dropping ONTO an item since they can't really contain any children.
6550     
6551     BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6552     if (isOnDropTypeProposal)
6553         return NSDragOperationNone;
6554     
6555     // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6556         if (item != nil)
6557         {
6558                 index = [fPresetsOutlineView rowForItem: item] + 1;
6559                 item = nil;
6560         }
6561     
6562     // Don't allow dropping into the Built In Presets.
6563     if (index < presetCurrentBuiltInCount)
6564     {
6565         return NSDragOperationNone;
6566         index = MAX (index, presetCurrentBuiltInCount);
6567         }    
6568         
6569     [outlineView setDropItem:item dropChildIndex:index];
6570     return NSDragOperationGeneric;
6571 }
6572
6573
6574
6575 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6576 {
6577     /* first, lets see if we are dropping into a folder */
6578     if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6579         {
6580     NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6581     childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6582     [childrenArray addObject:item];
6583     [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6584     [childrenArray autorelease];
6585     }
6586     else // We are not, so we just move the preset into the existing array 
6587     {
6588         NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6589         id obj;
6590         NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6591         while (obj = [enumerator nextObject])
6592         {
6593             [moveItems addIndex:[UserPresets indexOfObject:obj]];
6594         }
6595         // Successful drop, lets rearrange the view and save it all
6596         [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6597     }
6598     [fPresetsOutlineView reloadData];
6599     [self savePreset];
6600     return YES;
6601 }
6602
6603 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6604 {
6605     NSUInteger index = [indexSet lastIndex];
6606     NSUInteger aboveInsertIndexCount = 0;
6607     
6608     NSUInteger removeIndex;
6609
6610     if (index >= insertIndex)
6611     {
6612         removeIndex = index + aboveInsertIndexCount;
6613         aboveInsertIndexCount++;
6614     }
6615     else
6616     {
6617         removeIndex = index;
6618         insertIndex--;
6619     }
6620
6621     id object = [[array objectAtIndex:removeIndex] retain];
6622     [array removeObjectAtIndex:removeIndex];
6623     [array insertObject:object atIndex:insertIndex];
6624     [object release];
6625
6626     index = [indexSet indexLessThanIndex:index];
6627 }
6628
6629
6630
6631 #pragma mark - Functional Preset NSOutlineView Methods
6632
6633 - (IBAction)selectPreset:(id)sender
6634 {
6635     
6636     if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6637     {
6638         chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6639         [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6640         
6641         if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6642         {
6643             [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6644         }
6645         else
6646         {
6647             [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6648         }
6649         
6650         /* File Format */
6651         [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6652         [self formatPopUpChanged:nil];
6653         
6654         /* Chapter Markers*/
6655         [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6656         /* check to see if we have only one chapter */
6657         [self chapterPopUpChanged:nil];
6658         
6659         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6660         [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6661         /* Mux mp4 with http optimization */
6662         [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6663         
6664         /* Video encoder */
6665         [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6666         /* We set the advanced opt string here if applicable*/
6667         [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6668         
6669         /* Lets run through the following functions to get variables set there */
6670         [self videoEncoderPopUpChanged:nil];
6671         /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6672         [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6673         [self calculateBitrate:nil];
6674         
6675         /* Video quality */
6676         [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6677         
6678         [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6679         [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6680         
6681         /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6682          * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6683          * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6684          * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6685          * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6686         if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6687         {
6688             /* For the quality slider we need to convert the old percent's to the new rf scales */
6689             float rf =  (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6690             [fVidQualitySlider setFloatValue:rf];
6691             
6692         }
6693         else
6694         {
6695             /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6696             if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6697             {
6698                 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6699             }
6700             else
6701             {
6702                 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6703                 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6704             }
6705         }
6706         
6707         [self videoMatrixChanged:nil];
6708         
6709         /* Video framerate */
6710         /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6711          detected framerate in the fVidRatePopUp so we use index 0*/
6712         if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6713         {
6714             [fVidRatePopUp selectItemAtIndex: 0];
6715         }
6716         else
6717         {
6718             [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6719         }
6720         
6721         
6722         /* 2 Pass Encoding */
6723         [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6724         [self twoPassCheckboxChanged:nil];
6725         
6726         /* Turbo 1st pass for 2 Pass Encoding */
6727         [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6728         
6729         /*Audio*/
6730         /* First we check to see if we are using the current audio track layout based on AudioList array */
6731         if ([chosenPreset objectForKey:@"AudioList"])
6732         {
6733             
6734             /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6735             NSPopUpButton * trackLangPopUp = nil;
6736             NSPopUpButton * mixdownPopUp = nil;
6737             NSPopUpButton * audiocodecPopUp = nil;
6738             NSPopUpButton * sampleratePopUp = nil;
6739             NSPopUpButton * bitratePopUp = nil;
6740             NSSlider      * drcSlider = nil;
6741             
6742             
6743             /* Populate the audio widgets based on the contents of the AudioList array */
6744             int i = 0;
6745             NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6746             id tempObject;
6747             while (tempObject = [enumerator nextObject])
6748             {
6749                 i++;
6750                 if( i == 1 )
6751                 {
6752                     trackLangPopUp = fAudLang1PopUp;
6753                     mixdownPopUp = fAudTrack1MixPopUp;
6754                     audiocodecPopUp = fAudTrack1CodecPopUp;
6755                     sampleratePopUp = fAudTrack1RatePopUp;
6756                     bitratePopUp = fAudTrack1BitratePopUp;
6757                     drcSlider = fAudTrack1DrcSlider;
6758                 }
6759                 if( i == 2 )
6760                 {
6761                     trackLangPopUp = fAudLang2PopUp;
6762                     mixdownPopUp = fAudTrack2MixPopUp;
6763                     audiocodecPopUp = fAudTrack2CodecPopUp;
6764                     sampleratePopUp = fAudTrack2RatePopUp;
6765                     bitratePopUp = fAudTrack2BitratePopUp;
6766                     drcSlider = fAudTrack2DrcSlider;
6767                 }
6768                 if( i == 3 )
6769                 {
6770                     trackLangPopUp = fAudLang3PopUp;
6771                     mixdownPopUp = fAudTrack3MixPopUp;
6772                     audiocodecPopUp = fAudTrack3CodecPopUp;
6773                     sampleratePopUp = fAudTrack3RatePopUp;
6774                     bitratePopUp = fAudTrack3BitratePopUp;
6775                     drcSlider = fAudTrack3DrcSlider;
6776                 }
6777                 if( i == 4 )
6778                 {
6779                     trackLangPopUp = fAudLang4PopUp;
6780                     mixdownPopUp = fAudTrack4MixPopUp;
6781                     audiocodecPopUp = fAudTrack4CodecPopUp;
6782                     sampleratePopUp = fAudTrack4RatePopUp;
6783                     bitratePopUp = fAudTrack4BitratePopUp;
6784                     drcSlider = fAudTrack4DrcSlider;
6785                 }
6786                 
6787                 
6788                 if ([trackLangPopUp indexOfSelectedItem] == 0)
6789                 {
6790                     [trackLangPopUp selectItemAtIndex: 1];
6791                 }
6792                 [self audioTrackPopUpChanged: trackLangPopUp];
6793                 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6794                 /* check our pref for core audio and use it in place of faac if preset is a built in  */
6795                 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 && 
6796                     [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6797                     [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6798                 {
6799                     [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6800                 }                    
6801                 
6802                 [self audioTrackPopUpChanged: audiocodecPopUp];
6803                 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6804                 [self audioTrackMixdownChanged: mixdownPopUp];
6805                 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6806                  * mixdown*/
6807                 if  ([mixdownPopUp selectedItem] == nil)
6808                 {
6809                     [self audioTrackPopUpChanged: audiocodecPopUp];
6810                     [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6811                 }
6812                 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6813                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6814                 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6815                 {
6816                     [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6817                     /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6818                      *default mixdown bitrate*/
6819                     if ([bitratePopUp selectedItem] == nil)
6820                     {
6821                         [self audioTrackMixdownChanged: mixdownPopUp];
6822                     }
6823                 }
6824                 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6825                 [self audioDRCSliderChanged: drcSlider];
6826                 
6827                 
6828                 /* 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,
6829                  * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6830                 
6831                 if( i > 1 )
6832                 {
6833                     /* 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". */
6834                     if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])  && [trackLangPopUp indexOfSelectedItem] != 0)
6835                     {
6836                         hb_audio_config_t * audio;
6837                         /* get the audio source audio codec */
6838                         audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6839                         if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6840                             [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6841                         {
6842                             /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6843                             if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6844                             {
6845                                 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6846                             }
6847                             if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6848                             {
6849                                 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6850                             }
6851                             [self writeToActivityLog: "No matching source codec, setting track  %d to None", i];
6852                             [trackLangPopUp selectItemAtIndex: 0];
6853                             [self audioTrackPopUpChanged: trackLangPopUp]; 
6854                         }   
6855                     }
6856                 }
6857             }
6858             
6859             /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6860             
6861             if (i < 4)
6862             {
6863                 [fAudLang4PopUp selectItemAtIndex: 0];
6864                 [self audioTrackPopUpChanged: fAudLang4PopUp];
6865                 
6866                 if (i < 3)
6867                 {
6868                     [fAudLang3PopUp selectItemAtIndex: 0];
6869                     [self audioTrackPopUpChanged: fAudLang3PopUp];
6870                     
6871                     if (i < 2)
6872                     {
6873                         [fAudLang2PopUp selectItemAtIndex: 0];
6874                         [self audioTrackPopUpChanged: fAudLang2PopUp];
6875                     }
6876                 }
6877             }
6878             
6879         }
6880         else
6881         {
6882             if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6883             {
6884                 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6885                 {
6886                     [fAudLang1PopUp selectItemAtIndex: 1];
6887                 }
6888                 [self audioTrackPopUpChanged: fAudLang1PopUp];
6889                 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6890                 /* check our pref for core audio and use it in place of faac if preset is built in */
6891                 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 && 
6892                     [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6893                     [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6894                 {
6895                     [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6896                 }
6897                 
6898                 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6899                 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6900                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6901                  * mixdown*/
6902                 if  ([fAudTrack1MixPopUp selectedItem] == nil)
6903                 {
6904                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6905                 }
6906                 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6907                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6908                 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6909                 {
6910                     [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6911                 }
6912                 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6913                 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6914             }
6915             
6916             if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6917             {
6918                 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6919                 {
6920                     [fAudLang2PopUp selectItemAtIndex: 1];
6921                 }
6922                 [self audioTrackPopUpChanged: fAudLang2PopUp];
6923                 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6924                 /* check our pref for core audio and use it in place of faac if preset is built in */
6925                 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 && 
6926                     [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6927                     [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6928                 {
6929                     [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6930                 }
6931                 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6932                 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6933                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6934                  * mixdown*/
6935                 if  ([fAudTrack2MixPopUp selectedItem] == nil)
6936                 {
6937                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6938                 }
6939                 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6940                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6941                 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6942                 {
6943                     [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6944                 }
6945                 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6946                 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6947             }
6948             if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6949             {
6950                 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6951                 {
6952                     [fAudLang3PopUp selectItemAtIndex: 1];
6953                 }
6954                 [self audioTrackPopUpChanged: fAudLang3PopUp];
6955                 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6956                 /* check our pref for core audio and use it in place of faac if preset is built in */
6957                 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 && 
6958                     [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6959                     [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6960                 {
6961                     [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6962                 }
6963                 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6964                 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6965                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6966                  * mixdown*/
6967                 if  ([fAudTrack3MixPopUp selectedItem] == nil)
6968                 {
6969                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6970                 }
6971                 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6972                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6973                 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6974                 {
6975                     [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6976                 }
6977                 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6978                 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6979             }
6980             if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6981             {
6982                 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6983                 {
6984                     [fAudLang4PopUp selectItemAtIndex: 1];
6985                 }
6986                 [self audioTrackPopUpChanged: fAudLang4PopUp];
6987                 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6988                 /* check our pref for core audio and use it in place of faac if preset is built in */
6989                 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 && 
6990                     [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6991                     [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6992                 {
6993                     [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6994                 }
6995                 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6996                 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6997                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6998                  * mixdown*/
6999                 if  ([fAudTrack4MixPopUp selectedItem] == nil)
7000                 {
7001                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7002                 }
7003                 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7004                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7005                 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7006                 {
7007                     [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7008                 }
7009                 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7010                 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7011             }
7012             
7013             /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7014             
7015             if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7016             {
7017                 [fAudLang2PopUp selectItemAtIndex: 0];
7018                 [self audioTrackPopUpChanged: fAudLang2PopUp];
7019             }
7020             if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7021             {
7022                 [fAudLang3PopUp selectItemAtIndex: 0];
7023                 [self audioTrackPopUpChanged: fAudLang3PopUp];
7024             }
7025             if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7026             {
7027                 [fAudLang4PopUp selectItemAtIndex: 0];
7028                 [self audioTrackPopUpChanged: fAudLang4PopUp];
7029             }
7030         }
7031         
7032         /*Subtitles*/
7033         [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7034         /* Forced Subtitles */
7035         [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7036         
7037         /* Picture Settings */
7038         /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7039          * height, width, keep ar, anamorphic and crop settings.
7040          * picture filters are handled separately below.
7041          */
7042         /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None" 
7043          * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the 
7044          * preset completely ignores any picture sizing values in the preset.
7045          */
7046         if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] > 0)
7047         {
7048             hb_job_t * job = fTitle->job;
7049             
7050             /* If Cropping is set to custom, then recall all four crop values from
7051              when the preset was created and apply them */
7052             if ([[chosenPreset objectForKey:@"PictureAutoCrop"]  intValue] == 0)
7053             {
7054                 [fPictureController setAutoCrop:NO];
7055                 
7056                 /* Here we use the custom crop values saved at the time the preset was saved */
7057                 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"]  intValue];
7058                 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"]  intValue];
7059                 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"]  intValue];
7060                 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"]  intValue];
7061                 
7062             }
7063             else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7064             {
7065                 [fPictureController setAutoCrop:YES];
7066                 /* Here we use the auto crop values determined right after scan */
7067                 job->crop[0] = AutoCropTop;
7068                 job->crop[1] = AutoCropBottom;
7069                 job->crop[2] = AutoCropLeft;
7070                 job->crop[3] = AutoCropRight;
7071                 
7072             }
7073             
7074             /* Set modulus */
7075             if ([chosenPreset objectForKey:@"PictureModulus"])
7076             {
7077                 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"]  intValue];
7078             }
7079             else
7080             {
7081                 job->modulus = 16;
7082             }
7083              
7084             /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7085             if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"]  intValue] == 1)
7086             {
7087                 /* Use Max Picture settings for whatever the dvd is.*/
7088                 [self revertPictureSizeToMax:nil];
7089                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
7090                 if (job->keep_ratio == 1)
7091                 {
7092                     hb_fix_aspect( job, HB_KEEP_WIDTH );
7093                     if( job->height > fTitle->height )
7094                     {
7095                         job->height = fTitle->height;
7096                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
7097                     }
7098                 }
7099                 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
7100             }
7101             else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7102             {
7103                 /* we check to make sure the presets width/height does not exceed the sources width/height */
7104                 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"]  intValue])
7105                 {
7106                     /* if so, then we use the sources height and width to avoid scaling up */
7107                     //job->width = fTitle->width;
7108                     //job->height = fTitle->height;
7109                     [self revertPictureSizeToMax:nil];
7110                 }
7111                 else // source width/height is >= the preset height/width
7112                 {
7113                     /* we can go ahead and use the presets values for height and width */
7114                     job->width = [[chosenPreset objectForKey:@"PictureWidth"]  intValue];
7115                     job->height = [[chosenPreset objectForKey:@"PictureHeight"]  intValue];
7116                 }
7117                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
7118                 if (job->keep_ratio == 1)
7119                 {
7120                     hb_fix_aspect( job, HB_KEEP_WIDTH );
7121                     if( job->height > fTitle->height )
7122                     {
7123                         job->height = fTitle->height;
7124                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
7125                     }
7126                 }
7127                 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
7128                 
7129             }
7130             
7131             
7132         }
7133         /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7134         if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"]  intValue] > 0)
7135         {
7136             /* Filters */
7137             
7138             /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7139              * also, older presets may not have this key, in which case we also check to see if that preset had  PictureDecomb
7140              * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7141              * sane.
7142              */
7143             [fPictureController setUseDecomb:1];
7144             [fPictureController setDecomb:0];
7145             [fPictureController setDeinterlace:0];
7146             if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7147             {
7148                 /* we are using decomb */
7149                 /* Decomb */
7150                 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7151                 {
7152                     [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7153                     
7154                     /* if we are using "Custom" in the decomb setting, also set the custom string*/
7155                     if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7156                     {
7157                         [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];    
7158                     }
7159                 }
7160              }
7161             else
7162             {
7163                 /* We are using Deinterlace */
7164                 /* Deinterlace */
7165                 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7166                 {
7167                     [fPictureController setUseDecomb:0];
7168                     [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7169                     /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7170                     if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7171                     {
7172                         [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];    
7173                     }
7174                 }
7175             }
7176             
7177             
7178             /* Detelecine */
7179             if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7180             {
7181                 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7182                 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7183                 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7184                 {
7185                     [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];    
7186                 }
7187             }
7188             else
7189             {
7190                 [fPictureController setDetelecine:0];
7191             }
7192             
7193             /* Denoise */
7194             if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7195             {
7196                 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7197                 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7198                 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7199                 {
7200                     [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];    
7201                 }
7202             }
7203             else
7204             {
7205                 [fPictureController setDenoise:0];
7206             }   
7207             
7208             /* Deblock */
7209             if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7210             {
7211                 /* if its a one, then its the old on/off deblock, set on to 5*/
7212                 [fPictureController setDeblock:5];
7213             }
7214             else
7215             {
7216                 /* use the settings intValue */
7217                 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7218             }
7219             
7220             if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7221             {
7222                 [fPictureController setGrayscale:1];
7223             }
7224             else
7225             {
7226                 [fPictureController setGrayscale:0];
7227             }
7228         }
7229         /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7230         [fPictureController SetTitle:fTitle];
7231         [fPictureController SetTitle:fTitle];
7232         [self calculatePictureSizing:nil];
7233     }
7234 }
7235
7236
7237 #pragma mark -
7238 #pragma mark Manage Presets
7239
7240 - (void) loadPresets {
7241         /* We declare the default NSFileManager into fileManager */
7242         NSFileManager * fileManager = [NSFileManager defaultManager];
7243         /*We define the location of the user presets file */
7244     UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7245         UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7246     /* We check for the presets.plist */
7247         if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7248         {
7249                 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7250         }
7251
7252         UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7253         if (nil == UserPresets)
7254         {
7255                 UserPresets = [[NSMutableArray alloc] init];
7256                 [self addFactoryPresets:nil];
7257         }
7258         [fPresetsOutlineView reloadData];
7259     
7260     [self checkBuiltInsForUpdates];
7261 }
7262
7263 - (void) checkBuiltInsForUpdates {
7264     
7265         BOOL updateBuiltInPresets = NO;
7266     int i = 0;
7267     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7268     id tempObject;
7269     while (tempObject = [enumerator nextObject])
7270     {
7271         /* iterate through the built in presets to see if any have an old build number */
7272         NSMutableDictionary *thisPresetDict = tempObject;
7273         /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7274         if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)              
7275         {
7276                         if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7277             {
7278                 updateBuiltInPresets = YES;
7279             }   
7280                 }
7281         i++;
7282     }
7283     /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7284     if ( updateBuiltInPresets == YES)
7285     {
7286         if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7287         {
7288             /* Show an alert window that built in presets will be updated */
7289             /*On Screen Notification*/
7290             int status;
7291             NSBeep();
7292             status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7293             [NSApp requestUserAttention:NSCriticalRequest];
7294         }
7295         /* when alert is dismissed, go ahead and update the built in presets */
7296         [self addFactoryPresets:nil];
7297     }
7298     
7299 }
7300
7301
7302 - (IBAction) showAddPresetPanel: (id) sender
7303 {
7304     /* Deselect the currently selected Preset if there is one*/
7305     [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7306
7307     /* Populate the preset picture settings popup here */
7308     [fPresetNewPicSettingsPopUp removeAllItems];
7309     [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7310     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7311     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7312     [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];  
7313     /* Uncheck the preset use filters checkbox */
7314     [fPresetNewPicFiltersCheck setState:NSOffState];
7315     // fPresetNewFolderCheck
7316     [fPresetNewFolderCheck setState:NSOffState];
7317     /* Erase info from the input fields*/
7318         [fPresetNewName setStringValue: @""];
7319         [fPresetNewDesc setStringValue: @""];
7320         /* Show the panel */
7321         [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7322 }
7323
7324 - (IBAction) closeAddPresetPanel: (id) sender
7325 {
7326     [NSApp endSheet: fAddPresetPanel];
7327     [fAddPresetPanel orderOut: self];
7328 }
7329
7330 - (IBAction)addUserPreset:(id)sender
7331 {
7332     if (![[fPresetNewName stringValue] length])
7333             NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7334     else
7335     {
7336         /* Here we create a custom user preset */
7337         [UserPresets addObject:[self createPreset]];
7338         [self addPreset];
7339
7340         [self closeAddPresetPanel:nil];
7341     }
7342 }
7343 - (void)addPreset
7344 {
7345
7346         
7347         /* We Reload the New Table data for presets */
7348     [fPresetsOutlineView reloadData];
7349    /* We save all of the preset data here */
7350     [self savePreset];
7351 }
7352
7353 - (void)sortPresets
7354 {
7355
7356         
7357         /* We Sort the Presets By Factory or Custom */
7358         NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type" 
7359                                                     ascending:YES] autorelease];
7360         /* We Sort the Presets Alphabetically by name  We do not use this now as we have drag and drop*/
7361         /*
7362     NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName" 
7363                                                     ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7364         //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7365     
7366     */
7367     /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7368     NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7369         NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7370         [UserPresets setArray:sortedArray];
7371         
7372
7373 }
7374
7375 - (IBAction)insertPreset:(id)sender
7376 {
7377     int index = [fPresetsOutlineView selectedRow];
7378     [UserPresets insertObject:[self createPreset] atIndex:index];
7379     [fPresetsOutlineView reloadData];
7380     [self savePreset];
7381 }
7382
7383 - (NSDictionary *)createPreset
7384 {
7385     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7386     /* Preset build number */
7387     [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7388     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7389         /* Get the New Preset Name from the field in the AddPresetPanel */
7390     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7391     /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7392     [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7393         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7394         [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7395         /*Set whether or not this is default, at creation set to 0*/
7396         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7397     if ([fPresetNewFolderCheck state] == YES)
7398     {
7399         /* initialize and set an empty array for children here since we are a new folder */
7400         NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7401         [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7402         [childrenArray autorelease];
7403     }
7404     else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7405     {
7406         /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7407         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7408         /* Get whether or not to use the current Picture Filter settings for the preset */
7409         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7410         
7411         /* Get New Preset Description from the field in the AddPresetPanel*/
7412         [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7413         /* File Format */
7414         [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7415         /* Chapter Markers fCreateChapterMarkers*/
7416         [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7417         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7418         [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7419         /* Mux mp4 with http optimization */
7420         [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7421         /* Add iPod uuid atom */
7422         [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7423         
7424         /* Codecs */
7425         /* Video encoder */
7426         [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7427         /* x264 Option String */
7428         [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7429         
7430         [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7431         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7432         [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7433         [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7434         
7435         /* Video framerate */
7436         if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7437         {
7438             [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7439         }
7440         else // we can record the actual titleOfSelectedItem
7441         {
7442             [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7443         }
7444         
7445         /* 2 Pass Encoding */
7446         [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7447         /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7448         [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7449         /*Picture Settings*/
7450         hb_job_t * job = fTitle->job;
7451         /* Picture Sizing */
7452         /* Use Max Picture settings for whatever the dvd is.*/
7453         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7454         [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7455         [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7456         [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7457         [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7458         [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7459         
7460         /* Set crop settings here */
7461         [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7462         [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7463         [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7464         [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7465         [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7466         
7467         /* Picture Filters */
7468         [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7469         [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7470         [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7471         [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7472         [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7473         [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7474         [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7475         [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"]; 
7476         [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7477         [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7478         [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7479         
7480         /*Audio*/
7481         NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7482         /* we actually call the methods for the nests here */
7483         if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7484         {
7485             NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7486             [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7487             [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7488             [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7489             [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7490             [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7491             [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7492             [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7493             [audioTrack1Array autorelease];
7494             [audioListArray addObject:audioTrack1Array];
7495         }
7496         
7497         if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7498         {
7499             NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7500             [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7501             [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7502             [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7503             [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7504             [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7505             [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7506             [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7507             [audioTrack2Array autorelease];
7508             [audioListArray addObject:audioTrack2Array];
7509         }
7510         
7511         if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7512         {
7513             NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7514             [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7515             [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7516             [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7517             [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7518             [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7519             [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7520             [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7521             [audioTrack3Array autorelease];
7522             [audioListArray addObject:audioTrack3Array];
7523         }
7524         
7525         if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7526         {
7527             NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7528             [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7529             [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7530             [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7531             [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7532             [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7533             [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7534             [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7535             [audioTrack4Array autorelease];
7536             [audioListArray addObject:audioTrack4Array];
7537         }
7538         
7539         
7540         [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7541
7542         
7543         /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7544          * subititle array code. */
7545         /* Subtitles*/
7546         //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7547         /* Forced Subtitles */
7548         //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7549     }
7550     [preset autorelease];
7551     return preset;
7552     
7553 }
7554
7555 - (void)savePreset
7556 {
7557     [UserPresets writeToFile:UserPresetsFile atomically:YES];
7558         /* We get the default preset in case it changed */
7559         [self getDefaultPresets:nil];
7560
7561 }
7562
7563 - (IBAction)deletePreset:(id)sender
7564 {
7565     
7566     
7567     if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7568     {
7569         return;
7570     }
7571     /* Alert user before deleting preset */
7572         int status;
7573     status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7574     
7575     if ( status == NSAlertDefaultReturn ) 
7576     {
7577         int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7578         NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7579         NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7580         
7581         NSEnumerator *enumerator;
7582         NSMutableArray *presetsArrayToMod;
7583         NSMutableArray *tempArray;
7584         id tempObject;
7585         /* If we are a root level preset, we are modding the UserPresets array */
7586         if (presetToModLevel == 0)
7587         {
7588             presetsArrayToMod = UserPresets;
7589         }
7590         else // We have a parent preset, so we modify the chidren array object for key
7591         {
7592             presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"]; 
7593         }
7594         
7595         enumerator = [presetsArrayToMod objectEnumerator];
7596         tempArray = [NSMutableArray array];
7597         
7598         while (tempObject = [enumerator nextObject]) 
7599         {
7600             NSDictionary *thisPresetDict = tempObject;
7601             if (thisPresetDict == presetToMod)
7602             {
7603                 [tempArray addObject:tempObject];
7604             }
7605         }
7606         
7607         [presetsArrayToMod removeObjectsInArray:tempArray];
7608         [fPresetsOutlineView reloadData];
7609         [self savePreset];   
7610     }
7611 }
7612
7613
7614 #pragma mark -
7615 #pragma mark Import Export Preset(s)
7616
7617 - (IBAction) browseExportPresetFile: (id) sender
7618 {
7619     /* Open a panel to let the user choose where and how to save the export file */
7620     NSSavePanel * panel = [NSSavePanel savePanel];
7621         /* We get the current file name and path from the destination field here */
7622     NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7623
7624         [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7625                                    modalForWindow: fWindow modalDelegate: self
7626                                    didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7627                                           contextInfo: NULL];
7628 }
7629
7630 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7631                    returnCode: (int) returnCode contextInfo: (void *) contextInfo
7632 {
7633     if( returnCode == NSOKButton )
7634     {
7635         NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7636         NSString *exportPresetsFile = [sheet filename];
7637         [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7638         /* We check for the presets.plist */
7639         if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7640         {
7641             [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7642         }
7643         NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7644         if (nil == presetsToExport)
7645         {
7646             presetsToExport = [[NSMutableArray alloc] init];
7647             
7648             /* now get and add selected presets to export */
7649             
7650         }
7651         if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7652         {
7653             [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7654             [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7655             
7656         }
7657         
7658     }
7659 }
7660
7661
7662 - (IBAction) browseImportPresetFile: (id) sender
7663 {
7664
7665     NSOpenPanel * panel;
7666         
7667     panel = [NSOpenPanel openPanel];
7668     [panel setAllowsMultipleSelection: NO];
7669     [panel setCanChooseFiles: YES];
7670     [panel setCanChooseDirectories: NO ];
7671     NSString * sourceDirectory;
7672         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7673         {
7674                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7675         }
7676         else
7677         {
7678                 sourceDirectory = @"~/Desktop";
7679                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7680         }
7681     /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7682         * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7683         */
7684     /* set this for allowed file types, not sure if we should allow xml or not */
7685     NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7686     [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7687                    modalForWindow: fWindow modalDelegate: self
7688                    didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7689                       contextInfo: sender];
7690 }
7691
7692 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7693                      returnCode: (int) returnCode contextInfo: (void *) contextInfo
7694 {
7695     if( returnCode == NSOKButton )
7696     {
7697         NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7698         NSString *importPresetsFile = [sheet filename];
7699         [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7700         /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file   */
7701         NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7702         /* iterate though the new array of presets to import and add them to our presets array */
7703         int i = 0;
7704         NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7705         id tempObject;
7706         while (tempObject = [enumerator nextObject])
7707         {
7708             /* make any changes to the incoming preset we see fit */
7709             /* make sure the incoming preset is not tagged as default */
7710             [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7711             /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7712             NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7713             [tempObject setObject:prependedName forKey:@"PresetName"];
7714             
7715             /* actually add the new preset to our presets array */
7716             [UserPresets addObject:tempObject];
7717             i++;
7718         }
7719         [presetsToImport autorelease];
7720         [self sortPresets];
7721         [self addPreset];
7722         
7723     }
7724 }
7725
7726 #pragma mark -
7727 #pragma mark Manage Default Preset
7728
7729 - (IBAction)getDefaultPresets:(id)sender
7730 {
7731         presetHbDefault = nil;
7732     presetUserDefault = nil;
7733     presetUserDefaultParent = nil;
7734     presetUserDefaultParentParent = nil;
7735     NSMutableDictionary *presetHbDefaultParent = nil;
7736     NSMutableDictionary *presetHbDefaultParentParent = nil;
7737     
7738     int i = 0;
7739     BOOL userDefaultFound = NO;
7740     presetCurrentBuiltInCount = 0;
7741     /* First we iterate through the root UserPresets array to check for defaults */
7742     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7743         id tempObject;
7744         while (tempObject = [enumerator nextObject])
7745         {
7746                 NSMutableDictionary *thisPresetDict = tempObject;
7747                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7748                 {
7749                         presetHbDefault = thisPresetDict;       
7750                 }
7751                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7752                 {
7753                         presetUserDefault = thisPresetDict;
7754             userDefaultFound = YES;
7755         }
7756         if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset               
7757         {
7758                         presetCurrentBuiltInCount++; // <--increment the current number of built in presets     
7759                 }
7760                 i++;
7761         
7762         /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7763         if ([thisPresetDict objectForKey:@"ChildrenArray"])
7764         {
7765             NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7766             NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7767             id tempObject;
7768             while (tempObject = [enumerator nextObject])
7769             {
7770                 NSMutableDictionary *thisPresetDict = tempObject;
7771                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7772                 {
7773                     presetHbDefault = thisPresetDict;
7774                     presetHbDefaultParent = thisPresetDictParent;
7775                 }
7776                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7777                 {
7778                     presetUserDefault = thisPresetDict;
7779                     presetUserDefaultParent = thisPresetDictParent;
7780                     userDefaultFound = YES;
7781                 }
7782                 
7783                 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7784                 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7785                 {
7786                     NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7787                     NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7788                     id tempObject;
7789                     while (tempObject = [enumerator nextObject])
7790                     {
7791                         NSMutableDictionary *thisPresetDict = tempObject;
7792                         if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7793                         {
7794                             presetHbDefault = thisPresetDict;
7795                             presetHbDefaultParent = thisPresetDictParent;
7796                             presetHbDefaultParentParent = thisPresetDictParentParent;   
7797                         }
7798                         if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7799                         {
7800                             presetUserDefault = thisPresetDict;
7801                             presetUserDefaultParent = thisPresetDictParent;
7802                             presetUserDefaultParentParent = thisPresetDictParentParent;
7803                             userDefaultFound = YES;     
7804                         }
7805                         
7806                     }
7807                 }
7808             }
7809         }
7810         
7811         }
7812     /* check to see if a user specified preset was found, if not then assign the parents for
7813      * the presetHbDefault so that we can open the parents for the nested presets
7814      */
7815     if (userDefaultFound == NO)
7816     {
7817         presetUserDefaultParent = presetHbDefaultParent;
7818         presetUserDefaultParentParent = presetHbDefaultParentParent;
7819     }
7820 }
7821
7822 - (IBAction)setDefaultPreset:(id)sender
7823 {
7824 /* We need to determine if the item is a folder */
7825    if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7826    {
7827    return;
7828    }
7829
7830     int i = 0;
7831     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7832         id tempObject;
7833         /* First make sure the old user specified default preset is removed */
7834     while (tempObject = [enumerator nextObject])
7835         {
7836                 NSMutableDictionary *thisPresetDict = tempObject;
7837                 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7838                 {
7839                         [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"]; 
7840                 }
7841                 
7842                 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7843         if ([thisPresetDict objectForKey:@"ChildrenArray"])
7844         {
7845             NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7846             id tempObject;
7847             int ii = 0;
7848             while (tempObject = [enumerator nextObject])
7849             {
7850                 NSMutableDictionary *thisPresetDict1 = tempObject;
7851                 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7852                 {
7853                     [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"]; 
7854                 }
7855                 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7856                 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7857                 {
7858                     NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7859                     id tempObject;
7860                     int iii = 0;
7861                     while (tempObject = [enumerator nextObject])
7862                     {
7863                         if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7864                         {
7865                             [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];       
7866                         }
7867                         iii++;
7868                     }
7869                 }
7870                 ii++;
7871             }
7872             
7873         }
7874         i++; 
7875         }
7876     
7877     
7878     int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7879     NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7880     NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7881     
7882     
7883     NSMutableArray *presetsArrayToMod;
7884     NSMutableArray *tempArray;
7885     
7886     /* If we are a root level preset, we are modding the UserPresets array */
7887     if (presetToModLevel == 0)
7888     {
7889         presetsArrayToMod = UserPresets;
7890     }
7891     else // We have a parent preset, so we modify the chidren array object for key
7892     {
7893         presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"]; 
7894     }
7895     
7896     enumerator = [presetsArrayToMod objectEnumerator];
7897     tempArray = [NSMutableArray array];
7898     int iiii = 0;
7899     while (tempObject = [enumerator nextObject]) 
7900     {
7901         NSDictionary *thisPresetDict = tempObject;
7902         if (thisPresetDict == presetToMod)
7903         {
7904             if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7905             {
7906                 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];        
7907             }
7908         }
7909      iiii++;
7910      }
7911     
7912     
7913     /* We save all of the preset data here */
7914     [self savePreset];
7915     /* We Reload the New Table data for presets */
7916     [fPresetsOutlineView reloadData];
7917 }
7918
7919 - (IBAction)selectDefaultPreset:(id)sender
7920 {
7921         NSMutableDictionary *presetToMod;
7922     /* if there is a user specified default, we use it */
7923         if (presetUserDefault)
7924         {
7925         presetToMod = presetUserDefault;
7926     }
7927         else if (presetHbDefault) //else we use the built in default presetHbDefault
7928         {
7929         presetToMod = presetHbDefault;
7930         }
7931     else
7932     {
7933     return;
7934     }
7935     
7936     if (presetUserDefaultParent != nil)
7937     {
7938         [fPresetsOutlineView expandItem:presetUserDefaultParent];
7939         
7940     }
7941     if (presetUserDefaultParentParent != nil)
7942     {
7943         [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7944         
7945     }
7946     
7947     [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7948         [self selectPreset:nil];
7949 }
7950
7951
7952 #pragma mark -
7953 #pragma mark Manage Built In Presets
7954
7955
7956 - (IBAction)deleteFactoryPresets:(id)sender
7957 {
7958     //int status;
7959     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7960         id tempObject;
7961     
7962         //NSNumber *index;
7963     NSMutableArray *tempArray;
7964
7965
7966         tempArray = [NSMutableArray array];
7967         /* we look here to see if the preset is we move on to the next one */
7968         while ( tempObject = [enumerator nextObject] )  
7969                 {
7970                         /* if the preset is "Factory" then we put it in the array of
7971                         presets to delete */
7972                         if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7973                         {
7974                                 [tempArray addObject:tempObject];
7975                         }
7976         }
7977         
7978         [UserPresets removeObjectsInArray:tempArray];
7979         [fPresetsOutlineView reloadData];
7980         [self savePreset];   
7981
7982 }
7983
7984    /* We use this method to recreate new, updated factory presets */
7985 - (IBAction)addFactoryPresets:(id)sender
7986 {
7987     
7988     /* First, we delete any existing built in presets */
7989     [self deleteFactoryPresets: sender];
7990     /* Then we generate new built in presets programmatically with fPresetsBuiltin
7991      * which is all setup in HBPresets.h and  HBPresets.m*/
7992     [fPresetsBuiltin generateBuiltinPresets:UserPresets];
7993     /* update build number for built in presets */
7994     /* iterate though the new array of presets to import and add them to our presets array */
7995     int i = 0;
7996     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7997     id tempObject;
7998     while (tempObject = [enumerator nextObject])
7999     {
8000         /* Record the apps current build number in the PresetBuildNumber key */
8001         if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset           
8002         {
8003             /* Preset build number */
8004             [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8005         }
8006         i++;
8007     }
8008     /* report the built in preset updating to the activity log */
8009     [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8010     
8011     [self sortPresets];
8012     [self addPreset];
8013     
8014 }
8015
8016
8017 @end
8018
8019 /*******************************
8020  * Subclass of the HBPresetsOutlineView *
8021  *******************************/
8022
8023 @implementation HBPresetsOutlineView
8024 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8025 {
8026     fIsDragging = YES;
8027
8028     // By default, NSTableView only drags an image of the first column. Change this to
8029     // drag an image of the queue's icon and PresetName columns.
8030     NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8031     return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8032 }
8033
8034
8035
8036 - (void) mouseDown:(NSEvent *)theEvent
8037 {
8038     [super mouseDown:theEvent];
8039         fIsDragging = NO;
8040 }
8041
8042
8043
8044 - (BOOL) isDragging;
8045 {
8046     return fIsDragging;
8047 }
8048 @end
8049
8050
8051