OSDN Git Service

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