OSDN Git Service

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