1 /* $Id: Controller.mm,v 1.79 2005/11/04 19:41:32 titer Exp $
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. */
9 #import "HBOutputPanelController.h"
10 #import "HBPreferencesController.h"
11 #import "HBDVDDetector.h"
13 #import "HBPreviewController.h"
15 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
17 /* We setup the toolbar values here ShowPreviewIdentifier */
18 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
19 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
20 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
21 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
22 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
23 static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
24 static NSString * ShowPreviewIdentifier = @"Show Preview Window Item Identifier";
25 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
26 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
29 /*******************************
30 * HBController implementation *
31 *******************************/
32 @implementation HBController
42 /* replace bundled app icon with one which is 32/64-bit savvy */
43 #if defined( __LP64__ )
44 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
46 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
48 if( fApplicationIcon != nil )
49 [NSApp setApplicationIconImage:fApplicationIcon];
51 [HBPreferencesController registerUserDefaults];
53 fQueueEncodeLibhb = NULL;
54 /* Check for check for the app support directory here as
55 * outputPanel needs it right away, as may other future methods
57 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
59 YES ) objectAtIndex:0];
60 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
61 stringByAppendingPathComponent:@"HandBrake"];
62 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
64 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
67 /* Check for and create the App Support Preview directory if necessary */
68 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
69 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
71 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
74 outputPanel = [[HBOutputPanelController alloc] init];
75 fPictureController = [[PictureController alloc] init];
76 fQueueController = [[HBQueueController alloc] init];
77 fAdvancedOptions = [[HBAdvancedController alloc] init];
78 /* we init the HBPresets class which currently is only used
79 * for updating built in presets, may move more functionality
82 fPresetsBuiltin = [[HBPresets alloc] init];
83 fPreferencesController = [[HBPreferencesController alloc] init];
84 /* Lets report the HandBrake version number here to the activity log and text log file */
85 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
86 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
92 - (void) applicationDidFinishLaunching: (NSNotification *) notification
94 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
95 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
96 fHandle = hb_init(loggingLevel, 0);
97 /* Optional dvd nav UseDvdNav*/
98 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
99 /* Init a separate instance of libhb for user scanning and setting up jobs */
100 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
102 // Set the Growl Delegate
103 [GrowlApplicationBridge setGrowlDelegate: self];
104 /* Init others controllers */
105 [fPictureController SetHandle: fHandle];
106 [fPictureController setHBController: self];
108 [fQueueController setHandle: fQueueEncodeLibhb];
109 [fQueueController setHBController: self];
111 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
112 [fChapterTable setDataSource:fChapterTitlesDelegate];
113 [fChapterTable setDelegate:fChapterTitlesDelegate];
115 /* setup the subtitles delegate and connections to table */
116 fSubtitlesDelegate = [[HBSubtitles alloc] init];
117 [fSubtitlesTable setDataSource:fSubtitlesDelegate];
118 [fSubtitlesTable setDelegate:fSubtitlesDelegate];
119 [fSubtitlesTable setRowHeight:25.0];
121 [fPresetsOutlineView setAutosaveName:@"Presets View"];
122 [fPresetsOutlineView setAutosaveExpandedItems:YES];
124 dockIconProgress = 0;
126 /* Init QueueFile .plist */
127 [self loadQueueFile];
128 /* Run hbInstances to get any info on other instances as well as set the
129 * pid number for this instance in the case of multi-instance encoding. */
130 hbInstanceNum = [self hbInstances];
132 /* If we are a single instance it is safe to clean up the previews if there are any
133 * left over. This is a bit of a kludge but will prevent a build up of old instance
134 * live preview cruft. No danger of removing an active preview directory since they
135 * are created later in HBPreviewController if they don't exist at the moment a live
136 * preview encode is initiated. */
137 if (hbInstanceNum == 1)
139 NSString *PreviewDirectory = [NSString stringWithFormat:@"~/Library/Application Support/HandBrake/Previews"];
140 PreviewDirectory = [PreviewDirectory stringByExpandingTildeInPath];
142 NSArray *files = [ [NSFileManager defaultManager] contentsOfDirectoryAtPath: PreviewDirectory error: &error ];
143 for( NSString *file in files )
145 if( file != @"." && file != @".." )
147 [ [NSFileManager defaultManager] removeItemAtPath: [ PreviewDirectory stringByAppendingPathComponent: file ] error: &error ];
150 //an error occurred...
151 [self writeToActivityLog: "Could not remove existing preview at : %s",[file UTF8String] ];
160 /* Call UpdateUI every 1/2 sec */
162 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
163 scheduledTimerWithTimeInterval:0.5
165 selector:@selector(updateUI:)
166 userInfo:nil repeats:YES]
167 forMode:NSDefaultRunLoopMode];
170 // Open debug output window now if it was visible when HB was closed
171 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
172 [self showDebugOutputPanel:nil];
174 // Open queue window now if it was visible when HB was closed
175 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
176 [self showQueueWindow:nil];
178 [self openMainWindow:nil];
180 /* We have to set the bool to tell hb what to do after a scan
181 * Initially we set it to NO until we start processing the queue
183 applyQueueToScan = NO;
185 /* Now we re-check the queue array to see if there are
186 * any remaining encodes to be done in it and ask the
187 * user if they want to reload the queue */
188 if ([QueueFileArray count] > 0)
190 /* run getQueueStats to see whats in the queue file */
191 [self getQueueStats];
192 /* this results in these values
193 * fEncodingQueueItem = 0;
195 * fCompletedCount = 0;
196 * fCanceledCount = 0;
200 /*On Screen Notification*/
201 NSString * alertTitle;
203 /* We check to see if there is already another instance of hb running.
204 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
206 if (hbInstanceNum > 1)
208 alertTitle = [NSString stringWithFormat:
209 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
210 NSBeginCriticalAlertSheet(
212 NSLocalizedString(@"Reload Queue", nil),
216 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
217 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
221 if (fWorkingCount > 0 || fPendingCount > 0)
223 if (fWorkingCount > 0)
225 alertTitle = [NSString stringWithFormat:
226 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item(s) and %d Pending Item(s) In Your Queue.", @""),
227 fWorkingCount,fPendingCount];
231 alertTitle = [NSString stringWithFormat:
232 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
236 NSBeginCriticalAlertSheet(
238 NSLocalizedString(@"Reload Queue", nil),
240 NSLocalizedString(@"Empty Queue", nil),
242 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
243 NSLocalizedString(@" Do you want to reload them ?", nil));
247 /* Since we addressed any pending or previously encoding items above, we go ahead and make sure the queue
248 * is empty of any finished items or cancelled items */
249 [self clearQueueAllItems];
250 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
251 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
253 [self browseSources:nil];
256 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
258 [self browseSources:(id)fOpenSourceTitleMMenu];
266 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
267 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
269 [self browseSources:nil];
272 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
274 [self browseSources:(id)fOpenSourceTitleMMenu];
277 currentQueueEncodeNameString = @"";
281 #pragma mark Multiple Instances
283 /* hbInstances checks to see if other instances of HB are running and also sets the pid for this instance for multi-instance queue encoding */
285 /* 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. */
288 /* check to see if another instance of HandBrake.app is running */
289 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
290 NSDictionary *runningAppsDictionary;
292 NSString * thisInstanceAppPath = [[NSBundle mainBundle] bundlePath];
293 NSString * runningInstanceAppPath;
294 int runningInstancePidNum;
295 [self writeToActivityLog: "hbInstances path to this instance: %s", [thisInstanceAppPath UTF8String]];
296 for (runningAppsDictionary in runningAppDictionaries)
298 if ([[runningAppsDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
300 /*Report the path to each active instances app path */
301 runningInstancePidNum = [[runningAppsDictionary valueForKey:@"NSApplicationProcessIdentifier"] intValue];
302 runningInstanceAppPath = [runningAppsDictionary valueForKey:@"NSApplicationPath"];
303 [self writeToActivityLog: "hbInstance found instance pidnum:%d at path: %s", runningInstancePidNum, [runningInstanceAppPath UTF8String]];
304 /* see if this is us by comparing the app path */
305 if ([runningInstanceAppPath isEqualToString: thisInstanceAppPath])
307 /* If so this is our pidnum */
308 [self writeToActivityLog: "hbInstance MATCH FOUND, our pidnum is:%d", runningInstancePidNum];
309 /* Get the PID number for this hb instance, used in multi instance encoding */
310 pidNum = runningInstancePidNum;
311 /* Report this pid to the activity log */
312 [self writeToActivityLog: "Pid for this instance:%d", pidNum];
313 /* Tell fQueueController what our pidNum is */
314 [fQueueController setPidNum:pidNum];
329 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
332 [self writeToActivityLog: "didDimissReloadQueue number of hb instances:%d", hbInstanceNum];
333 if (returnCode == NSAlertOtherReturn)
335 [self writeToActivityLog: "didDimissReloadQueue NSAlertOtherReturn Chosen"];
336 [self clearQueueAllItems];
338 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
339 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
341 [self browseSources:nil];
344 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
346 [self browseSources:(id)fOpenSourceTitleMMenu];
351 [self writeToActivityLog: "didDimissReloadQueue First Button Chosen"];
352 if (hbInstanceNum == 1)
355 [self setQueueEncodingItemsAsPending];
357 [self showQueueWindow:NULL];
361 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
366 hb_get_state( fQueueEncodeLibhb, &s );
368 if ( s.state != HB_STATE_IDLE )
370 int result = NSRunCriticalAlertPanel(
371 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
372 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
373 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
375 if (result == NSAlertDefaultReturn)
377 return NSTerminateNow;
380 return NSTerminateCancel;
383 // Warn if items still in the queue
384 else if ( fPendingCount > 0 )
386 int result = NSRunCriticalAlertPanel(
387 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
388 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
389 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
391 if ( result == NSAlertDefaultReturn )
392 return NSTerminateNow;
394 return NSTerminateCancel;
397 return NSTerminateNow;
400 - (void)applicationWillTerminate:(NSNotification *)aNotification
402 [currentQueueEncodeNameString release];
403 [browsedSourceDisplayName release];
404 [outputPanel release];
405 [fQueueController release];
406 [fPreviewController release];
407 [fPictureController release];
408 [fApplicationIcon release];
411 hb_close(&fQueueEncodeLibhb);
417 - (void) awakeFromNib
420 [fWindow setExcludedFromWindowsMenu:NO];
422 [fAdvancedOptions setView:fAdvancedView];
424 /* lets setup our presets drawer for drag and drop here */
425 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
426 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
427 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
429 /* Initialize currentScanCount so HB can use it to
430 evaluate successive scans */
431 currentScanCount = 0;
434 /* Init UserPresets .plist */
437 fRipIndicatorShown = NO; // initially out of view in the nib
439 /* For 64 bit builds, the threaded animation in the progress
440 * indicators conflicts with the animation in the advanced tab
441 * for reasons not completely clear. jbrjake found a note in the
442 * 10.5 dev notes regarding this possiblility. It was also noted
443 * that unless specified, setUsesThreadedAnimation defaults to true.
444 * So, at least for now we set the indicator animation to NO for
445 * both the scan and regular progress indicators for both 32 and 64 bit
446 * as it test out fine on both and there is no reason our progress indicators
447 * should require their own thread.
450 [fScanIndicator setUsesThreadedAnimation:NO];
451 [fRipIndicator setUsesThreadedAnimation:NO];
455 /* Show/Dont Show Presets drawer upon launch based
456 on user preference DefaultPresetsDrawerShow*/
457 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
459 [fPresetDrawer setDelegate:self];
460 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
461 stringForKey:@"Drawer Size"] );
462 if( drawerSize.width )
463 [fPresetDrawer setContentSize: drawerSize];
464 [fPresetDrawer open];
467 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
468 [fSrcAngleLabel setHidden:YES];
469 [fSrcAnglePopUp setHidden:YES];
471 /* Setup the start / stop popup */
472 [fEncodeStartStopPopUp removeAllItems];
473 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
474 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
475 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
476 /* Align the start / stop widgets with the chapter popups */
477 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
478 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
480 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
481 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
484 NSMenuItem *menuItem;
485 [fDstFormatPopUp removeAllItems];
487 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
488 [menuItem setTag: HB_MUX_MP4];
490 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
491 [menuItem setTag: HB_MUX_MKV];
493 [fDstFormatPopUp selectItemAtIndex: 0];
495 [self formatPopUpChanged:nil];
497 /* We enable the create chapters checkbox here since we are .mp4 */
498 [fCreateChapterMarkers setEnabled: YES];
499 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
501 [fCreateChapterMarkers setState: NSOnState];
507 [fDstFile2Field setStringValue: [NSString stringWithFormat:
508 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
511 [fVidEncoderPopUp removeAllItems];
512 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
516 [fVidTargetSizeField setIntValue: 700];
517 [fVidBitrateField setIntValue: 1000];
519 [fVidQualityMatrix selectCell: fVidBitrateCell];
520 [self videoMatrixChanged:nil];
522 /* Video framerate */
523 [fVidRatePopUp removeAllItems];
524 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
525 for( int i = 0; i < hb_video_rates_count; i++ )
527 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
529 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
530 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
532 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
534 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
535 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
537 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
539 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
540 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
544 [fVidRatePopUp addItemWithTitle:
545 [NSString stringWithUTF8String: hb_video_rates[i].string]];
548 [fVidRatePopUp selectItemAtIndex: 0];
550 /* Set Auto Crop to On at launch */
551 [fPictureController setAutoCrop:YES];
554 [fAudTrack1BitratePopUp removeAllItems];
555 for( int i = 0; i < hb_audio_bitrates_count; i++ )
557 [fAudTrack1BitratePopUp addItemWithTitle:
558 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
561 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
563 /* Audio samplerate */
564 [fAudTrack1RatePopUp removeAllItems];
565 for( int i = 0; i < hb_audio_rates_count; i++ )
567 [fAudTrack1RatePopUp addItemWithTitle:
568 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
570 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
573 [fStatusField setStringValue: @""];
578 /* We disable the Turbo 1st pass checkbox since we are not x264 */
579 [fVidTurboPassCheck setEnabled: NO];
580 [fVidTurboPassCheck setState: NSOffState];
583 /* lets get our default prefs here */
584 [self getDefaultPresets:nil];
585 /* lets initialize the current successful scancount here to 0 */
586 currentSuccessfulScanCount = 0;
589 - (void) enableUI: (bool) b
591 NSControl * controls[] =
592 { fSrcTitleField, fSrcTitlePopUp,
593 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
594 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
595 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
596 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
597 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
598 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
599 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
600 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
601 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
602 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
603 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
604 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
605 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
606 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
607 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
608 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
609 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
610 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,
611 fSrcFrameEndEncodingField, fLoadChaptersButton, fSaveChaptersButton, fFrameratePfrCheck};
614 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
616 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
618 NSTextField * tf = (NSTextField *) controls[i];
619 if( ![tf isBezeled] )
621 [tf setTextColor: b ? [NSColor controlTextColor] :
622 [NSColor disabledControlTextColor]];
626 [controls[i] setEnabled: b];
633 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
634 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
635 [self setEnabledStateOfAudioMixdownControls:nil];
636 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
637 [self calculatePictureSizing:nil];
638 /* Also enable the preview window hud controls */
639 [fPictureController enablePreviewHudControls];
644 [fPresetsOutlineView setEnabled: NO];
645 [fPictureController disablePreviewHudControls];
648 [self videoMatrixChanged:nil];
649 [fAdvancedOptions enableUI:b];
653 /***********************************************************************
655 ***********************************************************************
656 * Shows a progression bar on the dock icon, filled according to
657 * 'progress' (0.0 <= progress <= 1.0).
658 * Called with progress < 0.0 or progress > 1.0, restores the original
660 **********************************************************************/
661 - (void) UpdateDockIcon: (float) progress
664 NSBitmapImageRep * bmp;
666 uint32_t black = htonl( 0x000000FF );
667 uint32_t red = htonl( 0xFF0000FF );
668 uint32_t white = htonl( 0xFFFFFFFF );
669 int row_start, row_end;
672 if( progress < 0.0 || progress > 1.0 )
674 [NSApp setApplicationIconImage: fApplicationIcon];
678 /* Get it in a raw bitmap form */
679 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
680 NSTIFFCompressionNone factor: 1.0];
681 bmp = [NSBitmapImageRep imageRepWithData: tiff];
683 /* Draw the progression bar */
684 /* It's pretty simple (ugly?) now, but I'm no designer */
686 row_start = 3 * (int) [bmp size].height / 4;
687 row_end = 7 * (int) [bmp size].height / 8;
689 for( i = row_start; i < row_start + 2; i++ )
691 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
692 for( j = 0; j < (int) [bmp size].width; j++ )
697 for( i = row_start + 2; i < row_end - 2; i++ )
699 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
702 for( j = 2; j < (int) [bmp size].width - 2; j++ )
704 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
716 for( i = row_end - 2; i < row_end; i++ )
718 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
719 for( j = 0; j < (int) [bmp size].width; j++ )
725 /* Now update the dock icon */
726 tiff = [bmp TIFFRepresentationUsingCompression:
727 NSTIFFCompressionNone factor: 1.0];
728 NSImage* icon = [[NSImage alloc] initWithData: tiff];
729 [NSApp setApplicationIconImage: icon];
733 - (void) updateUI: (NSTimer *) timer
736 /* Update UI for fHandle (user scanning instance of libhb ) */
739 list = hb_get_titles( fHandle );
740 /* check to see if there has been a new scan done
741 this bypasses the constraints of HB_STATE_WORKING
742 not allowing setting a newly scanned source */
743 int checkScanCount = hb_get_scancount( fHandle );
744 if( checkScanCount > currentScanCount )
746 currentScanCount = checkScanCount;
747 [fScanIndicator setIndeterminate: NO];
748 [fScanIndicator setDoubleValue: 0.0];
749 [fScanIndicator setHidden: YES];
750 [self showNewScan:nil];
754 hb_get_state( fHandle, &s );
760 #define p s.param.scanning
761 case HB_STATE_SCANNING:
763 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
764 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
765 p.title_cur, p.title_count]];
766 [fScanIndicator setHidden: NO];
767 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
772 #define p s.param.scandone
773 case HB_STATE_SCANDONE:
775 [fScanIndicator setIndeterminate: NO];
776 [fScanIndicator setDoubleValue: 0.0];
777 [fScanIndicator setHidden: YES];
778 [self writeToActivityLog:"ScanDone state received from fHandle"];
779 [self showNewScan:nil];
780 [[fWindow toolbar] validateVisibleItems];
786 #define p s.param.working
787 case HB_STATE_WORKING:
794 #define p s.param.muxing
795 case HB_STATE_MUXING:
802 case HB_STATE_PAUSED:
805 case HB_STATE_WORKDONE:
812 /* Update UI for fQueueEncodeLibhb */
814 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
815 /* check to see if there has been a new scan done
816 this bypasses the constraints of HB_STATE_WORKING
817 not allowing setting a newly scanned source */
819 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
820 if( checkScanCount > currentScanCount )
822 currentScanCount = checkScanCount;
826 hb_get_state( fQueueEncodeLibhb, &s );
832 #define p s.param.scanning
833 case HB_STATE_SCANNING:
835 [fStatusField setStringValue: [NSString stringWithFormat:
836 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
837 p.title_cur, p.title_count]];
839 /* Set the status string in fQueueController as well */
840 [fQueueController setQueueStatusString: [NSString stringWithFormat:
841 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
842 p.title_cur, p.title_count]];
847 #define p s.param.scandone
848 case HB_STATE_SCANDONE:
850 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
851 [self processNewQueueEncode];
852 [[fWindow toolbar] validateVisibleItems];
859 #define p s.param.working
861 case HB_STATE_SEARCHING:
863 NSMutableString * string;
864 NSString * pass_desc;
866 /* Update text field */
868 //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];
869 /* For now, do not announce "pass x of x for the search phase ... */
870 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
874 [string appendFormat:
875 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
878 [fStatusField setStringValue: string];
879 /* Set the status string in fQueueController as well */
880 [fQueueController setQueueStatusString: string];
882 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
883 [fRipIndicator setIndeterminate: NO];
884 [fRipIndicator setDoubleValue:100.0 * progress_total];
886 // If progress bar hasn't been revealed at the bottom of the window, do
887 // that now. This code used to be in doRip. I moved it to here to handle
888 // the case where hb_start is called by HBQueueController and not from
890 if( !fRipIndicatorShown )
892 NSRect frame = [fWindow frame];
893 if( frame.size.width <= 591 )
894 frame.size.width = 591;
895 frame.size.height += 36;
896 frame.origin.y -= 36;
897 [fWindow setFrame:frame display:YES animate:YES];
898 fRipIndicatorShown = YES;
902 /* Update dock icon */
903 /* Note not done yet */
908 case HB_STATE_WORKING:
910 NSMutableString * string;
911 NSString * pass_desc;
912 /* Update text field */
913 if (p.job_cur == 1 && p.job_count > 1)
915 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
917 pass_desc = @"(subtitle scan)";
929 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: %@ \nPass %d %@ of %d, %.2f %%", @"" ), currentQueueEncodeNameString, p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
933 [string appendFormat:
934 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
935 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
937 [fStatusField setStringValue: string];
938 [fQueueController setQueueStatusString:string];
941 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
942 [fRipIndicator setIndeterminate: NO];
943 [fRipIndicator setDoubleValue:100.0 * progress_total];
945 // If progress bar hasn't been revealed at the bottom of the window, do
946 // that now. This code used to be in doRip. I moved it to here to handle
947 // the case where hb_start is called by HBQueueController and not from
949 if( !fRipIndicatorShown )
951 NSRect frame = [fWindow frame];
952 if( frame.size.width <= 591 )
953 frame.size.width = 591;
954 frame.size.height += 36;
955 frame.origin.y -= 36;
956 [fWindow setFrame:frame display:YES animate:YES];
957 fRipIndicatorShown = YES;
961 /* Update dock icon */
962 if( dockIconProgress < 100.0 * progress_total )
964 [self UpdateDockIcon: progress_total];
965 dockIconProgress += 5;
972 #define p s.param.muxing
973 case HB_STATE_MUXING:
975 /* Update text field */
976 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
977 /* Set the status string in fQueueController as well */
978 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
980 [fRipIndicator setIndeterminate: YES];
981 [fRipIndicator startAnimation: nil];
983 /* Update dock icon */
984 [self UpdateDockIcon: 1.0];
990 case HB_STATE_PAUSED:
991 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
992 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
996 case HB_STATE_WORKDONE:
998 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
999 // or someone calling hb_stop. In the latter case, hb_stop does not clear
1000 // out the remaining passes/jobs in the queue. We'll do that here.
1002 // Delete all remaining jobs of this encode.
1003 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
1004 /* Set the status string in fQueueController as well */
1005 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
1006 [fRipIndicator setIndeterminate: NO];
1007 [fRipIndicator stopAnimation: nil];
1008 [fRipIndicator setDoubleValue: 0.0];
1009 [[fWindow toolbar] validateVisibleItems];
1011 /* Restore dock icon */
1012 [self UpdateDockIcon: -1.0];
1013 dockIconProgress = 0;
1015 if( fRipIndicatorShown )
1017 NSRect frame = [fWindow frame];
1018 if( frame.size.width <= 591 )
1019 frame.size.width = 591;
1020 frame.size.height += -36;
1021 frame.origin.y -= -36;
1022 [fWindow setFrame:frame display:YES animate:YES];
1023 fRipIndicatorShown = NO;
1025 /* Since we are done with this encode, tell output to stop writing to the
1026 * individual encode log
1028 [outputPanel endEncodeLog];
1029 /* Check to see if the encode state has not been cancelled
1030 to determine if we should check for encode done notifications */
1031 if( fEncodeState != 2 )
1033 NSString *pathOfFinishedEncode;
1034 /* Get the output file name for the finished encode */
1035 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
1037 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
1038 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1039 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1041 /* If Play System Alert has been selected in Preferences */
1042 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
1046 [self showGrowlDoneNotification:pathOfFinishedEncode];
1050 [self sendToMetaX:pathOfFinishedEncode];
1052 /* since we have successfully completed an encode, we increment the queue counter */
1053 [self incrementQueueItemDone:currentQueueEncodeIndex];
1061 /* 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
1062 * so we go ahead and do it in this existing timer as opposed to using a new one */
1064 NSMutableArray * tempQueueArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1065 [QueueFileArray setArray:tempQueueArray];
1066 [tempQueueArray release];
1067 /* Send Fresh QueueFileArray to fQueueController to update queue window */
1068 [fQueueController setQueueArray: QueueFileArray];
1069 [self getQueueStats];
1073 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1074 - (void) writeToActivityLog:(const char *) format, ...
1077 va_start(args, format);
1081 vsnprintf( str, 1024, format, args );
1083 time_t _now = time( NULL );
1084 struct tm * now = localtime( &_now );
1085 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1091 #pragma mark Toolbar
1092 // ============================================================
1093 // NSToolbar Related Methods
1094 // ============================================================
1096 - (void) setupToolbar {
1097 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1099 [toolbar setAllowsUserCustomization: YES];
1100 [toolbar setAutosavesConfiguration: YES];
1101 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1103 [toolbar setDelegate: self];
1105 [fWindow setToolbar: toolbar];
1108 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1109 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1110 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1112 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1114 [item setLabel: @"Toggle Presets"];
1115 [item setPaletteLabel: @"Toggler Presets"];
1116 [item setToolTip: @"Open/Close Preset Drawer"];
1117 [item setImage: [NSImage imageNamed: @"Drawer"]];
1118 [item setTarget: self];
1119 [item setAction: @selector(toggleDrawer:)];
1120 [item setAutovalidates: NO];
1122 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1124 [item setLabel: @"Start"];
1125 [item setPaletteLabel: @"Start Encoding"];
1126 [item setToolTip: @"Start Encoding"];
1127 [item setImage: [NSImage imageNamed: @"Play"]];
1128 [item setTarget: self];
1129 [item setAction: @selector(Rip:)];
1131 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1133 [item setLabel: @"Show Queue"];
1134 [item setPaletteLabel: @"Show Queue"];
1135 [item setToolTip: @"Show Queue"];
1136 [item setImage: [NSImage imageNamed: @"Queue"]];
1137 [item setTarget: self];
1138 [item setAction: @selector(showQueueWindow:)];
1139 [item setAutovalidates: NO];
1141 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1143 [item setLabel: @"Add to Queue"];
1144 [item setPaletteLabel: @"Add to Queue"];
1145 [item setToolTip: @"Add to Queue"];
1146 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1147 [item setTarget: self];
1148 [item setAction: @selector(addToQueue:)];
1150 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1152 [item setLabel: @"Pause"];
1153 [item setPaletteLabel: @"Pause Encoding"];
1154 [item setToolTip: @"Pause Encoding"];
1155 [item setImage: [NSImage imageNamed: @"Pause"]];
1156 [item setTarget: self];
1157 [item setAction: @selector(Pause:)];
1159 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1161 [item setLabel: @"Picture Settings"];
1162 [item setPaletteLabel: @"Show Picture Settings"];
1163 [item setToolTip: @"Show Picture Settings"];
1164 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1165 [item setTarget: self];
1166 [item setAction: @selector(showPicturePanel:)];
1168 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1170 [item setLabel: @"Preview Window"];
1171 [item setPaletteLabel: @"Show Preview"];
1172 [item setToolTip: @"Show Preview"];
1173 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1174 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1175 [item setTarget: self];
1176 [item setAction: @selector(showPreviewWindow:)];
1178 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1180 [item setLabel: @"Activity Window"];
1181 [item setPaletteLabel: @"Show Activity Window"];
1182 [item setToolTip: @"Show Activity Window"];
1183 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1184 [item setTarget: self];
1185 [item setAction: @selector(showDebugOutputPanel:)];
1186 [item setAutovalidates: NO];
1188 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1190 [item setLabel: @"Source"];
1191 [item setPaletteLabel: @"Source"];
1192 [item setToolTip: @"Choose Video Source"];
1193 [item setImage: [NSImage imageNamed: @"Source"]];
1194 [item setTarget: self];
1195 [item setAction: @selector(browseSources:)];
1205 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1207 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1208 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1209 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1212 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1214 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1215 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1216 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1217 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1220 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1222 NSString * ident = [toolbarItem itemIdentifier];
1228 hb_get_state( fHandle, &s );
1229 if (s.state == HB_STATE_SCANNING)
1232 if ([ident isEqualToString: ChooseSourceIdentifier])
1234 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1235 [toolbarItem setLabel: @"Cancel Scan"];
1236 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1237 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1241 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1246 if ([ident isEqualToString: ChooseSourceIdentifier])
1248 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1249 [toolbarItem setLabel: @"Source"];
1250 [toolbarItem setPaletteLabel: @"Source"];
1251 [toolbarItem setToolTip: @"Choose Video Source"];
1256 hb_get_state2( fQueueEncodeLibhb, &s );
1258 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1260 if ([ident isEqualToString: StartEncodingIdentifier])
1262 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1263 [toolbarItem setLabel: @"Stop"];
1264 [toolbarItem setPaletteLabel: @"Stop"];
1265 [toolbarItem setToolTip: @"Stop Encoding"];
1268 if ([ident isEqualToString: PauseEncodingIdentifier])
1270 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1271 [toolbarItem setLabel: @"Pause"];
1272 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1273 [toolbarItem setToolTip: @"Pause Encoding"];
1278 if ([ident isEqualToString: AddToQueueIdentifier])
1280 if ([ident isEqualToString: ShowPictureIdentifier])
1282 if ([ident isEqualToString: ShowPreviewIdentifier])
1286 else if (s.state == HB_STATE_PAUSED)
1288 if ([ident isEqualToString: PauseEncodingIdentifier])
1290 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1291 [toolbarItem setLabel: @"Resume"];
1292 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1293 [toolbarItem setToolTip: @"Resume Encoding"];
1296 if ([ident isEqualToString: StartEncodingIdentifier])
1298 if ([ident isEqualToString: AddToQueueIdentifier])
1300 if ([ident isEqualToString: ShowPictureIdentifier])
1302 if ([ident isEqualToString: ShowPreviewIdentifier])
1305 else if (s.state == HB_STATE_SCANNING)
1307 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1309 if ([ident isEqualToString: StartEncodingIdentifier])
1311 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1312 if (hb_count(fHandle) > 0)
1313 [toolbarItem setLabel: @"Start Queue"];
1315 [toolbarItem setLabel: @"Start"];
1316 [toolbarItem setPaletteLabel: @"Start Encoding"];
1317 [toolbarItem setToolTip: @"Start Encoding"];
1320 if ([ident isEqualToString: AddToQueueIdentifier])
1322 if ([ident isEqualToString: ShowPictureIdentifier])
1324 if ([ident isEqualToString: ShowPreviewIdentifier])
1329 /* If there are any pending queue items, make sure the start/stop button is active */
1330 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1332 if ([ident isEqualToString: ShowQueueIdentifier])
1334 if ([ident isEqualToString: ToggleDrawerIdentifier])
1336 if ([ident isEqualToString: ChooseSourceIdentifier])
1338 if ([ident isEqualToString: ShowActivityIdentifier])
1344 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1346 SEL action = [menuItem action];
1349 hb_get_state2( fHandle, &s );
1353 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1354 return SuccessfulScan && [fWindow attachedSheet] == nil;
1356 if (action == @selector(browseSources:))
1358 if (s.state == HB_STATE_SCANNING)
1361 return [fWindow attachedSheet] == nil;
1363 if (action == @selector(selectDefaultPreset:))
1364 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1365 if (action == @selector(Pause:))
1367 if (s.state == HB_STATE_WORKING)
1369 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1370 [menuItem setTitle:@"Pause Encoding"];
1373 else if (s.state == HB_STATE_PAUSED)
1375 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1376 [menuItem setTitle:@"Resume Encoding"];
1382 if (action == @selector(Rip:))
1384 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1386 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1387 [menuItem setTitle:@"Stop Encoding"];
1390 else if (SuccessfulScan)
1392 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1393 [menuItem setTitle:@"Start Encoding"];
1394 return [fWindow attachedSheet] == nil;
1400 if( action == @selector(setDefaultPreset:) )
1402 return [fPresetsOutlineView selectedRow] != -1;
1409 #pragma mark Encode Done Actions
1410 // register a test notification and make
1411 // it enabled by default
1412 #define SERVICE_NAME @"Encode Done"
1413 - (NSDictionary *)registrationDictionaryForGrowl
1415 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1416 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1417 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1420 return registrationDictionary;
1423 -(void)showGrowlDoneNotification:(NSString *) filePath
1425 /* This end of encode action is called as each encode rolls off of the queue */
1426 /* Setup the Growl stuff ... */
1427 NSString * finishedEncode = filePath;
1428 /* strip off the path to just show the file name */
1429 finishedEncode = [finishedEncode lastPathComponent];
1430 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1431 [GrowlApplicationBridge
1432 notifyWithTitle:@"Put down that cocktail..."
1433 description:growlMssg
1434 notificationName:SERVICE_NAME
1440 -(void)sendToMetaX:(NSString *) filePath
1442 /* This end of encode action is called as each encode rolls off of the queue */
1443 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1445 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1446 if (![sendToApp isEqualToString:@"None"])
1448 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1449 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1450 [myScript executeAndReturnError: nil];
1457 - (void) queueCompletedAlerts
1459 /* If Play System Alert has been selected in Preferences */
1460 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
1465 /* If Alert Window or Window and Growl has been selected */
1466 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
1467 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
1469 /*On Screen Notification*/
1471 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
1472 [NSApp requestUserAttention:NSCriticalRequest];
1475 /* If sleep has been selected */
1476 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
1479 NSDictionary* errorDict;
1480 NSAppleEventDescriptor* returnDescriptor = nil;
1481 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
1482 @"tell application \"Finder\" to sleep"];
1483 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1484 [scriptObject release];
1486 /* If Shutdown has been selected */
1487 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
1490 NSDictionary* errorDict;
1491 NSAppleEventDescriptor* returnDescriptor = nil;
1492 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
1493 @"tell application \"Finder\" to shut down"];
1494 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1495 [scriptObject release];
1500 #pragma mark Get New Source
1502 /*Opens the source browse window, called from Open Source widgets */
1503 - (IBAction) browseSources: (id) sender
1507 hb_get_state( fHandle, &s );
1508 if (s.state == HB_STATE_SCANNING)
1510 [self cancelScanning:nil];
1515 NSOpenPanel * panel;
1517 panel = [NSOpenPanel openPanel];
1518 [panel setAllowsMultipleSelection: NO];
1519 [panel setCanChooseFiles: YES];
1520 [panel setCanChooseDirectories: YES ];
1521 NSString * sourceDirectory;
1522 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1524 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1528 sourceDirectory = @"~/Desktop";
1529 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1531 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1532 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1534 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1535 modalForWindow: fWindow modalDelegate: self
1536 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1537 contextInfo: sender];
1540 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1541 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1543 /* we convert the sender content of contextInfo back into a variable called sender
1544 * mostly just for consistency for evaluation later
1546 id sender = (id)contextInfo;
1547 /* User selected a file to open */
1548 if( returnCode == NSOKButton )
1550 /* Free display name allocated previously by this code */
1551 [browsedSourceDisplayName release];
1553 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1554 /* we set the last searched source directory in the prefs here */
1555 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1556 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1557 /* we order out sheet, which is the browse window as we need to open
1558 * the title selection sheet right away
1560 [sheet orderOut: self];
1562 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1564 /* We put the chosen source path in the source display text field for the
1565 * source title selection sheet in which the user specifies the specific title to be
1566 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1567 * purposes in the title panel
1570 [fScanSrcTitlePathField setStringValue:scanPath];
1571 NSString *displayTitlescanSourceName;
1573 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1575 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1576 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1577 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1581 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1582 displayTitlescanSourceName = [scanPath lastPathComponent];
1584 /* we set the source display name in the title selection dialogue */
1585 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1586 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1587 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1588 /* We show the actual sheet where the user specifies the title to be scanned
1589 * as we are going to do a title specific scan
1591 [self showSourceTitleScanPanel:nil];
1595 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1596 NSString *path = [[sheet filenames] objectAtIndex: 0];
1598 /* We check to see if the chosen file at path is a package */
1599 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1601 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1602 /* We check to see if this is an .eyetv package */
1603 if ([[path pathExtension] isEqualToString: @"eyetv"])
1605 [self writeToActivityLog:"trying to open eyetv package"];
1606 /* We're looking at an EyeTV package - try to open its enclosed
1608 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1610 int n = [[path stringByAppendingString: @"/"]
1611 completePathIntoString: &mpgname caseSensitive: YES
1612 matchesIntoArray: nil
1613 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1616 /* Found an mpeg inside the eyetv package, make it our scan path
1617 and call performScan on the enclosed mpeg */
1619 [self writeToActivityLog:"found mpeg in eyetv package"];
1620 [self performScan:path scanTitleNum:0];
1624 /* We did not find an mpeg file in our package, so we do not call performScan */
1625 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1628 /* We check to see if this is a .dvdmedia package */
1629 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1631 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1632 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1633 [self writeToActivityLog:"trying to open dvdmedia package"];
1634 [self performScan:path scanTitleNum:0];
1638 /* The package is not an eyetv package, so we do not call performScan */
1639 [self writeToActivityLog:"unable to open package"];
1642 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1644 /* path is not a package, so we call perform scan directly on our file */
1645 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1647 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1648 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1649 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1653 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1654 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1655 /* make sure we remove any path extension as this can also be an '.mpg' file */
1656 browsedSourceDisplayName = [[path lastPathComponent] retain];
1658 applyQueueToScan = NO;
1659 [self performScan:path scanTitleNum:0];
1667 - (IBAction)showAboutPanel:(id)sender
1669 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1670 fApplicationIcon, @"ApplicationIcon",
1672 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1676 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1677 - (IBAction) showSourceTitleScanPanel: (id) sender
1679 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1682 [fScanSrcTitleNumField setStringValue: @"0"];
1683 /* Show the panel */
1684 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1687 - (IBAction) closeSourceTitleScanPanel: (id) sender
1689 [NSApp endSheet: fScanSrcTitlePanel];
1690 [fScanSrcTitlePanel orderOut: self];
1692 if(sender == fScanSrcTitleOpenButton)
1694 /* We setup the scan status in the main window to indicate a source title scan */
1695 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1696 [fScanIndicator setHidden: NO];
1697 [fScanIndicator setIndeterminate: YES];
1698 [fScanIndicator startAnimation: nil];
1700 /* We use the performScan method to actually perform the specified scan passing the path and the title
1703 applyQueueToScan = NO;
1704 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1708 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1709 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1712 /* use a bool to determine whether or not we can decrypt using vlc */
1713 BOOL cancelScanDecrypt = 0;
1715 NSString *path = scanPath;
1716 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1718 // Notify ChapterTitles that there's no title
1719 [fChapterTitlesDelegate resetWithTitle:nil];
1720 [fChapterTable reloadData];
1722 // Notify Subtitles that there's no title
1723 [fSubtitlesDelegate resetWithTitle:nil];
1724 [fSubtitlesTable reloadData];
1726 [self enableUI: NO];
1728 if( [detector isVideoDVD] )
1730 // The chosen path was actually on a DVD, so use the raw block
1731 // device path instead.
1732 path = [detector devicePath];
1733 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1735 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1736 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
1739 /*compatible vlc not found, so we set the bool to cancel scanning to 1 */
1740 cancelScanDecrypt = 1;
1741 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1743 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");
1744 [NSApp requestUserAttention:NSCriticalRequest];
1746 if (status == NSAlertDefaultReturn)
1748 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1749 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1751 else if (status == NSAlertAlternateReturn)
1753 /* User chose to cancel the scan */
1754 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1758 /* 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 */
1759 cancelScanDecrypt = 0;
1760 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1766 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1767 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1773 if (cancelScanDecrypt == 0)
1775 /* we actually pass the scan off to libhb here */
1776 /* If there is no title number passed to scan, we use "0"
1777 * which causes the default behavior of a full source scan
1783 if (scanTitleNum > 0)
1785 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1787 /* We use our advanced pref to determine how many previews to scan */
1788 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1789 /* We use our advanced pref to determine the minimum title length to use in seconds*/
1790 uint64_t min_title_duration_seconds = 90000L * [[[NSUserDefaults standardUserDefaults] objectForKey:@"MinTitleScanSeconds"] intValue];
1791 /* set title to NULL */
1793 [self writeToActivityLog: "Minimum length of title for scan: %d", min_title_duration_seconds];
1794 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 , min_title_duration_seconds );
1795 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1799 - (IBAction) cancelScanning:(id)sender
1801 hb_scan_stop(fHandle);
1804 - (IBAction) showNewScan:(id)sender
1808 int feature_title=0; // Used to store the main feature title
1810 list = hb_get_titles( fHandle );
1812 if( !hb_list_count( list ) )
1814 /* We display a message if a valid dvd source was not chosen */
1815 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1816 SuccessfulScan = NO;
1818 // Notify ChapterTitles that there's no title
1819 [fSubtitlesDelegate resetWithTitle:nil];
1820 [fSubtitlesTable reloadData];
1822 // Notify Subtitles that there's no title
1823 [fChapterTitlesDelegate resetWithTitle:nil];
1824 [fChapterTable reloadData];
1828 if (applyQueueToScan == YES)
1830 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1831 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1834 else if (applyQueueToScan == NO)
1836 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1840 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1843 /* We increment the successful scancount here by one,
1844 which we use at the end of this function to tell the gui
1845 if this is the first successful scan since launch and whether
1846 or not we should set all settings to the defaults */
1847 currentSuccessfulScanCount++;
1849 [[fWindow toolbar] validateVisibleItems];
1851 [fSrcTitlePopUp removeAllItems];
1852 for( int i = 0; i < hb_list_count( list ); i++ )
1854 title = (hb_title_t *) hb_list_item( list, i );
1856 currentSource = [NSString stringWithUTF8String: title->name];
1857 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1858 if (!browsedSourceDisplayName)
1860 browsedSourceDisplayName = @"NoNameDetected";
1862 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1864 /* If its a queue rescan for edit, get the queue item output path */
1865 /* if not, its a new source scan. */
1866 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1867 if (applyQueueToScan == YES)
1869 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1871 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1873 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1874 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1878 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1879 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1882 /* See if this is the main feature according to libhb */
1883 if (title->index == title->job->feature)
1888 [fSrcTitlePopUp addItemWithTitle: [NSString
1889 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1890 title->name,title->index, title->hours, title->minutes,
1894 /* if we are a stream, select the first title */
1895 if (title->type == HB_STREAM_TYPE)
1897 [fSrcTitlePopUp selectItemAtIndex: 0];
1901 /* if not then select the main feature title */
1902 [fSrcTitlePopUp selectItemAtIndex: feature_title];
1904 [self titlePopUpChanged:nil];
1906 SuccessfulScan = YES;
1907 [self enableUI: YES];
1909 /* if its the initial successful scan after awakeFromNib */
1910 if (currentSuccessfulScanCount == 1)
1912 [self encodeStartStopPopUpChanged:nil];
1914 [self selectDefaultPreset:nil];
1916 // Open preview window now if it was visible when HB was closed
1917 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1918 [self showPreviewWindow:nil];
1920 // Open picture sizing window now if it was visible when HB was closed
1921 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1922 [self showPicturePanel:nil];
1925 if (applyQueueToScan == YES)
1927 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1928 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1929 [self applyQueueSettingsToMainWindow:nil];
1940 #pragma mark New Output Destination
1942 - (IBAction) browseFile: (id) sender
1944 /* Open a panel to let the user choose and update the text field */
1945 NSSavePanel * panel = [NSSavePanel savePanel];
1946 /* We get the current file name and path from the destination field here */
1947 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1948 modalForWindow: fWindow modalDelegate: self
1949 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1953 - (void) browseFileDone: (NSSavePanel *) sheet
1954 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1956 if( returnCode == NSOKButton )
1958 [fDstFile2Field setStringValue: [sheet filename]];
1959 /* Save this path to the prefs so that on next browse destination window it opens there */
1960 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1961 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1967 #pragma mark Main Window Control
1969 - (IBAction) openMainWindow: (id) sender
1971 [fWindow makeKeyAndOrderFront:nil];
1974 - (BOOL) windowShouldClose: (id) sender
1979 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1982 [fWindow makeKeyAndOrderFront:nil];
1987 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1988 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1993 #pragma mark Queue File
1995 - (void) loadQueueFile {
1996 /* We declare the default NSFileManager into fileManager */
1997 NSFileManager * fileManager = [NSFileManager defaultManager];
1998 /*We define the location of the user presets file */
1999 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
2000 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
2001 /* We check for the Queue.plist */
2002 if ([fileManager fileExistsAtPath:QueueFile] == 0)
2004 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
2007 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
2008 /* lets check to see if there is anything in the queue file .plist */
2009 if (nil == QueueFileArray)
2011 /* if not, then lets initialize an empty array */
2012 QueueFileArray = [[NSMutableArray alloc] init];
2016 /* ONLY clear out encoded items if we are single instance */
2017 if (hbInstanceNum == 1)
2019 [self clearQueueEncodedItems];
2024 - (void)addQueueFileItem
2026 [QueueFileArray addObject:[self createQueueFileItem]];
2027 [self saveQueueFileItem];
2031 - (void) removeQueueFileItem:(int) queueItemToRemove
2033 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2034 [self saveQueueFileItem];
2038 - (void)saveQueueFileItem
2040 [QueueFileArray writeToFile:QueueFile atomically:YES];
2041 [fQueueController setQueueArray: QueueFileArray];
2042 [self getQueueStats];
2045 - (void)getQueueStats
2047 /* lets get the stats on the status of the queue array */
2049 fEncodingQueueItem = 0;
2051 fCompletedCount = 0;
2055 /* We use a number system to set the encode status of the queue item
2057 * 0 == already encoded
2058 * 1 == is being encoded
2059 * 2 == is yet to be encoded
2064 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2066 while (tempObject = [enumerator nextObject])
2068 NSDictionary *thisQueueDict = tempObject;
2069 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2073 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2076 fEncodingQueueItem = i;
2077 /* check to see if we are the instance doing this encoding */
2078 if ([thisQueueDict objectForKey:@"EncodingPID"] && [[thisQueueDict objectForKey:@"EncodingPID"] intValue] == pidNum)
2080 currentQueueEncodeIndex = i;
2084 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2088 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2095 /* Set the queue status field in the main window */
2096 NSMutableString * string;
2097 if (fPendingCount == 1)
2099 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in queue", @"" ), fPendingCount];
2103 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in queue", @"" ), fPendingCount];
2105 [fQueueStatus setStringValue:string];
2108 /* Used to get the next pending queue item index and return it if found */
2109 - (int)getNextPendingQueueIndex
2111 /* initialize nextPendingIndex to -1, this value tells incrementQueueItemDone that there are no pending items in the queue */
2112 int nextPendingIndex = -1;
2113 BOOL nextPendingFound = NO;
2114 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2117 while (tempObject = [enumerator nextObject])
2119 NSDictionary *thisQueueDict = tempObject;
2120 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2 && nextPendingFound == NO) // pending
2122 nextPendingFound = YES;
2123 nextPendingIndex = [QueueFileArray indexOfObject: tempObject];
2124 [self writeToActivityLog: "getNextPendingQueueIndex next pending encod index is:%d", nextPendingIndex];
2128 return nextPendingIndex;
2132 /* This method will set any item marked as encoding back to pending
2133 * currently used right after a queue reload
2135 - (void) setQueueEncodingItemsAsPending
2137 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2139 NSMutableArray *tempArray;
2140 tempArray = [NSMutableArray array];
2141 /* we look here to see if the preset is we move on to the next one */
2142 while ( tempObject = [enumerator nextObject] )
2144 /* We want to keep any queue item that is pending or was previously being encoded */
2145 if ([[tempObject objectForKey:@"Status"] intValue] == 1 || [[tempObject objectForKey:@"Status"] intValue] == 2)
2147 /* If the queue item is marked as "encoding" (1)
2148 * then change its status back to pending (2) which effectively
2149 * puts it back into the queue to be encoded
2151 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2153 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2155 [tempArray addObject:tempObject];
2159 [QueueFileArray setArray:tempArray];
2160 [self saveQueueFileItem];
2164 /* This method will clear the queue of any encodes that are not still pending
2165 * this includes both successfully completed encodes as well as cancelled encodes */
2166 - (void) clearQueueEncodedItems
2168 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2170 NSMutableArray *tempArray;
2171 tempArray = [NSMutableArray array];
2172 /* we look here to see if the preset is we move on to the next one */
2173 while ( tempObject = [enumerator nextObject] )
2175 /* If the queue item is either completed (0) or cancelled (3) from the
2176 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2177 * NOTE: this means we retain pending (2) and also an item that is marked as
2178 * still encoding (1). If the queue has an item that is still marked as encoding
2179 * from a previous session, we can conlude that HB was either shutdown, or crashed
2180 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2182 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2184 [tempArray addObject:tempObject];
2188 [QueueFileArray removeObjectsInArray:tempArray];
2189 [self saveQueueFileItem];
2192 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2193 - (void) clearQueueAllItems
2195 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2197 NSMutableArray *tempArray;
2198 tempArray = [NSMutableArray array];
2199 /* we look here to see if the preset is we move on to the next one */
2200 while ( tempObject = [enumerator nextObject] )
2202 [tempArray addObject:tempObject];
2205 [QueueFileArray removeObjectsInArray:tempArray];
2206 [self saveQueueFileItem];
2209 /* This method will duplicate prepareJob however into the
2210 * queue .plist instead of into the job structure so it can
2211 * be recalled later */
2212 - (NSDictionary *)createQueueFileItem
2214 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2216 hb_list_t * list = hb_get_titles( fHandle );
2217 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2218 [fSrcTitlePopUp indexOfSelectedItem] );
2219 hb_job_t * job = title->job;
2223 /* We use a number system to set the encode status of the queue item
2224 * 0 == already encoded
2225 * 1 == is being encoded
2226 * 2 == is yet to be encoded
2229 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2230 /* Source and Destination Information */
2232 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2233 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2234 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2235 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2237 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2238 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2240 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2242 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2244 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2246 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2248 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2250 /* Chapter encode info */
2251 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2252 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2253 /* Time (pts) encode info */
2254 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2255 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2256 /* Frame number encode info */
2257 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2258 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2261 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2262 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2263 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2265 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2267 /* Lets get the preset info if there is any */
2268 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2269 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2271 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2272 /* Chapter Markers*/
2273 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2274 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2276 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2280 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2283 /* We need to get the list of chapter names to put into an array and store
2284 * in our queue, so they can be reapplied in prepareJob when this queue
2285 * item comes up if Chapter Markers is set to on.
2288 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2289 int chaptercount = hb_list_count( fTitle->list_chapter );
2290 for( i = 0; i < chaptercount; i++ )
2292 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2293 if( chapter != NULL )
2295 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2298 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2299 [ChapterNamesArray autorelease];
2301 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2302 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2303 /* Mux mp4 with http optimization */
2304 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2305 /* Add iPod uuid atom */
2306 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2310 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2311 /* x264 Option String */
2312 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2314 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2315 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2316 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2317 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2319 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2320 [queueFileJob setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
2322 /* 2 Pass Encoding */
2323 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2324 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2325 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2327 /* Picture Sizing */
2328 /* Use Max Picture settings for whatever the dvd is.*/
2329 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2330 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2331 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2332 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2333 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2334 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2335 /* if we are custom anamorphic, store the exact storage, par and display dims */
2336 if (fTitle->job->anamorphic.mode == 3)
2338 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2340 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2341 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2343 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2344 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2346 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2347 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2350 NSString * pictureSummary;
2351 pictureSummary = [fPictureSizeField stringValue];
2352 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2353 /* Set crop settings here */
2354 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2355 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2356 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2357 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2358 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2360 /* Picture Filters */
2361 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2362 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2364 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2365 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2366 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2368 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2369 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2371 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2372 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2374 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2376 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2379 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2381 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2382 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2383 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2384 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2385 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2386 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2387 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2389 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2391 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2392 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2393 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2394 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2395 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2396 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2397 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2399 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2401 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2402 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2403 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2404 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2405 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2406 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2407 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2409 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2411 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2412 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2413 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2414 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2415 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2416 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2417 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2421 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2422 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2423 [subtitlesArray autorelease];
2425 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2427 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2429 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2432 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2436 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2439 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2440 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2441 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2443 /* Picture Sizing */
2444 /* Use Max Picture settings for whatever the dvd is.*/
2445 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2446 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2447 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2448 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2449 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2451 /* Set crop settings here */
2452 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2453 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2454 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2455 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2456 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2460 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2462 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2463 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2464 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2465 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2467 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2469 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2470 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2471 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2472 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2474 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2476 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2477 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2478 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2479 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2481 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2483 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2484 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2485 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2486 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2489 /* we need to auto relase the queueFileJob and return it */
2490 [queueFileJob autorelease];
2491 return queueFileJob;
2495 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2496 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2498 NSUInteger index = [indexSet lastIndex];
2499 NSUInteger aboveInsertIndexCount = 0;
2502 NSUInteger removeIndex;
2504 if (index >= insertIndex)
2506 removeIndex = index + aboveInsertIndexCount;
2507 aboveInsertIndexCount++;
2511 removeIndex = index;
2515 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2516 [QueueFileArray removeObjectAtIndex:removeIndex];
2517 [QueueFileArray insertObject:object atIndex:insertIndex];
2520 index = [indexSet indexLessThanIndex:index];
2522 /* We save all of the Queue data here
2523 * and it also gets sent back to the queue controller*/
2524 [self saveQueueFileItem];
2530 #pragma mark Queue Job Processing
2532 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2534 /* Mark the encode just finished as done (status 0)*/
2535 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2537 /* We save all of the Queue data here */
2538 [self saveQueueFileItem];
2540 /* Since we have now marked a queue item as done
2541 * we can go ahead and increment currentQueueEncodeIndex
2542 * so that if there is anything left in the queue we can
2543 * go ahead and move to the next item if we want to */
2544 int queueItems = [QueueFileArray count];
2545 /* Check to see if there are any more pending items in the queue */
2546 int newQueueItemIndex = [self getNextPendingQueueIndex];
2547 /* If we still have more pending items in our queue, lets go to the next one */
2548 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
2550 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
2551 currentQueueEncodeIndex = newQueueItemIndex;
2552 /* 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 */
2553 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2554 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
2555 [self saveQueueFileItem];
2556 /* now we can go ahead and scan the new pending queue item */
2557 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2562 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
2563 /*Since there are no more items to encode, go to queueCompletedAlerts for user specified alerts after queue completed*/
2564 [self queueCompletedAlerts];
2568 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2569 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2571 /* Tell HB to output a new activity log file for this encode */
2572 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2574 /* We now flag the queue item as being owned by this instance of HB using the PID */
2575 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:pidNum] forKey:@"EncodingPID"];
2576 /* Get the currentQueueEncodeNameString from the queue item to display in the status field */
2577 currentQueueEncodeNameString = [[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"] lastPathComponent]retain];
2578 /* We save all of the Queue data here */
2579 [self saveQueueFileItem];
2581 /* use a bool to determine whether or not we can decrypt using vlc */
2582 BOOL cancelScanDecrypt = 0;
2583 /* set the bool so that showNewScan knows to apply the appropriate queue
2584 * settings as this is a queue rescan
2586 NSString *path = scanPath;
2587 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2589 if( [detector isVideoDVD] )
2591 // The chosen path was actually on a DVD, so use the raw block
2592 // device path instead.
2593 path = [detector devicePath];
2594 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2596 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2597 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
2600 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2601 cancelScanDecrypt = 1;
2602 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2604 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");
2605 [NSApp requestUserAttention:NSCriticalRequest];
2607 if (status == NSAlertDefaultReturn)
2609 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2610 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2612 else if (status == NSAlertAlternateReturn)
2614 /* User chose to cancel the scan */
2615 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2619 /* 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 */
2620 cancelScanDecrypt = 0;
2621 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2627 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2629 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2633 if (cancelScanDecrypt == 0)
2635 /* we actually pass the scan off to libhb here */
2636 /* If there is no title number passed to scan, we use "0"
2637 * which causes the default behavior of a full source scan
2643 if (scanTitleNum > 0)
2645 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2648 /* We use our advance pref to determine how many previews to scan */
2649 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2650 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 , 0 );
2654 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2655 - (void) processNewQueueEncode
2657 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2658 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2659 hb_job_t * job = title->job;
2661 if( !hb_list_count( list ) )
2663 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2666 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2667 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2668 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2669 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2673 * If scanning we need to do some extra setup of the job.
2675 if( job->indepth_scan == 1 )
2680 * When subtitle scan is enabled do a fast pre-scan job
2681 * which will determine which subtitles to enable, if any.
2684 x264opts_tmp = job->x264opts;
2686 job->x264opts = NULL;
2688 job->indepth_scan = 1;
2692 * Add the pre-scan job
2694 hb_add( fQueueEncodeLibhb, job );
2695 job->x264opts = x264opts_tmp;
2699 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2701 job->indepth_scan = 0;
2707 hb_add( fQueueEncodeLibhb, job );
2711 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2712 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2714 hb_add( fQueueEncodeLibhb, job );
2719 job->indepth_scan = 0;
2722 hb_add( fQueueEncodeLibhb, job );
2725 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2726 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2727 /* Lets mark our new encode as 1 or "Encoding" */
2728 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2729 [self saveQueueFileItem];
2731 /* we need to clean up the subtitle tracks after the job(s) have been set */
2732 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2734 for(ii = 0; ii < num_subtitle_tracks; ii++)
2736 hb_subtitle_t * subtitle;
2737 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2740 hb_list_rem(job->list_subtitle, subtitle);
2744 /* We should be all setup so let 'er rip */
2749 #pragma mark Queue Item Editing
2751 /* Rescans the chosen queue item back into the main window */
2752 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2754 fqueueEditRescanItemNum = selectedQueueItem;
2755 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2756 applyQueueToScan = YES;
2757 /* Set the browsedSourceDisplayName for showNewScan */
2758 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2759 [self performScan:scanPath scanTitleNum:scanTitleNum];
2763 /* We use this method after a queue item rescan for edit.
2764 * it largely mirrors -selectPreset in terms of structure.
2765 * Assumes that a queue item has been reloaded into the main window.
2767 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2769 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2770 hb_job_t * job = fTitle->job;
2773 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2775 /* Set title number and chapters */
2776 /* since the queue only scans a single title, its already been selected in showNewScan
2777 so do not try to reset it here. However if we do decide to do full source scans on
2778 a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2779 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2781 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2782 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2785 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2786 [self formatPopUpChanged:nil];
2788 /* Chapter Markers*/
2789 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2790 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2791 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2792 /* Mux mp4 with http optimization */
2793 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2796 /* We set the advanced opt string here if applicable*/
2797 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2798 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2800 /* Lets run through the following functions to get variables set there */
2801 [self videoEncoderPopUpChanged:nil];
2802 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2803 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2804 [self calculateBitrate:nil];
2807 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2809 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2810 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2811 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2812 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2813 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2814 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2815 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2816 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2818 /* For the quality slider we need to convert the old percent's to the new rf scales */
2819 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2820 [fVidQualitySlider setFloatValue:rf];
2825 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2826 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2828 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2832 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2833 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2837 [self videoMatrixChanged:nil];
2839 /* Video framerate */
2840 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2841 detected framerate in the fVidRatePopUp so we use index 0*/
2842 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2844 [fVidRatePopUp selectItemAtIndex: 0];
2848 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2851 /* 2 Pass Encoding */
2852 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2853 [self twoPassCheckboxChanged:nil];
2854 /* Turbo 1st pass for 2 Pass Encoding */
2855 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2860 /* Now lets add our new tracks to the audio list here */
2861 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2863 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2864 [self audioTrackPopUpChanged: fAudLang1PopUp];
2865 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2866 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2868 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2870 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2871 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2873 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2874 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2878 [fAudLang1PopUp selectItemAtIndex: 0];
2879 [self audioTrackPopUpChanged: fAudLang1PopUp];
2881 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2883 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2884 [self audioTrackPopUpChanged: fAudLang2PopUp];
2885 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2886 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2888 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2890 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2891 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2893 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2894 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2898 [fAudLang2PopUp selectItemAtIndex: 0];
2899 [self audioTrackPopUpChanged: fAudLang2PopUp];
2901 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2903 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2904 [self audioTrackPopUpChanged: fAudLang3PopUp];
2905 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2906 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2908 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2910 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2911 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2913 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2914 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2918 [fAudLang3PopUp selectItemAtIndex: 0];
2919 [self audioTrackPopUpChanged: fAudLang3PopUp];
2921 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2923 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2924 [self audioTrackPopUpChanged: fAudLang4PopUp];
2925 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2926 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2928 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2930 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2931 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2933 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2934 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2938 [fAudLang4PopUp selectItemAtIndex: 0];
2939 [self audioTrackPopUpChanged: fAudLang4PopUp];
2943 /* Crashy crashy right now, working on it */
2944 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2945 [fSubtitlesTable reloadData];
2946 /* Picture Settings */
2948 /* If Cropping is set to custom, then recall all four crop values from
2949 when the preset was created and apply them */
2950 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2952 [fPictureController setAutoCrop:NO];
2954 /* Here we use the custom crop values saved at the time the preset was saved */
2955 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2956 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2957 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2958 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2961 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2963 [fPictureController setAutoCrop:YES];
2964 /* Here we use the auto crop values determined right after scan */
2965 job->crop[0] = AutoCropTop;
2966 job->crop[1] = AutoCropBottom;
2967 job->crop[2] = AutoCropLeft;
2968 job->crop[3] = AutoCropRight;
2972 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2974 /* we check to make sure the presets width/height does not exceed the sources width/height */
2975 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2977 /* if so, then we use the sources height and width to avoid scaling up */
2978 //job->width = fTitle->width;
2979 //job->height = fTitle->height;
2980 [self revertPictureSizeToMax:nil];
2982 else // source width/height is >= the preset height/width
2984 /* we can go ahead and use the presets values for height and width */
2985 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2986 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2988 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2989 if (job->keep_ratio == 1)
2991 hb_fix_aspect( job, HB_KEEP_WIDTH );
2992 if( job->height > fTitle->height )
2994 job->height = fTitle->height;
2995 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2998 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2999 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3003 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
3004 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
3005 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
3008 [fPictureController setUseDecomb:1];
3009 [fPictureController setDecomb:0];
3010 [fPictureController setDeinterlace:0];
3011 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3013 /* we are using decomb */
3015 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3017 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3019 /* if we are using "Custom" in the decomb setting, also set the custom string*/
3020 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3022 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
3028 /* We are using Deinterlace */
3030 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3032 [fPictureController setUseDecomb:0];
3033 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3034 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3035 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3037 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
3044 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3046 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3047 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3048 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3050 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
3055 [fPictureController setDetelecine:0];
3059 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3061 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3062 /* if we are using "Custom" in the denoise setting, also set the custom string*/
3063 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3065 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
3070 [fPictureController setDenoise:0];
3074 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3076 /* if its a one, then its the old on/off deblock, set on to 5*/
3077 [fPictureController setDeblock:5];
3081 /* use the settings intValue */
3082 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3085 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3087 [fPictureController setGrayscale:1];
3091 [fPictureController setGrayscale:0];
3094 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3095 [fPictureController SetTitle:fTitle];
3096 [self calculatePictureSizing:nil];
3098 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3099 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3100 //[queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3101 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3103 /* Deselect the currently selected Preset if there is one*/
3104 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3105 //[self selectPreset:nil];
3107 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3108 /* Change UI to show "Custom" settings are being used */
3109 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3111 curUserPresetChosenNum = nil;
3115 /* Deselect the currently selected Preset if there is one*/
3116 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3117 /* Change UI to show "Custom" settings are being used */
3118 [fPresetSelectedDisplay setStringValue: @"Custom"];
3120 //curUserPresetChosenNum = nil;
3123 /* We need to set this bool back to NO, in case the user wants to do a scan */
3124 //applyQueueToScan = NO;
3126 /* Not that source is loaded and settings applied, delete the queue item from the queue */
3127 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3128 [self removeQueueFileItem:fqueueEditRescanItemNum];
3134 #pragma mark Live Preview
3135 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3136 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3139 - (void) prepareJobForPreview
3141 hb_list_t * list = hb_get_titles( fHandle );
3142 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3143 [fSrcTitlePopUp indexOfSelectedItem] );
3144 hb_job_t * job = title->job;
3145 hb_audio_config_t * audio;
3146 /* set job->angle for libdvdnav */
3147 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3148 /* Chapter selection */
3149 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3150 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3152 /* Format (Muxer) and Video Encoder */
3153 job->mux = [[fDstFormatPopUp selectedItem] tag];
3154 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3156 job->chapter_markers = 0;
3158 if( job->vcodec & HB_VCODEC_X264 )
3161 /* Below Sends x264 options to the core library if x264 is selected*/
3162 /* Lets use this as per Nyx, Thanks Nyx!*/
3163 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3164 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3165 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3170 /* Video settings */
3171 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3172 * and detelecine is on, so we handle that in the logic below
3175 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3177 /* a specific framerate has been chosen */
3178 job->vrate = 27000000;
3179 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3180 /* We are not same as source so we set job->cfr to 1
3181 * to enable constant frame rate since user has specified
3182 * a specific framerate*/
3183 if ([fFrameratePfrCheck state] == 1)
3194 /* We are same as source (variable) */
3195 job->vrate = title->rate;
3196 job->vrate_base = title->rate_base;
3197 /* We are same as source so we set job->cfr to 0
3198 * to enable true same as source framerate */
3200 /* If we are same as source and we have detelecine on, we need to turn on
3203 if ([fPictureController detelecine] == 1)
3209 switch( [fVidQualityMatrix selectedRow] )
3213 Bitrate should already have been calculated and displayed
3214 in fVidBitrateField, so let's just use it */
3216 job->vquality = -1.0;
3217 job->vbitrate = [fVidBitrateField intValue];
3220 job->vquality = [fVidQualityRFField floatValue];
3225 /* Subtitle settings */
3226 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3233 bool one_burned = FALSE;
3236 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3238 while (tempObject = [enumerator nextObject])
3241 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3242 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3243 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3244 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3246 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3247 * we want to ignore it for display as well as encoding.
3251 /* if i is 0, then we are in the first item of the subtitles which we need to
3252 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3253 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3256 /* if we are on the first track and using "Foreign Audio Search" */
3257 if (i == 0 && subtitle == 1)
3259 /* NOTE: Currently foreign language search is borked for preview.
3260 * Commented out but left in for initial commit. */
3263 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3265 job->indepth_scan = 1;
3269 job->select_subtitle_config.dest = PASSTHRUSUB;
3273 job->select_subtitle_config.dest = RENDERSUB;
3276 job->select_subtitle_config.force = force;
3277 job->select_subtitle_config.default_track = def;
3282 /* for the actual source tracks, we must subtract the non source entries so
3283 * that the menu index matches the source subtitle_list index for convenience */
3286 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3287 * Foreign Language Search is 1) so subtract 2 */
3288 subtitle = subtitle - 2;
3292 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3295 subtitle = subtitle - 1;
3298 /* We are setting a source subtitle so access the source subtitle info */
3299 hb_subtitle_t * subt;
3301 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3303 /* if we are getting the subtitles from an external srt file */
3304 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3306 hb_subtitle_config_t sub_config;
3308 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3310 /* we need to srncpy file path and char code */
3311 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3312 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3314 sub_config.force = 0;
3315 sub_config.dest = PASSTHRUSUB;
3316 sub_config.default_track = def;
3318 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3323 hb_subtitle_config_t sub_config = subt->config;
3325 if ( !burned && subt->format == PICTURESUB )
3327 sub_config.dest = PASSTHRUSUB;
3329 else if ( burned && subt->format == PICTURESUB )
3331 // Only allow one subtitle to be burned into the video
3336 sub_config.force = force;
3337 sub_config.default_track = def;
3338 hb_subtitle_add( job, &sub_config, subtitle );
3348 [subtitlesArray autorelease];
3351 /* Audio tracks and mixdowns */
3352 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3353 int audiotrack_count = hb_list_count(job->list_audio);
3354 for( int i = 0; i < audiotrack_count;i++)
3356 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3357 hb_list_rem(job->list_audio, temp_audio);
3359 /* Now lets add our new tracks to the audio list here */
3360 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3362 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3363 hb_audio_config_init(audio);
3364 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3365 /* We go ahead and assign values to our audio->out.<properties> */
3366 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3367 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3368 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3369 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3370 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3371 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3373 hb_audio_add( job, audio );
3376 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3378 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3379 hb_audio_config_init(audio);
3380 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3381 /* We go ahead and assign values to our audio->out.<properties> */
3382 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3383 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3384 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3385 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3386 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3387 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3389 hb_audio_add( job, audio );
3394 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3396 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3397 hb_audio_config_init(audio);
3398 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3399 /* We go ahead and assign values to our audio->out.<properties> */
3400 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3401 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3402 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3403 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3404 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3405 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3407 hb_audio_add( job, audio );
3412 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3414 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3415 hb_audio_config_init(audio);
3416 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3417 /* We go ahead and assign values to our audio->out.<properties> */
3418 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3419 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3420 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3421 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3422 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3423 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3425 hb_audio_add( job, audio );
3434 /* Though Grayscale is not really a filter, per se
3435 * we put it here since its in the filters panel
3438 if ([fPictureController grayscale])
3447 /* Initialize the filters list */
3448 job->filters = hb_list_init();
3450 /* Now lets call the filters if applicable.
3451 * The order of the filters is critical
3455 hb_filter_detelecine.settings = NULL;
3456 if ([fPictureController detelecine] == 1)
3458 /* use a custom detelecine string */
3459 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3460 hb_list_add( job->filters, &hb_filter_detelecine );
3462 if ([fPictureController detelecine] == 2)
3465 hb_list_add( job->filters, &hb_filter_detelecine );
3470 if ([fPictureController useDecomb] == 1)
3473 /* we add the custom string if present */
3474 hb_filter_decomb.settings = NULL;
3475 if ([fPictureController decomb] == 1)
3477 /* use a custom decomb string */
3478 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3479 hb_list_add( job->filters, &hb_filter_decomb );
3481 if ([fPictureController decomb] == 2)
3483 /* Run old deinterlacer fd by default */
3484 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3485 hb_list_add( job->filters, &hb_filter_decomb );
3492 if ([fPictureController deinterlace] == 1)
3494 /* we add the custom string if present */
3495 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3496 hb_list_add( job->filters, &hb_filter_deinterlace );
3498 else if ([fPictureController deinterlace] == 2)
3500 /* Run old deinterlacer fd by default */
3501 hb_filter_deinterlace.settings = "-1";
3502 hb_list_add( job->filters, &hb_filter_deinterlace );
3504 else if ([fPictureController deinterlace] == 3)
3506 /* Yadif mode 0 (without spatial deinterlacing.) */
3507 hb_filter_deinterlace.settings = "2";
3508 hb_list_add( job->filters, &hb_filter_deinterlace );
3510 else if ([fPictureController deinterlace] == 4)
3512 /* Yadif (with spatial deinterlacing) */
3513 hb_filter_deinterlace.settings = "0";
3514 hb_list_add( job->filters, &hb_filter_deinterlace );
3520 if ([fPictureController denoise] == 1) // custom in popup
3522 /* we add the custom string if present */
3523 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3524 hb_list_add( job->filters, &hb_filter_denoise );
3526 else if ([fPictureController denoise] == 2) // Weak in popup
3528 hb_filter_denoise.settings = "2:1:2:3";
3529 hb_list_add( job->filters, &hb_filter_denoise );
3531 else if ([fPictureController denoise] == 3) // Medium in popup
3533 hb_filter_denoise.settings = "3:2:2:3";
3534 hb_list_add( job->filters, &hb_filter_denoise );
3536 else if ([fPictureController denoise] == 4) // Strong in popup
3538 hb_filter_denoise.settings = "7:7:5:5";
3539 hb_list_add( job->filters, &hb_filter_denoise );
3543 /* Deblock (uses pp7 default) */
3544 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3545 * the macgui's purposes a value of 0 actually means to not even use the filter
3546 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3548 if ([fPictureController deblock] != 0)
3550 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3551 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3552 hb_list_add( job->filters, &hb_filter_deblock );
3559 #pragma mark Job Handling
3565 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3566 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3567 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3568 hb_job_t * job = title->job;
3569 hb_audio_config_t * audio;
3570 /* Title Angle for dvdnav */
3571 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3573 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3575 /* Chapter selection */
3576 [self writeToActivityLog: "Start / Stop set to chapters"];
3577 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3578 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3580 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3582 /* we are pts based start / stop */
3583 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3585 /* Point A to Point B. Time to time in seconds.*/
3586 /* get the start seconds from the start seconds field */
3587 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3588 job->pts_to_start = start_seconds * 90000LL;
3589 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3590 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3591 job->pts_to_stop = stop_seconds * 90000LL;
3594 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3596 /* we are frame based start / stop */
3597 [self writeToActivityLog: "Start / Stop set to frames ..."];
3599 /* Point A to Point B. Frame to frame */
3600 /* get the start frame from the start frame field */
3601 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3602 job->frame_to_start = start_frame;
3603 /* get the frame to stop on from the end frame field */
3604 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3605 job->frame_to_stop = stop_frame;
3612 /* Format (Muxer) and Video Encoder */
3613 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3614 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3617 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3618 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3620 job->largeFileSize = 1;
3624 job->largeFileSize = 0;
3626 /* We set http optimized mp4 here */
3627 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3629 job->mp4_optimize = 1;
3633 job->mp4_optimize = 0;
3637 /* We set the chapter marker extraction here based on the format being
3638 mpeg4 or mkv and the checkbox being checked */
3639 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3641 job->chapter_markers = 1;
3643 /* now lets get our saved chapter names out the array in the queue file
3644 * and insert them back into the title chapter list. We have it here,
3645 * because unless we are inserting chapter markers there is no need to
3646 * spend the overhead of iterating through the chapter names array imo
3647 * Also, note that if for some reason we don't apply chapter names, the
3648 * chapters just come out 001, 002, etc. etc.
3651 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3653 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3655 while (tempObject = [enumerator nextObject])
3657 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3658 if( chapter != NULL )
3660 strncpy( chapter->title, [tempObject UTF8String], 1023);
3661 chapter->title[1023] = '\0';
3668 job->chapter_markers = 0;
3671 if( job->vcodec & HB_VCODEC_X264 )
3673 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3683 /* Below Sends x264 options to the core library if x264 is selected*/
3684 /* Lets use this as per Nyx, Thanks Nyx!*/
3685 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3686 /* Turbo first pass if two pass and Turbo First pass is selected */
3687 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3689 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3690 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3691 /* append the "Turbo" string variable to the existing opts string.
3692 Note: the "Turbo" string must be appended, not prepended to work properly*/
3693 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3694 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3698 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3704 /* Picture Size Settings */
3705 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3706 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3708 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3709 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3710 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3711 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3713 /* insert our custom values here for capuj */
3714 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3715 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3717 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3719 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3720 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3722 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3723 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3726 /* Here we use the crop values saved at the time the preset was saved */
3727 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3728 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3729 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3730 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3732 /* Video settings */
3735 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3736 * and detelecine is on, so we handle that in the logic below
3739 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3741 /* a specific framerate has been chosen */
3742 job->vrate = 27000000;
3743 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3744 /* We are not same as source so we set job->cfr to 1
3745 * to enable constant frame rate since user has specified
3746 * a specific framerate*/
3748 if ([[queueToApply objectForKey:@"VideoFrameratePFR"] intValue] == 1)
3759 /* We are same as source (variable) */
3760 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3761 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3762 /* We are same as source so we set job->cfr to 0
3763 * to enable true same as source framerate */
3765 /* If we are same as source and we have detelecine on, we need to turn on
3768 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3774 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3777 Bitrate should already have been calculated and displayed
3778 in fVidBitrateField, so let's just use it same as abr*/
3779 job->vquality = -1.0;
3780 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3782 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3784 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3789 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3794 #pragma mark Process Subtitles to libhb
3796 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3797 * which means that we need to account for the offset of non source language settings in from
3798 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3799 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3800 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3801 * to the source tracks position in title->list_subtitle.
3808 bool one_burned = FALSE;
3811 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3813 while (tempObject = [enumerator nextObject])
3816 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3817 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3818 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3819 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3821 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3822 * we want to ignore it for display as well as encoding.
3826 /* if i is 0, then we are in the first item of the subtitles which we need to
3827 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3828 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3831 /* if we are on the first track and using "Foreign Audio Search" */
3832 if (i == 0 && subtitle == 1)
3834 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3836 job->indepth_scan = 1;
3840 job->select_subtitle_config.dest = PASSTHRUSUB;
3844 job->select_subtitle_config.dest = RENDERSUB;
3847 job->select_subtitle_config.force = force;
3848 job->select_subtitle_config.default_track = def;
3853 /* for the actual source tracks, we must subtract the non source entries so
3854 * that the menu index matches the source subtitle_list index for convenience */
3857 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3858 * Foreign Language Search is 1) so subtract 2 */
3859 subtitle = subtitle - 2;
3863 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3866 subtitle = subtitle - 1;
3869 /* We are setting a source subtitle so access the source subtitle info */
3870 hb_subtitle_t * subt;
3872 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3874 /* if we are getting the subtitles from an external srt file */
3875 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3877 hb_subtitle_config_t sub_config;
3879 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3881 /* we need to srncpy file name and codeset */
3882 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3883 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3885 sub_config.force = 0;
3886 sub_config.dest = PASSTHRUSUB;
3887 sub_config.default_track = def;
3889 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3895 hb_subtitle_config_t sub_config = subt->config;
3897 if ( !burned && subt->format == PICTURESUB )
3899 sub_config.dest = PASSTHRUSUB;
3901 else if ( burned && subt->format == PICTURESUB )
3903 // Only allow one subtitle to be burned into the video
3908 sub_config.force = force;
3909 sub_config.default_track = def;
3910 hb_subtitle_add( job, &sub_config, subtitle );
3921 /* Audio tracks and mixdowns */
3922 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3923 int audiotrack_count = hb_list_count(job->list_audio);
3924 for( int i = 0; i < audiotrack_count;i++)
3926 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3927 hb_list_rem(job->list_audio, temp_audio);
3929 /* Now lets add our new tracks to the audio list here */
3930 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3932 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3933 hb_audio_config_init(audio);
3934 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3935 /* We go ahead and assign values to our audio->out.<properties> */
3936 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3937 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3938 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3939 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3940 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3941 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3943 hb_audio_add( job, audio );
3946 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3949 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3950 hb_audio_config_init(audio);
3951 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3952 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3953 /* We go ahead and assign values to our audio->out.<properties> */
3954 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3955 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3956 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3957 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3958 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3959 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3961 hb_audio_add( job, audio );
3965 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3967 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3968 hb_audio_config_init(audio);
3969 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3970 /* We go ahead and assign values to our audio->out.<properties> */
3971 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3972 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3973 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3974 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3975 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3976 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3978 hb_audio_add( job, audio );
3982 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3984 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3985 hb_audio_config_init(audio);
3986 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3987 /* We go ahead and assign values to our audio->out.<properties> */
3988 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3989 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3990 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3991 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3992 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3993 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3995 hb_audio_add( job, audio );
4001 job->filters = hb_list_init();
4003 /* Now lets call the filters if applicable.
4004 * The order of the filters is critical
4007 hb_filter_detelecine.settings = NULL;
4008 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4010 /* use a custom detelecine string */
4011 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4012 hb_list_add( job->filters, &hb_filter_detelecine );
4014 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4016 /* Use libhb's default values */
4017 hb_list_add( job->filters, &hb_filter_detelecine );
4020 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4023 /* we add the custom string if present */
4024 hb_filter_decomb.settings = NULL;
4025 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4027 /* use a custom decomb string */
4028 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4029 hb_list_add( job->filters, &hb_filter_decomb );
4031 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4033 /* Use libhb default */
4034 hb_list_add( job->filters, &hb_filter_decomb );
4042 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4044 /* we add the custom string if present */
4045 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4046 hb_list_add( job->filters, &hb_filter_deinterlace );
4048 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4050 /* Run old deinterlacer fd by default */
4051 hb_filter_deinterlace.settings = "-1";
4052 hb_list_add( job->filters, &hb_filter_deinterlace );
4054 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4056 /* Yadif mode 0 (without spatial deinterlacing.) */
4057 hb_filter_deinterlace.settings = "2";
4058 hb_list_add( job->filters, &hb_filter_deinterlace );
4060 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4062 /* Yadif (with spatial deinterlacing) */
4063 hb_filter_deinterlace.settings = "0";
4064 hb_list_add( job->filters, &hb_filter_deinterlace );
4070 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4072 /* we add the custom string if present */
4073 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4074 hb_list_add( job->filters, &hb_filter_denoise );
4076 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4078 hb_filter_denoise.settings = "2:1:2:3";
4079 hb_list_add( job->filters, &hb_filter_denoise );
4081 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4083 hb_filter_denoise.settings = "3:2:2:3";
4084 hb_list_add( job->filters, &hb_filter_denoise );
4086 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4088 hb_filter_denoise.settings = "7:7:5:5";
4089 hb_list_add( job->filters, &hb_filter_denoise );
4093 /* Deblock (uses pp7 default) */
4094 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
4095 * the macgui's purposes a value of 0 actually means to not even use the filter
4096 * current hb_filter_deblock.settings valid ranges are from 5 - 15
4098 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4100 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4101 hb_list_add( job->filters, &hb_filter_deblock );
4103 [self writeToActivityLog: "prepareJob exiting"];
4108 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4110 - (IBAction) addToQueue: (id) sender
4112 /* We get the destination directory from the destination field here */
4113 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4114 /* We check for a valid destination here */
4115 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4117 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4124 BOOL fileExistsInQueue;
4125 fileExistsInQueue = NO;
4127 /* We check for and existing file here */
4128 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4133 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4135 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4137 while (tempObject = [enumerator nextObject])
4139 NSDictionary *thisQueueDict = tempObject;
4140 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4142 fileExistsInQueue = YES;
4148 if(fileExists == YES)
4150 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4151 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4152 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4153 NULL, NULL, [NSString stringWithFormat:
4154 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4155 [fDstFile2Field stringValue]] );
4157 else if (fileExistsInQueue == YES)
4159 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4160 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4161 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4162 NULL, NULL, [NSString stringWithFormat:
4163 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4164 [fDstFile2Field stringValue]] );
4168 [self doAddToQueue];
4172 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4173 the user if they want to overwrite an exiting movie file.
4175 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4176 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4178 if( returnCode == NSAlertAlternateReturn )
4179 [self doAddToQueue];
4182 - (void) doAddToQueue
4184 [self addQueueFileItem ];
4189 /* Rip: puts up an alert before ultimately calling doRip
4191 - (IBAction) Rip: (id) sender
4193 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4194 /* Rip or Cancel ? */
4196 hb_get_state2( fQueueEncodeLibhb, &s );
4198 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4200 [self Cancel: sender];
4204 /* We check to see if we need to warn the user that the computer will go to sleep
4205 or shut down when encoding is finished */
4206 [self remindUserOfSleepOrShutdown];
4208 // If there are pending jobs in the queue, then this is a rip the queue
4209 if (fPendingCount > 0)
4211 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4212 /* here lets start the queue with the first pending item */
4213 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4218 // Before adding jobs to the queue, check for a valid destination.
4220 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4221 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4223 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4227 /* We check for duplicate name here */
4228 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4230 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4231 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4232 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4233 NULL, NULL, [NSString stringWithFormat:
4234 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4235 [fDstFile2Field stringValue]] );
4237 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4241 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4242 otherwise, just rip the queue */
4243 if(fPendingCount == 0)
4245 [self doAddToQueue];
4248 /* go right to processing the new queue encode */
4249 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4250 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4255 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4256 want to overwrite an exiting movie file.
4258 - (void) overWriteAlertDone: (NSWindow *) sheet
4259 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4261 if( returnCode == NSAlertAlternateReturn )
4263 /* if there are no jobs in the queue, then add this one to the queue and rip
4264 otherwise, just rip the queue */
4265 if( fPendingCount == 0 )
4267 [self doAddToQueue];
4270 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4271 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4272 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4277 - (void) remindUserOfSleepOrShutdown
4279 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4281 /*Warn that computer will sleep after encoding*/
4284 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);
4285 [NSApp requestUserAttention:NSCriticalRequest];
4286 if ( reminduser == NSAlertAlternateReturn )
4288 [self showPreferencesWindow:nil];
4291 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4293 /*Warn that computer will shut down after encoding*/
4296 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);
4297 [NSApp requestUserAttention:NSCriticalRequest];
4298 if ( reminduser == NSAlertAlternateReturn )
4300 [self showPreferencesWindow:nil];
4309 /* Let libhb do the job */
4310 hb_start( fQueueEncodeLibhb );
4311 /*set the fEncodeState State */
4316 //------------------------------------------------------------------------------------
4317 // Displays an alert asking user if the want to cancel encoding of current job.
4318 // Cancel: returns immediately after posting the alert. Later, when the user
4319 // acknowledges the alert, doCancelCurrentJob is called.
4320 //------------------------------------------------------------------------------------
4321 - (IBAction)Cancel: (id)sender
4323 if (!fQueueController) return;
4325 hb_pause( fQueueEncodeLibhb );
4326 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4328 // Which window to attach the sheet to?
4329 NSWindow * docWindow;
4330 if ([sender respondsToSelector: @selector(window)])
4331 docWindow = [sender window];
4333 docWindow = fWindow;
4335 NSBeginCriticalAlertSheet(
4337 NSLocalizedString(@"Continue Encoding", nil),
4338 NSLocalizedString(@"Cancel Current and Stop", nil),
4339 NSLocalizedString(@"Cancel Current and Continue", nil),
4341 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4342 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4344 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4347 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4349 hb_resume( fQueueEncodeLibhb );
4350 if (returnCode == NSAlertOtherReturn)
4352 [self doCancelCurrentJob]; // <- this also stops libhb
4354 if (returnCode == NSAlertAlternateReturn)
4356 [self doCancelCurrentJobAndStop];
4360 //------------------------------------------------------------------------------------
4361 // Cancels and deletes the current job and stops libhb from processing the remaining
4363 //------------------------------------------------------------------------------------
4364 - (void) doCancelCurrentJob
4366 // Stop the current job. hb_stop will only cancel the current pass and then set
4367 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4368 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4369 // remaining passes of the job and then start the queue back up if there are any
4373 hb_stop( fQueueEncodeLibhb );
4375 // Delete all remaining jobs since libhb doesn't do this on its own.
4377 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4378 hb_rem( fQueueEncodeLibhb, job );
4380 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4382 // now that we've stopped the currently encoding job, lets mark it as cancelled
4383 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4384 // and as always, save it in the queue .plist...
4385 /* We save all of the Queue data here */
4386 [self saveQueueFileItem];
4388 // ... and see if there are more items left in our queue
4389 int queueItems = [QueueFileArray count];
4390 /* If we still have more items in our queue, lets go to the next one */
4391 /* Check to see if there are any more pending items in the queue */
4392 int newQueueItemIndex = [self getNextPendingQueueIndex];
4393 /* If we still have more pending items in our queue, lets go to the next one */
4394 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
4396 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
4397 currentQueueEncodeIndex = newQueueItemIndex;
4398 /* 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 */
4399 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
4400 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
4401 [self saveQueueFileItem];
4402 /* now we can go ahead and scan the new pending queue item */
4403 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4408 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
4412 - (void) doCancelCurrentJobAndStop
4414 hb_stop( fQueueEncodeLibhb );
4416 // Delete all remaining jobs since libhb doesn't do this on its own.
4418 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4419 hb_rem( fQueueEncodeLibhb, job );
4422 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4424 // now that we've stopped the currently encoding job, lets mark it as cancelled
4425 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4426 // and as always, save it in the queue .plist...
4427 /* We save all of the Queue data here */
4428 [self saveQueueFileItem];
4429 // so now lets move to
4430 currentQueueEncodeIndex++ ;
4431 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4433 - (IBAction) Pause: (id) sender
4436 hb_get_state2( fQueueEncodeLibhb, &s );
4438 if( s.state == HB_STATE_PAUSED )
4440 hb_resume( fQueueEncodeLibhb );
4444 hb_pause( fQueueEncodeLibhb );
4449 #pragma mark GUI Controls Changed Methods
4451 - (IBAction) titlePopUpChanged: (id) sender
4453 hb_list_t * list = hb_get_titles( fHandle );
4454 hb_title_t * title = (hb_title_t*)
4455 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4457 /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4458 if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4460 /* we set the default name according to the new title->name */
4461 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4462 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4463 [NSString stringWithUTF8String: title->name],
4464 [[fDstFile2Field stringValue] pathExtension]]];
4466 /* Change the source to read out the parent folder also */
4467 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4470 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4471 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4472 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4473 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4474 /* 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 */
4475 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4476 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4477 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4479 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4480 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4482 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4483 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4484 [browsedSourceDisplayName stringByDeletingPathExtension],
4486 [[fDstFile2Field stringValue] pathExtension]]];
4488 /* Update encode start / stop variables */
4492 /* Update chapter popups */
4493 [fSrcChapterStartPopUp removeAllItems];
4494 [fSrcChapterEndPopUp removeAllItems];
4495 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4497 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4498 stringWithFormat: @"%d", i + 1]];
4499 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4500 stringWithFormat: @"%d", i + 1]];
4503 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4504 [fSrcChapterEndPopUp selectItemAtIndex:
4505 hb_list_count( title->list_chapter ) - 1];
4506 [self chapterPopUpChanged:nil];
4508 /* if using dvd nav, show the angle widget */
4509 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4511 [fSrcAngleLabel setHidden:NO];
4512 [fSrcAnglePopUp setHidden:NO];
4514 [fSrcAnglePopUp removeAllItems];
4515 for( int i = 0; i < title->angle_count; i++ )
4517 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4519 [fSrcAnglePopUp selectItemAtIndex: 0];
4523 [fSrcAngleLabel setHidden:YES];
4524 [fSrcAnglePopUp setHidden:YES];
4527 /* Start Get and set the initial pic size for display */
4528 hb_job_t * job = title->job;
4531 /* Set Auto Crop to on upon selecting a new title */
4532 [fPictureController setAutoCrop:YES];
4534 /* We get the originial output picture width and height and put them
4535 in variables for use with some presets later on */
4536 PicOrigOutputWidth = job->width;
4537 PicOrigOutputHeight = job->height;
4538 AutoCropTop = job->crop[0];
4539 AutoCropBottom = job->crop[1];
4540 AutoCropLeft = job->crop[2];
4541 AutoCropRight = job->crop[3];
4543 /* Reset the new title in fPictureController && fPreviewController*/
4544 [fPictureController SetTitle:title];
4547 /* Update Subtitle Table */
4548 [fSubtitlesDelegate resetWithTitle:title];
4549 [fSubtitlesTable reloadData];
4552 /* Update chapter table */
4553 [fChapterTitlesDelegate resetWithTitle:title];
4554 [fChapterTable reloadData];
4556 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4557 int audiotrack_count = hb_list_count(job->list_audio);
4558 for( int i = 0; i < audiotrack_count;i++)
4560 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4561 hb_list_rem(job->list_audio, temp_audio);
4564 /* Update audio popups */
4565 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4566 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4567 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4568 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4569 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4570 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4571 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4572 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4573 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4574 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4576 /* changing the title may have changed the audio channels on offer, */
4577 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4578 [self audioTrackPopUpChanged: fAudLang1PopUp];
4579 [self audioTrackPopUpChanged: fAudLang2PopUp];
4580 [self audioTrackPopUpChanged: fAudLang3PopUp];
4581 [self audioTrackPopUpChanged: fAudLang4PopUp];
4583 [fVidRatePopUp selectItemAtIndex: 0];
4585 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4586 [self calculatePictureSizing:nil];
4588 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4589 [self selectPreset:nil];
4592 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4594 if( [fEncodeStartStopPopUp isEnabled] )
4596 /* We are chapters */
4597 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4599 [fSrcChapterStartPopUp setHidden: NO];
4600 [fSrcChapterEndPopUp setHidden: NO];
4602 [fSrcTimeStartEncodingField setHidden: YES];
4603 [fSrcTimeEndEncodingField setHidden: YES];
4605 [fSrcFrameStartEncodingField setHidden: YES];
4606 [fSrcFrameEndEncodingField setHidden: YES];
4608 [self chapterPopUpChanged:nil];
4610 /* We are time based (seconds) */
4611 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4613 [fSrcChapterStartPopUp setHidden: YES];
4614 [fSrcChapterEndPopUp setHidden: YES];
4616 [fSrcTimeStartEncodingField setHidden: NO];
4617 [fSrcTimeEndEncodingField setHidden: NO];
4619 [fSrcFrameStartEncodingField setHidden: YES];
4620 [fSrcFrameEndEncodingField setHidden: YES];
4622 [self startEndSecValueChanged:nil];
4624 /* We are frame based */
4625 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4627 [fSrcChapterStartPopUp setHidden: YES];
4628 [fSrcChapterEndPopUp setHidden: YES];
4630 [fSrcTimeStartEncodingField setHidden: YES];
4631 [fSrcTimeEndEncodingField setHidden: YES];
4633 [fSrcFrameStartEncodingField setHidden: NO];
4634 [fSrcFrameEndEncodingField setHidden: NO];
4636 [self startEndFrameValueChanged:nil];
4641 - (IBAction) chapterPopUpChanged: (id) sender
4644 /* If start chapter popup is greater than end chapter popup,
4645 we set the end chapter popup to the same as start chapter popup */
4646 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4648 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4652 hb_list_t * list = hb_get_titles( fHandle );
4653 hb_title_t * title = (hb_title_t *)
4654 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4656 hb_chapter_t * chapter;
4657 int64_t duration = 0;
4658 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4659 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4661 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4662 duration += chapter->duration;
4665 duration /= 90000; /* pts -> seconds */
4666 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4667 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4670 [self calculateBitrate: sender];
4672 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4674 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4675 [fCreateChapterMarkers setEnabled: NO];
4676 [fCreateChapterMarkers setState: NSOffState];
4680 [fCreateChapterMarkers setEnabled: YES];
4684 - (IBAction) startEndSecValueChanged: (id) sender
4687 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4688 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4689 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4692 //[self calculateBitrate: sender];
4696 - (IBAction) startEndFrameValueChanged: (id) sender
4698 hb_list_t * list = hb_get_titles( fHandle );
4699 hb_title_t * title = (hb_title_t*)
4700 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4702 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4703 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4704 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4707 //[self calculateBitrate: sender];
4711 - (IBAction) formatPopUpChanged: (id) sender
4713 NSString * string = [fDstFile2Field stringValue];
4714 int format = [fDstFormatPopUp indexOfSelectedItem];
4716 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4717 [fDstMp4LargeFileCheck setHidden: YES];
4718 [fDstMp4HttpOptFileCheck setHidden: YES];
4719 [fDstMp4iPodFileCheck setHidden: YES];
4721 /* Update the Video Codec PopUp */
4722 /* lets get the tag of the currently selected item first so we might reset it later */
4723 int selectedVidEncoderTag;
4724 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4726 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4727 [fVidEncoderPopUp removeAllItems];
4728 NSMenuItem *menuItem;
4729 /* These video encoders are available to all of our current muxers, so lets list them once here */
4730 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4731 [menuItem setTag: HB_VCODEC_FFMPEG];
4736 /*Get Default MP4 File Extension*/
4737 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4745 /* Add additional video encoders here */
4746 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4747 [menuItem setTag: HB_VCODEC_X264];
4748 /* We show the mp4 option checkboxes here since we are mp4 */
4749 [fCreateChapterMarkers setEnabled: YES];
4750 [fDstMp4LargeFileCheck setHidden: NO];
4751 [fDstMp4HttpOptFileCheck setHidden: NO];
4752 [fDstMp4iPodFileCheck setHidden: NO];
4757 /* Add additional video encoders here */
4758 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4759 [menuItem setTag: HB_VCODEC_X264];
4760 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4761 [menuItem setTag: HB_VCODEC_THEORA];
4762 /* We enable the create chapters checkbox here */
4763 [fCreateChapterMarkers setEnabled: YES];
4768 /* tell fSubtitlesDelegate we have a new video container */
4770 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4771 [fSubtitlesTable reloadData];
4772 /* if we have a previously selected vid encoder tag, then try to select it */
4773 if (selectedVidEncoderTag)
4775 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4779 [fVidEncoderPopUp selectItemAtIndex: 0];
4782 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4783 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4784 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4785 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4788 [self autoSetM4vExtension: sender];
4790 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4792 if( SuccessfulScan )
4794 /* Add/replace to the correct extension */
4795 [self audioTrackPopUpChanged: fAudLang1PopUp];
4796 [self audioTrackPopUpChanged: fAudLang2PopUp];
4797 [self audioTrackPopUpChanged: fAudLang3PopUp];
4798 [self audioTrackPopUpChanged: fAudLang4PopUp];
4800 if( [fVidEncoderPopUp selectedItem] == nil )
4803 [fVidEncoderPopUp selectItemAtIndex:0];
4804 [self videoEncoderPopUpChanged:nil];
4806 /* changing the format may mean that we can / can't offer mono or 6ch, */
4807 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4809 /* We call the method to properly enable/disable turbo 2 pass */
4810 [self twoPassCheckboxChanged: sender];
4811 /* We call method method to change UI to reflect whether a preset is used or not*/
4814 [self customSettingUsed: sender];
4817 - (IBAction) autoSetM4vExtension: (id) sender
4819 if ( [fDstFormatPopUp indexOfSelectedItem] )
4822 NSString * extension = @"mp4";
4824 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4825 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4826 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4827 [fCreateChapterMarkers state] == NSOnState ||
4828 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4833 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4836 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4837 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4840 /* Method to determine if we should change the UI
4841 To reflect whether or not a Preset is being used or if
4842 the user is using "Custom" settings by determining the sender*/
4843 - (IBAction) customSettingUsed: (id) sender
4845 if ([sender stringValue])
4847 /* Deselect the currently selected Preset if there is one*/
4848 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4849 /* Change UI to show "Custom" settings are being used */
4850 [fPresetSelectedDisplay setStringValue: @"Custom"];
4852 curUserPresetChosenNum = nil;
4854 [self calculateBitrate:nil];
4859 #pragma mark - Video
4861 - (IBAction) videoEncoderPopUpChanged: (id) sender
4863 hb_job_t * job = fTitle->job;
4864 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4866 [fAdvancedOptions setHidden:YES];
4867 /* If we are using x264 then show the x264 advanced panel*/
4868 if (videoEncoder == HB_VCODEC_X264)
4870 [fAdvancedOptions setHidden:NO];
4871 [self autoSetM4vExtension: sender];
4874 if (videoEncoder == HB_VCODEC_FFMPEG)
4876 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4877 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4878 anything other than MP4.
4880 [fDstMp4iPodFileCheck setEnabled: NO];
4881 [fDstMp4iPodFileCheck setState: NSOffState];
4885 [fDstMp4iPodFileCheck setEnabled: YES];
4887 [self setupQualitySlider];
4888 [self calculatePictureSizing: sender];
4889 [self twoPassCheckboxChanged: sender];
4893 - (IBAction) twoPassCheckboxChanged: (id) sender
4895 /* check to see if x264 is chosen */
4896 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4898 if( [fVidTwoPassCheck state] == NSOnState)
4900 [fVidTurboPassCheck setHidden: NO];
4904 [fVidTurboPassCheck setHidden: YES];
4905 [fVidTurboPassCheck setState: NSOffState];
4907 /* Make sure Two Pass is checked if Turbo is checked */
4908 if( [fVidTurboPassCheck state] == NSOnState)
4910 [fVidTwoPassCheck setState: NSOnState];
4915 [fVidTurboPassCheck setHidden: YES];
4916 [fVidTurboPassCheck setState: NSOffState];
4919 /* We call method method to change UI to reflect whether a preset is used or not*/
4920 [self customSettingUsed: sender];
4923 - (IBAction ) videoFrameRateChanged: (id) sender
4925 /* Hide and set the PFR Checkbox to OFF if we are set to Same as Source */
4926 if ([fVidRatePopUp indexOfSelectedItem] == 0)
4928 [fFrameratePfrCheck setHidden:YES];
4929 [fFrameratePfrCheck setState:0];
4933 [fFrameratePfrCheck setHidden:NO];
4936 /* We call method method to calculatePictureSizing to error check detelecine*/
4937 [self calculatePictureSizing: sender];
4939 /* We call method method to change UI to reflect whether a preset is used or not*/
4940 [self customSettingUsed: sender];
4942 - (IBAction) videoMatrixChanged: (id) sender;
4944 bool target, bitrate, quality;
4946 target = bitrate = quality = false;
4947 if( [fVidQualityMatrix isEnabled] )
4949 switch( [fVidQualityMatrix selectedRow] )
4962 [fVidTargetSizeField setEnabled: target];
4963 [fVidBitrateField setEnabled: bitrate];
4964 [fVidQualitySlider setEnabled: quality];
4965 [fVidQualityRFField setEnabled: quality];
4966 [fVidQualityRFLabel setEnabled: quality];
4967 [fVidTwoPassCheck setEnabled: !quality &&
4968 [fVidQualityMatrix isEnabled]];
4971 [fVidTwoPassCheck setState: NSOffState];
4972 [fVidTurboPassCheck setHidden: YES];
4973 [fVidTurboPassCheck setState: NSOffState];
4976 [self qualitySliderChanged: sender];
4977 [self calculateBitrate: sender];
4978 [self customSettingUsed: sender];
4981 /* Use this method to setup the quality slider for cq/rf values depending on
4982 * the video encoder selected.
4984 - (void) setupQualitySlider
4986 /* Get the current slider maxValue to check for a change in slider scale later
4987 * so that we can choose a new similar value on the new slider scale */
4988 float previousMaxValue = [fVidQualitySlider maxValue];
4989 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4990 NSString * qpRFLabelString = @"QP:";
4992 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4994 [fVidQualitySlider setMinValue:0.0];
4995 [fVidQualitySlider setMaxValue:51.0];
4996 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4997 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4998 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4999 qpRFLabelString = @"RF:";
5002 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
5004 [fVidQualitySlider setMinValue:1.0];
5005 [fVidQualitySlider setMaxValue:31.0];
5006 [fVidQualitySlider setNumberOfTickMarks:31];
5009 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5011 [fVidQualitySlider setMinValue:0.0];
5012 [fVidQualitySlider setMaxValue:63.0];
5013 [fVidQualitySlider setNumberOfTickMarks:64];
5015 [fVidQualityRFLabel setStringValue:qpRFLabelString];
5017 /* check to see if we have changed slider scales */
5018 if (previousMaxValue != [fVidQualitySlider maxValue])
5020 /* if so, convert the old setting to the new scale as close as possible based on percentages */
5021 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
5022 [fVidQualitySlider setFloatValue:rf];
5025 [self qualitySliderChanged:nil];
5028 - (IBAction) qualitySliderChanged: (id) sender
5030 /* Our constant quality slider is in a range based
5031 * on each encoders qp/rf values. The range depends
5032 * on the encoder. Also, the range is inverse of quality
5033 * for all of the encoders *except* for theora
5034 * (ie. as the "quality" goes up, the cq or rf value
5035 * actually goes down). Since the IB sliders always set
5036 * their max value at the right end of the slider, we
5037 * will calculate the inverse, so as the slider floatValue
5038 * goes up, we will show the inverse in the rf field
5039 * so, the floatValue at the right for x264 would be 51
5040 * and our rf field needs to show 0 and vice versa.
5043 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5044 /* If the encoder is theora, use the float, otherwise use the inverse float*/
5045 //float sliderRfToPercent;
5046 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5048 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
5052 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5054 [self customSettingUsed: sender];
5057 - (void) controlTextDidChange: (NSNotification *) notification
5059 [self calculateBitrate:nil];
5062 - (IBAction) calculateBitrate: (id) sender
5064 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5069 hb_list_t * list = hb_get_titles( fHandle );
5070 hb_title_t * title = (hb_title_t *) hb_list_item( list,
5071 [fSrcTitlePopUp indexOfSelectedItem] );
5072 hb_job_t * job = title->job;
5073 hb_audio_config_t * audio;
5074 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
5075 * Target Size Field, we also need the job info for the Muxer, the Chapters
5076 * as well as all of the audio track info.
5077 * This used to be accomplished by simply calling prepareJob here, however
5078 * since the resilient queue sets the queue array values instead of the job
5079 * values directly, we duplicate the old prepareJob code here for the variables
5082 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5083 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
5084 job->mux = [[fDstFormatPopUp selectedItem] tag];
5086 /* Audio goes here */
5087 int audiotrack_count = hb_list_count(job->list_audio);
5088 for( int i = 0; i < audiotrack_count;i++)
5090 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5091 hb_list_rem(job->list_audio, temp_audio);
5093 /* Now we need our audio info here for each track if applicable */
5094 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5096 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5097 hb_audio_config_init(audio);
5098 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5099 /* We go ahead and assign values to our audio->out.<properties> */
5100 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5101 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5102 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5103 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5104 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5105 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5107 hb_audio_add( job, audio );
5110 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5112 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5113 hb_audio_config_init(audio);
5114 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5115 /* We go ahead and assign values to our audio->out.<properties> */
5116 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5117 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5118 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5119 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5120 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5121 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5123 hb_audio_add( job, audio );
5128 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5130 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5131 hb_audio_config_init(audio);
5132 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5133 /* We go ahead and assign values to our audio->out.<properties> */
5134 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5135 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5136 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5137 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5138 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5139 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5141 hb_audio_add( job, audio );
5146 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5148 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5149 hb_audio_config_init(audio);
5150 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5151 /* We go ahead and assign values to our audio->out.<properties> */
5152 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5153 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5154 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5155 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5156 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5157 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5159 hb_audio_add( job, audio );
5164 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5168 #pragma mark - Picture
5170 /* lets set the picture size back to the max from right after title scan
5171 Lets use an IBAction here as down the road we could always use a checkbox
5172 in the gui to easily take the user back to max. Remember, the compiler
5173 resolves IBActions down to -(void) during compile anyway */
5174 - (IBAction) revertPictureSizeToMax: (id) sender
5176 hb_job_t * job = fTitle->job;
5177 /* Here we apply the title source and height */
5178 job->width = fTitle->width;
5179 job->height = fTitle->height;
5181 [self calculatePictureSizing: sender];
5182 /* We call method to change UI to reflect whether a preset is used or not*/
5183 [self customSettingUsed: sender];
5187 * Registers changes made in the Picture Settings Window.
5190 - (void)pictureSettingsDidChange
5192 [self calculatePictureSizing:nil];
5195 /* Get and Display Current Pic Settings in main window */
5196 - (IBAction) calculatePictureSizing: (id) sender
5198 if (fTitle->job->anamorphic.mode > 0)
5200 fTitle->job->keep_ratio = 0;
5203 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5205 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5209 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5211 NSString *picCropping;
5212 /* Set the display field for crop as per boolean */
5213 if (![fPictureController autoCrop])
5215 picCropping = @"Custom";
5219 picCropping = @"Auto";
5221 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]]];
5223 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5225 NSString *videoFilters;
5228 if ([fPictureController detelecine] == 2)
5230 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5232 else if ([fPictureController detelecine] == 1)
5234 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5238 if ([fPictureController useDecomb] == 1)
5241 if ([fPictureController decomb] == 2)
5243 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5245 else if ([fPictureController decomb] == 1)
5247 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5253 if ([fPictureController deinterlace] > 0)
5255 fTitle->job->deinterlace = 1;
5259 fTitle->job->deinterlace = 0;
5262 if ([fPictureController deinterlace] == 2)
5264 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5266 else if ([fPictureController deinterlace] == 3)
5268 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5270 else if ([fPictureController deinterlace] == 4)
5272 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5274 else if ([fPictureController deinterlace] == 1)
5276 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5282 if ([fPictureController denoise] == 2)
5284 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5286 else if ([fPictureController denoise] == 3)
5288 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5290 else if ([fPictureController denoise] == 4)
5292 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5294 else if ([fPictureController denoise] == 1)
5296 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5300 if ([fPictureController deblock] > 0)
5302 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5306 if ([fPictureController grayscale])
5308 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5310 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5312 //[fPictureController reloadStillPreview];
5317 #pragma mark - Audio and Subtitles
5318 - (IBAction) audioCodecsPopUpChanged: (id) sender
5321 NSPopUpButton * audiotrackPopUp;
5322 NSPopUpButton * sampleratePopUp;
5323 NSPopUpButton * bitratePopUp;
5324 NSPopUpButton * audiocodecPopUp;
5325 if (sender == fAudTrack1CodecPopUp)
5327 audiotrackPopUp = fAudLang1PopUp;
5328 audiocodecPopUp = fAudTrack1CodecPopUp;
5329 sampleratePopUp = fAudTrack1RatePopUp;
5330 bitratePopUp = fAudTrack1BitratePopUp;
5332 else if (sender == fAudTrack2CodecPopUp)
5334 audiotrackPopUp = fAudLang2PopUp;
5335 audiocodecPopUp = fAudTrack2CodecPopUp;
5336 sampleratePopUp = fAudTrack2RatePopUp;
5337 bitratePopUp = fAudTrack2BitratePopUp;
5339 else if (sender == fAudTrack3CodecPopUp)
5341 audiotrackPopUp = fAudLang3PopUp;
5342 audiocodecPopUp = fAudTrack3CodecPopUp;
5343 sampleratePopUp = fAudTrack3RatePopUp;
5344 bitratePopUp = fAudTrack3BitratePopUp;
5348 audiotrackPopUp = fAudLang4PopUp;
5349 audiocodecPopUp = fAudTrack4CodecPopUp;
5350 sampleratePopUp = fAudTrack4RatePopUp;
5351 bitratePopUp = fAudTrack4BitratePopUp;
5354 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5355 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5356 [self audioTrackPopUpChanged: audiotrackPopUp];
5360 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5362 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5363 * the settings of the source audio for that track. We leave the samplerate and bitrate
5364 * to audiotrackMixdownChanged
5367 /* We will first verify that a lower track number has been selected before enabling each track
5368 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5371 /* If the source has no audio then disable audio track 1 */
5372 if (hb_list_count( fTitle->list_audio ) == 0)
5374 [fAudLang1PopUp selectItemAtIndex:0];
5377 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5379 [fAudLang2PopUp setEnabled: NO];
5380 [fAudLang2PopUp selectItemAtIndex: 0];
5384 [fAudLang2PopUp setEnabled: YES];
5387 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5389 [fAudLang3PopUp setEnabled: NO];
5390 [fAudLang3PopUp selectItemAtIndex: 0];
5394 [fAudLang3PopUp setEnabled: YES];
5396 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5398 [fAudLang4PopUp setEnabled: NO];
5399 [fAudLang4PopUp selectItemAtIndex: 0];
5403 [fAudLang4PopUp setEnabled: YES];
5405 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5406 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5407 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5408 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5409 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5410 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5411 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5412 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5414 [fAudTrack1CodecPopUp removeAllItems];
5415 [fAudTrack1MixPopUp removeAllItems];
5416 [fAudTrack1RatePopUp removeAllItems];
5417 [fAudTrack1BitratePopUp removeAllItems];
5418 [fAudTrack1DrcSlider setFloatValue: 0.00];
5419 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5421 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5423 [fAudTrack1RatePopUp setEnabled: NO];
5424 [fAudTrack1BitratePopUp setEnabled: NO];
5425 [fAudTrack1DrcSlider setEnabled: NO];
5426 [fAudTrack1DrcField setEnabled: NO];
5429 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5430 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5431 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5432 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5433 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5434 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5435 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5436 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5438 [fAudTrack2CodecPopUp removeAllItems];
5439 [fAudTrack2MixPopUp removeAllItems];
5440 [fAudTrack2RatePopUp removeAllItems];
5441 [fAudTrack2BitratePopUp removeAllItems];
5442 [fAudTrack2DrcSlider setFloatValue: 0.00];
5443 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5445 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5447 [fAudTrack2RatePopUp setEnabled: NO];
5448 [fAudTrack2BitratePopUp setEnabled: NO];
5449 [fAudTrack2DrcSlider setEnabled: NO];
5450 [fAudTrack2DrcField setEnabled: NO];
5453 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5454 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5455 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5456 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5457 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5458 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5459 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5460 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5462 [fAudTrack3CodecPopUp removeAllItems];
5463 [fAudTrack3MixPopUp removeAllItems];
5464 [fAudTrack3RatePopUp removeAllItems];
5465 [fAudTrack3BitratePopUp removeAllItems];
5466 [fAudTrack3DrcSlider setFloatValue: 0.00];
5467 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5469 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5471 [fAudTrack3RatePopUp setEnabled: NO];
5472 [fAudTrack3BitratePopUp setEnabled: NO];
5473 [fAudTrack3DrcSlider setEnabled: NO];
5474 [fAudTrack3DrcField setEnabled: NO];
5477 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5478 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5479 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5480 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5481 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5482 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5483 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5484 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5486 [fAudTrack4CodecPopUp removeAllItems];
5487 [fAudTrack4MixPopUp removeAllItems];
5488 [fAudTrack4RatePopUp removeAllItems];
5489 [fAudTrack4BitratePopUp removeAllItems];
5490 [fAudTrack4DrcSlider setFloatValue: 0.00];
5491 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5493 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5495 [fAudTrack4RatePopUp setEnabled: NO];
5496 [fAudTrack4BitratePopUp setEnabled: NO];
5497 [fAudTrack4DrcSlider setEnabled: NO];
5498 [fAudTrack4DrcField setEnabled: NO];
5503 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5506 hb_list_t * list = hb_get_titles( fHandle );
5507 hb_title_t * title = (hb_title_t*)
5508 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5510 hb_audio_config_t * audio;
5512 [sender removeAllItems];
5513 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5514 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5516 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5517 [[sender menu] addItemWithTitle:
5518 [NSString stringWithUTF8String: audio->lang.description]
5519 action: NULL keyEquivalent: @""];
5521 [sender selectItemAtIndex: 0];
5525 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5528 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5529 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5530 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5531 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5532 if (hb_list_count( fTitle->list_audio ) != 0)
5534 if (searchPrefixString)
5537 for( int i = 0; i < [sender numberOfItems]; i++ )
5539 /* Try to find the desired search string */
5540 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5542 [sender selectItemAtIndex: i];
5546 /* couldn't find the string, so select the requested "search string not found" item */
5547 /* index of 0 means select the "none" item */
5548 /* index of 1 means select the first audio track */
5549 [sender selectItemAtIndex: selectIndexIfNotFound];
5553 /* if no search string is provided, then select the selectIndexIfNotFound item */
5554 [sender selectItemAtIndex: selectIndexIfNotFound];
5559 [sender selectItemAtIndex: 0];
5563 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5565 int format = [fDstFormatPopUp indexOfSelectedItem];
5567 /* setup pointers to the appropriate popups for the correct track */
5568 NSPopUpButton * audiocodecPopUp;
5569 NSPopUpButton * audiotrackPopUp;
5570 if (sender == fAudTrack1CodecPopUp)
5572 audiotrackPopUp = fAudLang1PopUp;
5573 audiocodecPopUp = fAudTrack1CodecPopUp;
5575 else if (sender == fAudTrack2CodecPopUp)
5577 audiotrackPopUp = fAudLang2PopUp;
5578 audiocodecPopUp = fAudTrack2CodecPopUp;
5580 else if (sender == fAudTrack3CodecPopUp)
5582 audiotrackPopUp = fAudLang3PopUp;
5583 audiocodecPopUp = fAudTrack3CodecPopUp;
5587 audiotrackPopUp = fAudLang4PopUp;
5588 audiocodecPopUp = fAudTrack4CodecPopUp;
5591 [audiocodecPopUp removeAllItems];
5592 /* Make sure "None" isnt selected in the source track */
5593 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5595 [audiocodecPopUp setEnabled:YES];
5596 NSMenuItem *menuItem;
5597 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5603 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5604 [menuItem setTag: HB_ACODEC_CA_AAC];
5606 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5607 [menuItem setTag: HB_ACODEC_FAAC];
5609 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5610 [menuItem setTag: HB_ACODEC_LAME];
5612 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5613 [menuItem setTag: HB_ACODEC_AC3];
5619 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5620 [menuItem setTag: HB_ACODEC_CA_AAC];
5622 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5623 [menuItem setTag: HB_ACODEC_FAAC];
5625 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5626 [menuItem setTag: HB_ACODEC_AC3];
5628 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5629 [menuItem setTag: HB_ACODEC_DCA];
5631 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5632 [menuItem setTag: HB_ACODEC_LAME];
5634 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5635 [menuItem setTag: HB_ACODEC_VORBIS];
5638 [audiocodecPopUp selectItemAtIndex:0];
5642 [audiocodecPopUp setEnabled:NO];
5646 - (IBAction) audioTrackPopUpChanged: (id) sender
5648 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5649 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5652 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5655 /* make sure we have a selected title before continuing */
5656 if (fTitle == NULL) return;
5657 /* make sure we have a source audio track before continuing */
5658 if (hb_list_count( fTitle->list_audio ) == 0)
5660 [sender selectItemAtIndex:0];
5663 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5664 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5666 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5668 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5670 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5672 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5674 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5676 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5678 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5680 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5683 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5684 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5686 sender = fAudLang1PopUp;
5688 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5690 sender = fAudLang2PopUp;
5692 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5694 sender = fAudLang3PopUp;
5696 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5698 sender = fAudLang4PopUp;
5701 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5702 NSPopUpButton * mixdownPopUp;
5703 NSPopUpButton * audiocodecPopUp;
5704 NSPopUpButton * sampleratePopUp;
5705 NSPopUpButton * bitratePopUp;
5706 if (sender == fAudLang1PopUp)
5708 mixdownPopUp = fAudTrack1MixPopUp;
5709 audiocodecPopUp = fAudTrack1CodecPopUp;
5710 sampleratePopUp = fAudTrack1RatePopUp;
5711 bitratePopUp = fAudTrack1BitratePopUp;
5713 else if (sender == fAudLang2PopUp)
5715 mixdownPopUp = fAudTrack2MixPopUp;
5716 audiocodecPopUp = fAudTrack2CodecPopUp;
5717 sampleratePopUp = fAudTrack2RatePopUp;
5718 bitratePopUp = fAudTrack2BitratePopUp;
5720 else if (sender == fAudLang3PopUp)
5722 mixdownPopUp = fAudTrack3MixPopUp;
5723 audiocodecPopUp = fAudTrack3CodecPopUp;
5724 sampleratePopUp = fAudTrack3RatePopUp;
5725 bitratePopUp = fAudTrack3BitratePopUp;
5729 mixdownPopUp = fAudTrack4MixPopUp;
5730 audiocodecPopUp = fAudTrack4CodecPopUp;
5731 sampleratePopUp = fAudTrack4RatePopUp;
5732 bitratePopUp = fAudTrack4BitratePopUp;
5735 /* get the index of the selected audio Track*/
5736 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5738 /* pointer for the hb_audio_s struct we will use later on */
5739 hb_audio_config_t * audio;
5742 /* check if the audio mixdown controls need their enabled state changing */
5743 [self setEnabledStateOfAudioMixdownControls:nil];
5745 if (thisAudioIndex != -1)
5749 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5751 /* actually manipulate the proper mixdowns here */
5752 /* delete the previous audio mixdown options */
5753 [mixdownPopUp removeAllItems];
5755 acodec = [[audiocodecPopUp selectedItem] tag];
5760 /* find out if our selected output audio codec supports 6ch */
5761 int audioCodecsSupport6Ch = (audio->in.codec && acodec != HB_ACODEC_LAME);
5763 /* check for AC-3 passthru */
5764 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5767 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5768 [NSString stringWithUTF8String: "AC3 Passthru"]
5769 action: NULL keyEquivalent: @""];
5770 [menuItem setTag: HB_ACODEC_AC3];
5772 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5774 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5775 [NSString stringWithUTF8String: "DTS Passthru"]
5776 action: NULL keyEquivalent: @""];
5777 [menuItem setTag: HB_ACODEC_DCA];
5782 /* add the appropriate audio mixdown menuitems to the popupbutton */
5783 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5784 so that we can reference the mixdown later */
5786 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5787 int minMixdownUsed = 0;
5788 int maxMixdownUsed = 0;
5790 /* get the input channel layout without any lfe channels */
5791 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5793 /* add a mono option */
5794 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5795 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5796 action: NULL keyEquivalent: @""];
5797 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5798 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5799 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5801 /* do we want to add a stereo option? */
5802 /* offer stereo if we have a stereo-or-better source */
5803 if (layout >= HB_INPUT_CH_LAYOUT_STEREO)
5805 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5806 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5807 action: NULL keyEquivalent: @""];
5808 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5809 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5810 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5813 /* do we want to add a dolby surround (DPL1) option? */
5814 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5816 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5817 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5818 action: NULL keyEquivalent: @""];
5819 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5820 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5821 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5824 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5825 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5827 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5828 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5829 action: NULL keyEquivalent: @""];
5830 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5831 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5832 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5835 /* do we want to add a 6-channel discrete option? */
5836 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5838 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5839 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5840 action: NULL keyEquivalent: @""];
5841 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5842 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5843 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5846 /* do we want to add an AC-3 passthrough option? */
5847 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5849 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5850 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5851 action: NULL keyEquivalent: @""];
5852 [menuItem setTag: HB_ACODEC_AC3];
5853 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5854 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5857 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5858 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5860 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5861 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5862 action: NULL keyEquivalent: @""];
5863 [menuItem setTag: HB_ACODEC_DCA];
5864 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5865 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5868 /* auto-select the best mixdown based on our saved mixdown preference */
5870 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5871 /* ultimately this should be a prefs option */
5874 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5875 if (mixdownToUse > 0)
5877 useMixdown = mixdownToUse;
5881 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5884 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5885 if (useMixdown > maxMixdownUsed)
5887 useMixdown = maxMixdownUsed;
5890 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5891 if (useMixdown < minMixdownUsed)
5893 useMixdown = minMixdownUsed;
5896 /* select the (possibly-amended) preferred mixdown */
5897 [mixdownPopUp selectItemWithTag: useMixdown];
5900 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5901 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5903 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5905 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5908 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5909 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5911 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5913 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5916 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5917 [self audioTrackMixdownChanged: mixdownPopUp];
5921 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5923 [self autoSetM4vExtension: sender];
5927 - (IBAction) audioTrackMixdownChanged: (id) sender
5931 /* setup pointers to all of the other audio track controls
5932 * we will need later
5934 NSPopUpButton * mixdownPopUp;
5935 NSPopUpButton * sampleratePopUp;
5936 NSPopUpButton * bitratePopUp;
5937 NSPopUpButton * audiocodecPopUp;
5938 NSPopUpButton * audiotrackPopUp;
5939 NSSlider * drcSlider;
5940 NSTextField * drcField;
5941 if (sender == fAudTrack1MixPopUp)
5943 audiotrackPopUp = fAudLang1PopUp;
5944 audiocodecPopUp = fAudTrack1CodecPopUp;
5945 mixdownPopUp = fAudTrack1MixPopUp;
5946 sampleratePopUp = fAudTrack1RatePopUp;
5947 bitratePopUp = fAudTrack1BitratePopUp;
5948 drcSlider = fAudTrack1DrcSlider;
5949 drcField = fAudTrack1DrcField;
5951 else if (sender == fAudTrack2MixPopUp)
5953 audiotrackPopUp = fAudLang2PopUp;
5954 audiocodecPopUp = fAudTrack2CodecPopUp;
5955 mixdownPopUp = fAudTrack2MixPopUp;
5956 sampleratePopUp = fAudTrack2RatePopUp;
5957 bitratePopUp = fAudTrack2BitratePopUp;
5958 drcSlider = fAudTrack2DrcSlider;
5959 drcField = fAudTrack2DrcField;
5961 else if (sender == fAudTrack3MixPopUp)
5963 audiotrackPopUp = fAudLang3PopUp;
5964 audiocodecPopUp = fAudTrack3CodecPopUp;
5965 mixdownPopUp = fAudTrack3MixPopUp;
5966 sampleratePopUp = fAudTrack3RatePopUp;
5967 bitratePopUp = fAudTrack3BitratePopUp;
5968 drcSlider = fAudTrack3DrcSlider;
5969 drcField = fAudTrack3DrcField;
5973 audiotrackPopUp = fAudLang4PopUp;
5974 audiocodecPopUp = fAudTrack4CodecPopUp;
5975 mixdownPopUp = fAudTrack4MixPopUp;
5976 sampleratePopUp = fAudTrack4RatePopUp;
5977 bitratePopUp = fAudTrack4BitratePopUp;
5978 drcSlider = fAudTrack4DrcSlider;
5979 drcField = fAudTrack4DrcField;
5981 acodec = [[audiocodecPopUp selectedItem] tag];
5982 /* storage variable for the min and max bitrate allowed for this codec */
5988 case HB_ACODEC_FAAC:
5989 /* check if we have a 6ch discrete conversion in either audio track */
5990 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5992 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5994 /* If either mixdown popup includes 6-channel discrete, then allow up to 768 kbps */
6000 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
6002 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
6007 case HB_ACODEC_CA_AAC:
6008 /* check if we have a 6ch discrete conversion in either audio track */
6009 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6022 case HB_ACODEC_LAME:
6023 /* Lame is happy using our min bitrate of 32 kbps */
6025 /* Lame won't encode if the bitrate is higher than 320 kbps */
6029 case HB_ACODEC_VORBIS:
6030 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6032 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6034 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6040 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6042 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6048 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6054 /* make sure we have a selected title before continuing */
6055 if (fTitle == NULL || hb_list_count( fTitle->list_audio ) == 0) return;
6056 /* get the audio so we can find out what input rates are*/
6057 hb_audio_config_t * audio;
6058 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6059 int inputbitrate = audio->in.bitrate / 1000;
6060 int inputsamplerate = audio->in.samplerate;
6062 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6064 [bitratePopUp removeAllItems];
6066 for( int i = 0; i < hb_audio_bitrates_count; i++ )
6068 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6070 /* add a new menuitem for this bitrate */
6071 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6072 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6073 action: NULL keyEquivalent: @""];
6074 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6075 [menuItem setTag: hb_audio_bitrates[i].rate];
6079 /* select the default bitrate (but use 384 for 6-ch AAC) */
6080 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6082 [bitratePopUp selectItemWithTag: 384];
6086 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6089 /* populate and set the sample rate popup */
6090 /* Audio samplerate */
6091 [sampleratePopUp removeAllItems];
6092 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6093 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6094 [menuItem setTag: inputsamplerate];
6096 for( int i = 0; i < hb_audio_rates_count; i++ )
6098 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6099 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6100 action: NULL keyEquivalent: @""];
6101 [menuItem setTag: hb_audio_rates[i].rate];
6103 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6104 * and there is no compelling reason to use anything else as default, though the users default
6105 * preset will likely override any setting chosen here.
6107 [sampleratePopUp selectItemWithTag: inputsamplerate];
6110 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6111 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6112 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6114 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6117 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6118 [bitratePopUp removeAllItems];
6119 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6120 [NSString stringWithFormat:@"%d", inputbitrate]
6121 action: NULL keyEquivalent: @""];
6122 [menuItem setTag: inputbitrate];
6123 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6124 [bitratePopUp setEnabled: NO];
6125 [sampleratePopUp setEnabled: NO];
6127 [drcSlider setFloatValue: 0.00];
6128 [self audioDRCSliderChanged: drcSlider];
6129 [drcSlider setEnabled: NO];
6130 [drcField setEnabled: NO];
6134 [sampleratePopUp setEnabled: YES];
6135 [bitratePopUp setEnabled: YES];
6136 [drcSlider setEnabled: YES];
6137 [drcField setEnabled: YES];
6139 [self calculateBitrate:nil];
6142 - (IBAction) audioDRCSliderChanged: (id) sender
6144 NSSlider * drcSlider;
6145 NSTextField * drcField;
6146 if (sender == fAudTrack1DrcSlider)
6148 drcSlider = fAudTrack1DrcSlider;
6149 drcField = fAudTrack1DrcField;
6151 else if (sender == fAudTrack2DrcSlider)
6153 drcSlider = fAudTrack2DrcSlider;
6154 drcField = fAudTrack2DrcField;
6156 else if (sender == fAudTrack3DrcSlider)
6158 drcSlider = fAudTrack3DrcSlider;
6159 drcField = fAudTrack3DrcField;
6163 drcSlider = fAudTrack4DrcSlider;
6164 drcField = fAudTrack4DrcField;
6167 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6168 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6170 [drcSlider setFloatValue:1.0];
6174 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6175 /* For now, do not call this until we have an intelligent way to determine audio track selections
6176 * compared to presets
6178 //[self customSettingUsed: sender];
6183 - (IBAction) browseImportSrtFile: (id) sender
6186 NSOpenPanel * panel;
6188 panel = [NSOpenPanel openPanel];
6189 [panel setAllowsMultipleSelection: NO];
6190 [panel setCanChooseFiles: YES];
6191 [panel setCanChooseDirectories: NO ];
6192 NSString * sourceDirectory;
6193 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6195 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6199 sourceDirectory = @"~/Desktop";
6200 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6202 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6203 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6204 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6205 modalForWindow: fWindow modalDelegate: self
6206 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6207 contextInfo: sender];
6210 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6211 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6213 if( returnCode == NSOKButton )
6215 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6216 NSString *importSrtFilePath = [sheet filename];
6217 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6219 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6220 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6222 [fSubtitlesTable reloadData];
6228 #pragma mark Open New Windows
6230 - (IBAction) openHomepage: (id) sender
6232 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6233 URLWithString:@"http://handbrake.fr/"]];
6236 - (IBAction) openForums: (id) sender
6238 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6239 URLWithString:@"http://forum.handbrake.fr/"]];
6241 - (IBAction) openUserGuide: (id) sender
6243 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6244 URLWithString:@"https://trac.handbrake.fr/wiki/HandBrakeGuide"]];
6248 * Shows debug output window.
6250 - (IBAction)showDebugOutputPanel:(id)sender
6252 [outputPanel showOutputPanel:sender];
6256 * Shows preferences window.
6258 - (IBAction) showPreferencesWindow: (id) sender
6260 NSWindow * window = [fPreferencesController window];
6261 if (![window isVisible])
6264 [window makeKeyAndOrderFront: nil];
6268 * Shows queue window.
6270 - (IBAction) showQueueWindow:(id)sender
6272 [fQueueController showQueueWindow:sender];
6276 - (IBAction) toggleDrawer:(id)sender {
6277 [fPresetDrawer toggle:self];
6281 * Shows Picture Settings Window.
6284 - (IBAction) showPicturePanel: (id) sender
6286 [fPictureController showPictureWindow:sender];
6289 - (void) picturePanelFullScreen
6291 [fPictureController setToFullScreenMode];
6294 - (void) picturePanelWindowed
6296 [fPictureController setToWindowedMode];
6299 - (IBAction) showPreviewWindow: (id) sender
6301 [fPictureController showPreviewWindow:sender];
6305 #pragma mark Preset Outline View Methods
6306 #pragma mark - Required
6307 /* These are required by the NSOutlineView Datasource Delegate */
6310 /* used to specify the number of levels to show for each item */
6311 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6313 /* currently use no levels to test outline view viability */
6314 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6316 return [UserPresets count];
6320 /* we need to return the count of the array in ChildrenArray for this folder */
6321 NSArray *children = nil;
6322 children = [item objectForKey:@"ChildrenArray"];
6323 if ([children count] > 0)
6325 return [children count];
6334 /* We use this to deterimine children of an item */
6335 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6338 /* we need to return the count of the array in ChildrenArray for this folder */
6339 NSArray *children = nil;
6342 children = UserPresets;
6346 if ([item objectForKey:@"ChildrenArray"])
6348 children = [item objectForKey:@"ChildrenArray"];
6351 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6357 return [children objectAtIndex:index];
6361 // We are only one level deep, so we can't be asked about children
6362 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6366 /* We use this to determine if an item should be expandable */
6367 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6370 /* we need to return the count of the array in ChildrenArray for this folder */
6371 NSArray *children= nil;
6374 children = UserPresets;
6378 if ([item objectForKey:@"ChildrenArray"])
6380 children = [item objectForKey:@"ChildrenArray"];
6384 /* To deterimine if an item should show a disclosure triangle
6385 * we could do it by the children count as so:
6386 * if ([children count] < 1)
6387 * However, lets leave the triangle show even if there are no
6388 * children to help indicate a folder, just like folder in the
6389 * finder can show a disclosure triangle even when empty
6392 /* We need to determine if the item is a folder */
6393 if ([[item objectForKey:@"Folder"] intValue] == 1)
6404 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6406 // Our outline view has no levels, but we can still expand every item. Doing so
6407 // just makes the row taller. See heightOfRowByItem below.
6408 //return ![(HBQueueOutlineView*)outlineView isDragging];
6414 /* Used to tell the outline view which information is to be displayed per item */
6415 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6417 /* We have two columns right now, icon and PresetName */
6419 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6421 return [item objectForKey:@"PresetName"];
6430 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6432 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6434 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6436 return [NSKeyedArchiver archivedDataWithRootObject:item];
6439 #pragma mark - Added Functionality (optional)
6440 /* Use to customize the font and display characteristics of the title cell */
6441 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6443 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6447 NSColor *shadowColor;
6448 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6449 /*check to see if its a selected row */
6450 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6453 fontColor = [NSColor blackColor];
6454 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6458 if ([[item objectForKey:@"Type"] intValue] == 0)
6460 fontColor = [NSColor blueColor];
6462 else // User created preset, use a black font
6464 fontColor = [NSColor blackColor];
6466 /* check to see if its a folder */
6467 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6469 //fontColor = [NSColor greenColor];
6474 /* We use Bold Text for the HB Default */
6475 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6477 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6479 /* We use Bold Text for the User Specified Default */
6480 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6482 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6486 [cell setTextColor:fontColor];
6487 [cell setFont:txtFont];
6492 /* We use this to edit the name field in the outline view */
6493 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6495 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6500 [theRecord setObject:object forKey:@"PresetName"];
6504 [fPresetsOutlineView reloadData];
6505 /* We save all of the preset data here */
6509 /* We use this to provide tooltips for the items in the presets outline view */
6510 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6512 //if ([[tc identifier] isEqualToString:@"PresetName"])
6514 /* initialize the tooltip contents variable */
6516 /* if there is a description for the preset, we show it in the tooltip */
6517 if ([item objectForKey:@"PresetDescription"])
6519 loc_tip = [item objectForKey:@"PresetDescription"];
6524 loc_tip = @"No description available";
6531 #pragma mark Preset Outline View Methods (dragging related)
6534 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6536 // Dragging is only allowed for custom presets.
6537 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6538 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6542 // Don't retain since this is just holding temporaral drag information, and it is
6543 //only used during a drag! We could put this in the pboard actually.
6544 fDraggedNodes = items;
6545 // Provide data for our custom type, and simple NSStrings.
6546 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6548 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6549 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6554 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6557 // Don't allow dropping ONTO an item since they can't really contain any children.
6559 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6560 if (isOnDropTypeProposal)
6561 return NSDragOperationNone;
6563 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6566 index = [fPresetsOutlineView rowForItem: item] + 1;
6570 // Don't allow dropping into the Built In Presets.
6571 if (index < presetCurrentBuiltInCount)
6573 return NSDragOperationNone;
6574 index = MAX (index, presetCurrentBuiltInCount);
6577 [outlineView setDropItem:item dropChildIndex:index];
6578 return NSDragOperationGeneric;
6583 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6585 /* first, lets see if we are dropping into a folder */
6586 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6588 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6589 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6590 [childrenArray addObject:item];
6591 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6592 [childrenArray autorelease];
6594 else // We are not, so we just move the preset into the existing array
6596 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6598 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6599 while (obj = [enumerator nextObject])
6601 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6603 // Successful drop, lets rearrange the view and save it all
6604 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6606 [fPresetsOutlineView reloadData];
6611 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6613 NSUInteger index = [indexSet lastIndex];
6614 NSUInteger aboveInsertIndexCount = 0;
6616 NSUInteger removeIndex;
6618 if (index >= insertIndex)
6620 removeIndex = index + aboveInsertIndexCount;
6621 aboveInsertIndexCount++;
6625 removeIndex = index;
6629 id object = [[array objectAtIndex:removeIndex] retain];
6630 [array removeObjectAtIndex:removeIndex];
6631 [array insertObject:object atIndex:insertIndex];
6634 index = [indexSet indexLessThanIndex:index];
6639 #pragma mark - Functional Preset NSOutlineView Methods
6641 - (IBAction)selectPreset:(id)sender
6644 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6646 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6647 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6649 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6651 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6655 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6659 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6660 [self formatPopUpChanged:nil];
6662 /* Chapter Markers*/
6663 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6664 /* check to see if we have only one chapter */
6665 [self chapterPopUpChanged:nil];
6667 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6668 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6669 /* Mux mp4 with http optimization */
6670 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6673 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6674 /* We set the advanced opt string here if applicable*/
6675 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6677 /* Lets run through the following functions to get variables set there */
6678 [self videoEncoderPopUpChanged:nil];
6679 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6680 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6681 [self calculateBitrate:nil];
6684 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6686 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6687 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6689 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6690 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6691 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6692 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6693 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6694 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6696 /* For the quality slider we need to convert the old percent's to the new rf scales */
6697 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6698 [fVidQualitySlider setFloatValue:rf];
6703 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6704 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6706 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6710 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6711 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6715 [self videoMatrixChanged:nil];
6717 /* Video framerate */
6718 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6719 detected framerate in the fVidRatePopUp so we use index 0*/
6720 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6722 [fVidRatePopUp selectItemAtIndex: 0];
6726 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6729 [fFrameratePfrCheck setState:[[chosenPreset objectForKey:@"VideoFrameratePFR"] intValue]];
6730 [self videoFrameRateChanged:nil];
6732 /* 2 Pass Encoding */
6733 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6734 [self twoPassCheckboxChanged:nil];
6736 /* Turbo 1st pass for 2 Pass Encoding */
6737 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6740 /* First we check to see if we are using the current audio track layout based on AudioList array */
6741 if ([chosenPreset objectForKey:@"AudioList"])
6744 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6745 NSPopUpButton * trackLangPreviousPopUp = nil;
6746 NSPopUpButton * trackLangPopUp = nil;
6747 NSPopUpButton * mixdownPopUp = nil;
6748 NSPopUpButton * audiocodecPopUp = nil;
6749 NSPopUpButton * sampleratePopUp = nil;
6750 NSPopUpButton * bitratePopUp = nil;
6751 NSSlider * drcSlider = nil;
6754 /* Populate the audio widgets based on the contents of the AudioList array */
6756 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6758 while (tempObject = [enumerator nextObject])
6763 trackLangPopUp = fAudLang1PopUp;
6764 mixdownPopUp = fAudTrack1MixPopUp;
6765 audiocodecPopUp = fAudTrack1CodecPopUp;
6766 sampleratePopUp = fAudTrack1RatePopUp;
6767 bitratePopUp = fAudTrack1BitratePopUp;
6768 drcSlider = fAudTrack1DrcSlider;
6772 trackLangPreviousPopUp = fAudLang1PopUp;
6773 trackLangPopUp = fAudLang2PopUp;
6774 mixdownPopUp = fAudTrack2MixPopUp;
6775 audiocodecPopUp = fAudTrack2CodecPopUp;
6776 sampleratePopUp = fAudTrack2RatePopUp;
6777 bitratePopUp = fAudTrack2BitratePopUp;
6778 drcSlider = fAudTrack2DrcSlider;
6782 trackLangPreviousPopUp = fAudLang2PopUp;
6783 trackLangPopUp = fAudLang3PopUp;
6784 mixdownPopUp = fAudTrack3MixPopUp;
6785 audiocodecPopUp = fAudTrack3CodecPopUp;
6786 sampleratePopUp = fAudTrack3RatePopUp;
6787 bitratePopUp = fAudTrack3BitratePopUp;
6788 drcSlider = fAudTrack3DrcSlider;
6792 trackLangPreviousPopUp = fAudLang3PopUp;
6793 trackLangPopUp = fAudLang4PopUp;
6794 mixdownPopUp = fAudTrack4MixPopUp;
6795 audiocodecPopUp = fAudTrack4CodecPopUp;
6796 sampleratePopUp = fAudTrack4RatePopUp;
6797 bitratePopUp = fAudTrack4BitratePopUp;
6798 drcSlider = fAudTrack4DrcSlider;
6802 if ([trackLangPopUp indexOfSelectedItem] == 0)
6806 [trackLangPopUp selectItemAtIndex: 1];
6810 /* if we are greater than track 1, select
6811 * the same track as the previous track */
6812 [trackLangPopUp selectItemAtIndex: [trackLangPreviousPopUp indexOfSelectedItem]];
6815 [self audioTrackPopUpChanged: trackLangPopUp];
6816 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6817 /* check our pref for core audio and use it in place of faac if preset is a built in */
6818 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6819 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6820 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6822 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6825 [self audioTrackPopUpChanged: audiocodecPopUp];
6826 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6827 [self audioTrackMixdownChanged: mixdownPopUp];
6828 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6830 if ([mixdownPopUp selectedItem] == nil)
6832 [self audioTrackPopUpChanged: audiocodecPopUp];
6833 [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6835 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6836 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6837 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6839 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6840 /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6841 *default mixdown bitrate*/
6842 if ([bitratePopUp selectedItem] == nil)
6844 [self audioTrackMixdownChanged: mixdownPopUp];
6847 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6848 [self audioDRCSliderChanged: drcSlider];
6851 /* If we are any track greater than 1 check to make sure we have a matching source codec is using ac3 passthru or dts passthru,
6852 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6856 /* Check to see if the preset asks for a passhthru track (AC3 or DTS) and verify there is a matching source track if not, set the track to "None". */
6857 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6859 hb_audio_config_t * audio;
6860 /* get the audio source audio codec */
6861 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6862 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6863 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6865 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6866 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6868 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6870 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6872 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6874 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6875 [trackLangPopUp selectItemAtIndex: 0];
6876 [self audioTrackPopUpChanged: trackLangPopUp];
6882 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6886 [fAudLang4PopUp selectItemAtIndex: 0];
6887 [self audioTrackPopUpChanged: fAudLang4PopUp];
6891 [fAudLang3PopUp selectItemAtIndex: 0];
6892 [self audioTrackPopUpChanged: fAudLang3PopUp];
6896 [fAudLang2PopUp selectItemAtIndex: 0];
6897 [self audioTrackPopUpChanged: fAudLang2PopUp];
6905 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6907 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6909 [fAudLang1PopUp selectItemAtIndex: 1];
6911 [self audioTrackPopUpChanged: fAudLang1PopUp];
6912 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6913 /* check our pref for core audio and use it in place of faac if preset is built in */
6914 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6915 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6916 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6918 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6921 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6922 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6923 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6925 if ([fAudTrack1MixPopUp selectedItem] == nil)
6927 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6929 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6930 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6931 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6933 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6935 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6936 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6939 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6941 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6943 [fAudLang2PopUp selectItemAtIndex: 1];
6945 [self audioTrackPopUpChanged: fAudLang2PopUp];
6946 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6947 /* check our pref for core audio and use it in place of faac if preset is built in */
6948 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6949 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6950 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6952 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6954 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6955 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6956 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6958 if ([fAudTrack2MixPopUp selectedItem] == nil)
6960 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6962 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6963 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6964 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6966 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6968 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6969 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6971 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6973 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6975 [fAudLang3PopUp selectItemAtIndex: 1];
6977 [self audioTrackPopUpChanged: fAudLang3PopUp];
6978 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6979 /* check our pref for core audio and use it in place of faac if preset is built in */
6980 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6981 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6982 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6984 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6986 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6987 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6988 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6990 if ([fAudTrack3MixPopUp selectedItem] == nil)
6992 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6994 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6995 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6996 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6998 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
7000 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
7001 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
7003 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
7005 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
7007 [fAudLang4PopUp selectItemAtIndex: 1];
7009 [self audioTrackPopUpChanged: fAudLang4PopUp];
7010 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
7011 /* check our pref for core audio and use it in place of faac if preset is built in */
7012 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
7013 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
7014 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
7016 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
7018 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7019 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
7020 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7022 if ([fAudTrack4MixPopUp selectedItem] == nil)
7024 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7026 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7027 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7028 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7030 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7032 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7033 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7036 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7038 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7040 [fAudLang2PopUp selectItemAtIndex: 0];
7041 [self audioTrackPopUpChanged: fAudLang2PopUp];
7043 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7045 [fAudLang3PopUp selectItemAtIndex: 0];
7046 [self audioTrackPopUpChanged: fAudLang3PopUp];
7048 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7050 [fAudLang4PopUp selectItemAtIndex: 0];
7051 [self audioTrackPopUpChanged: fAudLang4PopUp];
7056 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7057 /* Forced Subtitles */
7058 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7060 /* Picture Settings */
7061 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7062 * height, width, keep ar, anamorphic and crop settings.
7063 * picture filters are handled separately below.
7065 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
7066 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
7067 * preset completely ignores any picture sizing values in the preset.
7069 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
7071 hb_job_t * job = fTitle->job;
7073 /* If Cropping is set to custom, then recall all four crop values from
7074 when the preset was created and apply them */
7075 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
7077 [fPictureController setAutoCrop:NO];
7079 /* Here we use the custom crop values saved at the time the preset was saved */
7080 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
7081 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
7082 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
7083 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
7086 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7088 [fPictureController setAutoCrop:YES];
7089 /* Here we use the auto crop values determined right after scan */
7090 job->crop[0] = AutoCropTop;
7091 job->crop[1] = AutoCropBottom;
7092 job->crop[2] = AutoCropLeft;
7093 job->crop[3] = AutoCropRight;
7098 if ([chosenPreset objectForKey:@"PictureModulus"])
7100 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
7107 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7108 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
7110 /* Use Max Picture settings for whatever the dvd is.*/
7111 [self revertPictureSizeToMax:nil];
7112 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7113 if (job->keep_ratio == 1)
7115 hb_fix_aspect( job, HB_KEEP_WIDTH );
7116 if( job->height > fTitle->height )
7118 job->height = fTitle->height;
7119 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7122 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7124 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7126 /* we check to make sure the presets width/height does not exceed the sources width/height */
7127 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
7129 /* if so, then we use the sources height and width to avoid scaling up */
7130 //job->width = fTitle->width;
7131 //job->height = fTitle->height;
7132 [self revertPictureSizeToMax:nil];
7134 else // source width/height is >= the preset height/width
7136 /* we can go ahead and use the presets values for height and width */
7137 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
7138 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
7140 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7141 if (job->keep_ratio == 1)
7143 int height = fTitle->height;
7145 if ( job->height && job->height < fTitle->height )
7146 height = job->height;
7148 hb_fix_aspect( job, HB_KEEP_WIDTH );
7149 // Make sure the resulting height is less than
7150 // the title height and less than the height
7151 // requested in the preset.
7152 if( job->height > height )
7154 job->height = height;
7155 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7158 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7159 if ( job->anamorphic.mode > 0 )
7161 int w, h, par_w, par_h;
7163 job->anamorphic.par_width = fTitle->pixel_aspect_width;
7164 job->anamorphic.par_height = fTitle->pixel_aspect_height;
7165 job->maxWidth = job->width;
7166 job->maxHeight = job->height;
7167 hb_set_anamorphic_size( job, &w, &h, &par_w, &par_h );
7178 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7179 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7183 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7184 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7185 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7188 [fPictureController setUseDecomb:1];
7189 [fPictureController setDecomb:0];
7190 [fPictureController setDeinterlace:0];
7191 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7193 /* we are using decomb */
7195 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7197 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7199 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7200 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7202 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7208 /* We are using Deinterlace */
7210 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7212 [fPictureController setUseDecomb:0];
7213 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7214 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7215 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7217 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7224 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7226 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7227 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7228 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7230 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7235 [fPictureController setDetelecine:0];
7239 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7241 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7242 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7243 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7245 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7250 [fPictureController setDenoise:0];
7254 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7256 /* if its a one, then its the old on/off deblock, set on to 5*/
7257 [fPictureController setDeblock:5];
7261 /* use the settings intValue */
7262 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7265 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7267 [fPictureController setGrayscale:1];
7271 [fPictureController setGrayscale:0];
7274 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7275 [fPictureController SetTitle:fTitle];
7276 [fPictureController SetTitle:fTitle];
7277 [self calculatePictureSizing:nil];
7283 #pragma mark Manage Presets
7285 - (void) loadPresets {
7286 /* We declare the default NSFileManager into fileManager */
7287 NSFileManager * fileManager = [NSFileManager defaultManager];
7288 /*We define the location of the user presets file */
7289 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7290 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7291 /* We check for the presets.plist */
7292 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7294 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7297 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7298 if (nil == UserPresets)
7300 UserPresets = [[NSMutableArray alloc] init];
7301 [self addFactoryPresets:nil];
7303 [fPresetsOutlineView reloadData];
7305 [self checkBuiltInsForUpdates];
7308 - (void) checkBuiltInsForUpdates {
7310 BOOL updateBuiltInPresets = NO;
7312 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7314 while (tempObject = [enumerator nextObject])
7316 /* iterate through the built in presets to see if any have an old build number */
7317 NSMutableDictionary *thisPresetDict = tempObject;
7318 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7319 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7321 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7323 updateBuiltInPresets = YES;
7328 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7329 if ( updateBuiltInPresets == YES)
7331 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7333 /* Show an alert window that built in presets will be updated */
7334 /*On Screen Notification*/
7337 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7338 [NSApp requestUserAttention:NSCriticalRequest];
7340 /* when alert is dismissed, go ahead and update the built in presets */
7341 [self addFactoryPresets:nil];
7347 - (IBAction) addPresetPicDropdownChanged: (id) sender
7349 if ([fPresetNewPicSettingsPopUp indexOfSelectedItem] == 1)
7351 [fPresetNewPicWidthHeightBox setHidden:NO];
7355 [fPresetNewPicWidthHeightBox setHidden:YES];
7359 - (IBAction) showAddPresetPanel: (id) sender
7361 /* Deselect the currently selected Preset if there is one*/
7362 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7364 /* Populate the preset picture settings popup here */
7365 [fPresetNewPicSettingsPopUp removeAllItems];
7366 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7367 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Custom"];
7368 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7369 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7370 /* Uncheck the preset use filters checkbox */
7371 [fPresetNewPicFiltersCheck setState:NSOffState];
7372 // fPresetNewFolderCheck
7373 [fPresetNewFolderCheck setState:NSOffState];
7374 /* Erase info from the input fields*/
7375 [fPresetNewName setStringValue: @""];
7376 [fPresetNewDesc setStringValue: @""];
7378 /* Initialize custom height and width settings to current values */
7380 [fPresetNewPicWidth setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->width]];
7381 [fPresetNewPicHeight setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->height]];
7382 [self addPresetPicDropdownChanged:nil];
7383 /* Show the panel */
7384 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7387 - (IBAction) closeAddPresetPanel: (id) sender
7389 [NSApp endSheet: fAddPresetPanel];
7390 [fAddPresetPanel orderOut: self];
7393 - (IBAction)addUserPreset:(id)sender
7395 if (![[fPresetNewName stringValue] length])
7396 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7399 /* Here we create a custom user preset */
7400 [UserPresets addObject:[self createPreset]];
7403 [self closeAddPresetPanel:nil];
7410 /* We Reload the New Table data for presets */
7411 [fPresetsOutlineView reloadData];
7412 /* We save all of the preset data here */
7420 /* We Sort the Presets By Factory or Custom */
7421 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7422 ascending:YES] autorelease];
7423 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7425 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7426 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7427 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7430 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7431 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7432 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7433 [UserPresets setArray:sortedArray];
7438 - (IBAction)insertPreset:(id)sender
7440 int index = [fPresetsOutlineView selectedRow];
7441 [UserPresets insertObject:[self createPreset] atIndex:index];
7442 [fPresetsOutlineView reloadData];
7446 - (NSDictionary *)createPreset
7448 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7449 /* Preset build number */
7450 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7451 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7452 /* Get the New Preset Name from the field in the AddPresetPanel */
7453 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7454 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7455 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7456 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7457 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7458 /*Set whether or not this is default, at creation set to 0*/
7459 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7460 if ([fPresetNewFolderCheck state] == YES)
7462 /* initialize and set an empty array for children here since we are a new folder */
7463 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7464 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7465 [childrenArray autorelease];
7467 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7469 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7470 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7471 /* Get whether or not to use the current Picture Filter settings for the preset */
7472 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7474 /* Get New Preset Description from the field in the AddPresetPanel*/
7475 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7477 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7478 /* Chapter Markers fCreateChapterMarkers*/
7479 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7480 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7481 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7482 /* Mux mp4 with http optimization */
7483 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7484 /* Add iPod uuid atom */
7485 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7489 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7490 /* x264 Option String */
7491 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7493 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7494 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7495 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7496 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7498 /* Video framerate */
7499 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7501 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7503 else // we can record the actual titleOfSelectedItem
7505 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7507 [preset setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
7509 /* 2 Pass Encoding */
7510 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7511 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7512 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7513 /*Picture Settings*/
7514 hb_job_t * job = fTitle->job;
7516 /* Picture Sizing */
7517 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7518 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicWidth intValue]] forKey:@"PictureWidth"];
7519 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicHeight intValue]] forKey:@"PictureHeight"];
7520 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7521 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7522 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7524 /* Set crop settings here */
7525 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7526 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7527 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7528 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7529 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7531 /* Picture Filters */
7532 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7533 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7534 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7535 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7536 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7537 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7538 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7539 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7540 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7541 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7542 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7545 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7546 /* we actually call the methods for the nests here */
7547 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7549 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7550 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7551 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7552 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7553 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7554 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7555 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7556 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7557 [audioTrack1Array autorelease];
7558 [audioListArray addObject:audioTrack1Array];
7561 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7563 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7564 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7565 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7566 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7567 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7568 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7569 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7570 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7571 [audioTrack2Array autorelease];
7572 [audioListArray addObject:audioTrack2Array];
7575 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7577 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7578 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7579 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7580 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7581 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7582 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7583 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7584 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7585 [audioTrack3Array autorelease];
7586 [audioListArray addObject:audioTrack3Array];
7589 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7591 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7592 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7593 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7594 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7595 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7596 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7597 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7598 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7599 [audioTrack4Array autorelease];
7600 [audioListArray addObject:audioTrack4Array];
7604 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7607 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7608 * subititle array code. */
7610 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7611 /* Forced Subtitles */
7612 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7614 [preset autorelease];
7621 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7622 /* We get the default preset in case it changed */
7623 [self getDefaultPresets:nil];
7627 - (IBAction)deletePreset:(id)sender
7631 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7635 /* Alert user before deleting preset */
7637 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7639 if ( status == NSAlertDefaultReturn )
7641 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7642 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7643 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7645 NSEnumerator *enumerator;
7646 NSMutableArray *presetsArrayToMod;
7647 NSMutableArray *tempArray;
7649 /* If we are a root level preset, we are modding the UserPresets array */
7650 if (presetToModLevel == 0)
7652 presetsArrayToMod = UserPresets;
7654 else // We have a parent preset, so we modify the chidren array object for key
7656 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7659 enumerator = [presetsArrayToMod objectEnumerator];
7660 tempArray = [NSMutableArray array];
7662 while (tempObject = [enumerator nextObject])
7664 NSDictionary *thisPresetDict = tempObject;
7665 if (thisPresetDict == presetToMod)
7667 [tempArray addObject:tempObject];
7671 [presetsArrayToMod removeObjectsInArray:tempArray];
7672 [fPresetsOutlineView reloadData];
7679 #pragma mark Import Export Preset(s)
7681 - (IBAction) browseExportPresetFile: (id) sender
7683 /* Open a panel to let the user choose where and how to save the export file */
7684 NSSavePanel * panel = [NSSavePanel savePanel];
7685 /* We get the current file name and path from the destination field here */
7686 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7688 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7689 modalForWindow: fWindow modalDelegate: self
7690 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7694 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7695 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7697 if( returnCode == NSOKButton )
7699 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7700 NSString *exportPresetsFile = [sheet filename];
7701 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7702 /* We check for the presets.plist */
7703 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7705 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7707 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7708 if (nil == presetsToExport)
7710 presetsToExport = [[NSMutableArray alloc] init];
7712 /* now get and add selected presets to export */
7715 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7717 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7718 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7726 - (IBAction) browseImportPresetFile: (id) sender
7729 NSOpenPanel * panel;
7731 panel = [NSOpenPanel openPanel];
7732 [panel setAllowsMultipleSelection: NO];
7733 [panel setCanChooseFiles: YES];
7734 [panel setCanChooseDirectories: NO ];
7735 NSString * sourceDirectory;
7736 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7738 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7742 sourceDirectory = @"~/Desktop";
7743 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7745 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7746 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7748 /* set this for allowed file types, not sure if we should allow xml or not */
7749 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7750 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7751 modalForWindow: fWindow modalDelegate: self
7752 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7753 contextInfo: sender];
7756 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7757 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7759 if( returnCode == NSOKButton )
7761 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7762 NSString *importPresetsFile = [sheet filename];
7763 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7764 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7765 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7766 /* iterate though the new array of presets to import and add them to our presets array */
7768 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7770 while (tempObject = [enumerator nextObject])
7772 /* make any changes to the incoming preset we see fit */
7773 /* make sure the incoming preset is not tagged as default */
7774 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7775 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7776 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7777 [tempObject setObject:prependedName forKey:@"PresetName"];
7779 /* actually add the new preset to our presets array */
7780 [UserPresets addObject:tempObject];
7783 [presetsToImport autorelease];
7791 #pragma mark Manage Default Preset
7793 - (IBAction)getDefaultPresets:(id)sender
7795 presetHbDefault = nil;
7796 presetUserDefault = nil;
7797 presetUserDefaultParent = nil;
7798 presetUserDefaultParentParent = nil;
7799 NSMutableDictionary *presetHbDefaultParent = nil;
7800 NSMutableDictionary *presetHbDefaultParentParent = nil;
7803 BOOL userDefaultFound = NO;
7804 presetCurrentBuiltInCount = 0;
7805 /* First we iterate through the root UserPresets array to check for defaults */
7806 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7808 while (tempObject = [enumerator nextObject])
7810 NSMutableDictionary *thisPresetDict = tempObject;
7811 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7813 presetHbDefault = thisPresetDict;
7815 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7817 presetUserDefault = thisPresetDict;
7818 userDefaultFound = YES;
7820 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7822 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7826 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7827 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7829 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7830 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7832 while (tempObject = [enumerator nextObject])
7834 NSMutableDictionary *thisPresetDict = tempObject;
7835 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7837 presetHbDefault = thisPresetDict;
7838 presetHbDefaultParent = thisPresetDictParent;
7840 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7842 presetUserDefault = thisPresetDict;
7843 presetUserDefaultParent = thisPresetDictParent;
7844 userDefaultFound = YES;
7847 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7848 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7850 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7851 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7853 while (tempObject = [enumerator nextObject])
7855 NSMutableDictionary *thisPresetDict = tempObject;
7856 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7858 presetHbDefault = thisPresetDict;
7859 presetHbDefaultParent = thisPresetDictParent;
7860 presetHbDefaultParentParent = thisPresetDictParentParent;
7862 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7864 presetUserDefault = thisPresetDict;
7865 presetUserDefaultParent = thisPresetDictParent;
7866 presetUserDefaultParentParent = thisPresetDictParentParent;
7867 userDefaultFound = YES;
7876 /* check to see if a user specified preset was found, if not then assign the parents for
7877 * the presetHbDefault so that we can open the parents for the nested presets
7879 if (userDefaultFound == NO)
7881 presetUserDefaultParent = presetHbDefaultParent;
7882 presetUserDefaultParentParent = presetHbDefaultParentParent;
7886 - (IBAction)setDefaultPreset:(id)sender
7888 /* We need to determine if the item is a folder */
7889 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7895 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7897 /* First make sure the old user specified default preset is removed */
7898 while (tempObject = [enumerator nextObject])
7900 NSMutableDictionary *thisPresetDict = tempObject;
7901 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7903 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7906 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7907 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7909 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7912 while (tempObject = [enumerator nextObject])
7914 NSMutableDictionary *thisPresetDict1 = tempObject;
7915 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7917 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7919 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7920 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7922 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7925 while (tempObject = [enumerator nextObject])
7927 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7929 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7942 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7943 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7944 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7947 NSMutableArray *presetsArrayToMod;
7948 NSMutableArray *tempArray;
7950 /* If we are a root level preset, we are modding the UserPresets array */
7951 if (presetToModLevel == 0)
7953 presetsArrayToMod = UserPresets;
7955 else // We have a parent preset, so we modify the chidren array object for key
7957 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7960 enumerator = [presetsArrayToMod objectEnumerator];
7961 tempArray = [NSMutableArray array];
7963 while (tempObject = [enumerator nextObject])
7965 NSDictionary *thisPresetDict = tempObject;
7966 if (thisPresetDict == presetToMod)
7968 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7970 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7977 /* We save all of the preset data here */
7979 /* We Reload the New Table data for presets */
7980 [fPresetsOutlineView reloadData];
7983 - (IBAction)selectDefaultPreset:(id)sender
7985 NSMutableDictionary *presetToMod;
7986 /* if there is a user specified default, we use it */
7987 if (presetUserDefault)
7989 presetToMod = presetUserDefault;
7991 else if (presetHbDefault) //else we use the built in default presetHbDefault
7993 presetToMod = presetHbDefault;
8000 if (presetUserDefaultParent != nil)
8002 [fPresetsOutlineView expandItem:presetUserDefaultParent];
8005 if (presetUserDefaultParentParent != nil)
8007 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
8011 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
8012 [self selectPreset:nil];
8017 #pragma mark Manage Built In Presets
8020 - (IBAction)deleteFactoryPresets:(id)sender
8023 NSEnumerator *enumerator = [UserPresets objectEnumerator];
8027 NSMutableArray *tempArray;
8030 tempArray = [NSMutableArray array];
8031 /* we look here to see if the preset is we move on to the next one */
8032 while ( tempObject = [enumerator nextObject] )
8034 /* if the preset is "Factory" then we put it in the array of
8035 presets to delete */
8036 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
8038 [tempArray addObject:tempObject];
8042 [UserPresets removeObjectsInArray:tempArray];
8043 [fPresetsOutlineView reloadData];
8048 /* We use this method to recreate new, updated factory presets */
8049 - (IBAction)addFactoryPresets:(id)sender
8052 /* First, we delete any existing built in presets */
8053 [self deleteFactoryPresets: sender];
8054 /* Then we generate new built in presets programmatically with fPresetsBuiltin
8055 * which is all setup in HBPresets.h and HBPresets.m*/
8056 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
8057 /* update build number for built in presets */
8058 /* iterate though the new array of presets to import and add them to our presets array */
8060 NSEnumerator *enumerator = [UserPresets objectEnumerator];
8062 while (tempObject = [enumerator nextObject])
8064 /* Record the apps current build number in the PresetBuildNumber key */
8065 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
8067 /* Preset build number */
8068 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8072 /* report the built in preset updating to the activity log */
8073 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8081 #pragma mark Chapter Files Import / Export
8083 - (IBAction) browseForChapterFile: (id) sender
8085 /* Open a panel to let the user choose the file */
8086 NSOpenPanel * panel = [NSOpenPanel openPanel];
8087 /* We get the current file name and path from the destination field here */
8088 [panel beginSheetForDirectory: [NSString stringWithFormat:@"%@/",
8089 [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"]]
8091 types: [NSArray arrayWithObjects:@"csv",nil]
8092 modalForWindow: fWindow modalDelegate: self
8093 didEndSelector: @selector( browseForChapterFileDone:returnCode:contextInfo: )
8097 - (void) browseForChapterFileDone: (NSOpenPanel *) sheet
8098 returnCode: (int) returnCode contextInfo: (void *) contextInfo
8100 NSArray *chaptersArray; /* temp array for chapters */
8101 NSMutableArray *chaptersMutableArray; /* temp array for chapters */
8102 NSString *chapterName; /* temp string from file */
8105 if( returnCode == NSOKButton ) /* if they click OK */
8107 chapterName = [[NSString alloc] initWithContentsOfFile:[sheet filename] encoding:NSUTF8StringEncoding error:NULL];
8108 chaptersArray = [chapterName componentsSeparatedByString:@"\n"];
8109 chaptersMutableArray= [chaptersArray mutableCopy];
8110 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
8111 if ([chaptersMutableArray count] > 0)
8113 /* if last item is empty remove it */
8114 if ([[chaptersMutableArray objectAtIndex:[chaptersArray count]-1] length] == 0)
8116 [chaptersMutableArray removeLastObject];
8119 /* if chapters in table is not equal to array count */
8120 if ((unsigned int) chapters != [chaptersMutableArray count])
8123 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
8124 defaultButton:NSLocalizedString(@"OK", @"OK")
8125 alternateButton:NULL
8127 informativeTextWithFormat:NSLocalizedString(@"%d chapters expected, %d chapters found in %@", @"%d chapters expected, %d chapters found in %@"),
8128 chapters, [chaptersMutableArray count], [[sheet filename] lastPathComponent]] runModal];
8131 /* otherwise, go ahead and populate table with array */
8132 for (i=0; i<chapters; i++)
8135 if([[chaptersMutableArray objectAtIndex:i] length] > 5)
8137 /* avoid a segfault */
8138 /* Get the Range.location of the first comma in the line and then put everything after that into chapterTitle */
8139 NSRange firstCommaRange = [[chaptersMutableArray objectAtIndex:i] rangeOfString:@","];
8140 NSString *chapterTitle = [[chaptersMutableArray objectAtIndex:i] substringFromIndex:firstCommaRange.location + 1];
8141 /* Since we store our chapterTitle commas as "\," for the cli, we now need to remove the escaping "\" from the title */
8142 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"\\," withString:@","];
8143 [fChapterTitlesDelegate tableView:fChapterTable
8144 setObjectValue:chapterTitle
8145 forTableColumn:fChapterTableNameColumn
8151 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
8152 defaultButton:NSLocalizedString(@"OK", @"OK")
8153 alternateButton:NULL
8155 informativeTextWithFormat:NSLocalizedString(@"%@ was not formatted as expected.", @"%@ was not formatted as expected."), [[sheet filename] lastPathComponent]] runModal];
8156 [fChapterTable reloadData];
8160 [fChapterTable reloadData];
8164 - (IBAction) browseForChapterFileSave: (id) sender
8166 NSSavePanel *panel = [NSSavePanel savePanel];
8167 /* Open a panel to let the user save to a file */
8168 [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv",nil]];
8169 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent]
8170 file: [[[[fDstFile2Field stringValue] lastPathComponent] stringByDeletingPathExtension]
8171 stringByAppendingString:@"-chapters.csv"]
8172 modalForWindow: fWindow
8174 didEndSelector: @selector( browseForChapterFileSaveDone:returnCode:contextInfo: )
8178 - (void) browseForChapterFileSaveDone: (NSSavePanel *) sheet
8179 returnCode: (int) returnCode contextInfo: (void *) contextInfo
8181 NSString *chapterName; /* pointer for string for later file-writing */
8182 NSString *chapterTitle;
8183 NSError *saveError = [[NSError alloc] init];
8184 int chapters, i; /* ints for the number of chapters in the table and the loop */
8186 if( returnCode == NSOKButton ) /* if they clicked OK */
8188 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
8189 chapterName = [NSString string];
8190 for (i=0; i<chapters; i++)
8192 /* put each chapter title from the table into the array */
8194 { /* if i is from 0 to 8 (chapters 1 to 9) add two leading zeros */
8195 chapterName = [chapterName stringByAppendingFormat:@"00%d,",i+1];
8198 { /* if i is from 9 to 98 (chapters 10 to 99) add one leading zero */
8199 chapterName = [chapterName stringByAppendingFormat:@"0%d,",i+1];
8202 { /* in case i is from 99 to 998 (chapters 100 to 999) no leading zeros */
8203 chapterName = [chapterName stringByAppendingFormat:@"%d,",i+1];
8206 chapterTitle = [fChapterTitlesDelegate tableView:fChapterTable objectValueForTableColumn:fChapterTableNameColumn row:i];
8207 /* escape any commas in the chapter name with "\," */
8208 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"," withString:@"\\,"];
8209 chapterName = [chapterName stringByAppendingString:chapterTitle];
8210 if (i+1 != chapters)
8211 { /* if not the last chapter */
8212 chapterName = [chapterName stringByAppendingString:@ "\n"];
8217 /* try to write it to where the user wanted */
8218 if (![chapterName writeToFile:[sheet filename]
8220 encoding:NSUTF8StringEncoding
8224 [[NSAlert alertWithError:saveError] runModal];
8231 /*******************************
8232 * Subclass of the HBPresetsOutlineView *
8233 *******************************/
8235 @implementation HBPresetsOutlineView
8236 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8240 // By default, NSTableView only drags an image of the first column. Change this to
8241 // drag an image of the queue's icon and PresetName columns.
8242 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8243 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8248 - (void) mouseDown:(NSEvent *)theEvent
8250 [super mouseDown:theEvent];
8256 - (BOOL) isDragging;