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 /* Call UpdateUI every 1/2 sec */
134 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
135 scheduledTimerWithTimeInterval:0.5
137 selector:@selector(updateUI:)
138 userInfo:nil repeats:YES]
139 forMode:NSDefaultRunLoopMode];
142 // Open debug output window now if it was visible when HB was closed
143 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
144 [self showDebugOutputPanel:nil];
146 // Open queue window now if it was visible when HB was closed
147 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
148 [self showQueueWindow:nil];
150 [self openMainWindow:nil];
152 /* We have to set the bool to tell hb what to do after a scan
153 * Initially we set it to NO until we start processing the queue
155 applyQueueToScan = NO;
157 /* Now we re-check the queue array to see if there are
158 * any remaining encodes to be done in it and ask the
159 * user if they want to reload the queue */
160 if ([QueueFileArray count] > 0)
162 /* run getQueueStats to see whats in the queue file */
163 [self getQueueStats];
164 /* this results in these values
165 * fEncodingQueueItem = 0;
167 * fCompletedCount = 0;
168 * fCanceledCount = 0;
172 /*On Screen Notification*/
173 NSString * alertTitle;
175 /* We check to see if there is already another instance of hb running.
176 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
178 if (hbInstanceNum > 1)
180 alertTitle = [NSString stringWithFormat:
181 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
182 NSBeginCriticalAlertSheet(
184 NSLocalizedString(@"Reload Queue", nil),
188 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
189 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
193 if (fWorkingCount > 0 || fPendingCount > 0)
195 if (fWorkingCount > 0)
197 alertTitle = [NSString stringWithFormat:
198 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item(s) and %d Pending Item(s) In Your Queue.", @""),
199 fWorkingCount,fPendingCount];
203 alertTitle = [NSString stringWithFormat:
204 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
208 NSBeginCriticalAlertSheet(
210 NSLocalizedString(@"Reload Queue", nil),
212 NSLocalizedString(@"Empty Queue", nil),
214 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
215 NSLocalizedString(@" Do you want to reload them ?", nil));
219 /* Since we addressed any pending or previously encoding items above, we go ahead and make sure the queue
220 * is empty of any finished items or cancelled items */
221 [self clearQueueAllItems];
222 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
223 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
225 [self browseSources:nil];
228 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
230 [self browseSources:(id)fOpenSourceTitleMMenu];
238 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
239 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
241 [self browseSources:nil];
244 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
246 [self browseSources:(id)fOpenSourceTitleMMenu];
249 currentQueueEncodeNameString = @"";
253 #pragma mark Multiple Instances
255 /* hbInstances checks to see if other instances of HB are running and also sets the pid for this instance for multi-instance queue encoding */
257 /* 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. */
260 /* check to see if another instance of HandBrake.app is running */
261 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
262 NSDictionary *runningAppsDictionary;
264 NSString * thisInstanceAppPath = [[NSBundle mainBundle] bundlePath];
265 NSString * runningInstanceAppPath;
266 int runningInstancePidNum;
267 [self writeToActivityLog: "hbInstances path to this instance: %s", [thisInstanceAppPath UTF8String]];
268 for (runningAppsDictionary in runningAppDictionaries)
270 if ([[runningAppsDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
272 /*Report the path to each active instances app path */
273 runningInstancePidNum = [[runningAppsDictionary valueForKey:@"NSApplicationProcessIdentifier"] intValue];
274 runningInstanceAppPath = [runningAppsDictionary valueForKey:@"NSApplicationPath"];
275 [self writeToActivityLog: "hbInstance found instance pidnum:%d at path: %s", runningInstancePidNum, [runningInstanceAppPath UTF8String]];
276 /* see if this is us by comparing the app path */
277 if ([runningInstanceAppPath isEqualToString: thisInstanceAppPath])
279 /* If so this is our pidnum */
280 [self writeToActivityLog: "hbInstance MATCH FOUND, our pidnum is:%d", runningInstancePidNum];
281 /* Get the PID number for this hb instance, used in multi instance encoding */
282 pidNum = runningInstancePidNum;
283 /* Report this pid to the activity log */
284 [self writeToActivityLog: "Pid for this instance:%d", pidNum];
285 /* Tell fQueueController what our pidNum is */
286 [fQueueController setPidNum:pidNum];
296 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
299 [self writeToActivityLog: "didDimissReloadQueue number of hb instances:%d", hbInstanceNum];
300 if (returnCode == NSAlertOtherReturn)
302 [self writeToActivityLog: "didDimissReloadQueue NSAlertOtherReturn Chosen"];
303 [self clearQueueAllItems];
305 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
306 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
308 [self browseSources:nil];
311 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
313 [self browseSources:(id)fOpenSourceTitleMMenu];
318 [self writeToActivityLog: "didDimissReloadQueue First Button Chosen"];
319 if (hbInstanceNum == 1)
322 [self setQueueEncodingItemsAsPending];
324 [self showQueueWindow:NULL];
328 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
333 hb_get_state( fQueueEncodeLibhb, &s );
335 if ( s.state != HB_STATE_IDLE )
337 int result = NSRunCriticalAlertPanel(
338 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
339 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
340 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
342 if (result == NSAlertDefaultReturn)
344 return NSTerminateNow;
347 return NSTerminateCancel;
350 // Warn if items still in the queue
351 else if ( fPendingCount > 0 )
353 int result = NSRunCriticalAlertPanel(
354 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
355 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
356 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
358 if ( result == NSAlertDefaultReturn )
359 return NSTerminateNow;
361 return NSTerminateCancel;
364 return NSTerminateNow;
367 - (void)applicationWillTerminate:(NSNotification *)aNotification
369 [currentQueueEncodeNameString release];
370 [browsedSourceDisplayName release];
371 [outputPanel release];
372 [fQueueController release];
373 [fPreviewController release];
374 [fPictureController release];
375 [fApplicationIcon release];
378 hb_close(&fQueueEncodeLibhb);
384 - (void) awakeFromNib
387 [fWindow setExcludedFromWindowsMenu:NO];
389 [fAdvancedOptions setView:fAdvancedView];
391 /* lets setup our presets drawer for drag and drop here */
392 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
393 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
394 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
396 /* Initialize currentScanCount so HB can use it to
397 evaluate successive scans */
398 currentScanCount = 0;
401 /* Init UserPresets .plist */
404 fRipIndicatorShown = NO; // initially out of view in the nib
406 /* For 64 bit builds, the threaded animation in the progress
407 * indicators conflicts with the animation in the advanced tab
408 * for reasons not completely clear. jbrjake found a note in the
409 * 10.5 dev notes regarding this possiblility. It was also noted
410 * that unless specified, setUsesThreadedAnimation defaults to true.
411 * So, at least for now we set the indicator animation to NO for
412 * both the scan and regular progress indicators for both 32 and 64 bit
413 * as it test out fine on both and there is no reason our progress indicators
414 * should require their own thread.
417 [fScanIndicator setUsesThreadedAnimation:NO];
418 [fRipIndicator setUsesThreadedAnimation:NO];
422 /* Show/Dont Show Presets drawer upon launch based
423 on user preference DefaultPresetsDrawerShow*/
424 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
426 [fPresetDrawer setDelegate:self];
427 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
428 stringForKey:@"Drawer Size"] );
429 if( drawerSize.width )
430 [fPresetDrawer setContentSize: drawerSize];
431 [fPresetDrawer open];
434 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
435 [fSrcAngleLabel setHidden:YES];
436 [fSrcAnglePopUp setHidden:YES];
438 /* Setup the start / stop popup */
439 [fEncodeStartStopPopUp removeAllItems];
440 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
441 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
442 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
443 /* Align the start / stop widgets with the chapter popups */
444 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
445 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
447 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
448 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
451 NSMenuItem *menuItem;
452 [fDstFormatPopUp removeAllItems];
454 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
455 [menuItem setTag: HB_MUX_MP4];
457 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
458 [menuItem setTag: HB_MUX_MKV];
460 [fDstFormatPopUp selectItemAtIndex: 0];
462 [self formatPopUpChanged:nil];
464 /* We enable the create chapters checkbox here since we are .mp4 */
465 [fCreateChapterMarkers setEnabled: YES];
466 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
468 [fCreateChapterMarkers setState: NSOnState];
474 [fDstFile2Field setStringValue: [NSString stringWithFormat:
475 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
478 [fVidEncoderPopUp removeAllItems];
479 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
483 [fVidTargetSizeField setIntValue: 700];
484 [fVidBitrateField setIntValue: 1000];
486 [fVidQualityMatrix selectCell: fVidBitrateCell];
487 [self videoMatrixChanged:nil];
489 /* Video framerate */
490 [fVidRatePopUp removeAllItems];
491 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
492 for( int i = 0; i < hb_video_rates_count; i++ )
494 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
496 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
497 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
499 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
501 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
502 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
504 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
506 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
507 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
511 [fVidRatePopUp addItemWithTitle:
512 [NSString stringWithUTF8String: hb_video_rates[i].string]];
515 [fVidRatePopUp selectItemAtIndex: 0];
517 /* Set Auto Crop to On at launch */
518 [fPictureController setAutoCrop:YES];
521 [fAudTrack1BitratePopUp removeAllItems];
522 for( int i = 0; i < hb_audio_bitrates_count; i++ )
524 [fAudTrack1BitratePopUp addItemWithTitle:
525 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
528 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
530 /* Audio samplerate */
531 [fAudTrack1RatePopUp removeAllItems];
532 for( int i = 0; i < hb_audio_rates_count; i++ )
534 [fAudTrack1RatePopUp addItemWithTitle:
535 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
537 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
540 [fStatusField setStringValue: @""];
545 /* We disable the Turbo 1st pass checkbox since we are not x264 */
546 [fVidTurboPassCheck setEnabled: NO];
547 [fVidTurboPassCheck setState: NSOffState];
550 /* lets get our default prefs here */
551 [self getDefaultPresets:nil];
552 /* lets initialize the current successful scancount here to 0 */
553 currentSuccessfulScanCount = 0;
556 - (void) enableUI: (bool) b
558 NSControl * controls[] =
559 { fSrcTitleField, fSrcTitlePopUp,
560 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
561 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
562 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
563 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
564 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
565 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
566 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
567 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
568 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
569 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
570 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
571 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
572 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
573 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
574 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
575 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
576 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
577 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,
578 fSrcFrameEndEncodingField, fLoadChaptersButton, fSaveChaptersButton, fFrameratePfrCheck};
581 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
583 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
585 NSTextField * tf = (NSTextField *) controls[i];
586 if( ![tf isBezeled] )
588 [tf setTextColor: b ? [NSColor controlTextColor] :
589 [NSColor disabledControlTextColor]];
593 [controls[i] setEnabled: b];
600 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
601 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
602 [self setEnabledStateOfAudioMixdownControls:nil];
603 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
604 [self calculatePictureSizing:nil];
605 /* Also enable the preview window hud controls */
606 [fPictureController enablePreviewHudControls];
611 [fPresetsOutlineView setEnabled: NO];
612 [fPictureController disablePreviewHudControls];
615 [self videoMatrixChanged:nil];
616 [fAdvancedOptions enableUI:b];
620 /***********************************************************************
622 ***********************************************************************
623 * Shows a progression bar on the dock icon, filled according to
624 * 'progress' (0.0 <= progress <= 1.0).
625 * Called with progress < 0.0 or progress > 1.0, restores the original
627 **********************************************************************/
628 - (void) UpdateDockIcon: (float) progress
631 NSBitmapImageRep * bmp;
633 uint32_t black = htonl( 0x000000FF );
634 uint32_t red = htonl( 0xFF0000FF );
635 uint32_t white = htonl( 0xFFFFFFFF );
636 int row_start, row_end;
639 if( progress < 0.0 || progress > 1.0 )
641 [NSApp setApplicationIconImage: fApplicationIcon];
645 /* Get it in a raw bitmap form */
646 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
647 NSTIFFCompressionNone factor: 1.0];
648 bmp = [NSBitmapImageRep imageRepWithData: tiff];
650 /* Draw the progression bar */
651 /* It's pretty simple (ugly?) now, but I'm no designer */
653 row_start = 3 * (int) [bmp size].height / 4;
654 row_end = 7 * (int) [bmp size].height / 8;
656 for( i = row_start; i < row_start + 2; i++ )
658 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
659 for( j = 0; j < (int) [bmp size].width; j++ )
664 for( i = row_start + 2; i < row_end - 2; i++ )
666 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
669 for( j = 2; j < (int) [bmp size].width - 2; j++ )
671 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
683 for( i = row_end - 2; i < row_end; i++ )
685 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
686 for( j = 0; j < (int) [bmp size].width; j++ )
692 /* Now update the dock icon */
693 tiff = [bmp TIFFRepresentationUsingCompression:
694 NSTIFFCompressionNone factor: 1.0];
695 NSImage* icon = [[NSImage alloc] initWithData: tiff];
696 [NSApp setApplicationIconImage: icon];
700 - (void) updateUI: (NSTimer *) timer
703 /* Update UI for fHandle (user scanning instance of libhb ) */
706 list = hb_get_titles( fHandle );
707 /* check to see if there has been a new scan done
708 this bypasses the constraints of HB_STATE_WORKING
709 not allowing setting a newly scanned source */
710 int checkScanCount = hb_get_scancount( fHandle );
711 if( checkScanCount > currentScanCount )
713 currentScanCount = checkScanCount;
714 [fScanIndicator setIndeterminate: NO];
715 [fScanIndicator setDoubleValue: 0.0];
716 [fScanIndicator setHidden: YES];
717 [self showNewScan:nil];
721 hb_get_state( fHandle, &s );
727 #define p s.param.scanning
728 case HB_STATE_SCANNING:
730 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
731 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
732 p.title_cur, p.title_count]];
733 [fScanIndicator setHidden: NO];
734 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
739 #define p s.param.scandone
740 case HB_STATE_SCANDONE:
742 [fScanIndicator setIndeterminate: NO];
743 [fScanIndicator setDoubleValue: 0.0];
744 [fScanIndicator setHidden: YES];
745 [self writeToActivityLog:"ScanDone state received from fHandle"];
746 [self showNewScan:nil];
747 [[fWindow toolbar] validateVisibleItems];
753 #define p s.param.working
754 case HB_STATE_WORKING:
761 #define p s.param.muxing
762 case HB_STATE_MUXING:
769 case HB_STATE_PAUSED:
772 case HB_STATE_WORKDONE:
779 /* Update UI for fQueueEncodeLibhb */
781 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
782 /* check to see if there has been a new scan done
783 this bypasses the constraints of HB_STATE_WORKING
784 not allowing setting a newly scanned source */
786 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
787 if( checkScanCount > currentScanCount )
789 currentScanCount = checkScanCount;
793 hb_get_state( fQueueEncodeLibhb, &s );
799 #define p s.param.scanning
800 case HB_STATE_SCANNING:
802 [fStatusField setStringValue: [NSString stringWithFormat:
803 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
804 p.title_cur, p.title_count]];
806 /* Set the status string in fQueueController as well */
807 [fQueueController setQueueStatusString: [NSString stringWithFormat:
808 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
809 p.title_cur, p.title_count]];
814 #define p s.param.scandone
815 case HB_STATE_SCANDONE:
817 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
818 [self processNewQueueEncode];
819 [[fWindow toolbar] validateVisibleItems];
826 #define p s.param.working
828 case HB_STATE_SEARCHING:
830 NSMutableString * string;
831 NSString * pass_desc;
833 /* Update text field */
835 //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];
836 /* For now, do not announce "pass x of x for the search phase ... */
837 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
841 [string appendFormat:
842 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
845 [fStatusField setStringValue: string];
846 /* Set the status string in fQueueController as well */
847 [fQueueController setQueueStatusString: string];
849 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
850 [fRipIndicator setIndeterminate: NO];
851 [fRipIndicator setDoubleValue:100.0 * progress_total];
853 // If progress bar hasn't been revealed at the bottom of the window, do
854 // that now. This code used to be in doRip. I moved it to here to handle
855 // the case where hb_start is called by HBQueueController and not from
857 if( !fRipIndicatorShown )
859 NSRect frame = [fWindow frame];
860 if( frame.size.width <= 591 )
861 frame.size.width = 591;
862 frame.size.height += 36;
863 frame.origin.y -= 36;
864 [fWindow setFrame:frame display:YES animate:YES];
865 fRipIndicatorShown = YES;
869 /* Update dock icon */
870 /* Note not done yet */
875 case HB_STATE_WORKING:
877 NSMutableString * string;
878 NSString * pass_desc;
879 /* Update text field */
880 if (p.job_cur == 1 && p.job_count > 1)
882 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
884 pass_desc = @"(subtitle scan)";
896 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
900 [string appendFormat:
901 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
902 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
905 [fStatusField setStringValue: string];
906 /* Set the status string in fQueueController as well but add currentQueueEncodeNameString to delineate
907 * which encode is being worked on by this instance in a multiple instance situation
909 NSString * queueStatusString = [NSString stringWithFormat:@"%@ -> %@",string,currentQueueEncodeNameString];
910 [fQueueController setQueueStatusString:queueStatusString];
913 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
914 [fRipIndicator setIndeterminate: NO];
915 [fRipIndicator setDoubleValue:100.0 * progress_total];
917 // If progress bar hasn't been revealed at the bottom of the window, do
918 // that now. This code used to be in doRip. I moved it to here to handle
919 // the case where hb_start is called by HBQueueController and not from
921 if( !fRipIndicatorShown )
923 NSRect frame = [fWindow frame];
924 if( frame.size.width <= 591 )
925 frame.size.width = 591;
926 frame.size.height += 36;
927 frame.origin.y -= 36;
928 [fWindow setFrame:frame display:YES animate:YES];
929 fRipIndicatorShown = YES;
933 /* Update dock icon */
934 if( dockIconProgress < 100.0 * progress_total )
936 [self UpdateDockIcon: progress_total];
937 dockIconProgress += 5;
944 #define p s.param.muxing
945 case HB_STATE_MUXING:
947 /* Update text field */
948 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
949 /* Set the status string in fQueueController as well */
950 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
952 [fRipIndicator setIndeterminate: YES];
953 [fRipIndicator startAnimation: nil];
955 /* Update dock icon */
956 [self UpdateDockIcon: 1.0];
962 case HB_STATE_PAUSED:
963 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
964 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
968 case HB_STATE_WORKDONE:
970 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
971 // or someone calling hb_stop. In the latter case, hb_stop does not clear
972 // out the remaining passes/jobs in the queue. We'll do that here.
974 // Delete all remaining jobs of this encode.
975 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
976 /* Set the status string in fQueueController as well */
977 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
978 [fRipIndicator setIndeterminate: NO];
979 [fRipIndicator stopAnimation: nil];
980 [fRipIndicator setDoubleValue: 0.0];
981 [[fWindow toolbar] validateVisibleItems];
983 /* Restore dock icon */
984 [self UpdateDockIcon: -1.0];
985 dockIconProgress = 0;
987 if( fRipIndicatorShown )
989 NSRect frame = [fWindow frame];
990 if( frame.size.width <= 591 )
991 frame.size.width = 591;
992 frame.size.height += -36;
993 frame.origin.y -= -36;
994 [fWindow setFrame:frame display:YES animate:YES];
995 fRipIndicatorShown = NO;
997 /* Since we are done with this encode, tell output to stop writing to the
998 * individual encode log
1000 [outputPanel endEncodeLog];
1001 /* Check to see if the encode state has not been cancelled
1002 to determine if we should check for encode done notifications */
1003 if( fEncodeState != 2 )
1005 NSString *pathOfFinishedEncode;
1006 /* Get the output file name for the finished encode */
1007 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
1009 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
1010 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1011 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1013 /* If Play System Alert has been selected in Preferences */
1014 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
1018 [self showGrowlDoneNotification:pathOfFinishedEncode];
1022 [self sendToMetaX:pathOfFinishedEncode];
1024 /* since we have successfully completed an encode, we increment the queue counter */
1025 [self incrementQueueItemDone:currentQueueEncodeIndex];
1033 /* 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
1034 * so we go ahead and do it in this existing timer as opposed to using a new one */
1036 NSMutableArray * tempQueueArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1037 [QueueFileArray setArray:tempQueueArray];
1038 [tempQueueArray release];
1039 /* Send Fresh QueueFileArray to fQueueController to update queue window */
1040 [fQueueController setQueueArray: QueueFileArray];
1041 [self getQueueStats];
1045 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1046 - (void) writeToActivityLog:(const char *) format, ...
1049 va_start(args, format);
1053 vsnprintf( str, 1024, format, args );
1055 time_t _now = time( NULL );
1056 struct tm * now = localtime( &_now );
1057 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1063 #pragma mark Toolbar
1064 // ============================================================
1065 // NSToolbar Related Methods
1066 // ============================================================
1068 - (void) setupToolbar {
1069 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1071 [toolbar setAllowsUserCustomization: YES];
1072 [toolbar setAutosavesConfiguration: YES];
1073 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1075 [toolbar setDelegate: self];
1077 [fWindow setToolbar: toolbar];
1080 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1081 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1082 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1084 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1086 [item setLabel: @"Toggle Presets"];
1087 [item setPaletteLabel: @"Toggler Presets"];
1088 [item setToolTip: @"Open/Close Preset Drawer"];
1089 [item setImage: [NSImage imageNamed: @"Drawer"]];
1090 [item setTarget: self];
1091 [item setAction: @selector(toggleDrawer:)];
1092 [item setAutovalidates: NO];
1094 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1096 [item setLabel: @"Start"];
1097 [item setPaletteLabel: @"Start Encoding"];
1098 [item setToolTip: @"Start Encoding"];
1099 [item setImage: [NSImage imageNamed: @"Play"]];
1100 [item setTarget: self];
1101 [item setAction: @selector(Rip:)];
1103 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1105 [item setLabel: @"Show Queue"];
1106 [item setPaletteLabel: @"Show Queue"];
1107 [item setToolTip: @"Show Queue"];
1108 [item setImage: [NSImage imageNamed: @"Queue"]];
1109 [item setTarget: self];
1110 [item setAction: @selector(showQueueWindow:)];
1111 [item setAutovalidates: NO];
1113 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1115 [item setLabel: @"Add to Queue"];
1116 [item setPaletteLabel: @"Add to Queue"];
1117 [item setToolTip: @"Add to Queue"];
1118 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1119 [item setTarget: self];
1120 [item setAction: @selector(addToQueue:)];
1122 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1124 [item setLabel: @"Pause"];
1125 [item setPaletteLabel: @"Pause Encoding"];
1126 [item setToolTip: @"Pause Encoding"];
1127 [item setImage: [NSImage imageNamed: @"Pause"]];
1128 [item setTarget: self];
1129 [item setAction: @selector(Pause:)];
1131 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1133 [item setLabel: @"Picture Settings"];
1134 [item setPaletteLabel: @"Show Picture Settings"];
1135 [item setToolTip: @"Show Picture Settings"];
1136 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1137 [item setTarget: self];
1138 [item setAction: @selector(showPicturePanel:)];
1140 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1142 [item setLabel: @"Preview Window"];
1143 [item setPaletteLabel: @"Show Preview"];
1144 [item setToolTip: @"Show Preview"];
1145 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1146 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1147 [item setTarget: self];
1148 [item setAction: @selector(showPreviewWindow:)];
1150 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1152 [item setLabel: @"Activity Window"];
1153 [item setPaletteLabel: @"Show Activity Window"];
1154 [item setToolTip: @"Show Activity Window"];
1155 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1156 [item setTarget: self];
1157 [item setAction: @selector(showDebugOutputPanel:)];
1158 [item setAutovalidates: NO];
1160 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1162 [item setLabel: @"Source"];
1163 [item setPaletteLabel: @"Source"];
1164 [item setToolTip: @"Choose Video Source"];
1165 [item setImage: [NSImage imageNamed: @"Source"]];
1166 [item setTarget: self];
1167 [item setAction: @selector(browseSources:)];
1177 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1179 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1180 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1181 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1184 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1186 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1187 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1188 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1189 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1192 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1194 NSString * ident = [toolbarItem itemIdentifier];
1200 hb_get_state( fHandle, &s );
1201 if (s.state == HB_STATE_SCANNING)
1204 if ([ident isEqualToString: ChooseSourceIdentifier])
1206 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1207 [toolbarItem setLabel: @"Cancel Scan"];
1208 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1209 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1213 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1218 if ([ident isEqualToString: ChooseSourceIdentifier])
1220 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1221 [toolbarItem setLabel: @"Source"];
1222 [toolbarItem setPaletteLabel: @"Source"];
1223 [toolbarItem setToolTip: @"Choose Video Source"];
1228 hb_get_state2( fQueueEncodeLibhb, &s );
1230 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1232 if ([ident isEqualToString: StartEncodingIdentifier])
1234 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1235 [toolbarItem setLabel: @"Stop"];
1236 [toolbarItem setPaletteLabel: @"Stop"];
1237 [toolbarItem setToolTip: @"Stop Encoding"];
1240 if ([ident isEqualToString: PauseEncodingIdentifier])
1242 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1243 [toolbarItem setLabel: @"Pause"];
1244 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1245 [toolbarItem setToolTip: @"Pause Encoding"];
1250 if ([ident isEqualToString: AddToQueueIdentifier])
1252 if ([ident isEqualToString: ShowPictureIdentifier])
1254 if ([ident isEqualToString: ShowPreviewIdentifier])
1258 else if (s.state == HB_STATE_PAUSED)
1260 if ([ident isEqualToString: PauseEncodingIdentifier])
1262 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1263 [toolbarItem setLabel: @"Resume"];
1264 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1265 [toolbarItem setToolTip: @"Resume Encoding"];
1268 if ([ident isEqualToString: StartEncodingIdentifier])
1270 if ([ident isEqualToString: AddToQueueIdentifier])
1272 if ([ident isEqualToString: ShowPictureIdentifier])
1274 if ([ident isEqualToString: ShowPreviewIdentifier])
1277 else if (s.state == HB_STATE_SCANNING)
1279 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1281 if ([ident isEqualToString: StartEncodingIdentifier])
1283 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1284 if (hb_count(fHandle) > 0)
1285 [toolbarItem setLabel: @"Start Queue"];
1287 [toolbarItem setLabel: @"Start"];
1288 [toolbarItem setPaletteLabel: @"Start Encoding"];
1289 [toolbarItem setToolTip: @"Start Encoding"];
1292 if ([ident isEqualToString: AddToQueueIdentifier])
1294 if ([ident isEqualToString: ShowPictureIdentifier])
1296 if ([ident isEqualToString: ShowPreviewIdentifier])
1301 /* If there are any pending queue items, make sure the start/stop button is active */
1302 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1304 if ([ident isEqualToString: ShowQueueIdentifier])
1306 if ([ident isEqualToString: ToggleDrawerIdentifier])
1308 if ([ident isEqualToString: ChooseSourceIdentifier])
1310 if ([ident isEqualToString: ShowActivityIdentifier])
1316 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1318 SEL action = [menuItem action];
1321 hb_get_state2( fHandle, &s );
1325 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1326 return SuccessfulScan && [fWindow attachedSheet] == nil;
1328 if (action == @selector(browseSources:))
1330 if (s.state == HB_STATE_SCANNING)
1333 return [fWindow attachedSheet] == nil;
1335 if (action == @selector(selectDefaultPreset:))
1336 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1337 if (action == @selector(Pause:))
1339 if (s.state == HB_STATE_WORKING)
1341 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1342 [menuItem setTitle:@"Pause Encoding"];
1345 else if (s.state == HB_STATE_PAUSED)
1347 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1348 [menuItem setTitle:@"Resume Encoding"];
1354 if (action == @selector(Rip:))
1356 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1358 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1359 [menuItem setTitle:@"Stop Encoding"];
1362 else if (SuccessfulScan)
1364 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1365 [menuItem setTitle:@"Start Encoding"];
1366 return [fWindow attachedSheet] == nil;
1372 if( action == @selector(setDefaultPreset:) )
1374 return [fPresetsOutlineView selectedRow] != -1;
1381 #pragma mark Encode Done Actions
1382 // register a test notification and make
1383 // it enabled by default
1384 #define SERVICE_NAME @"Encode Done"
1385 - (NSDictionary *)registrationDictionaryForGrowl
1387 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1388 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1389 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1392 return registrationDictionary;
1395 -(void)showGrowlDoneNotification:(NSString *) filePath
1397 /* This end of encode action is called as each encode rolls off of the queue */
1398 /* Setup the Growl stuff ... */
1399 NSString * finishedEncode = filePath;
1400 /* strip off the path to just show the file name */
1401 finishedEncode = [finishedEncode lastPathComponent];
1402 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1403 [GrowlApplicationBridge
1404 notifyWithTitle:@"Put down that cocktail..."
1405 description:growlMssg
1406 notificationName:SERVICE_NAME
1412 -(void)sendToMetaX:(NSString *) filePath
1414 /* This end of encode action is called as each encode rolls off of the queue */
1415 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1417 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1418 if (![sendToApp isEqualToString:@"None"])
1420 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1421 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1422 [myScript executeAndReturnError: nil];
1429 - (void) queueCompletedAlerts
1431 /* If Play System Alert has been selected in Preferences */
1432 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
1437 /* If Alert Window or Window and Growl has been selected */
1438 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
1439 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
1441 /*On Screen Notification*/
1443 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
1444 [NSApp requestUserAttention:NSCriticalRequest];
1447 /* If sleep has been selected */
1448 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
1451 NSDictionary* errorDict;
1452 NSAppleEventDescriptor* returnDescriptor = nil;
1453 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
1454 @"tell application \"Finder\" to sleep"];
1455 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1456 [scriptObject release];
1458 /* If Shutdown has been selected */
1459 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
1462 NSDictionary* errorDict;
1463 NSAppleEventDescriptor* returnDescriptor = nil;
1464 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
1465 @"tell application \"Finder\" to shut down"];
1466 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1467 [scriptObject release];
1472 #pragma mark Get New Source
1474 /*Opens the source browse window, called from Open Source widgets */
1475 - (IBAction) browseSources: (id) sender
1479 hb_get_state( fHandle, &s );
1480 if (s.state == HB_STATE_SCANNING)
1482 [self cancelScanning:nil];
1487 NSOpenPanel * panel;
1489 panel = [NSOpenPanel openPanel];
1490 [panel setAllowsMultipleSelection: NO];
1491 [panel setCanChooseFiles: YES];
1492 [panel setCanChooseDirectories: YES ];
1493 NSString * sourceDirectory;
1494 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1496 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1500 sourceDirectory = @"~/Desktop";
1501 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1503 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1504 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1506 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1507 modalForWindow: fWindow modalDelegate: self
1508 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1509 contextInfo: sender];
1512 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1513 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1515 /* we convert the sender content of contextInfo back into a variable called sender
1516 * mostly just for consistency for evaluation later
1518 id sender = (id)contextInfo;
1519 /* User selected a file to open */
1520 if( returnCode == NSOKButton )
1522 /* Free display name allocated previously by this code */
1523 [browsedSourceDisplayName release];
1525 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1526 /* we set the last searched source directory in the prefs here */
1527 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1528 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1529 /* we order out sheet, which is the browse window as we need to open
1530 * the title selection sheet right away
1532 [sheet orderOut: self];
1534 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1536 /* We put the chosen source path in the source display text field for the
1537 * source title selection sheet in which the user specifies the specific title to be
1538 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1539 * purposes in the title panel
1542 [fScanSrcTitlePathField setStringValue:scanPath];
1543 NSString *displayTitlescanSourceName;
1545 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1547 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1548 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1549 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1553 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1554 displayTitlescanSourceName = [scanPath lastPathComponent];
1556 /* we set the source display name in the title selection dialogue */
1557 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1558 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1559 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1560 /* We show the actual sheet where the user specifies the title to be scanned
1561 * as we are going to do a title specific scan
1563 [self showSourceTitleScanPanel:nil];
1567 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1568 NSString *path = [[sheet filenames] objectAtIndex: 0];
1570 /* We check to see if the chosen file at path is a package */
1571 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1573 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1574 /* We check to see if this is an .eyetv package */
1575 if ([[path pathExtension] isEqualToString: @"eyetv"])
1577 [self writeToActivityLog:"trying to open eyetv package"];
1578 /* We're looking at an EyeTV package - try to open its enclosed
1580 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1582 int n = [[path stringByAppendingString: @"/"]
1583 completePathIntoString: &mpgname caseSensitive: YES
1584 matchesIntoArray: nil
1585 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1588 /* Found an mpeg inside the eyetv package, make it our scan path
1589 and call performScan on the enclosed mpeg */
1591 [self writeToActivityLog:"found mpeg in eyetv package"];
1592 [self performScan:path scanTitleNum:0];
1596 /* We did not find an mpeg file in our package, so we do not call performScan */
1597 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1600 /* We check to see if this is a .dvdmedia package */
1601 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1603 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1604 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1605 [self writeToActivityLog:"trying to open dvdmedia package"];
1606 [self performScan:path scanTitleNum:0];
1610 /* The package is not an eyetv package, so we do not call performScan */
1611 [self writeToActivityLog:"unable to open package"];
1614 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1616 /* path is not a package, so we call perform scan directly on our file */
1617 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1619 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1620 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1621 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1625 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1626 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1627 /* make sure we remove any path extension as this can also be an '.mpg' file */
1628 browsedSourceDisplayName = [[path lastPathComponent] retain];
1630 applyQueueToScan = NO;
1631 [self performScan:path scanTitleNum:0];
1639 - (IBAction)showAboutPanel:(id)sender
1641 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1642 fApplicationIcon, @"ApplicationIcon",
1644 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1648 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1649 - (IBAction) showSourceTitleScanPanel: (id) sender
1651 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1654 [fScanSrcTitleNumField setStringValue: @"0"];
1655 /* Show the panel */
1656 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1659 - (IBAction) closeSourceTitleScanPanel: (id) sender
1661 [NSApp endSheet: fScanSrcTitlePanel];
1662 [fScanSrcTitlePanel orderOut: self];
1664 if(sender == fScanSrcTitleOpenButton)
1666 /* We setup the scan status in the main window to indicate a source title scan */
1667 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1668 [fScanIndicator setHidden: NO];
1669 [fScanIndicator setIndeterminate: YES];
1670 [fScanIndicator startAnimation: nil];
1672 /* We use the performScan method to actually perform the specified scan passing the path and the title
1675 applyQueueToScan = NO;
1676 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1680 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1681 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1684 /* use a bool to determine whether or not we can decrypt using vlc */
1685 BOOL cancelScanDecrypt = 0;
1687 NSString *path = scanPath;
1688 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1690 // Notify ChapterTitles that there's no title
1691 [fChapterTitlesDelegate resetWithTitle:nil];
1692 [fChapterTable reloadData];
1694 // Notify Subtitles that there's no title
1695 [fSubtitlesDelegate resetWithTitle:nil];
1696 [fSubtitlesTable reloadData];
1698 [self enableUI: NO];
1700 if( [detector isVideoDVD] )
1702 // The chosen path was actually on a DVD, so use the raw block
1703 // device path instead.
1704 path = [detector devicePath];
1705 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1707 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1708 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
1711 /*compatible vlc not found, so we set the bool to cancel scanning to 1 */
1712 cancelScanDecrypt = 1;
1713 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1715 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");
1716 [NSApp requestUserAttention:NSCriticalRequest];
1718 if (status == NSAlertDefaultReturn)
1720 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1721 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1723 else if (status == NSAlertAlternateReturn)
1725 /* User chose to cancel the scan */
1726 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1730 /* 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 */
1731 cancelScanDecrypt = 0;
1732 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1738 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1739 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1745 if (cancelScanDecrypt == 0)
1747 /* we actually pass the scan off to libhb here */
1748 /* If there is no title number passed to scan, we use "0"
1749 * which causes the default behavior of a full source scan
1755 if (scanTitleNum > 0)
1757 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1759 /* We use our advance pref to determine how many previews to scan */
1760 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1761 /* set title to NULL */
1763 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1764 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1768 - (IBAction) cancelScanning:(id)sender
1770 hb_scan_stop(fHandle);
1773 - (IBAction) showNewScan:(id)sender
1777 int feature_title=0; // Used to store the main feature title
1779 list = hb_get_titles( fHandle );
1781 if( !hb_list_count( list ) )
1783 /* We display a message if a valid dvd source was not chosen */
1784 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1785 SuccessfulScan = NO;
1787 // Notify ChapterTitles that there's no title
1788 [fSubtitlesDelegate resetWithTitle:nil];
1789 [fSubtitlesTable reloadData];
1791 // Notify Subtitles that there's no title
1792 [fChapterTitlesDelegate resetWithTitle:nil];
1793 [fChapterTable reloadData];
1797 if (applyQueueToScan == YES)
1799 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1800 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1803 else if (applyQueueToScan == NO)
1805 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1809 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1812 /* We increment the successful scancount here by one,
1813 which we use at the end of this function to tell the gui
1814 if this is the first successful scan since launch and whether
1815 or not we should set all settings to the defaults */
1816 currentSuccessfulScanCount++;
1818 [[fWindow toolbar] validateVisibleItems];
1820 [fSrcTitlePopUp removeAllItems];
1821 for( int i = 0; i < hb_list_count( list ); i++ )
1823 title = (hb_title_t *) hb_list_item( list, i );
1825 currentSource = [NSString stringWithUTF8String: title->name];
1826 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1827 if (!browsedSourceDisplayName)
1829 browsedSourceDisplayName = @"NoNameDetected";
1831 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1833 /* If its a queue rescan for edit, get the queue item output path */
1834 /* if not, its a new source scan. */
1835 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1836 if (applyQueueToScan == YES)
1838 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1840 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1842 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1843 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1847 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1848 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1851 /* See if this is the main feature according to libhb */
1852 if (title->index == title->job->feature)
1857 [fSrcTitlePopUp addItemWithTitle: [NSString
1858 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1859 title->name,title->index, title->hours, title->minutes,
1863 /* if we are a stream, select the first title */
1864 if (title->type == HB_STREAM_TYPE)
1866 [fSrcTitlePopUp selectItemAtIndex: 0];
1870 /* if not then select the main feature title */
1871 [fSrcTitlePopUp selectItemAtIndex: feature_title];
1873 [self titlePopUpChanged:nil];
1875 SuccessfulScan = YES;
1876 [self enableUI: YES];
1878 /* if its the initial successful scan after awakeFromNib */
1879 if (currentSuccessfulScanCount == 1)
1881 [self encodeStartStopPopUpChanged:nil];
1883 [self selectDefaultPreset:nil];
1885 // Open preview window now if it was visible when HB was closed
1886 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1887 [self showPreviewWindow:nil];
1889 // Open picture sizing window now if it was visible when HB was closed
1890 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1891 [self showPicturePanel:nil];
1894 if (applyQueueToScan == YES)
1896 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1897 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1898 [self applyQueueSettingsToMainWindow:nil];
1909 #pragma mark New Output Destination
1911 - (IBAction) browseFile: (id) sender
1913 /* Open a panel to let the user choose and update the text field */
1914 NSSavePanel * panel = [NSSavePanel savePanel];
1915 /* We get the current file name and path from the destination field here */
1916 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1917 modalForWindow: fWindow modalDelegate: self
1918 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1922 - (void) browseFileDone: (NSSavePanel *) sheet
1923 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1925 if( returnCode == NSOKButton )
1927 [fDstFile2Field setStringValue: [sheet filename]];
1928 /* Save this path to the prefs so that on next browse destination window it opens there */
1929 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1930 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1936 #pragma mark Main Window Control
1938 - (IBAction) openMainWindow: (id) sender
1940 [fWindow makeKeyAndOrderFront:nil];
1943 - (BOOL) windowShouldClose: (id) sender
1948 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1951 [fWindow makeKeyAndOrderFront:nil];
1959 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1960 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1965 #pragma mark Queue File
1967 - (void) loadQueueFile {
1968 /* We declare the default NSFileManager into fileManager */
1969 NSFileManager * fileManager = [NSFileManager defaultManager];
1970 /*We define the location of the user presets file */
1971 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1972 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1973 /* We check for the Queue.plist */
1974 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1976 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1979 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1980 /* lets check to see if there is anything in the queue file .plist */
1981 if (nil == QueueFileArray)
1983 /* if not, then lets initialize an empty array */
1984 QueueFileArray = [[NSMutableArray alloc] init];
1988 /* ONLY clear out encoded items if we are single instance */
1989 if (hbInstanceNum == 1)
1991 [self clearQueueEncodedItems];
1996 - (void)addQueueFileItem
1998 [QueueFileArray addObject:[self createQueueFileItem]];
1999 [self saveQueueFileItem];
2003 - (void) removeQueueFileItem:(int) queueItemToRemove
2005 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2006 [self saveQueueFileItem];
2010 - (void)saveQueueFileItem
2012 [QueueFileArray writeToFile:QueueFile atomically:YES];
2013 [fQueueController setQueueArray: QueueFileArray];
2014 [self getQueueStats];
2017 - (void)getQueueStats
2019 /* lets get the stats on the status of the queue array */
2021 fEncodingQueueItem = 0;
2023 fCompletedCount = 0;
2027 /* We use a number system to set the encode status of the queue item
2029 * 0 == already encoded
2030 * 1 == is being encoded
2031 * 2 == is yet to be encoded
2036 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2038 while (tempObject = [enumerator nextObject])
2040 NSDictionary *thisQueueDict = tempObject;
2041 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2045 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2048 fEncodingQueueItem = i;
2049 /* check to see if we are the instance doing this encoding */
2050 if ([thisQueueDict objectForKey:@"EncodingPID"] && [[thisQueueDict objectForKey:@"EncodingPID"] intValue] == pidNum)
2052 currentQueueEncodeIndex = i;
2056 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2060 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2067 /* Set the queue status field in the main window */
2068 NSMutableString * string;
2069 if (fPendingCount == 1)
2071 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2075 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2077 [fQueueStatus setStringValue:string];
2080 /* Used to get the next pending queue item index and return it if found */
2081 - (int)getNextPendingQueueIndex
2083 /* initialize nextPendingIndex to -1, this value tells incrementQueueItemDone that there are no pending items in the queue */
2084 int nextPendingIndex = -1;
2085 BOOL nextPendingFound = NO;
2086 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2089 while (tempObject = [enumerator nextObject])
2091 NSDictionary *thisQueueDict = tempObject;
2092 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2 && nextPendingFound == NO) // pending
2094 nextPendingFound = YES;
2095 nextPendingIndex = [QueueFileArray indexOfObject: tempObject];
2096 [self writeToActivityLog: "getNextPendingQueueIndex next pending encod index is:%d", nextPendingIndex];
2100 return nextPendingIndex;
2104 /* This method will set any item marked as encoding back to pending
2105 * currently used right after a queue reload
2107 - (void) setQueueEncodingItemsAsPending
2109 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2111 NSMutableArray *tempArray;
2112 tempArray = [NSMutableArray array];
2113 /* we look here to see if the preset is we move on to the next one */
2114 while ( tempObject = [enumerator nextObject] )
2116 /* We want to keep any queue item that is pending or was previously being encoded */
2117 if ([[tempObject objectForKey:@"Status"] intValue] == 1 || [[tempObject objectForKey:@"Status"] intValue] == 2)
2119 /* If the queue item is marked as "encoding" (1)
2120 * then change its status back to pending (2) which effectively
2121 * puts it back into the queue to be encoded
2123 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2125 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2127 [tempArray addObject:tempObject];
2131 [QueueFileArray setArray:tempArray];
2132 [self saveQueueFileItem];
2136 /* This method will clear the queue of any encodes that are not still pending
2137 * this includes both successfully completed encodes as well as cancelled encodes */
2138 - (void) clearQueueEncodedItems
2140 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2142 NSMutableArray *tempArray;
2143 tempArray = [NSMutableArray array];
2144 /* we look here to see if the preset is we move on to the next one */
2145 while ( tempObject = [enumerator nextObject] )
2147 /* If the queue item is either completed (0) or cancelled (3) from the
2148 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2149 * NOTE: this means we retain pending (2) and also an item that is marked as
2150 * still encoding (1). If the queue has an item that is still marked as encoding
2151 * from a previous session, we can conlude that HB was either shutdown, or crashed
2152 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2154 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2156 [tempArray addObject:tempObject];
2160 [QueueFileArray removeObjectsInArray:tempArray];
2161 [self saveQueueFileItem];
2164 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2165 - (void) clearQueueAllItems
2167 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2169 NSMutableArray *tempArray;
2170 tempArray = [NSMutableArray array];
2171 /* we look here to see if the preset is we move on to the next one */
2172 while ( tempObject = [enumerator nextObject] )
2174 [tempArray addObject:tempObject];
2177 [QueueFileArray removeObjectsInArray:tempArray];
2178 [self saveQueueFileItem];
2181 /* This method will duplicate prepareJob however into the
2182 * queue .plist instead of into the job structure so it can
2183 * be recalled later */
2184 - (NSDictionary *)createQueueFileItem
2186 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2188 hb_list_t * list = hb_get_titles( fHandle );
2189 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2190 [fSrcTitlePopUp indexOfSelectedItem] );
2191 hb_job_t * job = title->job;
2195 /* We use a number system to set the encode status of the queue item
2196 * 0 == already encoded
2197 * 1 == is being encoded
2198 * 2 == is yet to be encoded
2201 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2202 /* Source and Destination Information */
2204 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2205 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2206 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2207 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2209 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2210 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2212 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2214 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2216 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2218 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2220 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2222 /* Chapter encode info */
2223 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2224 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2225 /* Time (pts) encode info */
2226 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2227 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2228 /* Frame number encode info */
2229 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2230 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2233 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2234 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2235 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2237 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2239 /* Lets get the preset info if there is any */
2240 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2241 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2243 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2244 /* Chapter Markers*/
2245 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2246 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2248 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2252 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2255 /* We need to get the list of chapter names to put into an array and store
2256 * in our queue, so they can be reapplied in prepareJob when this queue
2257 * item comes up if Chapter Markers is set to on.
2260 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2261 int chaptercount = hb_list_count( fTitle->list_chapter );
2262 for( i = 0; i < chaptercount; i++ )
2264 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2265 if( chapter != NULL )
2267 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2270 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2271 [ChapterNamesArray autorelease];
2273 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2274 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2275 /* Mux mp4 with http optimization */
2276 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2277 /* Add iPod uuid atom */
2278 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2282 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2283 /* x264 Option String */
2284 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2286 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2287 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2288 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2289 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2291 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2292 [queueFileJob setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
2294 /* 2 Pass Encoding */
2295 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2296 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2297 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2299 /* Picture Sizing */
2300 /* Use Max Picture settings for whatever the dvd is.*/
2301 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2302 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2303 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2304 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2305 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2306 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2307 /* if we are custom anamorphic, store the exact storage, par and display dims */
2308 if (fTitle->job->anamorphic.mode == 3)
2310 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2312 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2313 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2315 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2316 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2318 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2319 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2322 NSString * pictureSummary;
2323 pictureSummary = [fPictureSizeField stringValue];
2324 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2325 /* Set crop settings here */
2326 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2327 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2328 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2329 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2330 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2332 /* Picture Filters */
2333 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2334 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2336 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2337 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2338 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2340 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2341 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2343 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2344 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2346 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2348 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2351 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2353 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2354 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2355 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2356 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2357 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2358 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2359 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2361 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2363 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2364 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2365 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2366 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2367 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2368 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2369 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2371 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2373 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2374 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2375 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2376 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2377 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2378 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2379 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2381 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2383 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2384 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2385 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2386 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2387 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2388 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2389 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2393 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2394 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2395 [subtitlesArray autorelease];
2397 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2399 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2401 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2404 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2408 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2411 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2412 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2413 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2415 /* Picture Sizing */
2416 /* Use Max Picture settings for whatever the dvd is.*/
2417 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2418 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2419 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2420 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2421 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2423 /* Set crop settings here */
2424 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2425 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2426 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2427 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2428 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2432 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2434 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2435 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2436 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2437 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2439 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2441 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2442 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2443 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2444 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2446 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2448 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2449 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2450 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2451 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2453 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2455 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2456 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2457 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2458 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2461 /* we need to auto relase the queueFileJob and return it */
2462 [queueFileJob autorelease];
2463 return queueFileJob;
2467 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2468 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2470 NSUInteger index = [indexSet lastIndex];
2471 NSUInteger aboveInsertIndexCount = 0;
2474 NSUInteger removeIndex;
2476 if (index >= insertIndex)
2478 removeIndex = index + aboveInsertIndexCount;
2479 aboveInsertIndexCount++;
2483 removeIndex = index;
2487 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2488 [QueueFileArray removeObjectAtIndex:removeIndex];
2489 [QueueFileArray insertObject:object atIndex:insertIndex];
2492 index = [indexSet indexLessThanIndex:index];
2494 /* We save all of the Queue data here
2495 * and it also gets sent back to the queue controller*/
2496 [self saveQueueFileItem];
2502 #pragma mark Queue Job Processing
2504 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2506 /* Mark the encode just finished as done (status 0)*/
2507 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2509 /* We save all of the Queue data here */
2510 [self saveQueueFileItem];
2512 /* Since we have now marked a queue item as done
2513 * we can go ahead and increment currentQueueEncodeIndex
2514 * so that if there is anything left in the queue we can
2515 * go ahead and move to the next item if we want to */
2516 int queueItems = [QueueFileArray count];
2517 /* Check to see if there are any more pending items in the queue */
2518 int newQueueItemIndex = [self getNextPendingQueueIndex];
2519 /* If we still have more pending items in our queue, lets go to the next one */
2520 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
2522 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
2523 currentQueueEncodeIndex = newQueueItemIndex;
2524 /* 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 */
2525 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2526 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
2527 [self saveQueueFileItem];
2528 /* now we can go ahead and scan the new pending queue item */
2529 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2534 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
2535 /*Since there are no more items to encode, go to queueCompletedAlerts for user specified alerts after queue completed*/
2536 [self queueCompletedAlerts];
2540 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2541 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2543 /* Tell HB to output a new activity log file for this encode */
2544 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2546 /* We now flag the queue item as being owned by this instance of HB using the PID */
2547 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:pidNum] forKey:@"EncodingPID"];
2548 /* Get the currentQueueEncodeNameString from the queue item to display in the status field */
2549 currentQueueEncodeNameString = [[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"] lastPathComponent]retain];
2550 /* We save all of the Queue data here */
2551 [self saveQueueFileItem];
2553 /* use a bool to determine whether or not we can decrypt using vlc */
2554 BOOL cancelScanDecrypt = 0;
2555 /* set the bool so that showNewScan knows to apply the appropriate queue
2556 * settings as this is a queue rescan
2558 NSString *path = scanPath;
2559 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2561 if( [detector isVideoDVD] )
2563 // The chosen path was actually on a DVD, so use the raw block
2564 // device path instead.
2565 path = [detector devicePath];
2566 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2568 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2569 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
2572 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2573 cancelScanDecrypt = 1;
2574 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2576 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");
2577 [NSApp requestUserAttention:NSCriticalRequest];
2579 if (status == NSAlertDefaultReturn)
2581 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2582 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2584 else if (status == NSAlertAlternateReturn)
2586 /* User chose to cancel the scan */
2587 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2591 /* 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 */
2592 cancelScanDecrypt = 0;
2593 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2599 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2601 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2605 if (cancelScanDecrypt == 0)
2607 /* we actually pass the scan off to libhb here */
2608 /* If there is no title number passed to scan, we use "0"
2609 * which causes the default behavior of a full source scan
2615 if (scanTitleNum > 0)
2617 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2620 /* We use our advance pref to determine how many previews to scan */
2621 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2622 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2626 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2627 - (void) processNewQueueEncode
2629 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2630 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2631 hb_job_t * job = title->job;
2633 if( !hb_list_count( list ) )
2635 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2638 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2639 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2640 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2641 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2645 * If scanning we need to do some extra setup of the job.
2647 if( job->indepth_scan == 1 )
2652 * When subtitle scan is enabled do a fast pre-scan job
2653 * which will determine which subtitles to enable, if any.
2656 x264opts_tmp = job->x264opts;
2658 job->x264opts = NULL;
2660 job->indepth_scan = 1;
2664 * Add the pre-scan job
2666 hb_add( fQueueEncodeLibhb, job );
2667 job->x264opts = x264opts_tmp;
2671 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2673 job->indepth_scan = 0;
2679 hb_add( fQueueEncodeLibhb, job );
2683 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2684 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2686 hb_add( fQueueEncodeLibhb, job );
2691 job->indepth_scan = 0;
2694 hb_add( fQueueEncodeLibhb, job );
2697 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2698 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2699 /* Lets mark our new encode as 1 or "Encoding" */
2700 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2701 [self saveQueueFileItem];
2703 /* we need to clean up the subtitle tracks after the job(s) have been set */
2704 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2706 for(ii = 0; ii < num_subtitle_tracks; ii++)
2708 hb_subtitle_t * subtitle;
2709 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2712 hb_list_rem(job->list_subtitle, subtitle);
2716 /* We should be all setup so let 'er rip */
2721 #pragma mark Queue Item Editing
2723 /* Rescans the chosen queue item back into the main window */
2724 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2726 fqueueEditRescanItemNum = selectedQueueItem;
2727 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2728 applyQueueToScan = YES;
2729 /* Set the browsedSourceDisplayName for showNewScan */
2730 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2731 [self performScan:scanPath scanTitleNum:scanTitleNum];
2735 /* We use this method after a queue item rescan for edit.
2736 * it largely mirrors -selectPreset in terms of structure.
2737 * Assumes that a queue item has been reloaded into the main window.
2739 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2741 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2742 hb_job_t * job = fTitle->job;
2745 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2747 /* Set title number and chapters */
2748 /* since the queue only scans a single title, its already been selected in showNewScan
2749 so do not try to reset it here. However if we do decide to do full source scans on
2750 a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2751 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2753 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2754 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2757 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2758 [self formatPopUpChanged:nil];
2760 /* Chapter Markers*/
2761 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2762 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2763 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2764 /* Mux mp4 with http optimization */
2765 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2768 /* We set the advanced opt string here if applicable*/
2769 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2770 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2772 /* Lets run through the following functions to get variables set there */
2773 [self videoEncoderPopUpChanged:nil];
2774 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2775 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2776 [self calculateBitrate:nil];
2779 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2781 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2782 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2783 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2784 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2785 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2786 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2787 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2788 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2790 /* For the quality slider we need to convert the old percent's to the new rf scales */
2791 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2792 [fVidQualitySlider setFloatValue:rf];
2797 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2798 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2800 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2804 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2805 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2809 [self videoMatrixChanged:nil];
2811 /* Video framerate */
2812 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2813 detected framerate in the fVidRatePopUp so we use index 0*/
2814 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2816 [fVidRatePopUp selectItemAtIndex: 0];
2820 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2823 /* 2 Pass Encoding */
2824 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2825 [self twoPassCheckboxChanged:nil];
2826 /* Turbo 1st pass for 2 Pass Encoding */
2827 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2832 /* Now lets add our new tracks to the audio list here */
2833 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2835 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2836 [self audioTrackPopUpChanged: fAudLang1PopUp];
2837 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2838 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2840 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2842 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2843 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2845 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2846 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2850 [fAudLang1PopUp selectItemAtIndex: 0];
2851 [self audioTrackPopUpChanged: fAudLang1PopUp];
2853 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2855 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2856 [self audioTrackPopUpChanged: fAudLang2PopUp];
2857 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2858 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2860 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2862 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2863 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2865 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2866 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2870 [fAudLang2PopUp selectItemAtIndex: 0];
2871 [self audioTrackPopUpChanged: fAudLang2PopUp];
2873 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2875 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2876 [self audioTrackPopUpChanged: fAudLang3PopUp];
2877 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2878 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2880 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2882 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2883 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2885 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2886 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2890 [fAudLang3PopUp selectItemAtIndex: 0];
2891 [self audioTrackPopUpChanged: fAudLang3PopUp];
2893 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2895 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2896 [self audioTrackPopUpChanged: fAudLang4PopUp];
2897 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2898 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2900 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2902 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2903 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2905 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2906 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2910 [fAudLang4PopUp selectItemAtIndex: 0];
2911 [self audioTrackPopUpChanged: fAudLang4PopUp];
2915 /* Crashy crashy right now, working on it */
2916 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2917 [fSubtitlesTable reloadData];
2918 /* Picture Settings */
2920 /* If Cropping is set to custom, then recall all four crop values from
2921 when the preset was created and apply them */
2922 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2924 [fPictureController setAutoCrop:NO];
2926 /* Here we use the custom crop values saved at the time the preset was saved */
2927 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2928 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2929 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2930 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2933 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2935 [fPictureController setAutoCrop:YES];
2936 /* Here we use the auto crop values determined right after scan */
2937 job->crop[0] = AutoCropTop;
2938 job->crop[1] = AutoCropBottom;
2939 job->crop[2] = AutoCropLeft;
2940 job->crop[3] = AutoCropRight;
2944 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2946 /* we check to make sure the presets width/height does not exceed the sources width/height */
2947 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2949 /* if so, then we use the sources height and width to avoid scaling up */
2950 //job->width = fTitle->width;
2951 //job->height = fTitle->height;
2952 [self revertPictureSizeToMax:nil];
2954 else // source width/height is >= the preset height/width
2956 /* we can go ahead and use the presets values for height and width */
2957 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2958 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2960 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2961 if (job->keep_ratio == 1)
2963 hb_fix_aspect( job, HB_KEEP_WIDTH );
2964 if( job->height > fTitle->height )
2966 job->height = fTitle->height;
2967 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2970 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2971 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2975 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2976 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2977 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2980 [fPictureController setUseDecomb:1];
2981 [fPictureController setDecomb:0];
2982 [fPictureController setDeinterlace:0];
2983 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2985 /* we are using decomb */
2987 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2989 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2991 /* if we are using "Custom" in the decomb setting, also set the custom string*/
2992 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
2994 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
3000 /* We are using Deinterlace */
3002 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3004 [fPictureController setUseDecomb:0];
3005 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3006 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3007 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3009 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
3016 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3018 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3019 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3020 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3022 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
3027 [fPictureController setDetelecine:0];
3031 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3033 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3034 /* if we are using "Custom" in the denoise setting, also set the custom string*/
3035 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3037 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
3042 [fPictureController setDenoise:0];
3046 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3048 /* if its a one, then its the old on/off deblock, set on to 5*/
3049 [fPictureController setDeblock:5];
3053 /* use the settings intValue */
3054 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3057 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3059 [fPictureController setGrayscale:1];
3063 [fPictureController setGrayscale:0];
3066 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3067 [fPictureController SetTitle:fTitle];
3068 [self calculatePictureSizing:nil];
3070 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3071 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3072 //[queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3073 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3075 /* Deselect the currently selected Preset if there is one*/
3076 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3077 //[self selectPreset:nil];
3079 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3080 /* Change UI to show "Custom" settings are being used */
3081 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3083 curUserPresetChosenNum = nil;
3087 /* Deselect the currently selected Preset if there is one*/
3088 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3089 /* Change UI to show "Custom" settings are being used */
3090 [fPresetSelectedDisplay setStringValue: @"Custom"];
3092 //curUserPresetChosenNum = nil;
3095 /* We need to set this bool back to NO, in case the user wants to do a scan */
3096 //applyQueueToScan = NO;
3098 /* Not that source is loaded and settings applied, delete the queue item from the queue */
3099 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3100 [self removeQueueFileItem:fqueueEditRescanItemNum];
3106 #pragma mark Live Preview
3107 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3108 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3111 - (void) prepareJobForPreview
3113 hb_list_t * list = hb_get_titles( fHandle );
3114 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3115 [fSrcTitlePopUp indexOfSelectedItem] );
3116 hb_job_t * job = title->job;
3117 hb_audio_config_t * audio;
3118 /* set job->angle for libdvdnav */
3119 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3120 /* Chapter selection */
3121 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3122 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3124 /* Format (Muxer) and Video Encoder */
3125 job->mux = [[fDstFormatPopUp selectedItem] tag];
3126 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3128 job->chapter_markers = 0;
3130 if( job->vcodec & HB_VCODEC_X264 )
3133 /* Below Sends x264 options to the core library if x264 is selected*/
3134 /* Lets use this as per Nyx, Thanks Nyx!*/
3135 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3136 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3137 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3142 /* Video settings */
3143 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3144 * and detelecine is on, so we handle that in the logic below
3147 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3149 /* a specific framerate has been chosen */
3150 job->vrate = 27000000;
3151 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3152 /* We are not same as source so we set job->cfr to 1
3153 * to enable constant frame rate since user has specified
3154 * a specific framerate*/
3155 if ([fFrameratePfrCheck state] == 1)
3166 /* We are same as source (variable) */
3167 job->vrate = title->rate;
3168 job->vrate_base = title->rate_base;
3169 /* We are same as source so we set job->cfr to 0
3170 * to enable true same as source framerate */
3172 /* If we are same as source and we have detelecine on, we need to turn on
3175 if ([fPictureController detelecine] == 1)
3181 switch( [fVidQualityMatrix selectedRow] )
3185 Bitrate should already have been calculated and displayed
3186 in fVidBitrateField, so let's just use it */
3188 job->vquality = -1.0;
3189 job->vbitrate = [fVidBitrateField intValue];
3192 job->vquality = [fVidQualityRFField floatValue];
3197 /* Subtitle settings */
3198 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3205 bool one_burned = FALSE;
3208 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3210 while (tempObject = [enumerator nextObject])
3213 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3214 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3215 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3216 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3218 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3219 * we want to ignore it for display as well as encoding.
3223 /* if i is 0, then we are in the first item of the subtitles which we need to
3224 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3225 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3228 /* if we are on the first track and using "Foreign Audio Search" */
3229 if (i == 0 && subtitle == 1)
3231 /* NOTE: Currently foreign language search is borked for preview.
3232 * Commented out but left in for initial commit. */
3235 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3237 job->indepth_scan = 1;
3241 job->select_subtitle_config.dest = PASSTHRUSUB;
3245 job->select_subtitle_config.dest = RENDERSUB;
3248 job->select_subtitle_config.force = force;
3249 job->select_subtitle_config.default_track = def;
3254 /* for the actual source tracks, we must subtract the non source entries so
3255 * that the menu index matches the source subtitle_list index for convenience */
3258 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3259 * Foreign Language Search is 1) so subtract 2 */
3260 subtitle = subtitle - 2;
3264 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3267 subtitle = subtitle - 1;
3270 /* We are setting a source subtitle so access the source subtitle info */
3271 hb_subtitle_t * subt;
3273 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3275 /* if we are getting the subtitles from an external srt file */
3276 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3278 hb_subtitle_config_t sub_config;
3280 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3282 /* we need to srncpy file path and char code */
3283 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3284 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3286 sub_config.force = 0;
3287 sub_config.dest = PASSTHRUSUB;
3288 sub_config.default_track = def;
3290 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3295 hb_subtitle_config_t sub_config = subt->config;
3297 if ( !burned && subt->format == PICTURESUB )
3299 sub_config.dest = PASSTHRUSUB;
3301 else if ( burned && subt->format == PICTURESUB )
3303 // Only allow one subtitle to be burned into the video
3308 sub_config.force = force;
3309 sub_config.default_track = def;
3310 hb_subtitle_add( job, &sub_config, subtitle );
3320 [subtitlesArray autorelease];
3323 /* Audio tracks and mixdowns */
3324 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3325 int audiotrack_count = hb_list_count(job->list_audio);
3326 for( int i = 0; i < audiotrack_count;i++)
3328 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3329 hb_list_rem(job->list_audio, temp_audio);
3331 /* Now lets add our new tracks to the audio list here */
3332 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3334 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3335 hb_audio_config_init(audio);
3336 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3337 /* We go ahead and assign values to our audio->out.<properties> */
3338 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3339 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3340 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3341 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3342 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3343 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3345 hb_audio_add( job, audio );
3348 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3350 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3351 hb_audio_config_init(audio);
3352 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3353 /* We go ahead and assign values to our audio->out.<properties> */
3354 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3355 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3356 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3357 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3358 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3359 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3361 hb_audio_add( job, audio );
3366 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3368 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3369 hb_audio_config_init(audio);
3370 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3371 /* We go ahead and assign values to our audio->out.<properties> */
3372 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3373 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3374 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3375 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3376 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3377 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3379 hb_audio_add( job, audio );
3384 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3386 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3387 hb_audio_config_init(audio);
3388 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3389 /* We go ahead and assign values to our audio->out.<properties> */
3390 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3391 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3392 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3393 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3394 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3395 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3397 hb_audio_add( job, audio );
3406 /* Though Grayscale is not really a filter, per se
3407 * we put it here since its in the filters panel
3410 if ([fPictureController grayscale])
3419 /* Initialize the filters list */
3420 job->filters = hb_list_init();
3422 /* Now lets call the filters if applicable.
3423 * The order of the filters is critical
3427 hb_filter_detelecine.settings = NULL;
3428 if ([fPictureController detelecine] == 1)
3430 /* use a custom detelecine string */
3431 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3432 hb_list_add( job->filters, &hb_filter_detelecine );
3434 if ([fPictureController detelecine] == 2)
3437 hb_list_add( job->filters, &hb_filter_detelecine );
3442 if ([fPictureController useDecomb] == 1)
3445 /* we add the custom string if present */
3446 hb_filter_decomb.settings = NULL;
3447 if ([fPictureController decomb] == 1)
3449 /* use a custom decomb string */
3450 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3451 hb_list_add( job->filters, &hb_filter_decomb );
3453 if ([fPictureController decomb] == 2)
3455 /* Run old deinterlacer fd by default */
3456 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3457 hb_list_add( job->filters, &hb_filter_decomb );
3464 if ([fPictureController deinterlace] == 1)
3466 /* we add the custom string if present */
3467 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3468 hb_list_add( job->filters, &hb_filter_deinterlace );
3470 else if ([fPictureController deinterlace] == 2)
3472 /* Run old deinterlacer fd by default */
3473 hb_filter_deinterlace.settings = "-1";
3474 hb_list_add( job->filters, &hb_filter_deinterlace );
3476 else if ([fPictureController deinterlace] == 3)
3478 /* Yadif mode 0 (without spatial deinterlacing.) */
3479 hb_filter_deinterlace.settings = "2";
3480 hb_list_add( job->filters, &hb_filter_deinterlace );
3482 else if ([fPictureController deinterlace] == 4)
3484 /* Yadif (with spatial deinterlacing) */
3485 hb_filter_deinterlace.settings = "0";
3486 hb_list_add( job->filters, &hb_filter_deinterlace );
3492 if ([fPictureController denoise] == 1) // custom in popup
3494 /* we add the custom string if present */
3495 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3496 hb_list_add( job->filters, &hb_filter_denoise );
3498 else if ([fPictureController denoise] == 2) // Weak in popup
3500 hb_filter_denoise.settings = "2:1:2:3";
3501 hb_list_add( job->filters, &hb_filter_denoise );
3503 else if ([fPictureController denoise] == 3) // Medium in popup
3505 hb_filter_denoise.settings = "3:2:2:3";
3506 hb_list_add( job->filters, &hb_filter_denoise );
3508 else if ([fPictureController denoise] == 4) // Strong in popup
3510 hb_filter_denoise.settings = "7:7:5:5";
3511 hb_list_add( job->filters, &hb_filter_denoise );
3515 /* Deblock (uses pp7 default) */
3516 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3517 * the macgui's purposes a value of 0 actually means to not even use the filter
3518 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3520 if ([fPictureController deblock] != 0)
3522 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3523 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3524 hb_list_add( job->filters, &hb_filter_deblock );
3531 #pragma mark Job Handling
3537 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3538 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3539 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3540 hb_job_t * job = title->job;
3541 hb_audio_config_t * audio;
3542 /* Title Angle for dvdnav */
3543 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3545 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3547 /* Chapter selection */
3548 [self writeToActivityLog: "Start / Stop set to chapters"];
3549 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3550 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3552 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3554 /* we are pts based start / stop */
3555 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3557 /* Point A to Point B. Time to time in seconds.*/
3558 /* get the start seconds from the start seconds field */
3559 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3560 job->pts_to_start = start_seconds * 90000LL;
3561 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3562 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3563 job->pts_to_stop = stop_seconds * 90000LL;
3566 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3568 /* we are frame based start / stop */
3569 [self writeToActivityLog: "Start / Stop set to frames ..."];
3571 /* Point A to Point B. Frame to frame */
3572 /* get the start frame from the start frame field */
3573 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3574 job->frame_to_start = start_frame;
3575 /* get the frame to stop on from the end frame field */
3576 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3577 job->frame_to_stop = stop_frame;
3584 /* Format (Muxer) and Video Encoder */
3585 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3586 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3589 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3590 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3592 job->largeFileSize = 1;
3596 job->largeFileSize = 0;
3598 /* We set http optimized mp4 here */
3599 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3601 job->mp4_optimize = 1;
3605 job->mp4_optimize = 0;
3609 /* We set the chapter marker extraction here based on the format being
3610 mpeg4 or mkv and the checkbox being checked */
3611 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3613 job->chapter_markers = 1;
3615 /* now lets get our saved chapter names out the array in the queue file
3616 * and insert them back into the title chapter list. We have it here,
3617 * because unless we are inserting chapter markers there is no need to
3618 * spend the overhead of iterating through the chapter names array imo
3619 * Also, note that if for some reason we don't apply chapter names, the
3620 * chapters just come out 001, 002, etc. etc.
3623 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3625 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3627 while (tempObject = [enumerator nextObject])
3629 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3630 if( chapter != NULL )
3632 strncpy( chapter->title, [tempObject UTF8String], 1023);
3633 chapter->title[1023] = '\0';
3640 job->chapter_markers = 0;
3643 if( job->vcodec & HB_VCODEC_X264 )
3645 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3655 /* Below Sends x264 options to the core library if x264 is selected*/
3656 /* Lets use this as per Nyx, Thanks Nyx!*/
3657 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3658 /* Turbo first pass if two pass and Turbo First pass is selected */
3659 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3661 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3662 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3663 /* append the "Turbo" string variable to the existing opts string.
3664 Note: the "Turbo" string must be appended, not prepended to work properly*/
3665 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3666 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3670 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3676 /* Picture Size Settings */
3677 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3678 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3680 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3681 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3682 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3683 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3685 /* insert our custom values here for capuj */
3686 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3687 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3689 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3691 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3692 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3694 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3695 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3698 /* Here we use the crop values saved at the time the preset was saved */
3699 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3700 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3701 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3702 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3704 /* Video settings */
3707 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3708 * and detelecine is on, so we handle that in the logic below
3711 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3713 /* a specific framerate has been chosen */
3714 job->vrate = 27000000;
3715 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3716 /* We are not same as source so we set job->cfr to 1
3717 * to enable constant frame rate since user has specified
3718 * a specific framerate*/
3720 if ([[queueToApply objectForKey:@"VideoFrameratePFR"] intValue] == 1)
3731 /* We are same as source (variable) */
3732 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3733 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3734 /* We are same as source so we set job->cfr to 0
3735 * to enable true same as source framerate */
3737 /* If we are same as source and we have detelecine on, we need to turn on
3740 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3746 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3749 Bitrate should already have been calculated and displayed
3750 in fVidBitrateField, so let's just use it same as abr*/
3751 job->vquality = -1.0;
3752 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3754 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3756 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3761 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3766 #pragma mark Process Subtitles to libhb
3768 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3769 * which means that we need to account for the offset of non source language settings in from
3770 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3771 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3772 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3773 * to the source tracks position in title->list_subtitle.
3780 bool one_burned = FALSE;
3783 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3785 while (tempObject = [enumerator nextObject])
3788 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3789 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3790 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3791 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3793 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3794 * we want to ignore it for display as well as encoding.
3798 /* if i is 0, then we are in the first item of the subtitles which we need to
3799 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3800 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3803 /* if we are on the first track and using "Foreign Audio Search" */
3804 if (i == 0 && subtitle == 1)
3806 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3808 job->indepth_scan = 1;
3812 job->select_subtitle_config.dest = PASSTHRUSUB;
3816 job->select_subtitle_config.dest = RENDERSUB;
3819 job->select_subtitle_config.force = force;
3820 job->select_subtitle_config.default_track = def;
3825 /* for the actual source tracks, we must subtract the non source entries so
3826 * that the menu index matches the source subtitle_list index for convenience */
3829 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3830 * Foreign Language Search is 1) so subtract 2 */
3831 subtitle = subtitle - 2;
3835 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3838 subtitle = subtitle - 1;
3841 /* We are setting a source subtitle so access the source subtitle info */
3842 hb_subtitle_t * subt;
3844 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3846 /* if we are getting the subtitles from an external srt file */
3847 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3849 hb_subtitle_config_t sub_config;
3851 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3853 /* we need to srncpy file name and codeset */
3854 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3855 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3857 sub_config.force = 0;
3858 sub_config.dest = PASSTHRUSUB;
3859 sub_config.default_track = def;
3861 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3867 hb_subtitle_config_t sub_config = subt->config;
3869 if ( !burned && subt->format == PICTURESUB )
3871 sub_config.dest = PASSTHRUSUB;
3873 else if ( burned && subt->format == PICTURESUB )
3875 // Only allow one subtitle to be burned into the video
3880 sub_config.force = force;
3881 sub_config.default_track = def;
3882 hb_subtitle_add( job, &sub_config, subtitle );
3893 /* Audio tracks and mixdowns */
3894 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3895 int audiotrack_count = hb_list_count(job->list_audio);
3896 for( int i = 0; i < audiotrack_count;i++)
3898 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3899 hb_list_rem(job->list_audio, temp_audio);
3901 /* Now lets add our new tracks to the audio list here */
3902 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3904 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3905 hb_audio_config_init(audio);
3906 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3907 /* We go ahead and assign values to our audio->out.<properties> */
3908 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3909 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3910 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3911 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3912 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3913 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3915 hb_audio_add( job, audio );
3918 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3921 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3922 hb_audio_config_init(audio);
3923 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3924 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3925 /* We go ahead and assign values to our audio->out.<properties> */
3926 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3927 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3928 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3929 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3930 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3931 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3933 hb_audio_add( job, audio );
3937 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3939 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3940 hb_audio_config_init(audio);
3941 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3942 /* We go ahead and assign values to our audio->out.<properties> */
3943 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3944 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3945 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3946 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3947 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3948 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3950 hb_audio_add( job, audio );
3954 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3956 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3957 hb_audio_config_init(audio);
3958 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3959 /* We go ahead and assign values to our audio->out.<properties> */
3960 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3961 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3962 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3963 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3964 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3965 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3967 hb_audio_add( job, audio );
3973 job->filters = hb_list_init();
3975 /* Now lets call the filters if applicable.
3976 * The order of the filters is critical
3979 hb_filter_detelecine.settings = NULL;
3980 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3982 /* use a custom detelecine string */
3983 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3984 hb_list_add( job->filters, &hb_filter_detelecine );
3986 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3988 /* Use libhb's default values */
3989 hb_list_add( job->filters, &hb_filter_detelecine );
3992 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3995 /* we add the custom string if present */
3996 hb_filter_decomb.settings = NULL;
3997 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3999 /* use a custom decomb string */
4000 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4001 hb_list_add( job->filters, &hb_filter_decomb );
4003 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4005 /* Use libhb default */
4006 hb_list_add( job->filters, &hb_filter_decomb );
4014 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4016 /* we add the custom string if present */
4017 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4018 hb_list_add( job->filters, &hb_filter_deinterlace );
4020 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4022 /* Run old deinterlacer fd by default */
4023 hb_filter_deinterlace.settings = "-1";
4024 hb_list_add( job->filters, &hb_filter_deinterlace );
4026 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4028 /* Yadif mode 0 (without spatial deinterlacing.) */
4029 hb_filter_deinterlace.settings = "2";
4030 hb_list_add( job->filters, &hb_filter_deinterlace );
4032 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4034 /* Yadif (with spatial deinterlacing) */
4035 hb_filter_deinterlace.settings = "0";
4036 hb_list_add( job->filters, &hb_filter_deinterlace );
4042 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4044 /* we add the custom string if present */
4045 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4046 hb_list_add( job->filters, &hb_filter_denoise );
4048 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4050 hb_filter_denoise.settings = "2:1:2:3";
4051 hb_list_add( job->filters, &hb_filter_denoise );
4053 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4055 hb_filter_denoise.settings = "3:2:2:3";
4056 hb_list_add( job->filters, &hb_filter_denoise );
4058 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4060 hb_filter_denoise.settings = "7:7:5:5";
4061 hb_list_add( job->filters, &hb_filter_denoise );
4065 /* Deblock (uses pp7 default) */
4066 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
4067 * the macgui's purposes a value of 0 actually means to not even use the filter
4068 * current hb_filter_deblock.settings valid ranges are from 5 - 15
4070 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4072 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4073 hb_list_add( job->filters, &hb_filter_deblock );
4075 [self writeToActivityLog: "prepareJob exiting"];
4080 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4082 - (IBAction) addToQueue: (id) sender
4084 /* We get the destination directory from the destination field here */
4085 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4086 /* We check for a valid destination here */
4087 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4089 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4096 BOOL fileExistsInQueue;
4097 fileExistsInQueue = NO;
4099 /* We check for and existing file here */
4100 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4105 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4107 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4109 while (tempObject = [enumerator nextObject])
4111 NSDictionary *thisQueueDict = tempObject;
4112 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4114 fileExistsInQueue = YES;
4120 if(fileExists == YES)
4122 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4123 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4124 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4125 NULL, NULL, [NSString stringWithFormat:
4126 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4127 [fDstFile2Field stringValue]] );
4129 else if (fileExistsInQueue == YES)
4131 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4132 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4133 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4134 NULL, NULL, [NSString stringWithFormat:
4135 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4136 [fDstFile2Field stringValue]] );
4140 [self doAddToQueue];
4144 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4145 the user if they want to overwrite an exiting movie file.
4147 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4148 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4150 if( returnCode == NSAlertAlternateReturn )
4151 [self doAddToQueue];
4154 - (void) doAddToQueue
4156 [self addQueueFileItem ];
4161 /* Rip: puts up an alert before ultimately calling doRip
4163 - (IBAction) Rip: (id) sender
4165 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4166 /* Rip or Cancel ? */
4168 hb_get_state2( fQueueEncodeLibhb, &s );
4170 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4172 [self Cancel: sender];
4176 /* We check to see if we need to warn the user that the computer will go to sleep
4177 or shut down when encoding is finished */
4178 [self remindUserOfSleepOrShutdown];
4180 // If there are pending jobs in the queue, then this is a rip the queue
4181 if (fPendingCount > 0)
4183 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4184 /* here lets start the queue with the first pending item */
4185 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4190 // Before adding jobs to the queue, check for a valid destination.
4192 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4193 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4195 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4199 /* We check for duplicate name here */
4200 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4202 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4203 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4204 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4205 NULL, NULL, [NSString stringWithFormat:
4206 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4207 [fDstFile2Field stringValue]] );
4209 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4213 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4214 otherwise, just rip the queue */
4215 if(fPendingCount == 0)
4217 [self doAddToQueue];
4220 /* go right to processing the new queue encode */
4221 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4222 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4227 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4228 want to overwrite an exiting movie file.
4230 - (void) overWriteAlertDone: (NSWindow *) sheet
4231 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4233 if( returnCode == NSAlertAlternateReturn )
4235 /* if there are no jobs in the queue, then add this one to the queue and rip
4236 otherwise, just rip the queue */
4237 if( fPendingCount == 0 )
4239 [self doAddToQueue];
4242 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4243 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4244 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4249 - (void) remindUserOfSleepOrShutdown
4251 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4253 /*Warn that computer will sleep after encoding*/
4256 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);
4257 [NSApp requestUserAttention:NSCriticalRequest];
4258 if ( reminduser == NSAlertAlternateReturn )
4260 [self showPreferencesWindow:nil];
4263 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4265 /*Warn that computer will shut down after encoding*/
4268 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);
4269 [NSApp requestUserAttention:NSCriticalRequest];
4270 if ( reminduser == NSAlertAlternateReturn )
4272 [self showPreferencesWindow:nil];
4281 /* Let libhb do the job */
4282 hb_start( fQueueEncodeLibhb );
4283 /*set the fEncodeState State */
4288 //------------------------------------------------------------------------------------
4289 // Displays an alert asking user if the want to cancel encoding of current job.
4290 // Cancel: returns immediately after posting the alert. Later, when the user
4291 // acknowledges the alert, doCancelCurrentJob is called.
4292 //------------------------------------------------------------------------------------
4293 - (IBAction)Cancel: (id)sender
4295 if (!fQueueController) return;
4297 hb_pause( fQueueEncodeLibhb );
4298 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4300 // Which window to attach the sheet to?
4301 NSWindow * docWindow;
4302 if ([sender respondsToSelector: @selector(window)])
4303 docWindow = [sender window];
4305 docWindow = fWindow;
4307 NSBeginCriticalAlertSheet(
4309 NSLocalizedString(@"Continue Encoding", nil),
4310 NSLocalizedString(@"Cancel Current and Stop", nil),
4311 NSLocalizedString(@"Cancel Current and Continue", nil),
4313 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4314 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4316 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4319 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4321 hb_resume( fQueueEncodeLibhb );
4322 if (returnCode == NSAlertOtherReturn)
4324 [self doCancelCurrentJob]; // <- this also stops libhb
4326 if (returnCode == NSAlertAlternateReturn)
4328 [self doCancelCurrentJobAndStop];
4332 //------------------------------------------------------------------------------------
4333 // Cancels and deletes the current job and stops libhb from processing the remaining
4335 //------------------------------------------------------------------------------------
4336 - (void) doCancelCurrentJob
4338 // Stop the current job. hb_stop will only cancel the current pass and then set
4339 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4340 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4341 // remaining passes of the job and then start the queue back up if there are any
4345 hb_stop( fQueueEncodeLibhb );
4347 // Delete all remaining jobs since libhb doesn't do this on its own.
4349 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4350 hb_rem( fQueueEncodeLibhb, job );
4352 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4354 // now that we've stopped the currently encoding job, lets mark it as cancelled
4355 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4356 // and as always, save it in the queue .plist...
4357 /* We save all of the Queue data here */
4358 [self saveQueueFileItem];
4360 // ... and see if there are more items left in our queue
4361 int queueItems = [QueueFileArray count];
4362 /* If we still have more items in our queue, lets go to the next one */
4363 /* Check to see if there are any more pending items in the queue */
4364 int newQueueItemIndex = [self getNextPendingQueueIndex];
4365 /* If we still have more pending items in our queue, lets go to the next one */
4366 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
4368 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
4369 currentQueueEncodeIndex = newQueueItemIndex;
4370 /* 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 */
4371 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
4372 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
4373 [self saveQueueFileItem];
4374 /* now we can go ahead and scan the new pending queue item */
4375 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4380 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
4384 - (void) doCancelCurrentJobAndStop
4386 hb_stop( fQueueEncodeLibhb );
4388 // Delete all remaining jobs since libhb doesn't do this on its own.
4390 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4391 hb_rem( fQueueEncodeLibhb, job );
4394 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4396 // now that we've stopped the currently encoding job, lets mark it as cancelled
4397 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4398 // and as always, save it in the queue .plist...
4399 /* We save all of the Queue data here */
4400 [self saveQueueFileItem];
4401 // so now lets move to
4402 currentQueueEncodeIndex++ ;
4403 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4405 - (IBAction) Pause: (id) sender
4408 hb_get_state2( fQueueEncodeLibhb, &s );
4410 if( s.state == HB_STATE_PAUSED )
4412 hb_resume( fQueueEncodeLibhb );
4416 hb_pause( fQueueEncodeLibhb );
4421 #pragma mark GUI Controls Changed Methods
4423 - (IBAction) titlePopUpChanged: (id) sender
4425 hb_list_t * list = hb_get_titles( fHandle );
4426 hb_title_t * title = (hb_title_t*)
4427 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4429 /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4430 if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4432 /* we set the default name according to the new title->name */
4433 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4434 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4435 [NSString stringWithUTF8String: title->name],
4436 [[fDstFile2Field stringValue] pathExtension]]];
4438 /* Change the source to read out the parent folder also */
4439 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4442 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4443 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4444 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4445 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4446 /* 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 */
4447 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4448 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4449 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4451 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4452 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4454 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4455 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4456 [browsedSourceDisplayName stringByDeletingPathExtension],
4458 [[fDstFile2Field stringValue] pathExtension]]];
4460 /* Update encode start / stop variables */
4464 /* Update chapter popups */
4465 [fSrcChapterStartPopUp removeAllItems];
4466 [fSrcChapterEndPopUp removeAllItems];
4467 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4469 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4470 stringWithFormat: @"%d", i + 1]];
4471 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4472 stringWithFormat: @"%d", i + 1]];
4475 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4476 [fSrcChapterEndPopUp selectItemAtIndex:
4477 hb_list_count( title->list_chapter ) - 1];
4478 [self chapterPopUpChanged:nil];
4480 /* if using dvd nav, show the angle widget */
4481 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4483 [fSrcAngleLabel setHidden:NO];
4484 [fSrcAnglePopUp setHidden:NO];
4486 [fSrcAnglePopUp removeAllItems];
4487 for( int i = 0; i < title->angle_count; i++ )
4489 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4491 [fSrcAnglePopUp selectItemAtIndex: 0];
4495 [fSrcAngleLabel setHidden:YES];
4496 [fSrcAnglePopUp setHidden:YES];
4499 /* Start Get and set the initial pic size for display */
4500 hb_job_t * job = title->job;
4503 /* Set Auto Crop to on upon selecting a new title */
4504 [fPictureController setAutoCrop:YES];
4506 /* We get the originial output picture width and height and put them
4507 in variables for use with some presets later on */
4508 PicOrigOutputWidth = job->width;
4509 PicOrigOutputHeight = job->height;
4510 AutoCropTop = job->crop[0];
4511 AutoCropBottom = job->crop[1];
4512 AutoCropLeft = job->crop[2];
4513 AutoCropRight = job->crop[3];
4515 /* Reset the new title in fPictureController && fPreviewController*/
4516 [fPictureController SetTitle:title];
4519 /* Update Subtitle Table */
4520 [fSubtitlesDelegate resetWithTitle:title];
4521 [fSubtitlesTable reloadData];
4524 /* Update chapter table */
4525 [fChapterTitlesDelegate resetWithTitle:title];
4526 [fChapterTable reloadData];
4528 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4529 int audiotrack_count = hb_list_count(job->list_audio);
4530 for( int i = 0; i < audiotrack_count;i++)
4532 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4533 hb_list_rem(job->list_audio, temp_audio);
4536 /* Update audio popups */
4537 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4538 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4539 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4540 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4541 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4542 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4543 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4544 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4545 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4546 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4548 /* changing the title may have changed the audio channels on offer, */
4549 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4550 [self audioTrackPopUpChanged: fAudLang1PopUp];
4551 [self audioTrackPopUpChanged: fAudLang2PopUp];
4552 [self audioTrackPopUpChanged: fAudLang3PopUp];
4553 [self audioTrackPopUpChanged: fAudLang4PopUp];
4555 [fVidRatePopUp selectItemAtIndex: 0];
4557 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4558 [self calculatePictureSizing:nil];
4560 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4561 [self selectPreset:nil];
4564 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4566 if( [fEncodeStartStopPopUp isEnabled] )
4568 /* We are chapters */
4569 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4571 [fSrcChapterStartPopUp setHidden: NO];
4572 [fSrcChapterEndPopUp setHidden: NO];
4574 [fSrcTimeStartEncodingField setHidden: YES];
4575 [fSrcTimeEndEncodingField setHidden: YES];
4577 [fSrcFrameStartEncodingField setHidden: YES];
4578 [fSrcFrameEndEncodingField setHidden: YES];
4580 [self chapterPopUpChanged:nil];
4582 /* We are time based (seconds) */
4583 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4585 [fSrcChapterStartPopUp setHidden: YES];
4586 [fSrcChapterEndPopUp setHidden: YES];
4588 [fSrcTimeStartEncodingField setHidden: NO];
4589 [fSrcTimeEndEncodingField setHidden: NO];
4591 [fSrcFrameStartEncodingField setHidden: YES];
4592 [fSrcFrameEndEncodingField setHidden: YES];
4594 [self startEndSecValueChanged:nil];
4596 /* We are frame based */
4597 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4599 [fSrcChapterStartPopUp setHidden: YES];
4600 [fSrcChapterEndPopUp setHidden: YES];
4602 [fSrcTimeStartEncodingField setHidden: YES];
4603 [fSrcTimeEndEncodingField setHidden: YES];
4605 [fSrcFrameStartEncodingField setHidden: NO];
4606 [fSrcFrameEndEncodingField setHidden: NO];
4608 [self startEndFrameValueChanged:nil];
4613 - (IBAction) chapterPopUpChanged: (id) sender
4616 /* If start chapter popup is greater than end chapter popup,
4617 we set the end chapter popup to the same as start chapter popup */
4618 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4620 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4624 hb_list_t * list = hb_get_titles( fHandle );
4625 hb_title_t * title = (hb_title_t *)
4626 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4628 hb_chapter_t * chapter;
4629 int64_t duration = 0;
4630 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4631 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4633 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4634 duration += chapter->duration;
4637 duration /= 90000; /* pts -> seconds */
4638 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4639 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4642 [self calculateBitrate: sender];
4644 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4646 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4647 [fCreateChapterMarkers setEnabled: NO];
4648 [fCreateChapterMarkers setState: NSOffState];
4652 [fCreateChapterMarkers setEnabled: YES];
4656 - (IBAction) startEndSecValueChanged: (id) sender
4659 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4660 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4661 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4664 //[self calculateBitrate: sender];
4668 - (IBAction) startEndFrameValueChanged: (id) sender
4670 hb_list_t * list = hb_get_titles( fHandle );
4671 hb_title_t * title = (hb_title_t*)
4672 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4674 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4675 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4676 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4679 //[self calculateBitrate: sender];
4683 - (IBAction) formatPopUpChanged: (id) sender
4685 NSString * string = [fDstFile2Field stringValue];
4686 int format = [fDstFormatPopUp indexOfSelectedItem];
4688 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4689 [fDstMp4LargeFileCheck setHidden: YES];
4690 [fDstMp4HttpOptFileCheck setHidden: YES];
4691 [fDstMp4iPodFileCheck setHidden: YES];
4693 /* Update the Video Codec PopUp */
4694 /* lets get the tag of the currently selected item first so we might reset it later */
4695 int selectedVidEncoderTag;
4696 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4698 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4699 [fVidEncoderPopUp removeAllItems];
4700 NSMenuItem *menuItem;
4701 /* These video encoders are available to all of our current muxers, so lets list them once here */
4702 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4703 [menuItem setTag: HB_VCODEC_FFMPEG];
4708 /*Get Default MP4 File Extension*/
4709 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4717 /* Add additional video encoders here */
4718 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4719 [menuItem setTag: HB_VCODEC_X264];
4720 /* We show the mp4 option checkboxes here since we are mp4 */
4721 [fCreateChapterMarkers setEnabled: YES];
4722 [fDstMp4LargeFileCheck setHidden: NO];
4723 [fDstMp4HttpOptFileCheck setHidden: NO];
4724 [fDstMp4iPodFileCheck setHidden: NO];
4729 /* Add additional video encoders here */
4730 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4731 [menuItem setTag: HB_VCODEC_X264];
4732 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4733 [menuItem setTag: HB_VCODEC_THEORA];
4734 /* We enable the create chapters checkbox here */
4735 [fCreateChapterMarkers setEnabled: YES];
4740 /* tell fSubtitlesDelegate we have a new video container */
4742 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4743 [fSubtitlesTable reloadData];
4744 /* if we have a previously selected vid encoder tag, then try to select it */
4745 if (selectedVidEncoderTag)
4747 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4751 [fVidEncoderPopUp selectItemAtIndex: 0];
4754 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4755 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4756 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4757 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4760 [self autoSetM4vExtension: sender];
4762 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4764 if( SuccessfulScan )
4766 /* Add/replace to the correct extension */
4767 [self audioTrackPopUpChanged: fAudLang1PopUp];
4768 [self audioTrackPopUpChanged: fAudLang2PopUp];
4769 [self audioTrackPopUpChanged: fAudLang3PopUp];
4770 [self audioTrackPopUpChanged: fAudLang4PopUp];
4772 if( [fVidEncoderPopUp selectedItem] == nil )
4775 [fVidEncoderPopUp selectItemAtIndex:0];
4776 [self videoEncoderPopUpChanged:nil];
4778 /* changing the format may mean that we can / can't offer mono or 6ch, */
4779 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4781 /* We call the method to properly enable/disable turbo 2 pass */
4782 [self twoPassCheckboxChanged: sender];
4783 /* We call method method to change UI to reflect whether a preset is used or not*/
4786 [self customSettingUsed: sender];
4789 - (IBAction) autoSetM4vExtension: (id) sender
4791 if ( [fDstFormatPopUp indexOfSelectedItem] )
4794 NSString * extension = @"mp4";
4796 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4797 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4798 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4799 [fCreateChapterMarkers state] == NSOnState ||
4800 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4805 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4808 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4809 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4812 /* Method to determine if we should change the UI
4813 To reflect whether or not a Preset is being used or if
4814 the user is using "Custom" settings by determining the sender*/
4815 - (IBAction) customSettingUsed: (id) sender
4817 if ([sender stringValue])
4819 /* Deselect the currently selected Preset if there is one*/
4820 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4821 /* Change UI to show "Custom" settings are being used */
4822 [fPresetSelectedDisplay setStringValue: @"Custom"];
4824 curUserPresetChosenNum = nil;
4826 [self calculateBitrate:nil];
4831 #pragma mark - Video
4833 - (IBAction) videoEncoderPopUpChanged: (id) sender
4835 hb_job_t * job = fTitle->job;
4836 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4838 [fAdvancedOptions setHidden:YES];
4839 /* If we are using x264 then show the x264 advanced panel*/
4840 if (videoEncoder == HB_VCODEC_X264)
4842 [fAdvancedOptions setHidden:NO];
4843 [self autoSetM4vExtension: sender];
4846 if (videoEncoder == HB_VCODEC_FFMPEG)
4848 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4849 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4850 anything other than MP4.
4852 [fDstMp4iPodFileCheck setEnabled: NO];
4853 [fDstMp4iPodFileCheck setState: NSOffState];
4857 [fDstMp4iPodFileCheck setEnabled: YES];
4859 [self setupQualitySlider];
4860 [self calculatePictureSizing: sender];
4861 [self twoPassCheckboxChanged: sender];
4865 - (IBAction) twoPassCheckboxChanged: (id) sender
4867 /* check to see if x264 is chosen */
4868 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4870 if( [fVidTwoPassCheck state] == NSOnState)
4872 [fVidTurboPassCheck setHidden: NO];
4876 [fVidTurboPassCheck setHidden: YES];
4877 [fVidTurboPassCheck setState: NSOffState];
4879 /* Make sure Two Pass is checked if Turbo is checked */
4880 if( [fVidTurboPassCheck state] == NSOnState)
4882 [fVidTwoPassCheck setState: NSOnState];
4887 [fVidTurboPassCheck setHidden: YES];
4888 [fVidTurboPassCheck setState: NSOffState];
4891 /* We call method method to change UI to reflect whether a preset is used or not*/
4892 [self customSettingUsed: sender];
4895 - (IBAction ) videoFrameRateChanged: (id) sender
4897 /* Hide and set the PFR Checkbox to OFF if we are set to Same as Source */
4898 if ([fVidRatePopUp indexOfSelectedItem] == 0)
4900 [fFrameratePfrCheck setHidden:YES];
4901 [fFrameratePfrCheck setState:0];
4905 [fFrameratePfrCheck setHidden:NO];
4908 /* We call method method to calculatePictureSizing to error check detelecine*/
4909 [self calculatePictureSizing: sender];
4911 /* We call method method to change UI to reflect whether a preset is used or not*/
4912 [self customSettingUsed: sender];
4914 - (IBAction) videoMatrixChanged: (id) sender;
4916 bool target, bitrate, quality;
4918 target = bitrate = quality = false;
4919 if( [fVidQualityMatrix isEnabled] )
4921 switch( [fVidQualityMatrix selectedRow] )
4934 [fVidTargetSizeField setEnabled: target];
4935 [fVidBitrateField setEnabled: bitrate];
4936 [fVidQualitySlider setEnabled: quality];
4937 [fVidQualityRFField setEnabled: quality];
4938 [fVidQualityRFLabel setEnabled: quality];
4939 [fVidTwoPassCheck setEnabled: !quality &&
4940 [fVidQualityMatrix isEnabled]];
4943 [fVidTwoPassCheck setState: NSOffState];
4944 [fVidTurboPassCheck setHidden: YES];
4945 [fVidTurboPassCheck setState: NSOffState];
4948 [self qualitySliderChanged: sender];
4949 [self calculateBitrate: sender];
4950 [self customSettingUsed: sender];
4953 /* Use this method to setup the quality slider for cq/rf values depending on
4954 * the video encoder selected.
4956 - (void) setupQualitySlider
4958 /* Get the current slider maxValue to check for a change in slider scale later
4959 * so that we can choose a new similar value on the new slider scale */
4960 float previousMaxValue = [fVidQualitySlider maxValue];
4961 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4962 NSString * qpRFLabelString = @"QP:";
4964 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4966 [fVidQualitySlider setMinValue:0.0];
4967 [fVidQualitySlider setMaxValue:51.0];
4968 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4969 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4970 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4971 qpRFLabelString = @"RF:";
4974 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
4976 [fVidQualitySlider setMinValue:1.0];
4977 [fVidQualitySlider setMaxValue:31.0];
4978 [fVidQualitySlider setNumberOfTickMarks:31];
4981 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4983 [fVidQualitySlider setMinValue:0.0];
4984 [fVidQualitySlider setMaxValue:63.0];
4985 [fVidQualitySlider setNumberOfTickMarks:64];
4987 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4989 /* check to see if we have changed slider scales */
4990 if (previousMaxValue != [fVidQualitySlider maxValue])
4992 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4993 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4994 [fVidQualitySlider setFloatValue:rf];
4997 [self qualitySliderChanged:nil];
5000 - (IBAction) qualitySliderChanged: (id) sender
5002 /* Our constant quality slider is in a range based
5003 * on each encoders qp/rf values. The range depends
5004 * on the encoder. Also, the range is inverse of quality
5005 * for all of the encoders *except* for theora
5006 * (ie. as the "quality" goes up, the cq or rf value
5007 * actually goes down). Since the IB sliders always set
5008 * their max value at the right end of the slider, we
5009 * will calculate the inverse, so as the slider floatValue
5010 * goes up, we will show the inverse in the rf field
5011 * so, the floatValue at the right for x264 would be 51
5012 * and our rf field needs to show 0 and vice versa.
5015 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5016 /* If the encoder is theora, use the float, otherwise use the inverse float*/
5017 //float sliderRfToPercent;
5018 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5020 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
5024 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5026 [self customSettingUsed: sender];
5029 - (void) controlTextDidChange: (NSNotification *) notification
5031 [self calculateBitrate:nil];
5034 - (IBAction) calculateBitrate: (id) sender
5036 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5041 hb_list_t * list = hb_get_titles( fHandle );
5042 hb_title_t * title = (hb_title_t *) hb_list_item( list,
5043 [fSrcTitlePopUp indexOfSelectedItem] );
5044 hb_job_t * job = title->job;
5045 hb_audio_config_t * audio;
5046 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
5047 * Target Size Field, we also need the job info for the Muxer, the Chapters
5048 * as well as all of the audio track info.
5049 * This used to be accomplished by simply calling prepareJob here, however
5050 * since the resilient queue sets the queue array values instead of the job
5051 * values directly, we duplicate the old prepareJob code here for the variables
5054 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5055 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
5056 job->mux = [[fDstFormatPopUp selectedItem] tag];
5058 /* Audio goes here */
5059 int audiotrack_count = hb_list_count(job->list_audio);
5060 for( int i = 0; i < audiotrack_count;i++)
5062 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5063 hb_list_rem(job->list_audio, temp_audio);
5065 /* Now we need our audio info here for each track if applicable */
5066 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5068 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5069 hb_audio_config_init(audio);
5070 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5071 /* We go ahead and assign values to our audio->out.<properties> */
5072 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5073 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5074 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5075 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5076 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5077 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5079 hb_audio_add( job, audio );
5082 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5084 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5085 hb_audio_config_init(audio);
5086 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5087 /* We go ahead and assign values to our audio->out.<properties> */
5088 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5089 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5090 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5091 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5092 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5093 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5095 hb_audio_add( job, audio );
5100 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5102 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5103 hb_audio_config_init(audio);
5104 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5105 /* We go ahead and assign values to our audio->out.<properties> */
5106 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5107 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5108 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5109 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5110 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5111 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5113 hb_audio_add( job, audio );
5118 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5120 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5121 hb_audio_config_init(audio);
5122 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5123 /* We go ahead and assign values to our audio->out.<properties> */
5124 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5125 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5126 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5127 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5128 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5129 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5131 hb_audio_add( job, audio );
5136 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5140 #pragma mark - Picture
5142 /* lets set the picture size back to the max from right after title scan
5143 Lets use an IBAction here as down the road we could always use a checkbox
5144 in the gui to easily take the user back to max. Remember, the compiler
5145 resolves IBActions down to -(void) during compile anyway */
5146 - (IBAction) revertPictureSizeToMax: (id) sender
5148 hb_job_t * job = fTitle->job;
5149 /* Here we apply the title source and height */
5150 job->width = fTitle->width;
5151 job->height = fTitle->height;
5153 [self calculatePictureSizing: sender];
5154 /* We call method to change UI to reflect whether a preset is used or not*/
5155 [self customSettingUsed: sender];
5159 * Registers changes made in the Picture Settings Window.
5162 - (void)pictureSettingsDidChange
5164 [self calculatePictureSizing:nil];
5167 /* Get and Display Current Pic Settings in main window */
5168 - (IBAction) calculatePictureSizing: (id) sender
5170 if (fTitle->job->anamorphic.mode > 0)
5172 fTitle->job->keep_ratio = 0;
5175 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5177 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5181 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5183 NSString *picCropping;
5184 /* Set the display field for crop as per boolean */
5185 if (![fPictureController autoCrop])
5187 picCropping = @"Custom";
5191 picCropping = @"Auto";
5193 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]]];
5195 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5197 NSString *videoFilters;
5200 if ([fPictureController detelecine] == 2)
5202 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5204 else if ([fPictureController detelecine] == 1)
5206 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5210 if ([fPictureController useDecomb] == 1)
5213 if ([fPictureController decomb] == 2)
5215 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5217 else if ([fPictureController decomb] == 1)
5219 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5225 if ([fPictureController deinterlace] > 0)
5227 fTitle->job->deinterlace = 1;
5231 fTitle->job->deinterlace = 0;
5234 if ([fPictureController deinterlace] == 2)
5236 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5238 else if ([fPictureController deinterlace] == 3)
5240 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5242 else if ([fPictureController deinterlace] == 4)
5244 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5246 else if ([fPictureController deinterlace] == 1)
5248 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5254 if ([fPictureController denoise] == 2)
5256 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5258 else if ([fPictureController denoise] == 3)
5260 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5262 else if ([fPictureController denoise] == 4)
5264 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5266 else if ([fPictureController denoise] == 1)
5268 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5272 if ([fPictureController deblock] > 0)
5274 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5278 if ([fPictureController grayscale])
5280 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5282 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5284 //[fPictureController reloadStillPreview];
5289 #pragma mark - Audio and Subtitles
5290 - (IBAction) audioCodecsPopUpChanged: (id) sender
5293 NSPopUpButton * audiotrackPopUp;
5294 NSPopUpButton * sampleratePopUp;
5295 NSPopUpButton * bitratePopUp;
5296 NSPopUpButton * audiocodecPopUp;
5297 if (sender == fAudTrack1CodecPopUp)
5299 audiotrackPopUp = fAudLang1PopUp;
5300 audiocodecPopUp = fAudTrack1CodecPopUp;
5301 sampleratePopUp = fAudTrack1RatePopUp;
5302 bitratePopUp = fAudTrack1BitratePopUp;
5304 else if (sender == fAudTrack2CodecPopUp)
5306 audiotrackPopUp = fAudLang2PopUp;
5307 audiocodecPopUp = fAudTrack2CodecPopUp;
5308 sampleratePopUp = fAudTrack2RatePopUp;
5309 bitratePopUp = fAudTrack2BitratePopUp;
5311 else if (sender == fAudTrack3CodecPopUp)
5313 audiotrackPopUp = fAudLang3PopUp;
5314 audiocodecPopUp = fAudTrack3CodecPopUp;
5315 sampleratePopUp = fAudTrack3RatePopUp;
5316 bitratePopUp = fAudTrack3BitratePopUp;
5320 audiotrackPopUp = fAudLang4PopUp;
5321 audiocodecPopUp = fAudTrack4CodecPopUp;
5322 sampleratePopUp = fAudTrack4RatePopUp;
5323 bitratePopUp = fAudTrack4BitratePopUp;
5326 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5327 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5328 [self audioTrackPopUpChanged: audiotrackPopUp];
5332 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5334 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5335 * the settings of the source audio for that track. We leave the samplerate and bitrate
5336 * to audiotrackMixdownChanged
5339 /* We will first verify that a lower track number has been selected before enabling each track
5340 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5343 /* If the source has no audio then disable audio track 1 */
5344 if (hb_list_count( fTitle->list_audio ) == 0)
5346 [fAudLang1PopUp selectItemAtIndex:0];
5349 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5351 [fAudLang2PopUp setEnabled: NO];
5352 [fAudLang2PopUp selectItemAtIndex: 0];
5356 [fAudLang2PopUp setEnabled: YES];
5359 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5361 [fAudLang3PopUp setEnabled: NO];
5362 [fAudLang3PopUp selectItemAtIndex: 0];
5366 [fAudLang3PopUp setEnabled: YES];
5368 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5370 [fAudLang4PopUp setEnabled: NO];
5371 [fAudLang4PopUp selectItemAtIndex: 0];
5375 [fAudLang4PopUp setEnabled: YES];
5377 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5378 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5379 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5380 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5381 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5382 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5383 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5384 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5386 [fAudTrack1CodecPopUp removeAllItems];
5387 [fAudTrack1MixPopUp removeAllItems];
5388 [fAudTrack1RatePopUp removeAllItems];
5389 [fAudTrack1BitratePopUp removeAllItems];
5390 [fAudTrack1DrcSlider setFloatValue: 0.00];
5391 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5393 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5395 [fAudTrack1RatePopUp setEnabled: NO];
5396 [fAudTrack1BitratePopUp setEnabled: NO];
5397 [fAudTrack1DrcSlider setEnabled: NO];
5398 [fAudTrack1DrcField setEnabled: NO];
5401 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5402 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5403 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5404 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5405 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5406 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5407 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5408 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5410 [fAudTrack2CodecPopUp removeAllItems];
5411 [fAudTrack2MixPopUp removeAllItems];
5412 [fAudTrack2RatePopUp removeAllItems];
5413 [fAudTrack2BitratePopUp removeAllItems];
5414 [fAudTrack2DrcSlider setFloatValue: 0.00];
5415 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5417 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5419 [fAudTrack2RatePopUp setEnabled: NO];
5420 [fAudTrack2BitratePopUp setEnabled: NO];
5421 [fAudTrack2DrcSlider setEnabled: NO];
5422 [fAudTrack2DrcField setEnabled: NO];
5425 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5426 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5427 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5428 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5429 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5430 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5431 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5432 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5434 [fAudTrack3CodecPopUp removeAllItems];
5435 [fAudTrack3MixPopUp removeAllItems];
5436 [fAudTrack3RatePopUp removeAllItems];
5437 [fAudTrack3BitratePopUp removeAllItems];
5438 [fAudTrack3DrcSlider setFloatValue: 0.00];
5439 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5441 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5443 [fAudTrack3RatePopUp setEnabled: NO];
5444 [fAudTrack3BitratePopUp setEnabled: NO];
5445 [fAudTrack3DrcSlider setEnabled: NO];
5446 [fAudTrack3DrcField setEnabled: NO];
5449 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5450 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5451 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5452 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5453 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5454 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5455 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5456 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5458 [fAudTrack4CodecPopUp removeAllItems];
5459 [fAudTrack4MixPopUp removeAllItems];
5460 [fAudTrack4RatePopUp removeAllItems];
5461 [fAudTrack4BitratePopUp removeAllItems];
5462 [fAudTrack4DrcSlider setFloatValue: 0.00];
5463 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5465 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5467 [fAudTrack4RatePopUp setEnabled: NO];
5468 [fAudTrack4BitratePopUp setEnabled: NO];
5469 [fAudTrack4DrcSlider setEnabled: NO];
5470 [fAudTrack4DrcField setEnabled: NO];
5475 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5478 hb_list_t * list = hb_get_titles( fHandle );
5479 hb_title_t * title = (hb_title_t*)
5480 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5482 hb_audio_config_t * audio;
5484 [sender removeAllItems];
5485 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5486 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5488 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5489 [[sender menu] addItemWithTitle:
5490 [NSString stringWithUTF8String: audio->lang.description]
5491 action: NULL keyEquivalent: @""];
5493 [sender selectItemAtIndex: 0];
5497 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5500 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5501 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5502 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5503 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5504 if (hb_list_count( fTitle->list_audio ) != 0)
5506 if (searchPrefixString)
5509 for( int i = 0; i < [sender numberOfItems]; i++ )
5511 /* Try to find the desired search string */
5512 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5514 [sender selectItemAtIndex: i];
5518 /* couldn't find the string, so select the requested "search string not found" item */
5519 /* index of 0 means select the "none" item */
5520 /* index of 1 means select the first audio track */
5521 [sender selectItemAtIndex: selectIndexIfNotFound];
5525 /* if no search string is provided, then select the selectIndexIfNotFound item */
5526 [sender selectItemAtIndex: selectIndexIfNotFound];
5531 [sender selectItemAtIndex: 0];
5535 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5537 int format = [fDstFormatPopUp indexOfSelectedItem];
5539 /* setup pointers to the appropriate popups for the correct track */
5540 NSPopUpButton * audiocodecPopUp;
5541 NSPopUpButton * audiotrackPopUp;
5542 if (sender == fAudTrack1CodecPopUp)
5544 audiotrackPopUp = fAudLang1PopUp;
5545 audiocodecPopUp = fAudTrack1CodecPopUp;
5547 else if (sender == fAudTrack2CodecPopUp)
5549 audiotrackPopUp = fAudLang2PopUp;
5550 audiocodecPopUp = fAudTrack2CodecPopUp;
5552 else if (sender == fAudTrack3CodecPopUp)
5554 audiotrackPopUp = fAudLang3PopUp;
5555 audiocodecPopUp = fAudTrack3CodecPopUp;
5559 audiotrackPopUp = fAudLang4PopUp;
5560 audiocodecPopUp = fAudTrack4CodecPopUp;
5563 [audiocodecPopUp removeAllItems];
5564 /* Make sure "None" isnt selected in the source track */
5565 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5567 [audiocodecPopUp setEnabled:YES];
5568 NSMenuItem *menuItem;
5569 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5575 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5576 [menuItem setTag: HB_ACODEC_CA_AAC];
5578 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5579 [menuItem setTag: HB_ACODEC_FAAC];
5581 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5582 [menuItem setTag: HB_ACODEC_LAME];
5584 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5585 [menuItem setTag: HB_ACODEC_AC3];
5591 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5592 [menuItem setTag: HB_ACODEC_CA_AAC];
5594 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5595 [menuItem setTag: HB_ACODEC_FAAC];
5597 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5598 [menuItem setTag: HB_ACODEC_AC3];
5600 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5601 [menuItem setTag: HB_ACODEC_DCA];
5603 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5604 [menuItem setTag: HB_ACODEC_LAME];
5606 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5607 [menuItem setTag: HB_ACODEC_VORBIS];
5610 [audiocodecPopUp selectItemAtIndex:0];
5614 [audiocodecPopUp setEnabled:NO];
5618 - (IBAction) audioTrackPopUpChanged: (id) sender
5620 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5621 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5624 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5627 /* make sure we have a selected title before continuing */
5628 if (fTitle == NULL) return;
5629 /* make sure we have a source audio track before continuing */
5630 if (hb_list_count( fTitle->list_audio ) == 0)
5632 [sender selectItemAtIndex:0];
5635 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5636 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5638 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5640 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5642 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5644 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5646 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5648 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5650 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5652 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5655 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5656 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5658 sender = fAudLang1PopUp;
5660 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5662 sender = fAudLang2PopUp;
5664 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5666 sender = fAudLang3PopUp;
5668 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5670 sender = fAudLang4PopUp;
5673 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5674 NSPopUpButton * mixdownPopUp;
5675 NSPopUpButton * audiocodecPopUp;
5676 NSPopUpButton * sampleratePopUp;
5677 NSPopUpButton * bitratePopUp;
5678 if (sender == fAudLang1PopUp)
5680 mixdownPopUp = fAudTrack1MixPopUp;
5681 audiocodecPopUp = fAudTrack1CodecPopUp;
5682 sampleratePopUp = fAudTrack1RatePopUp;
5683 bitratePopUp = fAudTrack1BitratePopUp;
5685 else if (sender == fAudLang2PopUp)
5687 mixdownPopUp = fAudTrack2MixPopUp;
5688 audiocodecPopUp = fAudTrack2CodecPopUp;
5689 sampleratePopUp = fAudTrack2RatePopUp;
5690 bitratePopUp = fAudTrack2BitratePopUp;
5692 else if (sender == fAudLang3PopUp)
5694 mixdownPopUp = fAudTrack3MixPopUp;
5695 audiocodecPopUp = fAudTrack3CodecPopUp;
5696 sampleratePopUp = fAudTrack3RatePopUp;
5697 bitratePopUp = fAudTrack3BitratePopUp;
5701 mixdownPopUp = fAudTrack4MixPopUp;
5702 audiocodecPopUp = fAudTrack4CodecPopUp;
5703 sampleratePopUp = fAudTrack4RatePopUp;
5704 bitratePopUp = fAudTrack4BitratePopUp;
5707 /* get the index of the selected audio Track*/
5708 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5710 /* pointer for the hb_audio_s struct we will use later on */
5711 hb_audio_config_t * audio;
5714 /* check if the audio mixdown controls need their enabled state changing */
5715 [self setEnabledStateOfAudioMixdownControls:nil];
5717 if (thisAudioIndex != -1)
5721 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5723 /* actually manipulate the proper mixdowns here */
5724 /* delete the previous audio mixdown options */
5725 [mixdownPopUp removeAllItems];
5727 acodec = [[audiocodecPopUp selectedItem] tag];
5732 /* find out if our selected output audio codec supports 6ch */
5733 int audioCodecsSupport6Ch = (audio->in.codec && acodec != HB_ACODEC_LAME);
5735 /* check for AC-3 passthru */
5736 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5739 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5740 [NSString stringWithUTF8String: "AC3 Passthru"]
5741 action: NULL keyEquivalent: @""];
5742 [menuItem setTag: HB_ACODEC_AC3];
5744 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5746 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5747 [NSString stringWithUTF8String: "DTS Passthru"]
5748 action: NULL keyEquivalent: @""];
5749 [menuItem setTag: HB_ACODEC_DCA];
5754 /* add the appropriate audio mixdown menuitems to the popupbutton */
5755 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5756 so that we can reference the mixdown later */
5758 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5759 int minMixdownUsed = 0;
5760 int maxMixdownUsed = 0;
5762 /* get the input channel layout without any lfe channels */
5763 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5765 /* add a mono option */
5766 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5767 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5768 action: NULL keyEquivalent: @""];
5769 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5770 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5771 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5773 /* do we want to add a stereo option? */
5774 /* offer stereo if we have a stereo-or-better source */
5775 if (layout >= HB_INPUT_CH_LAYOUT_STEREO)
5777 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5778 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5779 action: NULL keyEquivalent: @""];
5780 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5781 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5782 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5785 /* do we want to add a dolby surround (DPL1) option? */
5786 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5788 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5789 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5790 action: NULL keyEquivalent: @""];
5791 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5792 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5793 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5796 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5797 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5799 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5800 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5801 action: NULL keyEquivalent: @""];
5802 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5803 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5804 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5807 /* do we want to add a 6-channel discrete option? */
5808 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5810 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5811 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5812 action: NULL keyEquivalent: @""];
5813 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5814 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5815 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5818 /* do we want to add an AC-3 passthrough option? */
5819 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5821 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5822 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5823 action: NULL keyEquivalent: @""];
5824 [menuItem setTag: HB_ACODEC_AC3];
5825 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5826 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5829 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5830 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5832 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5833 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5834 action: NULL keyEquivalent: @""];
5835 [menuItem setTag: HB_ACODEC_DCA];
5836 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5837 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5840 /* auto-select the best mixdown based on our saved mixdown preference */
5842 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5843 /* ultimately this should be a prefs option */
5846 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5847 if (mixdownToUse > 0)
5849 useMixdown = mixdownToUse;
5853 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5856 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5857 if (useMixdown > maxMixdownUsed)
5859 useMixdown = maxMixdownUsed;
5862 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5863 if (useMixdown < minMixdownUsed)
5865 useMixdown = minMixdownUsed;
5868 /* select the (possibly-amended) preferred mixdown */
5869 [mixdownPopUp selectItemWithTag: useMixdown];
5872 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5873 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5875 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5877 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5880 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5881 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5883 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5885 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5888 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5889 [self audioTrackMixdownChanged: mixdownPopUp];
5893 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5895 [self autoSetM4vExtension: sender];
5899 - (IBAction) audioTrackMixdownChanged: (id) sender
5903 /* setup pointers to all of the other audio track controls
5904 * we will need later
5906 NSPopUpButton * mixdownPopUp;
5907 NSPopUpButton * sampleratePopUp;
5908 NSPopUpButton * bitratePopUp;
5909 NSPopUpButton * audiocodecPopUp;
5910 NSPopUpButton * audiotrackPopUp;
5911 NSSlider * drcSlider;
5912 NSTextField * drcField;
5913 if (sender == fAudTrack1MixPopUp)
5915 audiotrackPopUp = fAudLang1PopUp;
5916 audiocodecPopUp = fAudTrack1CodecPopUp;
5917 mixdownPopUp = fAudTrack1MixPopUp;
5918 sampleratePopUp = fAudTrack1RatePopUp;
5919 bitratePopUp = fAudTrack1BitratePopUp;
5920 drcSlider = fAudTrack1DrcSlider;
5921 drcField = fAudTrack1DrcField;
5923 else if (sender == fAudTrack2MixPopUp)
5925 audiotrackPopUp = fAudLang2PopUp;
5926 audiocodecPopUp = fAudTrack2CodecPopUp;
5927 mixdownPopUp = fAudTrack2MixPopUp;
5928 sampleratePopUp = fAudTrack2RatePopUp;
5929 bitratePopUp = fAudTrack2BitratePopUp;
5930 drcSlider = fAudTrack2DrcSlider;
5931 drcField = fAudTrack2DrcField;
5933 else if (sender == fAudTrack3MixPopUp)
5935 audiotrackPopUp = fAudLang3PopUp;
5936 audiocodecPopUp = fAudTrack3CodecPopUp;
5937 mixdownPopUp = fAudTrack3MixPopUp;
5938 sampleratePopUp = fAudTrack3RatePopUp;
5939 bitratePopUp = fAudTrack3BitratePopUp;
5940 drcSlider = fAudTrack3DrcSlider;
5941 drcField = fAudTrack3DrcField;
5945 audiotrackPopUp = fAudLang4PopUp;
5946 audiocodecPopUp = fAudTrack4CodecPopUp;
5947 mixdownPopUp = fAudTrack4MixPopUp;
5948 sampleratePopUp = fAudTrack4RatePopUp;
5949 bitratePopUp = fAudTrack4BitratePopUp;
5950 drcSlider = fAudTrack4DrcSlider;
5951 drcField = fAudTrack4DrcField;
5953 acodec = [[audiocodecPopUp selectedItem] tag];
5954 /* storage variable for the min and max bitrate allowed for this codec */
5960 case HB_ACODEC_FAAC:
5961 /* check if we have a 6ch discrete conversion in either audio track */
5962 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5964 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5966 /* If either mixdown popup includes 6-channel discrete, then allow up to 768 kbps */
5972 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5974 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5979 case HB_ACODEC_CA_AAC:
5980 /* check if we have a 6ch discrete conversion in either audio track */
5981 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5994 case HB_ACODEC_LAME:
5995 /* Lame is happy using our min bitrate of 32 kbps */
5997 /* Lame won't encode if the bitrate is higher than 320 kbps */
6001 case HB_ACODEC_VORBIS:
6002 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6004 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6006 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6012 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6014 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6020 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6026 /* make sure we have a selected title before continuing */
6027 if (fTitle == NULL || hb_list_count( fTitle->list_audio ) == 0) return;
6028 /* get the audio so we can find out what input rates are*/
6029 hb_audio_config_t * audio;
6030 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6031 int inputbitrate = audio->in.bitrate / 1000;
6032 int inputsamplerate = audio->in.samplerate;
6034 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6036 [bitratePopUp removeAllItems];
6038 for( int i = 0; i < hb_audio_bitrates_count; i++ )
6040 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6042 /* add a new menuitem for this bitrate */
6043 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6044 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6045 action: NULL keyEquivalent: @""];
6046 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6047 [menuItem setTag: hb_audio_bitrates[i].rate];
6051 /* select the default bitrate (but use 384 for 6-ch AAC) */
6052 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6054 [bitratePopUp selectItemWithTag: 384];
6058 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6061 /* populate and set the sample rate popup */
6062 /* Audio samplerate */
6063 [sampleratePopUp removeAllItems];
6064 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6065 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6066 [menuItem setTag: inputsamplerate];
6068 for( int i = 0; i < hb_audio_rates_count; i++ )
6070 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6071 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6072 action: NULL keyEquivalent: @""];
6073 [menuItem setTag: hb_audio_rates[i].rate];
6075 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6076 * and there is no compelling reason to use anything else as default, though the users default
6077 * preset will likely override any setting chosen here.
6079 [sampleratePopUp selectItemWithTag: inputsamplerate];
6082 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6083 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6084 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6086 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6089 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6090 [bitratePopUp removeAllItems];
6091 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6092 [NSString stringWithFormat:@"%d", inputbitrate]
6093 action: NULL keyEquivalent: @""];
6094 [menuItem setTag: inputbitrate];
6095 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6096 [bitratePopUp setEnabled: NO];
6097 [sampleratePopUp setEnabled: NO];
6099 [drcSlider setFloatValue: 0.00];
6100 [self audioDRCSliderChanged: drcSlider];
6101 [drcSlider setEnabled: NO];
6102 [drcField setEnabled: NO];
6106 [sampleratePopUp setEnabled: YES];
6107 [bitratePopUp setEnabled: YES];
6108 [drcSlider setEnabled: YES];
6109 [drcField setEnabled: YES];
6111 [self calculateBitrate:nil];
6114 - (IBAction) audioDRCSliderChanged: (id) sender
6116 NSSlider * drcSlider;
6117 NSTextField * drcField;
6118 if (sender == fAudTrack1DrcSlider)
6120 drcSlider = fAudTrack1DrcSlider;
6121 drcField = fAudTrack1DrcField;
6123 else if (sender == fAudTrack2DrcSlider)
6125 drcSlider = fAudTrack2DrcSlider;
6126 drcField = fAudTrack2DrcField;
6128 else if (sender == fAudTrack3DrcSlider)
6130 drcSlider = fAudTrack3DrcSlider;
6131 drcField = fAudTrack3DrcField;
6135 drcSlider = fAudTrack4DrcSlider;
6136 drcField = fAudTrack4DrcField;
6139 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6140 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6142 [drcSlider setFloatValue:1.0];
6146 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6147 /* For now, do not call this until we have an intelligent way to determine audio track selections
6148 * compared to presets
6150 //[self customSettingUsed: sender];
6155 - (IBAction) browseImportSrtFile: (id) sender
6158 NSOpenPanel * panel;
6160 panel = [NSOpenPanel openPanel];
6161 [panel setAllowsMultipleSelection: NO];
6162 [panel setCanChooseFiles: YES];
6163 [panel setCanChooseDirectories: NO ];
6164 NSString * sourceDirectory;
6165 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6167 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6171 sourceDirectory = @"~/Desktop";
6172 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6174 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6175 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6176 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6177 modalForWindow: fWindow modalDelegate: self
6178 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6179 contextInfo: sender];
6182 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6183 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6185 if( returnCode == NSOKButton )
6187 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6188 NSString *importSrtFilePath = [sheet filename];
6189 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6191 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6192 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6194 [fSubtitlesTable reloadData];
6200 #pragma mark Open New Windows
6202 - (IBAction) openHomepage: (id) sender
6204 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6205 URLWithString:@"http://handbrake.fr/"]];
6208 - (IBAction) openForums: (id) sender
6210 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6211 URLWithString:@"http://handbrake.fr/forum/"]];
6213 - (IBAction) openUserGuide: (id) sender
6215 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6216 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6220 * Shows debug output window.
6222 - (IBAction)showDebugOutputPanel:(id)sender
6224 [outputPanel showOutputPanel:sender];
6228 * Shows preferences window.
6230 - (IBAction) showPreferencesWindow: (id) sender
6232 NSWindow * window = [fPreferencesController window];
6233 if (![window isVisible])
6236 [window makeKeyAndOrderFront: nil];
6240 * Shows queue window.
6242 - (IBAction) showQueueWindow:(id)sender
6244 [fQueueController showQueueWindow:sender];
6248 - (IBAction) toggleDrawer:(id)sender {
6249 [fPresetDrawer toggle:self];
6253 * Shows Picture Settings Window.
6256 - (IBAction) showPicturePanel: (id) sender
6258 [fPictureController showPictureWindow:sender];
6261 - (void) picturePanelFullScreen
6263 [fPictureController setToFullScreenMode];
6266 - (void) picturePanelWindowed
6268 [fPictureController setToWindowedMode];
6271 - (IBAction) showPreviewWindow: (id) sender
6273 [fPictureController showPreviewWindow:sender];
6277 #pragma mark Preset Outline View Methods
6278 #pragma mark - Required
6279 /* These are required by the NSOutlineView Datasource Delegate */
6282 /* used to specify the number of levels to show for each item */
6283 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6285 /* currently use no levels to test outline view viability */
6286 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6288 return [UserPresets count];
6292 /* we need to return the count of the array in ChildrenArray for this folder */
6293 NSArray *children = nil;
6294 children = [item objectForKey:@"ChildrenArray"];
6295 if ([children count] > 0)
6297 return [children count];
6306 /* We use this to deterimine children of an item */
6307 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6310 /* we need to return the count of the array in ChildrenArray for this folder */
6311 NSArray *children = nil;
6314 children = UserPresets;
6318 if ([item objectForKey:@"ChildrenArray"])
6320 children = [item objectForKey:@"ChildrenArray"];
6323 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6329 return [children objectAtIndex:index];
6333 // We are only one level deep, so we can't be asked about children
6334 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6338 /* We use this to determine if an item should be expandable */
6339 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6342 /* we need to return the count of the array in ChildrenArray for this folder */
6343 NSArray *children= nil;
6346 children = UserPresets;
6350 if ([item objectForKey:@"ChildrenArray"])
6352 children = [item objectForKey:@"ChildrenArray"];
6356 /* To deterimine if an item should show a disclosure triangle
6357 * we could do it by the children count as so:
6358 * if ([children count] < 1)
6359 * However, lets leave the triangle show even if there are no
6360 * children to help indicate a folder, just like folder in the
6361 * finder can show a disclosure triangle even when empty
6364 /* We need to determine if the item is a folder */
6365 if ([[item objectForKey:@"Folder"] intValue] == 1)
6376 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6378 // Our outline view has no levels, but we can still expand every item. Doing so
6379 // just makes the row taller. See heightOfRowByItem below.
6380 //return ![(HBQueueOutlineView*)outlineView isDragging];
6386 /* Used to tell the outline view which information is to be displayed per item */
6387 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6389 /* We have two columns right now, icon and PresetName */
6391 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6393 return [item objectForKey:@"PresetName"];
6402 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6404 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6406 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6408 return [NSKeyedArchiver archivedDataWithRootObject:item];
6411 #pragma mark - Added Functionality (optional)
6412 /* Use to customize the font and display characteristics of the title cell */
6413 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6415 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6419 NSColor *shadowColor;
6420 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6421 /*check to see if its a selected row */
6422 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6425 fontColor = [NSColor blackColor];
6426 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6430 if ([[item objectForKey:@"Type"] intValue] == 0)
6432 fontColor = [NSColor blueColor];
6434 else // User created preset, use a black font
6436 fontColor = [NSColor blackColor];
6438 /* check to see if its a folder */
6439 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6441 //fontColor = [NSColor greenColor];
6446 /* We use Bold Text for the HB Default */
6447 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6449 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6451 /* We use Bold Text for the User Specified Default */
6452 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6454 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6458 [cell setTextColor:fontColor];
6459 [cell setFont:txtFont];
6464 /* We use this to edit the name field in the outline view */
6465 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6467 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6472 [theRecord setObject:object forKey:@"PresetName"];
6476 [fPresetsOutlineView reloadData];
6477 /* We save all of the preset data here */
6481 /* We use this to provide tooltips for the items in the presets outline view */
6482 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6484 //if ([[tc identifier] isEqualToString:@"PresetName"])
6486 /* initialize the tooltip contents variable */
6488 /* if there is a description for the preset, we show it in the tooltip */
6489 if ([item objectForKey:@"PresetDescription"])
6491 loc_tip = [item objectForKey:@"PresetDescription"];
6496 loc_tip = @"No description available";
6503 #pragma mark Preset Outline View Methods (dragging related)
6506 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6508 // Dragging is only allowed for custom presets.
6509 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6510 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6514 // Don't retain since this is just holding temporaral drag information, and it is
6515 //only used during a drag! We could put this in the pboard actually.
6516 fDraggedNodes = items;
6517 // Provide data for our custom type, and simple NSStrings.
6518 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6520 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6521 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6526 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6529 // Don't allow dropping ONTO an item since they can't really contain any children.
6531 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6532 if (isOnDropTypeProposal)
6533 return NSDragOperationNone;
6535 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6538 index = [fPresetsOutlineView rowForItem: item] + 1;
6542 // Don't allow dropping into the Built In Presets.
6543 if (index < presetCurrentBuiltInCount)
6545 return NSDragOperationNone;
6546 index = MAX (index, presetCurrentBuiltInCount);
6549 [outlineView setDropItem:item dropChildIndex:index];
6550 return NSDragOperationGeneric;
6555 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6557 /* first, lets see if we are dropping into a folder */
6558 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6560 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6561 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6562 [childrenArray addObject:item];
6563 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6564 [childrenArray autorelease];
6566 else // We are not, so we just move the preset into the existing array
6568 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6570 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6571 while (obj = [enumerator nextObject])
6573 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6575 // Successful drop, lets rearrange the view and save it all
6576 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6578 [fPresetsOutlineView reloadData];
6583 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6585 NSUInteger index = [indexSet lastIndex];
6586 NSUInteger aboveInsertIndexCount = 0;
6588 NSUInteger removeIndex;
6590 if (index >= insertIndex)
6592 removeIndex = index + aboveInsertIndexCount;
6593 aboveInsertIndexCount++;
6597 removeIndex = index;
6601 id object = [[array objectAtIndex:removeIndex] retain];
6602 [array removeObjectAtIndex:removeIndex];
6603 [array insertObject:object atIndex:insertIndex];
6606 index = [indexSet indexLessThanIndex:index];
6611 #pragma mark - Functional Preset NSOutlineView Methods
6613 - (IBAction)selectPreset:(id)sender
6616 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6618 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6619 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6621 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6623 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6627 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6631 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6632 [self formatPopUpChanged:nil];
6634 /* Chapter Markers*/
6635 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6636 /* check to see if we have only one chapter */
6637 [self chapterPopUpChanged:nil];
6639 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6640 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6641 /* Mux mp4 with http optimization */
6642 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6645 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6646 /* We set the advanced opt string here if applicable*/
6647 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6649 /* Lets run through the following functions to get variables set there */
6650 [self videoEncoderPopUpChanged:nil];
6651 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6652 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6653 [self calculateBitrate:nil];
6656 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6658 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6659 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6661 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6662 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6663 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6664 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6665 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6666 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6668 /* For the quality slider we need to convert the old percent's to the new rf scales */
6669 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6670 [fVidQualitySlider setFloatValue:rf];
6675 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6676 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6678 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6682 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6683 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6687 [self videoMatrixChanged:nil];
6689 /* Video framerate */
6690 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6691 detected framerate in the fVidRatePopUp so we use index 0*/
6692 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6694 [fVidRatePopUp selectItemAtIndex: 0];
6698 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6701 [fFrameratePfrCheck setState:[[chosenPreset objectForKey:@"VideoFrameratePFR"] intValue]];
6702 [self videoFrameRateChanged:nil];
6704 /* 2 Pass Encoding */
6705 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6706 [self twoPassCheckboxChanged:nil];
6708 /* Turbo 1st pass for 2 Pass Encoding */
6709 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6712 /* First we check to see if we are using the current audio track layout based on AudioList array */
6713 if ([chosenPreset objectForKey:@"AudioList"])
6716 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6717 NSPopUpButton * trackLangPreviousPopUp = nil;
6718 NSPopUpButton * trackLangPopUp = nil;
6719 NSPopUpButton * mixdownPopUp = nil;
6720 NSPopUpButton * audiocodecPopUp = nil;
6721 NSPopUpButton * sampleratePopUp = nil;
6722 NSPopUpButton * bitratePopUp = nil;
6723 NSSlider * drcSlider = nil;
6726 /* Populate the audio widgets based on the contents of the AudioList array */
6728 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6730 while (tempObject = [enumerator nextObject])
6735 trackLangPopUp = fAudLang1PopUp;
6736 mixdownPopUp = fAudTrack1MixPopUp;
6737 audiocodecPopUp = fAudTrack1CodecPopUp;
6738 sampleratePopUp = fAudTrack1RatePopUp;
6739 bitratePopUp = fAudTrack1BitratePopUp;
6740 drcSlider = fAudTrack1DrcSlider;
6744 trackLangPreviousPopUp = fAudLang1PopUp;
6745 trackLangPopUp = fAudLang2PopUp;
6746 mixdownPopUp = fAudTrack2MixPopUp;
6747 audiocodecPopUp = fAudTrack2CodecPopUp;
6748 sampleratePopUp = fAudTrack2RatePopUp;
6749 bitratePopUp = fAudTrack2BitratePopUp;
6750 drcSlider = fAudTrack2DrcSlider;
6754 trackLangPreviousPopUp = fAudLang2PopUp;
6755 trackLangPopUp = fAudLang3PopUp;
6756 mixdownPopUp = fAudTrack3MixPopUp;
6757 audiocodecPopUp = fAudTrack3CodecPopUp;
6758 sampleratePopUp = fAudTrack3RatePopUp;
6759 bitratePopUp = fAudTrack3BitratePopUp;
6760 drcSlider = fAudTrack3DrcSlider;
6764 trackLangPreviousPopUp = fAudLang3PopUp;
6765 trackLangPopUp = fAudLang4PopUp;
6766 mixdownPopUp = fAudTrack4MixPopUp;
6767 audiocodecPopUp = fAudTrack4CodecPopUp;
6768 sampleratePopUp = fAudTrack4RatePopUp;
6769 bitratePopUp = fAudTrack4BitratePopUp;
6770 drcSlider = fAudTrack4DrcSlider;
6774 if ([trackLangPopUp indexOfSelectedItem] == 0)
6778 [trackLangPopUp selectItemAtIndex: 1];
6782 /* if we are greater than track 1, select
6783 * the same track as the previous track */
6784 [trackLangPopUp selectItemAtIndex: [trackLangPreviousPopUp indexOfSelectedItem]];
6787 [self audioTrackPopUpChanged: trackLangPopUp];
6788 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6789 /* check our pref for core audio and use it in place of faac if preset is a built in */
6790 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6791 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6792 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6794 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6797 [self audioTrackPopUpChanged: audiocodecPopUp];
6798 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6799 [self audioTrackMixdownChanged: mixdownPopUp];
6800 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6802 if ([mixdownPopUp selectedItem] == nil)
6804 [self audioTrackPopUpChanged: audiocodecPopUp];
6805 [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6807 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6808 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6809 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6811 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6812 /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6813 *default mixdown bitrate*/
6814 if ([bitratePopUp selectedItem] == nil)
6816 [self audioTrackMixdownChanged: mixdownPopUp];
6819 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6820 [self audioDRCSliderChanged: drcSlider];
6823 /* 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,
6824 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6828 /* 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". */
6829 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6831 hb_audio_config_t * audio;
6832 /* get the audio source audio codec */
6833 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6834 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6835 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6837 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6838 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6840 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6842 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6844 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6846 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6847 [trackLangPopUp selectItemAtIndex: 0];
6848 [self audioTrackPopUpChanged: trackLangPopUp];
6854 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6858 [fAudLang4PopUp selectItemAtIndex: 0];
6859 [self audioTrackPopUpChanged: fAudLang4PopUp];
6863 [fAudLang3PopUp selectItemAtIndex: 0];
6864 [self audioTrackPopUpChanged: fAudLang3PopUp];
6868 [fAudLang2PopUp selectItemAtIndex: 0];
6869 [self audioTrackPopUpChanged: fAudLang2PopUp];
6877 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6879 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6881 [fAudLang1PopUp selectItemAtIndex: 1];
6883 [self audioTrackPopUpChanged: fAudLang1PopUp];
6884 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6885 /* check our pref for core audio and use it in place of faac if preset is built in */
6886 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6887 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6888 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6890 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6893 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6894 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6895 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6897 if ([fAudTrack1MixPopUp selectedItem] == nil)
6899 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6901 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6902 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6903 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6905 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6907 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6908 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6911 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6913 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6915 [fAudLang2PopUp selectItemAtIndex: 1];
6917 [self audioTrackPopUpChanged: fAudLang2PopUp];
6918 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6919 /* check our pref for core audio and use it in place of faac if preset is built in */
6920 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6921 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6922 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6924 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6926 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6927 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6928 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6930 if ([fAudTrack2MixPopUp selectedItem] == nil)
6932 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6934 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6935 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6936 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6938 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6940 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6941 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6943 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6945 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6947 [fAudLang3PopUp selectItemAtIndex: 1];
6949 [self audioTrackPopUpChanged: fAudLang3PopUp];
6950 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6951 /* check our pref for core audio and use it in place of faac if preset is built in */
6952 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6953 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6954 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6956 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6958 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6959 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6960 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6962 if ([fAudTrack3MixPopUp selectedItem] == nil)
6964 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6966 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6967 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6968 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6970 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6972 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6973 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6975 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6977 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6979 [fAudLang4PopUp selectItemAtIndex: 1];
6981 [self audioTrackPopUpChanged: fAudLang4PopUp];
6982 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6983 /* check our pref for core audio and use it in place of faac if preset is built in */
6984 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6985 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6986 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6988 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6990 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6991 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6992 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6994 if ([fAudTrack4MixPopUp selectedItem] == nil)
6996 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6998 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
6999 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7000 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7002 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7004 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7005 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7008 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7010 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7012 [fAudLang2PopUp selectItemAtIndex: 0];
7013 [self audioTrackPopUpChanged: fAudLang2PopUp];
7015 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7017 [fAudLang3PopUp selectItemAtIndex: 0];
7018 [self audioTrackPopUpChanged: fAudLang3PopUp];
7020 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7022 [fAudLang4PopUp selectItemAtIndex: 0];
7023 [self audioTrackPopUpChanged: fAudLang4PopUp];
7028 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7029 /* Forced Subtitles */
7030 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7032 /* Picture Settings */
7033 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7034 * height, width, keep ar, anamorphic and crop settings.
7035 * picture filters are handled separately below.
7037 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
7038 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
7039 * preset completely ignores any picture sizing values in the preset.
7041 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
7043 hb_job_t * job = fTitle->job;
7045 /* If Cropping is set to custom, then recall all four crop values from
7046 when the preset was created and apply them */
7047 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
7049 [fPictureController setAutoCrop:NO];
7051 /* Here we use the custom crop values saved at the time the preset was saved */
7052 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
7053 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
7054 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
7055 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
7058 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7060 [fPictureController setAutoCrop:YES];
7061 /* Here we use the auto crop values determined right after scan */
7062 job->crop[0] = AutoCropTop;
7063 job->crop[1] = AutoCropBottom;
7064 job->crop[2] = AutoCropLeft;
7065 job->crop[3] = AutoCropRight;
7070 if ([chosenPreset objectForKey:@"PictureModulus"])
7072 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
7079 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7080 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
7082 /* Use Max Picture settings for whatever the dvd is.*/
7083 [self revertPictureSizeToMax:nil];
7084 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7085 if (job->keep_ratio == 1)
7087 hb_fix_aspect( job, HB_KEEP_WIDTH );
7088 if( job->height > fTitle->height )
7090 job->height = fTitle->height;
7091 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7094 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7096 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7098 /* we check to make sure the presets width/height does not exceed the sources width/height */
7099 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
7101 /* if so, then we use the sources height and width to avoid scaling up */
7102 //job->width = fTitle->width;
7103 //job->height = fTitle->height;
7104 [self revertPictureSizeToMax:nil];
7106 else // source width/height is >= the preset height/width
7108 /* we can go ahead and use the presets values for height and width */
7109 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
7110 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
7112 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7113 if (job->keep_ratio == 1)
7115 int height = fTitle->height;
7117 if ( job->height && job->height < fTitle->height )
7118 height = job->height;
7120 hb_fix_aspect( job, HB_KEEP_WIDTH );
7121 // Make sure the resulting height is less than
7122 // the title height and less than the height
7123 // requested in the preset.
7124 if( job->height > height )
7126 job->height = height;
7127 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7130 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7131 if ( job->anamorphic.mode > 0 )
7133 int w, h, par_w, par_h;
7135 job->anamorphic.par_width = fTitle->pixel_aspect_width;
7136 job->anamorphic.par_height = fTitle->pixel_aspect_height;
7137 job->maxWidth = job->width;
7138 job->maxHeight = job->height;
7139 hb_set_anamorphic_size( job, &w, &h, &par_w, &par_h );
7150 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7151 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7155 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7156 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7157 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7160 [fPictureController setUseDecomb:1];
7161 [fPictureController setDecomb:0];
7162 [fPictureController setDeinterlace:0];
7163 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7165 /* we are using decomb */
7167 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7169 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7171 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7172 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7174 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7180 /* We are using Deinterlace */
7182 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7184 [fPictureController setUseDecomb:0];
7185 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7186 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7187 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7189 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7196 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7198 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7199 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7200 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7202 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7207 [fPictureController setDetelecine:0];
7211 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7213 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7214 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7215 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7217 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7222 [fPictureController setDenoise:0];
7226 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7228 /* if its a one, then its the old on/off deblock, set on to 5*/
7229 [fPictureController setDeblock:5];
7233 /* use the settings intValue */
7234 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7237 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7239 [fPictureController setGrayscale:1];
7243 [fPictureController setGrayscale:0];
7246 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7247 [fPictureController SetTitle:fTitle];
7248 [fPictureController SetTitle:fTitle];
7249 [self calculatePictureSizing:nil];
7255 #pragma mark Manage Presets
7257 - (void) loadPresets {
7258 /* We declare the default NSFileManager into fileManager */
7259 NSFileManager * fileManager = [NSFileManager defaultManager];
7260 /*We define the location of the user presets file */
7261 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7262 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7263 /* We check for the presets.plist */
7264 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7266 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7269 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7270 if (nil == UserPresets)
7272 UserPresets = [[NSMutableArray alloc] init];
7273 [self addFactoryPresets:nil];
7275 [fPresetsOutlineView reloadData];
7277 [self checkBuiltInsForUpdates];
7280 - (void) checkBuiltInsForUpdates {
7282 BOOL updateBuiltInPresets = NO;
7284 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7286 while (tempObject = [enumerator nextObject])
7288 /* iterate through the built in presets to see if any have an old build number */
7289 NSMutableDictionary *thisPresetDict = tempObject;
7290 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7291 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7293 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7295 updateBuiltInPresets = YES;
7300 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7301 if ( updateBuiltInPresets == YES)
7303 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7305 /* Show an alert window that built in presets will be updated */
7306 /*On Screen Notification*/
7309 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7310 [NSApp requestUserAttention:NSCriticalRequest];
7312 /* when alert is dismissed, go ahead and update the built in presets */
7313 [self addFactoryPresets:nil];
7319 - (IBAction) addPresetPicDropdownChanged: (id) sender
7321 if ([fPresetNewPicSettingsPopUp indexOfSelectedItem] == 1)
7323 [fPresetNewPicWidthHeightBox setHidden:NO];
7327 [fPresetNewPicWidthHeightBox setHidden:YES];
7331 - (IBAction) showAddPresetPanel: (id) sender
7333 /* Deselect the currently selected Preset if there is one*/
7334 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7336 /* Populate the preset picture settings popup here */
7337 [fPresetNewPicSettingsPopUp removeAllItems];
7338 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7339 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Custom"];
7340 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7341 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7342 /* Uncheck the preset use filters checkbox */
7343 [fPresetNewPicFiltersCheck setState:NSOffState];
7344 // fPresetNewFolderCheck
7345 [fPresetNewFolderCheck setState:NSOffState];
7346 /* Erase info from the input fields*/
7347 [fPresetNewName setStringValue: @""];
7348 [fPresetNewDesc setStringValue: @""];
7350 /* Initialize custom height and width settings to current values */
7352 [fPresetNewPicWidth setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->width]];
7353 [fPresetNewPicHeight setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->height]];
7354 [self addPresetPicDropdownChanged:nil];
7355 /* Show the panel */
7356 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7359 - (IBAction) closeAddPresetPanel: (id) sender
7361 [NSApp endSheet: fAddPresetPanel];
7362 [fAddPresetPanel orderOut: self];
7365 - (IBAction)addUserPreset:(id)sender
7367 if (![[fPresetNewName stringValue] length])
7368 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7371 /* Here we create a custom user preset */
7372 [UserPresets addObject:[self createPreset]];
7375 [self closeAddPresetPanel:nil];
7382 /* We Reload the New Table data for presets */
7383 [fPresetsOutlineView reloadData];
7384 /* We save all of the preset data here */
7392 /* We Sort the Presets By Factory or Custom */
7393 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7394 ascending:YES] autorelease];
7395 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7397 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7398 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7399 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7402 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7403 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7404 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7405 [UserPresets setArray:sortedArray];
7410 - (IBAction)insertPreset:(id)sender
7412 int index = [fPresetsOutlineView selectedRow];
7413 [UserPresets insertObject:[self createPreset] atIndex:index];
7414 [fPresetsOutlineView reloadData];
7418 - (NSDictionary *)createPreset
7420 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7421 /* Preset build number */
7422 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7423 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7424 /* Get the New Preset Name from the field in the AddPresetPanel */
7425 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7426 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7427 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7428 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7429 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7430 /*Set whether or not this is default, at creation set to 0*/
7431 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7432 if ([fPresetNewFolderCheck state] == YES)
7434 /* initialize and set an empty array for children here since we are a new folder */
7435 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7436 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7437 [childrenArray autorelease];
7439 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7441 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7442 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7443 /* Get whether or not to use the current Picture Filter settings for the preset */
7444 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7446 /* Get New Preset Description from the field in the AddPresetPanel*/
7447 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7449 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7450 /* Chapter Markers fCreateChapterMarkers*/
7451 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7452 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7453 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7454 /* Mux mp4 with http optimization */
7455 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7456 /* Add iPod uuid atom */
7457 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7461 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7462 /* x264 Option String */
7463 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7465 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7466 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7467 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7468 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7470 /* Video framerate */
7471 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7473 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7475 else // we can record the actual titleOfSelectedItem
7477 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7479 [preset setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
7481 /* 2 Pass Encoding */
7482 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7483 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7484 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7485 /*Picture Settings*/
7486 hb_job_t * job = fTitle->job;
7488 /* Picture Sizing */
7489 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7490 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicWidth intValue]] forKey:@"PictureWidth"];
7491 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicHeight intValue]] forKey:@"PictureHeight"];
7492 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7493 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7494 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7496 /* Set crop settings here */
7497 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7498 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7499 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7500 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7501 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7503 /* Picture Filters */
7504 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7505 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7506 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7507 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7508 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7509 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7510 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7511 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7512 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7513 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7514 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7517 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7518 /* we actually call the methods for the nests here */
7519 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7521 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7522 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7523 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7524 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7525 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7526 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7527 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7528 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7529 [audioTrack1Array autorelease];
7530 [audioListArray addObject:audioTrack1Array];
7533 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7535 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7536 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7537 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7538 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7539 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7540 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7541 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7542 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7543 [audioTrack2Array autorelease];
7544 [audioListArray addObject:audioTrack2Array];
7547 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7549 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7550 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7551 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7552 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7553 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7554 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7555 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7556 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7557 [audioTrack3Array autorelease];
7558 [audioListArray addObject:audioTrack3Array];
7561 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7563 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7564 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7565 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7566 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7567 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7568 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7569 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7570 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7571 [audioTrack4Array autorelease];
7572 [audioListArray addObject:audioTrack4Array];
7576 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7579 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7580 * subititle array code. */
7582 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7583 /* Forced Subtitles */
7584 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7586 [preset autorelease];
7593 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7594 /* We get the default preset in case it changed */
7595 [self getDefaultPresets:nil];
7599 - (IBAction)deletePreset:(id)sender
7603 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7607 /* Alert user before deleting preset */
7609 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7611 if ( status == NSAlertDefaultReturn )
7613 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7614 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7615 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7617 NSEnumerator *enumerator;
7618 NSMutableArray *presetsArrayToMod;
7619 NSMutableArray *tempArray;
7621 /* If we are a root level preset, we are modding the UserPresets array */
7622 if (presetToModLevel == 0)
7624 presetsArrayToMod = UserPresets;
7626 else // We have a parent preset, so we modify the chidren array object for key
7628 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7631 enumerator = [presetsArrayToMod objectEnumerator];
7632 tempArray = [NSMutableArray array];
7634 while (tempObject = [enumerator nextObject])
7636 NSDictionary *thisPresetDict = tempObject;
7637 if (thisPresetDict == presetToMod)
7639 [tempArray addObject:tempObject];
7643 [presetsArrayToMod removeObjectsInArray:tempArray];
7644 [fPresetsOutlineView reloadData];
7651 #pragma mark Import Export Preset(s)
7653 - (IBAction) browseExportPresetFile: (id) sender
7655 /* Open a panel to let the user choose where and how to save the export file */
7656 NSSavePanel * panel = [NSSavePanel savePanel];
7657 /* We get the current file name and path from the destination field here */
7658 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7660 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7661 modalForWindow: fWindow modalDelegate: self
7662 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7666 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7667 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7669 if( returnCode == NSOKButton )
7671 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7672 NSString *exportPresetsFile = [sheet filename];
7673 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7674 /* We check for the presets.plist */
7675 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7677 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7679 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7680 if (nil == presetsToExport)
7682 presetsToExport = [[NSMutableArray alloc] init];
7684 /* now get and add selected presets to export */
7687 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7689 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7690 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7698 - (IBAction) browseImportPresetFile: (id) sender
7701 NSOpenPanel * panel;
7703 panel = [NSOpenPanel openPanel];
7704 [panel setAllowsMultipleSelection: NO];
7705 [panel setCanChooseFiles: YES];
7706 [panel setCanChooseDirectories: NO ];
7707 NSString * sourceDirectory;
7708 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7710 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7714 sourceDirectory = @"~/Desktop";
7715 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7717 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7718 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7720 /* set this for allowed file types, not sure if we should allow xml or not */
7721 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7722 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7723 modalForWindow: fWindow modalDelegate: self
7724 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7725 contextInfo: sender];
7728 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7729 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7731 if( returnCode == NSOKButton )
7733 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7734 NSString *importPresetsFile = [sheet filename];
7735 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7736 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7737 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7738 /* iterate though the new array of presets to import and add them to our presets array */
7740 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7742 while (tempObject = [enumerator nextObject])
7744 /* make any changes to the incoming preset we see fit */
7745 /* make sure the incoming preset is not tagged as default */
7746 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7747 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7748 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7749 [tempObject setObject:prependedName forKey:@"PresetName"];
7751 /* actually add the new preset to our presets array */
7752 [UserPresets addObject:tempObject];
7755 [presetsToImport autorelease];
7763 #pragma mark Manage Default Preset
7765 - (IBAction)getDefaultPresets:(id)sender
7767 presetHbDefault = nil;
7768 presetUserDefault = nil;
7769 presetUserDefaultParent = nil;
7770 presetUserDefaultParentParent = nil;
7771 NSMutableDictionary *presetHbDefaultParent = nil;
7772 NSMutableDictionary *presetHbDefaultParentParent = nil;
7775 BOOL userDefaultFound = NO;
7776 presetCurrentBuiltInCount = 0;
7777 /* First we iterate through the root UserPresets array to check for defaults */
7778 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7780 while (tempObject = [enumerator nextObject])
7782 NSMutableDictionary *thisPresetDict = tempObject;
7783 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7785 presetHbDefault = thisPresetDict;
7787 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7789 presetUserDefault = thisPresetDict;
7790 userDefaultFound = YES;
7792 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7794 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7798 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7799 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7801 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7802 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7804 while (tempObject = [enumerator nextObject])
7806 NSMutableDictionary *thisPresetDict = tempObject;
7807 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7809 presetHbDefault = thisPresetDict;
7810 presetHbDefaultParent = thisPresetDictParent;
7812 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7814 presetUserDefault = thisPresetDict;
7815 presetUserDefaultParent = thisPresetDictParent;
7816 userDefaultFound = YES;
7819 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7820 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7822 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7823 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7825 while (tempObject = [enumerator nextObject])
7827 NSMutableDictionary *thisPresetDict = tempObject;
7828 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7830 presetHbDefault = thisPresetDict;
7831 presetHbDefaultParent = thisPresetDictParent;
7832 presetHbDefaultParentParent = thisPresetDictParentParent;
7834 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7836 presetUserDefault = thisPresetDict;
7837 presetUserDefaultParent = thisPresetDictParent;
7838 presetUserDefaultParentParent = thisPresetDictParentParent;
7839 userDefaultFound = YES;
7848 /* check to see if a user specified preset was found, if not then assign the parents for
7849 * the presetHbDefault so that we can open the parents for the nested presets
7851 if (userDefaultFound == NO)
7853 presetUserDefaultParent = presetHbDefaultParent;
7854 presetUserDefaultParentParent = presetHbDefaultParentParent;
7858 - (IBAction)setDefaultPreset:(id)sender
7860 /* We need to determine if the item is a folder */
7861 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7867 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7869 /* First make sure the old user specified default preset is removed */
7870 while (tempObject = [enumerator nextObject])
7872 NSMutableDictionary *thisPresetDict = tempObject;
7873 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7875 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7878 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7879 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7881 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7884 while (tempObject = [enumerator nextObject])
7886 NSMutableDictionary *thisPresetDict1 = tempObject;
7887 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7889 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7891 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7892 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7894 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7897 while (tempObject = [enumerator nextObject])
7899 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7901 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7914 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7915 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7916 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7919 NSMutableArray *presetsArrayToMod;
7920 NSMutableArray *tempArray;
7922 /* If we are a root level preset, we are modding the UserPresets array */
7923 if (presetToModLevel == 0)
7925 presetsArrayToMod = UserPresets;
7927 else // We have a parent preset, so we modify the chidren array object for key
7929 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7932 enumerator = [presetsArrayToMod objectEnumerator];
7933 tempArray = [NSMutableArray array];
7935 while (tempObject = [enumerator nextObject])
7937 NSDictionary *thisPresetDict = tempObject;
7938 if (thisPresetDict == presetToMod)
7940 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7942 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7949 /* We save all of the preset data here */
7951 /* We Reload the New Table data for presets */
7952 [fPresetsOutlineView reloadData];
7955 - (IBAction)selectDefaultPreset:(id)sender
7957 NSMutableDictionary *presetToMod;
7958 /* if there is a user specified default, we use it */
7959 if (presetUserDefault)
7961 presetToMod = presetUserDefault;
7963 else if (presetHbDefault) //else we use the built in default presetHbDefault
7965 presetToMod = presetHbDefault;
7972 if (presetUserDefaultParent != nil)
7974 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7977 if (presetUserDefaultParentParent != nil)
7979 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7983 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7984 [self selectPreset:nil];
7989 #pragma mark Manage Built In Presets
7992 - (IBAction)deleteFactoryPresets:(id)sender
7995 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7999 NSMutableArray *tempArray;
8002 tempArray = [NSMutableArray array];
8003 /* we look here to see if the preset is we move on to the next one */
8004 while ( tempObject = [enumerator nextObject] )
8006 /* if the preset is "Factory" then we put it in the array of
8007 presets to delete */
8008 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
8010 [tempArray addObject:tempObject];
8014 [UserPresets removeObjectsInArray:tempArray];
8015 [fPresetsOutlineView reloadData];
8020 /* We use this method to recreate new, updated factory presets */
8021 - (IBAction)addFactoryPresets:(id)sender
8024 /* First, we delete any existing built in presets */
8025 [self deleteFactoryPresets: sender];
8026 /* Then we generate new built in presets programmatically with fPresetsBuiltin
8027 * which is all setup in HBPresets.h and HBPresets.m*/
8028 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
8029 /* update build number for built in presets */
8030 /* iterate though the new array of presets to import and add them to our presets array */
8032 NSEnumerator *enumerator = [UserPresets objectEnumerator];
8034 while (tempObject = [enumerator nextObject])
8036 /* Record the apps current build number in the PresetBuildNumber key */
8037 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
8039 /* Preset build number */
8040 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8044 /* report the built in preset updating to the activity log */
8045 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8053 #pragma mark Chapter Files Import / Export
8055 - (IBAction) browseForChapterFile: (id) sender
8057 /* Open a panel to let the user choose the file */
8058 NSOpenPanel * panel = [NSOpenPanel openPanel];
8059 /* We get the current file name and path from the destination field here */
8060 [panel beginSheetForDirectory: [NSString stringWithFormat:@"%@/",
8061 [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"]]
8063 types: [NSArray arrayWithObjects:@"csv",nil]
8064 modalForWindow: fWindow modalDelegate: self
8065 didEndSelector: @selector( browseForChapterFileDone:returnCode:contextInfo: )
8069 - (void) browseForChapterFileDone: (NSOpenPanel *) sheet
8070 returnCode: (int) returnCode contextInfo: (void *) contextInfo
8072 NSArray *chaptersArray; /* temp array for chapters */
8073 NSMutableArray *chaptersMutableArray; /* temp array for chapters */
8074 NSString *chapterName; /* temp string from file */
8077 if( returnCode == NSOKButton ) /* if they click OK */
8079 chapterName = [[NSString alloc] initWithContentsOfFile:[sheet filename] encoding:NSUTF8StringEncoding error:NULL];
8080 chaptersArray = [chapterName componentsSeparatedByString:@"\n"];
8081 chaptersMutableArray= [chaptersArray mutableCopy];
8082 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
8083 if ([chaptersMutableArray count] > 0)
8085 /* if last item is empty remove it */
8086 if ([[chaptersMutableArray objectAtIndex:[chaptersArray count]-1] length] == 0)
8088 [chaptersMutableArray removeLastObject];
8091 /* if chapters in table is not equal to array count */
8092 if ((unsigned int) chapters != [chaptersMutableArray count])
8095 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
8096 defaultButton:NSLocalizedString(@"OK", @"OK")
8097 alternateButton:NULL
8099 informativeTextWithFormat:NSLocalizedString(@"%d chapters expected, %d chapters found in %@", @"%d chapters expected, %d chapters found in %@"),
8100 chapters, [chaptersMutableArray count], [[sheet filename] lastPathComponent]] runModal];
8103 /* otherwise, go ahead and populate table with array */
8104 for (i=0; i<chapters; i++)
8107 if([[chaptersMutableArray objectAtIndex:i] length] > 5)
8109 /* avoid a segfault */
8110 /* Get the Range.location of the first comma in the line and then put everything after that into chapterTitle */
8111 NSRange firstCommaRange = [[chaptersMutableArray objectAtIndex:i] rangeOfString:@","];
8112 NSString *chapterTitle = [[chaptersMutableArray objectAtIndex:i] substringFromIndex:firstCommaRange.location + 1];
8113 /* Since we store our chapterTitle commas as "\," for the cli, we now need to remove the escaping "\" from the title */
8114 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"\\," withString:@","];
8115 [fChapterTitlesDelegate tableView:fChapterTable
8116 setObjectValue:chapterTitle
8117 forTableColumn:fChapterTableNameColumn
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(@"%@ was not formatted as expected.", @"%@ was not formatted as expected."), [[sheet filename] lastPathComponent]] runModal];
8128 [fChapterTable reloadData];
8132 [fChapterTable reloadData];
8136 - (IBAction) browseForChapterFileSave: (id) sender
8138 NSSavePanel *panel = [NSSavePanel savePanel];
8139 /* Open a panel to let the user save to a file */
8140 [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv",nil]];
8141 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent]
8142 file: [[[[fDstFile2Field stringValue] lastPathComponent] stringByDeletingPathExtension]
8143 stringByAppendingString:@"-chapters.csv"]
8144 modalForWindow: fWindow
8146 didEndSelector: @selector( browseForChapterFileSaveDone:returnCode:contextInfo: )
8150 - (void) browseForChapterFileSaveDone: (NSSavePanel *) sheet
8151 returnCode: (int) returnCode contextInfo: (void *) contextInfo
8153 NSString *chapterName; /* pointer for string for later file-writing */
8154 NSString *chapterTitle;
8155 NSError *saveError = [[NSError alloc] init];
8156 int chapters, i; /* ints for the number of chapters in the table and the loop */
8158 if( returnCode == NSOKButton ) /* if they clicked OK */
8160 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
8161 chapterName = [NSString string];
8162 for (i=0; i<chapters; i++)
8164 /* put each chapter title from the table into the array */
8166 { /* if i is from 0 to 8 (chapters 1 to 9) add two leading zeros */
8167 chapterName = [chapterName stringByAppendingFormat:@"00%d,",i+1];
8170 { /* if i is from 9 to 98 (chapters 10 to 99) add one leading zero */
8171 chapterName = [chapterName stringByAppendingFormat:@"0%d,",i+1];
8174 { /* in case i is from 99 to 998 (chapters 100 to 999) no leading zeros */
8175 chapterName = [chapterName stringByAppendingFormat:@"%d,",i+1];
8178 chapterTitle = [fChapterTitlesDelegate tableView:fChapterTable objectValueForTableColumn:fChapterTableNameColumn row:i];
8179 /* escape any commas in the chapter name with "\," */
8180 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"," withString:@"\\,"];
8181 chapterName = [chapterName stringByAppendingString:chapterTitle];
8182 if (i+1 != chapters)
8183 { /* if not the last chapter */
8184 chapterName = [chapterName stringByAppendingString:@ "\n"];
8189 /* try to write it to where the user wanted */
8190 if (![chapterName writeToFile:[sheet filename]
8192 encoding:NSUTF8StringEncoding
8196 [[NSAlert alertWithError:saveError] runModal];
8203 /*******************************
8204 * Subclass of the HBPresetsOutlineView *
8205 *******************************/
8207 @implementation HBPresetsOutlineView
8208 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8212 // By default, NSTableView only drags an image of the first column. Change this to
8213 // drag an image of the queue's icon and PresetName columns.
8214 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8215 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8220 - (void) mouseDown:(NSEvent *)theEvent
8222 [super mouseDown:theEvent];
8228 - (BOOL) isDragging;