OSDN Git Service

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