OSDN Git Service

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