OSDN Git Service

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