OSDN Git Service

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