OSDN Git Service

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