OSDN Git Service

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