OSDN Git Service

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