OSDN Git Service

ce610fe7e7e072cc7703cd9aaca663e37ab2af89
[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     /* if we are custom anamorphic, store the exact storage, par and display dims */
2324     if (fTitle->job->anamorphic.mode == 3)
2325     {
2326         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.modulus] forKey:@"PicturePARModulus"];
2327         
2328         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2329         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2330         
2331         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2332         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2333         
2334         [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2335         [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2336
2337     }
2338     NSString * pictureSummary;
2339     pictureSummary = [fPictureSizeField stringValue];
2340     [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];                 
2341     /* Set crop settings here */
2342         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2343     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2344     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2345         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2346         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2347     
2348     /* Picture Filters */
2349     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2350     [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2351     
2352     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2353     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2354     [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2355     
2356     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2357     [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2358     
2359     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2360     [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2361     
2362     [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2363     
2364     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2365     
2366     /*Audio*/
2367     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2368     {
2369         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2370         [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2371         [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2372         [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2373         [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2374         [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2375         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2376     }
2377     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2378     {
2379         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2380         [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2381         [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2382         [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2383         [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2384         [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2385         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2386     }
2387     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2388     {
2389         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2390         [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2391         [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2392         [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2393         [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2394         [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2395         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2396     }
2397     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2398     {
2399         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2400         [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2401         [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2402         [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2403         [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2404         [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2405         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2406     }
2407     
2408         /* Subtitles*/
2409     NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2410     [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2411     [subtitlesArray autorelease];
2412
2413     /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2414      
2415     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2416     
2417     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2418     
2419     
2420     [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2421     
2422     /* Codecs */
2423         /* Video encoder */
2424         [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2425         
2426     /* Framerate */
2427     [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2428     [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2429     [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2430         
2431     /* Picture Sizing */
2432         /* Use Max Picture settings for whatever the dvd is.*/
2433         [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2434         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2435         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2436         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2437         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2438     
2439     /* Set crop settings here */
2440         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2441     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2442     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2443         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2444         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2445     
2446     
2447     /*Audio*/
2448     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2449     {
2450         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2451         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2452         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2453         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2454         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2455      }
2456     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2457     {
2458         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2459         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2460         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2461         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2462         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2463     }
2464     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2465     {
2466         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2467         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2468         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2469         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2470         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2471     }
2472     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2473     {
2474         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2475         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2476         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2477         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2478         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2479     }
2480
2481  
2482     /* we need to auto relase the queueFileJob and return it */
2483     [queueFileJob autorelease];
2484     return queueFileJob;
2485
2486 }
2487
2488 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2489 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2490 {
2491     NSUInteger index = [indexSet lastIndex];
2492     NSUInteger aboveInsertIndexCount = 0;
2493     
2494     
2495     NSUInteger removeIndex;
2496         
2497     if (index >= insertIndex)
2498     {
2499         removeIndex = index + aboveInsertIndexCount;
2500         aboveInsertIndexCount++;
2501     }
2502     else
2503     {
2504         removeIndex = index;
2505         insertIndex--;
2506     }
2507
2508     id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2509     [QueueFileArray removeObjectAtIndex:removeIndex];
2510     [QueueFileArray insertObject:object atIndex:insertIndex];
2511     [object release];
2512         
2513     index = [indexSet indexLessThanIndex:index];
2514
2515    /* We save all of the Queue data here 
2516     * and it also gets sent back to the queue controller*/
2517     [self saveQueueFileItem]; 
2518     
2519 }
2520
2521
2522 #pragma mark -
2523 #pragma mark Queue Job Processing
2524
2525 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2526 {
2527     int i = currentQueueEncodeIndex;
2528     [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2529         
2530     /* We save all of the Queue data here */
2531     [self saveQueueFileItem];
2532         /* We Reload the New Table data for presets */
2533     //[fPresetsOutlineView reloadData];
2534
2535     /* Since we have now marked a queue item as done
2536      * we can go ahead and increment currentQueueEncodeIndex 
2537      * so that if there is anything left in the queue we can
2538      * go ahead and move to the next item if we want to */
2539     currentQueueEncodeIndex++ ;
2540     [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2541     int queueItems = [QueueFileArray count];
2542     /* If we still have more items in our queue, lets go to the next one */
2543     if (currentQueueEncodeIndex < queueItems)
2544     {
2545     [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2546     [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2547     }
2548     else
2549     {
2550         [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2551     }
2552 }
2553
2554 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2555 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2556 {
2557    /* Tell HB to output a new activity log file for this encode */
2558     [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2559     
2560     
2561      /* use a bool to determine whether or not we can decrypt using vlc */
2562     BOOL cancelScanDecrypt = 0;
2563     /* set the bool so that showNewScan knows to apply the appropriate queue
2564     * settings as this is a queue rescan
2565     */
2566     //applyQueueToScan = YES;
2567     NSString *path = scanPath;
2568     HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2569     
2570     if( [detector isVideoDVD] )
2571     {
2572         // The chosen path was actually on a DVD, so use the raw block
2573         // device path instead.
2574         path = [detector devicePath];
2575         [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2576
2577         /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2578         NSString *vlcPath = @"/Applications/VLC.app";
2579         NSFileManager * fileManager = [NSFileManager defaultManager];
2580             if ([fileManager fileExistsAtPath:vlcPath] == 0) 
2581             {
2582             /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2583             cancelScanDecrypt = 1;
2584             [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2585             int status;
2586             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");
2587             [NSApp requestUserAttention:NSCriticalRequest];
2588             
2589             if (status == NSAlertDefaultReturn)
2590             {
2591                 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2592                 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2593             }
2594             else if (status == NSAlertAlternateReturn)
2595             {
2596             /* User chose to cancel the scan */
2597             [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2598             }
2599             else
2600             {
2601             /* 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 */
2602             cancelScanDecrypt = 0;
2603             [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2604             }
2605
2606         }
2607         else
2608         {
2609             /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2610             [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2611         }
2612     }
2613
2614     if (cancelScanDecrypt == 0)
2615     {
2616         /* we actually pass the scan off to libhb here */
2617         /* If there is no title number passed to scan, we use "0"
2618          * which causes the default behavior of a full source scan
2619          */
2620         if (!scanTitleNum)
2621         {
2622             scanTitleNum = 0;
2623         }
2624         if (scanTitleNum > 0)
2625         {
2626             [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2627         }
2628         
2629         [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2630         /* We use our advance pref to determine how many previews to scan */
2631         int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2632         hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2633     }
2634 }
2635
2636 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2637 - (void) processNewQueueEncode
2638 {
2639     hb_list_t  * list  = hb_get_titles( fQueueEncodeLibhb );
2640     hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2641     hb_job_t * job = title->job;
2642     
2643     if( !hb_list_count( list ) )
2644     {
2645         [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2646     }
2647     
2648     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2649     [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2650     [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2651     job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2652     //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2653     [self prepareJob];
2654     
2655     /*
2656      * If scanning we need to do some extra setup of the job.
2657      */
2658     if( job->indepth_scan == 1 )
2659     {
2660         char *x264opts_tmp;
2661         
2662         /*
2663          * When subtitle scan is enabled do a fast pre-scan job
2664          * which will determine which subtitles to enable, if any.
2665          */
2666         job->pass = -1;
2667         x264opts_tmp = job->x264opts;
2668         
2669         job->x264opts = NULL;
2670         
2671         job->indepth_scan = 1;  
2672
2673         
2674         /*
2675          * Add the pre-scan job
2676          */
2677         hb_add( fQueueEncodeLibhb, job );
2678         job->x264opts = x264opts_tmp;
2679     }
2680
2681     
2682     if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2683     {
2684         job->indepth_scan = 0;
2685         
2686
2687         
2688         job->pass = 1;
2689         
2690         hb_add( fQueueEncodeLibhb, job );
2691         
2692         job->pass = 2;
2693         
2694         job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */  
2695         strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2696         
2697         hb_add( fQueueEncodeLibhb, job );
2698         
2699     }
2700     else
2701     {
2702         job->indepth_scan = 0;
2703         job->pass = 0;
2704         
2705         hb_add( fQueueEncodeLibhb, job );
2706     }
2707         
2708     NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2709         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2710         /* Lets mark our new encode as 1 or "Encoding" */
2711     [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2712     [self saveQueueFileItem];
2713     
2714     /* we need to clean up the subtitle tracks after the job(s) have been set  */
2715     int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2716     int ii;
2717     for(ii = 0; ii < num_subtitle_tracks; ii++)
2718     {
2719         hb_subtitle_t * subtitle;
2720         subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2721         
2722
2723         hb_list_rem(job->list_subtitle, subtitle);
2724         free(subtitle);
2725     }
2726     
2727     
2728     /* We should be all setup so let 'er rip */   
2729     [self doRip];
2730 }
2731
2732
2733
2734 #pragma mark -
2735 #pragma mark Queue Item Editing
2736
2737 /* Rescans the chosen queue item back into the main window */
2738 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2739 {
2740     fqueueEditRescanItemNum = selectedQueueItem;
2741     [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2742     applyQueueToScan = YES;
2743     /* Set the browsedSourceDisplayName for showNewScan */
2744     browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2745     [self performScan:scanPath scanTitleNum:scanTitleNum];
2746 }
2747
2748
2749 /* We use this method after a queue item rescan for edit.
2750  * it largely mirrors -selectPreset in terms of structure.
2751  * Assumes that a queue item has been reloaded into the main window.
2752  */
2753 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2754 {
2755     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2756     hb_job_t * job = fTitle->job;
2757     if (queueToApply)
2758     {
2759         [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2760     }
2761     /* Set title number and chapters */
2762     /* since the queue only scans a single title, we really don't need to pick a title */
2763     [fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2764     
2765     [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2766     [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2767     
2768     /* File Format */
2769     [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2770     [self formatPopUpChanged:nil];
2771     
2772     /* Chapter Markers*/
2773     [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2774     /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2775     [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2776     /* Mux mp4 with http optimization */
2777     [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2778     
2779     /* Video encoder */
2780     /* We set the advanced opt string here if applicable*/
2781     [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2782     [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2783     
2784     /* Lets run through the following functions to get variables set there */
2785     [self videoEncoderPopUpChanged:nil];
2786     /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2787     [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2788     [self calculateBitrate:nil];
2789     
2790     /* Video quality */
2791     [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2792     
2793     [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2794     [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2795     /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2796      * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2797      * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2798      * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2799      * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2800     if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2801     {
2802         /* For the quality slider we need to convert the old percent's to the new rf scales */
2803         float rf =  (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2804         [fVidQualitySlider setFloatValue:rf];
2805         
2806     }
2807     else
2808     {
2809         /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2810         if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2811         {
2812             [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2813         }
2814         else
2815         {
2816             /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2817             [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2818         }
2819     }
2820     
2821     [self videoMatrixChanged:nil];
2822     [self writeToActivityLog: "applyQueueSettingsToMainWindow: video matrix changed"];    
2823     /* Video framerate */
2824     /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2825      detected framerate in the fVidRatePopUp so we use index 0*/
2826     if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2827     {
2828         [fVidRatePopUp selectItemAtIndex: 0];
2829     }
2830     else
2831     {
2832         [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2833     }
2834     
2835     /* 2 Pass Encoding */
2836     [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2837     [self twoPassCheckboxChanged:nil];
2838     /* Turbo 1st pass for 2 Pass Encoding */
2839     [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2840     
2841     /*Audio*/
2842     
2843     
2844     /* Now lets add our new tracks to the audio list here */
2845     if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2846     {
2847         [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2848         [self audioTrackPopUpChanged: fAudLang1PopUp];
2849         [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2850         [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2851         
2852         [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2853         
2854         [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2855         [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2856         
2857         [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2858         [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2859     }
2860     else
2861     {
2862         [fAudLang1PopUp selectItemAtIndex: 0];
2863         [self audioTrackPopUpChanged: fAudLang1PopUp];
2864     }
2865     if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2866     {
2867         [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2868         [self audioTrackPopUpChanged: fAudLang2PopUp];
2869         [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2870         [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2871         
2872         [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2873         
2874         [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2875         [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2876         
2877         [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2878         [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2879     }
2880     else
2881     {
2882         [fAudLang2PopUp selectItemAtIndex: 0];
2883         [self audioTrackPopUpChanged: fAudLang2PopUp];
2884     }
2885     if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2886     {
2887         [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2888         [self audioTrackPopUpChanged: fAudLang3PopUp];
2889         [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2890         [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2891         
2892         [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2893         
2894         [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2895         [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2896         
2897         [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2898         [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2899     }
2900     else
2901     {
2902         [fAudLang3PopUp selectItemAtIndex: 0];
2903         [self audioTrackPopUpChanged: fAudLang3PopUp];
2904     }
2905     if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2906     {
2907         [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2908         [self audioTrackPopUpChanged: fAudLang4PopUp];
2909         [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2910         [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2911         
2912         [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2913         
2914         [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2915         [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2916         
2917         [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2918         [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2919     }
2920     else
2921     {
2922         [fAudLang4PopUp selectItemAtIndex: 0];
2923         [self audioTrackPopUpChanged: fAudLang4PopUp];
2924     }
2925     
2926     [self writeToActivityLog: "applyQueueSettingsToMainWindow: audio set up"];
2927     /*Subtitles*/
2928     /* Crashy crashy right now, working on it */
2929     [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2930     [fSubtitlesTable reloadData];  
2931     /* Picture Settings */
2932     
2933     /* If Cropping is set to custom, then recall all four crop values from
2934      when the preset was created and apply them */
2935     if ([[queueToApply objectForKey:@"PictureAutoCrop"]  intValue] == 0)
2936     {
2937         [fPictureController setAutoCrop:NO];
2938         
2939         /* Here we use the custom crop values saved at the time the preset was saved */
2940         job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
2941         job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
2942         job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
2943         job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
2944         
2945     }
2946     else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2947     {
2948         [fPictureController setAutoCrop:YES];
2949         /* Here we use the auto crop values determined right after scan */
2950         job->crop[0] = AutoCropTop;
2951         job->crop[1] = AutoCropBottom;
2952         job->crop[2] = AutoCropLeft;
2953         job->crop[3] = AutoCropRight;
2954         
2955     }
2956     
2957     
2958     /* we check to make sure the presets width/height does not exceed the sources width/height */
2959     if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"]  intValue])
2960     {
2961         /* if so, then we use the sources height and width to avoid scaling up */
2962         //job->width = fTitle->width;
2963         //job->height = fTitle->height;
2964         [self revertPictureSizeToMax:nil];
2965     }
2966     else // source width/height is >= the preset height/width
2967     {
2968         /* we can go ahead and use the presets values for height and width */
2969         job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
2970         job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
2971     }
2972     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
2973     if (job->keep_ratio == 1)
2974     {
2975         hb_fix_aspect( job, HB_KEEP_WIDTH );
2976         if( job->height > fTitle->height )
2977         {
2978             job->height = fTitle->height;
2979             hb_fix_aspect( job, HB_KEEP_HEIGHT );
2980         }
2981     }
2982     job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
2983     
2984     
2985     [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture sizing set up"];
2986     
2987     
2988     /* Filters */
2989     
2990     /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2991      * also, older presets may not have this key, in which case we also check to see if that preset had  PictureDecomb
2992      * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2993      * sane.
2994      */
2995     [fPictureController setUseDecomb:1];
2996     [fPictureController setDecomb:0];
2997     [fPictureController setDeinterlace:0];
2998     if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2999     {
3000         /* we are using decomb */
3001         /* Decomb */
3002         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3003         {
3004             [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3005             
3006             /* if we are using "Custom" in the decomb setting, also set the custom string*/
3007             if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3008             {
3009                 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];    
3010             }
3011         }
3012     }
3013     else
3014     {
3015         /* We are using Deinterlace */
3016         /* Deinterlace */
3017         if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3018         {
3019             [fPictureController setUseDecomb:0];
3020             [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3021             /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3022             if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3023             {
3024                 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];    
3025             }
3026         }
3027     }
3028     
3029     
3030     /* Detelecine */
3031     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3032     {
3033         [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3034         /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3035         if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3036         {
3037             [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];    
3038         }
3039     }
3040     else
3041     {
3042         [fPictureController setDetelecine:0];
3043     }
3044     
3045     /* Denoise */
3046     if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3047     {
3048         [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3049         /* if we are using "Custom" in the denoise setting, also set the custom string*/
3050         if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3051         {
3052             [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];    
3053         }
3054     }
3055     else
3056     {
3057         [fPictureController setDenoise:0];
3058     }   
3059     
3060     /* Deblock */
3061     if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3062     {
3063         /* if its a one, then its the old on/off deblock, set on to 5*/
3064         [fPictureController setDeblock:5];
3065     }
3066     else
3067     {
3068         /* use the settings intValue */
3069         [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3070     }
3071     
3072     if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3073     {
3074         [fPictureController setGrayscale:1];
3075     }
3076     else
3077     {
3078         [fPictureController setGrayscale:0];
3079     }
3080     
3081     /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3082     [fPictureController SetTitle:fTitle];
3083     [fPictureController SetTitle:fTitle];
3084     [self calculatePictureSizing:nil];
3085     
3086     [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture filters set up"];
3087     /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3088     //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3089     //    [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3090     if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3091         {
3092                 /* Deselect the currently selected Preset if there is one*/
3093         //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3094         //[self selectPreset:nil];
3095                 
3096         //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3097                 /* Change UI to show "Custom" settings are being used */
3098                 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3099         
3100                 curUserPresetChosenNum = nil;
3101         }
3102     else
3103     {
3104         /* Deselect the currently selected Preset if there is one*/
3105                 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3106                 /* Change UI to show "Custom" settings are being used */
3107                 [fPresetSelectedDisplay setStringValue: @"Custom"];
3108         
3109                 //curUserPresetChosenNum = nil;
3110     }
3111     
3112     /* We need to set this bool back to NO, in case the user wants to do a scan */
3113     //applyQueueToScan = NO;
3114     
3115     /* Not that source is loaded and settings applied, delete the queue item from the queue */
3116     [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3117     [self removeQueueFileItem:fqueueEditRescanItemNum];
3118 }
3119
3120
3121
3122 #pragma mark -
3123 #pragma mark Live Preview
3124 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3125  * can encode to its temp preview directory and playback. This is *not* used for any actual user
3126  * encodes
3127  */
3128 - (void) prepareJobForPreview
3129 {
3130     hb_list_t  * list  = hb_get_titles( fHandle );
3131     hb_title_t * title = (hb_title_t *) hb_list_item( list,
3132             [fSrcTitlePopUp indexOfSelectedItem] );
3133     hb_job_t * job = title->job;
3134     hb_audio_config_t * audio;
3135     /* set job->angle for libdvdnav */
3136     job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3137     /* Chapter selection */
3138     job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3139     job->chapter_end   = [fSrcChapterEndPopUp   indexOfSelectedItem] + 1;
3140         
3141     /* Format (Muxer) and Video Encoder */
3142     job->mux = [[fDstFormatPopUp selectedItem] tag];
3143     job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3144
3145     job->chapter_markers = 0;
3146     
3147         if( job->vcodec & HB_VCODEC_X264 )
3148     {
3149                 
3150                 /* Below Sends x264 options to the core library if x264 is selected*/
3151                 /* Lets use this as per Nyx, Thanks Nyx!*/
3152                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3153                 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3154                 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3155
3156         
3157     }
3158
3159     /* Video settings */
3160    /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3161      * and detelecine is on, so we handle that in the logic below
3162      */
3163     job->vfr = 0;
3164     if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3165     {
3166         /* a specific framerate has been chosen */
3167         job->vrate      = 27000000;
3168         job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3169         /* We are not same as source so we set job->cfr to 1 
3170          * to enable constant frame rate since user has specified
3171          * a specific framerate*/
3172         job->cfr = 1;
3173     }
3174     else
3175     {
3176         /* We are same as source (variable) */
3177         job->vrate      = title->rate;
3178         job->vrate_base = title->rate_base;
3179         /* We are same as source so we set job->cfr to 0 
3180          * to enable true same as source framerate */
3181         job->cfr = 0;
3182         /* If we are same as source and we have detelecine on, we need to turn on
3183          * job->vfr
3184          */
3185         if ([fPictureController detelecine] == 1)
3186         {
3187             job->vfr = 1;
3188         }
3189     }
3190
3191     switch( [fVidQualityMatrix selectedRow] )
3192     {
3193         case 0:
3194             /* Target size.
3195                Bitrate should already have been calculated and displayed
3196                in fVidBitrateField, so let's just use it */
3197         case 1:
3198             job->vquality = -1.0;
3199             job->vbitrate = [fVidBitrateField intValue];
3200             break;
3201         case 2:
3202             job->vquality = [fVidQualityRFField floatValue];
3203             job->vbitrate = 0;
3204             break;
3205     }
3206
3207     /* Subtitle settings */
3208     NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3209     
3210     
3211 int subtitle = nil;
3212 int force;
3213 int burned;
3214 int def;
3215 bool one_burned = FALSE;
3216
3217     int i = 0;
3218     NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3219     id tempObject;
3220     while (tempObject = [enumerator nextObject])
3221     {
3222         
3223         subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3224         force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3225         burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3226         def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3227         
3228         /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3229          * we want to ignore it for display as well as encoding.
3230          */
3231         if (subtitle > 0)
3232         {
3233             /* if i is 0, then we are in the first item of the subtitles which we need to 
3234              * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3235              * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3236              */
3237             
3238             /* if we are on the first track and using "Foreign Audio Search" */ 
3239             if (i == 0 && subtitle == 1)
3240             {
3241                 /* NOTE: Currently foreign language search is borked for preview.
3242                  * Commented out but left in for initial commit. */
3243                 
3244                 
3245                 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3246                 
3247                 job->indepth_scan = 1;
3248                 if (burned == 1 || job->mux != HB_MUX_MP4)
3249                 {
3250                     if (burned != 1 && job->mux == HB_MUX_MKV)
3251                     {
3252                         job->select_subtitle_config.dest = PASSTHRUSUB;
3253                     }
3254                     else
3255                     {
3256                         job->select_subtitle_config.dest = RENDERSUB;
3257                     }
3258                     
3259                     job->select_subtitle_config.force = force;
3260                     job->select_subtitle_config.default_track = def;
3261                     
3262                 }
3263                 
3264                 
3265             }
3266             else
3267             {
3268                 
3269                 /* for the actual source tracks, we must subtract the non source entries so 
3270                  * that the menu index matches the source subtitle_list index for convenience */
3271                 if (i == 0)
3272                 {
3273                     /* for the first track, the source tracks start at menu index 2 ( None is 0,
3274                      * Foreign Language Search is 1) so subtract 2 */
3275                     subtitle = subtitle - 2;
3276                 }
3277                 else
3278                 {
3279                     /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3280                      * so subtract 1. */
3281                     
3282                     subtitle = subtitle - 1;
3283                 }
3284                 
3285                 /* We are setting a source subtitle so access the source subtitle info */  
3286                 hb_subtitle_t * subt;
3287                 
3288                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3289                 
3290                 /* if we are getting the subtitles from an external srt file */
3291                 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3292                 {
3293                     hb_subtitle_config_t sub_config;
3294                     
3295                     sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3296                     
3297                     /* we need to srncpy file path and char code */
3298                     strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3299                     strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3300                     
3301                     sub_config.force = 0;
3302                     sub_config.dest = PASSTHRUSUB;
3303                     sub_config.default_track = def;
3304                     
3305                     hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3306                 }
3307                 
3308                 if (subt != NULL)
3309                 {
3310                     hb_subtitle_config_t sub_config = subt->config;
3311                     
3312                     if (!burned && job->mux == HB_MUX_MKV && 
3313                         subt->format == PICTURESUB)
3314                     {
3315                         sub_config.dest = PASSTHRUSUB;
3316                     }
3317                     else if (!burned && job->mux == HB_MUX_MP4 && 
3318                              subt->format == PICTURESUB)
3319                     {
3320                         // Skip any non-burned vobsubs when output is mp4
3321                         continue;
3322                     }
3323                     else if ( burned && subt->format == PICTURESUB )
3324                     {
3325                         // Only allow one subtitle to be burned into the video
3326                         if (one_burned)
3327                             continue;
3328                         one_burned = TRUE;
3329                     }
3330                     sub_config.force = force;
3331                     sub_config.default_track = def;
3332                     hb_subtitle_add( job, &sub_config, subtitle );
3333                 }   
3334                 
3335             }
3336         }
3337         i++;
3338     }
3339    
3340     
3341     
3342 [subtitlesArray autorelease];    
3343     
3344     
3345     /* Audio tracks and mixdowns */
3346     /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3347     int audiotrack_count = hb_list_count(job->list_audio);
3348     for( int i = 0; i < audiotrack_count;i++)
3349     {
3350         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3351         hb_list_rem(job->list_audio, temp_audio);
3352     }
3353     /* Now lets add our new tracks to the audio list here */
3354     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3355     {
3356         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3357         hb_audio_config_init(audio);
3358         audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3359         /* We go ahead and assign values to our audio->out.<properties> */
3360         audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3361         audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3362         audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3363         audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3364         audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3365         audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3366         
3367         hb_audio_add( job, audio );
3368         free(audio);
3369     }  
3370     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3371     {
3372         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3373         hb_audio_config_init(audio);
3374         audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3375         /* We go ahead and assign values to our audio->out.<properties> */
3376         audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3377         audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3378         audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3379         audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3380         audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3381         audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3382         
3383         hb_audio_add( job, audio );
3384         free(audio);
3385         
3386     }
3387     
3388     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3389     {
3390         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3391         hb_audio_config_init(audio);
3392         audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3393         /* We go ahead and assign values to our audio->out.<properties> */
3394         audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3395         audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3396         audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3397         audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3398         audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3399         audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3400         
3401         hb_audio_add( job, audio );
3402         free(audio);
3403         
3404     }
3405
3406     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3407     {
3408         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3409         hb_audio_config_init(audio);
3410         audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3411         /* We go ahead and assign values to our audio->out.<properties> */
3412         audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3413         audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3414         audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3415         audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3416         audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3417         audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3418         
3419         hb_audio_add( job, audio );
3420         free(audio);
3421         
3422     }
3423
3424     
3425     
3426     /* Filters */
3427     
3428     /* Though Grayscale is not really a filter, per se
3429      * we put it here since its in the filters panel
3430      */
3431      
3432     if ([fPictureController grayscale])
3433     {
3434         job->grayscale = 1;
3435     }
3436     else
3437     {
3438         job->grayscale = 0;
3439     }
3440     
3441     /* Initialize the filters list */
3442     job->filters = hb_list_init();
3443     
3444     /* Now lets call the filters if applicable.
3445     * The order of the filters is critical
3446     */
3447     
3448         /* Detelecine */
3449     if ([fPictureController detelecine] == 1)
3450     {
3451         /* use a custom detelecine string */
3452         hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3453         hb_list_add( job->filters, &hb_filter_detelecine );
3454     }
3455     if ([fPictureController detelecine] == 2)
3456     {
3457         /* Default */
3458         hb_list_add( job->filters, &hb_filter_detelecine );
3459     }
3460     
3461     
3462     
3463     if ([fPictureController useDecomb] == 1)
3464     {
3465         /* Decomb */
3466         /* we add the custom string if present */
3467         if ([fPictureController decomb] == 1)
3468         {
3469             /* use a custom decomb string */
3470             hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3471             hb_list_add( job->filters, &hb_filter_decomb );
3472         }
3473         if ([fPictureController decomb] == 2)
3474         {
3475             /* Run old deinterlacer fd by default */
3476             //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3477             hb_list_add( job->filters, &hb_filter_decomb );
3478         }
3479     }
3480     else
3481     {
3482         
3483         /* Deinterlace */
3484         if ([fPictureController deinterlace] == 1)
3485         {
3486             /* we add the custom string if present */
3487             hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3488             hb_list_add( job->filters, &hb_filter_deinterlace );            
3489         }
3490         else if ([fPictureController deinterlace] == 2)
3491         {
3492             /* Run old deinterlacer fd by default */
3493             hb_filter_deinterlace.settings = "-1"; 
3494             hb_list_add( job->filters, &hb_filter_deinterlace );
3495         }
3496         else if ([fPictureController deinterlace] == 3)
3497         {
3498             /* Yadif mode 0 (without spatial deinterlacing.) */
3499             hb_filter_deinterlace.settings = "2"; 
3500             hb_list_add( job->filters, &hb_filter_deinterlace );            
3501         }
3502         else if ([fPictureController deinterlace] == 4)
3503         {
3504             /* Yadif (with spatial deinterlacing) */
3505             hb_filter_deinterlace.settings = "0"; 
3506             hb_list_add( job->filters, &hb_filter_deinterlace );            
3507         }
3508         
3509         }
3510     
3511     /* Denoise */
3512         if ([fPictureController denoise] == 1) // custom in popup
3513         {
3514                 /* we add the custom string if present */
3515         hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String]; 
3516         hb_list_add( job->filters, &hb_filter_denoise );        
3517         }
3518     else if ([fPictureController denoise] == 2) // Weak in popup
3519         {
3520                 hb_filter_denoise.settings = "2:1:2:3"; 
3521         hb_list_add( job->filters, &hb_filter_denoise );        
3522         }
3523         else if ([fPictureController denoise] == 3) // Medium in popup
3524         {
3525                 hb_filter_denoise.settings = "3:2:2:3"; 
3526         hb_list_add( job->filters, &hb_filter_denoise );        
3527         }
3528         else if ([fPictureController denoise] == 4) // Strong in popup
3529         {
3530                 hb_filter_denoise.settings = "7:7:5:5"; 
3531         hb_list_add( job->filters, &hb_filter_denoise );        
3532         }
3533     
3534     
3535     /* Deblock  (uses pp7 default) */
3536     /* NOTE: even though there is a valid deblock setting of 0 for the filter, for 
3537      * the macgui's purposes a value of 0 actually means to not even use the filter
3538      * current hb_filter_deblock.settings valid ranges are from 5 - 15 
3539      */
3540     if ([fPictureController deblock] != 0)
3541     {
3542         NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3543         hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3544         hb_list_add( job->filters, &hb_filter_deblock );
3545     }
3546
3547 }
3548
3549
3550 #pragma mark -
3551 #pragma mark Job Handling
3552
3553
3554 - (void) prepareJob
3555 {
3556     
3557     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3558     hb_list_t  * list  = hb_get_titles( fQueueEncodeLibhb );
3559     hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3560     hb_job_t * job = title->job;
3561     hb_audio_config_t * audio;
3562     /* Title Angle for dvdnav */
3563     job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3564     
3565     if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3566     {
3567         /* Chapter selection */
3568         [self writeToActivityLog: "Start / Stop set to chapters"];
3569         job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3570         job->chapter_end   = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3571     }
3572     else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3573     {
3574         /* we are pts based start / stop */
3575         [self writeToActivityLog: "Start / Stop set to seconds ..."];
3576         
3577         /* 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
3578          * 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.
3579          */
3580         /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3581         /* get the start seconds from the start seconds field */
3582         int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3583         //job->start_at_preview = start_seconds;
3584         /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3585         //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3586         job->pts_to_start = start_seconds * 90000LL;
3587         /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3588         int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3589         job->pts_to_stop = stop_seconds * 90000LL;
3590
3591         /* A bunch of verbose activity log messages to check on what should be expected */
3592         [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3593         [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];
3594         [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3595         [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3596         [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3597         [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];
3598     }
3599     else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3600     {
3601         /* we are frame based start / stop */
3602         [self writeToActivityLog: "Start / Stop set to frames ..."];
3603         
3604         /* 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
3605          * 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.
3606          */
3607         /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3608         /* get the start seconds from the start seconds field */
3609         int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3610         //job->start_at_preview = start_seconds;
3611         /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3612         //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3613         job->frame_to_start = start_frame;
3614         /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3615         int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3616         job->frame_to_stop = stop_frame;
3617
3618         /* A bunch of verbose activity log messages to check on what should be expected */
3619         [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3620         [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3621         [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3622     }
3623
3624         
3625         
3626     
3627     /* Format (Muxer) and Video Encoder */
3628     job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3629     job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3630     
3631     
3632     /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3633     if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3634     {
3635         job->largeFileSize = 1;
3636     }
3637     else
3638     {
3639         job->largeFileSize = 0;
3640     }
3641     /* We set http optimized mp4 here */
3642     if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3643     {
3644         job->mp4_optimize = 1;
3645     }
3646     else
3647     {
3648         job->mp4_optimize = 0;
3649     }
3650
3651         
3652     /* We set the chapter marker extraction here based on the format being
3653      mpeg4 or mkv and the checkbox being checked */
3654     if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3655     {
3656         job->chapter_markers = 1;
3657         
3658         /* now lets get our saved chapter names out the array in the queue file
3659          * and insert them back into the title chapter list. We have it here,
3660          * because unless we are inserting chapter markers there is no need to
3661          * spend the overhead of iterating through the chapter names array imo
3662          * Also, note that if for some reason we don't apply chapter names, the
3663          * chapters just come out 001, 002, etc. etc.
3664          */
3665          
3666         NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3667         int i = 0;
3668         NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3669         id tempObject;
3670         while (tempObject = [enumerator nextObject])
3671         {
3672             hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3673             if( chapter != NULL )
3674             {
3675                 strncpy( chapter->title, [tempObject UTF8String], 1023);
3676                 chapter->title[1023] = '\0';
3677             }
3678             i++;
3679         }
3680     }
3681     else
3682     {
3683         job->chapter_markers = 0;
3684     }
3685     
3686     if( job->vcodec & HB_VCODEC_X264 )
3687     {
3688                 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3689             {
3690             job->ipod_atom = 1;
3691                 }
3692         else
3693         {
3694             job->ipod_atom = 0;
3695         }
3696                 
3697                 
3698                 /* Below Sends x264 options to the core library if x264 is selected*/
3699                 /* Lets use this as per Nyx, Thanks Nyx!*/
3700                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3701                 /* Turbo first pass if two pass and Turbo First pass is selected */
3702                 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3703                 {
3704                         /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3705                         NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3706                         /* append the "Turbo" string variable to the existing opts string.
3707              Note: the "Turbo" string must be appended, not prepended to work properly*/
3708                         NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3709                         strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3710                 }
3711                 else
3712                 {
3713                         strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3714                 }
3715         
3716     }
3717     
3718     
3719     /* Picture Size Settings */
3720     job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
3721     job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
3722     
3723     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
3724     job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
3725     if ([[queueToApply objectForKey:@"PicturePAR"]  intValue] == 3)
3726     {
3727         /* insert our custom values here for capuj */
3728         job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"]  intValue];
3729         job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"]  intValue];
3730         
3731         job->anamorphic.modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3732         
3733         job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"]  intValue];
3734         job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"]  intValue];
3735         
3736         job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"]  floatValue];
3737         job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"]  floatValue];
3738     }
3739     
3740     /* Here we use the crop values saved at the time the preset was saved */
3741     job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
3742     job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
3743     job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
3744     job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
3745     
3746     /* Video settings */
3747     /* Framerate */
3748     
3749     /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3750      * and detelecine is on, so we handle that in the logic below
3751      */
3752     job->vfr = 0;
3753     if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3754     {
3755         /* a specific framerate has been chosen */
3756         job->vrate      = 27000000;
3757         job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3758         /* We are not same as source so we set job->cfr to 1 
3759          * to enable constant frame rate since user has specified
3760          * a specific framerate*/
3761         job->cfr = 1;
3762     }
3763     else
3764     {
3765         /* We are same as source (variable) */
3766         job->vrate      = [[queueToApply objectForKey:@"JobVrate"] intValue];
3767         job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3768         /* We are same as source so we set job->cfr to 0 
3769          * to enable true same as source framerate */
3770         job->cfr = 0;
3771         /* If we are same as source and we have detelecine on, we need to turn on
3772          * job->vfr
3773          */
3774         if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3775         {
3776             job->vfr = 1;
3777         }
3778     }
3779     
3780     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3781     {
3782         /* Target size.
3783          Bitrate should already have been calculated and displayed
3784          in fVidBitrateField, so let's just use it same as abr*/
3785         job->vquality = -1.0;
3786         job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3787     }
3788     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3789     {
3790         job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3791         job->vbitrate = 0;
3792         
3793     }
3794     
3795     job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3796     
3797
3798
3799 #pragma mark -
3800 #pragma mark Process Subtitles to libhb
3801
3802 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3803  * which means that we need to account for the offset of non source language settings in from
3804  * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3805  * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3806  * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3807  * to the source tracks position in title->list_subtitle.
3808  */
3809
3810 int subtitle = nil;
3811 int force;
3812 int burned;
3813 int def;
3814 bool one_burned = FALSE;
3815
3816     int i = 0;
3817     NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3818     id tempObject;
3819     while (tempObject = [enumerator nextObject])
3820     {
3821         
3822         subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3823         force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3824         burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3825         def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3826         
3827         /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3828          * we want to ignore it for display as well as encoding.
3829          */
3830         if (subtitle > 0)
3831         {
3832             /* if i is 0, then we are in the first item of the subtitles which we need to 
3833              * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3834              * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3835              */
3836             
3837             /* if we are on the first track and using "Foreign Audio Search" */ 
3838             if (i == 0 && subtitle == 1)
3839             {
3840                 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3841                 
3842                 job->indepth_scan = 1;
3843                 if (burned == 1 || job->mux != HB_MUX_MP4)
3844                 {
3845                     if (burned != 1 && job->mux == HB_MUX_MKV)
3846                     {
3847                         job->select_subtitle_config.dest = PASSTHRUSUB;
3848                     }
3849                     else
3850                     {
3851                         job->select_subtitle_config.dest = RENDERSUB;
3852                     }
3853                     
3854                     job->select_subtitle_config.force = force;
3855                     job->select_subtitle_config.default_track = def;
3856                 }
3857                 
3858                 
3859             }
3860             else
3861             {
3862                 
3863                 /* for the actual source tracks, we must subtract the non source entries so 
3864                  * that the menu index matches the source subtitle_list index for convenience */
3865                 if (i == 0)
3866                 {
3867                     /* for the first track, the source tracks start at menu index 2 ( None is 0,
3868                      * Foreign Language Search is 1) so subtract 2 */
3869                     subtitle = subtitle - 2;
3870                 }
3871                 else
3872                 {
3873                     /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3874                      * so subtract 1. */
3875                     
3876                     subtitle = subtitle - 1;
3877                 }
3878                 
3879                 /* We are setting a source subtitle so access the source subtitle info */  
3880                 hb_subtitle_t * subt;
3881                 
3882                 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3883                 
3884                 /* if we are getting the subtitles from an external srt file */
3885                 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3886                 {
3887                     hb_subtitle_config_t sub_config;
3888                     
3889                     sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3890                     
3891                     /* we need to srncpy file name and codeset */
3892                     strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3893                     strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3894                     
3895                     sub_config.force = 0;
3896                     sub_config.dest = PASSTHRUSUB;
3897                     sub_config.default_track = def;
3898                     
3899                     hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3900                 }
3901                 
3902                 
3903                 if (subt != NULL)
3904                 {
3905                     hb_subtitle_config_t sub_config = subt->config;
3906                     
3907                     if (!burned && job->mux == HB_MUX_MKV && 
3908                         subt->format == PICTURESUB)
3909                     {
3910                         sub_config.dest = PASSTHRUSUB;
3911                     }
3912                     else if (!burned && job->mux == HB_MUX_MP4 && 
3913                              subt->format == PICTURESUB)
3914                     {
3915                         // Skip any non-burned vobsubs when output is mp4
3916                         continue;
3917                     }
3918                     else if ( burned && subt->format == PICTURESUB )
3919                     {
3920                         // Only allow one subtitle to be burned into the video
3921                         if (one_burned)
3922                             continue;
3923                         one_burned = TRUE;
3924                     }
3925                     sub_config.force = force;
3926                     sub_config.default_track = def;
3927                     hb_subtitle_add( job, &sub_config, subtitle );
3928                 }   
3929                 
3930             }
3931         }
3932         i++;
3933     }
3934
3935 #pragma mark -
3936
3937    
3938     /* Audio tracks and mixdowns */
3939     /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3940     int audiotrack_count = hb_list_count(job->list_audio);
3941     for( int i = 0; i < audiotrack_count;i++)
3942     {
3943         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3944         hb_list_rem(job->list_audio, temp_audio);
3945     }
3946     /* Now lets add our new tracks to the audio list here */
3947     if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3948     {
3949         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3950         hb_audio_config_init(audio);
3951         audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3952         /* We go ahead and assign values to our audio->out.<properties> */
3953         audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3954         audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3955         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3956         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3957         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3958         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3959         
3960         hb_audio_add( job, audio );
3961         free(audio);
3962     }  
3963     if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3964     {
3965         
3966         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3967         hb_audio_config_init(audio);
3968         audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3969         [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3970         /* We go ahead and assign values to our audio->out.<properties> */
3971         audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3972         audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3973         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3974         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3975         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3976         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3977         
3978         hb_audio_add( job, audio );
3979         free(audio);
3980     }
3981     
3982     if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3983     {
3984         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3985         hb_audio_config_init(audio);
3986         audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3987         /* We go ahead and assign values to our audio->out.<properties> */
3988         audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3989         audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3990         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3991         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3992         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3993         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3994         
3995         hb_audio_add( job, audio );
3996         free(audio);        
3997     }
3998     
3999     if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
4000     {
4001         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4002         hb_audio_config_init(audio);
4003         audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4004         /* We go ahead and assign values to our audio->out.<properties> */
4005         audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4006         audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
4007         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
4008         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
4009         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
4010         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
4011         
4012         hb_audio_add( job, audio );
4013         
4014
4015     }
4016     
4017     /* Filters */ 
4018     job->filters = hb_list_init();
4019     
4020     /* Now lets call the filters if applicable.
4021      * The order of the filters is critical
4022      */
4023     /* Detelecine */
4024     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4025     {
4026         /* use a custom detelecine string */
4027         hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4028         hb_list_add( job->filters, &hb_filter_detelecine );
4029     }
4030     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4031     {
4032         /* Use libhb's default values */
4033         hb_list_add( job->filters, &hb_filter_detelecine );
4034     }
4035     
4036     if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4037     {
4038         /* Decomb */
4039         /* we add the custom string if present */
4040         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4041         {
4042             /* use a custom decomb string */
4043             hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4044             hb_list_add( job->filters, &hb_filter_decomb );
4045         }
4046         if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4047         {
4048             /* Use libhb default */
4049             hb_list_add( job->filters, &hb_filter_decomb );
4050         }
4051         
4052     }
4053     else
4054     {
4055         
4056         /* Deinterlace */
4057         if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4058         {
4059             /* we add the custom string if present */
4060             hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4061             hb_list_add( job->filters, &hb_filter_deinterlace );            
4062         }
4063         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4064         {
4065             /* Run old deinterlacer fd by default */
4066             hb_filter_deinterlace.settings = "-1"; 
4067             hb_list_add( job->filters, &hb_filter_deinterlace );
4068         }
4069         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4070         {
4071             /* Yadif mode 0 (without spatial deinterlacing.) */
4072             hb_filter_deinterlace.settings = "2"; 
4073             hb_list_add( job->filters, &hb_filter_deinterlace );            
4074         }
4075         else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4076         {
4077             /* Yadif (with spatial deinterlacing) */
4078             hb_filter_deinterlace.settings = "0"; 
4079             hb_list_add( job->filters, &hb_filter_deinterlace );            
4080         }
4081         
4082         
4083     }
4084     /* Denoise */
4085         if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4086         {
4087                 /* we add the custom string if present */
4088         hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4089         hb_list_add( job->filters, &hb_filter_denoise );        
4090         }
4091     else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4092         {
4093                 hb_filter_denoise.settings = "2:1:2:3"; 
4094         hb_list_add( job->filters, &hb_filter_denoise );        
4095         }
4096         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4097         {
4098                 hb_filter_denoise.settings = "3:2:2:3"; 
4099         hb_list_add( job->filters, &hb_filter_denoise );        
4100         }
4101         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4102         {
4103                 hb_filter_denoise.settings = "7:7:5:5"; 
4104         hb_list_add( job->filters, &hb_filter_denoise );        
4105         }
4106     
4107     
4108     /* Deblock  (uses pp7 default) */
4109     /* NOTE: even though there is a valid deblock setting of 0 for the filter, for 
4110      * the macgui's purposes a value of 0 actually means to not even use the filter
4111      * current hb_filter_deblock.settings valid ranges are from 5 - 15 
4112      */
4113     if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4114     {
4115         hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4116         hb_list_add( job->filters, &hb_filter_deblock );
4117     }
4118 [self writeToActivityLog: "prepareJob exiting"];    
4119 }
4120
4121
4122
4123 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4124 */
4125 - (IBAction) addToQueue: (id) sender
4126 {
4127         /* We get the destination directory from the destination field here */
4128         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4129         /* We check for a valid destination here */
4130         if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
4131         {
4132                 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4133         return;
4134         }
4135     
4136     BOOL fileExists;
4137     fileExists = NO;
4138     
4139     BOOL fileExistsInQueue;
4140     fileExistsInQueue = NO;
4141     
4142     /* We check for and existing file here */
4143     if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4144     {
4145         fileExists = YES;
4146     }
4147     
4148     /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4149     int i = 0;
4150     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4151         id tempObject;
4152         while (tempObject = [enumerator nextObject])
4153         {
4154                 NSDictionary *thisQueueDict = tempObject;
4155                 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4156                 {
4157                         fileExistsInQueue = YES;        
4158                 }
4159         i++;
4160         }
4161     
4162     
4163         if(fileExists == YES)
4164     {
4165         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4166                                   NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4167                                   @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4168                                   NULL, NULL, [NSString stringWithFormat:
4169                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4170                                                [fDstFile2Field stringValue]] );
4171     }
4172     else if (fileExistsInQueue == YES)
4173     {
4174     NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4175                                   NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4176                                   @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4177                                   NULL, NULL, [NSString stringWithFormat:
4178                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4179                                                [fDstFile2Field stringValue]] );
4180     }
4181     else
4182     {
4183         [self doAddToQueue];
4184     }
4185 }
4186
4187 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4188    the user if they want to overwrite an exiting movie file.
4189 */
4190 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4191     returnCode: (int) returnCode contextInfo: (void *) contextInfo
4192 {
4193     if( returnCode == NSAlertAlternateReturn )
4194         [self doAddToQueue];
4195 }
4196
4197 - (void) doAddToQueue
4198 {
4199     [self addQueueFileItem ];
4200 }
4201
4202
4203
4204 /* Rip: puts up an alert before ultimately calling doRip
4205 */
4206 - (IBAction) Rip: (id) sender
4207 {
4208     [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4209     /* Rip or Cancel ? */
4210     hb_state_t s;
4211     hb_get_state2( fQueueEncodeLibhb, &s );
4212     
4213     if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4214         {
4215         [self Cancel: sender];
4216         return;
4217     }
4218     
4219     /* We check to see if we need to warn the user that the computer will go to sleep
4220                  or shut down when encoding is finished */
4221                 [self remindUserOfSleepOrShutdown];
4222     
4223     // If there are pending jobs in the queue, then this is a rip the queue
4224     if (fPendingCount > 0)
4225     {
4226         /* here lets start the queue with the first pending item */
4227         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4228         
4229         return;
4230     }
4231     
4232     // Before adding jobs to the queue, check for a valid destination.
4233     
4234     NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4235     if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
4236     {
4237         NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4238         return;
4239     }
4240     
4241     /* We check for duplicate name here */
4242     if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4243     {
4244         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4245                                   NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4246                                   @selector( overWriteAlertDone:returnCode:contextInfo: ),
4247                                   NULL, NULL, [NSString stringWithFormat:
4248                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4249                                                [fDstFile2Field stringValue]] );
4250         
4251         // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4252     }
4253     else
4254     {
4255         /* if there are no pending jobs in the queue, then add this one to the queue and rip
4256          otherwise, just rip the queue */
4257         if(fPendingCount == 0)
4258         {
4259             [self doAddToQueue];
4260         }
4261         
4262         /* go right to processing the new queue encode */
4263         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4264         
4265     }
4266 }
4267
4268 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4269    want to overwrite an exiting movie file.
4270 */
4271 - (void) overWriteAlertDone: (NSWindow *) sheet
4272     returnCode: (int) returnCode contextInfo: (void *) contextInfo
4273 {
4274     if( returnCode == NSAlertAlternateReturn )
4275     {
4276         /* if there are no jobs in the queue, then add this one to the queue and rip 
4277         otherwise, just rip the queue */
4278         if( fPendingCount == 0 )
4279         {
4280             [self doAddToQueue];
4281         }
4282
4283         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4284         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4285         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
4286       
4287     }
4288 }
4289
4290 - (void) remindUserOfSleepOrShutdown
4291 {
4292        if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4293        {
4294                /*Warn that computer will sleep after encoding*/
4295                int reminduser;
4296                NSBeep();
4297                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);
4298                [NSApp requestUserAttention:NSCriticalRequest];
4299                if ( reminduser == NSAlertAlternateReturn )
4300                {
4301                        [self showPreferencesWindow:nil];
4302                }
4303        }
4304        else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4305        {
4306                /*Warn that computer will shut down after encoding*/
4307                int reminduser;
4308                NSBeep();
4309                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);
4310                [NSApp requestUserAttention:NSCriticalRequest];
4311                if ( reminduser == NSAlertAlternateReturn )
4312                {
4313                        [self showPreferencesWindow:nil];
4314                }
4315        }
4316
4317 }
4318
4319
4320 - (void) doRip
4321 {
4322     /* Let libhb do the job */
4323     hb_start( fQueueEncodeLibhb );
4324     /*set the fEncodeState State */
4325         fEncodeState = 1;
4326 }
4327
4328
4329 //------------------------------------------------------------------------------------
4330 // Displays an alert asking user if the want to cancel encoding of current job.
4331 // Cancel: returns immediately after posting the alert. Later, when the user
4332 // acknowledges the alert, doCancelCurrentJob is called.
4333 //------------------------------------------------------------------------------------
4334 - (IBAction)Cancel: (id)sender
4335 {
4336     if (!fQueueController) return;
4337     
4338   hb_pause( fQueueEncodeLibhb );
4339     NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4340    
4341     // Which window to attach the sheet to?
4342     NSWindow * docWindow;
4343     if ([sender respondsToSelector: @selector(window)])
4344         docWindow = [sender window];
4345     else
4346         docWindow = fWindow;
4347         
4348     NSBeginCriticalAlertSheet(
4349             alertTitle,
4350             NSLocalizedString(@"Continue Encoding", nil),
4351             NSLocalizedString(@"Cancel Current and Stop", nil),
4352             NSLocalizedString(@"Cancel Current and Continue", nil),
4353             docWindow, self,
4354             nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4355             NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4356     
4357     // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4358 }
4359
4360 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4361 {
4362    hb_resume( fQueueEncodeLibhb );
4363      if (returnCode == NSAlertOtherReturn)
4364     {
4365         [self doCancelCurrentJob];  // <- this also stops libhb
4366     }
4367     if (returnCode == NSAlertAlternateReturn)
4368     {
4369     [self doCancelCurrentJobAndStop];
4370     }
4371 }
4372
4373 //------------------------------------------------------------------------------------
4374 // Cancels and deletes the current job and stops libhb from processing the remaining
4375 // encodes.
4376 //------------------------------------------------------------------------------------
4377 - (void) doCancelCurrentJob
4378 {
4379     // Stop the current job. hb_stop will only cancel the current pass and then set
4380     // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4381     // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4382     // remaining passes of the job and then start the queue back up if there are any
4383     // remaining jobs.
4384      
4385     
4386     hb_stop( fQueueEncodeLibhb );
4387     
4388     // Delete all remaining jobs since libhb doesn't do this on its own.
4389             hb_job_t * job;
4390             while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4391                 hb_rem( fQueueEncodeLibhb, job );
4392                 
4393     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
4394     
4395     // now that we've stopped the currently encoding job, lets mark it as cancelled
4396     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4397     // and as always, save it in the queue .plist...
4398     /* We save all of the Queue data here */
4399     [self saveQueueFileItem];
4400     // so now lets move to 
4401     currentQueueEncodeIndex++ ;
4402     // ... and see if there are more items left in our queue
4403     int queueItems = [QueueFileArray count];
4404     /* If we still have more items in our queue, lets go to the next one */
4405     if (currentQueueEncodeIndex < queueItems)
4406     {
4407     [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4408     [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4409     
4410     [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4411     }
4412     else
4413     {
4414         [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4415     }
4416
4417 }
4418
4419 - (void) doCancelCurrentJobAndStop
4420 {
4421     hb_stop( fQueueEncodeLibhb );
4422     
4423     // Delete all remaining jobs since libhb doesn't do this on its own.
4424             hb_job_t * job;
4425             while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4426                 hb_rem( fQueueEncodeLibhb, job );
4427                 
4428                 
4429     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
4430     
4431     // now that we've stopped the currently encoding job, lets mark it as cancelled
4432     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4433     // and as always, save it in the queue .plist...
4434     /* We save all of the Queue data here */
4435     [self saveQueueFileItem];
4436     // so now lets move to 
4437     currentQueueEncodeIndex++ ;
4438     [self writeToActivityLog: "cancelling current job and stopping the queue"];
4439 }
4440 - (IBAction) Pause: (id) sender
4441 {
4442     hb_state_t s;
4443     hb_get_state2( fQueueEncodeLibhb, &s );
4444
4445     if( s.state == HB_STATE_PAUSED )
4446     {
4447         hb_resume( fQueueEncodeLibhb );
4448     }
4449     else
4450     {
4451         hb_pause( fQueueEncodeLibhb );
4452     }
4453 }
4454
4455 #pragma mark -
4456 #pragma mark GUI Controls Changed Methods
4457
4458 - (IBAction) titlePopUpChanged: (id) sender
4459 {
4460     hb_list_t  * list  = hb_get_titles( fHandle );
4461     hb_title_t * title = (hb_title_t*)
4462         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4463
4464     /* If we are a stream type, grok the output file name from title->name upon title change */
4465     if (title->type == HB_STREAM_TYPE)
4466     {
4467         /* we set the default name according to the new title->name */
4468         [fDstFile2Field setStringValue: [NSString stringWithFormat:
4469                                          @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4470                                          [NSString stringWithUTF8String: title->name],
4471                                          [[fDstFile2Field stringValue] pathExtension]]];
4472         /* If we have more than one title and are stream then we have a batch, change the source to read out the parent folder also */
4473         if ( hb_list_count( list ) > 1 )
4474         {                                  
4475             [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4476         }
4477     }
4478     
4479     /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4480     int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4481     [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4482     [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4483     /* 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 */
4484     [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4485     //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4486     [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];    
4487     
4488     /* If Auto Naming is on. We create an output filename of dvd name - title number */
4489     if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4490         {
4491                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4492                         @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4493                         [browsedSourceDisplayName stringByDeletingPathExtension],
4494             title->index,
4495                         [[fDstFile2Field stringValue] pathExtension]]]; 
4496         }
4497     /* Update encode start / stop variables */
4498      
4499     
4500     
4501     /* Update chapter popups */
4502     [fSrcChapterStartPopUp removeAllItems];
4503     [fSrcChapterEndPopUp   removeAllItems];
4504     for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4505     {
4506         [fSrcChapterStartPopUp addItemWithTitle: [NSString
4507             stringWithFormat: @"%d", i + 1]];
4508         [fSrcChapterEndPopUp addItemWithTitle: [NSString
4509             stringWithFormat: @"%d", i + 1]];
4510     }
4511
4512     [fSrcChapterStartPopUp selectItemAtIndex: 0];
4513     [fSrcChapterEndPopUp   selectItemAtIndex:
4514         hb_list_count( title->list_chapter ) - 1];
4515     [self chapterPopUpChanged:nil];
4516     
4517     /* if using dvd nav, show the angle widget */
4518     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4519     {
4520         [fSrcAngleLabel setHidden:NO];
4521         [fSrcAnglePopUp setHidden:NO];
4522         
4523         [fSrcAnglePopUp removeAllItems];
4524         for( int i = 0; i < title->angle_count; i++ )
4525         {
4526             [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4527         }
4528         [fSrcAnglePopUp selectItemAtIndex: 0];
4529     }
4530     else
4531     {
4532         [fSrcAngleLabel setHidden:YES];
4533         [fSrcAnglePopUp setHidden:YES];
4534     }
4535     
4536     /* Start Get and set the initial pic size for display */
4537         hb_job_t * job = title->job;
4538         fTitle = title;
4539     
4540     /* Set Auto Crop to on upon selecting a new title  */
4541     [fPictureController setAutoCrop:YES];
4542     
4543         /* We get the originial output picture width and height and put them
4544         in variables for use with some presets later on */
4545         PicOrigOutputWidth = job->width;
4546         PicOrigOutputHeight = job->height;
4547         AutoCropTop = job->crop[0];
4548         AutoCropBottom = job->crop[1];
4549         AutoCropLeft = job->crop[2];
4550         AutoCropRight = job->crop[3];
4551
4552         /* Reset the new title in fPictureController &&  fPreviewController*/
4553     [fPictureController SetTitle:title];
4554
4555         
4556     /* Update Subtitle Table */
4557     [fSubtitlesDelegate resetWithTitle:title];
4558     [fSubtitlesTable reloadData];
4559     
4560
4561     /* Update chapter table */
4562     [fChapterTitlesDelegate resetWithTitle:title];
4563     [fChapterTable reloadData];
4564
4565    /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4566     int audiotrack_count = hb_list_count(job->list_audio);
4567     for( int i = 0; i < audiotrack_count;i++)
4568     {
4569         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4570         hb_list_rem(job->list_audio, temp_audio);
4571     }
4572
4573     /* Update audio popups */
4574     [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4575     [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4576     [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4577     [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4578     /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4579         NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4580         [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4581     [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4582     [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4583     [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4584
4585         /* changing the title may have changed the audio channels on offer, */
4586         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4587         [self audioTrackPopUpChanged: fAudLang1PopUp];
4588         [self audioTrackPopUpChanged: fAudLang2PopUp];
4589     [self audioTrackPopUpChanged: fAudLang3PopUp];
4590     [self audioTrackPopUpChanged: fAudLang4PopUp];
4591
4592     [fVidRatePopUp selectItemAtIndex: 0];
4593
4594     /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4595         [self calculatePictureSizing:nil];
4596
4597    /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4598     [self selectPreset:nil];
4599 }
4600
4601 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4602 {
4603     if( [fEncodeStartStopPopUp isEnabled] )
4604     {
4605         /* We are chapters */
4606         if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4607         {
4608             [fSrcChapterStartPopUp  setHidden: NO];
4609             [fSrcChapterEndPopUp  setHidden: NO];
4610             
4611             [fSrcTimeStartEncodingField  setHidden: YES];
4612             [fSrcTimeEndEncodingField  setHidden: YES];
4613             
4614             [fSrcFrameStartEncodingField  setHidden: YES];
4615             [fSrcFrameEndEncodingField  setHidden: YES];
4616             
4617                [self chapterPopUpChanged:nil];   
4618         }
4619         /* We are time based (seconds) */
4620         else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4621         {
4622             [fSrcChapterStartPopUp  setHidden: YES];
4623             [fSrcChapterEndPopUp  setHidden: YES];
4624             
4625             [fSrcTimeStartEncodingField  setHidden: NO];
4626             [fSrcTimeEndEncodingField  setHidden: NO];
4627             
4628             [fSrcFrameStartEncodingField  setHidden: YES];
4629             [fSrcFrameEndEncodingField  setHidden: YES];
4630             
4631             [self startEndSecValueChanged:nil];
4632         }
4633         /* We are frame based */
4634         else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4635         {
4636             [fSrcChapterStartPopUp  setHidden: YES];
4637             [fSrcChapterEndPopUp  setHidden: YES];
4638             
4639             [fSrcTimeStartEncodingField  setHidden: YES];
4640             [fSrcTimeEndEncodingField  setHidden: YES];
4641             
4642             [fSrcFrameStartEncodingField  setHidden: NO];
4643             [fSrcFrameEndEncodingField  setHidden: NO];
4644             
4645             [self startEndFrameValueChanged:nil];
4646         }
4647     }
4648 }
4649
4650 - (IBAction) chapterPopUpChanged: (id) sender
4651 {
4652
4653         /* If start chapter popup is greater than end chapter popup,
4654         we set the end chapter popup to the same as start chapter popup */
4655         if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4656         {
4657                 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4658     }
4659
4660                 
4661         hb_list_t  * list  = hb_get_titles( fHandle );
4662     hb_title_t * title = (hb_title_t *)
4663         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4664
4665     hb_chapter_t * chapter;
4666     int64_t        duration = 0;
4667     for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4668          i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4669     {
4670         chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4671         duration += chapter->duration;
4672     }
4673     
4674     duration /= 90000; /* pts -> seconds */
4675     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4676         @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4677         duration % 60]];
4678     
4679     [self calculateBitrate: sender];
4680     
4681     if ( [fSrcChapterStartPopUp indexOfSelectedItem] ==  [fSrcChapterEndPopUp indexOfSelectedItem] )
4682     {
4683     /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4684     [fCreateChapterMarkers setEnabled: NO];
4685     [fCreateChapterMarkers setState: NSOffState];
4686     }
4687     else
4688     {
4689     [fCreateChapterMarkers setEnabled: YES];
4690     }
4691 }
4692
4693 - (IBAction) startEndSecValueChanged: (id) sender
4694 {
4695
4696         int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4697     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4698         @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4699         duration % 60]];
4700     
4701     //[self calculateBitrate: sender];
4702     
4703 }
4704
4705 - (IBAction) startEndFrameValueChanged: (id) sender
4706 {
4707     hb_list_t  * list  = hb_get_titles( fHandle );
4708     hb_title_t * title = (hb_title_t*)
4709     hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4710     
4711     int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4712     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4713                                          @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4714                                          duration % 60]];
4715     
4716     //[self calculateBitrate: sender];
4717 }
4718
4719
4720 - (IBAction) formatPopUpChanged: (id) sender
4721 {
4722     NSString * string = [fDstFile2Field stringValue];
4723     int format = [fDstFormatPopUp indexOfSelectedItem];
4724     char * ext = NULL;
4725         /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4726     [fDstMp4LargeFileCheck setHidden: YES];
4727     [fDstMp4HttpOptFileCheck setHidden: YES];
4728     [fDstMp4iPodFileCheck setHidden: YES];
4729     
4730     /* Update the Video Codec PopUp */
4731     /* lets get the tag of the currently selected item first so we might reset it later */
4732     int selectedVidEncoderTag;
4733     selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4734     
4735     /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4736     [fVidEncoderPopUp removeAllItems];
4737     NSMenuItem *menuItem;
4738     /* These video encoders are available to all of our current muxers, so lets list them once here */
4739     menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4740     [menuItem setTag: HB_VCODEC_FFMPEG];
4741     
4742     switch( format )
4743     {
4744         case 0:
4745                         /*Get Default MP4 File Extension*/
4746                         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4747                         {
4748                                 ext = "m4v";
4749                         }
4750                         else
4751                         {
4752                                 ext = "mp4";
4753                         }
4754             /* Add additional video encoders here */
4755             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4756             [menuItem setTag: HB_VCODEC_X264];
4757             /* We show the mp4 option checkboxes here since we are mp4 */
4758             [fCreateChapterMarkers setEnabled: YES];
4759                         [fDstMp4LargeFileCheck setHidden: NO];
4760                         [fDstMp4HttpOptFileCheck setHidden: NO];
4761             [fDstMp4iPodFileCheck setHidden: NO];
4762             break;
4763             
4764             case 1:
4765             ext = "mkv";
4766             /* Add additional video encoders here */
4767             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4768             [menuItem setTag: HB_VCODEC_X264];
4769             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4770             [menuItem setTag: HB_VCODEC_THEORA];
4771             /* We enable the create chapters checkbox here */
4772                         [fCreateChapterMarkers setEnabled: YES];
4773                         break;
4774             
4775
4776     }
4777     /* tell fSubtitlesDelegate we have a new video container */
4778     
4779     [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4780     [fSubtitlesTable reloadData];
4781     /* if we have a previously selected vid encoder tag, then try to select it */
4782     if (selectedVidEncoderTag)
4783     {
4784         [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4785     }
4786     else
4787     {
4788         [fVidEncoderPopUp selectItemAtIndex: 0];
4789     }
4790
4791     [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4792     [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4793     [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4794     [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4795
4796     if( format == 0 )
4797         [self autoSetM4vExtension: sender];
4798     else
4799         [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4800
4801     if( SuccessfulScan )
4802     {
4803         /* Add/replace to the correct extension */
4804         [self audioTrackPopUpChanged: fAudLang1PopUp];
4805         [self audioTrackPopUpChanged: fAudLang2PopUp];
4806         [self audioTrackPopUpChanged: fAudLang3PopUp];
4807         [self audioTrackPopUpChanged: fAudLang4PopUp];
4808
4809         if( [fVidEncoderPopUp selectedItem] == nil )
4810         {
4811
4812             [fVidEncoderPopUp selectItemAtIndex:0];
4813             [self videoEncoderPopUpChanged:nil];
4814
4815             /* changing the format may mean that we can / can't offer mono or 6ch, */
4816             /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4817
4818             /* We call the method to properly enable/disable turbo 2 pass */
4819             [self twoPassCheckboxChanged: sender];
4820             /* We call method method to change UI to reflect whether a preset is used or not*/
4821         }
4822     }
4823         [self customSettingUsed: sender];
4824 }
4825
4826 - (IBAction) autoSetM4vExtension: (id) sender
4827 {
4828     if ( [fDstFormatPopUp indexOfSelectedItem] )
4829         return;
4830
4831     NSString * extension = @"mp4";
4832
4833     if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4834                                                         [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4835                                                         [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4836                                                         [fCreateChapterMarkers state] == NSOnState ||
4837                                                         [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4838     {
4839         extension = @"m4v";
4840     }
4841
4842     if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4843         return;
4844     else
4845         [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4846                                     [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4847 }
4848
4849 /* Method to determine if we should change the UI
4850 To reflect whether or not a Preset is being used or if
4851 the user is using "Custom" settings by determining the sender*/
4852 - (IBAction) customSettingUsed: (id) sender
4853 {
4854         if ([sender stringValue])
4855         {
4856                 /* Deselect the currently selected Preset if there is one*/
4857                 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4858                 /* Change UI to show "Custom" settings are being used */
4859                 [fPresetSelectedDisplay setStringValue: @"Custom"];
4860
4861                 curUserPresetChosenNum = nil;
4862         }
4863 [self calculateBitrate:nil];
4864 }
4865
4866
4867 #pragma mark -
4868 #pragma mark - Video
4869
4870 - (IBAction) videoEncoderPopUpChanged: (id) sender
4871 {
4872     hb_job_t * job = fTitle->job;
4873     int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4874     
4875     [fAdvancedOptions setHidden:YES];
4876     /* If we are using x264 then show the x264 advanced panel*/
4877     if (videoEncoder == HB_VCODEC_X264)
4878     {
4879         [fAdvancedOptions setHidden:NO];
4880         [self autoSetM4vExtension: sender];
4881     }
4882
4883     if (videoEncoder == HB_VCODEC_FFMPEG)
4884     {
4885         /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4886          container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4887          anything other than MP4.
4888          */ 
4889         [fDstMp4iPodFileCheck setEnabled: NO];
4890         [fDstMp4iPodFileCheck setState: NSOffState];
4891     }
4892     else
4893     {
4894         [fDstMp4iPodFileCheck setEnabled: YES];
4895     }
4896     [self setupQualitySlider];
4897         [self calculatePictureSizing: sender];
4898         [self twoPassCheckboxChanged: sender];
4899 }
4900
4901
4902 - (IBAction) twoPassCheckboxChanged: (id) sender
4903 {
4904         /* check to see if x264 is chosen */
4905         if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4906     {
4907                 if( [fVidTwoPassCheck state] == NSOnState)
4908                 {
4909                         [fVidTurboPassCheck setHidden: NO];
4910                 }
4911                 else
4912                 {
4913                         [fVidTurboPassCheck setHidden: YES];
4914                         [fVidTurboPassCheck setState: NSOffState];
4915                 }
4916                 /* Make sure Two Pass is checked if Turbo is checked */
4917                 if( [fVidTurboPassCheck state] == NSOnState)
4918                 {
4919                         [fVidTwoPassCheck setState: NSOnState];
4920                 }
4921         }
4922         else
4923         {
4924                 [fVidTurboPassCheck setHidden: YES];
4925                 [fVidTurboPassCheck setState: NSOffState];
4926         }
4927         
4928         /* We call method method to change UI to reflect whether a preset is used or not*/
4929         [self customSettingUsed: sender];
4930 }
4931
4932 - (IBAction ) videoFrameRateChanged: (id) sender
4933 {
4934     /* We call method method to calculatePictureSizing to error check detelecine*/
4935     [self calculatePictureSizing: sender];
4936
4937     /* We call method method to change UI to reflect whether a preset is used or not*/
4938         [self customSettingUsed: sender];
4939 }
4940 - (IBAction) videoMatrixChanged: (id) sender;
4941 {
4942     bool target, bitrate, quality;
4943
4944     target = bitrate = quality = false;
4945     if( [fVidQualityMatrix isEnabled] )
4946     {
4947         switch( [fVidQualityMatrix selectedRow] )
4948         {
4949             case 0:
4950                 target = true;
4951                 break;
4952             case 1:
4953                 bitrate = true;
4954                 break;
4955             case 2:
4956                 quality = true;
4957                 break;
4958         }
4959     }
4960     [fVidTargetSizeField  setEnabled: target];
4961     [fVidBitrateField     setEnabled: bitrate];
4962     [fVidQualitySlider    setEnabled: quality];
4963     [fVidQualityRFField   setEnabled: quality];
4964     [fVidQualityRFLabel    setEnabled: quality];
4965     [fVidTwoPassCheck     setEnabled: !quality &&
4966         [fVidQualityMatrix isEnabled]];
4967     if( quality )
4968     {
4969         [fVidTwoPassCheck setState: NSOffState];
4970                 [fVidTurboPassCheck setHidden: YES];
4971                 [fVidTurboPassCheck setState: NSOffState];
4972     }
4973
4974     [self qualitySliderChanged: sender];
4975     [self calculateBitrate: sender];
4976         [self customSettingUsed: sender];
4977 }
4978
4979 /* Use this method to setup the quality slider for cq/rf values depending on
4980  * the video encoder selected.
4981  */
4982 - (void) setupQualitySlider
4983 {
4984     /* Get the current slider maxValue to check for a change in slider scale later
4985      * so that we can choose a new similar value on the new slider scale */
4986     float previousMaxValue = [fVidQualitySlider maxValue];
4987     float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4988     NSString * qpRFLabelString = @"QP:";
4989     /* x264 0-51 */
4990     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4991     {
4992         [fVidQualitySlider setMinValue:0.0];
4993         [fVidQualitySlider setMaxValue:51.0];
4994         /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4995         int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4996         [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4997         qpRFLabelString = @"RF:";
4998     }
4999     /* ffmpeg  1-31 */
5000     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
5001     {
5002         [fVidQualitySlider setMinValue:1.0];
5003         [fVidQualitySlider setMaxValue:31.0];
5004         [fVidQualitySlider setNumberOfTickMarks:31];
5005     }
5006     /* Theora 0-63 */
5007     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5008     {
5009         [fVidQualitySlider setMinValue:0.0];
5010         [fVidQualitySlider setMaxValue:63.0];
5011         [fVidQualitySlider setNumberOfTickMarks:64];
5012     }
5013     [fVidQualityRFLabel setStringValue:qpRFLabelString];
5014     
5015     /* check to see if we have changed slider scales */
5016     if (previousMaxValue != [fVidQualitySlider maxValue])
5017     {
5018         /* if so, convert the old setting to the new scale as close as possible based on percentages */
5019         float rf =  ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
5020         [fVidQualitySlider setFloatValue:rf];
5021     }
5022     
5023     [self qualitySliderChanged:nil];
5024 }
5025
5026 - (IBAction) qualitySliderChanged: (id) sender
5027 {
5028     /* Our constant quality slider is in a range based
5029      * on each encoders qp/rf values. The range depends
5030      * on the encoder. Also, the range is inverse of quality
5031      * for all of the encoders *except* for theora
5032      * (ie. as the "quality" goes up, the cq or rf value
5033      * actually goes down). Since the IB sliders always set
5034      * their max value at the right end of the slider, we
5035      * will calculate the inverse, so as the slider floatValue
5036      * goes up, we will show the inverse in the rf field
5037      * so, the floatValue at the right for x264 would be 51
5038      * and our rf field needs to show 0 and vice versa.
5039      */
5040     
5041     float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5042     /* If the encoder is theora, use the float, otherwise use the inverse float*/
5043     float sliderRfToPercent;
5044     if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5045     {
5046         [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
5047         sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);   
5048     }
5049     else
5050     {
5051         [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5052         sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue])  - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
5053     }
5054     [fVidConstantCell setTitle: [NSString stringWithFormat:
5055                                  NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
5056     
5057     [self customSettingUsed: sender];
5058 }
5059
5060 - (void) controlTextDidChange: (NSNotification *) notification
5061 {
5062     [self calculateBitrate:nil];
5063 }
5064
5065 - (IBAction) calculateBitrate: (id) sender
5066 {
5067     if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5068     {
5069         return;
5070     }
5071
5072     hb_list_t  * list  = hb_get_titles( fHandle );
5073     hb_title_t * title = (hb_title_t *) hb_list_item( list,
5074             [fSrcTitlePopUp indexOfSelectedItem] );
5075     hb_job_t * job = title->job;
5076     hb_audio_config_t * audio;
5077     /* For  hb_calc_bitrate in addition to the Target Size in MB out of the
5078      * Target Size Field, we also need the job info for the Muxer, the Chapters
5079      * as well as all of the audio track info.
5080      * This used to be accomplished by simply calling prepareJob here, however
5081      * since the resilient queue sets the queue array values instead of the job
5082      * values directly, we duplicate the old prepareJob code here for the variables
5083      * needed
5084      */
5085     job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5086     job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1; 
5087     job->mux = [[fDstFormatPopUp selectedItem] tag];
5088     
5089     /* Audio goes here */
5090     int audiotrack_count = hb_list_count(job->list_audio);
5091     for( int i = 0; i < audiotrack_count;i++)
5092     {
5093         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5094         hb_list_rem(job->list_audio, temp_audio);
5095     }
5096     /* Now we need our audio info here for each track if applicable */
5097     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5098     {
5099         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5100         hb_audio_config_init(audio);
5101         audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5102         /* We go ahead and assign values to our audio->out.<properties> */
5103         audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5104         audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5105         audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5106         audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5107         audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5108         audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5109         
5110         hb_audio_add( job, audio );
5111         free(audio);
5112     }  
5113     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5114     {
5115         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5116         hb_audio_config_init(audio);
5117         audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5118         /* We go ahead and assign values to our audio->out.<properties> */
5119         audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5120         audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5121         audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5122         audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5123         audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5124         audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5125         
5126         hb_audio_add( job, audio );
5127         free(audio);
5128         
5129     }
5130     
5131     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5132     {
5133         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5134         hb_audio_config_init(audio);
5135         audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5136         /* We go ahead and assign values to our audio->out.<properties> */
5137         audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5138         audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5139         audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5140         audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5141         audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5142         audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5143         
5144         hb_audio_add( job, audio );
5145         free(audio);
5146         
5147     }
5148
5149     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5150     {
5151         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5152         hb_audio_config_init(audio);
5153         audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5154         /* We go ahead and assign values to our audio->out.<properties> */
5155         audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5156         audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5157         audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5158         audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5159         audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5160         audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5161         
5162         hb_audio_add( job, audio );
5163         free(audio);
5164         
5165     }
5166        
5167 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5168 }
5169
5170 #pragma mark -
5171 #pragma mark - Picture
5172
5173 /* lets set the picture size back to the max from right after title scan
5174    Lets use an IBAction here as down the road we could always use a checkbox
5175    in the gui to easily take the user back to max. Remember, the compiler
5176    resolves IBActions down to -(void) during compile anyway */
5177 - (IBAction) revertPictureSizeToMax: (id) sender
5178 {
5179         hb_job_t * job = fTitle->job;
5180         /* Here we apply the title source and height */
5181     job->width = fTitle->width;
5182     job->height = fTitle->height;
5183     
5184     [self calculatePictureSizing: sender];
5185     /* We call method to change UI to reflect whether a preset is used or not*/    
5186     [self customSettingUsed: sender];
5187 }
5188
5189 /**
5190  * Registers changes made in the Picture Settings Window.
5191  */
5192
5193 - (void)pictureSettingsDidChange 
5194 {
5195         [self calculatePictureSizing:nil];
5196 }
5197
5198 /* Get and Display Current Pic Settings in main window */
5199 - (IBAction) calculatePictureSizing: (id) sender
5200 {
5201         if (fTitle->job->anamorphic.mode > 0)
5202         {
5203         fTitle->job->keep_ratio = 0;
5204         }
5205     
5206     [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5207     
5208     NSString *picCropping;
5209     /* Set the display field for crop as per boolean */
5210         if (![fPictureController autoCrop])
5211         {
5212         picCropping =  @"Custom";
5213         }
5214         else
5215         {
5216                 picCropping =  @"Auto";
5217         }
5218     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]]];
5219     
5220     [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5221     
5222     NSString *videoFilters;
5223     videoFilters = @"";
5224     /* Detelecine */
5225     if ([fPictureController detelecine] == 2) 
5226     {
5227         videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5228     }
5229     else if ([fPictureController detelecine] == 1) 
5230     {
5231         videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5232     }
5233     
5234     
5235     if ([fPictureController useDecomb] == 1)
5236     {
5237         /* Decomb */
5238         if ([fPictureController decomb] == 2)
5239         {
5240             videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5241         }
5242         else if ([fPictureController decomb] == 1)
5243         {
5244             videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5245         }
5246     }
5247     else
5248     {
5249         /* Deinterlace */
5250         if ([fPictureController deinterlace] > 0)
5251         {
5252             fTitle->job->deinterlace  = 1;
5253         }
5254         else
5255         {
5256             fTitle->job->deinterlace  = 0;
5257         }
5258         
5259         if ([fPictureController deinterlace] == 2)
5260         {
5261             videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5262         }
5263         else if ([fPictureController deinterlace] == 3)
5264         {
5265             videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5266         }
5267         else if ([fPictureController deinterlace] == 4)
5268         {
5269             videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5270         }
5271         else if ([fPictureController deinterlace] == 1)
5272         {
5273             videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5274         }
5275         }
5276     
5277     
5278     /* Denoise */
5279         if ([fPictureController denoise] == 2)
5280         {
5281                 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5282     }
5283         else if ([fPictureController denoise] == 3)
5284         {
5285                 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5286     }
5287         else if ([fPictureController denoise] == 4)
5288         {
5289                 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5290         }
5291     else if ([fPictureController denoise] == 1)
5292         {
5293                 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5294         }
5295     
5296     /* Deblock */
5297     if ([fPictureController deblock] > 0) 
5298     {
5299         videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5300     }
5301         
5302     /* Grayscale */
5303     if ([fPictureController grayscale]) 
5304     {
5305         videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5306     }
5307     [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5308     
5309     //[fPictureController reloadStillPreview]; 
5310 }
5311
5312
5313 #pragma mark -
5314 #pragma mark - Audio and Subtitles
5315 - (IBAction) audioCodecsPopUpChanged: (id) sender
5316 {
5317     
5318     NSPopUpButton * audiotrackPopUp;
5319     NSPopUpButton * sampleratePopUp;
5320     NSPopUpButton * bitratePopUp;
5321     NSPopUpButton * audiocodecPopUp;
5322     if (sender == fAudTrack1CodecPopUp)
5323     {
5324         audiotrackPopUp = fAudLang1PopUp;
5325         audiocodecPopUp = fAudTrack1CodecPopUp;
5326         sampleratePopUp = fAudTrack1RatePopUp;
5327         bitratePopUp = fAudTrack1BitratePopUp;
5328     }
5329     else if (sender == fAudTrack2CodecPopUp)
5330     {
5331         audiotrackPopUp = fAudLang2PopUp;
5332         audiocodecPopUp = fAudTrack2CodecPopUp;
5333         sampleratePopUp = fAudTrack2RatePopUp;
5334         bitratePopUp = fAudTrack2BitratePopUp;
5335     }
5336     else if (sender == fAudTrack3CodecPopUp)
5337     {
5338         audiotrackPopUp = fAudLang3PopUp;
5339         audiocodecPopUp = fAudTrack3CodecPopUp;
5340         sampleratePopUp = fAudTrack3RatePopUp;
5341         bitratePopUp = fAudTrack3BitratePopUp;
5342     }
5343     else
5344     {
5345         audiotrackPopUp = fAudLang4PopUp;
5346         audiocodecPopUp = fAudTrack4CodecPopUp;
5347         sampleratePopUp = fAudTrack4RatePopUp;
5348         bitratePopUp = fAudTrack4BitratePopUp;
5349     }
5350         
5351     /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5352         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5353     [self audioTrackPopUpChanged: audiotrackPopUp];
5354     
5355 }
5356
5357 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5358 {
5359     /* We will be setting the enabled/disabled state of each tracks audio controls based on
5360      * the settings of the source audio for that track. We leave the samplerate and bitrate
5361      * to audiotrackMixdownChanged
5362      */
5363     
5364     /* We will first verify that a lower track number has been selected before enabling each track
5365      * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5366      */
5367     if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5368     {
5369         [fAudLang2PopUp setEnabled: NO];
5370         [fAudLang2PopUp selectItemAtIndex: 0];
5371     }
5372     else
5373     {
5374         [fAudLang2PopUp setEnabled: YES];
5375     }
5376     
5377     if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5378     {
5379         [fAudLang3PopUp setEnabled: NO];
5380         [fAudLang3PopUp selectItemAtIndex: 0];
5381     }
5382     else
5383     {
5384         [fAudLang3PopUp setEnabled: YES];
5385     }
5386     if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5387     {
5388         [fAudLang4PopUp setEnabled: NO];
5389         [fAudLang4PopUp selectItemAtIndex: 0];
5390     }
5391     else
5392     {
5393         [fAudLang4PopUp setEnabled: YES];
5394     }
5395     /* enable/disable the mixdown text and popupbutton for audio track 1 */
5396     [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5397     [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5398     [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5399     [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5400     [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5401     [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5402     if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5403     {
5404         [fAudTrack1CodecPopUp removeAllItems];
5405         [fAudTrack1MixPopUp removeAllItems];
5406         [fAudTrack1RatePopUp removeAllItems];
5407         [fAudTrack1BitratePopUp removeAllItems];
5408         [fAudTrack1DrcSlider setFloatValue: 0.00];
5409         [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5410     }
5411     else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5412     {
5413         [fAudTrack1RatePopUp setEnabled: NO];
5414         [fAudTrack1BitratePopUp setEnabled: NO];
5415         [fAudTrack1DrcSlider setEnabled: NO];
5416         [fAudTrack1DrcField setEnabled: NO];
5417     }
5418     
5419     /* enable/disable the mixdown text and popupbutton for audio track 2 */
5420     [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5421     [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5422     [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5423     [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5424     [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5425     [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5426     if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5427     {
5428         [fAudTrack2CodecPopUp removeAllItems];
5429         [fAudTrack2MixPopUp removeAllItems];
5430         [fAudTrack2RatePopUp removeAllItems];
5431         [fAudTrack2BitratePopUp removeAllItems];
5432         [fAudTrack2DrcSlider setFloatValue: 0.00];
5433         [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5434     }
5435     else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5436     {
5437         [fAudTrack2RatePopUp setEnabled: NO];
5438         [fAudTrack2BitratePopUp setEnabled: NO];
5439         [fAudTrack2DrcSlider setEnabled: NO];
5440         [fAudTrack2DrcField setEnabled: NO];
5441     }
5442     
5443     /* enable/disable the mixdown text and popupbutton for audio track 3 */
5444     [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5445     [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5446     [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5447     [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5448     [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5449     [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5450     if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5451     {
5452         [fAudTrack3CodecPopUp removeAllItems];
5453         [fAudTrack3MixPopUp removeAllItems];
5454         [fAudTrack3RatePopUp removeAllItems];
5455         [fAudTrack3BitratePopUp removeAllItems];
5456         [fAudTrack3DrcSlider setFloatValue: 0.00];
5457         [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5458     }
5459     else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5460     {
5461         [fAudTrack3RatePopUp setEnabled: NO];
5462         [fAudTrack3BitratePopUp setEnabled: NO];
5463         [fAudTrack3DrcSlider setEnabled: NO];
5464         [fAudTrack3DrcField setEnabled: NO];
5465     }
5466     
5467     /* enable/disable the mixdown text and popupbutton for audio track 4 */
5468     [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5469     [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5470     [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5471     [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5472     [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5473     [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5474     if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5475     {
5476         [fAudTrack4CodecPopUp removeAllItems];
5477         [fAudTrack4MixPopUp removeAllItems];
5478         [fAudTrack4RatePopUp removeAllItems];
5479         [fAudTrack4BitratePopUp removeAllItems];
5480         [fAudTrack4DrcSlider setFloatValue: 0.00];
5481         [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5482     }
5483     else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5484     {
5485         [fAudTrack4RatePopUp setEnabled: NO];
5486         [fAudTrack4BitratePopUp setEnabled: NO];
5487         [fAudTrack4DrcSlider setEnabled: NO];
5488         [fAudTrack4DrcField setEnabled: NO];
5489     }
5490     
5491 }
5492
5493 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5494 {
5495
5496     hb_list_t  * list  = hb_get_titles( fHandle );
5497     hb_title_t * title = (hb_title_t*)
5498         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5499
5500         hb_audio_config_t * audio;
5501
5502     [sender removeAllItems];
5503     [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5504     for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5505     {
5506         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5507         [[sender menu] addItemWithTitle:
5508             [NSString stringWithUTF8String: audio->lang.description]
5509             action: NULL keyEquivalent: @""];
5510     }
5511     [sender selectItemAtIndex: 0];
5512
5513 }
5514
5515 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5516 {
5517
5518     /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5519     /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5520     /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5521     /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5522
5523         if (searchPrefixString)
5524         {
5525
5526         for( int i = 0; i < [sender numberOfItems]; i++ )
5527         {
5528             /* Try to find the desired search string */
5529             if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5530             {
5531                 [sender selectItemAtIndex: i];
5532                 return;
5533             }
5534         }
5535         /* couldn't find the string, so select the requested "search string not found" item */
5536         /* index of 0 means select the "none" item */
5537         /* index of 1 means select the first audio track */
5538         [sender selectItemAtIndex: selectIndexIfNotFound];
5539         }
5540     else
5541     {
5542         /* if no search string is provided, then select the selectIndexIfNotFound item */
5543         [sender selectItemAtIndex: selectIndexIfNotFound];
5544     }
5545
5546 }
5547 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5548 {
5549     int format = [fDstFormatPopUp indexOfSelectedItem];
5550     
5551     /* setup pointers to the appropriate popups for the correct track */
5552     NSPopUpButton * audiocodecPopUp;
5553     NSPopUpButton * audiotrackPopUp;
5554     if (sender == fAudTrack1CodecPopUp)
5555     {
5556         audiotrackPopUp = fAudLang1PopUp;
5557         audiocodecPopUp = fAudTrack1CodecPopUp;
5558     }
5559     else if (sender == fAudTrack2CodecPopUp)
5560     {
5561         audiotrackPopUp = fAudLang2PopUp;
5562         audiocodecPopUp = fAudTrack2CodecPopUp;
5563     }
5564     else if (sender == fAudTrack3CodecPopUp)
5565     {
5566         audiotrackPopUp = fAudLang3PopUp;
5567         audiocodecPopUp = fAudTrack3CodecPopUp;
5568     }
5569     else
5570     {
5571         audiotrackPopUp = fAudLang4PopUp;
5572         audiocodecPopUp = fAudTrack4CodecPopUp;
5573     }
5574     
5575     [audiocodecPopUp removeAllItems];
5576     /* Make sure "None" isnt selected in the source track */
5577     if ([audiotrackPopUp indexOfSelectedItem] > 0)
5578     {
5579         [audiocodecPopUp setEnabled:YES];
5580         NSMenuItem *menuItem;
5581         /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5582         switch( format )
5583         {
5584             case 0:
5585                 /* MP4 */
5586                 // FAAC
5587                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5588                 [menuItem setTag: HB_ACODEC_FAAC];
5589
5590                 // CA_AAC
5591                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5592                 [menuItem setTag: HB_ACODEC_CA_AAC];
5593
5594                 // AC3 Passthru
5595                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5596                 [menuItem setTag: HB_ACODEC_AC3];
5597                 break;
5598                 
5599             case 1:
5600                 /* MKV */
5601                 // FAAC
5602                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5603                 [menuItem setTag: HB_ACODEC_FAAC];
5604                 // CA_AAC
5605                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5606                 [menuItem setTag: HB_ACODEC_CA_AAC];
5607                 // AC3 Passthru
5608                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5609                 [menuItem setTag: HB_ACODEC_AC3];
5610                 // DTS Passthru
5611                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5612                 [menuItem setTag: HB_ACODEC_DCA];
5613                 // MP3
5614                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5615                 [menuItem setTag: HB_ACODEC_LAME];
5616                 // Vorbis
5617                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5618                 [menuItem setTag: HB_ACODEC_VORBIS];
5619                 break;
5620                 
5621             case 2: 
5622                 /* AVI */
5623                 // MP3
5624                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5625                 [menuItem setTag: HB_ACODEC_LAME];
5626                 // AC3 Passthru
5627                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5628                 [menuItem setTag: HB_ACODEC_AC3];
5629                 break;
5630                 
5631             case 3:
5632                 /* OGM */
5633                 // Vorbis
5634                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5635                 [menuItem setTag: HB_ACODEC_VORBIS];
5636                 // MP3
5637                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5638                 [menuItem setTag: HB_ACODEC_LAME];
5639                 break;
5640         }
5641         [audiocodecPopUp selectItemAtIndex:0];
5642     }
5643     else
5644     {
5645         [audiocodecPopUp setEnabled:NO];
5646     }
5647 }
5648
5649 - (IBAction) audioTrackPopUpChanged: (id) sender
5650 {
5651     /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5652     [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5653 }
5654
5655 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5656 {
5657     
5658     /* make sure we have a selected title before continuing */
5659     if (fTitle == NULL) return;
5660     /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5661     * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5662     */
5663     if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5664     {
5665         [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5666     }
5667     if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5668     {
5669         [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5670     }
5671     if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5672     {
5673         [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5674     }
5675     if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5676     {
5677         [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5678     }
5679     
5680     /* Now lets make the sender the appropriate Audio Track popup from this point on */
5681     if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5682     {
5683         sender = fAudLang1PopUp;
5684     }
5685     if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5686     {
5687         sender = fAudLang2PopUp;
5688     }
5689     if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5690     {
5691         sender = fAudLang3PopUp;
5692     }
5693     if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5694     {
5695         sender = fAudLang4PopUp;
5696     }
5697     
5698     /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5699     NSPopUpButton * mixdownPopUp;
5700     NSPopUpButton * audiocodecPopUp;
5701     NSPopUpButton * sampleratePopUp;
5702     NSPopUpButton * bitratePopUp;
5703     if (sender == fAudLang1PopUp)
5704     {
5705         mixdownPopUp = fAudTrack1MixPopUp;
5706         audiocodecPopUp = fAudTrack1CodecPopUp;
5707         sampleratePopUp = fAudTrack1RatePopUp;
5708         bitratePopUp = fAudTrack1BitratePopUp;
5709     }
5710     else if (sender == fAudLang2PopUp)
5711     {
5712         mixdownPopUp = fAudTrack2MixPopUp;
5713         audiocodecPopUp = fAudTrack2CodecPopUp;
5714         sampleratePopUp = fAudTrack2RatePopUp;
5715         bitratePopUp = fAudTrack2BitratePopUp;
5716     }
5717     else if (sender == fAudLang3PopUp)
5718     {
5719         mixdownPopUp = fAudTrack3MixPopUp;
5720         audiocodecPopUp = fAudTrack3CodecPopUp;
5721         sampleratePopUp = fAudTrack3RatePopUp;
5722         bitratePopUp = fAudTrack3BitratePopUp;
5723     }
5724     else
5725     {
5726         mixdownPopUp = fAudTrack4MixPopUp;
5727         audiocodecPopUp = fAudTrack4CodecPopUp;
5728         sampleratePopUp = fAudTrack4RatePopUp;
5729         bitratePopUp = fAudTrack4BitratePopUp;
5730     }
5731
5732     /* get the index of the selected audio Track*/
5733     int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5734
5735     /* pointer for the hb_audio_s struct we will use later on */
5736     hb_audio_config_t * audio;
5737
5738     int acodec;
5739     /* check if the audio mixdown controls need their enabled state changing */
5740     [self setEnabledStateOfAudioMixdownControls:nil];
5741
5742     if (thisAudioIndex != -1)
5743     {
5744
5745         /* get the audio */
5746         audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5747
5748         /* actually manipulate the proper mixdowns here */
5749         /* delete the previous audio mixdown options */
5750         [mixdownPopUp removeAllItems];
5751
5752         acodec = [[audiocodecPopUp selectedItem] tag];
5753
5754         if (audio != NULL)
5755         {
5756
5757             /* find out if our selected output audio codec supports mono and / or 6ch */
5758             /* we also check for an input codec of AC3 or DCA,
5759              as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5760             /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5761              but this may change in the future, so they are separated for flexibility */
5762             int audioCodecsSupportMono =
5763                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5764                     (acodec != HB_ACODEC_LAME);
5765             int audioCodecsSupport6Ch =
5766                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5767                     (acodec != HB_ACODEC_LAME);
5768             
5769             /* check for AC-3 passthru */
5770             if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5771             {
5772                 
5773             NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5774                  [NSString stringWithUTF8String: "AC3 Passthru"]
5775                                                action: NULL keyEquivalent: @""];
5776              [menuItem setTag: HB_ACODEC_AC3];   
5777             }
5778             else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5779             {
5780             NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5781                  [NSString stringWithUTF8String: "DTS Passthru"]
5782                                                action: NULL keyEquivalent: @""];
5783              [menuItem setTag: HB_ACODEC_DCA]; 
5784             }
5785             else
5786             {
5787                 
5788                 /* add the appropriate audio mixdown menuitems to the popupbutton */
5789                 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5790                  so that we can reference the mixdown later */
5791                 
5792                 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5793                 int minMixdownUsed = 0;
5794                 int maxMixdownUsed = 0;
5795                 
5796                 /* get the input channel layout without any lfe channels */
5797                 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5798                 
5799                 /* do we want to add a mono option? */
5800                 if (audioCodecsSupportMono == 1)
5801                 {
5802                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5803                                             [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5804                                                                           action: NULL keyEquivalent: @""];
5805                     [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5806                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5807                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5808                 }
5809                 
5810                 /* do we want to add a stereo option? */
5811                 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5812                 /* also offer stereo if we have a stereo-or-better source */
5813                 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5814                 {
5815                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5816                                             [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5817                                                                           action: NULL keyEquivalent: @""];
5818                     [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5819                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5820                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5821                 }
5822                 
5823                 /* do we want to add a dolby surround (DPL1) option? */
5824                 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5825                 {
5826                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5827                                             [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5828                                                                           action: NULL keyEquivalent: @""];
5829                     [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5830                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5831                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5832                 }
5833                 
5834                 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5835                 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5836                 {
5837                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5838                                             [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5839                                                                           action: NULL keyEquivalent: @""];
5840                     [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5841                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5842                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5843                 }
5844                 
5845                 /* do we want to add a 6-channel discrete option? */
5846                 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5847                 {
5848                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5849                                             [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5850                                                                           action: NULL keyEquivalent: @""];
5851                     [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5852                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5853                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5854                 }
5855                 
5856                 /* do we want to add an AC-3 passthrough option? */
5857                 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3) 
5858                 {
5859                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5860                                             [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5861                                                                           action: NULL keyEquivalent: @""];
5862                     [menuItem setTag: HB_ACODEC_AC3];
5863                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5864                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5865                 }
5866                 
5867                 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5868                 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA) 
5869                 {
5870                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5871                                             [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5872                                                                           action: NULL keyEquivalent: @""];
5873                     [menuItem setTag: HB_ACODEC_DCA];
5874                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5875                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5876                 }
5877                 
5878                 /* auto-select the best mixdown based on our saved mixdown preference */
5879                 
5880                 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5881                 /* ultimately this should be a prefs option */
5882                 int useMixdown;
5883                 
5884                 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5885                 if (mixdownToUse > 0)
5886                 {
5887                     useMixdown = mixdownToUse;
5888                 }
5889                 else
5890                 {
5891                     useMixdown = HB_AMIXDOWN_DOLBYPLII;
5892                 }
5893                 
5894                 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5895                 if (useMixdown > maxMixdownUsed)
5896                 { 
5897                     useMixdown = maxMixdownUsed;
5898                 }
5899                 
5900                 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5901                 if (useMixdown < minMixdownUsed)
5902                 { 
5903                     useMixdown = minMixdownUsed;
5904                 }
5905                 
5906                 /* select the (possibly-amended) preferred mixdown */
5907                 [mixdownPopUp selectItemWithTag: useMixdown];
5908
5909             }
5910             /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5911              * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5912              * other containers.
5913              */
5914             if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5915             {
5916                 /* If we are using the avi container, we select MP3 as there is no aac available*/
5917                 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5918                 {
5919                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5920                 }
5921                 else
5922                 {
5923                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5924                 }
5925             }
5926             
5927             /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5928              * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5929              * other containers.
5930              */
5931             if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5932             {
5933                 /* If we are using the avi container, we select MP3 as there is no aac available*/
5934                 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5935                 {
5936                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5937                 }
5938                 else
5939                 {
5940                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5941                 }
5942             }
5943             
5944             /* Setup our samplerate and bitrate popups we will need based on mixdown */
5945             [self audioTrackMixdownChanged: mixdownPopUp];             
5946         }
5947     
5948     }
5949     if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5950     {
5951         [self autoSetM4vExtension: sender];
5952     }
5953 }
5954
5955 - (IBAction) audioTrackMixdownChanged: (id) sender
5956 {
5957     
5958     int acodec;
5959     /* setup pointers to all of the other audio track controls
5960     * we will need later
5961     */
5962     NSPopUpButton * mixdownPopUp;
5963     NSPopUpButton * sampleratePopUp;
5964     NSPopUpButton * bitratePopUp;
5965     NSPopUpButton * audiocodecPopUp;
5966     NSPopUpButton * audiotrackPopUp;
5967     NSSlider * drcSlider;
5968     NSTextField * drcField;
5969     if (sender == fAudTrack1MixPopUp)
5970     {
5971         audiotrackPopUp = fAudLang1PopUp;
5972         audiocodecPopUp = fAudTrack1CodecPopUp;
5973         mixdownPopUp = fAudTrack1MixPopUp;
5974         sampleratePopUp = fAudTrack1RatePopUp;
5975         bitratePopUp = fAudTrack1BitratePopUp;
5976         drcSlider = fAudTrack1DrcSlider;
5977         drcField = fAudTrack1DrcField;
5978     }
5979     else if (sender == fAudTrack2MixPopUp)
5980     {
5981         audiotrackPopUp = fAudLang2PopUp;
5982         audiocodecPopUp = fAudTrack2CodecPopUp;
5983         mixdownPopUp = fAudTrack2MixPopUp;
5984         sampleratePopUp = fAudTrack2RatePopUp;
5985         bitratePopUp = fAudTrack2BitratePopUp;
5986         drcSlider = fAudTrack2DrcSlider;
5987         drcField = fAudTrack2DrcField;
5988     }
5989     else if (sender == fAudTrack3MixPopUp)
5990     {
5991         audiotrackPopUp = fAudLang3PopUp;
5992         audiocodecPopUp = fAudTrack3CodecPopUp;
5993         mixdownPopUp = fAudTrack3MixPopUp;
5994         sampleratePopUp = fAudTrack3RatePopUp;
5995         bitratePopUp = fAudTrack3BitratePopUp;
5996         drcSlider = fAudTrack3DrcSlider;
5997         drcField = fAudTrack3DrcField;
5998     }
5999     else
6000     {
6001         audiotrackPopUp = fAudLang4PopUp;
6002         audiocodecPopUp = fAudTrack4CodecPopUp;
6003         mixdownPopUp = fAudTrack4MixPopUp;
6004         sampleratePopUp = fAudTrack4RatePopUp;
6005         bitratePopUp = fAudTrack4BitratePopUp;
6006         drcSlider = fAudTrack4DrcSlider;
6007         drcField = fAudTrack4DrcField;
6008     }
6009     acodec = [[audiocodecPopUp selectedItem] tag];
6010     /* storage variable for the min and max bitrate allowed for this codec */
6011     int minbitrate;
6012     int maxbitrate;
6013     
6014     switch( acodec )
6015     {
6016         case HB_ACODEC_FAAC:
6017             /* check if we have a 6ch discrete conversion in either audio track */
6018             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6019             {
6020                 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
6021                 minbitrate = 192;
6022                 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
6023                 maxbitrate = 448;
6024                 break;
6025             }
6026             else
6027             {
6028                 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
6029                 minbitrate = 32;
6030                 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
6031                 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
6032                 maxbitrate = 160;
6033                 break;
6034             }
6035
6036         case HB_ACODEC_CA_AAC:
6037             /* check if we have a 6ch discrete conversion in either audio track */
6038             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6039             {
6040                 minbitrate = 128;
6041                 maxbitrate = 768;
6042                 break;
6043             }
6044             else
6045             {
6046                 minbitrate = 64;
6047                 maxbitrate = 320;
6048                 break;
6049             }
6050
6051             case HB_ACODEC_LAME:
6052             /* Lame is happy using our min bitrate of 32 kbps */
6053             minbitrate = 32;
6054             /* Lame won't encode if the bitrate is higher than 320 kbps */
6055             maxbitrate = 320;
6056             break;
6057             
6058             case HB_ACODEC_VORBIS:
6059             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6060             {
6061                 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6062                 minbitrate = 192;
6063                 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6064                 maxbitrate = 384;
6065                 break;
6066             }
6067             else
6068             {
6069                 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6070                 minbitrate = 48;
6071                 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6072                 maxbitrate = 384;
6073                 break;
6074             }
6075             
6076             default:
6077             /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6078             minbitrate = 32;
6079             maxbitrate = 384;
6080             
6081     }
6082     
6083     /* make sure we have a selected title before continuing */
6084     if (fTitle == NULL) return;
6085     /* get the audio so we can find out what input rates are*/
6086     hb_audio_config_t * audio;
6087     audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6088     int inputbitrate = audio->in.bitrate / 1000;
6089     int inputsamplerate = audio->in.samplerate;
6090     
6091     if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6092     {
6093         [bitratePopUp removeAllItems];
6094         
6095         for( int i = 0; i < hb_audio_bitrates_count; i++ )
6096         {
6097             if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6098             {
6099                 /* add a new menuitem for this bitrate */
6100                 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6101                                         [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6102                                                                       action: NULL keyEquivalent: @""];
6103                 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6104                 [menuItem setTag: hb_audio_bitrates[i].rate];
6105             }
6106         }
6107         
6108         /* select the default bitrate (but use 384 for 6-ch AAC) */
6109         if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6110         {
6111             [bitratePopUp selectItemWithTag: 384];
6112         }
6113         else
6114         {
6115             [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6116         }
6117     }
6118     /* populate and set the sample rate popup */
6119     /* Audio samplerate */
6120     [sampleratePopUp removeAllItems];
6121     /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6122     NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6123     [menuItem setTag: inputsamplerate];
6124     
6125     for( int i = 0; i < hb_audio_rates_count; i++ )
6126     {
6127         NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6128                                 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6129                                                                  action: NULL keyEquivalent: @""];
6130         [menuItem setTag: hb_audio_rates[i].rate];
6131     }
6132     /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6133     * and there is no compelling reason to use anything else as default, though the users default
6134     * preset will likely override any setting chosen here.
6135     */
6136     [sampleratePopUp selectItemWithTag: inputsamplerate];
6137     
6138     
6139     /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6140     * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6141     * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6142     */
6143     if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6144     {
6145         
6146         /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6147         [bitratePopUp removeAllItems];
6148         NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6149                                 [NSString stringWithFormat:@"%d", inputbitrate]
6150                                                               action: NULL keyEquivalent: @""];
6151         [menuItem setTag: inputbitrate];
6152         /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6153         [bitratePopUp setEnabled: NO];
6154         [sampleratePopUp setEnabled: NO];
6155         
6156         [drcSlider setFloatValue: 0.00];
6157         [self audioDRCSliderChanged: drcSlider];
6158         [drcSlider setEnabled: NO];
6159         [drcField setEnabled: NO];
6160     }
6161     else
6162     {
6163         [sampleratePopUp setEnabled: YES];
6164         [bitratePopUp setEnabled: YES];
6165         [drcSlider setEnabled: YES];
6166         [drcField setEnabled: YES];
6167     }
6168 [self calculateBitrate:nil];    
6169 }
6170
6171 - (IBAction) audioDRCSliderChanged: (id) sender
6172 {
6173     NSSlider * drcSlider;
6174     NSTextField * drcField;
6175     if (sender == fAudTrack1DrcSlider)
6176     {
6177         drcSlider = fAudTrack1DrcSlider;
6178         drcField = fAudTrack1DrcField;
6179     }
6180     else if (sender == fAudTrack2DrcSlider)
6181     {
6182         drcSlider = fAudTrack2DrcSlider;
6183         drcField = fAudTrack2DrcField;
6184     }
6185     else if (sender == fAudTrack3DrcSlider)
6186     {
6187         drcSlider = fAudTrack3DrcSlider;
6188         drcField = fAudTrack3DrcField;
6189     }
6190     else
6191     {
6192         drcSlider = fAudTrack4DrcSlider;
6193         drcField = fAudTrack4DrcField;
6194     }
6195     
6196     /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6197     if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6198     {
6199         [drcSlider setFloatValue:1.0];
6200     }
6201     
6202     
6203     [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6204     /* For now, do not call this until we have an intelligent way to determine audio track selections
6205     * compared to presets
6206     */
6207     //[self customSettingUsed: sender];
6208 }
6209
6210 #pragma mark -
6211
6212 - (IBAction) browseImportSrtFile: (id) sender
6213 {
6214
6215     NSOpenPanel * panel;
6216         
6217     panel = [NSOpenPanel openPanel];
6218     [panel setAllowsMultipleSelection: NO];
6219     [panel setCanChooseFiles: YES];
6220     [panel setCanChooseDirectories: NO ];
6221     NSString * sourceDirectory;
6222         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6223         {
6224                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6225         }
6226         else
6227         {
6228                 sourceDirectory = @"~/Desktop";
6229                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6230         }
6231     /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6232     NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6233     [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6234                    modalForWindow: fWindow modalDelegate: self
6235                    didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6236                       contextInfo: sender];
6237 }
6238
6239 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6240                      returnCode: (int) returnCode contextInfo: (void *) contextInfo
6241 {
6242     if( returnCode == NSOKButton )
6243     {
6244         NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6245         NSString *importSrtFilePath = [sheet filename];
6246         [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6247         
6248         /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6249         [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6250         
6251         [fSubtitlesTable reloadData];
6252         
6253     }
6254 }                                           
6255
6256 #pragma mark -
6257 #pragma mark Open New Windows
6258
6259 - (IBAction) openHomepage: (id) sender
6260 {
6261     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6262         URLWithString:@"http://handbrake.fr/"]];
6263 }
6264
6265 - (IBAction) openForums: (id) sender
6266 {
6267     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6268         URLWithString:@"http://handbrake.fr/forum/"]];
6269 }
6270 - (IBAction) openUserGuide: (id) sender
6271 {
6272     [[NSWorkspace sharedWorkspace] openURL: [NSURL
6273         URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6274 }
6275
6276 /**
6277  * Shows debug output window.
6278  */
6279 - (IBAction)showDebugOutputPanel:(id)sender
6280 {
6281     [outputPanel showOutputPanel:sender];
6282 }
6283
6284 /**
6285  * Shows preferences window.
6286  */
6287 - (IBAction) showPreferencesWindow: (id) sender
6288 {
6289     NSWindow * window = [fPreferencesController window];
6290     if (![window isVisible])
6291         [window center];
6292
6293     [window makeKeyAndOrderFront: nil];
6294 }
6295
6296 /**
6297  * Shows queue window.
6298  */
6299 - (IBAction) showQueueWindow:(id)sender
6300 {
6301     [fQueueController showQueueWindow:sender];
6302 }
6303
6304
6305 - (IBAction) toggleDrawer:(id)sender {
6306     [fPresetDrawer toggle:self];
6307 }
6308
6309 /**
6310  * Shows Picture Settings Window.
6311  */
6312
6313 - (IBAction) showPicturePanel: (id) sender
6314 {
6315         [fPictureController showPictureWindow:sender];
6316 }
6317
6318 - (void) picturePanelFullScreen
6319 {
6320         [fPictureController setToFullScreenMode];
6321 }
6322
6323 - (void) picturePanelWindowed
6324 {
6325         [fPictureController setToWindowedMode];
6326 }
6327
6328 - (IBAction) showPreviewWindow: (id) sender
6329 {
6330         [fPictureController showPreviewWindow:sender];
6331 }
6332
6333 #pragma mark -
6334 #pragma mark Preset Outline View Methods
6335 #pragma mark - Required
6336 /* These are required by the NSOutlineView Datasource Delegate */
6337
6338
6339 /* used to specify the number of levels to show for each item */
6340 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6341 {
6342     /* currently use no levels to test outline view viability */
6343     if (item == nil) // for an outline view the root level of the hierarchy is always nil
6344     {
6345         return [UserPresets count];
6346     }
6347     else
6348     {
6349         /* we need to return the count of the array in ChildrenArray for this folder */
6350         NSArray *children = nil;
6351         children = [item objectForKey:@"ChildrenArray"];
6352         if ([children count] > 0)
6353         {
6354             return [children count];
6355         }
6356         else
6357         {
6358             return 0;
6359         }
6360     }
6361 }
6362
6363 /* We use this to deterimine children of an item */
6364 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6365 {
6366     
6367     /* we need to return the count of the array in ChildrenArray for this folder */
6368     NSArray *children = nil;
6369     if (item == nil)
6370     {
6371         children = UserPresets;
6372     }
6373     else
6374     {
6375         if ([item objectForKey:@"ChildrenArray"])
6376         {
6377             children = [item objectForKey:@"ChildrenArray"];
6378         }
6379     }   
6380     if ((children == nil) || ( [children count] <= (NSUInteger) index))
6381     {
6382         return nil;
6383     }
6384     else
6385     {
6386         return [children objectAtIndex:index];
6387     }
6388     
6389     
6390     // We are only one level deep, so we can't be asked about children
6391     //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6392     //return nil;
6393 }
6394
6395 /* We use this to determine if an item should be expandable */
6396 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6397 {
6398     
6399     /* we need to return the count of the array in ChildrenArray for this folder */
6400     NSArray *children= nil;
6401     if (item == nil)
6402     {
6403         children = UserPresets;
6404     }
6405     else
6406     {
6407         if ([item objectForKey:@"ChildrenArray"])
6408         {
6409             children = [item objectForKey:@"ChildrenArray"];
6410         }
6411     }   
6412     
6413     /* To deterimine if an item should show a disclosure triangle
6414      * we could do it by the children count as so:
6415      * if ([children count] < 1)
6416      * However, lets leave the triangle show even if there are no
6417      * children to help indicate a folder, just like folder in the
6418      * finder can show a disclosure triangle even when empty
6419      */
6420     
6421     /* We need to determine if the item is a folder */
6422    if ([[item objectForKey:@"Folder"] intValue] == 1)
6423    {
6424         return YES;
6425     }
6426     else
6427     {
6428         return NO;
6429     }
6430     
6431 }
6432
6433 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6434 {
6435     // Our outline view has no levels, but we can still expand every item. Doing so
6436     // just makes the row taller. See heightOfRowByItem below.
6437 //return ![(HBQueueOutlineView*)outlineView isDragging];
6438
6439 return YES;
6440 }
6441
6442
6443 /* Used to tell the outline view which information is to be displayed per item */
6444 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6445 {
6446         /* We have two columns right now, icon and PresetName */
6447         
6448     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6449     {
6450         return [item objectForKey:@"PresetName"];
6451     }
6452     else
6453     {
6454         //return @"";
6455         return nil;
6456     }
6457 }
6458
6459 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6460 {
6461     return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6462 }
6463 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6464 {
6465     return [NSKeyedArchiver archivedDataWithRootObject:item];
6466 }
6467
6468 #pragma mark - Added Functionality (optional)
6469 /* Use to customize the font and display characteristics of the title cell */
6470 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6471 {
6472     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6473     {
6474         NSFont *txtFont;
6475         NSColor *fontColor;
6476         NSColor *shadowColor;
6477         txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6478         /*check to see if its a selected row */
6479         if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6480         {
6481             
6482             fontColor = [NSColor blackColor];
6483             shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6484         }
6485         else
6486         {
6487             if ([[item objectForKey:@"Type"] intValue] == 0)
6488             {
6489                 fontColor = [NSColor blueColor];
6490             }
6491             else // User created preset, use a black font
6492             {
6493                 fontColor = [NSColor blackColor];
6494             }
6495             /* check to see if its a folder */
6496             //if ([[item objectForKey:@"Folder"] intValue] == 1)
6497             //{
6498             //fontColor = [NSColor greenColor];
6499             //}
6500             
6501             
6502         }
6503         /* We use Bold Text for the HB Default */
6504         if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6505         {
6506             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6507         }
6508         /* We use Bold Text for the User Specified Default */
6509         if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6510         {
6511             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6512         }
6513         
6514         
6515         [cell setTextColor:fontColor];
6516         [cell setFont:txtFont];
6517         
6518     }
6519 }
6520
6521 /* We use this to edit the name field in the outline view */
6522 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6523 {
6524     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6525     {
6526         id theRecord;
6527         
6528         theRecord = item;
6529         [theRecord setObject:object forKey:@"PresetName"];
6530         
6531         [self sortPresets];
6532         
6533         [fPresetsOutlineView reloadData];
6534         /* We save all of the preset data here */
6535         [self savePreset];
6536     }
6537 }
6538 /* We use this to provide tooltips for the items in the presets outline view */
6539 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6540 {
6541     //if ([[tc identifier] isEqualToString:@"PresetName"])
6542     //{
6543         /* initialize the tooltip contents variable */
6544         NSString *loc_tip;
6545         /* if there is a description for the preset, we show it in the tooltip */
6546         if ([item objectForKey:@"PresetDescription"])
6547         {
6548             loc_tip = [item objectForKey:@"PresetDescription"];
6549             return (loc_tip);
6550         }
6551         else
6552         {
6553             loc_tip = @"No description available";
6554         }
6555         return (loc_tip);
6556     //}
6557 }
6558
6559 #pragma mark -
6560 #pragma mark Preset Outline View Methods (dragging related)
6561
6562
6563 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6564 {
6565         // Dragging is only allowed for custom presets.
6566     //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6567         if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6568     {
6569         return NO;
6570     }
6571     // Don't retain since this is just holding temporaral drag information, and it is
6572     //only used during a drag!  We could put this in the pboard actually.
6573     fDraggedNodes = items;
6574     // Provide data for our custom type, and simple NSStrings.
6575     [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6576     
6577     // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6578     [pboard setData:[NSData data] forType:DragDropSimplePboardType]; 
6579     
6580     return YES;
6581 }
6582
6583 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6584 {
6585         
6586         // Don't allow dropping ONTO an item since they can't really contain any children.
6587     
6588     BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6589     if (isOnDropTypeProposal)
6590         return NSDragOperationNone;
6591     
6592     // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6593         if (item != nil)
6594         {
6595                 index = [fPresetsOutlineView rowForItem: item] + 1;
6596                 item = nil;
6597         }
6598     
6599     // Don't allow dropping into the Built In Presets.
6600     if (index < presetCurrentBuiltInCount)
6601     {
6602         return NSDragOperationNone;
6603         index = MAX (index, presetCurrentBuiltInCount);
6604         }    
6605         
6606     [outlineView setDropItem:item dropChildIndex:index];
6607     return NSDragOperationGeneric;
6608 }
6609
6610
6611
6612 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6613 {
6614     /* first, lets see if we are dropping into a folder */
6615     if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6616         {
6617     NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6618     childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6619     [childrenArray addObject:item];
6620     [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6621     [childrenArray autorelease];
6622     }
6623     else // We are not, so we just move the preset into the existing array 
6624     {
6625         NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6626         id obj;
6627         NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6628         while (obj = [enumerator nextObject])
6629         {
6630             [moveItems addIndex:[UserPresets indexOfObject:obj]];
6631         }
6632         // Successful drop, lets rearrange the view and save it all
6633         [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6634     }
6635     [fPresetsOutlineView reloadData];
6636     [self savePreset];
6637     return YES;
6638 }
6639
6640 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6641 {
6642     NSUInteger index = [indexSet lastIndex];
6643     NSUInteger aboveInsertIndexCount = 0;
6644     
6645     NSUInteger removeIndex;
6646
6647     if (index >= insertIndex)
6648     {
6649         removeIndex = index + aboveInsertIndexCount;
6650         aboveInsertIndexCount++;
6651     }
6652     else
6653     {
6654         removeIndex = index;
6655         insertIndex--;
6656     }
6657
6658     id object = [[array objectAtIndex:removeIndex] retain];
6659     [array removeObjectAtIndex:removeIndex];
6660     [array insertObject:object atIndex:insertIndex];
6661     [object release];
6662
6663     index = [indexSet indexLessThanIndex:index];
6664 }
6665
6666
6667
6668 #pragma mark - Functional Preset NSOutlineView Methods
6669
6670 - (IBAction)selectPreset:(id)sender
6671 {
6672     
6673     if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6674     {
6675         chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6676         [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6677         
6678         if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6679         {
6680             [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6681         }
6682         else
6683         {
6684             [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6685         }
6686         
6687         /* File Format */
6688         [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6689         [self formatPopUpChanged:nil];
6690         
6691         /* Chapter Markers*/
6692         [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6693         /* check to see if we have only one chapter */
6694         [self chapterPopUpChanged:nil];
6695         
6696         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6697         [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6698         /* Mux mp4 with http optimization */
6699         [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6700         
6701         /* Video encoder */
6702         [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6703         /* We set the advanced opt string here if applicable*/
6704         [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6705         
6706         /* Lets run through the following functions to get variables set there */
6707         [self videoEncoderPopUpChanged:nil];
6708         /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6709         [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6710         [self calculateBitrate:nil];
6711         
6712         /* Video quality */
6713         [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6714         
6715         [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6716         [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6717         
6718         /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6719          * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6720          * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6721          * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6722          * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6723         if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6724         {
6725             /* For the quality slider we need to convert the old percent's to the new rf scales */
6726             float rf =  (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6727             [fVidQualitySlider setFloatValue:rf];
6728             
6729         }
6730         else
6731         {
6732             /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6733             if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6734             {
6735                 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6736             }
6737             else
6738             {
6739                 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6740                 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6741             }
6742         }
6743         
6744         [self videoMatrixChanged:nil];
6745         
6746         /* Video framerate */
6747         /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6748          detected framerate in the fVidRatePopUp so we use index 0*/
6749         if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6750         {
6751             [fVidRatePopUp selectItemAtIndex: 0];
6752         }
6753         else
6754         {
6755             [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6756         }
6757         
6758         
6759         /* 2 Pass Encoding */
6760         [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6761         [self twoPassCheckboxChanged:nil];
6762         
6763         /* Turbo 1st pass for 2 Pass Encoding */
6764         [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6765         
6766         /*Audio*/
6767         /* First we check to see if we are using the current audio track layout based on AudioList array */
6768         if ([chosenPreset objectForKey:@"AudioList"])
6769         {
6770             
6771             /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6772             NSPopUpButton * trackLangPopUp = nil;
6773             NSPopUpButton * mixdownPopUp = nil;
6774             NSPopUpButton * audiocodecPopUp = nil;
6775             NSPopUpButton * sampleratePopUp = nil;
6776             NSPopUpButton * bitratePopUp = nil;
6777             NSSlider      * drcSlider = nil;
6778             
6779             
6780             /* Populate the audio widgets based on the contents of the AudioList array */
6781             int i = 0;
6782             NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6783             id tempObject;
6784             while (tempObject = [enumerator nextObject])
6785             {
6786                 i++;
6787                 if( i == 1 )
6788                 {
6789                     trackLangPopUp = fAudLang1PopUp;
6790                     mixdownPopUp = fAudTrack1MixPopUp;
6791                     audiocodecPopUp = fAudTrack1CodecPopUp;
6792                     sampleratePopUp = fAudTrack1RatePopUp;
6793                     bitratePopUp = fAudTrack1BitratePopUp;
6794                     drcSlider = fAudTrack1DrcSlider;
6795                 }
6796                 if( i == 2 )
6797                 {
6798                     trackLangPopUp = fAudLang2PopUp;
6799                     mixdownPopUp = fAudTrack2MixPopUp;
6800                     audiocodecPopUp = fAudTrack2CodecPopUp;
6801                     sampleratePopUp = fAudTrack2RatePopUp;
6802                     bitratePopUp = fAudTrack2BitratePopUp;
6803                     drcSlider = fAudTrack2DrcSlider;
6804                 }
6805                 if( i == 3 )
6806                 {
6807                     trackLangPopUp = fAudLang3PopUp;
6808                     mixdownPopUp = fAudTrack3MixPopUp;
6809                     audiocodecPopUp = fAudTrack3CodecPopUp;
6810                     sampleratePopUp = fAudTrack3RatePopUp;
6811                     bitratePopUp = fAudTrack3BitratePopUp;
6812                     drcSlider = fAudTrack3DrcSlider;
6813                 }
6814                 if( i == 4 )
6815                 {
6816                     trackLangPopUp = fAudLang4PopUp;
6817                     mixdownPopUp = fAudTrack4MixPopUp;
6818                     audiocodecPopUp = fAudTrack4CodecPopUp;
6819                     sampleratePopUp = fAudTrack4RatePopUp;
6820                     bitratePopUp = fAudTrack4BitratePopUp;
6821                     drcSlider = fAudTrack4DrcSlider;
6822                 }
6823                 
6824                 
6825                 if ([trackLangPopUp indexOfSelectedItem] == 0)
6826                 {
6827                     [trackLangPopUp selectItemAtIndex: 1];
6828                 }
6829                 [self audioTrackPopUpChanged: trackLangPopUp];
6830                 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6831                 /* check our pref for core audio and use it in place of faac if applicable */
6832                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6833                     [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6834                 {
6835                     [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6836                 }                    
6837                 
6838                 [self audioTrackPopUpChanged: audiocodecPopUp];
6839                 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6840                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6841                  * mixdown*/
6842                 if  ([mixdownPopUp selectedItem] == nil)
6843                 {
6844                     [self audioTrackPopUpChanged: audiocodecPopUp];
6845                 }
6846                 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6847                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6848                 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6849                 {
6850                     [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6851                 }
6852                 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6853                 [self audioDRCSliderChanged: drcSlider];
6854                 
6855                 
6856                 /* 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,
6857                  * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6858                 
6859                 if( i > 1 )
6860                 {
6861                     /* 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". */
6862                     if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])  && [trackLangPopUp indexOfSelectedItem] != 0)
6863                     {
6864                         hb_audio_config_t * audio;
6865                         /* get the audio source audio codec */
6866                         audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6867                         if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6868                             [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6869                         {
6870                             /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6871                             if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6872                             {
6873                                 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6874                             }
6875                             if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6876                             {
6877                                 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6878                             }
6879                             [self writeToActivityLog: "No matching source codec, setting track  %d to None", i];
6880                             [trackLangPopUp selectItemAtIndex: 0];
6881                             [self audioTrackPopUpChanged: trackLangPopUp]; 
6882                         }   
6883                     }
6884                 }
6885             }
6886             
6887             /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6888             
6889             if (i < 4)
6890             {
6891                 [fAudLang4PopUp selectItemAtIndex: 0];
6892                 [self audioTrackPopUpChanged: fAudLang4PopUp];
6893                 
6894                 if (i < 3)
6895                 {
6896                     [fAudLang3PopUp selectItemAtIndex: 0];
6897                     [self audioTrackPopUpChanged: fAudLang3PopUp];
6898                     
6899                     if (i < 2)
6900                     {
6901                         [fAudLang2PopUp selectItemAtIndex: 0];
6902                         [self audioTrackPopUpChanged: fAudLang2PopUp];
6903                     }
6904                 }
6905             }
6906             
6907         }
6908         else
6909         {
6910             if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6911             {
6912                 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6913                 {
6914                     [fAudLang1PopUp selectItemAtIndex: 1];
6915                 }
6916                 [self audioTrackPopUpChanged: fAudLang1PopUp];
6917                 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6918                 /* check our pref for core audio and use it in place of faac if applicable */
6919                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6920                     [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6921                 {
6922                     [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6923                 }
6924                 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6925                 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6926                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6927                  * mixdown*/
6928                 if  ([fAudTrack1MixPopUp selectedItem] == nil)
6929                 {
6930                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6931                 }
6932                 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6933                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6934                 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6935                 {
6936                     [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6937                 }
6938                 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6939                 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6940             }
6941             
6942             if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6943             {
6944                 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6945                 {
6946                     [fAudLang2PopUp selectItemAtIndex: 1];
6947                 }
6948                 [self audioTrackPopUpChanged: fAudLang2PopUp];
6949                 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6950                 /* check our pref for core audio and use it in place of faac if applicable */
6951                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6952                     [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6953                 {
6954                     [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6955                 }
6956                 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6957                 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6958                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6959                  * mixdown*/
6960                 if  ([fAudTrack2MixPopUp selectedItem] == nil)
6961                 {
6962                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6963                 }
6964                 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6965                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6966                 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6967                 {
6968                     [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6969                 }
6970                 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6971                 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6972             }
6973             if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6974             {
6975                 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6976                 {
6977                     [fAudLang3PopUp selectItemAtIndex: 1];
6978                 }
6979                 [self audioTrackPopUpChanged: fAudLang3PopUp];
6980                 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6981                 /* check our pref for core audio and use it in place of faac if applicable */
6982                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
6983                     [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6984                 {
6985                     [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6986                 }
6987                 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6988                 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6989                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6990                  * mixdown*/
6991                 if  ([fAudTrack3MixPopUp selectedItem] == nil)
6992                 {
6993                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6994                 }
6995                 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6996                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6997                 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6998                 {
6999                     [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
7000                 }
7001                 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
7002                 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
7003             }
7004             if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
7005             {
7006                 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
7007                 {
7008                     [fAudLang4PopUp selectItemAtIndex: 1];
7009                 }
7010                 [self audioTrackPopUpChanged: fAudLang4PopUp];
7011                 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
7012                 /* check our pref for core audio and use it in place of faac if applicable */
7013                 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES && 
7014                     [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
7015                 {
7016                     [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
7017                 }
7018                 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7019                 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
7020                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7021                  * mixdown*/
7022                 if  ([fAudTrack4MixPopUp selectedItem] == nil)
7023                 {
7024                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7025                 }
7026                 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7027                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7028                 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7029                 {
7030                     [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7031                 }
7032                 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7033                 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7034             }
7035             
7036             /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7037             
7038             if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7039             {
7040                 [fAudLang2PopUp selectItemAtIndex: 0];
7041                 [self audioTrackPopUpChanged: fAudLang2PopUp];
7042             }
7043             if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7044             {
7045                 [fAudLang3PopUp selectItemAtIndex: 0];
7046                 [self audioTrackPopUpChanged: fAudLang3PopUp];
7047             }
7048             if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7049             {
7050                 [fAudLang4PopUp selectItemAtIndex: 0];
7051                 [self audioTrackPopUpChanged: fAudLang4PopUp];
7052             }
7053         }
7054         
7055         /*Subtitles*/
7056         [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7057         /* Forced Subtitles */
7058         [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7059         
7060         /* Picture Settings */
7061         /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7062          * height, width, keep ar, anamorphic and crop settings.
7063          * picture filters are handled separately below.
7064          */
7065         /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None" 
7066          * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the 
7067          * preset completely ignores any picture sizing values in the preset.
7068          */
7069         if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] > 0)
7070         {
7071             hb_job_t * job = fTitle->job;
7072             
7073             /* If Cropping is set to custom, then recall all four crop values from
7074              when the preset was created and apply them */
7075             if ([[chosenPreset objectForKey:@"PictureAutoCrop"]  intValue] == 0)
7076             {
7077                 [fPictureController setAutoCrop:NO];
7078                 
7079                 /* Here we use the custom crop values saved at the time the preset was saved */
7080                 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"]  intValue];
7081                 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"]  intValue];
7082                 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"]  intValue];
7083                 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"]  intValue];
7084                 
7085             }
7086             else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7087             {
7088                 [fPictureController setAutoCrop:YES];
7089                 /* Here we use the auto crop values determined right after scan */
7090                 job->crop[0] = AutoCropTop;
7091                 job->crop[1] = AutoCropBottom;
7092                 job->crop[2] = AutoCropLeft;
7093                 job->crop[3] = AutoCropRight;
7094                 
7095             }
7096             
7097             
7098             /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7099             if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"]  intValue] == 1)
7100             {
7101                 /* Use Max Picture settings for whatever the dvd is.*/
7102                 [self revertPictureSizeToMax:nil];
7103                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
7104                 if (job->keep_ratio == 1)
7105                 {
7106                     hb_fix_aspect( job, HB_KEEP_WIDTH );
7107                     if( job->height > fTitle->height )
7108                     {
7109                         job->height = fTitle->height;
7110                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
7111                     }
7112                 }
7113                 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
7114             }
7115             else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7116             {
7117                 /* we check to make sure the presets width/height does not exceed the sources width/height */
7118                 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"]  intValue])
7119                 {
7120                     /* if so, then we use the sources height and width to avoid scaling up */
7121                     //job->width = fTitle->width;
7122                     //job->height = fTitle->height;
7123                     [self revertPictureSizeToMax:nil];
7124                 }
7125                 else // source width/height is >= the preset height/width
7126                 {
7127                     /* we can go ahead and use the presets values for height and width */
7128                     job->width = [[chosenPreset objectForKey:@"PictureWidth"]  intValue];
7129                     job->height = [[chosenPreset objectForKey:@"PictureHeight"]  intValue];
7130                 }
7131                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
7132                 if (job->keep_ratio == 1)
7133                 {
7134                     hb_fix_aspect( job, HB_KEEP_WIDTH );
7135                     if( job->height > fTitle->height )
7136                     {
7137                         job->height = fTitle->height;
7138                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
7139                     }
7140                 }
7141                 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
7142                 
7143             }
7144             
7145             
7146         }
7147         /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7148         if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"]  intValue] > 0)
7149         {
7150             /* Filters */
7151             
7152             /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7153              * also, older presets may not have this key, in which case we also check to see if that preset had  PictureDecomb
7154              * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7155              * sane.
7156              */
7157             [fPictureController setUseDecomb:1];
7158             [fPictureController setDecomb:0];
7159             [fPictureController setDeinterlace:0];
7160             if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7161             {
7162                 /* we are using decomb */
7163                 /* Decomb */
7164                 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7165                 {
7166                     [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7167                     
7168                     /* if we are using "Custom" in the decomb setting, also set the custom string*/
7169                     if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7170                     {
7171                         [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];    
7172                     }
7173                 }
7174              }
7175             else
7176             {
7177                 /* We are using Deinterlace */
7178                 /* Deinterlace */
7179                 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7180                 {
7181                     [fPictureController setUseDecomb:0];
7182                     [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7183                     /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7184                     if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7185                     {
7186                         [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];    
7187                     }
7188                 }
7189             }
7190             
7191             
7192             /* Detelecine */
7193             if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7194             {
7195                 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7196                 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7197                 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7198                 {
7199                     [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];    
7200                 }
7201             }
7202             else
7203             {
7204                 [fPictureController setDetelecine:0];
7205             }
7206             
7207             /* Denoise */
7208             if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7209             {
7210                 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7211                 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7212                 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7213                 {
7214                     [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];    
7215                 }
7216             }
7217             else
7218             {
7219                 [fPictureController setDenoise:0];
7220             }   
7221             
7222             /* Deblock */
7223             if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7224             {
7225                 /* if its a one, then its the old on/off deblock, set on to 5*/
7226                 [fPictureController setDeblock:5];
7227             }
7228             else
7229             {
7230                 /* use the settings intValue */
7231                 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7232             }
7233             
7234             if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7235             {
7236                 [fPictureController setGrayscale:1];
7237             }
7238             else
7239             {
7240                 [fPictureController setGrayscale:0];
7241             }
7242         }
7243         /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7244         [fPictureController SetTitle:fTitle];
7245         [fPictureController SetTitle:fTitle];
7246         [self calculatePictureSizing:nil];
7247     }
7248 }
7249
7250
7251 #pragma mark -
7252 #pragma mark Manage Presets
7253
7254 - (void) loadPresets {
7255         /* We declare the default NSFileManager into fileManager */
7256         NSFileManager * fileManager = [NSFileManager defaultManager];
7257         /*We define the location of the user presets file */
7258     UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7259         UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7260     /* We check for the presets.plist */
7261         if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7262         {
7263                 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7264         }
7265
7266         UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7267         if (nil == UserPresets)
7268         {
7269                 UserPresets = [[NSMutableArray alloc] init];
7270                 [self addFactoryPresets:nil];
7271         }
7272         [fPresetsOutlineView reloadData];
7273     
7274     [self checkBuiltInsForUpdates];
7275 }
7276
7277 - (void) checkBuiltInsForUpdates {
7278     
7279         BOOL updateBuiltInPresets = NO;
7280     int i = 0;
7281     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7282     id tempObject;
7283     while (tempObject = [enumerator nextObject])
7284     {
7285         /* iterate through the built in presets to see if any have an old build number */
7286         NSMutableDictionary *thisPresetDict = tempObject;
7287         /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7288         if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)              
7289         {
7290                         if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7291             {
7292                 updateBuiltInPresets = YES;
7293             }   
7294                 }
7295         i++;
7296     }
7297     /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7298     if ( updateBuiltInPresets == YES)
7299     {
7300         if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7301         {
7302             /* Show an alert window that built in presets will be updated */
7303             /*On Screen Notification*/
7304             int status;
7305             NSBeep();
7306             status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7307             [NSApp requestUserAttention:NSCriticalRequest];
7308         }
7309         /* when alert is dismissed, go ahead and update the built in presets */
7310         [self addFactoryPresets:nil];
7311     }
7312     
7313 }
7314
7315
7316 - (IBAction) showAddPresetPanel: (id) sender
7317 {
7318     /* Deselect the currently selected Preset if there is one*/
7319     [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7320
7321     /* Populate the preset picture settings popup here */
7322     [fPresetNewPicSettingsPopUp removeAllItems];
7323     [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7324     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7325     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7326     [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];  
7327     /* Uncheck the preset use filters checkbox */
7328     [fPresetNewPicFiltersCheck setState:NSOffState];
7329     // fPresetNewFolderCheck
7330     [fPresetNewFolderCheck setState:NSOffState];
7331     /* Erase info from the input fields*/
7332         [fPresetNewName setStringValue: @""];
7333         [fPresetNewDesc setStringValue: @""];
7334         /* Show the panel */
7335         [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7336 }
7337
7338 - (IBAction) closeAddPresetPanel: (id) sender
7339 {
7340     [NSApp endSheet: fAddPresetPanel];
7341     [fAddPresetPanel orderOut: self];
7342 }
7343
7344 - (IBAction)addUserPreset:(id)sender
7345 {
7346     if (![[fPresetNewName stringValue] length])
7347             NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7348     else
7349     {
7350         /* Here we create a custom user preset */
7351         [UserPresets addObject:[self createPreset]];
7352         [self addPreset];
7353
7354         [self closeAddPresetPanel:nil];
7355     }
7356 }
7357 - (void)addPreset
7358 {
7359
7360         
7361         /* We Reload the New Table data for presets */
7362     [fPresetsOutlineView reloadData];
7363    /* We save all of the preset data here */
7364     [self savePreset];
7365 }
7366
7367 - (void)sortPresets
7368 {
7369
7370         
7371         /* We Sort the Presets By Factory or Custom */
7372         NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type" 
7373                                                     ascending:YES] autorelease];
7374         /* We Sort the Presets Alphabetically by name  We do not use this now as we have drag and drop*/
7375         /*
7376     NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName" 
7377                                                     ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7378         //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7379     
7380     */
7381     /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7382     NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7383         NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7384         [UserPresets setArray:sortedArray];
7385         
7386
7387 }
7388
7389 - (IBAction)insertPreset:(id)sender
7390 {
7391     int index = [fPresetsOutlineView selectedRow];
7392     [UserPresets insertObject:[self createPreset] atIndex:index];
7393     [fPresetsOutlineView reloadData];
7394     [self savePreset];
7395 }
7396
7397 - (NSDictionary *)createPreset
7398 {
7399     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7400     /* Preset build number */
7401     [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7402     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7403         /* Get the New Preset Name from the field in the AddPresetPanel */
7404     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7405     /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7406     [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7407         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7408         [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7409         /*Set whether or not this is default, at creation set to 0*/
7410         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7411     if ([fPresetNewFolderCheck state] == YES)
7412     {
7413         /* initialize and set an empty array for children here since we are a new folder */
7414         NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7415         [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7416         [childrenArray autorelease];
7417     }
7418     else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7419     {
7420         /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7421         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7422         /* Get whether or not to use the current Picture Filter settings for the preset */
7423         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7424         
7425         /* Get New Preset Description from the field in the AddPresetPanel*/
7426         [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7427         /* File Format */
7428         [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7429         /* Chapter Markers fCreateChapterMarkers*/
7430         [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7431         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7432         [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7433         /* Mux mp4 with http optimization */
7434         [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7435         /* Add iPod uuid atom */
7436         [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7437         
7438         /* Codecs */
7439         /* Video encoder */
7440         [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7441         /* x264 Option String */
7442         [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7443         
7444         [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7445         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7446         [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7447         [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7448         
7449         /* Video framerate */
7450         if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7451         {
7452             [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7453         }
7454         else // we can record the actual titleOfSelectedItem
7455         {
7456             [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7457         }
7458         
7459         /* 2 Pass Encoding */
7460         [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7461         /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7462         [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7463         /*Picture Settings*/
7464         hb_job_t * job = fTitle->job;
7465         /* Picture Sizing */
7466         /* Use Max Picture settings for whatever the dvd is.*/
7467         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7468         [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7469         [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7470         [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7471         [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7472         
7473         /* Set crop settings here */
7474         [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7475         [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7476         [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7477         [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7478         [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7479         
7480         /* Picture Filters */
7481         [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7482         [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7483         [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7484         [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7485         [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7486         [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7487         [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7488         [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"]; 
7489         [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7490         [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7491         [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7492         
7493         /*Audio*/
7494         NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7495         /* we actually call the methods for the nests here */
7496         if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7497         {
7498             NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7499             [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7500             [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7501             [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7502             [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7503             [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7504             [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7505             [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7506             [audioTrack1Array autorelease];
7507             [audioListArray addObject:audioTrack1Array];
7508         }
7509         
7510         if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7511         {
7512             NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7513             [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7514             [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7515             [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7516             [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7517             [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7518             [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7519             [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7520             [audioTrack2Array autorelease];
7521             [audioListArray addObject:audioTrack2Array];
7522         }
7523         
7524         if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7525         {
7526             NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7527             [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7528             [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7529             [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7530             [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7531             [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7532             [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7533             [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7534             [audioTrack3Array autorelease];
7535             [audioListArray addObject:audioTrack3Array];
7536         }
7537         
7538         if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7539         {
7540             NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7541             [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7542             [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7543             [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7544             [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7545             [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7546             [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7547             [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7548             [audioTrack4Array autorelease];
7549             [audioListArray addObject:audioTrack4Array];
7550         }
7551         
7552         
7553         [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7554
7555         
7556         /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7557          * subititle array code. */
7558         /* Subtitles*/
7559         //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7560         /* Forced Subtitles */
7561         //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7562     }
7563     [preset autorelease];
7564     return preset;
7565     
7566 }
7567
7568 - (void)savePreset
7569 {
7570     [UserPresets writeToFile:UserPresetsFile atomically:YES];
7571         /* We get the default preset in case it changed */
7572         [self getDefaultPresets:nil];
7573
7574 }
7575
7576 - (IBAction)deletePreset:(id)sender
7577 {
7578     
7579     
7580     if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7581     {
7582         return;
7583     }
7584     /* Alert user before deleting preset */
7585         int status;
7586     status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7587     
7588     if ( status == NSAlertDefaultReturn ) 
7589     {
7590         int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7591         NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7592         NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7593         
7594         NSEnumerator *enumerator;
7595         NSMutableArray *presetsArrayToMod;
7596         NSMutableArray *tempArray;
7597         id tempObject;
7598         /* If we are a root level preset, we are modding the UserPresets array */
7599         if (presetToModLevel == 0)
7600         {
7601             presetsArrayToMod = UserPresets;
7602         }
7603         else // We have a parent preset, so we modify the chidren array object for key
7604         {
7605             presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"]; 
7606         }
7607         
7608         enumerator = [presetsArrayToMod objectEnumerator];
7609         tempArray = [NSMutableArray array];
7610         
7611         while (tempObject = [enumerator nextObject]) 
7612         {
7613             NSDictionary *thisPresetDict = tempObject;
7614             if (thisPresetDict == presetToMod)
7615             {
7616                 [tempArray addObject:tempObject];
7617             }
7618         }
7619         
7620         [presetsArrayToMod removeObjectsInArray:tempArray];
7621         [fPresetsOutlineView reloadData];
7622         [self savePreset];   
7623     }
7624 }
7625
7626
7627 #pragma mark -
7628 #pragma mark Import Export Preset(s)
7629
7630 - (IBAction) browseExportPresetFile: (id) sender
7631 {
7632     /* Open a panel to let the user choose where and how to save the export file */
7633     NSSavePanel * panel = [NSSavePanel savePanel];
7634         /* We get the current file name and path from the destination field here */
7635     NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7636
7637         [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7638                                    modalForWindow: fWindow modalDelegate: self
7639                                    didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7640                                           contextInfo: NULL];
7641 }
7642
7643 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7644                    returnCode: (int) returnCode contextInfo: (void *) contextInfo
7645 {
7646     if( returnCode == NSOKButton )
7647     {
7648         NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7649         NSString *exportPresetsFile = [sheet filename];
7650         [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7651         /* We check for the presets.plist */
7652         if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7653         {
7654             [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7655         }
7656         NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7657         if (nil == presetsToExport)
7658         {
7659             presetsToExport = [[NSMutableArray alloc] init];
7660             
7661             /* now get and add selected presets to export */
7662             
7663         }
7664         if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7665         {
7666             [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7667             [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7668             
7669         }
7670         
7671     }
7672 }
7673
7674
7675 - (IBAction) browseImportPresetFile: (id) sender
7676 {
7677
7678     NSOpenPanel * panel;
7679         
7680     panel = [NSOpenPanel openPanel];
7681     [panel setAllowsMultipleSelection: NO];
7682     [panel setCanChooseFiles: YES];
7683     [panel setCanChooseDirectories: NO ];
7684     NSString * sourceDirectory;
7685         if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7686         {
7687                 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7688         }
7689         else
7690         {
7691                 sourceDirectory = @"~/Desktop";
7692                 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7693         }
7694     /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7695         * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7696         */
7697     /* set this for allowed file types, not sure if we should allow xml or not */
7698     NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7699     [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7700                    modalForWindow: fWindow modalDelegate: self
7701                    didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7702                       contextInfo: sender];
7703 }
7704
7705 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7706                      returnCode: (int) returnCode contextInfo: (void *) contextInfo
7707 {
7708     if( returnCode == NSOKButton )
7709     {
7710         NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7711         NSString *importPresetsFile = [sheet filename];
7712         [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7713         /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file   */
7714         NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7715         /* iterate though the new array of presets to import and add them to our presets array */
7716         int i = 0;
7717         NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7718         id tempObject;
7719         while (tempObject = [enumerator nextObject])
7720         {
7721             /* make any changes to the incoming preset we see fit */
7722             /* make sure the incoming preset is not tagged as default */
7723             [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7724             /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7725             NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7726             [tempObject setObject:prependedName forKey:@"PresetName"];
7727             
7728             /* actually add the new preset to our presets array */
7729             [UserPresets addObject:tempObject];
7730             i++;
7731         }
7732         [presetsToImport autorelease];
7733         [self sortPresets];
7734         [self addPreset];
7735         
7736     }
7737 }
7738
7739 #pragma mark -
7740 #pragma mark Manage Default Preset
7741
7742 - (IBAction)getDefaultPresets:(id)sender
7743 {
7744         presetHbDefault = nil;
7745     presetUserDefault = nil;
7746     presetUserDefaultParent = nil;
7747     presetUserDefaultParentParent = nil;
7748     NSMutableDictionary *presetHbDefaultParent = nil;
7749     NSMutableDictionary *presetHbDefaultParentParent = nil;
7750     
7751     int i = 0;
7752     BOOL userDefaultFound = NO;
7753     presetCurrentBuiltInCount = 0;
7754     /* First we iterate through the root UserPresets array to check for defaults */
7755     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7756         id tempObject;
7757         while (tempObject = [enumerator nextObject])
7758         {
7759                 NSMutableDictionary *thisPresetDict = tempObject;
7760                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7761                 {
7762                         presetHbDefault = thisPresetDict;       
7763                 }
7764                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7765                 {
7766                         presetUserDefault = thisPresetDict;
7767             userDefaultFound = YES;
7768         }
7769         if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset               
7770         {
7771                         presetCurrentBuiltInCount++; // <--increment the current number of built in presets     
7772                 }
7773                 i++;
7774         
7775         /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7776         if ([thisPresetDict objectForKey:@"ChildrenArray"])
7777         {
7778             NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7779             NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7780             id tempObject;
7781             while (tempObject = [enumerator nextObject])
7782             {
7783                 NSMutableDictionary *thisPresetDict = tempObject;
7784                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7785                 {
7786                     presetHbDefault = thisPresetDict;
7787                     presetHbDefaultParent = thisPresetDictParent;
7788                 }
7789                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7790                 {
7791                     presetUserDefault = thisPresetDict;
7792                     presetUserDefaultParent = thisPresetDictParent;
7793                     userDefaultFound = YES;
7794                 }
7795                 
7796                 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7797                 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7798                 {
7799                     NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7800                     NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7801                     id tempObject;
7802                     while (tempObject = [enumerator nextObject])
7803                     {
7804                         NSMutableDictionary *thisPresetDict = tempObject;
7805                         if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7806                         {
7807                             presetHbDefault = thisPresetDict;
7808                             presetHbDefaultParent = thisPresetDictParent;
7809                             presetHbDefaultParentParent = thisPresetDictParentParent;   
7810                         }
7811                         if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7812                         {
7813                             presetUserDefault = thisPresetDict;
7814                             presetUserDefaultParent = thisPresetDictParent;
7815                             presetUserDefaultParentParent = thisPresetDictParentParent;
7816                             userDefaultFound = YES;     
7817                         }
7818                         
7819                     }
7820                 }
7821             }
7822         }
7823         
7824         }
7825     /* check to see if a user specified preset was found, if not then assign the parents for
7826      * the presetHbDefault so that we can open the parents for the nested presets
7827      */
7828     if (userDefaultFound == NO)
7829     {
7830         presetUserDefaultParent = presetHbDefaultParent;
7831         presetUserDefaultParentParent = presetHbDefaultParentParent;
7832     }
7833 }
7834
7835 - (IBAction)setDefaultPreset:(id)sender
7836 {
7837 /* We need to determine if the item is a folder */
7838    if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7839    {
7840    return;
7841    }
7842
7843     int i = 0;
7844     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7845         id tempObject;
7846         /* First make sure the old user specified default preset is removed */
7847     while (tempObject = [enumerator nextObject])
7848         {
7849                 NSMutableDictionary *thisPresetDict = tempObject;
7850                 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7851                 {
7852                         [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"]; 
7853                 }
7854                 
7855                 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7856         if ([thisPresetDict objectForKey:@"ChildrenArray"])
7857         {
7858             NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7859             id tempObject;
7860             int ii = 0;
7861             while (tempObject = [enumerator nextObject])
7862             {
7863                 NSMutableDictionary *thisPresetDict1 = tempObject;
7864                 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7865                 {
7866                     [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"]; 
7867                 }
7868                 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7869                 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7870                 {
7871                     NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7872                     id tempObject;
7873                     int iii = 0;
7874                     while (tempObject = [enumerator nextObject])
7875                     {
7876                         if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7877                         {
7878                             [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];       
7879                         }
7880                         iii++;
7881                     }
7882                 }
7883                 ii++;
7884             }
7885             
7886         }
7887         i++; 
7888         }
7889     
7890     
7891     int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7892     NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7893     NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7894     
7895     
7896     NSMutableArray *presetsArrayToMod;
7897     NSMutableArray *tempArray;
7898     
7899     /* If we are a root level preset, we are modding the UserPresets array */
7900     if (presetToModLevel == 0)
7901     {
7902         presetsArrayToMod = UserPresets;
7903     }
7904     else // We have a parent preset, so we modify the chidren array object for key
7905     {
7906         presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"]; 
7907     }
7908     
7909     enumerator = [presetsArrayToMod objectEnumerator];
7910     tempArray = [NSMutableArray array];
7911     int iiii = 0;
7912     while (tempObject = [enumerator nextObject]) 
7913     {
7914         NSDictionary *thisPresetDict = tempObject;
7915         if (thisPresetDict == presetToMod)
7916         {
7917             if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7918             {
7919                 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];        
7920             }
7921         }
7922      iiii++;
7923      }
7924     
7925     
7926     /* We save all of the preset data here */
7927     [self savePreset];
7928     /* We Reload the New Table data for presets */
7929     [fPresetsOutlineView reloadData];
7930 }
7931
7932 - (IBAction)selectDefaultPreset:(id)sender
7933 {
7934         NSMutableDictionary *presetToMod;
7935     /* if there is a user specified default, we use it */
7936         if (presetUserDefault)
7937         {
7938         presetToMod = presetUserDefault;
7939     }
7940         else if (presetHbDefault) //else we use the built in default presetHbDefault
7941         {
7942         presetToMod = presetHbDefault;
7943         }
7944     else
7945     {
7946     return;
7947     }
7948     
7949     if (presetUserDefaultParent != nil)
7950     {
7951         [fPresetsOutlineView expandItem:presetUserDefaultParent];
7952         
7953     }
7954     if (presetUserDefaultParentParent != nil)
7955     {
7956         [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7957         
7958     }
7959     
7960     [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7961         [self selectPreset:nil];
7962 }
7963
7964
7965 #pragma mark -
7966 #pragma mark Manage Built In Presets
7967
7968
7969 - (IBAction)deleteFactoryPresets:(id)sender
7970 {
7971     //int status;
7972     NSEnumerator *enumerator = [UserPresets objectEnumerator];
7973         id tempObject;
7974     
7975         //NSNumber *index;
7976     NSMutableArray *tempArray;
7977
7978
7979         tempArray = [NSMutableArray array];
7980         /* we look here to see if the preset is we move on to the next one */
7981         while ( tempObject = [enumerator nextObject] )  
7982                 {
7983                         /* if the preset is "Factory" then we put it in the array of
7984                         presets to delete */
7985                         if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7986                         {
7987                                 [tempArray addObject:tempObject];
7988                         }
7989         }
7990         
7991         [UserPresets removeObjectsInArray:tempArray];
7992         [fPresetsOutlineView reloadData];
7993         [self savePreset];   
7994
7995 }
7996
7997    /* We use this method to recreate new, updated factory presets */
7998 - (IBAction)addFactoryPresets:(id)sender
7999 {
8000     
8001     /* First, we delete any existing built in presets */
8002     [self deleteFactoryPresets: sender];
8003     /* Then we generate new built in presets programmatically with fPresetsBuiltin
8004      * which is all setup in HBPresets.h and  HBPresets.m*/
8005     [fPresetsBuiltin generateBuiltinPresets:UserPresets];
8006     /* update build number for built in presets */
8007     /* iterate though the new array of presets to import and add them to our presets array */
8008     int i = 0;
8009     NSEnumerator *enumerator = [UserPresets objectEnumerator];
8010     id tempObject;
8011     while (tempObject = [enumerator nextObject])
8012     {
8013         /* Record the apps current build number in the PresetBuildNumber key */
8014         if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset           
8015         {
8016             /* Preset build number */
8017             [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8018         }
8019         i++;
8020     }
8021     /* report the built in preset updating to the activity log */
8022     [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8023     
8024     [self sortPresets];
8025     [self addPreset];
8026     
8027 }
8028
8029
8030 @end
8031
8032 /*******************************
8033  * Subclass of the HBPresetsOutlineView *
8034  *******************************/
8035
8036 @implementation HBPresetsOutlineView
8037 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8038 {
8039     fIsDragging = YES;
8040
8041     // By default, NSTableView only drags an image of the first column. Change this to
8042     // drag an image of the queue's icon and PresetName columns.
8043     NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8044     return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8045 }
8046
8047
8048
8049 - (void) mouseDown:(NSEvent *)theEvent
8050 {
8051     [super mouseDown:theEvent];
8052         fIsDragging = NO;
8053 }
8054
8055
8056
8057 - (BOOL) isDragging;
8058 {
8059     return fIsDragging;
8060 }
8061 @end
8062
8063
8064