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. */
8 #import "HBOutputPanelController.h"
9 #import "HBPreferencesController.h"
10 #import "HBDVDDetector.h"
12 #import "HBPreviewController.h"
14 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
16 /* We setup the toolbar values here ShowPreviewIdentifier */
17 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
18 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
19 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
20 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
21 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
22 static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
23 static NSString * ShowPreviewIdentifier = @"Show Preview Window Item Identifier";
24 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
25 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
28 /*******************************
29 * HBController implementation *
30 *******************************/
31 @implementation HBController
41 /* replace bundled app icon with one which is 32/64-bit savvy */
42 #if defined( __LP64__ )
43 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
45 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
47 if( fApplicationIcon != nil )
48 [NSApp setApplicationIconImage:fApplicationIcon];
50 [HBPreferencesController registerUserDefaults];
52 fQueueEncodeLibhb = NULL;
53 /* Check for check for the app support directory here as
54 * outputPanel needs it right away, as may other future methods
56 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
58 YES ) objectAtIndex:0];
59 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
60 stringByAppendingPathComponent:@"HandBrake"];
61 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
63 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
66 /* Check for and create the App Support Preview directory if necessary */
67 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
68 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
70 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
73 outputPanel = [[HBOutputPanelController alloc] init];
74 fPictureController = [[PictureController alloc] init];
75 fQueueController = [[HBQueueController alloc] init];
76 fAdvancedOptions = [[HBAdvancedController alloc] init];
77 /* we init the HBPresets class which currently is only used
78 * for updating built in presets, may move more functionality
81 fPresetsBuiltin = [[HBPresets alloc] init];
82 fPreferencesController = [[HBPreferencesController alloc] init];
83 /* Lets report the HandBrake version number here to the activity log and text log file */
84 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
85 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
91 - (void) applicationDidFinishLaunching: (NSNotification *) notification
93 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
94 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
95 fHandle = hb_init(loggingLevel, 0);
96 /* Optional dvd nav UseDvdNav*/
97 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
98 /* Init a separate instance of libhb for user scanning and setting up jobs */
99 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
101 // Set the Growl Delegate
102 [GrowlApplicationBridge setGrowlDelegate: self];
103 /* Init others controllers */
104 [fPictureController SetHandle: fHandle];
105 [fPictureController setHBController: self];
107 [fQueueController setHandle: fQueueEncodeLibhb];
108 [fQueueController setHBController: self];
110 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
111 [fChapterTable setDataSource:fChapterTitlesDelegate];
112 [fChapterTable setDelegate:fChapterTitlesDelegate];
114 /* setup the subtitles delegate and connections to table */
115 fSubtitlesDelegate = [[HBSubtitles alloc] init];
116 [fSubtitlesTable setDataSource:fSubtitlesDelegate];
117 [fSubtitlesTable setDelegate:fSubtitlesDelegate];
118 [fSubtitlesTable setRowHeight:25.0];
120 [fPresetsOutlineView setAutosaveName:@"Presets View"];
121 [fPresetsOutlineView setAutosaveExpandedItems:YES];
123 dockIconProgress = 0;
125 /* Call UpdateUI every 1/2 sec */
126 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
127 scheduledTimerWithTimeInterval:0.5 target:self
128 selector:@selector(updateUI:) userInfo:nil repeats:YES]
129 forMode:NSDefaultRunLoopMode];
131 // Open debug output window now if it was visible when HB was closed
132 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
133 [self showDebugOutputPanel:nil];
135 // Open queue window now if it was visible when HB was closed
136 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
137 [self showQueueWindow:nil];
139 [self openMainWindow:nil];
141 /* We have to set the bool to tell hb what to do after a scan
142 * Initially we set it to NO until we start processing the queue
144 applyQueueToScan = NO;
146 /* Now we re-check the queue array to see if there are
147 * any remaining encodes to be done in it and ask the
148 * user if they want to reload the queue */
149 if ([QueueFileArray count] > 0)
151 /* run getQueueStats to see whats in the queue file */
152 [self getQueueStats];
153 /* this results in these values
154 * fEncodingQueueItem = 0;
156 * fCompletedCount = 0;
157 * fCanceledCount = 0;
161 /*On Screen Notification*/
162 NSString * alertTitle;
164 /* We check to see if there is already another instance of hb running.
165 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
167 if ([self hbInstances] > 1)
169 alertTitle = [NSString stringWithFormat:
170 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
171 NSBeginCriticalAlertSheet(
173 NSLocalizedString(@"Reload Queue", nil),
177 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
178 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
182 if (fWorkingCount > 0)
184 alertTitle = [NSString stringWithFormat:
185 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
186 fWorkingCount,fPendingCount];
190 alertTitle = [NSString stringWithFormat:
191 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
195 NSBeginCriticalAlertSheet(
197 NSLocalizedString(@"Reload Queue", nil),
199 NSLocalizedString(@"Empty Queue", nil),
201 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
202 NSLocalizedString(@" Do you want to reload them ?", nil));
208 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
209 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
211 [self browseSources:nil];
214 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
216 [self browseSources:(id)fOpenSourceTitleMMenu];
223 /* check to see if another instance of HandBrake.app is running */
224 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
225 NSDictionary *aDictionary;
227 for (aDictionary in runningAppDictionaries)
229 if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
237 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
239 if (returnCode == NSAlertOtherReturn)
241 [self clearQueueAllItems];
242 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
243 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
245 [self browseSources:nil];
248 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
250 [self browseSources:(id)fOpenSourceTitleMMenu];
255 if ([self hbInstances] == 1)
257 [self setQueueEncodingItemsAsPending];
259 [self showQueueWindow:NULL];
263 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
265 /* if we are in preview full screen mode, we need to go to
266 * windowed mode and release the display before we terminate.
267 * We do it here (instead of applicationWillTerminate) so we
268 * release the displays and can then see the alerts below.
270 if ([fPictureController previewFullScreenMode] == YES)
272 [fPictureController previewGoWindowed:nil];
276 hb_get_state( fQueueEncodeLibhb, &s );
278 if ( s.state != HB_STATE_IDLE )
280 int result = NSRunCriticalAlertPanel(
281 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
282 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
283 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
285 if (result == NSAlertDefaultReturn)
287 return NSTerminateNow;
290 return NSTerminateCancel;
293 // Warn if items still in the queue
294 else if ( fPendingCount > 0 )
296 int result = NSRunCriticalAlertPanel(
297 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
298 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
299 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
301 if ( result == NSAlertDefaultReturn )
302 return NSTerminateNow;
304 return NSTerminateCancel;
307 return NSTerminateNow;
310 - (void)applicationWillTerminate:(NSNotification *)aNotification
313 [browsedSourceDisplayName release];
314 [outputPanel release];
315 [fQueueController release];
316 [fPreviewController release];
317 [fPictureController release];
318 [fApplicationIcon release];
321 hb_close(&fQueueEncodeLibhb);
325 - (void) awakeFromNib
328 [fWindow setExcludedFromWindowsMenu:YES];
329 [fAdvancedOptions setView:fAdvancedView];
331 /* lets setup our presets drawer for drag and drop here */
332 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
333 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
334 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
336 /* Initialize currentScanCount so HB can use it to
337 evaluate successive scans */
338 currentScanCount = 0;
341 /* Init UserPresets .plist */
344 /* Init QueueFile .plist */
345 [self loadQueueFile];
347 fRipIndicatorShown = NO; // initially out of view in the nib
349 /* For 64 bit builds, the threaded animation in the progress
350 * indicators conflicts with the animation in the advanced tab
351 * for reasons not completely clear. jbrjake found a note in the
352 * 10.5 dev notes regarding this possiblility. It was also noted
353 * that unless specified, setUsesThreadedAnimation defaults to true.
354 * So, at least for now we set the indicator animation to NO for
355 * both the scan and regular progress indicators for both 32 and 64 bit
356 * as it test out fine on both and there is no reason our progress indicators
357 * should require their own thread.
360 [fScanIndicator setUsesThreadedAnimation:NO];
361 [fRipIndicator setUsesThreadedAnimation:NO];
365 /* Show/Dont Show Presets drawer upon launch based
366 on user preference DefaultPresetsDrawerShow*/
367 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
369 [fPresetDrawer setDelegate:self];
370 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
371 stringForKey:@"Drawer Size"] );
372 if( drawerSize.width )
373 [fPresetDrawer setContentSize: drawerSize];
374 [fPresetDrawer open];
377 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
378 [fSrcAngleLabel setHidden:YES];
379 [fSrcAnglePopUp setHidden:YES];
381 /* Setup the start / stop popup */
382 [fEncodeStartStopPopUp removeAllItems];
383 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
384 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
385 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
386 /* Align the start / stop widgets with the chapter popups */
387 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
388 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
390 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
391 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
394 NSMenuItem *menuItem;
395 [fDstFormatPopUp removeAllItems];
397 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
398 [menuItem setTag: HB_MUX_MP4];
400 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
401 [menuItem setTag: HB_MUX_MKV];
403 [fDstFormatPopUp selectItemAtIndex: 0];
405 [self formatPopUpChanged:nil];
407 /* We enable the create chapters checkbox here since we are .mp4 */
408 [fCreateChapterMarkers setEnabled: YES];
409 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
411 [fCreateChapterMarkers setState: NSOnState];
417 [fDstFile2Field setStringValue: [NSString stringWithFormat:
418 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
421 [fVidEncoderPopUp removeAllItems];
422 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
426 [fVidTargetSizeField setIntValue: 700];
427 [fVidBitrateField setIntValue: 1000];
429 [fVidQualityMatrix selectCell: fVidBitrateCell];
430 [self videoMatrixChanged:nil];
432 /* Video framerate */
433 [fVidRatePopUp removeAllItems];
434 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
435 for( int i = 0; i < hb_video_rates_count; i++ )
437 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
439 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
440 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
442 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
444 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
445 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
447 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
449 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
450 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
454 [fVidRatePopUp addItemWithTitle:
455 [NSString stringWithUTF8String: hb_video_rates[i].string]];
458 [fVidRatePopUp selectItemAtIndex: 0];
460 /* Set Auto Crop to On at launch */
461 [fPictureController setAutoCrop:YES];
464 [fAudTrack1BitratePopUp removeAllItems];
465 for( int i = 0; i < hb_audio_bitrates_count; i++ )
467 [fAudTrack1BitratePopUp addItemWithTitle:
468 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
471 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
473 /* Audio samplerate */
474 [fAudTrack1RatePopUp removeAllItems];
475 for( int i = 0; i < hb_audio_rates_count; i++ )
477 [fAudTrack1RatePopUp addItemWithTitle:
478 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
480 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
483 [fStatusField setStringValue: @""];
488 /* We disable the Turbo 1st pass checkbox since we are not x264 */
489 [fVidTurboPassCheck setEnabled: NO];
490 [fVidTurboPassCheck setState: NSOffState];
493 /* lets get our default prefs here */
494 [self getDefaultPresets:nil];
495 /* lets initialize the current successful scancount here to 0 */
496 currentSuccessfulScanCount = 0;
501 - (void) enableUI: (bool) b
503 NSControl * controls[] =
504 { fSrcTitleField, fSrcTitlePopUp,
505 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
506 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
507 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
508 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
509 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
510 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
511 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
512 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
513 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
514 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
515 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
516 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
517 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
518 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
519 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
520 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
521 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
522 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,fSrcFrameEndEncodingField};
525 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
527 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
529 NSTextField * tf = (NSTextField *) controls[i];
530 if( ![tf isBezeled] )
532 [tf setTextColor: b ? [NSColor controlTextColor] :
533 [NSColor disabledControlTextColor]];
537 [controls[i] setEnabled: b];
543 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
544 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
545 [self setEnabledStateOfAudioMixdownControls:nil];
546 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
547 [self calculatePictureSizing:nil];
551 [fPresetsOutlineView setEnabled: NO];
555 [self videoMatrixChanged:nil];
556 [fAdvancedOptions enableUI:b];
560 /***********************************************************************
562 ***********************************************************************
563 * Shows a progression bar on the dock icon, filled according to
564 * 'progress' (0.0 <= progress <= 1.0).
565 * Called with progress < 0.0 or progress > 1.0, restores the original
567 **********************************************************************/
568 - (void) UpdateDockIcon: (float) progress
571 NSBitmapImageRep * bmp;
573 uint32_t black = htonl( 0x000000FF );
574 uint32_t red = htonl( 0xFF0000FF );
575 uint32_t white = htonl( 0xFFFFFFFF );
576 int row_start, row_end;
579 if( progress < 0.0 || progress > 1.0 )
581 [NSApp setApplicationIconImage: fApplicationIcon];
585 /* Get it in a raw bitmap form */
586 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
587 NSTIFFCompressionNone factor: 1.0];
588 bmp = [NSBitmapImageRep imageRepWithData: tiff];
590 /* Draw the progression bar */
591 /* It's pretty simple (ugly?) now, but I'm no designer */
593 row_start = 3 * (int) [bmp size].height / 4;
594 row_end = 7 * (int) [bmp size].height / 8;
596 for( i = row_start; i < row_start + 2; i++ )
598 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
599 for( j = 0; j < (int) [bmp size].width; j++ )
604 for( i = row_start + 2; i < row_end - 2; i++ )
606 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
609 for( j = 2; j < (int) [bmp size].width - 2; j++ )
611 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
623 for( i = row_end - 2; i < row_end; i++ )
625 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
626 for( j = 0; j < (int) [bmp size].width; j++ )
632 /* Now update the dock icon */
633 tiff = [bmp TIFFRepresentationUsingCompression:
634 NSTIFFCompressionNone factor: 1.0];
635 NSImage* icon = [[NSImage alloc] initWithData: tiff];
636 [NSApp setApplicationIconImage: icon];
640 - (void) updateUI: (NSTimer *) timer
643 /* Update UI for fHandle (user scanning instance of libhb ) */
646 list = hb_get_titles( fHandle );
647 /* check to see if there has been a new scan done
648 this bypasses the constraints of HB_STATE_WORKING
649 not allowing setting a newly scanned source */
650 int checkScanCount = hb_get_scancount( fHandle );
651 if( checkScanCount > currentScanCount )
653 currentScanCount = checkScanCount;
654 [fScanIndicator setIndeterminate: NO];
655 [fScanIndicator setDoubleValue: 0.0];
656 [fScanIndicator setHidden: YES];
657 [self showNewScan:nil];
661 hb_get_state( fHandle, &s );
667 #define p s.param.scanning
668 case HB_STATE_SCANNING:
670 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
671 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
672 p.title_cur, p.title_count]];
673 [fScanIndicator setHidden: NO];
674 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
679 #define p s.param.scandone
680 case HB_STATE_SCANDONE:
682 [fScanIndicator setIndeterminate: NO];
683 [fScanIndicator setDoubleValue: 0.0];
684 [fScanIndicator setHidden: YES];
685 [self writeToActivityLog:"ScanDone state received from fHandle"];
686 [self showNewScan:nil];
687 [[fWindow toolbar] validateVisibleItems];
693 #define p s.param.working
694 case HB_STATE_WORKING:
701 #define p s.param.muxing
702 case HB_STATE_MUXING:
709 case HB_STATE_PAUSED:
712 case HB_STATE_WORKDONE:
719 /* Update UI for fQueueEncodeLibhb */
721 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
722 /* check to see if there has been a new scan done
723 this bypasses the constraints of HB_STATE_WORKING
724 not allowing setting a newly scanned source */
726 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
727 if( checkScanCount > currentScanCount )
729 currentScanCount = checkScanCount;
733 hb_get_state( fQueueEncodeLibhb, &s );
739 #define p s.param.scanning
740 case HB_STATE_SCANNING:
742 [fStatusField setStringValue: [NSString stringWithFormat:
743 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
744 p.title_cur, p.title_count]];
746 /* Set the status string in fQueueController as well */
747 [fQueueController setQueueStatusString: [NSString stringWithFormat:
748 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
749 p.title_cur, p.title_count]];
754 #define p s.param.scandone
755 case HB_STATE_SCANDONE:
757 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
758 [self processNewQueueEncode];
759 [[fWindow toolbar] validateVisibleItems];
766 #define p s.param.working
768 case HB_STATE_SEARCHING:
770 NSMutableString * string;
771 NSString * pass_desc;
773 /* Update text field */
775 //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];
776 /* For now, do not announce "pass x of x for the search phase ... */
777 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
781 [string appendFormat:
782 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
785 [fStatusField setStringValue: string];
786 /* Set the status string in fQueueController as well */
787 [fQueueController setQueueStatusString: string];
789 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
790 [fRipIndicator setIndeterminate: NO];
791 [fRipIndicator setDoubleValue:100.0 * progress_total];
793 // If progress bar hasn't been revealed at the bottom of the window, do
794 // that now. This code used to be in doRip. I moved it to here to handle
795 // the case where hb_start is called by HBQueueController and not from
797 if( !fRipIndicatorShown )
799 NSRect frame = [fWindow frame];
800 if( frame.size.width <= 591 )
801 frame.size.width = 591;
802 frame.size.height += 36;
803 frame.origin.y -= 36;
804 [fWindow setFrame:frame display:YES animate:YES];
805 fRipIndicatorShown = YES;
809 /* Update dock icon */
810 /* Note not done yet */
815 case HB_STATE_WORKING:
817 NSMutableString * string;
818 NSString * pass_desc;
819 /* Update text field */
820 if (p.job_cur == 1 && p.job_count > 1)
822 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
824 pass_desc = @"(subtitle scan)";
836 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
840 [string appendFormat:
841 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
842 p.rate_cur, p.rate_avg, 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 if( dockIconProgress < 100.0 * progress_total )
872 [self UpdateDockIcon: progress_total];
873 dockIconProgress += 5;
880 #define p s.param.muxing
881 case HB_STATE_MUXING:
883 /* Update text field */
884 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
885 /* Set the status string in fQueueController as well */
886 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
888 [fRipIndicator setIndeterminate: YES];
889 [fRipIndicator startAnimation: nil];
891 /* Update dock icon */
892 [self UpdateDockIcon: 1.0];
898 case HB_STATE_PAUSED:
899 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
900 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
904 case HB_STATE_WORKDONE:
906 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
907 // or someone calling hb_stop. In the latter case, hb_stop does not clear
908 // out the remaining passes/jobs in the queue. We'll do that here.
910 // Delete all remaining jobs of this encode.
911 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
912 /* Set the status string in fQueueController as well */
913 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
914 [fRipIndicator setIndeterminate: NO];
915 [fRipIndicator stopAnimation: nil];
916 [fRipIndicator setDoubleValue: 0.0];
917 [[fWindow toolbar] validateVisibleItems];
919 /* Restore dock icon */
920 [self UpdateDockIcon: -1.0];
921 dockIconProgress = 0;
923 if( fRipIndicatorShown )
925 NSRect frame = [fWindow frame];
926 if( frame.size.width <= 591 )
927 frame.size.width = 591;
928 frame.size.height += -36;
929 frame.origin.y -= -36;
930 [fWindow setFrame:frame display:YES animate:YES];
931 fRipIndicatorShown = NO;
933 /* Since we are done with this encode, tell output to stop writing to the
934 * individual encode log
936 [outputPanel endEncodeLog];
937 /* Check to see if the encode state has not been cancelled
938 to determine if we should check for encode done notifications */
939 if( fEncodeState != 2 )
941 NSString *pathOfFinishedEncode;
942 /* Get the output file name for the finished encode */
943 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
945 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
947 [self showGrowlDoneNotification:pathOfFinishedEncode];
949 [self sendToMetaX:pathOfFinishedEncode];
951 /* since we have successfully completed an encode, we increment the queue counter */
952 [self incrementQueueItemDone:nil];
954 /* all end of queue actions below need to be done after all queue encodes have finished
955 * and there are no pending jobs left to process
957 if (fPendingCount == 0)
959 /* If Alert Window or Window and Growl has been selected */
960 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
961 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
963 /*On Screen Notification*/
966 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
967 [NSApp requestUserAttention:NSCriticalRequest];
970 /* If sleep has been selected */
971 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
974 NSDictionary* errorDict;
975 NSAppleEventDescriptor* returnDescriptor = nil;
976 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
977 @"tell application \"Finder\" to sleep"];
978 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
979 [scriptObject release];
981 /* If Shutdown has been selected */
982 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
985 NSDictionary* errorDict;
986 NSAppleEventDescriptor* returnDescriptor = nil;
987 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
988 @"tell application \"Finder\" to shut down"];
989 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
990 [scriptObject release];
1004 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1005 - (void) writeToActivityLog:(const char *) format, ...
1008 va_start(args, format);
1012 vsnprintf( str, 1024, format, args );
1014 time_t _now = time( NULL );
1015 struct tm * now = localtime( &_now );
1016 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1022 #pragma mark Toolbar
1023 // ============================================================
1024 // NSToolbar Related Methods
1025 // ============================================================
1027 - (void) setupToolbar {
1028 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1030 [toolbar setAllowsUserCustomization: YES];
1031 [toolbar setAutosavesConfiguration: YES];
1032 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1034 [toolbar setDelegate: self];
1036 [fWindow setToolbar: toolbar];
1039 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1040 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1041 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1043 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1045 [item setLabel: @"Toggle Presets"];
1046 [item setPaletteLabel: @"Toggler Presets"];
1047 [item setToolTip: @"Open/Close Preset Drawer"];
1048 [item setImage: [NSImage imageNamed: @"Drawer"]];
1049 [item setTarget: self];
1050 [item setAction: @selector(toggleDrawer:)];
1051 [item setAutovalidates: NO];
1053 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1055 [item setLabel: @"Start"];
1056 [item setPaletteLabel: @"Start Encoding"];
1057 [item setToolTip: @"Start Encoding"];
1058 [item setImage: [NSImage imageNamed: @"Play"]];
1059 [item setTarget: self];
1060 [item setAction: @selector(Rip:)];
1062 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1064 [item setLabel: @"Show Queue"];
1065 [item setPaletteLabel: @"Show Queue"];
1066 [item setToolTip: @"Show Queue"];
1067 [item setImage: [NSImage imageNamed: @"Queue"]];
1068 [item setTarget: self];
1069 [item setAction: @selector(showQueueWindow:)];
1070 [item setAutovalidates: NO];
1072 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1074 [item setLabel: @"Add to Queue"];
1075 [item setPaletteLabel: @"Add to Queue"];
1076 [item setToolTip: @"Add to Queue"];
1077 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1078 [item setTarget: self];
1079 [item setAction: @selector(addToQueue:)];
1081 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1083 [item setLabel: @"Pause"];
1084 [item setPaletteLabel: @"Pause Encoding"];
1085 [item setToolTip: @"Pause Encoding"];
1086 [item setImage: [NSImage imageNamed: @"Pause"]];
1087 [item setTarget: self];
1088 [item setAction: @selector(Pause:)];
1090 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1092 [item setLabel: @"Picture Settings"];
1093 [item setPaletteLabel: @"Show Picture Settings"];
1094 [item setToolTip: @"Show Picture Settings"];
1095 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1096 [item setTarget: self];
1097 [item setAction: @selector(showPicturePanel:)];
1099 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1101 [item setLabel: @"Preview Window"];
1102 [item setPaletteLabel: @"Show Preview"];
1103 [item setToolTip: @"Show Preview"];
1104 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1105 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1106 [item setTarget: self];
1107 [item setAction: @selector(showPreviewWindow:)];
1109 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1111 [item setLabel: @"Activity Window"];
1112 [item setPaletteLabel: @"Show Activity Window"];
1113 [item setToolTip: @"Show Activity Window"];
1114 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1115 [item setTarget: self];
1116 [item setAction: @selector(showDebugOutputPanel:)];
1117 [item setAutovalidates: NO];
1119 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1121 [item setLabel: @"Source"];
1122 [item setPaletteLabel: @"Source"];
1123 [item setToolTip: @"Choose Video Source"];
1124 [item setImage: [NSImage imageNamed: @"Source"]];
1125 [item setTarget: self];
1126 [item setAction: @selector(browseSources:)];
1136 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1138 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1139 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1140 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1143 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1145 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1146 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1147 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1148 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1151 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1153 NSString * ident = [toolbarItem itemIdentifier];
1159 hb_get_state( fHandle, &s );
1160 if (s.state == HB_STATE_SCANNING)
1163 if ([ident isEqualToString: ChooseSourceIdentifier])
1165 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1166 [toolbarItem setLabel: @"Cancel Scan"];
1167 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1168 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1172 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1177 if ([ident isEqualToString: ChooseSourceIdentifier])
1179 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1180 [toolbarItem setLabel: @"Source"];
1181 [toolbarItem setPaletteLabel: @"Source"];
1182 [toolbarItem setToolTip: @"Choose Video Source"];
1187 hb_get_state2( fQueueEncodeLibhb, &s );
1189 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1191 if ([ident isEqualToString: StartEncodingIdentifier])
1193 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1194 [toolbarItem setLabel: @"Stop"];
1195 [toolbarItem setPaletteLabel: @"Stop"];
1196 [toolbarItem setToolTip: @"Stop Encoding"];
1199 if ([ident isEqualToString: PauseEncodingIdentifier])
1201 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1202 [toolbarItem setLabel: @"Pause"];
1203 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1204 [toolbarItem setToolTip: @"Pause Encoding"];
1209 if ([ident isEqualToString: AddToQueueIdentifier])
1211 if ([ident isEqualToString: ShowPictureIdentifier])
1213 if ([ident isEqualToString: ShowPreviewIdentifier])
1217 else if (s.state == HB_STATE_PAUSED)
1219 if ([ident isEqualToString: PauseEncodingIdentifier])
1221 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1222 [toolbarItem setLabel: @"Resume"];
1223 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1224 [toolbarItem setToolTip: @"Resume Encoding"];
1227 if ([ident isEqualToString: StartEncodingIdentifier])
1229 if ([ident isEqualToString: AddToQueueIdentifier])
1231 if ([ident isEqualToString: ShowPictureIdentifier])
1233 if ([ident isEqualToString: ShowPreviewIdentifier])
1236 else if (s.state == HB_STATE_SCANNING)
1238 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1240 if ([ident isEqualToString: StartEncodingIdentifier])
1242 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1243 if (hb_count(fHandle) > 0)
1244 [toolbarItem setLabel: @"Start Queue"];
1246 [toolbarItem setLabel: @"Start"];
1247 [toolbarItem setPaletteLabel: @"Start Encoding"];
1248 [toolbarItem setToolTip: @"Start Encoding"];
1251 if ([ident isEqualToString: AddToQueueIdentifier])
1253 if ([ident isEqualToString: ShowPictureIdentifier])
1255 if ([ident isEqualToString: ShowPreviewIdentifier])
1260 /* If there are any pending queue items, make sure the start/stop button is active */
1261 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1263 if ([ident isEqualToString: ShowQueueIdentifier])
1265 if ([ident isEqualToString: ToggleDrawerIdentifier])
1267 if ([ident isEqualToString: ChooseSourceIdentifier])
1269 if ([ident isEqualToString: ShowActivityIdentifier])
1275 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1277 SEL action = [menuItem action];
1280 hb_get_state2( fHandle, &s );
1284 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1285 return SuccessfulScan && [fWindow attachedSheet] == nil;
1287 if (action == @selector(browseSources:))
1289 if (s.state == HB_STATE_SCANNING)
1292 return [fWindow attachedSheet] == nil;
1294 if (action == @selector(selectDefaultPreset:))
1295 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1296 if (action == @selector(Pause:))
1298 if (s.state == HB_STATE_WORKING)
1300 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1301 [menuItem setTitle:@"Pause Encoding"];
1304 else if (s.state == HB_STATE_PAUSED)
1306 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1307 [menuItem setTitle:@"Resume Encoding"];
1313 if (action == @selector(Rip:))
1315 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1317 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1318 [menuItem setTitle:@"Stop Encoding"];
1321 else if (SuccessfulScan)
1323 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1324 [menuItem setTitle:@"Start Encoding"];
1325 return [fWindow attachedSheet] == nil;
1331 if( action == @selector(setDefaultPreset:) )
1333 return [fPresetsOutlineView selectedRow] != -1;
1340 #pragma mark Encode Done Actions
1341 // register a test notification and make
1342 // it enabled by default
1343 #define SERVICE_NAME @"Encode Done"
1344 - (NSDictionary *)registrationDictionaryForGrowl
1346 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1347 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1348 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1351 return registrationDictionary;
1354 -(void)showGrowlDoneNotification:(NSString *) filePath
1356 /* This end of encode action is called as each encode rolls off of the queue */
1357 NSString * finishedEncode = filePath;
1358 /* strip off the path to just show the file name */
1359 finishedEncode = [finishedEncode lastPathComponent];
1360 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1361 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1363 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1364 [GrowlApplicationBridge
1365 notifyWithTitle:@"Put down that cocktail..."
1366 description:growlMssg
1367 notificationName:SERVICE_NAME
1375 -(void)sendToMetaX:(NSString *) filePath
1377 /* This end of encode action is called as each encode rolls off of the queue */
1378 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1380 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1381 if (![sendToApp isEqualToString:@"None"])
1383 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1384 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1385 [myScript executeAndReturnError: nil];
1392 #pragma mark Get New Source
1394 /*Opens the source browse window, called from Open Source widgets */
1395 - (IBAction) browseSources: (id) sender
1399 hb_get_state( fHandle, &s );
1400 if (s.state == HB_STATE_SCANNING)
1402 [self cancelScanning:nil];
1407 NSOpenPanel * panel;
1409 panel = [NSOpenPanel openPanel];
1410 [panel setAllowsMultipleSelection: NO];
1411 [panel setCanChooseFiles: YES];
1412 [panel setCanChooseDirectories: YES ];
1413 NSString * sourceDirectory;
1414 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1416 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1420 sourceDirectory = @"~/Desktop";
1421 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1423 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1424 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1426 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1427 modalForWindow: fWindow modalDelegate: self
1428 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1429 contextInfo: sender];
1432 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1433 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1435 /* we convert the sender content of contextInfo back into a variable called sender
1436 * mostly just for consistency for evaluation later
1438 id sender = (id)contextInfo;
1439 /* User selected a file to open */
1440 if( returnCode == NSOKButton )
1442 /* Free display name allocated previously by this code */
1443 [browsedSourceDisplayName release];
1445 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1446 /* we set the last searched source directory in the prefs here */
1447 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1448 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1449 /* we order out sheet, which is the browse window as we need to open
1450 * the title selection sheet right away
1452 [sheet orderOut: self];
1454 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1456 /* We put the chosen source path in the source display text field for the
1457 * source title selection sheet in which the user specifies the specific title to be
1458 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1459 * purposes in the title panel
1462 [fScanSrcTitlePathField setStringValue:scanPath];
1463 NSString *displayTitlescanSourceName;
1465 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1467 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1468 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1469 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1473 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1474 displayTitlescanSourceName = [scanPath lastPathComponent];
1476 /* we set the source display name in the title selection dialogue */
1477 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1478 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1479 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1480 /* We show the actual sheet where the user specifies the title to be scanned
1481 * as we are going to do a title specific scan
1483 [self showSourceTitleScanPanel:nil];
1487 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1488 NSString *path = [[sheet filenames] objectAtIndex: 0];
1490 /* We check to see if the chosen file at path is a package */
1491 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1493 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1494 /* We check to see if this is an .eyetv package */
1495 if ([[path pathExtension] isEqualToString: @"eyetv"])
1497 [self writeToActivityLog:"trying to open eyetv package"];
1498 /* We're looking at an EyeTV package - try to open its enclosed
1500 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1502 int n = [[path stringByAppendingString: @"/"]
1503 completePathIntoString: &mpgname caseSensitive: YES
1504 matchesIntoArray: nil
1505 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1508 /* Found an mpeg inside the eyetv package, make it our scan path
1509 and call performScan on the enclosed mpeg */
1511 [self writeToActivityLog:"found mpeg in eyetv package"];
1512 [self performScan:path scanTitleNum:0];
1516 /* We did not find an mpeg file in our package, so we do not call performScan */
1517 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1520 /* We check to see if this is a .dvdmedia package */
1521 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1523 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1524 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1525 [self writeToActivityLog:"trying to open dvdmedia package"];
1526 [self performScan:path scanTitleNum:0];
1530 /* The package is not an eyetv package, so we do not call performScan */
1531 [self writeToActivityLog:"unable to open package"];
1534 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1536 /* path is not a package, so we call perform scan directly on our file */
1537 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1539 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1540 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1541 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1545 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1546 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1547 /* make sure we remove any path extension as this can also be an '.mpg' file */
1548 browsedSourceDisplayName = [[path lastPathComponent] retain];
1550 applyQueueToScan = NO;
1551 [self performScan:path scanTitleNum:0];
1559 - (IBAction)showAboutPanel:(id)sender
1561 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1562 fApplicationIcon, @"ApplicationIcon",
1564 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1568 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1569 - (IBAction) showSourceTitleScanPanel: (id) sender
1571 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1574 [fScanSrcTitleNumField setStringValue: @"0"];
1575 /* Show the panel */
1576 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1579 - (IBAction) closeSourceTitleScanPanel: (id) sender
1581 [NSApp endSheet: fScanSrcTitlePanel];
1582 [fScanSrcTitlePanel orderOut: self];
1584 if(sender == fScanSrcTitleOpenButton)
1586 /* We setup the scan status in the main window to indicate a source title scan */
1587 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1588 [fScanIndicator setHidden: NO];
1589 [fScanIndicator setIndeterminate: YES];
1590 [fScanIndicator startAnimation: nil];
1592 /* We use the performScan method to actually perform the specified scan passing the path and the title
1595 applyQueueToScan = NO;
1596 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1600 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1601 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1604 /* use a bool to determine whether or not we can decrypt using vlc */
1605 BOOL cancelScanDecrypt = 0;
1607 NSString *path = scanPath;
1608 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1610 // Notify ChapterTitles that there's no title
1611 [fChapterTitlesDelegate resetWithTitle:nil];
1612 [fChapterTable reloadData];
1614 // Notify Subtitles that there's no title
1615 [fSubtitlesDelegate resetWithTitle:nil];
1616 [fSubtitlesTable reloadData];
1618 [self enableUI: NO];
1620 if( [detector isVideoDVD] )
1623 #if defined( __LP64__ )
1632 // The chosen path was actually on a DVD, so use the raw block
1633 // device path instead.
1634 path = [detector devicePath];
1635 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1637 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1638 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1639 NSFileManager * fileManager = [NSFileManager defaultManager];
1640 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1642 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1643 cancelScanDecrypt = 1;
1644 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1646 status = NSRunAlertPanel(@"HandBrake could not find VLC or your VLC is out of date.",@"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");
1647 [NSApp requestUserAttention:NSCriticalRequest];
1649 if (status == NSAlertDefaultReturn)
1651 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1652 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1654 else if (status == NSAlertAlternateReturn)
1656 /* User chose to cancel the scan */
1657 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1661 /* 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 */
1662 cancelScanDecrypt = 0;
1663 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1669 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1670 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1673 /* test for architecture of the vlc app */
1674 NSArray *vlc_architecturesArray = [[NSBundle bundleWithPath:@"/Applications/VLC.app"] executableArchitectures];
1675 BOOL vlcIntel32bit = NO;
1676 BOOL vlcIntel64bit = NO;
1677 BOOL vlcPPC32bit = NO;
1678 BOOL vlcPPC64bit = NO;
1679 /* check the available architectures for vlc and note accordingly */
1680 NSEnumerator *enumerator = [vlc_architecturesArray objectEnumerator];
1682 while (tempObject = [enumerator nextObject])
1685 if ([tempObject intValue] == NSBundleExecutableArchitectureI386)
1687 vlcIntel32bit = YES;
1689 if ([tempObject intValue] == NSBundleExecutableArchitectureX86_64)
1691 vlcIntel64bit = YES;
1693 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC)
1697 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC64)
1703 /* Write vlc architecture findings to activity window */
1706 [self writeToActivityLog: " 32-Bit VLC app found for decrypting physical dvd"];
1710 [self writeToActivityLog: " 64-Bit VLC app found for decrypting physical dvd"];
1715 if (vlcFound && hb_arch == 64 && !vlcIntel64bit && cancelScanDecrypt != 1)
1720 /* Appropriate VLC not found, so cancel */
1721 cancelScanDecrypt = 1;
1722 [self writeToActivityLog: "This version of HandBrake is 64 bit, 64 bit version of vlc not found, scan cancelled"];
1723 /*On Screen Notification*/
1726 status = NSRunAlertPanel(@"This version of HandBrake is 64 bit, VLC found but not 64 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 64 bit VLC", nil);
1727 [NSApp requestUserAttention:NSCriticalRequest];
1729 if (status == NSAlertDefaultReturn)
1731 /* User chose to cancel the scan */
1732 [self writeToActivityLog: "cannot open physical dvd VLC found but not 64 bit, scan cancelled"];
1733 cancelScanDecrypt = 1;
1735 else if (status == NSAlertAlternateReturn)
1737 [self writeToActivityLog: "user overrode 64-bit warning trying to open physical dvd without proper decryption"];
1738 cancelScanDecrypt = 0;
1742 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1743 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1747 else if (vlcFound && hb_arch == 32 && !vlcIntel32bit && cancelScanDecrypt != 1)
1750 /* Appropriate VLC not found, so cancel */
1751 cancelScanDecrypt = 1;
1752 [self writeToActivityLog: "This version of HandBrake is 32 bit, 32 bit version of vlc not found, scan cancelled"];
1753 /*On Screen Notification*/
1756 status = NSRunAlertPanel(@"This version of HandBrake is 32 bit, VLC found but not 32 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 32 bit VLC", nil);
1757 [NSApp requestUserAttention:NSCriticalRequest];
1759 if (status == NSAlertDefaultReturn)
1761 /* User chose to cancel the scan */
1762 [self writeToActivityLog: "cannot open physical dvd VLC found but not 32 bit, scan cancelled"];
1763 cancelScanDecrypt = 1;
1765 else if (status == NSAlertAlternateReturn)
1767 [self writeToActivityLog: "user overrode 32-bit warning trying to open physical dvd without proper decryption"];
1768 cancelScanDecrypt = 0;
1772 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1773 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1779 if (cancelScanDecrypt == 0)
1781 /* we actually pass the scan off to libhb here */
1782 /* If there is no title number passed to scan, we use "0"
1783 * which causes the default behavior of a full source scan
1789 if (scanTitleNum > 0)
1791 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1793 /* We use our advance pref to determine how many previews to scan */
1794 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1795 /* set title to NULL */
1797 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1798 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1802 - (IBAction) cancelScanning:(id)sender
1804 hb_scan_stop(fHandle);
1807 - (IBAction) showNewScan:(id)sender
1811 int indxpri=0; // Used to search the longuest title (default in combobox)
1812 int longuestpri=0; // Used to search the longuest title (default in combobox)
1815 list = hb_get_titles( fHandle );
1817 if( !hb_list_count( list ) )
1819 /* We display a message if a valid dvd source was not chosen */
1820 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1821 SuccessfulScan = NO;
1823 // Notify ChapterTitles that there's no title
1824 [fSubtitlesDelegate resetWithTitle:nil];
1825 [fSubtitlesTable reloadData];
1827 // Notify Subtitles that there's no title
1828 [fChapterTitlesDelegate resetWithTitle:nil];
1829 [fChapterTable reloadData];
1833 if (applyQueueToScan == YES)
1835 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1836 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1839 else if (applyQueueToScan == NO)
1841 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1845 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1848 /* We increment the successful scancount here by one,
1849 which we use at the end of this function to tell the gui
1850 if this is the first successful scan since launch and whether
1851 or not we should set all settings to the defaults */
1852 currentSuccessfulScanCount++;
1854 [[fWindow toolbar] validateVisibleItems];
1856 [fSrcTitlePopUp removeAllItems];
1857 for( int i = 0; i < hb_list_count( list ); i++ )
1859 title = (hb_title_t *) hb_list_item( list, i );
1861 currentSource = [NSString stringWithUTF8String: title->name];
1862 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1863 if (!browsedSourceDisplayName)
1865 browsedSourceDisplayName = @"NoNameDetected";
1867 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1869 /* If its a queue rescan for edit, get the queue item output path */
1870 /* if not, its a new source scan. */
1871 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1872 if (applyQueueToScan == YES)
1874 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1876 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1878 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1879 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1883 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1884 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1888 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1890 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1894 [fSrcTitlePopUp addItemWithTitle: [NSString
1895 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1896 title->name,title->index, title->hours, title->minutes,
1900 /* if we are a stream, select the first title */
1901 if (title->type == HB_STREAM_TYPE)
1903 [fSrcTitlePopUp selectItemAtIndex: 0];
1907 /* if not then select the longest title (dvd) */
1908 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1910 [self titlePopUpChanged:nil];
1912 SuccessfulScan = YES;
1913 [self enableUI: YES];
1915 /* if its the initial successful scan after awakeFromNib */
1916 if (currentSuccessfulScanCount == 1)
1918 [self encodeStartStopPopUpChanged:nil];
1920 [self selectDefaultPreset:nil];
1922 // Open preview window now if it was visible when HB was closed
1923 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1924 [self showPreviewWindow:nil];
1926 // Open picture sizing window now if it was visible when HB was closed
1927 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1928 [self showPicturePanel:nil];
1931 if (applyQueueToScan == YES)
1933 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1934 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1935 [self applyQueueSettingsToMainWindow:nil];
1946 #pragma mark New Output Destination
1948 - (IBAction) browseFile: (id) sender
1950 /* Open a panel to let the user choose and update the text field */
1951 NSSavePanel * panel = [NSSavePanel savePanel];
1952 /* We get the current file name and path from the destination field here */
1953 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1954 modalForWindow: fWindow modalDelegate: self
1955 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1959 - (void) browseFileDone: (NSSavePanel *) sheet
1960 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1962 if( returnCode == NSOKButton )
1964 [fDstFile2Field setStringValue: [sheet filename]];
1965 /* Save this path to the prefs so that on next browse destination window it opens there */
1966 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1967 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1973 #pragma mark Main Window Control
1975 - (IBAction) openMainWindow: (id) sender
1977 [fWindow makeKeyAndOrderFront:nil];
1980 - (BOOL) windowShouldClose: (id) sender
1985 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1988 [fWindow makeKeyAndOrderFront:nil];
1996 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1997 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
2002 #pragma mark Queue File
2004 - (void) loadQueueFile {
2005 /* We declare the default NSFileManager into fileManager */
2006 NSFileManager * fileManager = [NSFileManager defaultManager];
2007 /*We define the location of the user presets file */
2008 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
2009 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
2010 /* We check for the presets.plist */
2011 if ([fileManager fileExistsAtPath:QueueFile] == 0)
2013 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
2016 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
2017 /* lets check to see if there is anything in the queue file .plist */
2018 if (nil == QueueFileArray)
2020 /* if not, then lets initialize an empty array */
2021 QueueFileArray = [[NSMutableArray alloc] init];
2023 /* Initialize our curQueueEncodeIndex to 0
2024 * so we can use it to track which queue
2025 * item is to be used to track our encodes */
2026 /* NOTE: this should be changed if and when we
2027 * are able to get the last unfinished encode
2028 * in the case of a crash or shutdown */
2033 [self clearQueueEncodedItems];
2035 currentQueueEncodeIndex = 0;
2038 - (void)addQueueFileItem
2040 [QueueFileArray addObject:[self createQueueFileItem]];
2041 [self saveQueueFileItem];
2045 - (void) removeQueueFileItem:(int) queueItemToRemove
2048 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
2049 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
2051 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
2052 * by one to keep in sync with the queue array
2054 currentQueueEncodeIndex--;
2055 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
2057 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2058 [self saveQueueFileItem];
2062 - (void)saveQueueFileItem
2064 [QueueFileArray writeToFile:QueueFile atomically:YES];
2065 [fQueueController setQueueArray: QueueFileArray];
2066 [self getQueueStats];
2069 - (void)getQueueStats
2071 /* lets get the stats on the status of the queue array */
2073 fEncodingQueueItem = 0;
2075 fCompletedCount = 0;
2079 /* We use a number system to set the encode status of the queue item
2081 * 0 == already encoded
2082 * 1 == is being encoded
2083 * 2 == is yet to be encoded
2088 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2090 while (tempObject = [enumerator nextObject])
2092 NSDictionary *thisQueueDict = tempObject;
2093 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2097 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2100 fEncodingQueueItem = i;
2102 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2106 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2113 /* Set the queue status field in the main window */
2114 NSMutableString * string;
2115 if (fPendingCount == 1)
2117 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2121 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2123 [fQueueStatus setStringValue:string];
2126 /* This method will set any item marked as encoding back to pending
2127 * currently used right after a queue reload
2129 - (void) setQueueEncodingItemsAsPending
2131 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2133 NSMutableArray *tempArray;
2134 tempArray = [NSMutableArray array];
2135 /* we look here to see if the preset is we move on to the next one */
2136 while ( tempObject = [enumerator nextObject] )
2138 /* If the queue item is marked as "encoding" (1)
2139 * then change its status back to pending (2) which effectively
2140 * puts it back into the queue to be encoded
2142 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2144 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2146 [tempArray addObject:tempObject];
2149 [QueueFileArray setArray:tempArray];
2150 [self saveQueueFileItem];
2154 /* This method will clear the queue of any encodes that are not still pending
2155 * this includes both successfully completed encodes as well as cancelled encodes */
2156 - (void) clearQueueEncodedItems
2158 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2160 NSMutableArray *tempArray;
2161 tempArray = [NSMutableArray array];
2162 /* we look here to see if the preset is we move on to the next one */
2163 while ( tempObject = [enumerator nextObject] )
2165 /* If the queue item is either completed (0) or cancelled (3) from the
2166 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2167 * NOTE: this means we retain pending (2) and also an item that is marked as
2168 * still encoding (1). If the queue has an item that is still marked as encoding
2169 * from a previous session, we can conlude that HB was either shutdown, or crashed
2170 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2172 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2174 [tempArray addObject:tempObject];
2178 [QueueFileArray removeObjectsInArray:tempArray];
2179 [self saveQueueFileItem];
2182 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2183 - (void) clearQueueAllItems
2185 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2187 NSMutableArray *tempArray;
2188 tempArray = [NSMutableArray array];
2189 /* we look here to see if the preset is we move on to the next one */
2190 while ( tempObject = [enumerator nextObject] )
2192 [tempArray addObject:tempObject];
2195 [QueueFileArray removeObjectsInArray:tempArray];
2196 [self saveQueueFileItem];
2199 /* This method will duplicate prepareJob however into the
2200 * queue .plist instead of into the job structure so it can
2201 * be recalled later */
2202 - (NSDictionary *)createQueueFileItem
2204 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2206 hb_list_t * list = hb_get_titles( fHandle );
2207 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2208 [fSrcTitlePopUp indexOfSelectedItem] );
2209 hb_job_t * job = title->job;
2213 /* We use a number system to set the encode status of the queue item
2214 * 0 == already encoded
2215 * 1 == is being encoded
2216 * 2 == is yet to be encoded
2219 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2220 /* Source and Destination Information */
2222 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2223 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2224 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2225 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2227 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2228 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2230 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2232 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2234 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2236 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2238 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2240 /* Chapter encode info */
2241 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2242 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2243 /* Time (pts) encode info */
2244 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2245 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2246 /* Frame number encode info */
2247 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2248 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2251 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2252 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2253 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2255 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2257 /* Lets get the preset info if there is any */
2258 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2259 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2261 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2262 /* Chapter Markers*/
2263 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2264 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2266 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2270 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2273 /* We need to get the list of chapter names to put into an array and store
2274 * in our queue, so they can be reapplied in prepareJob when this queue
2275 * item comes up if Chapter Markers is set to on.
2278 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2279 int chaptercount = hb_list_count( fTitle->list_chapter );
2280 for( i = 0; i < chaptercount; i++ )
2282 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2283 if( chapter != NULL )
2285 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2288 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2289 [ChapterNamesArray autorelease];
2291 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2292 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2293 /* Mux mp4 with http optimization */
2294 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2295 /* Add iPod uuid atom */
2296 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2300 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2301 /* x264 Option String */
2302 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2304 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2305 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2306 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2307 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2309 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2311 /* 2 Pass Encoding */
2312 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2313 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2314 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2316 /* Picture Sizing */
2317 /* Use Max Picture settings for whatever the dvd is.*/
2318 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2319 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2320 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2321 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2322 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2323 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2324 /* if we are custom anamorphic, store the exact storage, par and display dims */
2325 if (fTitle->job->anamorphic.mode == 3)
2327 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2329 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2330 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2332 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2333 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2335 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2336 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2339 NSString * pictureSummary;
2340 pictureSummary = [fPictureSizeField stringValue];
2341 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2342 /* Set crop settings here */
2343 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2344 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2345 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2346 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2347 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2349 /* Picture Filters */
2350 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2351 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2353 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2354 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2355 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2357 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2358 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2360 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2361 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2363 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2365 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2368 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2370 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2371 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2372 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2373 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2374 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2375 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2376 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2378 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2380 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2381 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2382 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2383 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2384 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2385 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2386 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2388 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2390 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2391 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2392 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2393 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2394 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2395 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2396 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2398 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2400 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2401 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2402 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2403 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2404 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2405 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2406 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2410 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2411 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2412 [subtitlesArray autorelease];
2414 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2416 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2418 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2421 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2425 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2428 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2429 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2430 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2432 /* Picture Sizing */
2433 /* Use Max Picture settings for whatever the dvd is.*/
2434 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2435 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2436 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2437 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2438 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2440 /* Set crop settings here */
2441 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2442 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2443 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2444 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2445 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2449 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2451 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2452 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2453 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2454 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2455 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2457 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2459 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2460 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2461 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2462 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2463 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2465 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2467 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2468 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2469 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2470 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2471 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2473 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2475 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2476 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2477 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2478 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2479 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2483 /* we need to auto relase the queueFileJob and return it */
2484 [queueFileJob autorelease];
2485 return queueFileJob;
2489 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2490 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2492 NSUInteger index = [indexSet lastIndex];
2493 NSUInteger aboveInsertIndexCount = 0;
2496 NSUInteger removeIndex;
2498 if (index >= insertIndex)
2500 removeIndex = index + aboveInsertIndexCount;
2501 aboveInsertIndexCount++;
2505 removeIndex = index;
2509 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2510 [QueueFileArray removeObjectAtIndex:removeIndex];
2511 [QueueFileArray insertObject:object atIndex:insertIndex];
2514 index = [indexSet indexLessThanIndex:index];
2516 /* We save all of the Queue data here
2517 * and it also gets sent back to the queue controller*/
2518 [self saveQueueFileItem];
2524 #pragma mark Queue Job Processing
2526 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2528 int i = currentQueueEncodeIndex;
2529 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2531 /* We save all of the Queue data here */
2532 [self saveQueueFileItem];
2533 /* We Reload the New Table data for presets */
2534 //[fPresetsOutlineView reloadData];
2536 /* Since we have now marked a queue item as done
2537 * we can go ahead and increment currentQueueEncodeIndex
2538 * so that if there is anything left in the queue we can
2539 * go ahead and move to the next item if we want to */
2540 currentQueueEncodeIndex++ ;
2541 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2542 int queueItems = [QueueFileArray count];
2543 /* If we still have more items in our queue, lets go to the next one */
2544 if (currentQueueEncodeIndex < queueItems)
2546 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2547 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2551 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2555 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2556 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2558 /* Tell HB to output a new activity log file for this encode */
2559 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2562 /* use a bool to determine whether or not we can decrypt using vlc */
2563 BOOL cancelScanDecrypt = 0;
2564 /* set the bool so that showNewScan knows to apply the appropriate queue
2565 * settings as this is a queue rescan
2567 //applyQueueToScan = YES;
2568 NSString *path = scanPath;
2569 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2571 if( [detector isVideoDVD] )
2573 // The chosen path was actually on a DVD, so use the raw block
2574 // device path instead.
2575 path = [detector devicePath];
2576 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2578 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2579 NSString *vlcPath = @"/Applications/VLC.app";
2580 NSFileManager * fileManager = [NSFileManager defaultManager];
2581 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2583 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2584 cancelScanDecrypt = 1;
2585 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2587 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");
2588 [NSApp requestUserAttention:NSCriticalRequest];
2590 if (status == NSAlertDefaultReturn)
2592 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2593 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2595 else if (status == NSAlertAlternateReturn)
2597 /* User chose to cancel the scan */
2598 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2602 /* 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 */
2603 cancelScanDecrypt = 0;
2604 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2610 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2611 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2615 if (cancelScanDecrypt == 0)
2617 /* we actually pass the scan off to libhb here */
2618 /* If there is no title number passed to scan, we use "0"
2619 * which causes the default behavior of a full source scan
2625 if (scanTitleNum > 0)
2627 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2630 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2631 /* We use our advance pref to determine how many previews to scan */
2632 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2633 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2637 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2638 - (void) processNewQueueEncode
2640 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2641 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2642 hb_job_t * job = title->job;
2644 if( !hb_list_count( list ) )
2646 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2649 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2650 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2651 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2652 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2653 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2657 * If scanning we need to do some extra setup of the job.
2659 if( job->indepth_scan == 1 )
2664 * When subtitle scan is enabled do a fast pre-scan job
2665 * which will determine which subtitles to enable, if any.
2668 x264opts_tmp = job->x264opts;
2670 job->x264opts = NULL;
2672 job->indepth_scan = 1;
2676 * Add the pre-scan job
2678 hb_add( fQueueEncodeLibhb, job );
2679 job->x264opts = x264opts_tmp;
2683 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2685 job->indepth_scan = 0;
2691 hb_add( fQueueEncodeLibhb, job );
2695 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2696 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2698 hb_add( fQueueEncodeLibhb, job );
2703 job->indepth_scan = 0;
2706 hb_add( fQueueEncodeLibhb, job );
2709 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2710 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2711 /* Lets mark our new encode as 1 or "Encoding" */
2712 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2713 [self saveQueueFileItem];
2715 /* we need to clean up the subtitle tracks after the job(s) have been set */
2716 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2718 for(ii = 0; ii < num_subtitle_tracks; ii++)
2720 hb_subtitle_t * subtitle;
2721 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2724 hb_list_rem(job->list_subtitle, subtitle);
2729 /* We should be all setup so let 'er rip */
2736 #pragma mark Queue Item Editing
2738 /* Rescans the chosen queue item back into the main window */
2739 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2741 fqueueEditRescanItemNum = selectedQueueItem;
2742 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2743 applyQueueToScan = YES;
2744 /* Set the browsedSourceDisplayName for showNewScan */
2745 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2746 [self performScan:scanPath scanTitleNum:scanTitleNum];
2750 /* We use this method after a queue item rescan for edit.
2751 * it largely mirrors -selectPreset in terms of structure.
2752 * Assumes that a queue item has been reloaded into the main window.
2754 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2756 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2757 hb_job_t * job = fTitle->job;
2760 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2762 /* Set title number and chapters */
2763 /* since the queue only scans a single title, its already been selected in showNewScan
2764 so do not try to reset it here. However if we do decide to do full source scans on
2765 a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2766 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2768 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2769 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2772 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2773 [self formatPopUpChanged:nil];
2775 /* Chapter Markers*/
2776 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2777 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2778 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2779 /* Mux mp4 with http optimization */
2780 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2783 /* We set the advanced opt string here if applicable*/
2784 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2785 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2787 /* Lets run through the following functions to get variables set there */
2788 [self videoEncoderPopUpChanged:nil];
2789 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2790 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2791 [self calculateBitrate:nil];
2794 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2796 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2797 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2798 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2799 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2800 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2801 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2802 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2803 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2805 /* For the quality slider we need to convert the old percent's to the new rf scales */
2806 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2807 [fVidQualitySlider setFloatValue:rf];
2812 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2813 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2815 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2819 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2820 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2824 [self videoMatrixChanged:nil];
2825 [self writeToActivityLog: "applyQueueSettingsToMainWindow: video matrix changed"];
2826 /* Video framerate */
2827 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2828 detected framerate in the fVidRatePopUp so we use index 0*/
2829 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2831 [fVidRatePopUp selectItemAtIndex: 0];
2835 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2838 /* 2 Pass Encoding */
2839 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2840 [self twoPassCheckboxChanged:nil];
2841 /* Turbo 1st pass for 2 Pass Encoding */
2842 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2847 /* Now lets add our new tracks to the audio list here */
2848 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2850 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2851 [self audioTrackPopUpChanged: fAudLang1PopUp];
2852 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2853 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2855 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2857 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2858 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2860 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2861 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2865 [fAudLang1PopUp selectItemAtIndex: 0];
2866 [self audioTrackPopUpChanged: fAudLang1PopUp];
2868 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2870 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2871 [self audioTrackPopUpChanged: fAudLang2PopUp];
2872 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2873 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2875 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2877 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2878 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2880 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2881 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2885 [fAudLang2PopUp selectItemAtIndex: 0];
2886 [self audioTrackPopUpChanged: fAudLang2PopUp];
2888 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2890 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2891 [self audioTrackPopUpChanged: fAudLang3PopUp];
2892 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2893 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2895 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2897 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2898 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2900 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2901 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2905 [fAudLang3PopUp selectItemAtIndex: 0];
2906 [self audioTrackPopUpChanged: fAudLang3PopUp];
2908 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2910 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2911 [self audioTrackPopUpChanged: fAudLang4PopUp];
2912 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2913 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2915 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2917 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2918 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2920 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2921 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2925 [fAudLang4PopUp selectItemAtIndex: 0];
2926 [self audioTrackPopUpChanged: fAudLang4PopUp];
2929 [self writeToActivityLog: "applyQueueSettingsToMainWindow: audio set up"];
2931 /* Crashy crashy right now, working on it */
2932 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2933 [fSubtitlesTable reloadData];
2934 /* Picture Settings */
2936 /* If Cropping is set to custom, then recall all four crop values from
2937 when the preset was created and apply them */
2938 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2940 [fPictureController setAutoCrop:NO];
2942 /* Here we use the custom crop values saved at the time the preset was saved */
2943 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2944 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2945 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2946 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2949 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2951 [fPictureController setAutoCrop:YES];
2952 /* Here we use the auto crop values determined right after scan */
2953 job->crop[0] = AutoCropTop;
2954 job->crop[1] = AutoCropBottom;
2955 job->crop[2] = AutoCropLeft;
2956 job->crop[3] = AutoCropRight;
2960 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2962 /* we check to make sure the presets width/height does not exceed the sources width/height */
2963 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2965 /* if so, then we use the sources height and width to avoid scaling up */
2966 //job->width = fTitle->width;
2967 //job->height = fTitle->height;
2968 [self revertPictureSizeToMax:nil];
2970 else // source width/height is >= the preset height/width
2972 /* we can go ahead and use the presets values for height and width */
2973 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2974 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2976 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2977 if (job->keep_ratio == 1)
2979 hb_fix_aspect( job, HB_KEEP_WIDTH );
2980 if( job->height > fTitle->height )
2982 job->height = fTitle->height;
2983 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2986 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2987 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2989 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture sizing set up"];
2994 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2995 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2996 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2999 [fPictureController setUseDecomb:1];
3000 [fPictureController setDecomb:0];
3001 [fPictureController setDeinterlace:0];
3002 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3004 /* we are using decomb */
3006 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3008 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3010 /* if we are using "Custom" in the decomb setting, also set the custom string*/
3011 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3013 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
3019 /* We are using Deinterlace */
3021 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3023 [fPictureController setUseDecomb:0];
3024 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3025 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3026 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3028 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
3035 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3037 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3038 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3039 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3041 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
3046 [fPictureController setDetelecine:0];
3050 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3052 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3053 /* if we are using "Custom" in the denoise setting, also set the custom string*/
3054 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3056 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
3061 [fPictureController setDenoise:0];
3065 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3067 /* if its a one, then its the old on/off deblock, set on to 5*/
3068 [fPictureController setDeblock:5];
3072 /* use the settings intValue */
3073 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3076 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3078 [fPictureController setGrayscale:1];
3082 [fPictureController setGrayscale:0];
3085 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3086 [fPictureController SetTitle:fTitle];
3087 [self calculatePictureSizing:nil];
3089 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture filters set up"];
3090 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3091 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3092 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3093 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3095 /* Deselect the currently selected Preset if there is one*/
3096 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3097 //[self selectPreset:nil];
3099 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3100 /* Change UI to show "Custom" settings are being used */
3101 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3103 curUserPresetChosenNum = nil;
3107 /* Deselect the currently selected Preset if there is one*/
3108 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3109 /* Change UI to show "Custom" settings are being used */
3110 [fPresetSelectedDisplay setStringValue: @"Custom"];
3112 //curUserPresetChosenNum = nil;
3115 /* We need to set this bool back to NO, in case the user wants to do a scan */
3116 //applyQueueToScan = NO;
3118 /* Not that source is loaded and settings applied, delete the queue item from the queue */
3119 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3120 [self removeQueueFileItem:fqueueEditRescanItemNum];
3126 #pragma mark Live Preview
3127 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3128 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3131 - (void) prepareJobForPreview
3133 hb_list_t * list = hb_get_titles( fHandle );
3134 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3135 [fSrcTitlePopUp indexOfSelectedItem] );
3136 hb_job_t * job = title->job;
3137 hb_audio_config_t * audio;
3138 /* set job->angle for libdvdnav */
3139 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3140 /* Chapter selection */
3141 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3142 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3144 /* Format (Muxer) and Video Encoder */
3145 job->mux = [[fDstFormatPopUp selectedItem] tag];
3146 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3148 job->chapter_markers = 0;
3150 if( job->vcodec & HB_VCODEC_X264 )
3153 /* Below Sends x264 options to the core library if x264 is selected*/
3154 /* Lets use this as per Nyx, Thanks Nyx!*/
3155 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3156 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3157 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3162 /* Video settings */
3163 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3164 * and detelecine is on, so we handle that in the logic below
3167 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3169 /* a specific framerate has been chosen */
3170 job->vrate = 27000000;
3171 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3172 /* We are not same as source so we set job->cfr to 1
3173 * to enable constant frame rate since user has specified
3174 * a specific framerate*/
3179 /* We are same as source (variable) */
3180 job->vrate = title->rate;
3181 job->vrate_base = title->rate_base;
3182 /* We are same as source so we set job->cfr to 0
3183 * to enable true same as source framerate */
3185 /* If we are same as source and we have detelecine on, we need to turn on
3188 if ([fPictureController detelecine] == 1)
3194 switch( [fVidQualityMatrix selectedRow] )
3198 Bitrate should already have been calculated and displayed
3199 in fVidBitrateField, so let's just use it */
3201 job->vquality = -1.0;
3202 job->vbitrate = [fVidBitrateField intValue];
3205 job->vquality = [fVidQualityRFField floatValue];
3210 /* Subtitle settings */
3211 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3218 bool one_burned = FALSE;
3221 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3223 while (tempObject = [enumerator nextObject])
3226 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3227 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3228 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3229 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3231 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3232 * we want to ignore it for display as well as encoding.
3236 /* if i is 0, then we are in the first item of the subtitles which we need to
3237 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3238 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3241 /* if we are on the first track and using "Foreign Audio Search" */
3242 if (i == 0 && subtitle == 1)
3244 /* NOTE: Currently foreign language search is borked for preview.
3245 * Commented out but left in for initial commit. */
3248 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3250 job->indepth_scan = 1;
3251 if (burned == 1 || job->mux != HB_MUX_MP4)
3253 if (burned != 1 && job->mux == HB_MUX_MKV)
3255 job->select_subtitle_config.dest = PASSTHRUSUB;
3259 job->select_subtitle_config.dest = RENDERSUB;
3262 job->select_subtitle_config.force = force;
3263 job->select_subtitle_config.default_track = def;
3272 /* for the actual source tracks, we must subtract the non source entries so
3273 * that the menu index matches the source subtitle_list index for convenience */
3276 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3277 * Foreign Language Search is 1) so subtract 2 */
3278 subtitle = subtitle - 2;
3282 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3285 subtitle = subtitle - 1;
3288 /* We are setting a source subtitle so access the source subtitle info */
3289 hb_subtitle_t * subt;
3291 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3293 /* if we are getting the subtitles from an external srt file */
3294 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3296 hb_subtitle_config_t sub_config;
3298 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3300 /* we need to srncpy file path and char code */
3301 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3302 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3304 sub_config.force = 0;
3305 sub_config.dest = PASSTHRUSUB;
3306 sub_config.default_track = def;
3308 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3313 hb_subtitle_config_t sub_config = subt->config;
3315 if (!burned && job->mux == HB_MUX_MKV &&
3316 subt->format == PICTURESUB)
3318 sub_config.dest = PASSTHRUSUB;
3320 else if (!burned && job->mux == HB_MUX_MP4 &&
3321 subt->format == PICTURESUB)
3323 // Skip any non-burned vobsubs when output is mp4
3326 else if ( burned && subt->format == PICTURESUB )
3328 // Only allow one subtitle to be burned into the video
3333 sub_config.force = force;
3334 sub_config.default_track = def;
3335 hb_subtitle_add( job, &sub_config, subtitle );
3345 [subtitlesArray autorelease];
3348 /* Audio tracks and mixdowns */
3349 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3350 int audiotrack_count = hb_list_count(job->list_audio);
3351 for( int i = 0; i < audiotrack_count;i++)
3353 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3354 hb_list_rem(job->list_audio, temp_audio);
3356 /* Now lets add our new tracks to the audio list here */
3357 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3359 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3360 hb_audio_config_init(audio);
3361 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3362 /* We go ahead and assign values to our audio->out.<properties> */
3363 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3364 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3365 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3366 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3367 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3368 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3370 hb_audio_add( job, audio );
3373 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3375 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3376 hb_audio_config_init(audio);
3377 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3378 /* We go ahead and assign values to our audio->out.<properties> */
3379 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3380 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3381 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3382 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3383 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3384 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3386 hb_audio_add( job, audio );
3391 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3393 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3394 hb_audio_config_init(audio);
3395 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3396 /* We go ahead and assign values to our audio->out.<properties> */
3397 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3398 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3399 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3400 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3401 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3402 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3404 hb_audio_add( job, audio );
3409 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3411 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3412 hb_audio_config_init(audio);
3413 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3414 /* We go ahead and assign values to our audio->out.<properties> */
3415 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3416 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3417 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3418 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3419 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3420 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3422 hb_audio_add( job, audio );
3431 /* Though Grayscale is not really a filter, per se
3432 * we put it here since its in the filters panel
3435 if ([fPictureController grayscale])
3444 /* Initialize the filters list */
3445 job->filters = hb_list_init();
3447 /* Now lets call the filters if applicable.
3448 * The order of the filters is critical
3452 if ([fPictureController detelecine] == 1)
3454 /* use a custom detelecine string */
3455 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3456 hb_list_add( job->filters, &hb_filter_detelecine );
3458 if ([fPictureController detelecine] == 2)
3461 hb_list_add( job->filters, &hb_filter_detelecine );
3466 if ([fPictureController useDecomb] == 1)
3469 /* we add the custom string if present */
3470 if ([fPictureController decomb] == 1)
3472 /* use a custom decomb string */
3473 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3474 hb_list_add( job->filters, &hb_filter_decomb );
3476 if ([fPictureController decomb] == 2)
3478 /* Run old deinterlacer fd by default */
3479 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3480 hb_list_add( job->filters, &hb_filter_decomb );
3487 if ([fPictureController deinterlace] == 1)
3489 /* we add the custom string if present */
3490 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3491 hb_list_add( job->filters, &hb_filter_deinterlace );
3493 else if ([fPictureController deinterlace] == 2)
3495 /* Run old deinterlacer fd by default */
3496 hb_filter_deinterlace.settings = "-1";
3497 hb_list_add( job->filters, &hb_filter_deinterlace );
3499 else if ([fPictureController deinterlace] == 3)
3501 /* Yadif mode 0 (without spatial deinterlacing.) */
3502 hb_filter_deinterlace.settings = "2";
3503 hb_list_add( job->filters, &hb_filter_deinterlace );
3505 else if ([fPictureController deinterlace] == 4)
3507 /* Yadif (with spatial deinterlacing) */
3508 hb_filter_deinterlace.settings = "0";
3509 hb_list_add( job->filters, &hb_filter_deinterlace );
3515 if ([fPictureController denoise] == 1) // custom in popup
3517 /* we add the custom string if present */
3518 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3519 hb_list_add( job->filters, &hb_filter_denoise );
3521 else if ([fPictureController denoise] == 2) // Weak in popup
3523 hb_filter_denoise.settings = "2:1:2:3";
3524 hb_list_add( job->filters, &hb_filter_denoise );
3526 else if ([fPictureController denoise] == 3) // Medium in popup
3528 hb_filter_denoise.settings = "3:2:2:3";
3529 hb_list_add( job->filters, &hb_filter_denoise );
3531 else if ([fPictureController denoise] == 4) // Strong in popup
3533 hb_filter_denoise.settings = "7:7:5:5";
3534 hb_list_add( job->filters, &hb_filter_denoise );
3538 /* Deblock (uses pp7 default) */
3539 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3540 * the macgui's purposes a value of 0 actually means to not even use the filter
3541 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3543 if ([fPictureController deblock] != 0)
3545 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3546 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3547 hb_list_add( job->filters, &hb_filter_deblock );
3554 #pragma mark Job Handling
3560 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3561 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3562 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3563 hb_job_t * job = title->job;
3564 hb_audio_config_t * audio;
3565 /* Title Angle for dvdnav */
3566 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3568 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3570 /* Chapter selection */
3571 [self writeToActivityLog: "Start / Stop set to chapters"];
3572 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3573 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3575 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3577 /* we are pts based start / stop */
3578 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3580 /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3581 * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3583 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3584 /* get the start seconds from the start seconds field */
3585 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3586 //job->start_at_preview = start_seconds;
3587 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3588 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3589 job->pts_to_start = start_seconds * 90000LL;
3590 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3591 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3592 job->pts_to_stop = stop_seconds * 90000LL;
3594 /* A bunch of verbose activity log messages to check on what should be expected */
3595 [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3596 [self writeToActivityLog: "point a to b should start at (hh:mm:ss): %d:%d:%d", start_seconds / 3600, ( start_seconds / 60 ) % 60,start_seconds % 60];
3597 [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3598 [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3599 [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3600 [self writeToActivityLog: "point a to b should end at (hh:mm:ss): %d:%d:%d", (start_seconds + stop_seconds) / 3600, ( (start_seconds + stop_seconds) / 60 ) % 60,(start_seconds + stop_seconds) % 60];
3602 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3604 /* we are frame based start / stop */
3605 [self writeToActivityLog: "Start / Stop set to frames ..."];
3607 /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3608 * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3610 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3611 /* get the start seconds from the start seconds field */
3612 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3613 //job->start_at_preview = start_seconds;
3614 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3615 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3616 job->frame_to_start = start_frame;
3617 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3618 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3619 job->frame_to_stop = stop_frame;
3621 /* A bunch of verbose activity log messages to check on what should be expected */
3622 [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3623 [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3624 [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3630 /* Format (Muxer) and Video Encoder */
3631 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3632 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3635 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3636 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3638 job->largeFileSize = 1;
3642 job->largeFileSize = 0;
3644 /* We set http optimized mp4 here */
3645 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3647 job->mp4_optimize = 1;
3651 job->mp4_optimize = 0;
3655 /* We set the chapter marker extraction here based on the format being
3656 mpeg4 or mkv and the checkbox being checked */
3657 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3659 job->chapter_markers = 1;
3661 /* now lets get our saved chapter names out the array in the queue file
3662 * and insert them back into the title chapter list. We have it here,
3663 * because unless we are inserting chapter markers there is no need to
3664 * spend the overhead of iterating through the chapter names array imo
3665 * Also, note that if for some reason we don't apply chapter names, the
3666 * chapters just come out 001, 002, etc. etc.
3669 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3671 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3673 while (tempObject = [enumerator nextObject])
3675 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3676 if( chapter != NULL )
3678 strncpy( chapter->title, [tempObject UTF8String], 1023);
3679 chapter->title[1023] = '\0';
3686 job->chapter_markers = 0;
3689 if( job->vcodec & HB_VCODEC_X264 )
3691 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3701 /* Below Sends x264 options to the core library if x264 is selected*/
3702 /* Lets use this as per Nyx, Thanks Nyx!*/
3703 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3704 /* Turbo first pass if two pass and Turbo First pass is selected */
3705 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3707 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3708 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3709 /* append the "Turbo" string variable to the existing opts string.
3710 Note: the "Turbo" string must be appended, not prepended to work properly*/
3711 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3712 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3716 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3722 /* Picture Size Settings */
3723 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3724 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3726 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3727 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3728 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3729 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3731 /* insert our custom values here for capuj */
3732 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3733 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3735 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3737 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3738 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3740 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3741 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3744 /* Here we use the crop values saved at the time the preset was saved */
3745 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3746 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3747 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3748 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3750 /* Video settings */
3753 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3754 * and detelecine is on, so we handle that in the logic below
3757 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3759 /* a specific framerate has been chosen */
3760 job->vrate = 27000000;
3761 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3762 /* We are not same as source so we set job->cfr to 1
3763 * to enable constant frame rate since user has specified
3764 * a specific framerate*/
3769 /* We are same as source (variable) */
3770 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3771 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3772 /* We are same as source so we set job->cfr to 0
3773 * to enable true same as source framerate */
3775 /* If we are same as source and we have detelecine on, we need to turn on
3778 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3784 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3787 Bitrate should already have been calculated and displayed
3788 in fVidBitrateField, so let's just use it same as abr*/
3789 job->vquality = -1.0;
3790 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3792 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3794 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3799 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3804 #pragma mark Process Subtitles to libhb
3806 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3807 * which means that we need to account for the offset of non source language settings in from
3808 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3809 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3810 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3811 * to the source tracks position in title->list_subtitle.
3818 bool one_burned = FALSE;
3821 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3823 while (tempObject = [enumerator nextObject])
3826 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3827 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3828 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3829 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3831 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3832 * we want to ignore it for display as well as encoding.
3836 /* if i is 0, then we are in the first item of the subtitles which we need to
3837 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3838 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3841 /* if we are on the first track and using "Foreign Audio Search" */
3842 if (i == 0 && subtitle == 1)
3844 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3846 job->indepth_scan = 1;
3847 if (burned == 1 || job->mux != HB_MUX_MP4)
3849 if (burned != 1 && job->mux == HB_MUX_MKV)
3851 job->select_subtitle_config.dest = PASSTHRUSUB;
3855 job->select_subtitle_config.dest = RENDERSUB;
3858 job->select_subtitle_config.force = force;
3859 job->select_subtitle_config.default_track = def;
3867 /* for the actual source tracks, we must subtract the non source entries so
3868 * that the menu index matches the source subtitle_list index for convenience */
3871 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3872 * Foreign Language Search is 1) so subtract 2 */
3873 subtitle = subtitle - 2;
3877 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3880 subtitle = subtitle - 1;
3883 /* We are setting a source subtitle so access the source subtitle info */
3884 hb_subtitle_t * subt;
3886 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3888 /* if we are getting the subtitles from an external srt file */
3889 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3891 hb_subtitle_config_t sub_config;
3893 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3895 /* we need to srncpy file name and codeset */
3896 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3897 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3899 sub_config.force = 0;
3900 sub_config.dest = PASSTHRUSUB;
3901 sub_config.default_track = def;
3903 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3909 hb_subtitle_config_t sub_config = subt->config;
3911 if (!burned && job->mux == HB_MUX_MKV &&
3912 subt->format == PICTURESUB)
3914 sub_config.dest = PASSTHRUSUB;
3916 else if (!burned && job->mux == HB_MUX_MP4 &&
3917 subt->format == PICTURESUB)
3919 // Skip any non-burned vobsubs when output is mp4
3922 else if ( burned && subt->format == PICTURESUB )
3924 // Only allow one subtitle to be burned into the video
3929 sub_config.force = force;
3930 sub_config.default_track = def;
3931 hb_subtitle_add( job, &sub_config, subtitle );
3942 /* Audio tracks and mixdowns */
3943 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3944 int audiotrack_count = hb_list_count(job->list_audio);
3945 for( int i = 0; i < audiotrack_count;i++)
3947 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3948 hb_list_rem(job->list_audio, temp_audio);
3950 /* Now lets add our new tracks to the audio list here */
3951 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3953 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3954 hb_audio_config_init(audio);
3955 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3956 /* We go ahead and assign values to our audio->out.<properties> */
3957 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3958 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3959 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3960 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3961 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3962 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3964 hb_audio_add( job, audio );
3967 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3970 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3971 hb_audio_config_init(audio);
3972 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3973 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3974 /* We go ahead and assign values to our audio->out.<properties> */
3975 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3976 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3977 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3978 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3979 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3980 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3982 hb_audio_add( job, audio );
3986 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3988 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3989 hb_audio_config_init(audio);
3990 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3991 /* We go ahead and assign values to our audio->out.<properties> */
3992 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3993 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3994 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3995 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3996 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3997 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3999 hb_audio_add( job, audio );
4003 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
4005 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4006 hb_audio_config_init(audio);
4007 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4008 /* We go ahead and assign values to our audio->out.<properties> */
4009 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4010 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
4011 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
4012 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
4013 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
4014 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
4016 hb_audio_add( job, audio );
4022 job->filters = hb_list_init();
4024 /* Now lets call the filters if applicable.
4025 * The order of the filters is critical
4028 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4030 /* use a custom detelecine string */
4031 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4032 hb_list_add( job->filters, &hb_filter_detelecine );
4034 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4036 /* Use libhb's default values */
4037 hb_list_add( job->filters, &hb_filter_detelecine );
4040 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4043 /* we add the custom string if present */
4044 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4046 /* use a custom decomb string */
4047 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4048 hb_list_add( job->filters, &hb_filter_decomb );
4050 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4052 /* Use libhb default */
4053 hb_list_add( job->filters, &hb_filter_decomb );
4061 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4063 /* we add the custom string if present */
4064 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4065 hb_list_add( job->filters, &hb_filter_deinterlace );
4067 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4069 /* Run old deinterlacer fd by default */
4070 hb_filter_deinterlace.settings = "-1";
4071 hb_list_add( job->filters, &hb_filter_deinterlace );
4073 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4075 /* Yadif mode 0 (without spatial deinterlacing.) */
4076 hb_filter_deinterlace.settings = "2";
4077 hb_list_add( job->filters, &hb_filter_deinterlace );
4079 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4081 /* Yadif (with spatial deinterlacing) */
4082 hb_filter_deinterlace.settings = "0";
4083 hb_list_add( job->filters, &hb_filter_deinterlace );
4089 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4091 /* we add the custom string if present */
4092 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4093 hb_list_add( job->filters, &hb_filter_denoise );
4095 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4097 hb_filter_denoise.settings = "2:1:2:3";
4098 hb_list_add( job->filters, &hb_filter_denoise );
4100 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4102 hb_filter_denoise.settings = "3:2:2:3";
4103 hb_list_add( job->filters, &hb_filter_denoise );
4105 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4107 hb_filter_denoise.settings = "7:7:5:5";
4108 hb_list_add( job->filters, &hb_filter_denoise );
4112 /* Deblock (uses pp7 default) */
4113 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
4114 * the macgui's purposes a value of 0 actually means to not even use the filter
4115 * current hb_filter_deblock.settings valid ranges are from 5 - 15
4117 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4119 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4120 hb_list_add( job->filters, &hb_filter_deblock );
4122 [self writeToActivityLog: "prepareJob exiting"];
4127 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4129 - (IBAction) addToQueue: (id) sender
4131 /* We get the destination directory from the destination field here */
4132 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4133 /* We check for a valid destination here */
4134 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4136 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4143 BOOL fileExistsInQueue;
4144 fileExistsInQueue = NO;
4146 /* We check for and existing file here */
4147 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4152 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4154 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4156 while (tempObject = [enumerator nextObject])
4158 NSDictionary *thisQueueDict = tempObject;
4159 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4161 fileExistsInQueue = YES;
4167 if(fileExists == YES)
4169 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4170 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4171 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4172 NULL, NULL, [NSString stringWithFormat:
4173 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4174 [fDstFile2Field stringValue]] );
4176 else if (fileExistsInQueue == YES)
4178 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4179 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4180 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4181 NULL, NULL, [NSString stringWithFormat:
4182 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4183 [fDstFile2Field stringValue]] );
4187 [self doAddToQueue];
4191 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4192 the user if they want to overwrite an exiting movie file.
4194 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4195 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4197 if( returnCode == NSAlertAlternateReturn )
4198 [self doAddToQueue];
4201 - (void) doAddToQueue
4203 [self addQueueFileItem ];
4208 /* Rip: puts up an alert before ultimately calling doRip
4210 - (IBAction) Rip: (id) sender
4212 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4213 /* Rip or Cancel ? */
4215 hb_get_state2( fQueueEncodeLibhb, &s );
4217 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4219 [self Cancel: sender];
4223 /* We check to see if we need to warn the user that the computer will go to sleep
4224 or shut down when encoding is finished */
4225 [self remindUserOfSleepOrShutdown];
4227 // If there are pending jobs in the queue, then this is a rip the queue
4228 if (fPendingCount > 0)
4230 /* here lets start the queue with the first pending item */
4231 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4236 // Before adding jobs to the queue, check for a valid destination.
4238 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4239 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4241 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4245 /* We check for duplicate name here */
4246 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4248 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4249 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4250 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4251 NULL, NULL, [NSString stringWithFormat:
4252 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4253 [fDstFile2Field stringValue]] );
4255 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4259 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4260 otherwise, just rip the queue */
4261 if(fPendingCount == 0)
4263 [self doAddToQueue];
4266 /* go right to processing the new queue encode */
4267 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4272 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4273 want to overwrite an exiting movie file.
4275 - (void) overWriteAlertDone: (NSWindow *) sheet
4276 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4278 if( returnCode == NSAlertAlternateReturn )
4280 /* if there are no jobs in the queue, then add this one to the queue and rip
4281 otherwise, just rip the queue */
4282 if( fPendingCount == 0 )
4284 [self doAddToQueue];
4287 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4288 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4289 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4294 - (void) remindUserOfSleepOrShutdown
4296 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4298 /*Warn that computer will sleep after encoding*/
4301 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);
4302 [NSApp requestUserAttention:NSCriticalRequest];
4303 if ( reminduser == NSAlertAlternateReturn )
4305 [self showPreferencesWindow:nil];
4308 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4310 /*Warn that computer will shut down after encoding*/
4313 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);
4314 [NSApp requestUserAttention:NSCriticalRequest];
4315 if ( reminduser == NSAlertAlternateReturn )
4317 [self showPreferencesWindow:nil];
4326 /* Let libhb do the job */
4327 hb_start( fQueueEncodeLibhb );
4328 /*set the fEncodeState State */
4333 //------------------------------------------------------------------------------------
4334 // Displays an alert asking user if the want to cancel encoding of current job.
4335 // Cancel: returns immediately after posting the alert. Later, when the user
4336 // acknowledges the alert, doCancelCurrentJob is called.
4337 //------------------------------------------------------------------------------------
4338 - (IBAction)Cancel: (id)sender
4340 if (!fQueueController) return;
4342 hb_pause( fQueueEncodeLibhb );
4343 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4345 // Which window to attach the sheet to?
4346 NSWindow * docWindow;
4347 if ([sender respondsToSelector: @selector(window)])
4348 docWindow = [sender window];
4350 docWindow = fWindow;
4352 NSBeginCriticalAlertSheet(
4354 NSLocalizedString(@"Continue Encoding", nil),
4355 NSLocalizedString(@"Cancel Current and Stop", nil),
4356 NSLocalizedString(@"Cancel Current and Continue", nil),
4358 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4359 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4361 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4364 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4366 hb_resume( fQueueEncodeLibhb );
4367 if (returnCode == NSAlertOtherReturn)
4369 [self doCancelCurrentJob]; // <- this also stops libhb
4371 if (returnCode == NSAlertAlternateReturn)
4373 [self doCancelCurrentJobAndStop];
4377 //------------------------------------------------------------------------------------
4378 // Cancels and deletes the current job and stops libhb from processing the remaining
4380 //------------------------------------------------------------------------------------
4381 - (void) doCancelCurrentJob
4383 // Stop the current job. hb_stop will only cancel the current pass and then set
4384 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4385 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4386 // remaining passes of the job and then start the queue back up if there are any
4390 hb_stop( fQueueEncodeLibhb );
4392 // Delete all remaining jobs since libhb doesn't do this on its own.
4394 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4395 hb_rem( fQueueEncodeLibhb, job );
4397 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4399 // now that we've stopped the currently encoding job, lets mark it as cancelled
4400 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4401 // and as always, save it in the queue .plist...
4402 /* We save all of the Queue data here */
4403 [self saveQueueFileItem];
4404 // so now lets move to
4405 currentQueueEncodeIndex++ ;
4406 // ... and see if there are more items left in our queue
4407 int queueItems = [QueueFileArray count];
4408 /* If we still have more items in our queue, lets go to the next one */
4409 if (currentQueueEncodeIndex < queueItems)
4411 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4412 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4414 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4418 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4423 - (void) doCancelCurrentJobAndStop
4425 hb_stop( fQueueEncodeLibhb );
4427 // Delete all remaining jobs since libhb doesn't do this on its own.
4429 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4430 hb_rem( fQueueEncodeLibhb, job );
4433 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4435 // now that we've stopped the currently encoding job, lets mark it as cancelled
4436 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4437 // and as always, save it in the queue .plist...
4438 /* We save all of the Queue data here */
4439 [self saveQueueFileItem];
4440 // so now lets move to
4441 currentQueueEncodeIndex++ ;
4442 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4444 - (IBAction) Pause: (id) sender
4447 hb_get_state2( fQueueEncodeLibhb, &s );
4449 if( s.state == HB_STATE_PAUSED )
4451 hb_resume( fQueueEncodeLibhb );
4455 hb_pause( fQueueEncodeLibhb );
4460 #pragma mark GUI Controls Changed Methods
4462 - (IBAction) titlePopUpChanged: (id) sender
4464 hb_list_t * list = hb_get_titles( fHandle );
4465 hb_title_t * title = (hb_title_t*)
4466 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4468 /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4469 if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4471 /* we set the default name according to the new title->name */
4472 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4473 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4474 [NSString stringWithUTF8String: title->name],
4475 [[fDstFile2Field stringValue] pathExtension]]];
4477 /* Change the source to read out the parent folder also */
4478 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4481 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4482 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4483 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4484 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4485 /* 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 */
4486 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4487 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4488 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4490 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4491 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4493 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4494 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4495 [browsedSourceDisplayName stringByDeletingPathExtension],
4497 [[fDstFile2Field stringValue] pathExtension]]];
4499 /* Update encode start / stop variables */
4503 /* Update chapter popups */
4504 [fSrcChapterStartPopUp removeAllItems];
4505 [fSrcChapterEndPopUp removeAllItems];
4506 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4508 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4509 stringWithFormat: @"%d", i + 1]];
4510 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4511 stringWithFormat: @"%d", i + 1]];
4514 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4515 [fSrcChapterEndPopUp selectItemAtIndex:
4516 hb_list_count( title->list_chapter ) - 1];
4517 [self chapterPopUpChanged:nil];
4519 /* if using dvd nav, show the angle widget */
4520 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4522 [fSrcAngleLabel setHidden:NO];
4523 [fSrcAnglePopUp setHidden:NO];
4525 [fSrcAnglePopUp removeAllItems];
4526 for( int i = 0; i < title->angle_count; i++ )
4528 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4530 [fSrcAnglePopUp selectItemAtIndex: 0];
4534 [fSrcAngleLabel setHidden:YES];
4535 [fSrcAnglePopUp setHidden:YES];
4538 /* Start Get and set the initial pic size for display */
4539 hb_job_t * job = title->job;
4542 /* Set Auto Crop to on upon selecting a new title */
4543 [fPictureController setAutoCrop:YES];
4545 /* We get the originial output picture width and height and put them
4546 in variables for use with some presets later on */
4547 PicOrigOutputWidth = job->width;
4548 PicOrigOutputHeight = job->height;
4549 AutoCropTop = job->crop[0];
4550 AutoCropBottom = job->crop[1];
4551 AutoCropLeft = job->crop[2];
4552 AutoCropRight = job->crop[3];
4554 /* Reset the new title in fPictureController && fPreviewController*/
4555 [fPictureController SetTitle:title];
4558 /* Update Subtitle Table */
4559 [fSubtitlesDelegate resetWithTitle:title];
4560 [fSubtitlesTable reloadData];
4563 /* Update chapter table */
4564 [fChapterTitlesDelegate resetWithTitle:title];
4565 [fChapterTable reloadData];
4567 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4568 int audiotrack_count = hb_list_count(job->list_audio);
4569 for( int i = 0; i < audiotrack_count;i++)
4571 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4572 hb_list_rem(job->list_audio, temp_audio);
4575 /* Update audio popups */
4576 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4577 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4578 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4579 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4580 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4581 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4582 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4583 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4584 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4585 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4587 /* changing the title may have changed the audio channels on offer, */
4588 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4589 [self audioTrackPopUpChanged: fAudLang1PopUp];
4590 [self audioTrackPopUpChanged: fAudLang2PopUp];
4591 [self audioTrackPopUpChanged: fAudLang3PopUp];
4592 [self audioTrackPopUpChanged: fAudLang4PopUp];
4594 [fVidRatePopUp selectItemAtIndex: 0];
4596 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4597 [self calculatePictureSizing:nil];
4599 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4600 [self selectPreset:nil];
4603 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4605 if( [fEncodeStartStopPopUp isEnabled] )
4607 /* We are chapters */
4608 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4610 [fSrcChapterStartPopUp setHidden: NO];
4611 [fSrcChapterEndPopUp setHidden: NO];
4613 [fSrcTimeStartEncodingField setHidden: YES];
4614 [fSrcTimeEndEncodingField setHidden: YES];
4616 [fSrcFrameStartEncodingField setHidden: YES];
4617 [fSrcFrameEndEncodingField setHidden: YES];
4619 [self chapterPopUpChanged:nil];
4621 /* We are time based (seconds) */
4622 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4624 [fSrcChapterStartPopUp setHidden: YES];
4625 [fSrcChapterEndPopUp setHidden: YES];
4627 [fSrcTimeStartEncodingField setHidden: NO];
4628 [fSrcTimeEndEncodingField setHidden: NO];
4630 [fSrcFrameStartEncodingField setHidden: YES];
4631 [fSrcFrameEndEncodingField setHidden: YES];
4633 [self startEndSecValueChanged:nil];
4635 /* We are frame based */
4636 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4638 [fSrcChapterStartPopUp setHidden: YES];
4639 [fSrcChapterEndPopUp setHidden: YES];
4641 [fSrcTimeStartEncodingField setHidden: YES];
4642 [fSrcTimeEndEncodingField setHidden: YES];
4644 [fSrcFrameStartEncodingField setHidden: NO];
4645 [fSrcFrameEndEncodingField setHidden: NO];
4647 [self startEndFrameValueChanged:nil];
4652 - (IBAction) chapterPopUpChanged: (id) sender
4655 /* If start chapter popup is greater than end chapter popup,
4656 we set the end chapter popup to the same as start chapter popup */
4657 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4659 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4663 hb_list_t * list = hb_get_titles( fHandle );
4664 hb_title_t * title = (hb_title_t *)
4665 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4667 hb_chapter_t * chapter;
4668 int64_t duration = 0;
4669 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4670 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4672 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4673 duration += chapter->duration;
4676 duration /= 90000; /* pts -> seconds */
4677 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4678 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4681 [self calculateBitrate: sender];
4683 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4685 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4686 [fCreateChapterMarkers setEnabled: NO];
4687 [fCreateChapterMarkers setState: NSOffState];
4691 [fCreateChapterMarkers setEnabled: YES];
4695 - (IBAction) startEndSecValueChanged: (id) sender
4698 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4699 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4700 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4703 //[self calculateBitrate: sender];
4707 - (IBAction) startEndFrameValueChanged: (id) sender
4709 hb_list_t * list = hb_get_titles( fHandle );
4710 hb_title_t * title = (hb_title_t*)
4711 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4713 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4714 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4715 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4718 //[self calculateBitrate: sender];
4722 - (IBAction) formatPopUpChanged: (id) sender
4724 NSString * string = [fDstFile2Field stringValue];
4725 int format = [fDstFormatPopUp indexOfSelectedItem];
4727 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4728 [fDstMp4LargeFileCheck setHidden: YES];
4729 [fDstMp4HttpOptFileCheck setHidden: YES];
4730 [fDstMp4iPodFileCheck setHidden: YES];
4732 /* Update the Video Codec PopUp */
4733 /* lets get the tag of the currently selected item first so we might reset it later */
4734 int selectedVidEncoderTag;
4735 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4737 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4738 [fVidEncoderPopUp removeAllItems];
4739 NSMenuItem *menuItem;
4740 /* These video encoders are available to all of our current muxers, so lets list them once here */
4741 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4742 [menuItem setTag: HB_VCODEC_FFMPEG];
4747 /*Get Default MP4 File Extension*/
4748 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4756 /* Add additional video encoders here */
4757 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4758 [menuItem setTag: HB_VCODEC_X264];
4759 /* We show the mp4 option checkboxes here since we are mp4 */
4760 [fCreateChapterMarkers setEnabled: YES];
4761 [fDstMp4LargeFileCheck setHidden: NO];
4762 [fDstMp4HttpOptFileCheck setHidden: NO];
4763 [fDstMp4iPodFileCheck setHidden: NO];
4768 /* Add additional video encoders here */
4769 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4770 [menuItem setTag: HB_VCODEC_X264];
4771 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4772 [menuItem setTag: HB_VCODEC_THEORA];
4773 /* We enable the create chapters checkbox here */
4774 [fCreateChapterMarkers setEnabled: YES];
4779 /* tell fSubtitlesDelegate we have a new video container */
4781 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4782 [fSubtitlesTable reloadData];
4783 /* if we have a previously selected vid encoder tag, then try to select it */
4784 if (selectedVidEncoderTag)
4786 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4790 [fVidEncoderPopUp selectItemAtIndex: 0];
4793 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4794 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4795 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4796 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4799 [self autoSetM4vExtension: sender];
4801 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4803 if( SuccessfulScan )
4805 /* Add/replace to the correct extension */
4806 [self audioTrackPopUpChanged: fAudLang1PopUp];
4807 [self audioTrackPopUpChanged: fAudLang2PopUp];
4808 [self audioTrackPopUpChanged: fAudLang3PopUp];
4809 [self audioTrackPopUpChanged: fAudLang4PopUp];
4811 if( [fVidEncoderPopUp selectedItem] == nil )
4814 [fVidEncoderPopUp selectItemAtIndex:0];
4815 [self videoEncoderPopUpChanged:nil];
4817 /* changing the format may mean that we can / can't offer mono or 6ch, */
4818 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4820 /* We call the method to properly enable/disable turbo 2 pass */
4821 [self twoPassCheckboxChanged: sender];
4822 /* We call method method to change UI to reflect whether a preset is used or not*/
4825 [self customSettingUsed: sender];
4828 - (IBAction) autoSetM4vExtension: (id) sender
4830 if ( [fDstFormatPopUp indexOfSelectedItem] )
4833 NSString * extension = @"mp4";
4835 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4836 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4837 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4838 [fCreateChapterMarkers state] == NSOnState ||
4839 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4844 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4847 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4848 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4851 /* Method to determine if we should change the UI
4852 To reflect whether or not a Preset is being used or if
4853 the user is using "Custom" settings by determining the sender*/
4854 - (IBAction) customSettingUsed: (id) sender
4856 if ([sender stringValue])
4858 /* Deselect the currently selected Preset if there is one*/
4859 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4860 /* Change UI to show "Custom" settings are being used */
4861 [fPresetSelectedDisplay setStringValue: @"Custom"];
4863 curUserPresetChosenNum = nil;
4865 [self calculateBitrate:nil];
4870 #pragma mark - Video
4872 - (IBAction) videoEncoderPopUpChanged: (id) sender
4874 hb_job_t * job = fTitle->job;
4875 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4877 [fAdvancedOptions setHidden:YES];
4878 /* If we are using x264 then show the x264 advanced panel*/
4879 if (videoEncoder == HB_VCODEC_X264)
4881 [fAdvancedOptions setHidden:NO];
4882 [self autoSetM4vExtension: sender];
4885 if (videoEncoder == HB_VCODEC_FFMPEG)
4887 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4888 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4889 anything other than MP4.
4891 [fDstMp4iPodFileCheck setEnabled: NO];
4892 [fDstMp4iPodFileCheck setState: NSOffState];
4896 [fDstMp4iPodFileCheck setEnabled: YES];
4898 [self setupQualitySlider];
4899 [self calculatePictureSizing: sender];
4900 [self twoPassCheckboxChanged: sender];
4904 - (IBAction) twoPassCheckboxChanged: (id) sender
4906 /* check to see if x264 is chosen */
4907 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4909 if( [fVidTwoPassCheck state] == NSOnState)
4911 [fVidTurboPassCheck setHidden: NO];
4915 [fVidTurboPassCheck setHidden: YES];
4916 [fVidTurboPassCheck setState: NSOffState];
4918 /* Make sure Two Pass is checked if Turbo is checked */
4919 if( [fVidTurboPassCheck state] == NSOnState)
4921 [fVidTwoPassCheck setState: NSOnState];
4926 [fVidTurboPassCheck setHidden: YES];
4927 [fVidTurboPassCheck setState: NSOffState];
4930 /* We call method method to change UI to reflect whether a preset is used or not*/
4931 [self customSettingUsed: sender];
4934 - (IBAction ) videoFrameRateChanged: (id) sender
4936 /* We call method method to calculatePictureSizing to error check detelecine*/
4937 [self calculatePictureSizing: sender];
4939 /* We call method method to change UI to reflect whether a preset is used or not*/
4940 [self customSettingUsed: sender];
4942 - (IBAction) videoMatrixChanged: (id) sender;
4944 bool target, bitrate, quality;
4946 target = bitrate = quality = false;
4947 if( [fVidQualityMatrix isEnabled] )
4949 switch( [fVidQualityMatrix selectedRow] )
4962 [fVidTargetSizeField setEnabled: target];
4963 [fVidBitrateField setEnabled: bitrate];
4964 [fVidQualitySlider setEnabled: quality];
4965 [fVidQualityRFField setEnabled: quality];
4966 [fVidQualityRFLabel setEnabled: quality];
4967 [fVidTwoPassCheck setEnabled: !quality &&
4968 [fVidQualityMatrix isEnabled]];
4971 [fVidTwoPassCheck setState: NSOffState];
4972 [fVidTurboPassCheck setHidden: YES];
4973 [fVidTurboPassCheck setState: NSOffState];
4976 [self qualitySliderChanged: sender];
4977 [self calculateBitrate: sender];
4978 [self customSettingUsed: sender];
4981 /* Use this method to setup the quality slider for cq/rf values depending on
4982 * the video encoder selected.
4984 - (void) setupQualitySlider
4986 /* Get the current slider maxValue to check for a change in slider scale later
4987 * so that we can choose a new similar value on the new slider scale */
4988 float previousMaxValue = [fVidQualitySlider maxValue];
4989 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4990 NSString * qpRFLabelString = @"QP:";
4992 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4994 [fVidQualitySlider setMinValue:0.0];
4995 [fVidQualitySlider setMaxValue:51.0];
4996 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4997 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4998 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4999 qpRFLabelString = @"RF:";
5002 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
5004 [fVidQualitySlider setMinValue:1.0];
5005 [fVidQualitySlider setMaxValue:31.0];
5006 [fVidQualitySlider setNumberOfTickMarks:31];
5009 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5011 [fVidQualitySlider setMinValue:0.0];
5012 [fVidQualitySlider setMaxValue:63.0];
5013 [fVidQualitySlider setNumberOfTickMarks:64];
5015 [fVidQualityRFLabel setStringValue:qpRFLabelString];
5017 /* check to see if we have changed slider scales */
5018 if (previousMaxValue != [fVidQualitySlider maxValue])
5020 /* if so, convert the old setting to the new scale as close as possible based on percentages */
5021 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
5022 [fVidQualitySlider setFloatValue:rf];
5025 [self qualitySliderChanged:nil];
5028 - (IBAction) qualitySliderChanged: (id) sender
5030 /* Our constant quality slider is in a range based
5031 * on each encoders qp/rf values. The range depends
5032 * on the encoder. Also, the range is inverse of quality
5033 * for all of the encoders *except* for theora
5034 * (ie. as the "quality" goes up, the cq or rf value
5035 * actually goes down). Since the IB sliders always set
5036 * their max value at the right end of the slider, we
5037 * will calculate the inverse, so as the slider floatValue
5038 * goes up, we will show the inverse in the rf field
5039 * so, the floatValue at the right for x264 would be 51
5040 * and our rf field needs to show 0 and vice versa.
5043 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5044 /* If the encoder is theora, use the float, otherwise use the inverse float*/
5045 //float sliderRfToPercent;
5046 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5048 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
5052 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5054 [self customSettingUsed: sender];
5057 - (void) controlTextDidChange: (NSNotification *) notification
5059 [self calculateBitrate:nil];
5062 - (IBAction) calculateBitrate: (id) sender
5064 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5069 hb_list_t * list = hb_get_titles( fHandle );
5070 hb_title_t * title = (hb_title_t *) hb_list_item( list,
5071 [fSrcTitlePopUp indexOfSelectedItem] );
5072 hb_job_t * job = title->job;
5073 hb_audio_config_t * audio;
5074 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
5075 * Target Size Field, we also need the job info for the Muxer, the Chapters
5076 * as well as all of the audio track info.
5077 * This used to be accomplished by simply calling prepareJob here, however
5078 * since the resilient queue sets the queue array values instead of the job
5079 * values directly, we duplicate the old prepareJob code here for the variables
5082 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5083 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
5084 job->mux = [[fDstFormatPopUp selectedItem] tag];
5086 /* Audio goes here */
5087 int audiotrack_count = hb_list_count(job->list_audio);
5088 for( int i = 0; i < audiotrack_count;i++)
5090 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5091 hb_list_rem(job->list_audio, temp_audio);
5093 /* Now we need our audio info here for each track if applicable */
5094 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5096 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5097 hb_audio_config_init(audio);
5098 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5099 /* We go ahead and assign values to our audio->out.<properties> */
5100 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5101 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5102 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5103 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5104 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5105 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5107 hb_audio_add( job, audio );
5110 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5112 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5113 hb_audio_config_init(audio);
5114 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5115 /* We go ahead and assign values to our audio->out.<properties> */
5116 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5117 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5118 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5119 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5120 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5121 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5123 hb_audio_add( job, audio );
5128 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5130 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5131 hb_audio_config_init(audio);
5132 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5133 /* We go ahead and assign values to our audio->out.<properties> */
5134 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5135 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5136 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5137 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5138 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5139 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5141 hb_audio_add( job, audio );
5146 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5148 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5149 hb_audio_config_init(audio);
5150 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5151 /* We go ahead and assign values to our audio->out.<properties> */
5152 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5153 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5154 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5155 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5156 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5157 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5159 hb_audio_add( job, audio );
5164 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5168 #pragma mark - Picture
5170 /* lets set the picture size back to the max from right after title scan
5171 Lets use an IBAction here as down the road we could always use a checkbox
5172 in the gui to easily take the user back to max. Remember, the compiler
5173 resolves IBActions down to -(void) during compile anyway */
5174 - (IBAction) revertPictureSizeToMax: (id) sender
5176 hb_job_t * job = fTitle->job;
5177 /* Here we apply the title source and height */
5178 job->width = fTitle->width;
5179 job->height = fTitle->height;
5181 [self calculatePictureSizing: sender];
5182 /* We call method to change UI to reflect whether a preset is used or not*/
5183 [self customSettingUsed: sender];
5187 * Registers changes made in the Picture Settings Window.
5190 - (void)pictureSettingsDidChange
5192 [self calculatePictureSizing:nil];
5195 /* Get and Display Current Pic Settings in main window */
5196 - (IBAction) calculatePictureSizing: (id) sender
5198 if (fTitle->job->anamorphic.mode > 0)
5200 fTitle->job->keep_ratio = 0;
5203 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5205 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5209 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5211 NSString *picCropping;
5212 /* Set the display field for crop as per boolean */
5213 if (![fPictureController autoCrop])
5215 picCropping = @"Custom";
5219 picCropping = @"Auto";
5221 picCropping = [picCropping stringByAppendingString:[NSString stringWithFormat:@" %d/%d/%d/%d",fTitle->job->crop[0],fTitle->job->crop[1],fTitle->job->crop[2],fTitle->job->crop[3]]];
5223 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5225 NSString *videoFilters;
5228 if ([fPictureController detelecine] == 2)
5230 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5232 else if ([fPictureController detelecine] == 1)
5234 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5238 if ([fPictureController useDecomb] == 1)
5241 if ([fPictureController decomb] == 2)
5243 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5245 else if ([fPictureController decomb] == 1)
5247 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5253 if ([fPictureController deinterlace] > 0)
5255 fTitle->job->deinterlace = 1;
5259 fTitle->job->deinterlace = 0;
5262 if ([fPictureController deinterlace] == 2)
5264 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5266 else if ([fPictureController deinterlace] == 3)
5268 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5270 else if ([fPictureController deinterlace] == 4)
5272 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5274 else if ([fPictureController deinterlace] == 1)
5276 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5282 if ([fPictureController denoise] == 2)
5284 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5286 else if ([fPictureController denoise] == 3)
5288 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5290 else if ([fPictureController denoise] == 4)
5292 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5294 else if ([fPictureController denoise] == 1)
5296 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5300 if ([fPictureController deblock] > 0)
5302 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5306 if ([fPictureController grayscale])
5308 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5310 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5312 //[fPictureController reloadStillPreview];
5317 #pragma mark - Audio and Subtitles
5318 - (IBAction) audioCodecsPopUpChanged: (id) sender
5321 NSPopUpButton * audiotrackPopUp;
5322 NSPopUpButton * sampleratePopUp;
5323 NSPopUpButton * bitratePopUp;
5324 NSPopUpButton * audiocodecPopUp;
5325 if (sender == fAudTrack1CodecPopUp)
5327 audiotrackPopUp = fAudLang1PopUp;
5328 audiocodecPopUp = fAudTrack1CodecPopUp;
5329 sampleratePopUp = fAudTrack1RatePopUp;
5330 bitratePopUp = fAudTrack1BitratePopUp;
5332 else if (sender == fAudTrack2CodecPopUp)
5334 audiotrackPopUp = fAudLang2PopUp;
5335 audiocodecPopUp = fAudTrack2CodecPopUp;
5336 sampleratePopUp = fAudTrack2RatePopUp;
5337 bitratePopUp = fAudTrack2BitratePopUp;
5339 else if (sender == fAudTrack3CodecPopUp)
5341 audiotrackPopUp = fAudLang3PopUp;
5342 audiocodecPopUp = fAudTrack3CodecPopUp;
5343 sampleratePopUp = fAudTrack3RatePopUp;
5344 bitratePopUp = fAudTrack3BitratePopUp;
5348 audiotrackPopUp = fAudLang4PopUp;
5349 audiocodecPopUp = fAudTrack4CodecPopUp;
5350 sampleratePopUp = fAudTrack4RatePopUp;
5351 bitratePopUp = fAudTrack4BitratePopUp;
5354 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5355 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5356 [self audioTrackPopUpChanged: audiotrackPopUp];
5360 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5362 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5363 * the settings of the source audio for that track. We leave the samplerate and bitrate
5364 * to audiotrackMixdownChanged
5367 /* We will first verify that a lower track number has been selected before enabling each track
5368 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5370 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5372 [fAudLang2PopUp setEnabled: NO];
5373 [fAudLang2PopUp selectItemAtIndex: 0];
5377 [fAudLang2PopUp setEnabled: YES];
5380 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5382 [fAudLang3PopUp setEnabled: NO];
5383 [fAudLang3PopUp selectItemAtIndex: 0];
5387 [fAudLang3PopUp setEnabled: YES];
5389 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5391 [fAudLang4PopUp setEnabled: NO];
5392 [fAudLang4PopUp selectItemAtIndex: 0];
5396 [fAudLang4PopUp setEnabled: YES];
5398 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5399 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5400 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5401 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5402 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5403 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5404 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5405 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5407 [fAudTrack1CodecPopUp removeAllItems];
5408 [fAudTrack1MixPopUp removeAllItems];
5409 [fAudTrack1RatePopUp removeAllItems];
5410 [fAudTrack1BitratePopUp removeAllItems];
5411 [fAudTrack1DrcSlider setFloatValue: 0.00];
5412 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5414 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5416 [fAudTrack1RatePopUp setEnabled: NO];
5417 [fAudTrack1BitratePopUp setEnabled: NO];
5418 [fAudTrack1DrcSlider setEnabled: NO];
5419 [fAudTrack1DrcField setEnabled: NO];
5422 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5423 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5424 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5425 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5426 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5427 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5428 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5429 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5431 [fAudTrack2CodecPopUp removeAllItems];
5432 [fAudTrack2MixPopUp removeAllItems];
5433 [fAudTrack2RatePopUp removeAllItems];
5434 [fAudTrack2BitratePopUp removeAllItems];
5435 [fAudTrack2DrcSlider setFloatValue: 0.00];
5436 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5438 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5440 [fAudTrack2RatePopUp setEnabled: NO];
5441 [fAudTrack2BitratePopUp setEnabled: NO];
5442 [fAudTrack2DrcSlider setEnabled: NO];
5443 [fAudTrack2DrcField setEnabled: NO];
5446 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5447 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5448 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5449 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5450 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5451 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5452 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5453 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5455 [fAudTrack3CodecPopUp removeAllItems];
5456 [fAudTrack3MixPopUp removeAllItems];
5457 [fAudTrack3RatePopUp removeAllItems];
5458 [fAudTrack3BitratePopUp removeAllItems];
5459 [fAudTrack3DrcSlider setFloatValue: 0.00];
5460 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5462 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5464 [fAudTrack3RatePopUp setEnabled: NO];
5465 [fAudTrack3BitratePopUp setEnabled: NO];
5466 [fAudTrack3DrcSlider setEnabled: NO];
5467 [fAudTrack3DrcField setEnabled: NO];
5470 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5471 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5472 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5473 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5474 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5475 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5476 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5477 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5479 [fAudTrack4CodecPopUp removeAllItems];
5480 [fAudTrack4MixPopUp removeAllItems];
5481 [fAudTrack4RatePopUp removeAllItems];
5482 [fAudTrack4BitratePopUp removeAllItems];
5483 [fAudTrack4DrcSlider setFloatValue: 0.00];
5484 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5486 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5488 [fAudTrack4RatePopUp setEnabled: NO];
5489 [fAudTrack4BitratePopUp setEnabled: NO];
5490 [fAudTrack4DrcSlider setEnabled: NO];
5491 [fAudTrack4DrcField setEnabled: NO];
5496 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5499 hb_list_t * list = hb_get_titles( fHandle );
5500 hb_title_t * title = (hb_title_t*)
5501 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5503 hb_audio_config_t * audio;
5505 [sender removeAllItems];
5506 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5507 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5509 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5510 [[sender menu] addItemWithTitle:
5511 [NSString stringWithUTF8String: audio->lang.description]
5512 action: NULL keyEquivalent: @""];
5514 [sender selectItemAtIndex: 0];
5518 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5521 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5522 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5523 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5524 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5526 if (searchPrefixString)
5529 for( int i = 0; i < [sender numberOfItems]; i++ )
5531 /* Try to find the desired search string */
5532 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5534 [sender selectItemAtIndex: i];
5538 /* couldn't find the string, so select the requested "search string not found" item */
5539 /* index of 0 means select the "none" item */
5540 /* index of 1 means select the first audio track */
5541 [sender selectItemAtIndex: selectIndexIfNotFound];
5545 /* if no search string is provided, then select the selectIndexIfNotFound item */
5546 [sender selectItemAtIndex: selectIndexIfNotFound];
5550 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5552 int format = [fDstFormatPopUp indexOfSelectedItem];
5554 /* setup pointers to the appropriate popups for the correct track */
5555 NSPopUpButton * audiocodecPopUp;
5556 NSPopUpButton * audiotrackPopUp;
5557 if (sender == fAudTrack1CodecPopUp)
5559 audiotrackPopUp = fAudLang1PopUp;
5560 audiocodecPopUp = fAudTrack1CodecPopUp;
5562 else if (sender == fAudTrack2CodecPopUp)
5564 audiotrackPopUp = fAudLang2PopUp;
5565 audiocodecPopUp = fAudTrack2CodecPopUp;
5567 else if (sender == fAudTrack3CodecPopUp)
5569 audiotrackPopUp = fAudLang3PopUp;
5570 audiocodecPopUp = fAudTrack3CodecPopUp;
5574 audiotrackPopUp = fAudLang4PopUp;
5575 audiocodecPopUp = fAudTrack4CodecPopUp;
5578 [audiocodecPopUp removeAllItems];
5579 /* Make sure "None" isnt selected in the source track */
5580 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5582 [audiocodecPopUp setEnabled:YES];
5583 NSMenuItem *menuItem;
5584 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5590 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5591 [menuItem setTag: HB_ACODEC_CA_AAC];
5593 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5594 [menuItem setTag: HB_ACODEC_FAAC];
5596 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5597 [menuItem setTag: HB_ACODEC_AC3];
5603 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5604 [menuItem setTag: HB_ACODEC_CA_AAC];
5606 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5607 [menuItem setTag: HB_ACODEC_FAAC];
5609 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5610 [menuItem setTag: HB_ACODEC_AC3];
5612 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5613 [menuItem setTag: HB_ACODEC_DCA];
5615 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5616 [menuItem setTag: HB_ACODEC_LAME];
5618 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5619 [menuItem setTag: HB_ACODEC_VORBIS];
5622 [audiocodecPopUp selectItemAtIndex:0];
5626 [audiocodecPopUp setEnabled:NO];
5630 - (IBAction) audioTrackPopUpChanged: (id) sender
5632 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5633 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5636 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5639 /* make sure we have a selected title before continuing */
5640 if (fTitle == NULL) return;
5641 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5642 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5644 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5646 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5648 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5650 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5652 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5654 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5656 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5658 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5661 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5662 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5664 sender = fAudLang1PopUp;
5666 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5668 sender = fAudLang2PopUp;
5670 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5672 sender = fAudLang3PopUp;
5674 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5676 sender = fAudLang4PopUp;
5679 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5680 NSPopUpButton * mixdownPopUp;
5681 NSPopUpButton * audiocodecPopUp;
5682 NSPopUpButton * sampleratePopUp;
5683 NSPopUpButton * bitratePopUp;
5684 if (sender == fAudLang1PopUp)
5686 mixdownPopUp = fAudTrack1MixPopUp;
5687 audiocodecPopUp = fAudTrack1CodecPopUp;
5688 sampleratePopUp = fAudTrack1RatePopUp;
5689 bitratePopUp = fAudTrack1BitratePopUp;
5691 else if (sender == fAudLang2PopUp)
5693 mixdownPopUp = fAudTrack2MixPopUp;
5694 audiocodecPopUp = fAudTrack2CodecPopUp;
5695 sampleratePopUp = fAudTrack2RatePopUp;
5696 bitratePopUp = fAudTrack2BitratePopUp;
5698 else if (sender == fAudLang3PopUp)
5700 mixdownPopUp = fAudTrack3MixPopUp;
5701 audiocodecPopUp = fAudTrack3CodecPopUp;
5702 sampleratePopUp = fAudTrack3RatePopUp;
5703 bitratePopUp = fAudTrack3BitratePopUp;
5707 mixdownPopUp = fAudTrack4MixPopUp;
5708 audiocodecPopUp = fAudTrack4CodecPopUp;
5709 sampleratePopUp = fAudTrack4RatePopUp;
5710 bitratePopUp = fAudTrack4BitratePopUp;
5713 /* get the index of the selected audio Track*/
5714 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5716 /* pointer for the hb_audio_s struct we will use later on */
5717 hb_audio_config_t * audio;
5720 /* check if the audio mixdown controls need their enabled state changing */
5721 [self setEnabledStateOfAudioMixdownControls:nil];
5723 if (thisAudioIndex != -1)
5727 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5729 /* actually manipulate the proper mixdowns here */
5730 /* delete the previous audio mixdown options */
5731 [mixdownPopUp removeAllItems];
5733 acodec = [[audiocodecPopUp selectedItem] tag];
5738 /* find out if our selected output audio codec supports mono and / or 6ch */
5739 /* we also check for an input codec of AC3 or DCA,
5740 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5741 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5742 but this may change in the future, so they are separated for flexibility */
5743 int audioCodecsSupportMono =
5744 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5745 (acodec != HB_ACODEC_LAME);
5746 int audioCodecsSupport6Ch =
5747 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5748 (acodec != HB_ACODEC_LAME);
5750 /* check for AC-3 passthru */
5751 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5754 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5755 [NSString stringWithUTF8String: "AC3 Passthru"]
5756 action: NULL keyEquivalent: @""];
5757 [menuItem setTag: HB_ACODEC_AC3];
5759 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5761 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5762 [NSString stringWithUTF8String: "DTS Passthru"]
5763 action: NULL keyEquivalent: @""];
5764 [menuItem setTag: HB_ACODEC_DCA];
5769 /* add the appropriate audio mixdown menuitems to the popupbutton */
5770 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5771 so that we can reference the mixdown later */
5773 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5774 int minMixdownUsed = 0;
5775 int maxMixdownUsed = 0;
5777 /* get the input channel layout without any lfe channels */
5778 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5780 /* do we want to add a mono option? */
5781 if (audioCodecsSupportMono == 1)
5783 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5784 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5785 action: NULL keyEquivalent: @""];
5786 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5787 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5788 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5791 /* do we want to add a stereo option? */
5792 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5793 /* also offer stereo if we have a stereo-or-better source */
5794 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5796 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5797 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5798 action: NULL keyEquivalent: @""];
5799 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5800 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5801 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5804 /* do we want to add a dolby surround (DPL1) option? */
5805 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5807 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5808 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5809 action: NULL keyEquivalent: @""];
5810 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5811 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5812 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5815 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5816 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5818 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5819 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5820 action: NULL keyEquivalent: @""];
5821 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5822 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5823 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5826 /* do we want to add a 6-channel discrete option? */
5827 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5829 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5830 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5831 action: NULL keyEquivalent: @""];
5832 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5833 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5834 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5837 /* do we want to add an AC-3 passthrough option? */
5838 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5840 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5841 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5842 action: NULL keyEquivalent: @""];
5843 [menuItem setTag: HB_ACODEC_AC3];
5844 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5845 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5848 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5849 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5851 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5852 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5853 action: NULL keyEquivalent: @""];
5854 [menuItem setTag: HB_ACODEC_DCA];
5855 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5856 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5859 /* auto-select the best mixdown based on our saved mixdown preference */
5861 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5862 /* ultimately this should be a prefs option */
5865 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5866 if (mixdownToUse > 0)
5868 useMixdown = mixdownToUse;
5872 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5875 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5876 if (useMixdown > maxMixdownUsed)
5878 useMixdown = maxMixdownUsed;
5881 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5882 if (useMixdown < minMixdownUsed)
5884 useMixdown = minMixdownUsed;
5887 /* select the (possibly-amended) preferred mixdown */
5888 [mixdownPopUp selectItemWithTag: useMixdown];
5891 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5892 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5894 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5896 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5899 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5900 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5902 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5904 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5907 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5908 [self audioTrackMixdownChanged: mixdownPopUp];
5912 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5914 [self autoSetM4vExtension: sender];
5918 - (IBAction) audioTrackMixdownChanged: (id) sender
5922 /* setup pointers to all of the other audio track controls
5923 * we will need later
5925 NSPopUpButton * mixdownPopUp;
5926 NSPopUpButton * sampleratePopUp;
5927 NSPopUpButton * bitratePopUp;
5928 NSPopUpButton * audiocodecPopUp;
5929 NSPopUpButton * audiotrackPopUp;
5930 NSSlider * drcSlider;
5931 NSTextField * drcField;
5932 if (sender == fAudTrack1MixPopUp)
5934 audiotrackPopUp = fAudLang1PopUp;
5935 audiocodecPopUp = fAudTrack1CodecPopUp;
5936 mixdownPopUp = fAudTrack1MixPopUp;
5937 sampleratePopUp = fAudTrack1RatePopUp;
5938 bitratePopUp = fAudTrack1BitratePopUp;
5939 drcSlider = fAudTrack1DrcSlider;
5940 drcField = fAudTrack1DrcField;
5942 else if (sender == fAudTrack2MixPopUp)
5944 audiotrackPopUp = fAudLang2PopUp;
5945 audiocodecPopUp = fAudTrack2CodecPopUp;
5946 mixdownPopUp = fAudTrack2MixPopUp;
5947 sampleratePopUp = fAudTrack2RatePopUp;
5948 bitratePopUp = fAudTrack2BitratePopUp;
5949 drcSlider = fAudTrack2DrcSlider;
5950 drcField = fAudTrack2DrcField;
5952 else if (sender == fAudTrack3MixPopUp)
5954 audiotrackPopUp = fAudLang3PopUp;
5955 audiocodecPopUp = fAudTrack3CodecPopUp;
5956 mixdownPopUp = fAudTrack3MixPopUp;
5957 sampleratePopUp = fAudTrack3RatePopUp;
5958 bitratePopUp = fAudTrack3BitratePopUp;
5959 drcSlider = fAudTrack3DrcSlider;
5960 drcField = fAudTrack3DrcField;
5964 audiotrackPopUp = fAudLang4PopUp;
5965 audiocodecPopUp = fAudTrack4CodecPopUp;
5966 mixdownPopUp = fAudTrack4MixPopUp;
5967 sampleratePopUp = fAudTrack4RatePopUp;
5968 bitratePopUp = fAudTrack4BitratePopUp;
5969 drcSlider = fAudTrack4DrcSlider;
5970 drcField = fAudTrack4DrcField;
5972 acodec = [[audiocodecPopUp selectedItem] tag];
5973 /* storage variable for the min and max bitrate allowed for this codec */
5979 case HB_ACODEC_FAAC:
5980 /* check if we have a 6ch discrete conversion in either audio track */
5981 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5983 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5985 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
5991 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5993 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5994 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5999 case HB_ACODEC_CA_AAC:
6000 /* check if we have a 6ch discrete conversion in either audio track */
6001 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6014 case HB_ACODEC_LAME:
6015 /* Lame is happy using our min bitrate of 32 kbps */
6017 /* Lame won't encode if the bitrate is higher than 320 kbps */
6021 case HB_ACODEC_VORBIS:
6022 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6024 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6026 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6032 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6034 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6040 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6046 /* make sure we have a selected title before continuing */
6047 if (fTitle == NULL) return;
6048 /* get the audio so we can find out what input rates are*/
6049 hb_audio_config_t * audio;
6050 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6051 int inputbitrate = audio->in.bitrate / 1000;
6052 int inputsamplerate = audio->in.samplerate;
6054 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6056 [bitratePopUp removeAllItems];
6058 for( int i = 0; i < hb_audio_bitrates_count; i++ )
6060 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6062 /* add a new menuitem for this bitrate */
6063 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6064 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6065 action: NULL keyEquivalent: @""];
6066 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6067 [menuItem setTag: hb_audio_bitrates[i].rate];
6071 /* select the default bitrate (but use 384 for 6-ch AAC) */
6072 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6074 [bitratePopUp selectItemWithTag: 384];
6078 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6081 /* populate and set the sample rate popup */
6082 /* Audio samplerate */
6083 [sampleratePopUp removeAllItems];
6084 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6085 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6086 [menuItem setTag: inputsamplerate];
6088 for( int i = 0; i < hb_audio_rates_count; i++ )
6090 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6091 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6092 action: NULL keyEquivalent: @""];
6093 [menuItem setTag: hb_audio_rates[i].rate];
6095 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6096 * and there is no compelling reason to use anything else as default, though the users default
6097 * preset will likely override any setting chosen here.
6099 [sampleratePopUp selectItemWithTag: inputsamplerate];
6102 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6103 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6104 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6106 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6109 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6110 [bitratePopUp removeAllItems];
6111 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6112 [NSString stringWithFormat:@"%d", inputbitrate]
6113 action: NULL keyEquivalent: @""];
6114 [menuItem setTag: inputbitrate];
6115 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6116 [bitratePopUp setEnabled: NO];
6117 [sampleratePopUp setEnabled: NO];
6119 [drcSlider setFloatValue: 0.00];
6120 [self audioDRCSliderChanged: drcSlider];
6121 [drcSlider setEnabled: NO];
6122 [drcField setEnabled: NO];
6126 [sampleratePopUp setEnabled: YES];
6127 [bitratePopUp setEnabled: YES];
6128 [drcSlider setEnabled: YES];
6129 [drcField setEnabled: YES];
6131 [self calculateBitrate:nil];
6134 - (IBAction) audioDRCSliderChanged: (id) sender
6136 NSSlider * drcSlider;
6137 NSTextField * drcField;
6138 if (sender == fAudTrack1DrcSlider)
6140 drcSlider = fAudTrack1DrcSlider;
6141 drcField = fAudTrack1DrcField;
6143 else if (sender == fAudTrack2DrcSlider)
6145 drcSlider = fAudTrack2DrcSlider;
6146 drcField = fAudTrack2DrcField;
6148 else if (sender == fAudTrack3DrcSlider)
6150 drcSlider = fAudTrack3DrcSlider;
6151 drcField = fAudTrack3DrcField;
6155 drcSlider = fAudTrack4DrcSlider;
6156 drcField = fAudTrack4DrcField;
6159 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6160 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6162 [drcSlider setFloatValue:1.0];
6166 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6167 /* For now, do not call this until we have an intelligent way to determine audio track selections
6168 * compared to presets
6170 //[self customSettingUsed: sender];
6175 - (IBAction) browseImportSrtFile: (id) sender
6178 NSOpenPanel * panel;
6180 panel = [NSOpenPanel openPanel];
6181 [panel setAllowsMultipleSelection: NO];
6182 [panel setCanChooseFiles: YES];
6183 [panel setCanChooseDirectories: NO ];
6184 NSString * sourceDirectory;
6185 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6187 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6191 sourceDirectory = @"~/Desktop";
6192 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6194 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6195 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6196 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6197 modalForWindow: fWindow modalDelegate: self
6198 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6199 contextInfo: sender];
6202 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6203 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6205 if( returnCode == NSOKButton )
6207 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6208 NSString *importSrtFilePath = [sheet filename];
6209 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6211 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6212 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6214 [fSubtitlesTable reloadData];
6220 #pragma mark Open New Windows
6222 - (IBAction) openHomepage: (id) sender
6224 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6225 URLWithString:@"http://handbrake.fr/"]];
6228 - (IBAction) openForums: (id) sender
6230 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6231 URLWithString:@"http://handbrake.fr/forum/"]];
6233 - (IBAction) openUserGuide: (id) sender
6235 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6236 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6240 * Shows debug output window.
6242 - (IBAction)showDebugOutputPanel:(id)sender
6244 [outputPanel showOutputPanel:sender];
6248 * Shows preferences window.
6250 - (IBAction) showPreferencesWindow: (id) sender
6252 NSWindow * window = [fPreferencesController window];
6253 if (![window isVisible])
6256 [window makeKeyAndOrderFront: nil];
6260 * Shows queue window.
6262 - (IBAction) showQueueWindow:(id)sender
6264 [fQueueController showQueueWindow:sender];
6268 - (IBAction) toggleDrawer:(id)sender {
6269 [fPresetDrawer toggle:self];
6273 * Shows Picture Settings Window.
6276 - (IBAction) showPicturePanel: (id) sender
6278 [fPictureController showPictureWindow:sender];
6281 - (void) picturePanelFullScreen
6283 [fPictureController setToFullScreenMode];
6286 - (void) picturePanelWindowed
6288 [fPictureController setToWindowedMode];
6291 - (IBAction) showPreviewWindow: (id) sender
6293 [fPictureController showPreviewWindow:sender];
6297 #pragma mark Preset Outline View Methods
6298 #pragma mark - Required
6299 /* These are required by the NSOutlineView Datasource Delegate */
6302 /* used to specify the number of levels to show for each item */
6303 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6305 /* currently use no levels to test outline view viability */
6306 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6308 return [UserPresets count];
6312 /* we need to return the count of the array in ChildrenArray for this folder */
6313 NSArray *children = nil;
6314 children = [item objectForKey:@"ChildrenArray"];
6315 if ([children count] > 0)
6317 return [children count];
6326 /* We use this to deterimine children of an item */
6327 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6330 /* we need to return the count of the array in ChildrenArray for this folder */
6331 NSArray *children = nil;
6334 children = UserPresets;
6338 if ([item objectForKey:@"ChildrenArray"])
6340 children = [item objectForKey:@"ChildrenArray"];
6343 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6349 return [children objectAtIndex:index];
6353 // We are only one level deep, so we can't be asked about children
6354 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6358 /* We use this to determine if an item should be expandable */
6359 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6362 /* we need to return the count of the array in ChildrenArray for this folder */
6363 NSArray *children= nil;
6366 children = UserPresets;
6370 if ([item objectForKey:@"ChildrenArray"])
6372 children = [item objectForKey:@"ChildrenArray"];
6376 /* To deterimine if an item should show a disclosure triangle
6377 * we could do it by the children count as so:
6378 * if ([children count] < 1)
6379 * However, lets leave the triangle show even if there are no
6380 * children to help indicate a folder, just like folder in the
6381 * finder can show a disclosure triangle even when empty
6384 /* We need to determine if the item is a folder */
6385 if ([[item objectForKey:@"Folder"] intValue] == 1)
6396 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6398 // Our outline view has no levels, but we can still expand every item. Doing so
6399 // just makes the row taller. See heightOfRowByItem below.
6400 //return ![(HBQueueOutlineView*)outlineView isDragging];
6406 /* Used to tell the outline view which information is to be displayed per item */
6407 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6409 /* We have two columns right now, icon and PresetName */
6411 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6413 return [item objectForKey:@"PresetName"];
6422 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6424 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6426 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6428 return [NSKeyedArchiver archivedDataWithRootObject:item];
6431 #pragma mark - Added Functionality (optional)
6432 /* Use to customize the font and display characteristics of the title cell */
6433 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6435 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6439 NSColor *shadowColor;
6440 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6441 /*check to see if its a selected row */
6442 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6445 fontColor = [NSColor blackColor];
6446 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6450 if ([[item objectForKey:@"Type"] intValue] == 0)
6452 fontColor = [NSColor blueColor];
6454 else // User created preset, use a black font
6456 fontColor = [NSColor blackColor];
6458 /* check to see if its a folder */
6459 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6461 //fontColor = [NSColor greenColor];
6466 /* We use Bold Text for the HB Default */
6467 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6469 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6471 /* We use Bold Text for the User Specified Default */
6472 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6474 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6478 [cell setTextColor:fontColor];
6479 [cell setFont:txtFont];
6484 /* We use this to edit the name field in the outline view */
6485 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6487 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6492 [theRecord setObject:object forKey:@"PresetName"];
6496 [fPresetsOutlineView reloadData];
6497 /* We save all of the preset data here */
6501 /* We use this to provide tooltips for the items in the presets outline view */
6502 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6504 //if ([[tc identifier] isEqualToString:@"PresetName"])
6506 /* initialize the tooltip contents variable */
6508 /* if there is a description for the preset, we show it in the tooltip */
6509 if ([item objectForKey:@"PresetDescription"])
6511 loc_tip = [item objectForKey:@"PresetDescription"];
6516 loc_tip = @"No description available";
6523 #pragma mark Preset Outline View Methods (dragging related)
6526 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6528 // Dragging is only allowed for custom presets.
6529 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6530 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6534 // Don't retain since this is just holding temporaral drag information, and it is
6535 //only used during a drag! We could put this in the pboard actually.
6536 fDraggedNodes = items;
6537 // Provide data for our custom type, and simple NSStrings.
6538 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6540 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6541 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6546 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6549 // Don't allow dropping ONTO an item since they can't really contain any children.
6551 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6552 if (isOnDropTypeProposal)
6553 return NSDragOperationNone;
6555 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6558 index = [fPresetsOutlineView rowForItem: item] + 1;
6562 // Don't allow dropping into the Built In Presets.
6563 if (index < presetCurrentBuiltInCount)
6565 return NSDragOperationNone;
6566 index = MAX (index, presetCurrentBuiltInCount);
6569 [outlineView setDropItem:item dropChildIndex:index];
6570 return NSDragOperationGeneric;
6575 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6577 /* first, lets see if we are dropping into a folder */
6578 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6580 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6581 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6582 [childrenArray addObject:item];
6583 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6584 [childrenArray autorelease];
6586 else // We are not, so we just move the preset into the existing array
6588 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6590 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6591 while (obj = [enumerator nextObject])
6593 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6595 // Successful drop, lets rearrange the view and save it all
6596 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6598 [fPresetsOutlineView reloadData];
6603 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6605 NSUInteger index = [indexSet lastIndex];
6606 NSUInteger aboveInsertIndexCount = 0;
6608 NSUInteger removeIndex;
6610 if (index >= insertIndex)
6612 removeIndex = index + aboveInsertIndexCount;
6613 aboveInsertIndexCount++;
6617 removeIndex = index;
6621 id object = [[array objectAtIndex:removeIndex] retain];
6622 [array removeObjectAtIndex:removeIndex];
6623 [array insertObject:object atIndex:insertIndex];
6626 index = [indexSet indexLessThanIndex:index];
6631 #pragma mark - Functional Preset NSOutlineView Methods
6633 - (IBAction)selectPreset:(id)sender
6636 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6638 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6639 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6641 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6643 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6647 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6651 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6652 [self formatPopUpChanged:nil];
6654 /* Chapter Markers*/
6655 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6656 /* check to see if we have only one chapter */
6657 [self chapterPopUpChanged:nil];
6659 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6660 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6661 /* Mux mp4 with http optimization */
6662 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6665 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6666 /* We set the advanced opt string here if applicable*/
6667 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6669 /* Lets run through the following functions to get variables set there */
6670 [self videoEncoderPopUpChanged:nil];
6671 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6672 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6673 [self calculateBitrate:nil];
6676 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6678 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6679 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6681 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6682 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6683 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6684 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6685 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6686 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6688 /* For the quality slider we need to convert the old percent's to the new rf scales */
6689 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6690 [fVidQualitySlider setFloatValue:rf];
6695 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6696 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6698 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6702 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6703 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6707 [self videoMatrixChanged:nil];
6709 /* Video framerate */
6710 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6711 detected framerate in the fVidRatePopUp so we use index 0*/
6712 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6714 [fVidRatePopUp selectItemAtIndex: 0];
6718 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6722 /* 2 Pass Encoding */
6723 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6724 [self twoPassCheckboxChanged:nil];
6726 /* Turbo 1st pass for 2 Pass Encoding */
6727 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6730 /* First we check to see if we are using the current audio track layout based on AudioList array */
6731 if ([chosenPreset objectForKey:@"AudioList"])
6734 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6735 NSPopUpButton * trackLangPopUp = nil;
6736 NSPopUpButton * mixdownPopUp = nil;
6737 NSPopUpButton * audiocodecPopUp = nil;
6738 NSPopUpButton * sampleratePopUp = nil;
6739 NSPopUpButton * bitratePopUp = nil;
6740 NSSlider * drcSlider = nil;
6743 /* Populate the audio widgets based on the contents of the AudioList array */
6745 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6747 while (tempObject = [enumerator nextObject])
6752 trackLangPopUp = fAudLang1PopUp;
6753 mixdownPopUp = fAudTrack1MixPopUp;
6754 audiocodecPopUp = fAudTrack1CodecPopUp;
6755 sampleratePopUp = fAudTrack1RatePopUp;
6756 bitratePopUp = fAudTrack1BitratePopUp;
6757 drcSlider = fAudTrack1DrcSlider;
6761 trackLangPopUp = fAudLang2PopUp;
6762 mixdownPopUp = fAudTrack2MixPopUp;
6763 audiocodecPopUp = fAudTrack2CodecPopUp;
6764 sampleratePopUp = fAudTrack2RatePopUp;
6765 bitratePopUp = fAudTrack2BitratePopUp;
6766 drcSlider = fAudTrack2DrcSlider;
6770 trackLangPopUp = fAudLang3PopUp;
6771 mixdownPopUp = fAudTrack3MixPopUp;
6772 audiocodecPopUp = fAudTrack3CodecPopUp;
6773 sampleratePopUp = fAudTrack3RatePopUp;
6774 bitratePopUp = fAudTrack3BitratePopUp;
6775 drcSlider = fAudTrack3DrcSlider;
6779 trackLangPopUp = fAudLang4PopUp;
6780 mixdownPopUp = fAudTrack4MixPopUp;
6781 audiocodecPopUp = fAudTrack4CodecPopUp;
6782 sampleratePopUp = fAudTrack4RatePopUp;
6783 bitratePopUp = fAudTrack4BitratePopUp;
6784 drcSlider = fAudTrack4DrcSlider;
6788 if ([trackLangPopUp indexOfSelectedItem] == 0)
6790 [trackLangPopUp selectItemAtIndex: 1];
6792 [self audioTrackPopUpChanged: trackLangPopUp];
6793 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6794 /* check our pref for core audio and use it in place of faac if preset is a built in */
6795 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6796 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6797 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6799 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6802 [self audioTrackPopUpChanged: audiocodecPopUp];
6803 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6804 [self audioTrackMixdownChanged: mixdownPopUp];
6805 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6807 if ([mixdownPopUp selectedItem] == nil)
6809 [self audioTrackPopUpChanged: audiocodecPopUp];
6810 [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6812 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6813 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6814 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6816 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6817 /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6818 *default mixdown bitrate*/
6819 if ([bitratePopUp selectedItem] == nil)
6821 [self audioTrackMixdownChanged: mixdownPopUp];
6824 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6825 [self audioDRCSliderChanged: drcSlider];
6828 /* 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,
6829 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6833 /* 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". */
6834 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6836 hb_audio_config_t * audio;
6837 /* get the audio source audio codec */
6838 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6839 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6840 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6842 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6843 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6845 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6847 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6849 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6851 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6852 [trackLangPopUp selectItemAtIndex: 0];
6853 [self audioTrackPopUpChanged: trackLangPopUp];
6859 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6863 [fAudLang4PopUp selectItemAtIndex: 0];
6864 [self audioTrackPopUpChanged: fAudLang4PopUp];
6868 [fAudLang3PopUp selectItemAtIndex: 0];
6869 [self audioTrackPopUpChanged: fAudLang3PopUp];
6873 [fAudLang2PopUp selectItemAtIndex: 0];
6874 [self audioTrackPopUpChanged: fAudLang2PopUp];
6882 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6884 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6886 [fAudLang1PopUp selectItemAtIndex: 1];
6888 [self audioTrackPopUpChanged: fAudLang1PopUp];
6889 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6890 /* check our pref for core audio and use it in place of faac if preset is built in */
6891 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6892 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6893 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6895 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6898 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6899 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6900 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6902 if ([fAudTrack1MixPopUp selectedItem] == nil)
6904 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6906 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6907 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6908 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6910 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6912 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6913 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6916 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6918 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6920 [fAudLang2PopUp selectItemAtIndex: 1];
6922 [self audioTrackPopUpChanged: fAudLang2PopUp];
6923 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6924 /* check our pref for core audio and use it in place of faac if preset is built in */
6925 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6926 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6927 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6929 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6931 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6932 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6933 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6935 if ([fAudTrack2MixPopUp selectedItem] == nil)
6937 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6939 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6940 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6941 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6943 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6945 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6946 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6948 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6950 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6952 [fAudLang3PopUp selectItemAtIndex: 1];
6954 [self audioTrackPopUpChanged: fAudLang3PopUp];
6955 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6956 /* check our pref for core audio and use it in place of faac if preset is built in */
6957 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6958 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6959 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6961 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6963 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6964 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6965 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6967 if ([fAudTrack3MixPopUp selectedItem] == nil)
6969 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6971 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6972 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6973 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6975 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6977 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6978 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6980 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6982 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6984 [fAudLang4PopUp selectItemAtIndex: 1];
6986 [self audioTrackPopUpChanged: fAudLang4PopUp];
6987 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6988 /* check our pref for core audio and use it in place of faac if preset is built in */
6989 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6990 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6991 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6993 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6995 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6996 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6997 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6999 if ([fAudTrack4MixPopUp selectedItem] == nil)
7001 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7003 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7004 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7005 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7007 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7009 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7010 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7013 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7015 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7017 [fAudLang2PopUp selectItemAtIndex: 0];
7018 [self audioTrackPopUpChanged: fAudLang2PopUp];
7020 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7022 [fAudLang3PopUp selectItemAtIndex: 0];
7023 [self audioTrackPopUpChanged: fAudLang3PopUp];
7025 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7027 [fAudLang4PopUp selectItemAtIndex: 0];
7028 [self audioTrackPopUpChanged: fAudLang4PopUp];
7033 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7034 /* Forced Subtitles */
7035 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7037 /* Picture Settings */
7038 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7039 * height, width, keep ar, anamorphic and crop settings.
7040 * picture filters are handled separately below.
7042 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
7043 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
7044 * preset completely ignores any picture sizing values in the preset.
7046 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
7048 hb_job_t * job = fTitle->job;
7050 /* If Cropping is set to custom, then recall all four crop values from
7051 when the preset was created and apply them */
7052 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
7054 [fPictureController setAutoCrop:NO];
7056 /* Here we use the custom crop values saved at the time the preset was saved */
7057 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
7058 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
7059 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
7060 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
7063 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7065 [fPictureController setAutoCrop:YES];
7066 /* Here we use the auto crop values determined right after scan */
7067 job->crop[0] = AutoCropTop;
7068 job->crop[1] = AutoCropBottom;
7069 job->crop[2] = AutoCropLeft;
7070 job->crop[3] = AutoCropRight;
7075 if ([chosenPreset objectForKey:@"PictureModulus"])
7077 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
7084 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7085 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
7087 /* Use Max Picture settings for whatever the dvd is.*/
7088 [self revertPictureSizeToMax:nil];
7089 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7090 if (job->keep_ratio == 1)
7092 hb_fix_aspect( job, HB_KEEP_WIDTH );
7093 if( job->height > fTitle->height )
7095 job->height = fTitle->height;
7096 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7099 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7101 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7103 /* we check to make sure the presets width/height does not exceed the sources width/height */
7104 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
7106 /* if so, then we use the sources height and width to avoid scaling up */
7107 //job->width = fTitle->width;
7108 //job->height = fTitle->height;
7109 [self revertPictureSizeToMax:nil];
7111 else // source width/height is >= the preset height/width
7113 /* we can go ahead and use the presets values for height and width */
7114 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
7115 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
7117 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7118 if (job->keep_ratio == 1)
7120 hb_fix_aspect( job, HB_KEEP_WIDTH );
7121 if( job->height > fTitle->height )
7123 job->height = fTitle->height;
7124 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7127 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7133 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7134 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7138 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7139 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7140 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7143 [fPictureController setUseDecomb:1];
7144 [fPictureController setDecomb:0];
7145 [fPictureController setDeinterlace:0];
7146 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7148 /* we are using decomb */
7150 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7152 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7154 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7155 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7157 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7163 /* We are using Deinterlace */
7165 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7167 [fPictureController setUseDecomb:0];
7168 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7169 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7170 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7172 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7179 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7181 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7182 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7183 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7185 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7190 [fPictureController setDetelecine:0];
7194 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7196 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7197 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7198 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7200 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7205 [fPictureController setDenoise:0];
7209 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7211 /* if its a one, then its the old on/off deblock, set on to 5*/
7212 [fPictureController setDeblock:5];
7216 /* use the settings intValue */
7217 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7220 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7222 [fPictureController setGrayscale:1];
7226 [fPictureController setGrayscale:0];
7229 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7230 [fPictureController SetTitle:fTitle];
7231 [fPictureController SetTitle:fTitle];
7232 [self calculatePictureSizing:nil];
7238 #pragma mark Manage Presets
7240 - (void) loadPresets {
7241 /* We declare the default NSFileManager into fileManager */
7242 NSFileManager * fileManager = [NSFileManager defaultManager];
7243 /*We define the location of the user presets file */
7244 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7245 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7246 /* We check for the presets.plist */
7247 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7249 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7252 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7253 if (nil == UserPresets)
7255 UserPresets = [[NSMutableArray alloc] init];
7256 [self addFactoryPresets:nil];
7258 [fPresetsOutlineView reloadData];
7260 [self checkBuiltInsForUpdates];
7263 - (void) checkBuiltInsForUpdates {
7265 BOOL updateBuiltInPresets = NO;
7267 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7269 while (tempObject = [enumerator nextObject])
7271 /* iterate through the built in presets to see if any have an old build number */
7272 NSMutableDictionary *thisPresetDict = tempObject;
7273 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7274 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7276 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7278 updateBuiltInPresets = YES;
7283 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7284 if ( updateBuiltInPresets == YES)
7286 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7288 /* Show an alert window that built in presets will be updated */
7289 /*On Screen Notification*/
7292 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7293 [NSApp requestUserAttention:NSCriticalRequest];
7295 /* when alert is dismissed, go ahead and update the built in presets */
7296 [self addFactoryPresets:nil];
7302 - (IBAction) showAddPresetPanel: (id) sender
7304 /* Deselect the currently selected Preset if there is one*/
7305 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7307 /* Populate the preset picture settings popup here */
7308 [fPresetNewPicSettingsPopUp removeAllItems];
7309 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7310 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7311 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7312 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7313 /* Uncheck the preset use filters checkbox */
7314 [fPresetNewPicFiltersCheck setState:NSOffState];
7315 // fPresetNewFolderCheck
7316 [fPresetNewFolderCheck setState:NSOffState];
7317 /* Erase info from the input fields*/
7318 [fPresetNewName setStringValue: @""];
7319 [fPresetNewDesc setStringValue: @""];
7320 /* Show the panel */
7321 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7324 - (IBAction) closeAddPresetPanel: (id) sender
7326 [NSApp endSheet: fAddPresetPanel];
7327 [fAddPresetPanel orderOut: self];
7330 - (IBAction)addUserPreset:(id)sender
7332 if (![[fPresetNewName stringValue] length])
7333 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7336 /* Here we create a custom user preset */
7337 [UserPresets addObject:[self createPreset]];
7340 [self closeAddPresetPanel:nil];
7347 /* We Reload the New Table data for presets */
7348 [fPresetsOutlineView reloadData];
7349 /* We save all of the preset data here */
7357 /* We Sort the Presets By Factory or Custom */
7358 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7359 ascending:YES] autorelease];
7360 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7362 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7363 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7364 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7367 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7368 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7369 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7370 [UserPresets setArray:sortedArray];
7375 - (IBAction)insertPreset:(id)sender
7377 int index = [fPresetsOutlineView selectedRow];
7378 [UserPresets insertObject:[self createPreset] atIndex:index];
7379 [fPresetsOutlineView reloadData];
7383 - (NSDictionary *)createPreset
7385 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7386 /* Preset build number */
7387 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7388 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7389 /* Get the New Preset Name from the field in the AddPresetPanel */
7390 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7391 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7392 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7393 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7394 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7395 /*Set whether or not this is default, at creation set to 0*/
7396 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7397 if ([fPresetNewFolderCheck state] == YES)
7399 /* initialize and set an empty array for children here since we are a new folder */
7400 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7401 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7402 [childrenArray autorelease];
7404 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7406 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7407 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7408 /* Get whether or not to use the current Picture Filter settings for the preset */
7409 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7411 /* Get New Preset Description from the field in the AddPresetPanel*/
7412 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7414 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7415 /* Chapter Markers fCreateChapterMarkers*/
7416 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7417 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7418 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7419 /* Mux mp4 with http optimization */
7420 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7421 /* Add iPod uuid atom */
7422 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7426 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7427 /* x264 Option String */
7428 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7430 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7431 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7432 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7433 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7435 /* Video framerate */
7436 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7438 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7440 else // we can record the actual titleOfSelectedItem
7442 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7445 /* 2 Pass Encoding */
7446 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7447 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7448 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7449 /*Picture Settings*/
7450 hb_job_t * job = fTitle->job;
7451 /* Picture Sizing */
7452 /* Use Max Picture settings for whatever the dvd is.*/
7453 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7454 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7455 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7456 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7457 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7458 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7460 /* Set crop settings here */
7461 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7462 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7463 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7464 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7465 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7467 /* Picture Filters */
7468 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7469 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7470 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7471 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7472 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7473 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7474 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7475 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7476 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7477 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7478 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7481 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7482 /* we actually call the methods for the nests here */
7483 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7485 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7486 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7487 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7488 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7489 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7490 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7491 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7492 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7493 [audioTrack1Array autorelease];
7494 [audioListArray addObject:audioTrack1Array];
7497 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7499 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7500 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7501 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7502 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7503 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7504 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7505 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7506 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7507 [audioTrack2Array autorelease];
7508 [audioListArray addObject:audioTrack2Array];
7511 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7513 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7514 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7515 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7516 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7517 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7518 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7519 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7520 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7521 [audioTrack3Array autorelease];
7522 [audioListArray addObject:audioTrack3Array];
7525 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7527 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7528 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7529 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7530 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7531 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7532 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7533 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7534 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7535 [audioTrack4Array autorelease];
7536 [audioListArray addObject:audioTrack4Array];
7540 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7543 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7544 * subititle array code. */
7546 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7547 /* Forced Subtitles */
7548 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7550 [preset autorelease];
7557 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7558 /* We get the default preset in case it changed */
7559 [self getDefaultPresets:nil];
7563 - (IBAction)deletePreset:(id)sender
7567 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7571 /* Alert user before deleting preset */
7573 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7575 if ( status == NSAlertDefaultReturn )
7577 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7578 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7579 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7581 NSEnumerator *enumerator;
7582 NSMutableArray *presetsArrayToMod;
7583 NSMutableArray *tempArray;
7585 /* If we are a root level preset, we are modding the UserPresets array */
7586 if (presetToModLevel == 0)
7588 presetsArrayToMod = UserPresets;
7590 else // We have a parent preset, so we modify the chidren array object for key
7592 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7595 enumerator = [presetsArrayToMod objectEnumerator];
7596 tempArray = [NSMutableArray array];
7598 while (tempObject = [enumerator nextObject])
7600 NSDictionary *thisPresetDict = tempObject;
7601 if (thisPresetDict == presetToMod)
7603 [tempArray addObject:tempObject];
7607 [presetsArrayToMod removeObjectsInArray:tempArray];
7608 [fPresetsOutlineView reloadData];
7615 #pragma mark Import Export Preset(s)
7617 - (IBAction) browseExportPresetFile: (id) sender
7619 /* Open a panel to let the user choose where and how to save the export file */
7620 NSSavePanel * panel = [NSSavePanel savePanel];
7621 /* We get the current file name and path from the destination field here */
7622 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7624 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7625 modalForWindow: fWindow modalDelegate: self
7626 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7630 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7631 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7633 if( returnCode == NSOKButton )
7635 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7636 NSString *exportPresetsFile = [sheet filename];
7637 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7638 /* We check for the presets.plist */
7639 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7641 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7643 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7644 if (nil == presetsToExport)
7646 presetsToExport = [[NSMutableArray alloc] init];
7648 /* now get and add selected presets to export */
7651 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7653 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7654 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7662 - (IBAction) browseImportPresetFile: (id) sender
7665 NSOpenPanel * panel;
7667 panel = [NSOpenPanel openPanel];
7668 [panel setAllowsMultipleSelection: NO];
7669 [panel setCanChooseFiles: YES];
7670 [panel setCanChooseDirectories: NO ];
7671 NSString * sourceDirectory;
7672 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7674 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7678 sourceDirectory = @"~/Desktop";
7679 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7681 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7682 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7684 /* set this for allowed file types, not sure if we should allow xml or not */
7685 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7686 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7687 modalForWindow: fWindow modalDelegate: self
7688 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7689 contextInfo: sender];
7692 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7693 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7695 if( returnCode == NSOKButton )
7697 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7698 NSString *importPresetsFile = [sheet filename];
7699 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7700 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7701 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7702 /* iterate though the new array of presets to import and add them to our presets array */
7704 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7706 while (tempObject = [enumerator nextObject])
7708 /* make any changes to the incoming preset we see fit */
7709 /* make sure the incoming preset is not tagged as default */
7710 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7711 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7712 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7713 [tempObject setObject:prependedName forKey:@"PresetName"];
7715 /* actually add the new preset to our presets array */
7716 [UserPresets addObject:tempObject];
7719 [presetsToImport autorelease];
7727 #pragma mark Manage Default Preset
7729 - (IBAction)getDefaultPresets:(id)sender
7731 presetHbDefault = nil;
7732 presetUserDefault = nil;
7733 presetUserDefaultParent = nil;
7734 presetUserDefaultParentParent = nil;
7735 NSMutableDictionary *presetHbDefaultParent = nil;
7736 NSMutableDictionary *presetHbDefaultParentParent = nil;
7739 BOOL userDefaultFound = NO;
7740 presetCurrentBuiltInCount = 0;
7741 /* First we iterate through the root UserPresets array to check for defaults */
7742 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7744 while (tempObject = [enumerator nextObject])
7746 NSMutableDictionary *thisPresetDict = tempObject;
7747 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7749 presetHbDefault = thisPresetDict;
7751 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7753 presetUserDefault = thisPresetDict;
7754 userDefaultFound = YES;
7756 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7758 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7762 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7763 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7765 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7766 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7768 while (tempObject = [enumerator nextObject])
7770 NSMutableDictionary *thisPresetDict = tempObject;
7771 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7773 presetHbDefault = thisPresetDict;
7774 presetHbDefaultParent = thisPresetDictParent;
7776 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7778 presetUserDefault = thisPresetDict;
7779 presetUserDefaultParent = thisPresetDictParent;
7780 userDefaultFound = YES;
7783 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7784 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7786 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7787 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7789 while (tempObject = [enumerator nextObject])
7791 NSMutableDictionary *thisPresetDict = tempObject;
7792 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7794 presetHbDefault = thisPresetDict;
7795 presetHbDefaultParent = thisPresetDictParent;
7796 presetHbDefaultParentParent = thisPresetDictParentParent;
7798 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7800 presetUserDefault = thisPresetDict;
7801 presetUserDefaultParent = thisPresetDictParent;
7802 presetUserDefaultParentParent = thisPresetDictParentParent;
7803 userDefaultFound = YES;
7812 /* check to see if a user specified preset was found, if not then assign the parents for
7813 * the presetHbDefault so that we can open the parents for the nested presets
7815 if (userDefaultFound == NO)
7817 presetUserDefaultParent = presetHbDefaultParent;
7818 presetUserDefaultParentParent = presetHbDefaultParentParent;
7822 - (IBAction)setDefaultPreset:(id)sender
7824 /* We need to determine if the item is a folder */
7825 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7831 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7833 /* First make sure the old user specified default preset is removed */
7834 while (tempObject = [enumerator nextObject])
7836 NSMutableDictionary *thisPresetDict = tempObject;
7837 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7839 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7842 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7843 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7845 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7848 while (tempObject = [enumerator nextObject])
7850 NSMutableDictionary *thisPresetDict1 = tempObject;
7851 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7853 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7855 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7856 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7858 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7861 while (tempObject = [enumerator nextObject])
7863 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7865 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7878 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7879 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7880 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7883 NSMutableArray *presetsArrayToMod;
7884 NSMutableArray *tempArray;
7886 /* If we are a root level preset, we are modding the UserPresets array */
7887 if (presetToModLevel == 0)
7889 presetsArrayToMod = UserPresets;
7891 else // We have a parent preset, so we modify the chidren array object for key
7893 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7896 enumerator = [presetsArrayToMod objectEnumerator];
7897 tempArray = [NSMutableArray array];
7899 while (tempObject = [enumerator nextObject])
7901 NSDictionary *thisPresetDict = tempObject;
7902 if (thisPresetDict == presetToMod)
7904 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7906 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7913 /* We save all of the preset data here */
7915 /* We Reload the New Table data for presets */
7916 [fPresetsOutlineView reloadData];
7919 - (IBAction)selectDefaultPreset:(id)sender
7921 NSMutableDictionary *presetToMod;
7922 /* if there is a user specified default, we use it */
7923 if (presetUserDefault)
7925 presetToMod = presetUserDefault;
7927 else if (presetHbDefault) //else we use the built in default presetHbDefault
7929 presetToMod = presetHbDefault;
7936 if (presetUserDefaultParent != nil)
7938 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7941 if (presetUserDefaultParentParent != nil)
7943 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7947 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7948 [self selectPreset:nil];
7953 #pragma mark Manage Built In Presets
7956 - (IBAction)deleteFactoryPresets:(id)sender
7959 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7963 NSMutableArray *tempArray;
7966 tempArray = [NSMutableArray array];
7967 /* we look here to see if the preset is we move on to the next one */
7968 while ( tempObject = [enumerator nextObject] )
7970 /* if the preset is "Factory" then we put it in the array of
7971 presets to delete */
7972 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7974 [tempArray addObject:tempObject];
7978 [UserPresets removeObjectsInArray:tempArray];
7979 [fPresetsOutlineView reloadData];
7984 /* We use this method to recreate new, updated factory presets */
7985 - (IBAction)addFactoryPresets:(id)sender
7988 /* First, we delete any existing built in presets */
7989 [self deleteFactoryPresets: sender];
7990 /* Then we generate new built in presets programmatically with fPresetsBuiltin
7991 * which is all setup in HBPresets.h and HBPresets.m*/
7992 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
7993 /* update build number for built in presets */
7994 /* iterate though the new array of presets to import and add them to our presets array */
7996 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7998 while (tempObject = [enumerator nextObject])
8000 /* Record the apps current build number in the PresetBuildNumber key */
8001 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
8003 /* Preset build number */
8004 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8008 /* report the built in preset updating to the activity log */
8009 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8019 /*******************************
8020 * Subclass of the HBPresetsOutlineView *
8021 *******************************/
8023 @implementation HBPresetsOutlineView
8024 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8028 // By default, NSTableView only drags an image of the first column. Change this to
8029 // drag an image of the queue's icon and PresetName columns.
8030 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8031 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8036 - (void) mouseDown:(NSEvent *)theEvent
8038 [super mouseDown:theEvent];
8044 - (BOOL) isDragging;