OSDN Git Service

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