OSDN Git Service

MacGui: Custom chapter names restored (borked in 1703)
[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    /* Find out if the item we are removing is a cancelled item*/
1540    if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3)
1541     {
1542     /* Since we are removing a cancelled item, WE need to decrement the currentQueueEncodeIndex
1543      * by one to keep in sync with the queue array
1544      */
1545     currentQueueEncodeIndex--;
1546     [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
1547     }
1548     [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1549     [self saveQueueFileItem];
1550
1551 }
1552
1553 - (void)saveQueueFileItem
1554 {
1555     [QueueFileArray writeToFile:QueueFile atomically:YES];
1556     [fQueueController setQueueArray: QueueFileArray];
1557     [self getQueueStats];
1558 }
1559
1560 - (void)getQueueStats
1561 {
1562 /* lets get the stats on the status of the queue array */
1563
1564 fEncodingQueueItem = 0;
1565 fPendingCount = 0;
1566 fCompletedCount = 0;
1567 fCanceledCount = 0;
1568 fWorkingCount = 0;
1569
1570     /* We use a number system to set the encode status of the queue item
1571      * in controller.mm
1572      * 0 == already encoded
1573      * 1 == is being encoded
1574      * 2 == is yet to be encoded
1575      * 3 == cancelled
1576      */
1577
1578         int i = 0;
1579     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1580         id tempObject;
1581         while (tempObject = [enumerator nextObject])
1582         {
1583                 NSDictionary *thisQueueDict = tempObject;
1584                 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1585                 {
1586                         fCompletedCount++;      
1587                 }
1588                 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1589                 {
1590                         fWorkingCount++;
1591             fEncodingQueueItem = i;     
1592                 }
1593         if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending          
1594         {
1595                         fPendingCount++;
1596                 }
1597         if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled                
1598         {
1599                         fCanceledCount++;
1600                 }
1601                 i++;
1602         }
1603
1604     /* Set the queue status field in the main window */
1605     NSMutableString * string;
1606     if (fPendingCount == 1)
1607     {
1608         string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
1609     }
1610     else
1611     {
1612         string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
1613     }
1614     [fQueueStatus setStringValue:string];
1615 }
1616
1617
1618 /* This method will clear the queue of any encodes that are not still pending
1619  * this includes both successfully completed encodes as well as cancelled encodes */
1620 - (void) clearQueueEncodedItems
1621 {
1622     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1623         id tempObject;
1624     NSMutableArray *tempArray;
1625     tempArray = [NSMutableArray array];
1626     /* we look here to see if the preset is we move on to the next one */
1627     while ( tempObject = [enumerator nextObject] )  
1628     {
1629         /* If the queue item is not still pending (finished successfully or it was cancelled
1630          * during the last session, then we put it in tempArray to be deleted from QueueFileArray*/
1631         if ([[tempObject objectForKey:@"Status"] intValue] != 2)
1632         {
1633             [tempArray addObject:tempObject];
1634         }
1635     }
1636     
1637     [QueueFileArray removeObjectsInArray:tempArray];
1638     [self saveQueueFileItem];
1639     
1640 }
1641
1642 /* This method will clear the queue of any encodes that are not still pending
1643  * this includes both successfully completed encodes as well as cancelled encodes */
1644 - (void) clearQueueAllItems
1645 {
1646     NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1647         id tempObject;
1648     NSMutableArray *tempArray;
1649     tempArray = [NSMutableArray array];
1650     /* we look here to see if the preset is we move on to the next one */
1651     while ( tempObject = [enumerator nextObject] )  
1652     {
1653         [tempArray addObject:tempObject];
1654     }
1655     
1656     [QueueFileArray removeObjectsInArray:tempArray];
1657     [self saveQueueFileItem];
1658     
1659 }
1660
1661 /* This method will duplicate prepareJob however into the
1662  * queue .plist instead of into the job structure so it can
1663  * be recalled later */
1664 - (NSDictionary *)createQueueFileItem
1665 {
1666     NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
1667     
1668        hb_list_t  * list  = hb_get_titles( fHandle );
1669     hb_title_t * title = (hb_title_t *) hb_list_item( list,
1670             [fSrcTitlePopUp indexOfSelectedItem] );
1671     hb_job_t * job = title->job;
1672     
1673     
1674     
1675     /* We use a number system to set the encode status of the queue item
1676      * 0 == already encoded
1677      * 1 == is being encoded
1678      * 2 == is yet to be encoded
1679      * 3 == cancelled
1680      */
1681     [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
1682     /* Source and Destination Information */
1683     
1684     [queueFileJob setObject:[NSString stringWithUTF8String: title->dvd] forKey:@"SourcePath"];
1685     [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
1686     [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
1687     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
1688     
1689     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
1690     
1691     [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
1692     
1693     /* Lets get the preset info if there is any */
1694     [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
1695     [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
1696     
1697     [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
1698         /* Chapter Markers fCreateChapterMarkers*/
1699         [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
1700         
1701     /* We need to get the list of chapter names to put into an array and store 
1702      * in our queue, so they can be reapplied in prepareJob when this queue
1703      * item comes up if Chapter Markers is set to on.
1704      */
1705      int i;
1706      NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
1707      int chaptercount = hb_list_count( fTitle->list_chapter );
1708      for( i = 0; i < chaptercount; i++ )
1709     {
1710         hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
1711         if( chapter != NULL )
1712         {
1713          [ChapterNamesArray addObject:[NSString stringWithFormat:@"%s",chapter->title]];
1714         }
1715     }
1716     [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
1717     [ChapterNamesArray autorelease];
1718     
1719     /* Allow Mpeg4 64 bit formatting +4GB file sizes */
1720         [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
1721     /* Mux mp4 with http optimization */
1722     [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
1723     /* Add iPod uuid atom */
1724     [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
1725     
1726     /* Codecs */
1727         /* Video encoder */
1728         [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
1729         /* x264 Option String */
1730         [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
1731
1732         [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
1733         [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
1734         [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
1735         [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
1736     /* Framerate */
1737     [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
1738     
1739     /* GrayScale */
1740         [queueFileJob setObject:[NSNumber numberWithInt:[fVidGrayscaleCheck state]] forKey:@"VideoGrayScale"];
1741         /* 2 Pass Encoding */
1742         [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
1743         /* Turbo 2 pass Encoding fVidTurboPassCheck*/
1744         [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
1745     
1746         /* Picture Sizing */
1747         /* Use Max Picture settings for whatever the dvd is.*/
1748         [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1749         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1750         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1751         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1752         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
1753     NSString * pictureSummary;
1754     pictureSummary = [NSString stringWithFormat:@"Source: %@ Output: %@ Anamorphic: %@", 
1755                      [fPicSettingsSrc stringValue], 
1756                      [fPicSettingsOutp stringValue], 
1757                      [fPicSettingsAnamorphic stringValue]];
1758     [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];                 
1759     /* Set crop settings here */
1760         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
1761     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
1762     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
1763         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
1764         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
1765     
1766     /* Picture Filters */
1767     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
1768         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
1769     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController vfr]] forKey:@"VFR"];
1770         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
1771     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"]; 
1772     [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
1773     
1774     /*Audio*/
1775     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
1776     {
1777         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
1778         [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
1779         [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
1780         [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
1781         [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
1782         [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
1783         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
1784     }
1785     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
1786     {
1787         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
1788         [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
1789         [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
1790         [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
1791         [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
1792         [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
1793         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
1794     }
1795     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
1796     {
1797         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
1798         [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
1799         [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
1800         [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
1801         [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
1802         [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
1803         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
1804     }
1805     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
1806     {
1807         [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
1808         [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
1809         [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
1810         [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
1811         [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
1812         [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
1813         [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
1814     }
1815     
1816         /* Subtitles*/
1817         [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
1818     [queueFileJob setObject:[NSNumber numberWithInt:[fSubPopUp indexOfSelectedItem]] forKey:@"JobSubtitlesIndex"];
1819     /* Forced Subtitles */
1820         [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
1821     
1822     
1823     
1824     /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
1825      
1826     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
1827     
1828     [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
1829     
1830     
1831     [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
1832         /* Chapter Markers fCreateChapterMarkers*/
1833         //[queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
1834         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
1835         //[queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
1836     /* Mux mp4 with http optimization */
1837     //[queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
1838     /* Add iPod uuid atom */
1839     //[queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
1840     
1841     /* Codecs */
1842         /* Video encoder */
1843         [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
1844         /* x264 Option String */
1845         //[queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
1846
1847         //[queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
1848         //[queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
1849         //[queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
1850         //[queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
1851     /* Framerate */
1852     [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
1853     [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
1854     [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
1855         /* Picture Sizing */
1856         /* Use Max Picture settings for whatever the dvd is.*/
1857         [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1858         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1859         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1860         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1861         [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
1862     
1863     /* Set crop settings here */
1864         [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
1865     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
1866     [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
1867         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
1868         [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
1869     
1870     /* Picture Filters */
1871     [queueFileJob setObject:[fPicSettingDecomb stringValue] forKey:@"JobPictureDecomb"];
1872     
1873     /*Audio*/
1874     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
1875     {
1876         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
1877         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
1878         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
1879         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
1880         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
1881      }
1882     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
1883     {
1884         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
1885         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
1886         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
1887         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
1888         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
1889     }
1890     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
1891     {
1892         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
1893         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
1894         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
1895         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
1896         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
1897     }
1898     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
1899     {
1900         //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
1901         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
1902         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
1903         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
1904         [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
1905     }
1906         /* Subtitles*/
1907         [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
1908     /* Forced Subtitles */
1909         [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
1910  
1911     /* we need to auto relase the queueFileJob and return it */
1912     [queueFileJob autorelease];
1913     return queueFileJob;
1914
1915 }
1916
1917 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
1918 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
1919 {
1920     unsigned index = [indexSet lastIndex];
1921     unsigned aboveInsertIndexCount = 0;
1922     
1923     while (index != NSNotFound)
1924     {
1925         unsigned removeIndex;
1926         
1927         if (index >= insertIndex)
1928         {
1929             removeIndex = index + aboveInsertIndexCount;
1930             aboveInsertIndexCount++;
1931         }
1932         else
1933         {
1934             removeIndex = index;
1935             insertIndex--;
1936         }
1937         
1938         id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
1939         [QueueFileArray removeObjectAtIndex:removeIndex];
1940         [QueueFileArray insertObject:object atIndex:insertIndex];
1941         [object release];
1942         
1943         index = [indexSet indexLessThanIndex:index];
1944     }
1945    /* We save all of the Queue data here 
1946     * and it also gets sent back to the queue controller*/
1947     [self saveQueueFileItem]; 
1948     
1949 }
1950
1951
1952 #pragma mark -
1953 #pragma mark Queue Job Processing
1954
1955 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
1956 {
1957     int i = currentQueueEncodeIndex;
1958     [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
1959         
1960     /* We save all of the Queue data here */
1961     [self saveQueueFileItem];
1962         /* We Reload the New Table data for presets */
1963     //[fPresetsOutlineView reloadData];
1964
1965     /* Since we have now marked a queue item as done
1966      * we can go ahead and increment currentQueueEncodeIndex 
1967      * so that if there is anything left in the queue we can
1968      * go ahead and move to the next item if we want to */
1969     currentQueueEncodeIndex++ ;
1970     [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
1971     int queueItems = [QueueFileArray count];
1972     /* If we still have more items in our queue, lets go to the next one */
1973     if (currentQueueEncodeIndex < queueItems)
1974     {
1975     [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
1976     [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
1977     }
1978     else
1979     {
1980         [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
1981     }
1982 }
1983
1984 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1985 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1986 {
1987    //NSRunAlertPanel(@"Hello!", @"We are now performing a new queue scan!", @"OK", nil, nil);
1988
1989      /* use a bool to determine whether or not we can decrypt using vlc */
1990     BOOL cancelScanDecrypt = 0;
1991     /* set the bool so that showNewScan knows to apply the appropriate queue
1992     * settings as this is a queue rescan
1993     */
1994     applyQueueToScan = YES;
1995     NSString *path = scanPath;
1996     HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1997
1998         /*On Screen Notification*/
1999         //int status;
2000         //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2001         //[NSApp requestUserAttention:NSCriticalRequest];
2002
2003     // Notify ChapterTitles that there's no title
2004     [fChapterTitlesDelegate resetWithTitle:nil];
2005     [fChapterTable reloadData];
2006
2007     //[self enableUI: NO];
2008
2009     if( [detector isVideoDVD] )
2010     {
2011         // The chosen path was actually on a DVD, so use the raw block
2012         // device path instead.
2013         path = [detector devicePath];
2014         [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2015
2016         /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2017         NSString *vlcPath = @"/Applications/VLC.app";
2018         NSFileManager * fileManager = [NSFileManager defaultManager];
2019             if ([fileManager fileExistsAtPath:vlcPath] == 0) 
2020             {
2021             /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2022             cancelScanDecrypt = 1;
2023             [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2024             int status;
2025             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");
2026             [NSApp requestUserAttention:NSCriticalRequest];
2027             
2028             if (status == NSAlertDefaultReturn)
2029             {
2030                 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2031                 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2032             }
2033             else if (status == NSAlertAlternateReturn)
2034             {
2035             /* User chose to cancel the scan */
2036             [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2037             }
2038             else
2039             {
2040             /* 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 */
2041             cancelScanDecrypt = 0;
2042             [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2043             }
2044
2045         }
2046         else
2047         {
2048             /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2049             [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2050         }
2051     }
2052
2053     if (cancelScanDecrypt == 0)
2054     {
2055         /* we actually pass the scan off to libhb here */
2056         /* If there is no title number passed to scan, we use "0"
2057          * which causes the default behavior of a full source scan
2058          */
2059         if (!scanTitleNum)
2060         {
2061             scanTitleNum = 0;
2062         }
2063         if (scanTitleNum > 0)
2064         {
2065             [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2066         }
2067         [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2068         hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum );
2069     }
2070 }
2071
2072 /* This method was originally used to load up a new queue item in the gui and
2073  * then start processing it. However we now have modified -prepareJob and use a second
2074  * instance of libhb to do our actual encoding, therefor right now it is not required. 
2075  * Nonetheless I want to leave this in here
2076  * because basically its everything we need to be able to actually modify a pending queue
2077  * item in the gui and resave it. At least for now - dynaflash
2078  */
2079
2080 - (IBAction)applyQueueSettings:(id)sender
2081 {
2082     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2083     hb_job_t * job = fTitle->job;
2084     
2085     /* Set title number and chapters */
2086     /* since the queue only scans a single title, we really don't need to pick a title */
2087     //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2088     
2089     [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2090     [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2091     
2092     /* File Format */
2093     [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2094     [self formatPopUpChanged:nil];
2095     
2096     /* Chapter Markers*/
2097     [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2098     /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2099     [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2100     /* Mux mp4 with http optimization */
2101     [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2102     
2103     /* Video encoder */
2104     /* We set the advanced opt string here if applicable*/
2105     [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2106     [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2107     
2108     /* Lets run through the following functions to get variables set there */
2109     [self videoEncoderPopUpChanged:nil];
2110     /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2111     [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2112     [self calculateBitrate:nil];
2113     
2114     /* Video quality */
2115     [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2116     
2117     [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2118     [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2119     [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2120     
2121     [self videoMatrixChanged:nil];
2122     
2123     /* Video framerate */
2124     /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2125      detected framerate in the fVidRatePopUp so we use index 0*/
2126     if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2127     {
2128         [fVidRatePopUp selectItemAtIndex: 0];
2129     }
2130     else
2131     {
2132         [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2133     }
2134     
2135     /* GrayScale */
2136     [fVidGrayscaleCheck setState:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2137     
2138     /* 2 Pass Encoding */
2139     [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2140     [self twoPassCheckboxChanged:nil];
2141     /* Turbo 1st pass for 2 Pass Encoding */
2142     [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2143     
2144     /*Audio*/
2145     if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2146     {
2147         if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2148         {
2149             [fAudLang1PopUp selectItemAtIndex: 1];
2150         }
2151         [self audioTrackPopUpChanged: fAudLang1PopUp];
2152         [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2153         [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2154         [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2155         /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2156          * mixdown*/
2157         if  ([fAudTrack1MixPopUp selectedItem] == nil)
2158         {
2159             [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2160         }
2161         [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2162         /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2163         if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2164         {
2165             [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2166         }
2167         [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2168         [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2169     }
2170     if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2171     {
2172         if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2173         {
2174             [fAudLang2PopUp selectItemAtIndex: 1];
2175         }
2176         [self audioTrackPopUpChanged: fAudLang2PopUp];
2177         [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2178         [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2179         [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2180         /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2181          * mixdown*/
2182         if  ([fAudTrack2MixPopUp selectedItem] == nil)
2183         {
2184             [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2185         }
2186         [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2187         /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2188         if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2189         {
2190             [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2191         }
2192         [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2193         [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2194     }
2195     if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2196     {
2197         if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2198         {
2199             [fAudLang3PopUp selectItemAtIndex: 1];
2200         }
2201         [self audioTrackPopUpChanged: fAudLang3PopUp];
2202         [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2203         [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2204         [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2205         /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2206          * mixdown*/
2207         if  ([fAudTrack3MixPopUp selectedItem] == nil)
2208         {
2209             [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2210         }
2211         [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2212         /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2213         if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2214         {
2215             [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2216         }
2217         [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2218         [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2219     }
2220     if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2221     {
2222         if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2223         {
2224             [fAudLang4PopUp selectItemAtIndex: 1];
2225         }
2226         [self audioTrackPopUpChanged: fAudLang4PopUp];
2227         [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2228         [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2229         [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2230         /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2231          * mixdown*/
2232         if  ([fAudTrack4MixPopUp selectedItem] == nil)
2233         {
2234             [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2235         }
2236         [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2237         /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2238         if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2239         {
2240             [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2241         }
2242         [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2243         [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2244     }
2245     
2246     
2247     /*Subtitles*/
2248     [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2249     /* Forced Subtitles */
2250     [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2251     
2252     /* Picture Settings */
2253     /* we check to make sure the presets width/height does not exceed the sources width/height */
2254     if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"]  intValue])
2255     {
2256         /* if so, then we use the sources height and width to avoid scaling up */
2257         job->width = fTitle->width;
2258         job->height = fTitle->height;
2259     }
2260     else // source width/height is >= the preset height/width
2261     {
2262         /* we can go ahead and use the presets values for height and width */
2263         job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
2264         job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
2265     }
2266     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
2267     if (job->keep_ratio == 1)
2268     {
2269         hb_fix_aspect( job, HB_KEEP_WIDTH );
2270         if( job->height > fTitle->height )
2271         {
2272             job->height = fTitle->height;
2273             hb_fix_aspect( job, HB_KEEP_HEIGHT );
2274         }
2275     }
2276     job->pixel_ratio = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
2277     
2278     
2279     /* If Cropping is set to custom, then recall all four crop values from
2280      when the preset was created and apply them */
2281     if ([[queueToApply objectForKey:@"PictureAutoCrop"]  intValue] == 0)
2282     {
2283         [fPictureController setAutoCrop:NO];
2284         
2285         /* Here we use the custom crop values saved at the time the preset was saved */
2286         job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
2287         job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
2288         job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
2289         job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
2290         
2291     }
2292     else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2293     {
2294         [fPictureController setAutoCrop:YES];
2295         /* Here we use the auto crop values determined right after scan */
2296         job->crop[0] = AutoCropTop;
2297         job->crop[1] = AutoCropBottom;
2298         job->crop[2] = AutoCropLeft;
2299         job->crop[3] = AutoCropRight;
2300         
2301     }
2302     
2303     /* Filters */
2304     /* Deinterlace */
2305     [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2306     /* VFR */
2307     [fPictureController setVFR:[[queueToApply objectForKey:@"VFR"] intValue]];
2308     /* Detelecine */
2309     [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2310     /* Denoise */
2311     [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2312     /* Deblock */
2313     [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2314     /* Decomb */
2315     [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2316     
2317     [self calculatePictureSizing:nil];
2318     
2319     
2320     /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2321     //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2322     //    [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2323     if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2324         {
2325                 /* Deselect the currently selected Preset if there is one*/
2326         //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2327         //[self selectPreset:nil];
2328                 
2329         //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2330                 /* Change UI to show "Custom" settings are being used */
2331                 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2332         
2333                 curUserPresetChosenNum = nil;
2334         }
2335     else
2336     {
2337         /* Deselect the currently selected Preset if there is one*/
2338                 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2339                 /* Change UI to show "Custom" settings are being used */
2340                 [fPresetSelectedDisplay setStringValue: @"Custom"];
2341         
2342                 //curUserPresetChosenNum = nil;
2343     }
2344     
2345     /* We need to set this bool back to NO, in case the user wants to do a scan */
2346     //applyQueueToScan = NO;
2347     
2348     /* so now we go ahead and process the new settings */
2349     [self processNewQueueEncode];
2350 }
2351
2352
2353
2354 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2355 - (void) processNewQueueEncode
2356 {
2357     hb_list_t  * list  = hb_get_titles( fQueueEncodeLibhb );
2358     hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2359     hb_job_t * job = title->job;
2360     
2361     if( !hb_list_count( list ) )
2362     {
2363         [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2364     }
2365     else
2366     {
2367         [self writeToActivityLog: "processNewQueueEncode title list is: %d", hb_list_count( list )];
2368     }
2369     
2370     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2371     [self writeToActivityLog: "processNewQueueEncode currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2372     [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2373     job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2374     [self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2375     [self prepareJob];
2376     [self writeToActivityLog: "processNewQueueEncode back from prepareJob"];
2377     if( [[queueToApply objectForKey:@"SubtitlesForced"] intValue] == 1 )
2378         job->subtitle_force = 1;
2379     else
2380         job->subtitle_force = 0;
2381     
2382     /*
2383      * subtitle of -1 is a scan
2384      */
2385     if( job->subtitle == -1 )
2386     {
2387         char *x264opts_tmp;
2388         
2389         /*
2390          * When subtitle scan is enabled do a fast pre-scan job
2391          * which will determine which subtitles to enable, if any.
2392          */
2393         job->pass = -1;
2394         x264opts_tmp = job->x264opts;
2395         job->subtitle = -1;
2396         
2397         job->x264opts = NULL;
2398         
2399         job->indepth_scan = 1;  
2400         
2401         job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
2402         *(job->select_subtitle) = NULL;
2403         
2404         /*
2405          * Add the pre-scan job
2406          */
2407         hb_add( fQueueEncodeLibhb, job );
2408         job->x264opts = x264opts_tmp;
2409     }
2410     else
2411         job->select_subtitle = NULL;
2412     
2413     /* No subtitle were selected, so reset the subtitle to -1 (which before
2414      * this point meant we were scanning
2415      */
2416     if( job->subtitle == -2 )
2417         job->subtitle = -1;
2418     
2419     if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2420     {
2421         hb_subtitle_t **subtitle_tmp = job->select_subtitle;
2422         job->indepth_scan = 0;
2423         
2424         /*
2425          * Do not autoselect subtitles on the first pass of a two pass
2426          */
2427         job->select_subtitle = NULL;
2428         
2429         job->pass = 1;
2430         
2431         hb_add( fQueueEncodeLibhb, job );
2432         
2433         job->pass = 2;
2434         
2435         job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */  
2436         strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2437         
2438         job->select_subtitle = subtitle_tmp;
2439         
2440         hb_add( fQueueEncodeLibhb, job );
2441         
2442     }
2443     else
2444     {
2445         job->indepth_scan = 0;
2446         job->pass = 0;
2447         
2448         hb_add( fQueueEncodeLibhb, job );
2449     }
2450         
2451     NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2452         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2453         /* Lets mark our new encode as 1 or "Encoding" */
2454     [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2455     [self saveQueueFileItem];
2456     /* We should be all setup so let 'er rip */   
2457     [self doRip];
2458 }
2459
2460
2461 #pragma mark -
2462 #pragma mark Job Handling
2463
2464
2465 - (void) prepareJob
2466 {
2467     
2468     NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2469     hb_list_t  * list  = hb_get_titles( fQueueEncodeLibhb );
2470     hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2471     hb_job_t * job = title->job;
2472     hb_audio_config_t * audio;
2473     [self writeToActivityLog: "prepareJob reached"];
2474     /* Chapter selection */
2475     job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
2476     job->chapter_end   = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
2477         
2478     /* Format (Muxer) and Video Encoder */
2479     job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
2480     job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
2481     
2482     
2483     /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
2484         //if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
2485         //{
2486     /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
2487      mpeg4 and the checkbox being checked 
2488      *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
2489     if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
2490     {
2491         job->largeFileSize = 1;
2492     }
2493     else
2494     {
2495         job->largeFileSize = 0;
2496     }
2497     /* We set http optimized mp4 here */
2498     if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
2499     {
2500         job->mp4_optimize = 1;
2501     }
2502     else
2503     {
2504         job->mp4_optimize = 0;
2505     }
2506     
2507     //}
2508         
2509     /* We set the chapter marker extraction here based on the format being
2510      mpeg4 or mkv and the checkbox being checked */
2511     if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
2512     {
2513         job->chapter_markers = 1;
2514         
2515         /* now lets get our saved chapter names out the array in the queue file
2516          * and insert them back into the title chapter list. We have it here,
2517          * because unless we are inserting chapter markers there is no need to
2518          * spend the overhead of iterating through the chapter names array imo
2519          * Also, note that if for some reason we don't apply chapter names, the
2520          * chapters just come out 001, 002, etc. etc.
2521          */
2522          
2523         NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
2524         int i = 0;
2525         NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
2526         id tempObject;
2527         while (tempObject = [enumerator nextObject])
2528         {
2529             hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
2530             if( chapter != NULL )
2531             {
2532                 strncpy( chapter->title, [tempObject UTF8String], 1023);
2533                 chapter->title[1023] = '\0';
2534             }
2535             i++;
2536         }
2537     }
2538     else
2539     {
2540         job->chapter_markers = 0;
2541     }
2542     
2543
2544     
2545     
2546     
2547     if( job->vcodec & HB_VCODEC_X264 )
2548     {
2549                 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
2550             {
2551             job->ipod_atom = 1;
2552                 }
2553         else
2554         {
2555             job->ipod_atom = 0;
2556         }
2557                 
2558                 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2559          Currently only used with Constant Quality setting*/
2560                 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2)
2561                 {
2562                 job->crf = 1;
2563                 }
2564                 /* Below Sends x264 options to the core library if x264 is selected*/
2565                 /* Lets use this as per Nyx, Thanks Nyx!*/
2566                 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2567                 /* Turbo first pass if two pass and Turbo First pass is selected */
2568                 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
2569                 {
2570                         /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
2571                         NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
2572                         /* append the "Turbo" string variable to the existing opts string.
2573              Note: the "Turbo" string must be appended, not prepended to work properly*/
2574                         NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
2575                         strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
2576                 }
2577                 else
2578                 {
2579                         strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2580                 }
2581         
2582     }
2583     
2584     
2585     [self writeToActivityLog: "prepareJob reached Picture Settings"];
2586     /* Picture Size Settings */
2587     job->width = [[queueToApply objectForKey:@"PictureWidth"]  intValue];
2588     job->height = [[queueToApply objectForKey:@"PictureHeight"]  intValue];
2589     
2590     job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"]  intValue];
2591     job->pixel_ratio = [[queueToApply objectForKey:@"PicturePAR"]  intValue];
2592     
2593     
2594     /* Here we use the crop values saved at the time the preset was saved */
2595     job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"]  intValue];
2596     job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"]  intValue];
2597     job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"]  intValue];
2598     job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"]  intValue];
2599     
2600     [self writeToActivityLog: "prepareJob reached Frame Rate"];
2601     
2602     /* Video settings */
2603     if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
2604     {
2605         job->vrate      = 27000000;
2606         job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
2607         /* We are not same as source so we set job->cfr to 1 
2608          * to enable constant frame rate since user has specified
2609          * a specific framerate*/
2610         job->cfr = 1;
2611     }
2612     else
2613     {
2614         job->vrate      = [[queueToApply objectForKey:@"JobVrate"] intValue];
2615         job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
2616         /* We are same as source so we set job->cfr to 0 
2617          * to enable true same as source framerate */
2618         job->cfr = 0;
2619     }
2620     [self writeToActivityLog: "prepareJob reached Bitrate Video Quality"];
2621     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 0 )
2622     {
2623         /* Target size.
2624          Bitrate should already have been calculated and displayed
2625          in fVidBitrateField, so let's just use it */
2626     }
2627     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 1 )
2628     {
2629         job->vquality = -1.0;
2630         job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
2631     }
2632     if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
2633     {
2634         job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
2635         job->vbitrate = 0;
2636         
2637     }
2638     
2639     job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
2640     /* Subtitle settings */
2641     job->subtitle = [[queueToApply objectForKey:@"JobSubtitlesIndex"] intValue] - 2;
2642     
2643     [self writeToActivityLog: "prepareJob reached Audio"];
2644     /* Audio tracks and mixdowns */
2645     /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
2646     int audiotrack_count = hb_list_count(job->list_audio);
2647     for( int i = 0; i < audiotrack_count;i++)
2648     {
2649         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
2650         hb_list_rem(job->list_audio, temp_audio);
2651     }
2652     /* Now lets add our new tracks to the audio list here */
2653     if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2654     {
2655         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2656         hb_audio_config_init(audio);
2657         audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
2658         /* We go ahead and assign values to our audio->out.<properties> */
2659         audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
2660         audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
2661         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
2662         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
2663         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
2664         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
2665         
2666         hb_audio_add( job, audio );
2667         free(audio);
2668     }  
2669     if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2670     {
2671         
2672         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2673         hb_audio_config_init(audio);
2674         audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
2675         [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
2676         /* We go ahead and assign values to our audio->out.<properties> */
2677         audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
2678         audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
2679         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
2680         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
2681         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
2682         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
2683         
2684         hb_audio_add( job, audio );
2685         free(audio);
2686     }
2687     
2688     if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2689     {
2690         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2691         hb_audio_config_init(audio);
2692         audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
2693         /* We go ahead and assign values to our audio->out.<properties> */
2694         audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
2695         audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
2696         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
2697         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
2698         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
2699         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
2700         
2701         hb_audio_add( job, audio );
2702         free(audio);        
2703     }
2704     
2705     if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2706     {
2707         audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2708         hb_audio_config_init(audio);
2709         audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
2710         /* We go ahead and assign values to our audio->out.<properties> */
2711         audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
2712         audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
2713         audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
2714         audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
2715         audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
2716         audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
2717         
2718         hb_audio_add( job, audio );
2719         free(audio);
2720     }
2721     
2722     /* set vfr according to the Picture Window */
2723     if ([[queueToApply objectForKey:@"VFR"] intValue] == 1)
2724     {
2725         job->vfr = 1;
2726     }
2727     else
2728     {
2729         job->vfr = 0;
2730     }
2731     
2732    [self writeToActivityLog: "prepareJob reached Filters"];
2733      /* Filters */ 
2734     job->filters = hb_list_init();
2735     
2736     /* Now lets call the filters if applicable.
2737      * The order of the filters is critical
2738      */
2739     /* Detelecine */
2740     if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
2741     {
2742         hb_list_add( job->filters, &hb_filter_detelecine );
2743     }
2744     
2745     /* Decomb */
2746     if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
2747     {
2748         /* Run old deinterlacer fd by default */
2749         hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"JobPictureDecomb"] UTF8String];
2750         hb_list_add( job->filters, &hb_filter_decomb );
2751     }
2752     
2753     /* Deinterlace */
2754     if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
2755     {
2756         /* Run old deinterlacer fd by default */
2757         hb_filter_deinterlace.settings = "-1"; 
2758         hb_list_add( job->filters, &hb_filter_deinterlace );
2759     }
2760     else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
2761     {
2762         /* Yadif mode 0 (without spatial deinterlacing.) */
2763         hb_filter_deinterlace.settings = "2"; 
2764         hb_list_add( job->filters, &hb_filter_deinterlace );            
2765     }
2766     else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
2767     {
2768         /* Yadif (with spatial deinterlacing) */
2769         hb_filter_deinterlace.settings = "0"; 
2770         hb_list_add( job->filters, &hb_filter_deinterlace );            
2771     }
2772         
2773     /* Denoise */
2774         if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Weak in popup
2775         {
2776                 hb_filter_denoise.settings = "2:1:2:3"; 
2777         hb_list_add( job->filters, &hb_filter_denoise );        
2778         }
2779         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Medium in popup
2780         {
2781                 hb_filter_denoise.settings = "3:2:2:3"; 
2782         hb_list_add( job->filters, &hb_filter_denoise );        
2783         }
2784         else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Strong in popup
2785         {
2786                 hb_filter_denoise.settings = "7:7:5:5"; 
2787         hb_list_add( job->filters, &hb_filter_denoise );        
2788         }
2789     
2790     /* Deblock  (uses pp7 default) */
2791     if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
2792     {
2793         hb_list_add( job->filters, &hb_filter_deblock );
2794     }
2795 [self writeToActivityLog: "prepareJob exiting"];    
2796 }
2797
2798
2799
2800 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
2801 */
2802 - (IBAction) addToQueue: (id) sender
2803 {
2804         /* We get the destination directory from the destination field here */
2805         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
2806         /* We check for a valid destination here */
2807         if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
2808         {
2809                 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
2810         return;
2811         }
2812
2813     /* We check for duplicate name here */
2814         if( [[NSFileManager defaultManager] fileExistsAtPath:
2815             [fDstFile2Field stringValue]] )
2816     {
2817         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
2818             NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
2819             @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
2820             NULL, NULL, [NSString stringWithFormat:
2821             NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
2822             [fDstFile2Field stringValue]] );
2823         // overwriteAddToQueueAlertDone: will be called when the alert is dismissed.
2824     }
2825     else
2826     {
2827         [self doAddToQueue];
2828     }
2829 }
2830
2831 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
2832    the user if they want to overwrite an exiting movie file.
2833 */
2834 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
2835     returnCode: (int) returnCode contextInfo: (void *) contextInfo
2836 {
2837     if( returnCode == NSAlertAlternateReturn )
2838         [self doAddToQueue];
2839 }
2840
2841 - (void) doAddToQueue
2842 {
2843     [self addQueueFileItem ];
2844 }
2845
2846
2847
2848 /* Rip: puts up an alert before ultimately calling doRip
2849 */
2850 - (IBAction) Rip: (id) sender
2851 {
2852     [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
2853     /* Rip or Cancel ? */
2854     hb_state_t s;
2855     hb_get_state2( fQueueEncodeLibhb, &s );
2856     
2857     if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
2858         {
2859         [self Cancel: sender];
2860         return;
2861     }
2862     
2863     // If there are pending jobs in the queue, then this is a rip the queue
2864     
2865     if (fPendingCount > 0)
2866     {
2867         /* here lets start the queue with the first pending item */
2868         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
2869         
2870         return;
2871     }
2872     
2873     // Before adding jobs to the queue, check for a valid destination.
2874     
2875     NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
2876     if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0) 
2877     {
2878         NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
2879         return;
2880     }
2881     
2882     /* We check for duplicate name here */
2883     if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
2884     {
2885         NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
2886                                   NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
2887                                   @selector( overWriteAlertDone:returnCode:contextInfo: ),
2888                                   NULL, NULL, [NSString stringWithFormat:
2889                                                NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
2890                                                [fDstFile2Field stringValue]] );
2891         
2892         // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
2893     }
2894     else
2895     {
2896         /* if there are no pending jobs in the queue, then add this one to the queue and rip
2897          otherwise, just rip the queue */
2898         if(fPendingCount == 0)
2899         {
2900          [self writeToActivityLog: "Rip: No pending jobs, so sending this one to doAddToQueue"];
2901                [self doAddToQueue];
2902         }
2903         
2904         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
2905         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2906         /* go right to processing the new queue encode */
2907        [self writeToActivityLog: "Rip: Going right to performNewQueueScan"];
2908          [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
2909         
2910     }
2911 }
2912
2913 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
2914    want to overwrite an exiting movie file.
2915 */
2916 - (void) overWriteAlertDone: (NSWindow *) sheet
2917     returnCode: (int) returnCode contextInfo: (void *) contextInfo
2918 {
2919     if( returnCode == NSAlertAlternateReturn )
2920     {
2921         /* if there are no jobs in the queue, then add this one to the queue and rip 
2922         otherwise, just rip the queue */
2923         if( fPendingCount == 0 )
2924         {
2925             [self doAddToQueue];
2926         }
2927
2928         NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
2929         [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2930         [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]]; 
2931       
2932     }
2933 }
2934
2935 - (void) remindUserOfSleepOrShutdown
2936 {
2937        if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
2938        {
2939                /*Warn that computer will sleep after encoding*/
2940                int reminduser;
2941                NSBeep();
2942                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);
2943                [NSApp requestUserAttention:NSCriticalRequest];
2944                if ( reminduser == NSAlertAlternateReturn )
2945                {
2946                        [self showPreferencesWindow:nil];
2947                }
2948        }
2949        else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
2950        {
2951                /*Warn that computer will shut down after encoding*/
2952                int reminduser;
2953                NSBeep();
2954                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);
2955                [NSApp requestUserAttention:NSCriticalRequest];
2956                if ( reminduser == NSAlertAlternateReturn )
2957                {
2958                        [self showPreferencesWindow:nil];
2959                }
2960        }
2961
2962 }
2963
2964
2965 - (void) doRip
2966 {
2967     /* Let libhb do the job */
2968     hb_start( fQueueEncodeLibhb );
2969     /*set the fEncodeState State */
2970         fEncodeState = 1;
2971 }
2972
2973
2974 //------------------------------------------------------------------------------------
2975 // Cancels and deletes the current job and stops libhb from processing the remaining
2976 // encodes.
2977 //------------------------------------------------------------------------------------
2978 - (void) doCancelCurrentJob
2979 {
2980     // Stop the current job. hb_stop will only cancel the current pass and then set
2981     // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
2982     // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
2983     // remaining passes of the job and then start the queue back up if there are any
2984     // remaining jobs.
2985      
2986     
2987     hb_stop( fQueueEncodeLibhb );
2988     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
2989     
2990     // now that we've stopped the currently encoding job, lets mark it as cancelled
2991     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
2992     // and as always, save it in the queue .plist...
2993     /* We save all of the Queue data here */
2994     [self saveQueueFileItem];
2995     // so now lets move to 
2996     currentQueueEncodeIndex++ ;
2997     // ... and see if there are more items left in our queue
2998     int queueItems = [QueueFileArray count];
2999     /* If we still have more items in our queue, lets go to the next one */
3000     if (currentQueueEncodeIndex < queueItems)
3001     {
3002     [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
3003     [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
3004     
3005     [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3006     }
3007     else
3008     {
3009         [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
3010     }
3011
3012 }
3013
3014 //------------------------------------------------------------------------------------
3015 // Displays an alert asking user if the want to cancel encoding of current job.
3016 // Cancel: returns immediately after posting the alert. Later, when the user
3017 // acknowledges the alert, doCancelCurrentJob is called.
3018 //------------------------------------------------------------------------------------
3019 - (IBAction)Cancel: (id)sender
3020 {
3021     if (!fQueueController) return;
3022     
3023   hb_pause( fQueueEncodeLibhb );
3024     NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
3025    
3026     // Which window to attach the sheet to?
3027     NSWindow * docWindow;
3028     if ([sender respondsToSelector: @selector(window)])
3029         docWindow = [sender window];
3030     else
3031         docWindow = fWindow;
3032         
3033     NSBeginCriticalAlertSheet(
3034             alertTitle,
3035             NSLocalizedString(@"Continue Encoding", nil),
3036             NSLocalizedString(@"Cancel Current and Stop", nil),
3037             NSLocalizedString(@"Cancel Current and Continue", nil),
3038             docWindow, self,
3039             nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
3040             NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
3041     
3042     // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
3043 }
3044
3045 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
3046 {
3047    hb_resume( fQueueEncodeLibhb );
3048      if (returnCode == NSAlertOtherReturn)
3049     {
3050         [self doCancelCurrentJob];  // <- this also stops libhb
3051     }
3052     if (returnCode == NSAlertAlternateReturn)
3053     {
3054     [self doCancelCurrentJobAndStop];
3055     }
3056 }
3057
3058 - (void) doCancelCurrentJobAndStop
3059 {
3060     hb_stop( fQueueEncodeLibhb );
3061     fEncodeState = 2;   // don't alert at end of processing since this was a cancel
3062     
3063     // now that we've stopped the currently encoding job, lets mark it as cancelled
3064     [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3065     // and as always, save it in the queue .plist...
3066     /* We save all of the Queue data here */
3067     [self saveQueueFileItem];
3068     // so now lets move to 
3069     currentQueueEncodeIndex++ ;
3070     [self writeToActivityLog: "cancelling current job and stopping the queue"];
3071 }
3072 - (IBAction) Pause: (id) sender
3073 {
3074     hb_state_t s;
3075     hb_get_state2( fQueueEncodeLibhb, &s );
3076
3077     if( s.state == HB_STATE_PAUSED )
3078     {
3079         hb_resume( fQueueEncodeLibhb );
3080     }
3081     else
3082     {
3083         hb_pause( fQueueEncodeLibhb );
3084     }
3085 }
3086
3087 #pragma mark -
3088 #pragma mark GUI Controls Changed Methods
3089
3090 - (IBAction) titlePopUpChanged: (id) sender
3091 {
3092     hb_list_t  * list  = hb_get_titles( fHandle );
3093     hb_title_t * title = (hb_title_t*)
3094         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3095
3096     /* If Auto Naming is on. We create an output filename of dvd name - title number */
3097     if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
3098         {
3099                 [fDstFile2Field setStringValue: [NSString stringWithFormat:
3100                         @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
3101                         [browsedSourceDisplayName stringByDeletingPathExtension],
3102             title->index,
3103                         [[fDstFile2Field stringValue] pathExtension]]]; 
3104         }
3105
3106     /* Update chapter popups */
3107     [fSrcChapterStartPopUp removeAllItems];
3108     [fSrcChapterEndPopUp   removeAllItems];
3109     for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
3110     {
3111         [fSrcChapterStartPopUp addItemWithTitle: [NSString
3112             stringWithFormat: @"%d", i + 1]];
3113         [fSrcChapterEndPopUp addItemWithTitle: [NSString
3114             stringWithFormat: @"%d", i + 1]];
3115     }
3116
3117     [fSrcChapterStartPopUp selectItemAtIndex: 0];
3118     [fSrcChapterEndPopUp   selectItemAtIndex:
3119         hb_list_count( title->list_chapter ) - 1];
3120     [self chapterPopUpChanged:nil];
3121
3122     /* Start Get and set the initial pic size for display */
3123         hb_job_t * job = title->job;
3124         fTitle = title;
3125
3126         /*Set Source Size Field Here */
3127     [fPicSettingsSrc setStringValue: [NSString stringWithFormat: @"%d x %d", fTitle->width, fTitle->height]];
3128         
3129         /* Set Auto Crop to on upon selecting a new title */
3130     [fPictureController setAutoCrop:YES];
3131     
3132         /* We get the originial output picture width and height and put them
3133         in variables for use with some presets later on */
3134         PicOrigOutputWidth = job->width;
3135         PicOrigOutputHeight = job->height;
3136         AutoCropTop = job->crop[0];
3137         AutoCropBottom = job->crop[1];
3138         AutoCropLeft = job->crop[2];
3139         AutoCropRight = job->crop[3];
3140
3141         /* Run Through encoderPopUpChanged to see if there
3142                 needs to be any pic value modifications based on encoder settings */
3143         //[self encoderPopUpChanged: NULL];
3144         /* END Get and set the initial pic size for display */ 
3145
3146     /* Update subtitle popups */
3147     hb_subtitle_t * subtitle;
3148     [fSubPopUp removeAllItems];
3149     [fSubPopUp addItemWithTitle: @"None"];
3150     [fSubPopUp addItemWithTitle: @"Autoselect"];
3151     for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
3152     {
3153         subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
3154
3155         /* We cannot use NSPopUpButton's addItemWithTitle because
3156            it checks for duplicate entries */
3157         [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
3158             subtitle->lang] action: NULL keyEquivalent: @""];
3159     }
3160     [fSubPopUp selectItemAtIndex: 0];
3161
3162         [self subtitleSelectionChanged:nil];
3163
3164     /* Update chapter table */
3165     [fChapterTitlesDelegate resetWithTitle:title];
3166     [fChapterTable reloadData];
3167
3168    /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3169     int audiotrack_count = hb_list_count(job->list_audio);
3170     for( int i = 0; i < audiotrack_count;i++)
3171     {
3172         hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3173         hb_list_rem(job->list_audio, temp_audio);
3174     }
3175
3176     /* Update audio popups */
3177     [self addAllAudioTracksToPopUp: fAudLang1PopUp];
3178     [self addAllAudioTracksToPopUp: fAudLang2PopUp];
3179     [self addAllAudioTracksToPopUp: fAudLang3PopUp];
3180     [self addAllAudioTracksToPopUp: fAudLang4PopUp];
3181     /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
3182         NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
3183         [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
3184     [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3185     [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3186     [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3187
3188         /* changing the title may have changed the audio channels on offer, */
3189         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3190         [self audioTrackPopUpChanged: fAudLang1PopUp];
3191         [self audioTrackPopUpChanged: fAudLang2PopUp];
3192     [self audioTrackPopUpChanged: fAudLang3PopUp];
3193     [self audioTrackPopUpChanged: fAudLang4PopUp];
3194
3195     [fVidRatePopUp selectItemAtIndex: 0];
3196
3197     /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
3198         [self calculatePictureSizing:nil];
3199
3200    /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
3201         [self selectPreset:nil];
3202 }
3203
3204 - (IBAction) chapterPopUpChanged: (id) sender
3205 {
3206
3207         /* If start chapter popup is greater than end chapter popup,
3208         we set the end chapter popup to the same as start chapter popup */
3209         if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
3210         {
3211                 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
3212     }
3213
3214                 
3215         hb_list_t  * list  = hb_get_titles( fHandle );
3216     hb_title_t * title = (hb_title_t *)
3217         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3218
3219     hb_chapter_t * chapter;
3220     int64_t        duration = 0;
3221     for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
3222          i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
3223     {
3224         chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3225         duration += chapter->duration;
3226     }
3227     
3228     duration /= 90000; /* pts -> seconds */
3229     [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
3230         @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
3231         duration % 60]];
3232
3233     [self calculateBitrate: sender];
3234 }
3235
3236 - (IBAction) formatPopUpChanged: (id) sender
3237 {
3238     NSString * string = [fDstFile2Field stringValue];
3239     int format = [fDstFormatPopUp indexOfSelectedItem];
3240     char * ext = NULL;
3241         /* Initially set the large file (64 bit formatting) output checkbox to hidden */
3242     [fDstMp4LargeFileCheck setHidden: YES];
3243     [fDstMp4HttpOptFileCheck setHidden: YES];
3244     [fDstMp4iPodFileCheck setHidden: YES];
3245     
3246     /* Update the Video Codec PopUp */
3247     /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
3248     [fVidEncoderPopUp removeAllItems];
3249     NSMenuItem *menuItem;
3250     /* These video encoders are available to all of our current muxers, so lets list them once here */
3251     menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
3252     [menuItem setTag: HB_VCODEC_FFMPEG];
3253     
3254     menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (XviD)" action: NULL keyEquivalent: @""];
3255     [menuItem setTag: HB_VCODEC_XVID];
3256     switch( format )
3257     {
3258         case 0:
3259                         /*Get Default MP4 File Extension*/
3260                         if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
3261                         {
3262                                 ext = "m4v";
3263                         }
3264                         else
3265                         {
3266                                 ext = "mp4";
3267                         }
3268             /* Add additional video encoders here */
3269             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3270             [menuItem setTag: HB_VCODEC_X264];
3271             /* We show the mp4 option checkboxes here since we are mp4 */
3272             [fCreateChapterMarkers setEnabled: YES];
3273                         [fDstMp4LargeFileCheck setHidden: NO];
3274                         [fDstMp4HttpOptFileCheck setHidden: NO];
3275             [fDstMp4iPodFileCheck setHidden: NO];
3276             break;
3277             
3278             case 1:
3279             ext = "mkv";
3280             /* Add additional video encoders here */
3281             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3282             [menuItem setTag: HB_VCODEC_X264];
3283             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3284             [menuItem setTag: HB_VCODEC_THEORA];
3285             /* We enable the create chapters checkbox here */
3286                         [fCreateChapterMarkers setEnabled: YES];
3287                         break;
3288             
3289             case 2: 
3290             ext = "avi";
3291             /* Add additional video encoders here */
3292             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3293             [menuItem setTag: HB_VCODEC_X264];
3294             /* We disable the create chapters checkbox here and make sure it is unchecked*/
3295                         [fCreateChapterMarkers setEnabled: NO];
3296                         [fCreateChapterMarkers setState: NSOffState];
3297                         break;
3298             
3299             case 3:
3300             ext = "ogm";
3301             /* Add additional video encoders here */
3302             menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3303             [menuItem setTag: HB_VCODEC_THEORA];
3304             /* We disable the create chapters checkbox here and make sure it is unchecked*/
3305                         [fCreateChapterMarkers setEnabled: NO];
3306                         [fCreateChapterMarkers setState: NSOffState];
3307                         break;
3308     }
3309     [fVidEncoderPopUp selectItemAtIndex: 0];
3310
3311     [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
3312     [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
3313     [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
3314     [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
3315
3316     if( format == 0 )
3317         [self autoSetM4vExtension: sender];
3318     else
3319         [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
3320
3321     if( SuccessfulScan )
3322     {
3323         /* Add/replace to the correct extension */
3324         [self audioTrackPopUpChanged: fAudLang1PopUp];
3325         [self audioTrackPopUpChanged: fAudLang2PopUp];
3326         [self audioTrackPopUpChanged: fAudLang3PopUp];
3327         [self audioTrackPopUpChanged: fAudLang4PopUp];
3328
3329         if( [fVidEncoderPopUp selectedItem] == nil )
3330         {
3331
3332             [fVidEncoderPopUp selectItemAtIndex:0];
3333             [self videoEncoderPopUpChanged:nil];
3334
3335             /* changing the format may mean that we can / can't offer mono or 6ch, */
3336             /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3337
3338             /* We call the method to properly enable/disable turbo 2 pass */
3339             [self twoPassCheckboxChanged: sender];
3340             /* We call method method to change UI to reflect whether a preset is used or not*/
3341         }
3342     }
3343         [self customSettingUsed: sender];
3344 }
3345
3346 - (IBAction) autoSetM4vExtension: (id) sender
3347 {
3348     if ( [fDstFormatPopUp indexOfSelectedItem] )
3349         return;
3350
3351     NSString * extension = @"mp4";
3352
3353     if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3354                                                         [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3355                                                         [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3356                                                         [fCreateChapterMarkers state] == NSOnState ||
3357                                                         [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
3358     {
3359         extension = @"m4v";
3360     }
3361
3362     if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
3363         return;
3364     else
3365         [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
3366                                     [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
3367 }
3368
3369 - (void) shouldEnableHttpMp4CheckBox: (id) sender
3370 {
3371     if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3372                                                         [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3373                                                         [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 )
3374         [fDstMp4HttpOptFileCheck setEnabled: NO];
3375     else
3376         [fDstMp4HttpOptFileCheck setEnabled: YES];
3377 }
3378         
3379 /* Method to determine if we should change the UI
3380 To reflect whether or not a Preset is being used or if
3381 the user is using "Custom" settings by determining the sender*/
3382 - (IBAction) customSettingUsed: (id) sender
3383 {
3384         if ([sender stringValue])
3385         {
3386                 /* Deselect the currently selected Preset if there is one*/
3387                 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3388                 /* Change UI to show "Custom" settings are being used */
3389                 [fPresetSelectedDisplay setStringValue: @"Custom"];
3390
3391                 curUserPresetChosenNum = nil;
3392         }
3393 }
3394
3395
3396 #pragma mark -
3397 #pragma mark - Video
3398
3399 - (IBAction) videoEncoderPopUpChanged: (id) sender
3400 {
3401     hb_job_t * job = fTitle->job;
3402     int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
3403     
3404     [fAdvancedOptions setHidden:YES];
3405     /* If we are using x264 then show the x264 advanced panel*/
3406     if (videoEncoder == HB_VCODEC_X264)
3407     {
3408         [fAdvancedOptions setHidden:NO];
3409         [self autoSetM4vExtension: sender];
3410     }
3411     
3412     /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
3413     is being used as it borks up loose anamorphic .
3414     For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
3415     to use the index itself but this is easier */
3416     if (videoEncoder == HB_VCODEC_FFMPEG)
3417     {
3418         if (job->pixel_ratio == 2)
3419         {
3420             job->pixel_ratio = 0;
3421         }
3422         [fPictureController setAllowLooseAnamorphic:NO];
3423         /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
3424          container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
3425          anything other than MP4.
3426          */ 
3427         [fDstMp4iPodFileCheck setEnabled: NO];
3428         [fDstMp4iPodFileCheck setState: NSOffState];
3429     }
3430     else
3431     {
3432         [fPictureController setAllowLooseAnamorphic:YES];
3433         [fDstMp4iPodFileCheck setEnabled: YES];
3434     }
3435     
3436         [self calculatePictureSizing: sender];
3437         [self twoPassCheckboxChanged: sender];
3438 }
3439
3440
3441 - (IBAction) twoPassCheckboxChanged: (id) sender
3442 {
3443         /* check to see if x264 is chosen */
3444         if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
3445     {
3446                 if( [fVidTwoPassCheck state] == NSOnState)
3447                 {
3448                         [fVidTurboPassCheck setHidden: NO];
3449                 }
3450                 else
3451                 {
3452                         [fVidTurboPassCheck setHidden: YES];
3453                         [fVidTurboPassCheck setState: NSOffState];
3454                 }
3455                 /* Make sure Two Pass is checked if Turbo is checked */
3456                 if( [fVidTurboPassCheck state] == NSOnState)
3457                 {
3458                         [fVidTwoPassCheck setState: NSOnState];
3459                 }
3460         }
3461         else
3462         {
3463                 [fVidTurboPassCheck setHidden: YES];
3464                 [fVidTurboPassCheck setState: NSOffState];
3465         }
3466         
3467         /* We call method method to change UI to reflect whether a preset is used or not*/
3468         [self customSettingUsed: sender];
3469 }
3470
3471 - (IBAction ) videoFrameRateChanged: (id) sender
3472 {
3473     /* We call method method to calculatePictureSizing to error check detelecine*/
3474     [self calculatePictureSizing: sender];
3475
3476     /* We call method method to change UI to reflect whether a preset is used or not*/
3477         [self customSettingUsed: sender];
3478 }
3479 - (IBAction) videoMatrixChanged: (id) sender;
3480 {
3481     bool target, bitrate, quality;
3482
3483     target = bitrate = quality = false;
3484     if( [fVidQualityMatrix isEnabled] )
3485     {
3486         switch( [fVidQualityMatrix selectedRow] )
3487         {
3488             case 0:
3489                 target = true;
3490                 break;
3491             case 1:
3492                 bitrate = true;
3493                 break;
3494             case 2:
3495                 quality = true;
3496                 break;
3497         }
3498     }
3499     [fVidTargetSizeField  setEnabled: target];
3500     [fVidBitrateField     setEnabled: bitrate];
3501     [fVidQualitySlider    setEnabled: quality];
3502     [fVidTwoPassCheck     setEnabled: !quality &&
3503         [fVidQualityMatrix isEnabled]];
3504     if( quality )
3505     {
3506         [fVidTwoPassCheck setState: NSOffState];
3507                 [fVidTurboPassCheck setHidden: YES];
3508                 [fVidTurboPassCheck setState: NSOffState];
3509     }
3510
3511     [self qualitySliderChanged: sender];
3512     [self calculateBitrate: sender];
3513         [self customSettingUsed: sender];
3514 }
3515
3516 - (IBAction) qualitySliderChanged: (id) sender
3517 {
3518     [fVidConstantCell setTitle: [NSString stringWithFormat:
3519         NSLocalizedString( @"Constant quality: %.0f %%", @"" ), 100.0 *
3520         [fVidQualitySlider floatValue]]];
3521                 [self customSettingUsed: sender];
3522 }
3523
3524 - (void) controlTextDidChange: (NSNotification *) notification
3525 {
3526     [self calculateBitrate:nil];
3527 }
3528
3529 - (IBAction) calculateBitrate: (id) sender
3530 {
3531     if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
3532     {
3533         return;
3534     }
3535
3536     hb_list_t  * list  = hb_get_titles( fHandle );
3537     hb_title_t * title = (hb_title_t *) hb_list_item( list,
3538             [fSrcTitlePopUp indexOfSelectedItem] );
3539     hb_job_t * job = title->job;
3540      
3541     [fVidBitrateField setIntValue: hb_calc_bitrate( job,
3542             [fVidTargetSizeField intValue] )];
3543 }
3544
3545 #pragma mark -
3546 #pragma mark - Picture
3547
3548 /* lets set the picture size back to the max from right after title scan
3549    Lets use an IBAction here as down the road we could always use a checkbox
3550    in the gui to easily take the user back to max. Remember, the compiler
3551    resolves IBActions down to -(void) during compile anyway */
3552 - (IBAction) revertPictureSizeToMax: (id) sender
3553 {
3554         hb_job_t * job = fTitle->job;
3555         /* We use the output picture width and height
3556      as calculated from libhb right after title is set
3557      in TitlePopUpChanged */
3558         job->width = PicOrigOutputWidth;
3559         job->height = PicOrigOutputHeight;
3560     [fPictureController setAutoCrop:YES];
3561         /* Here we use the auto crop values determined right after scan */
3562         job->crop[0] = AutoCropTop;
3563         job->crop[1] = AutoCropBottom;
3564         job->crop[2] = AutoCropLeft;
3565         job->crop[3] = AutoCropRight;
3566     
3567     
3568     [self calculatePictureSizing: sender];
3569     /* We call method to change UI to reflect whether a preset is used or not*/    
3570     [self customSettingUsed: sender];
3571 }
3572
3573 /**
3574  * Registers changes made in the Picture Settings Window.
3575  */
3576
3577 - (void)pictureSettingsDidChange {
3578         [self calculatePictureSizing:nil];
3579 }
3580
3581 /* Get and Display Current Pic Settings in main window */
3582 - (IBAction) calculatePictureSizing: (id) sender
3583 {
3584         [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", fTitle->job->width, fTitle->job->height]];
3585         
3586     if (fTitle->job->pixel_ratio == 1)
3587         {
3588         int titlewidth = fTitle->width-fTitle->job->crop[2]-fTitle->job->crop[3];
3589         int arpwidth = fTitle->job->pixel_aspect_width;
3590         int arpheight = fTitle->job->pixel_aspect_height;
3591         int displayparwidth = titlewidth * arpwidth / arpheight;
3592         int displayparheight = fTitle->height-fTitle->job->crop[0]-fTitle->job->crop[1];
3593         [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", titlewidth, displayparheight]];
3594         [fPicSettingsAnamorphic setStringValue: [NSString stringWithFormat:@"%d x %d Strict", displayparwidth, displayparheight]];
3595         fTitle->job->keep_ratio = 0;
3596         }
3597     else if (fTitle->job->pixel_ratio == 2)
3598     {
3599         hb_job_t * job = fTitle->job;
3600         int output_width, output_height, output_par_width, output_par_height;
3601         hb_set_anamorphic_size(job, &output_width, &output_height, &output_par_width, &output_par_height);
3602         int display_width;
3603         display_width = output_width * output_par_width / output_par_height;
3604
3605         [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", output_width, output_height]];
3606         [fPicSettingsAnamorphic setStringValue: [NSString stringWithFormat:@"%d x %d Loose", display_width, output_height]];
3607
3608         fTitle->job->keep_ratio = 0;
3609     }
3610         else
3611         {
3612         [fPicSettingsAnamorphic setStringValue:@"Off"];
3613         }
3614
3615         /* Set ON/Off values for the deinterlace/keep aspect ratio according to boolean */
3616         if (fTitle->job->keep_ratio > 0)
3617         {
3618                 [fPicSettingARkeep setStringValue: @"On"];
3619         }
3620         else
3621         {
3622                 [fPicSettingARkeep setStringValue: @"Off"];
3623         }       
3624     
3625     /* Detelecine */
3626     if ([fPictureController detelecine]) {
3627         [fPicSettingDetelecine setStringValue: @"Yes"];
3628     }
3629     else {
3630         [fPicSettingDetelecine setStringValue: @"No"];
3631     }
3632     
3633     /* Decomb */
3634         if ([fPictureController decomb] == 0)
3635         {
3636                 [fPicSettingDecomb setStringValue: @"Off"];
3637         }
3638         else if ([fPictureController decomb] == 1)
3639         {
3640                 [fPicSettingDecomb setStringValue: @"1:2:6:9:80:16:16"];
3641         }
3642     else if ([fPictureController decomb] == 2)
3643     {
3644         [fPicSettingDecomb setStringValue:[[NSUserDefaults standardUserDefaults] stringForKey:@"DecombCustomString"]];
3645     }
3646
3647     /* VFR (Variable Frame Rate) */
3648     if ([fPictureController vfr]) {
3649         /* We change the string of the fps popup to warn that vfr is on Framerate (FPS): */
3650         [fVidRateField setStringValue: @"Framerate (VFR On):"]; 
3651         /* for VFR we select same as source (or title framerate) and disable the popup.
3652         * We know its index 0 as that is determined in titlePopUpChanged */
3653         [fVidRatePopUp selectItemAtIndex: 0];
3654         [fVidRatePopUp setEnabled: NO];  
3655         
3656     }
3657     else {
3658         /* make sure the label for framerate is set to its default */  
3659         [fVidRateField setStringValue: @"Framerate (FPS):"];
3660         [fVidRatePopUp setEnabled: YES];
3661     }
3662     
3663         /* Deinterlace */
3664         if ([fPictureController deinterlace] == 0)
3665         {
3666                 [fPicSettingDeinterlace setStringValue: @"Off"];
3667         }
3668         else if ([fPictureController deinterlace] == 1)
3669         {
3670                 [fPicSettingDeinterlace setStringValue: @"Fast"];
3671         }
3672         else if ([fPictureController deinterlace] == 2)
3673         {
3674                 [fPicSettingDeinterlace setStringValue: @"Slow"];
3675         }
3676         else if ([fPictureController deinterlace] == 3)
3677         {
3678                 [fPicSettingDeinterlace setStringValue: @"Slower"];
3679         }
3680                 
3681     /* Denoise */
3682         if ([fPictureController denoise] == 0)
3683         {
3684                 [fPicSettingDenoise setStringValue: @"Off"];
3685         }
3686         else if ([fPictureController denoise] == 1)
3687         {
3688                 [fPicSettingDenoise setStringValue: @"Weak"];
3689         }
3690         else if ([fPictureController denoise] == 2)
3691         {
3692                 [fPicSettingDenoise setStringValue: @"Medium"];
3693         }
3694         else if ([fPictureController denoise] == 3)
3695         {
3696                 [fPicSettingDenoise setStringValue: @"Strong"];
3697         }
3698     
3699     /* Deblock */
3700     if ([fPictureController deblock]) {
3701         [fPicSettingDeblock setStringValue: @"Yes"];
3702     }
3703     else {
3704         [fPicSettingDeblock setStringValue: @"No"];
3705     }
3706         
3707         if (fTitle->job->pixel_ratio > 0)
3708         {
3709                 [fPicSettingPAR setStringValue: @""];
3710         }
3711         else
3712         {
3713                 [fPicSettingPAR setStringValue: @"Off"];
3714         }
3715         
3716     /* Set the display field for crop as per boolean */
3717         if (![fPictureController autoCrop])
3718         {
3719             [fPicSettingAutoCrop setStringValue: @"Custom"];
3720         }
3721         else
3722         {
3723                 [fPicSettingAutoCrop setStringValue: @"Auto"];
3724         }       
3725         
3726     
3727 }
3728
3729
3730 #pragma mark -
3731 #pragma mark - Audio and Subtitles
3732 - (IBAction) audioCodecsPopUpChanged: (id) sender
3733 {
3734     
3735     NSPopUpButton * audiotrackPopUp;
3736     NSPopUpButton * sampleratePopUp;
3737     NSPopUpButton * bitratePopUp;
3738     NSPopUpButton * audiocodecPopUp;
3739     if (sender == fAudTrack1CodecPopUp)
3740     {
3741         audiotrackPopUp = fAudLang1PopUp;
3742         audiocodecPopUp = fAudTrack1CodecPopUp;
3743         sampleratePopUp = fAudTrack1RatePopUp;
3744         bitratePopUp = fAudTrack1BitratePopUp;
3745     }
3746     else if (sender == fAudTrack2CodecPopUp)
3747     {
3748         audiotrackPopUp = fAudLang2PopUp;
3749         audiocodecPopUp = fAudTrack2CodecPopUp;
3750         sampleratePopUp = fAudTrack2RatePopUp;
3751         bitratePopUp = fAudTrack2BitratePopUp;
3752     }
3753     else if (sender == fAudTrack3CodecPopUp)
3754     {
3755         audiotrackPopUp = fAudLang3PopUp;
3756         audiocodecPopUp = fAudTrack3CodecPopUp;
3757         sampleratePopUp = fAudTrack3RatePopUp;
3758         bitratePopUp = fAudTrack3BitratePopUp;
3759     }
3760     else
3761     {
3762         audiotrackPopUp = fAudLang4PopUp;
3763         audiocodecPopUp = fAudTrack4CodecPopUp;
3764         sampleratePopUp = fAudTrack4RatePopUp;
3765         bitratePopUp = fAudTrack4BitratePopUp;
3766     }
3767         
3768     /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
3769         /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3770     [self audioTrackPopUpChanged: audiotrackPopUp];
3771     
3772 }
3773
3774 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
3775 {
3776     /* We will be setting the enabled/disabled state of each tracks audio controls based on
3777      * the settings of the source audio for that track. We leave the samplerate and bitrate
3778      * to audiotrackMixdownChanged
3779      */
3780     
3781     /* We will first verify that a lower track number has been selected before enabling each track
3782      * for example, make sure a track is selected for track 1 before enabling track 2, etc.
3783      */
3784     if ([fAudLang1PopUp indexOfSelectedItem] == 0)
3785     {
3786         [fAudLang2PopUp setEnabled: NO];
3787         [fAudLang2PopUp selectItemAtIndex: 0];
3788     }
3789     else
3790     {
3791         [fAudLang2PopUp setEnabled: YES];
3792     }
3793     
3794     if ([fAudLang2PopUp indexOfSelectedItem] == 0)
3795     {
3796         [fAudLang3PopUp setEnabled: NO];
3797         [fAudLang3PopUp selectItemAtIndex: 0];
3798     }
3799     else
3800     {
3801         [fAudLang3PopUp setEnabled: YES];
3802     }
3803     if ([fAudLang3PopUp indexOfSelectedItem] == 0)
3804     {
3805         [fAudLang4PopUp setEnabled: NO];
3806         [fAudLang4PopUp selectItemAtIndex: 0];
3807     }
3808     else
3809     {
3810         [fAudLang4PopUp setEnabled: YES];
3811     }
3812     /* enable/disable the mixdown text and popupbutton for audio track 1 */
3813     [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
3814     [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
3815     [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
3816     [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
3817     [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
3818     [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
3819     if ([fAudLang1PopUp indexOfSelectedItem] == 0)
3820     {
3821         [fAudTrack1CodecPopUp removeAllItems];
3822         [fAudTrack1MixPopUp removeAllItems];
3823         [fAudTrack1RatePopUp removeAllItems];
3824         [fAudTrack1BitratePopUp removeAllItems];
3825         [fAudTrack1DrcSlider setFloatValue: 1.00];
3826         [self audioDRCSliderChanged: fAudTrack1DrcSlider];
3827     }
3828     else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
3829     {
3830         [fAudTrack1RatePopUp setEnabled: NO];
3831         [fAudTrack1BitratePopUp setEnabled: NO];
3832         [fAudTrack1DrcSlider setEnabled: NO];
3833         [fAudTrack1DrcField setEnabled: NO];
3834     }
3835     
3836     /* enable/disable the mixdown text and popupbutton for audio track 2 */
3837     [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
3838     [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
3839     [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
3840     [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
3841     [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
3842     [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
3843     if ([fAudLang2PopUp indexOfSelectedItem] == 0)
3844     {
3845         [fAudTrack2CodecPopUp removeAllItems];
3846         [fAudTrack2MixPopUp removeAllItems];
3847         [fAudTrack2RatePopUp removeAllItems];
3848         [fAudTrack2BitratePopUp removeAllItems];
3849         [fAudTrack2DrcSlider setFloatValue: 1.00];
3850         [self audioDRCSliderChanged: fAudTrack2DrcSlider];
3851     }
3852     else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
3853     {
3854         [fAudTrack2RatePopUp setEnabled: NO];
3855         [fAudTrack2BitratePopUp setEnabled: NO];
3856         [fAudTrack2DrcSlider setEnabled: NO];
3857         [fAudTrack2DrcField setEnabled: NO];
3858     }
3859     
3860     /* enable/disable the mixdown text and popupbutton for audio track 3 */
3861     [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
3862     [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
3863     [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
3864     [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
3865     [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
3866     [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
3867     if ([fAudLang3PopUp indexOfSelectedItem] == 0)
3868     {
3869         [fAudTrack3CodecPopUp removeAllItems];
3870         [fAudTrack3MixPopUp removeAllItems];
3871         [fAudTrack3RatePopUp removeAllItems];
3872         [fAudTrack3BitratePopUp removeAllItems];
3873         [fAudTrack3DrcSlider setFloatValue: 1.00];
3874         [self audioDRCSliderChanged: fAudTrack3DrcSlider];
3875     }
3876     else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
3877     {
3878         [fAudTrack3RatePopUp setEnabled: NO];
3879         [fAudTrack3BitratePopUp setEnabled: NO];
3880         [fAudTrack3DrcSlider setEnabled: NO];
3881         [fAudTrack3DrcField setEnabled: NO];
3882     }
3883     
3884     /* enable/disable the mixdown text and popupbutton for audio track 4 */
3885     [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
3886     [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
3887     [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
3888     [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
3889     [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
3890     [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
3891     if ([fAudLang4PopUp indexOfSelectedItem] == 0)
3892     {
3893         [fAudTrack4CodecPopUp removeAllItems];
3894         [fAudTrack4MixPopUp removeAllItems];
3895         [fAudTrack4RatePopUp removeAllItems];
3896         [fAudTrack4BitratePopUp removeAllItems];
3897         [fAudTrack4DrcSlider setFloatValue: 1.00];
3898         [self audioDRCSliderChanged: fAudTrack4DrcSlider];
3899     }
3900     else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
3901     {
3902         [fAudTrack4RatePopUp setEnabled: NO];
3903         [fAudTrack4BitratePopUp setEnabled: NO];
3904         [fAudTrack4DrcSlider setEnabled: NO];
3905         [fAudTrack4DrcField setEnabled: NO];
3906     }
3907     
3908 }
3909
3910 - (IBAction) addAllAudioTracksToPopUp: (id) sender
3911 {
3912
3913     hb_list_t  * list  = hb_get_titles( fHandle );
3914     hb_title_t * title = (hb_title_t*)
3915         hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3916
3917         hb_audio_config_t * audio;
3918
3919     [sender removeAllItems];
3920     [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
3921     for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
3922     {
3923         audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
3924         [[sender menu] addItemWithTitle:
3925             [NSString stringWithCString: audio->lang.description]
3926             action: NULL keyEquivalent: @""];
3927     }
3928     [sender selectItemAtIndex: 0];
3929
3930 }
3931
3932 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
3933 {
3934
3935     /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
3936     /* e.g. to find the first French track, pass in an NSString * of "Francais" */
3937     /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
3938     /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
3939
3940         if (searchPrefixString)
3941         {
3942
3943         for( int i = 0; i < [sender numberOfItems]; i++ )
3944         {
3945             /* Try to find the desired search string */
3946             if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
3947             {
3948                 [sender selectItemAtIndex: i];
3949                 return;
3950             }
3951         }
3952         /* couldn't find the string, so select the requested "search string not found" item */
3953         /* index of 0 means select the "none" item */
3954         /* index of 1 means select the first audio track */
3955         [sender selectItemAtIndex: selectIndexIfNotFound];
3956         }
3957     else
3958     {
3959         /* if no search string is provided, then select the selectIndexIfNotFound item */
3960         [sender selectItemAtIndex: selectIndexIfNotFound];
3961     }
3962
3963 }
3964 - (IBAction) audioAddAudioTrackCodecs: (id)sender
3965 {
3966     int format = [fDstFormatPopUp indexOfSelectedItem];
3967     
3968     /* setup pointers to the appropriate popups for the correct track */
3969     NSPopUpButton * audiocodecPopUp;
3970     NSPopUpButton * audiotrackPopUp;
3971     if (sender == fAudTrack1CodecPopUp)
3972     {
3973         audiotrackPopUp = fAudLang1PopUp;
3974         audiocodecPopUp = fAudTrack1CodecPopUp;
3975     }
3976     else if (sender == fAudTrack2CodecPopUp)
3977     {
3978         audiotrackPopUp = fAudLang2PopUp;
3979         audiocodecPopUp = fAudTrack2CodecPopUp;
3980     }
3981     else if (sender == fAudTrack3CodecPopUp)
3982     {
3983         audiotrackPopUp = fAudLang3PopUp;
3984         audiocodecPopUp = fAudTrack3CodecPopUp;
3985     }
3986     else
3987     {
3988         audiotrackPopUp = fAudLang4PopUp;
3989         audiocodecPopUp = fAudTrack4CodecPopUp;
3990     }
3991     
3992     [audiocodecPopUp removeAllItems];
3993     /* Make sure "None" isnt selected in the source track */
3994     if ([audiotrackPopUp indexOfSelectedItem] > 0)
3995     {
3996         [audiocodecPopUp setEnabled:YES];
3997         NSMenuItem *menuItem;
3998         /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
3999         switch( format )
4000         {
4001             case 0:
4002                 /* MP4 */
4003                 // AAC
4004                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4005                 [menuItem setTag: HB_ACODEC_FAAC];
4006                 
4007                 // AC3 Passthru
4008                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4009                 [menuItem setTag: HB_ACODEC_AC3];
4010                 break;
4011                 
4012             case 1:
4013                 /* MKV */
4014                 // AAC
4015                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4016                 [menuItem setTag: HB_ACODEC_FAAC];
4017                 // AC3 Passthru
4018                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4019                 [menuItem setTag: HB_ACODEC_AC3];
4020                 // MP3
4021                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4022                 [menuItem setTag: HB_ACODEC_LAME];
4023                 // Vorbis
4024                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4025                 [menuItem setTag: HB_ACODEC_VORBIS];
4026                 break;
4027                 
4028             case 2: 
4029                 /* AVI */
4030                 // MP3
4031                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4032                 [menuItem setTag: HB_ACODEC_LAME];
4033                 // AC3 Passthru
4034                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4035                 [menuItem setTag: HB_ACODEC_AC3];
4036                 break;
4037                 
4038             case 3:
4039                 /* OGM */
4040                 // Vorbis
4041                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4042                 [menuItem setTag: HB_ACODEC_VORBIS];
4043                 // MP3
4044                 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4045                 [menuItem setTag: HB_ACODEC_LAME];
4046                 break;
4047         }
4048         [audiocodecPopUp selectItemAtIndex:0];
4049     }
4050     else
4051     {
4052         [audiocodecPopUp setEnabled:NO];
4053     }
4054 }
4055
4056 - (IBAction) audioTrackPopUpChanged: (id) sender
4057 {
4058     /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
4059     [self audioTrackPopUpChanged: sender mixdownToUse: 0];
4060 }
4061
4062 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
4063 {
4064     
4065     /* make sure we have a selected title before continuing */
4066     if (fTitle == NULL) return;
4067     /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
4068     * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
4069     */
4070     if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
4071     {
4072         [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4073     }
4074     if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
4075     {
4076         [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4077     }
4078     if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
4079     {
4080         [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4081     }
4082     if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
4083     {
4084         [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4085     }
4086     
4087     /* Now lets make the sender the appropriate Audio Track popup from this point on */
4088     if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
4089     {
4090         sender = fAudLang1PopUp;
4091     }
4092     if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
4093     {
4094         sender = fAudLang2PopUp;
4095     }
4096     if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
4097     {
4098         sender = fAudLang3PopUp;
4099     }
4100     if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
4101     {
4102         sender = fAudLang4PopUp;
4103     }
4104     
4105     /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
4106     NSPopUpButton * mixdownPopUp;
4107     NSPopUpButton * audiocodecPopUp;
4108     NSPopUpButton * sampleratePopUp;
4109     NSPopUpButton * bitratePopUp;
4110     if (sender == fAudLang1PopUp)
4111     {
4112         mixdownPopUp = fAudTrack1MixPopUp;
4113         audiocodecPopUp = fAudTrack1CodecPopUp;
4114         sampleratePopUp = fAudTrack1RatePopUp;
4115         bitratePopUp = fAudTrack1BitratePopUp;
4116     }
4117     else if (sender == fAudLang2PopUp)
4118     {
4119         mixdownPopUp = fAudTrack2MixPopUp;
4120         audiocodecPopUp = fAudTrack2CodecPopUp;
4121         sampleratePopUp = fAudTrack2RatePopUp;
4122         bitratePopUp = fAudTrack2BitratePopUp;
4123     }
4124     else if (sender == fAudLang3PopUp)
4125     {
4126         mixdownPopUp = fAudTrack3MixPopUp;
4127         audiocodecPopUp = fAudTrack3CodecPopUp;
4128         sampleratePopUp = fAudTrack3RatePopUp;
4129         bitratePopUp = fAudTrack3BitratePopUp;
4130     }
4131     else
4132     {
4133         mixdownPopUp = fAudTrack4MixPopUp;
4134         audiocodecPopUp = fAudTrack4CodecPopUp;
4135         sampleratePopUp = fAudTrack4RatePopUp;
4136         bitratePopUp = fAudTrack4BitratePopUp;
4137     }
4138
4139     /* get the index of the selected audio Track*/
4140     int thisAudioIndex = [sender indexOfSelectedItem] - 1;
4141
4142     /* pointer for the hb_audio_s struct we will use later on */
4143     hb_audio_config_t * audio;
4144
4145     int acodec;
4146     /* check if the audio mixdown controls need their enabled state changing */
4147     [self setEnabledStateOfAudioMixdownControls:nil];
4148
4149     if (thisAudioIndex != -1)
4150     {
4151
4152         /* get the audio */
4153         audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
4154
4155         /* actually manipulate the proper mixdowns here */
4156         /* delete the previous audio mixdown options */
4157         [mixdownPopUp removeAllItems];
4158
4159         acodec = [[audiocodecPopUp selectedItem] tag];
4160
4161         if (audio != NULL)
4162         {
4163
4164             /* find out if our selected output audio codec supports mono and / or 6ch */
4165             /* we also check for an input codec of AC3 or DCA,
4166              as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
4167             /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
4168              but this may change in the future, so they are separated for flexibility */
4169             int audioCodecsSupportMono =
4170                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4171                     (acodec != HB_ACODEC_LAME);
4172             int audioCodecsSupport6Ch =
4173                     (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4174                     (acodec != HB_ACODEC_LAME);
4175             
4176             /* check for AC-3 passthru */
4177             if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4178             {
4179                 
4180             NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4181                  [NSString stringWithCString: "AC3 Passthru"]
4182                                                action: NULL keyEquivalent: @""];
4183              [menuItem setTag: HB_ACODEC_AC3];   
4184             }
4185             else
4186             {
4187                 
4188                 /* add the appropriate audio mixdown menuitems to the popupbutton */
4189                 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
4190                  so that we can reference the mixdown later */
4191                 
4192                 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
4193                 int minMixdownUsed = 0;
4194                 int maxMixdownUsed = 0;
4195                 
4196                 /* get the input channel layout without any lfe channels */
4197                 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4198                 
4199                 /* do we want to add a mono option? */
4200                 if (audioCodecsSupportMono == 1)
4201                 {
4202                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4203                                             [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
4204                                                                           action: NULL keyEquivalent: @""];
4205                     [menuItem setTag: hb_audio_mixdowns[0].amixdown];
4206                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
4207                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
4208                 }
4209                 
4210                 /* do we want to add a stereo option? */
4211                 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
4212                 /* also offer stereo if we have a stereo-or-better source */
4213                 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
4214                 {
4215                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4216                                             [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
4217                                                                           action: NULL keyEquivalent: @""];
4218                     [menuItem setTag: hb_audio_mixdowns[1].amixdown];
4219                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
4220                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
4221                 }
4222                 
4223                 /* do we want to add a dolby surround (DPL1) option? */
4224                 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
4225                 {
4226                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4227                                             [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
4228                                                                           action: NULL keyEquivalent: @""];
4229                     [menuItem setTag: hb_audio_mixdowns[2].amixdown];
4230                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
4231                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
4232                 }
4233                 
4234                 /* do we want to add a dolby pro logic 2 (DPL2) option? */
4235                 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
4236                 {
4237                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4238                                             [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
4239                                                                           action: NULL keyEquivalent: @""];
4240                     [menuItem setTag: hb_audio_mixdowns[3].amixdown];
4241                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
4242                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
4243                 }
4244                 
4245                 /* do we want to add a 6-channel discrete option? */
4246                 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
4247                 {
4248                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4249                                             [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
4250                                                                           action: NULL keyEquivalent: @""];
4251                     [menuItem setTag: hb_audio_mixdowns[4].amixdown];
4252                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
4253                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
4254                 }
4255                 
4256                 /* do we want to add an AC-3 passthrough option? */
4257                 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3) 
4258                 {
4259                     NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4260                                             [NSString stringWithCString: hb_audio_mixdowns[5].human_readable_name]
4261                                                                           action: NULL keyEquivalent: @""];
4262                     [menuItem setTag: HB_ACODEC_AC3];
4263                     if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
4264                     maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
4265                 }
4266                 
4267                 /* auto-select the best mixdown based on our saved mixdown preference */
4268                 
4269                 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
4270                 /* ultimately this should be a prefs option */
4271                 int useMixdown;
4272                 
4273                 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
4274                 if (mixdownToUse > 0)
4275                 {
4276                     useMixdown = mixdownToUse;
4277                 }
4278                 else
4279                 {
4280                     useMixdown = HB_AMIXDOWN_DOLBYPLII;
4281                 }
4282                 
4283                 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
4284                 if (useMixdown > maxMixdownUsed)
4285                 { 
4286                     useMixdown = maxMixdownUsed;
4287                 }
4288                 
4289                 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
4290                 if (useMixdown < minMixdownUsed)
4291                 { 
4292                     useMixdown = minMixdownUsed;
4293                 }
4294                 
4295                 /* select the (possibly-amended) preferred mixdown */
4296                 [mixdownPopUp selectItemWithTag: useMixdown];
4297
4298             }
4299             /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
4300              * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
4301              * other containers.
4302              */
4303             if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
4304             {
4305                 /* If we are using the avi container, we select MP3 as there is no aac available*/
4306                 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
4307                 {
4308                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
4309                 }
4310                 else
4311                 {
4312                     [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
4313                 }
4314             }
4315             /* Setup our samplerate and bitrate popups we will need based on mixdown */
4316             [self audioTrackMixdownChanged: mixdownPopUp];             
4317         }
4318     
4319     }
4320     if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
4321     {
4322         [self autoSetM4vExtension: sender];
4323         [self shouldEnableHttpMp4CheckBox: sender];
4324     }
4325 }
4326
4327 - (IBAction) audioTrackMixdownChanged: (id) sender
4328 {
4329     
4330     int acodec;
4331     /* setup pointers to all of the other audio track controls
4332     * we will need later
4333     */
4334     NSPopUpButton * mixdownPopUp;
4335     NSPopUpButton * sampleratePopUp;
4336     NSPopUpButton * bitratePopUp;
4337     NSPopUpButton * audiocodecPopUp;
4338     NSPopUpButton * audiotrackPopUp;
4339     NSSlider * drcSlider;
4340     NSTextField * drcField;
4341     if (sender == fAudTrack1MixPopUp)
4342     {
4343         audiotrackPopUp = fAudLang1PopUp;
4344         audiocodecPopUp = fAudTrack1CodecPopUp;
4345         mixdownPopUp = fAudTrack1MixPopUp;
4346         sampleratePopUp = fAudTrack1RatePopUp;
4347         bitratePopUp = fAudTrack1BitratePopUp;
4348         drcSlider = fAudTrack1DrcSlider;
4349         drcField = fAudTrack1DrcField;
4350     }
4351     else if (sender == fAudTrack2MixPopUp)
4352     {
4353         audiotrackPopUp = fAudLang2PopUp;
4354         audiocodecPopUp = fAudTrack2CodecPopUp;
4355         mixdownPopUp = fAudTrack2MixPopUp;
4356         sampleratePopUp = fAudTrack2RatePopUp;
4357         bitratePopUp = fAudTrack2BitratePopUp;
4358         drcSlider = fAudTrack2DrcSlider;
4359         drcField = fAudTrack2DrcField;
4360     }
4361     else if (sender == fAudTrack3MixPopUp)
4362     {
4363         audiotrackPopUp = fAudLang3PopUp;
4364         audiocodecPopUp = fAudTrack3CodecPopUp;
4365         mixdownPopUp = fAudTrack3MixPopUp;
4366         sampleratePopUp = fAudTrack3RatePopUp;
4367         bitratePopUp = fAudTrack3BitratePopUp;
4368         drcSlider = fAudTrack3DrcSlider;
4369         drcField = fAudTrack3DrcField;
4370     }
4371     else
4372     {
4373         audiotrackPopUp = fAudLang4PopUp;
4374         audiocodecPopUp = fAudTrack4CodecPopUp;
4375         mixdownPopUp = fAudTrack4MixPopUp;
4376         sampleratePopUp = fAudTrack4RatePopUp;
4377         bitratePopUp = fAudTrack4BitratePopUp;
4378         drcSlider = fAudTrack4DrcSlider;
4379         drcField = fAudTrack4DrcField;
4380     }
4381     acodec = [[audiocodecPopUp selectedItem] tag];
4382     /* storage variable for the min and max bitrate allowed for this codec */
4383     int minbitrate;
4384     int maxbitrate;
4385     
4386     switch( acodec )
4387     {
4388         case HB_ACODEC_FAAC:
4389             /* check if we have a 6ch discrete conversion in either audio track */
4390             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
4391             {
4392                 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
4393                 minbitrate = 32;
4394                 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
4395                 maxbitrate = 384;
4396                 break;
4397             }
4398             else
4399             {
4400                 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
4401                 minbitrate = 32;
4402                 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
4403                 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
4404                 maxbitrate = 160;
4405                 break;
4406             }
4407             
4408             case HB_ACODEC_LAME:
4409             /* Lame is happy using our min bitrate of 32 kbps */
4410             minbitrate = 32;
4411             /* Lame won't encode if the bitrate is higher than 320 kbps */
4412             maxbitrate = 320;
4413             break;
4414             
4415             case HB_ACODEC_VORBIS:
4416             if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
4417             {
4418                 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
4419                 minbitrate = 192;
4420                 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
4421                 maxbitrate = 384;
4422                 break;
4423             }
4424             else
4425             {
4426                 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
4427                 minbitrate = 48;
4428                 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
4429                 maxbitrate = 384;
4430                 break;
4431             }
4432             
4433             default:
4434             /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
4435             minbitrate = 32;
4436             maxbitrate = 384;
4437             
4438     }
4439     
4440     /* make sure we have a selected title before continuing */
4441     if (fTitle == NULL) return;
4442     /* get the audio so we can find out what input rates are*/
4443     hb_audio_config_t * audio;
4444     audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
4445     int inputbitrate = audio->in.bitrate / 1000;
4446     int inputsamplerate = audio->in.samplerate;
4447     
4448     if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3)
4449     {
4450         [bitratePopUp removeAllItems];
4451         
4452         for( int i = 0; i < hb_audio_bitrates_count; i++ )
4453         {
4454             if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
4455             {
4456                 /* add a new menuitem for this bitrate */
4457                 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
4458                                         [NSString stringWithCString: hb_audio_bitrates[i].string]
4459                                                                       action: NULL keyEquivalent: @""];
4460                 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
4461                 [menuItem setTag: hb_audio_bitrates[i].rate];
4462             }
4463         }
4464         
4465         /* select the default bitrate (but use 384 for 6-ch AAC) */
4466         if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
4467         {
4468             [bitratePopUp selectItemWithTag: 384];
4469         }
4470         else
4471         {
4472             [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
4473         }
4474     }
4475     /* populate and set the sample rate popup */
4476     /* Audio samplerate */
4477     [sampleratePopUp removeAllItems];
4478     /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
4479     NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
4480     [menuItem setTag: inputsamplerate];
4481     
4482     for( int i = 0; i < hb_audio_rates_count; i++ )
4483     {
4484         NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
4485                                 [NSString stringWithCString: hb_audio_rates[i].string]
4486                                                                  action: NULL keyEquivalent: @""];
4487         [menuItem setTag: hb_audio_rates[i].rate];
4488     }
4489     /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
4490     * and there is no compelling reason to use anything else as default, though the users default
4491     * preset will likely override any setting chosen here.
4492     */
4493     [sampleratePopUp selectItemWithTag: inputsamplerate];
4494     
4495     
4496     /* Since AC3 Pass Thru uses the input ac3 bitrate and sample rate, we get the input tracks
4497     * bitrate and dispay it in the bitrate popup even though libhb happily ignores any bitrate input from
4498     * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
4499     */
4500     if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3)
4501     {
4502         
4503         /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
4504         [bitratePopUp removeAllItems];
4505         NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
4506                                 [NSString stringWithFormat:@"%d", inputbitrate]
4507                                                               action: NULL keyEquivalent: @""];
4508         [menuItem setTag: inputbitrate];
4509         /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
4510         [bitratePopUp setEnabled: NO];
4511         [sampleratePopUp setEnabled: NO];
4512         
4513         [drcSlider setFloatValue: 1.00];
4514         [self audioDRCSliderChanged: drcSlider];
4515         [drcSlider setEnabled: NO];
4516         [drcField setEnabled: NO];
4517     }
4518     else
4519     {
4520         [sampleratePopUp setEnabled: YES];
4521         [bitratePopUp setEnabled: YES];
4522         [drcSlider setEnabled: YES];
4523         [drcField setEnabled: YES];
4524     }
4525     
4526 }
4527
4528 - (IBAction) audioDRCSliderChanged: (id) sender
4529 {
4530     NSSlider * drcSlider;
4531     NSTextField * drcField;
4532     if (sender == fAudTrack1DrcSlider)
4533     {
4534         drcSlider = fAudTrack1DrcSlider;
4535         drcField = fAudTrack1DrcField;
4536     }
4537     else if (sender == fAudTrack2DrcSlider)
4538     {
4539         drcSlider = fAudTrack2DrcSlider;
4540         drcField = fAudTrack2DrcField;
4541     }
4542     else if (sender == fAudTrack3DrcSlider)
4543     {
4544         drcSlider = fAudTrack3DrcSlider;
4545         drcField = fAudTrack3DrcField;
4546     }
4547     else
4548     {
4549         drcSlider = fAudTrack4DrcSlider;
4550         drcField = fAudTrack4DrcField;
4551     }
4552     [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
4553     /* For now, do not call this until we have an intelligent way to determine audio track selections
4554     * compared to presets
4555     */
4556     //[self customSettingUsed: sender];
4557 }
4558
4559 - (IBAction) subtitleSelectionChanged: (id) sender
4560 {
4561         if ([fSubPopUp indexOfSelectedItem] == 0)
4562         {
4563         [fSubForcedCheck setState: NSOffState];
4564         [fSubForcedCheck setEnabled: NO];       
4565         }
4566         else
4567         {
4568         [fSubForcedCheck setEnabled: YES];      
4569         }
4570         
4571 }
4572
4573
4574
4575
4576 #pragma mark -
4577 #pragma mark Open New Windows
4578
4579 - (IBAction) openHomepage: (id) sender
4580 {
4581     [[NSWorkspace sharedWorkspace] openURL: [NSURL
4582         URLWithString:@"http://handbrake.fr/"]];
4583 }
4584
4585 - (IBAction) openForums: (id) sender
4586 {
4587     [[NSWorkspace sharedWorkspace] openURL: [NSURL
4588         URLWithString:@"http://handbrake.fr/forum/"]];
4589 }
4590 - (IBAction) openUserGuide: (id) sender
4591 {
4592     [[NSWorkspace sharedWorkspace] openURL: [NSURL
4593         URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
4594 }
4595
4596 /**
4597  * Shows debug output window.
4598  */
4599 - (IBAction)showDebugOutputPanel:(id)sender
4600 {
4601     [outputPanel showOutputPanel:sender];
4602 }
4603
4604 /**
4605  * Shows preferences window.
4606  */
4607 - (IBAction) showPreferencesWindow: (id) sender
4608 {
4609     NSWindow * window = [fPreferencesController window];
4610     if (![window isVisible])
4611         [window center];
4612
4613     [window makeKeyAndOrderFront: nil];
4614 }
4615
4616 /**
4617  * Shows queue window.
4618  */
4619 - (IBAction) showQueueWindow:(id)sender
4620 {
4621     [fQueueController showQueueWindow:sender];
4622 }
4623
4624
4625 - (IBAction) toggleDrawer:(id)sender {
4626     [fPresetDrawer toggle:self];
4627 }
4628
4629 /**
4630  * Shows Picture Settings Window.
4631  */
4632
4633 - (IBAction) showPicturePanel: (id) sender
4634 {
4635         hb_list_t  * list  = hb_get_titles( fHandle );
4636     hb_title_t * title = (hb_title_t *) hb_list_item( list,
4637             [fSrcTitlePopUp indexOfSelectedItem] );
4638     [fPictureController showPanelInWindow:fWindow forTitle:title];
4639 }
4640
4641 #pragma mark -
4642 #pragma mark Preset Outline View Methods
4643 #pragma mark - Required
4644 /* These are required by the NSOutlineView Datasource Delegate */
4645 /* We use this to deterimine children of an item */
4646 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
4647 {
4648 if (item == nil)
4649         return [UserPresets objectAtIndex:index];
4650     
4651     // We are only one level deep, so we can't be asked about children
4652     NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
4653     return nil;
4654 }
4655 /* We use this to determine if an item should be expandable */
4656 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
4657 {
4658
4659     /* For now, we maintain one level, so set to no
4660     * when nested, we set to yes for any preset "folders"
4661     */
4662     return NO;
4663
4664 }
4665 /* used to specify the number of levels to show for each item */
4666 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
4667 {
4668     /* currently use no levels to test outline view viability */
4669     if (item == nil)
4670         return [UserPresets count];
4671     else
4672         return 0;
4673 }
4674 /* Used to tell the outline view which information is to be displayed per item */
4675 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
4676 {
4677         /* We have two columns right now, icon and PresetName */
4678         
4679     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
4680     {
4681         return [item objectForKey:@"PresetName"];
4682     }
4683     else
4684     {
4685         return @"something";
4686     }
4687 }
4688
4689 #pragma mark - Added Functionality (optional)
4690 /* Use to customize the font and display characteristics of the title cell */
4691 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
4692 {
4693     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
4694     {
4695         NSDictionary *userPresetDict = item;
4696         NSFont *txtFont;
4697         NSColor *fontColor;
4698         NSColor *shadowColor;
4699         txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
4700         /*check to see if its a selected row */
4701         if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
4702         {
4703             
4704             fontColor = [NSColor blackColor];
4705             shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
4706         }
4707         else
4708         {
4709             if ([[userPresetDict objectForKey:@"Type"] intValue] == 0)
4710             {
4711                 fontColor = [NSColor blueColor];
4712             }
4713             else // User created preset, use a black font
4714             {
4715                 fontColor = [NSColor blackColor];
4716             }
4717             shadowColor = nil;
4718         }
4719         /* We use Bold Text for the HB Default */
4720         if ([[userPresetDict objectForKey:@"Default"] intValue] == 1)// 1 is HB default
4721         {
4722             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
4723         }
4724         /* We use Bold Text for the User Specified Default */
4725         if ([[userPresetDict objectForKey:@"Default"] intValue] == 2)// 2 is User default
4726         {
4727             txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
4728         }
4729         
4730         
4731         [cell setTextColor:fontColor];
4732         [cell setFont:txtFont];
4733         
4734     }
4735 }
4736
4737 /* We use this to edit the name field in the outline view */
4738 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
4739 {
4740     if ([[tableColumn identifier] isEqualToString:@"PresetName"])
4741     {
4742         id theRecord;
4743         
4744         theRecord = item;
4745         [theRecord setObject:object forKey:@"PresetName"];
4746         
4747         [self sortPresets];
4748         
4749         [fPresetsOutlineView reloadData];
4750         /* We save all of the preset data here */
4751         [self savePreset];
4752     }
4753 }
4754 /* We use this to provide tooltips for the items in the presets outline view */
4755 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
4756 {
4757     //if ([[tc identifier] isEqualToString:@"PresetName"])
4758     //{
4759         /* initialize the tooltip contents variable */
4760         NSString *loc_tip;
4761         /* if there is a description for the preset, we show it in the tooltip */
4762         if ([item objectForKey:@"PresetDescription"])
4763         {
4764             loc_tip = [item objectForKey:@"PresetDescription"];
4765             return (loc_tip);
4766         }
4767         else
4768         {
4769             loc_tip = @"No description available";
4770         }
4771         return (loc_tip);
4772     //}
4773 }
4774
4775 #pragma mark -
4776 #pragma mark Preset Outline View Methods (dragging related)
4777
4778
4779 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
4780 {
4781         // Dragging is only allowed for custom presets.
4782         if ([[[UserPresets objectAtIndex:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
4783     {
4784         return NO;
4785     }
4786     // Don't retain since this is just holding temporaral drag information, and it is
4787     //only used during a drag!  We could put this in the pboard actually.
4788     fDraggedNodes = items;
4789     // Provide data for our custom type, and simple NSStrings.
4790     [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
4791     
4792     // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
4793     [pboard setData:[NSData data] forType:DragDropSimplePboardType]; 
4794     
4795     return YES;
4796 }
4797
4798 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
4799 {
4800         // Don't allow dropping ONTO an item since they can't really contain any children.
4801     
4802     BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
4803     if (isOnDropTypeProposal)
4804         return NSDragOperationNone;
4805     
4806     
4807         // Don't allow dropping INTO an item since they can't really contain any children as of yet.
4808         
4809     if (item != nil)
4810         {
4811                 index = [fPresetsOutlineView rowForItem: item] + 1;
4812                 item = nil;
4813         }
4814     
4815     // Don't allow dropping into the Built In Presets.
4816     if (index < presetCurrentBuiltInCount)
4817     {
4818         return NSDragOperationNone;
4819         index = MAX (index, presetCurrentBuiltInCount);
4820         }
4821         
4822     [outlineView setDropItem:item dropChildIndex:index];
4823     return NSDragOperationGeneric;
4824 }
4825
4826
4827
4828 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
4829 {
4830     NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
4831     
4832     id obj;
4833     NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
4834     while (obj = [enumerator nextObject])
4835     {
4836         [moveItems addIndex:[UserPresets indexOfObject:obj]];
4837     }
4838     // Successful drop, lets rearrange the view and save it all
4839     [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
4840     [fPresetsOutlineView reloadData];
4841     [self savePreset];
4842     return YES;
4843 }
4844
4845 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
4846 {
4847     unsigned index = [indexSet lastIndex];
4848     unsigned aboveInsertIndexCount = 0;
4849     
4850     while (index != NSNotFound)
4851     {
4852         unsigned removeIndex;
4853         
4854         if (index >= insertIndex)
4855         {
4856             removeIndex = index + aboveInsertIndexCount;
4857             aboveInsertIndexCount++;
4858         }
4859         else
4860         {
4861             removeIndex = index;
4862             insertIndex--;
4863         }
4864         
4865         id object = [[array objectAtIndex:removeIndex] retain];
4866         [array removeObjectAtIndex:removeIndex];
4867         [array insertObject:object atIndex:insertIndex];
4868         [object release];
4869         
4870         index = [indexSet indexLessThanIndex:index];
4871     }
4872 }
4873
4874
4875
4876 #pragma mark - Functional Preset NSOutlineView Methods
4877
4878 - (IBAction)selectPreset:(id)sender
4879 {
4880
4881     if ([fPresetsOutlineView selectedRow] >= 0)
4882     {
4883         chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
4884         /* we set the preset display field in main window here */
4885         [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
4886         if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
4887         {
4888             [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
4889         }
4890         else
4891         {
4892             [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
4893         }
4894         /* File Format */
4895         [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
4896         [self formatPopUpChanged:nil];
4897
4898         /* Chapter Markers*/
4899         [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
4900         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
4901         [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
4902         /* Mux mp4 with http optimization */
4903         [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
4904
4905         /* Video encoder */
4906         /* We set the advanced opt string here if applicable*/
4907         [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
4908         /* We use a conditional to account for the new x264 encoder dropdown as well as presets made using legacy x264 settings*/
4909         if ([[chosenPreset objectForKey:@"VideoEncoder"] isEqualToString:@"x264 (h.264 Main)"] ||
4910             [[chosenPreset objectForKey:@"VideoEncoder"] isEqualToString:@"x264 (h.264 iPod)"] ||
4911             [[chosenPreset objectForKey:@"VideoEncoder"] isEqualToString:@"x264"])
4912         {
4913             [fVidEncoderPopUp selectItemWithTitle:@"H.264 (x264)"];
4914             /* special case for legacy preset to check the new fDstMp4HttpOptFileCheck checkbox to set the ipod atom */
4915             if ([[chosenPreset objectForKey:@"VideoEncoder"] isEqualToString:@"x264 (h.264 iPod)"])
4916             {
4917                 [fDstMp4iPodFileCheck setState:NSOnState];
4918                 /* We also need to add "level=30:" to the advanced opts string to set the correct level for the iPod when
4919                  encountering a legacy preset as it used to be handled separately from the opt string*/
4920                 [fAdvancedOptions setOptions:[@"level=30:" stringByAppendingString:[fAdvancedOptions optionsString]]];
4921             }
4922             else
4923             {
4924                 [fDstMp4iPodFileCheck setState:NSOffState];
4925             }
4926         }
4927         else if ([[chosenPreset objectForKey:@"VideoEncoder"] isEqualToString:@"FFmpeg"])
4928         {
4929             [fVidEncoderPopUp selectItemWithTitle:@"MPEG-4 (FFmpeg)"];
4930         }
4931         else if ([[chosenPreset objectForKey:@"VideoEncoder"] isEqualToString:@"XviD"])
4932         {
4933             [fVidEncoderPopUp selectItemWithTitle:@"MPEG-4 (XviD)"];
4934         }
4935         else
4936         {
4937             [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
4938         }
4939
4940         /* Lets run through the following functions to get variables set there */
4941         [self videoEncoderPopUpChanged:nil];
4942         /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
4943         [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
4944         [self calculateBitrate:nil];
4945
4946         /* Video quality */
4947         [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
4948
4949         [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
4950         [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
4951         [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
4952
4953         [self videoMatrixChanged:nil];
4954
4955         /* Video framerate */
4956         /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
4957          detected framerate in the fVidRatePopUp so we use index 0*/
4958         if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
4959         {
4960             [fVidRatePopUp selectItemAtIndex: 0];
4961         }
4962         else
4963         {
4964             [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
4965         }
4966
4967         /* GrayScale */
4968         [fVidGrayscaleCheck setState:[[chosenPreset objectForKey:@"VideoGrayScale"] intValue]];
4969
4970         /* 2 Pass Encoding */
4971         [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
4972         [self twoPassCheckboxChanged:nil];
4973         /* Turbo 1st pass for 2 Pass Encoding */
4974         [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
4975
4976         /*Audio*/
4977         if ([chosenPreset objectForKey:@"FileCodecs"])
4978         {
4979             /* We need to handle the audio codec popup by determining what was chosen from the deprecated Codecs PopUp for past presets*/
4980             if ([[chosenPreset objectForKey:@"FileCodecs"] isEqualToString: @"AVC/H.264 Video / AAC + AC3 Audio"])
4981             {
4982                 /* We need to address setting languages etc. here in the new multi track audio panel */
4983                 /* Track One set here */
4984                 /*for track one though a track should be selected but lets check here anyway and use track one if its not.*/
4985                 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4986                 {
4987                     [fAudLang1PopUp selectItemAtIndex: 1];
4988                     [self audioTrackPopUpChanged: fAudLang1PopUp];
4989                 }
4990                 [fAudTrack1CodecPopUp selectItemWithTitle: @"AAC (faac)"];
4991                 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4992                 /* Track Two, set source same as track one */
4993                 [fAudLang2PopUp selectItemAtIndex: [fAudLang1PopUp indexOfSelectedItem]];
4994                 [self audioTrackPopUpChanged: fAudLang2PopUp];
4995                 [fAudTrack2CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
4996                 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4997             }
4998             else if ([[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"MPEG-4 Video / AAC Audio"] ||
4999                      [[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"AVC/H.264 Video / AAC Audio"])
5000             {
5001                 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5002                 {
5003                     [fAudTrack1CodecPopUp selectItemWithTitle: @"AAC (faac)"];
5004                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5005                 }
5006                 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5007                 {
5008                     [fAudTrack2CodecPopUp selectItemWithTitle: @"AAC (faac)"];
5009                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5010                 }
5011                 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5012                 {
5013                     [fAudTrack3CodecPopUp selectItemWithTitle: @"AAC (faac)"];
5014                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5015                 }
5016                 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5017                 {
5018                     [fAudTrack4CodecPopUp selectItemWithTitle: @"AAC (faac)"];
5019                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5020                 }
5021             }
5022             else if ([[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"MPEG-4 Video / AC-3 Audio"] ||
5023                      [[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"AVC/H.264 Video / AC-3 Audio"])
5024             {
5025                 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5026                 {
5027                     [fAudTrack1CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
5028                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5029                 }
5030                 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5031                 {
5032                     [fAudTrack2CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
5033                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5034                 }
5035                 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5036                 {
5037                     [fAudTrack3CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
5038                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5039                 }
5040                 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5041                 {
5042                     [fAudTrack4CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
5043                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5044                 }
5045             }
5046             else if ([[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"MPEG-4 Video / MP3 Audio"] ||
5047                      [[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"AVC/H.264 Video / MP3 Audio"])
5048             {
5049                 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5050                 {
5051                     [fAudTrack1CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
5052                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5053                 }
5054                 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5055                 {
5056                     [fAudTrack2CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
5057                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5058                 }
5059                 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5060                 {
5061                     [fAudTrack3CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
5062                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5063                 }
5064                 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5065                 {
5066                     [fAudTrack4CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
5067                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5068                 }
5069             }
5070             else if ([[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"MPEG-4 Video / Vorbis Audio"])
5071             {
5072                 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5073                 {
5074                     [fAudTrack1CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
5075                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5076                 }
5077                 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5078                 {
5079                     [fAudTrack2CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
5080                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5081                 }
5082                 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5083                 {
5084                     [fAudTrack3CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
5085                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5086                 }
5087                 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5088                 {
5089                     [fAudTrack4CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
5090                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5091                 }
5092             }
5093             /* 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
5094             * UNLESS the CodecPopUp is AC3 in which case the preset values are ignored in favor of rates set in audioTrackMixdownChanged*/
5095             if ([chosenPreset objectForKey:@"AudioSampleRate"])
5096             {
5097                 if ([fAudLang1PopUp indexOfSelectedItem] > 0 && [fAudTrack1CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
5098                 {
5099                     [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioSampleRate"]];
5100                     [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioBitRate"]];
5101                 }
5102                 if ([fAudLang2PopUp indexOfSelectedItem] > 0 && [fAudTrack2CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
5103                 {
5104                     [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioSampleRate"]];
5105                     [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioBitRate"]];
5106                 }
5107                 if ([fAudLang3PopUp indexOfSelectedItem] > 0 && [fAudTrack3CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
5108                 {
5109                     [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioSampleRate"]];
5110                     [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioBitRate"]];
5111                 }
5112                 if ([fAudLang4PopUp indexOfSelectedItem] > 0 && [fAudTrack4CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
5113                 {
5114                     [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioSampleRate"]];
5115                     [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"AudioBitRate"]];
5116                 }
5117             }
5118             /* We detect here if we have the old DRC Slider and if so we apply it to the existing four tracks if chosen */
5119             if ([chosenPreset objectForKey:@"AudioDRCSlider"])
5120             {
5121                 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5122                 {
5123                     [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"AudioDRCSlider"] floatValue]];
5124                     [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5125                 }
5126                 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5127                 {
5128                     [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"AudioDRCSlider"] floatValue]];
5129                     [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5130                 }
5131                 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5132                 {
5133                     [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"AudioDRCSlider"] floatValue]];
5134                     [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5135                 }
5136                 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5137                 {
5138                     [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"AudioDRCSlider"] floatValue]];
5139                     [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5140                 }
5141             }
5142         }
5143         else // since there was no codecs key in the preset we know we can use new multi-audio track presets
5144         {
5145             if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
5146             {
5147                 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5148                 {
5149                     [fAudLang1PopUp selectItemAtIndex: 1];
5150                 }
5151                 [self audioTrackPopUpChanged: fAudLang1PopUp];
5152                 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
5153                 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5154                 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
5155                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5156                  * mixdown*/
5157                 if  ([fAudTrack1MixPopUp selectedItem] == nil)
5158                 {
5159                     [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5160                 }
5161                 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
5162                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5163                 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
5164                 {
5165                     [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
5166                 }
5167                 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
5168                 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5169             }
5170             if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
5171             {
5172                 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5173                 {
5174                     [fAudLang2PopUp selectItemAtIndex: 1];
5175                 }
5176                 [self audioTrackPopUpChanged: fAudLang2PopUp];
5177                 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
5178                 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5179                 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
5180                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5181                  * mixdown*/
5182                 if  ([fAudTrack2MixPopUp selectedItem] == nil)
5183                 {
5184                     [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5185                 }
5186                 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
5187                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5188                 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
5189                 {
5190                     [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
5191                 }
5192                 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
5193                 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5194             }
5195             if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
5196             {
5197                 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5198                 {
5199                     [fAudLang3PopUp selectItemAtIndex: 1];
5200                 }
5201                 [self audioTrackPopUpChanged: fAudLang3PopUp];
5202                 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
5203                 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5204                 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
5205                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5206                  * mixdown*/
5207                 if  ([fAudTrack3MixPopUp selectedItem] == nil)
5208                 {
5209                     [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5210                 }
5211                 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
5212                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5213                 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
5214                 {
5215                     [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
5216                 }
5217                 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
5218                 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5219             }
5220             if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
5221             {
5222                 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5223                 {
5224                     [fAudLang4PopUp selectItemAtIndex: 1];
5225                 }
5226                 [self audioTrackPopUpChanged: fAudLang4PopUp];
5227                 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
5228                 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5229                 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
5230                 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5231                  * mixdown*/
5232                 if  ([fAudTrack4MixPopUp selectedItem] == nil)
5233                 {
5234                     [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5235                 }
5236                 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
5237                 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5238                 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
5239                 {
5240                     [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
5241                 }
5242                 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
5243                 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5244             }
5245
5246
5247         }
5248
5249         /* 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
5250          * duplicate any code for legacy presets.*/
5251         /* First we handle the legacy Codecs crazy AVC/H.264 Video / AAC + AC3 Audio atv hybrid */
5252         if ([chosenPreset objectForKey:@"FileCodecs"] && [[chosenPreset objectForKey:@"FileCodecs"] isEqualToString:@"AVC/H.264 Video / AAC + AC3 Audio"])
5253         {
5254             [fAudLang3PopUp selectItemAtIndex: 0];
5255             [self audioTrackPopUpChanged: fAudLang3PopUp];
5256             [fAudLang4PopUp selectItemAtIndex: 0];
5257             [self audioTrackPopUpChanged: fAudLang4PopUp];
5258         }
5259         else
5260         {
5261             if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
5262             {
5263                 [fAudLang2PopUp selectItemAtIndex: 0];
5264                 [self audioTrackPopUpChanged: fAudLang2PopUp];
5265             }
5266             if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
5267             {
5268                 [fAudLang3PopUp selectItemAtIndex: 0];
5269                 [self audioTrackPopUpChanged: fAudLang3PopUp];
5270             }
5271             if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
5272             {
5273                 [fAudLang4PopUp selectItemAtIndex: 0];
5274                 [self audioTrackPopUpChanged: fAudLang4PopUp];
5275             }
5276         }
5277
5278         /*Subtitles*/
5279         [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
5280         /* Forced Subtitles */
5281         [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
5282
5283         /* Picture Settings */
5284         /* Note: objectForKey:@"UsesPictureSettings" now refers to picture size, this encompasses:
5285          * height, width, keep ar, anamorphic and crop settings.
5286          * picture filters are now handled separately.
5287          * We will be able to actually change the key names for legacy preset keys when preset file
5288          * update code is done. But for now, lets hang onto the old legacy key name for backwards compatibility.
5289          */
5290         /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None" 
5291          * and the preset completely ignores any picture sizing values in the preset.
5292          */
5293         if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] > 0)
5294         {
5295             hb_job_t * job = fTitle->job;
5296             /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
5297             if ([[chosenPreset objectForKey:@"UsesPictureSettings"]  intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"]  intValue] == 1)
5298             {
5299                 /* Use Max Picture settings for whatever the dvd is.*/
5300                 [self revertPictureSizeToMax:nil];
5301                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
5302                 if (job->keep_ratio == 1)
5303                 {
5304                     hb_fix_aspect( job, HB_KEEP_WIDTH );
5305                     if( job->height > fTitle->height )
5306                     {
5307                         job->height = fTitle->height;
5308                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
5309                     }
5310                 }
5311                 job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
5312             }
5313             else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
5314             {
5315                 /* we check to make sure the presets width/height does not exceed the sources width/height */
5316                 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"]  intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"]  intValue])
5317                 {
5318                     /* if so, then we use the sources height and width to avoid scaling up */
5319                     job->width = fTitle->width;
5320                     job->height = fTitle->height;
5321                 }
5322                 else // source width/height is >= the preset height/width
5323                 {
5324                     /* we can go ahead and use the presets values for height and width */
5325                     job->width = [[chosenPreset objectForKey:@"PictureWidth"]  intValue];
5326                     job->height = [[chosenPreset objectForKey:@"PictureHeight"]  intValue];
5327                 }
5328                 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"]  intValue];
5329                 if (job->keep_ratio == 1)
5330                 {
5331                     hb_fix_aspect( job, HB_KEEP_WIDTH );
5332                     if( job->height > fTitle->height )
5333                     {
5334                         job->height = fTitle->height;
5335                         hb_fix_aspect( job, HB_KEEP_HEIGHT );
5336                     }
5337                 }
5338                 job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"]  intValue];
5339                 
5340                 
5341                 /* If Cropping is set to custom, then recall all four crop values from
5342                  when the preset was created and apply them */
5343                 if ([[chosenPreset objectForKey:@"PictureAutoCrop"]  intValue] == 0)
5344                 {
5345                     [fPictureController setAutoCrop:NO];
5346                     
5347                     /* Here we use the custom crop values saved at the time the preset was saved */
5348                     job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"]  intValue];
5349                     job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"]  intValue];
5350                     job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"]  intValue];
5351                     job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"]  intValue];
5352                     
5353                 }
5354                 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
5355                 {
5356                     [fPictureController setAutoCrop:YES];
5357                     /* Here we use the auto crop values determined right after scan */
5358                     job->crop[0] = AutoCropTop;
5359                     job->crop[1] = AutoCropBottom;
5360                     job->crop[2] = AutoCropLeft;
5361                     job->crop[3] = AutoCropRight;
5362                     
5363                 }
5364                 /* If the preset has no objectForKey:@"UsesPictureFilters", then we know it is a legacy preset
5365                  * and handle the filters here as before.
5366                  * NOTE: This should be removed when the update presets code is done as we can be assured that legacy
5367                  * presets are updated to work properly with new keys.
5368                  */
5369                 if (![chosenPreset objectForKey:@"UsesPictureFilters"])
5370                 {
5371                     /* Filters */
5372                     /* Deinterlace */
5373                     if ([chosenPreset objectForKey:@"PictureDeinterlace"])
5374                     {
5375                         /* We check to see if the preset used the past fourth "Slowest" deinterlaceing and set that to "Slower
5376                          * since we no longer have a fourth "Slowest" deinterlacing due to the mcdeint bug */
5377                         if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
5378                         {
5379                             [fPictureController setDeinterlace:3];
5380                         }
5381                         else
5382                         {
5383                             
5384                             [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
5385                         }
5386                     }
5387                     else
5388                     {
5389                         [fPictureController setDeinterlace:0];
5390                     }
5391                     /* VFR */
5392                     if ([[chosenPreset objectForKey:@"VFR"] intValue] == 1)
5393                     {
5394                         [fPictureController setVFR:[[chosenPreset objectForKey:@"VFR"] intValue]];
5395                     }
5396                     else
5397                     {
5398                         [fPictureController setVFR:0];
5399                     }
5400                     /* Detelecine */
5401                     if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
5402                     {
5403                         [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
5404                     }
5405                     else
5406                     {
5407                         [fPictureController setDetelecine:0];
5408                     }
5409                     /* Denoise */
5410                     if ([chosenPreset objectForKey:@"PictureDenoise"])
5411                     {
5412                         [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
5413                     }
5414                     else
5415                     {
5416                         [fPictureController setDenoise:0];
5417                     }   
5418                     /* Deblock */
5419                     if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
5420                     {
5421                         [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
5422                     }
5423                     else
5424                     {
5425                         [fPictureController setDeblock:0];
5426                     }
5427
5428                    [self calculatePictureSizing:nil];
5429                 }
5430
5431             }
5432
5433
5434         }
5435         /* If the preset has an objectForKey:@"UsesPictureFilters", then we know it is a newer style filters preset
5436          * and handle the filters here depending on whether or not the preset specifies applying the filter.
5437          */
5438         if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"]  intValue] > 0)
5439         {
5440             /* Filters */
5441             /* Deinterlace */
5442             if ([chosenPreset objectForKey:@"PictureDeinterlace"])
5443             {
5444                 /* We check to see if the preset used the past fourth "Slowest" deinterlaceing and set that to "Slower
5445                  * since we no longer have a fourth "Slowest" deinterlacing due to the mcdeint bug */
5446                 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
5447                 {
5448                     [fPictureController setDeinterlace:3];
5449                 }
5450                 else
5451                 {
5452                     [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
5453                 }
5454             }
5455             else
5456             {
5457                 [fPictureController setDeinterlace:0];
5458             }
5459             /* VFR */
5460             if ([[chosenPreset objectForKey:@"VFR"] intValue] == 1)
5461             {
5462                 [fPictureController setVFR:[[chosenPreset objectForKey:@"VFR"] intValue]];
5463             }
5464             else
5465             {
5466                 [fPictureController setVFR:0];
5467             }
5468             /* Detelecine */
5469             if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
5470             {
5471                 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
5472             }
5473             else
5474             {
5475                 [fPictureController setDetelecine:0];
5476             }
5477             /* Denoise */
5478             if ([chosenPreset objectForKey:@"PictureDenoise"])
5479             {
5480                 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
5481             }
5482             else
5483             {
5484                 [fPictureController setDenoise:0];
5485             }   
5486             /* Deblock */
5487             if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
5488             {
5489                 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
5490             }
5491             else
5492             {
5493                 [fPictureController setDeblock:0];
5494             }
5495             /* Decomb */
5496             /* Even though we currently allow for a custom setting for decomb, ultimately it will only have Off and
5497              * Default so we just pay attention to anything greater than 0 as 1 (Default). 0 is Off. */
5498             if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
5499             {
5500                 [fPictureController setDecomb:1];
5501             }
5502             else
5503             {
5504                 [fPictureController setDecomb:0];
5505             }
5506         }
5507         [self calculatePictureSizing:nil];
5508     }
5509 }
5510
5511
5512 #pragma mark -
5513 #pragma mark Manage Presets
5514
5515 - (void) loadPresets {
5516         /* We declare the default NSFileManager into fileManager */
5517         NSFileManager * fileManager = [NSFileManager defaultManager];
5518         /*We define the location of the user presets file */
5519     UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
5520         UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
5521     /* We check for the presets.plist */
5522         if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
5523         {
5524                 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
5525         }
5526
5527         UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
5528         if (nil == UserPresets)
5529         {
5530                 UserPresets = [[NSMutableArray alloc] init];
5531                 [self addFactoryPresets:nil];
5532         }
5533         [fPresetsOutlineView reloadData];
5534 }
5535
5536
5537 - (IBAction) showAddPresetPanel: (id) sender
5538 {
5539     /* Deselect the currently selected Preset if there is one*/
5540     [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
5541
5542     /* Populate the preset picture settings popup here */
5543     [fPresetNewPicSettingsPopUp removeAllItems];
5544     [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
5545     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
5546     [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
5547     [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];  
5548     /* Uncheck the preset use filters checkbox */
5549     [fPresetNewPicFiltersCheck setState:NSOffState];
5550     /* Erase info from the input fields*/
5551         [fPresetNewName setStringValue: @""];
5552         [fPresetNewDesc setStringValue: @""];
5553         /* Show the panel */
5554         [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
5555 }
5556
5557 - (IBAction) closeAddPresetPanel: (id) sender
5558 {
5559     [NSApp endSheet: fAddPresetPanel];
5560     [fAddPresetPanel orderOut: self];
5561 }
5562
5563 - (IBAction)addUserPreset:(id)sender
5564 {
5565     if (![[fPresetNewName stringValue] length])
5566             NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
5567     else
5568     {
5569         /* Here we create a custom user preset */
5570         [UserPresets addObject:[self createPreset]];
5571         [self addPreset];
5572
5573         [self closeAddPresetPanel:nil];
5574     }
5575 }
5576 - (void)addPreset
5577 {
5578
5579         
5580         /* We Reload the New Table data for presets */
5581     [fPresetsOutlineView reloadData];
5582    /* We save all of the preset data here */
5583     [self savePreset];
5584 }
5585
5586 - (void)sortPresets
5587 {
5588
5589         
5590         /* We Sort the Presets By Factory or Custom */
5591         NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type" 
5592                                                     ascending:YES] autorelease];
5593         /* We Sort the Presets Alphabetically by name  We do not use this now as we have drag and drop*/
5594         /*
5595     NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName" 
5596                                                     ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
5597         //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
5598     
5599     */
5600     /* Since we can drag and drop our custom presets, lets just sort by type and not name */
5601     NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
5602         NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
5603         [UserPresets setArray:sortedArray];
5604         
5605
5606 }
5607
5608 - (IBAction)insertPreset:(id)sender
5609 {
5610     int index = [fPresetsOutlineView selectedRow];
5611     [UserPresets insertObject:[self createPreset] atIndex:index];
5612     [fPresetsOutlineView reloadData];
5613     [self savePreset];
5614 }
5615
5616 - (NSDictionary *)createPreset
5617 {
5618     NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
5619         /* Get the New Preset Name from the field in the AddPresetPanel */
5620     [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
5621         /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
5622         [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
5623         /*Set whether or not this is default, at creation set to 0*/
5624         [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
5625         /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
5626         [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
5627     /* Get whether or not to use the current Picture Filter settings for the preset */
5628     [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
5629  
5630     /* Get New Preset Description from the field in the AddPresetPanel*/
5631         [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
5632         /* File Format */
5633     [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
5634         /* Chapter Markers fCreateChapterMarkers*/
5635         [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
5636         /* Allow Mpeg4 64 bit formatting +4GB file sizes */
5637         [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
5638     /* Mux mp4 with http optimization */
5639     [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
5640     /* Add iPod uuid atom */
5641     [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
5642
5643     /* Codecs */
5644         /* Video encoder */
5645         [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
5646         /* x264 Option String */
5647         [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
5648
5649         [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
5650         [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
5651         [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
5652         [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
5653
5654         /* Video framerate */
5655     if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
5656         {
5657         [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
5658     }
5659     else // we can record the actual titleOfSelectedItem
5660     {
5661     [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
5662     }
5663         /* GrayScale */
5664         [preset setObject:[NSNumber numberWithInt:[fVidGrayscaleCheck state]] forKey:@"VideoGrayScale"];
5665         /* 2 Pass Encoding */
5666         [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
5667         /* Turbo 2 pass Encoding fVidTurboPassCheck*/
5668         [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
5669         /*Picture Settings*/
5670         hb_job_t * job = fTitle->job;
5671         /* Picture Sizing */
5672         /* Use Max Picture settings for whatever the dvd is.*/
5673         [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
5674         [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
5675         [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
5676         [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
5677         [preset setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
5678     
5679     /* Set crop settings here */
5680         [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
5681     [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
5682     [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
5683         [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
5684         [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
5685     
5686     /* Picture Filters */
5687     [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
5688         [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
5689     [preset setObject:[NSNumber numberWithInt:[fPictureController vfr]] forKey:@"VFR"];
5690         [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
5691     [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"]; 
5692     [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
5693     
5694     
5695     /*Audio*/
5696     if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5697     {
5698         [preset setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
5699         [preset setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
5700         [preset setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
5701         [preset setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
5702         [preset setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
5703         [preset setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
5704         [preset setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
5705     }
5706     if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5707     {
5708         [preset setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
5709         [preset setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
5710         [preset setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
5711         [preset setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
5712         [preset setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
5713         [preset setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
5714         [preset setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
5715     }
5716     if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5717     {
5718         [preset setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
5719         [preset setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
5720         [preset setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
5721         [preset setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
5722         [preset setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
5723         [preset setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
5724         [preset setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
5725     }
5726     if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5727     {
5728         [preset setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
5729         [preset setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
5730         [preset setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
5731         [preset setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
5732         [preset setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
5733         [preset setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
5734         [preset setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
5735     }
5736     
5737         /* Subtitles*/
5738         [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
5739     /* Forced Subtitles */
5740         [preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
5741     
5742     [preset autorelease];
5743     return preset;
5744
5745 }
5746
5747 - (void)savePreset
5748 {
5749     [UserPresets writeToFile:UserPresetsFile atomically:YES];
5750         /* We get the default preset in case it changed */
5751         [self getDefaultPresets:nil];
5752
5753 }
5754
5755 - (IBAction)deletePreset:(id)sender
5756 {
5757     int status;
5758     NSEnumerator *enumerator;
5759     NSNumber *index;
5760     NSMutableArray *tempArray;
5761     id tempObject;
5762     
5763     if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
5764         return;
5765     /* Alert user before deleting preset */
5766         /* Comment out for now, tie to user pref eventually */
5767
5768     //NSBeep();
5769     status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
5770     
5771     if ( status == NSAlertDefaultReturn ) {
5772         enumerator = [fPresetsOutlineView selectedRowEnumerator];
5773         tempArray = [NSMutableArray array];
5774         
5775         while ( (index = [enumerator nextObject]) ) {
5776             tempObject = [UserPresets objectAtIndex:[index intValue]];
5777             [tempArray addObject:tempObject];
5778         }
5779         
5780         [UserPresets removeObjectsInArray:tempArray];
5781         [fPresetsOutlineView reloadData];
5782         [self savePreset];   
5783     }
5784 }
5785
5786 #pragma mark -
5787 #pragma mark Manage Default Preset
5788
5789 - (IBAction)getDefaultPresets:(id)sender
5790 {
5791         int i = 0;
5792     presetCurrentBuiltInCount = 0;
5793     NSEnumerator *enumerator = [UserPresets objectEnumerator];
5794         id tempObject;
5795         while (tempObject = [enumerator nextObject])
5796         {
5797                 NSDictionary *thisPresetDict = tempObject;
5798                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
5799                 {
5800                         presetHbDefault = i;    
5801                 }
5802                 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
5803                 {
5804                         presetUserDefault = i;  
5805                 }
5806         if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset               
5807         {
5808                         presetCurrentBuiltInCount++; // <--increment the current number of built in presets     
5809                 }
5810                 i++;
5811         }
5812 }
5813
5814 - (IBAction)setDefaultPreset:(id)sender
5815 {
5816     int i = 0;
5817     NSEnumerator *enumerator = [UserPresets objectEnumerator];
5818         id tempObject;
5819         /* First make sure the old user specified default preset is removed */
5820         while (tempObject = [enumerator nextObject])
5821         {
5822                 /* make sure we are not removing the default HB preset */
5823                 if ([[[UserPresets objectAtIndex:i] objectForKey:@"Default"] intValue] != 1) // 1 is HB default
5824                 {
5825                         [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
5826                 }
5827                 i++;
5828         }
5829         /* Second, go ahead and set the appropriate user specfied preset */
5830         /* we get the chosen preset from the UserPresets array */
5831         if ([[[UserPresets objectAtIndex:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1) // 1 is HB default
5832         {
5833                 [[UserPresets objectAtIndex:[fPresetsOutlineView selectedRow]] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
5834         }
5835         /*FIX ME: I think we now need to use the items not rows in NSOutlineView */
5836     presetUserDefault = [fPresetsOutlineView selectedRow];
5837         
5838         /* We save all of the preset data here */
5839     [self savePreset];
5840         /* We Reload the New Table data for presets */
5841     [fPresetsOutlineView reloadData];
5842 }
5843
5844 - (IBAction)selectDefaultPreset:(id)sender
5845 {
5846         /* if there is a user specified default, we use it */
5847         if (presetUserDefault)
5848         {
5849         [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:presetUserDefault] byExtendingSelection:NO];
5850         [self selectPreset:nil];
5851         }
5852         else if (presetHbDefault) //else we use the built in default presetHbDefault
5853         {
5854         [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:presetHbDefault] byExtendingSelection:NO];
5855         [self selectPreset:nil];
5856         }
5857 }
5858
5859
5860 #pragma mark -
5861 #pragma mark Manage Built In Presets
5862
5863
5864 - (IBAction)deleteFactoryPresets:(id)sender
5865 {
5866     //int status;
5867     NSEnumerator *enumerator = [UserPresets objectEnumerator];
5868         id tempObject;
5869     
5870         //NSNumber *index;
5871     NSMutableArray *tempArray;
5872
5873
5874         tempArray = [NSMutableArray array];
5875         /* we look here to see if the preset is we move on to the next one */
5876         while ( tempObject = [enumerator nextObject] )  
5877                 {
5878                         /* if the preset is "Factory" then we put it in the array of
5879                         presets to delete */
5880                         if ([[tempObject objectForKey:@"Type"] intValue] == 0)
5881                         {
5882                                 [tempArray addObject:tempObject];
5883                         }
5884         }
5885         
5886         [UserPresets removeObjectsInArray:tempArray];
5887         [fPresetsOutlineView reloadData];
5888         [self savePreset];   
5889
5890 }
5891
5892    /* We use this method to recreate new, updated factory
5893    presets */
5894 - (IBAction)addFactoryPresets:(id)sender
5895 {
5896    
5897    /* First, we delete any existing built in presets */
5898     [self deleteFactoryPresets: sender];
5899     /* Then we generate new built in presets programmatically with fPresetsBuiltin
5900     * which is all setup in HBPresets.h and  HBPresets.m*/
5901     [fPresetsBuiltin generateBuiltinPresets:UserPresets];
5902     [self sortPresets];
5903     [self addPreset];
5904     
5905 }
5906
5907
5908
5909
5910
5911 @end
5912
5913 /*******************************
5914  * Subclass of the HBPresetsOutlineView *
5915  *******************************/
5916
5917 @implementation HBPresetsOutlineView
5918 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
5919 {
5920     fIsDragging = YES;
5921
5922     // By default, NSTableView only drags an image of the first column. Change this to
5923     // drag an image of the queue's icon and PresetName columns.
5924     NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"icon"], [self tableColumnWithIdentifier:@"PresetName"], nil];
5925     return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
5926 }
5927
5928
5929
5930 - (void) mouseDown:(NSEvent *)theEvent
5931 {
5932     [super mouseDown:theEvent];
5933         fIsDragging = NO;
5934 }
5935
5936
5937
5938 - (BOOL) isDragging;
5939 {
5940     return fIsDragging;
5941 }
5942 @end
5943
5944
5945