OSDN Git Service

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