OSDN Git Service

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