OSDN Git Service

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