OSDN Git Service

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