OSDN Git Service

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