OSDN Git Service

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