OSDN Git Service

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