OSDN Git Service

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