OSDN Git Service

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