OSDN Git Service

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