OSDN Git Service

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