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));
205 // call didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
206 // right below to either clear the old queue or keep it loaded up.
210 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
211 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
213 [self browseSources:nil];
216 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
218 [self browseSources:(id)fOpenSourceTitleMMenu];
225 /* check to see if another instance of HandBrake.app is running */
226 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
227 NSDictionary *aDictionary;
229 for (aDictionary in runningAppDictionaries)
231 // NSLog(@"Open App: %@", [aDictionary valueForKey:@"NSApplicationName"]);
233 if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
241 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
243 if (returnCode == NSAlertOtherReturn)
245 [self clearQueueAllItems];
246 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
247 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
249 [self browseSources:nil];
252 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
254 [self browseSources:(id)fOpenSourceTitleMMenu];
259 if ([self hbInstances] == 1)
261 [self setQueueEncodingItemsAsPending];
263 [self showQueueWindow:NULL];
267 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
269 /* if we are in preview full screen mode, we need to go to
270 * windowed mode and release the display before we terminate.
271 * We do it here (instead of applicationWillTerminate) so we
272 * release the displays and can then see the alerts below.
274 if ([fPictureController previewFullScreenMode] == YES)
276 [fPictureController previewGoWindowed:nil];
280 hb_get_state( fQueueEncodeLibhb, &s );
282 if ( s.state != HB_STATE_IDLE )
284 int result = NSRunCriticalAlertPanel(
285 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
286 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
287 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
289 if (result == NSAlertDefaultReturn)
291 return NSTerminateNow;
294 return NSTerminateCancel;
297 // Warn if items still in the queue
298 else if ( fPendingCount > 0 )
300 int result = NSRunCriticalAlertPanel(
301 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
302 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
303 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
305 if ( result == NSAlertDefaultReturn )
306 return NSTerminateNow;
308 return NSTerminateCancel;
311 return NSTerminateNow;
314 - (void)applicationWillTerminate:(NSNotification *)aNotification
317 [browsedSourceDisplayName release];
318 [outputPanel release];
319 [fQueueController release];
320 [fPreviewController release];
321 [fPictureController release];
322 [fApplicationIcon release];
325 hb_close(&fQueueEncodeLibhb);
329 - (void) awakeFromNib
332 [fWindow setExcludedFromWindowsMenu:YES];
333 [fAdvancedOptions setView:fAdvancedView];
335 /* lets setup our presets drawer for drag and drop here */
336 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
337 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
338 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
340 /* Initialize currentScanCount so HB can use it to
341 evaluate successive scans */
342 currentScanCount = 0;
345 /* Init UserPresets .plist */
348 /* Init QueueFile .plist */
349 [self loadQueueFile];
351 fRipIndicatorShown = NO; // initially out of view in the nib
353 /* For 64 bit builds, the threaded animation in the progress
354 * indicators conflicts with the animation in the advanced tab
355 * for reasons not completely clear. jbrjake found a note in the
356 * 10.5 dev notes regarding this possiblility. It was also noted
357 * that unless specified, setUsesThreadedAnimation defaults to true.
358 * So, at least for now we set the indicator animation to NO for
359 * both the scan and regular progress indicators for both 32 and 64 bit
360 * as it test out fine on both and there is no reason our progress indicators
361 * should require their own thread.
364 [fScanIndicator setUsesThreadedAnimation:NO];
365 [fRipIndicator setUsesThreadedAnimation:NO];
369 /* Show/Dont Show Presets drawer upon launch based
370 on user preference DefaultPresetsDrawerShow*/
371 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
373 [fPresetDrawer setDelegate:self];
374 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
375 stringForKey:@"Drawer Size"] );
376 if( drawerSize.width )
377 [fPresetDrawer setContentSize: drawerSize];
378 [fPresetDrawer open];
381 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
382 [fSrcAngleLabel setHidden:YES];
383 [fSrcAnglePopUp setHidden:YES];
386 NSMenuItem *menuItem;
387 [fDstFormatPopUp removeAllItems];
389 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
390 [menuItem setTag: HB_MUX_MP4];
392 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
393 [menuItem setTag: HB_MUX_MKV];
395 [fDstFormatPopUp selectItemAtIndex: 0];
397 [self formatPopUpChanged:nil];
399 /* We enable the create chapters checkbox here since we are .mp4 */
400 [fCreateChapterMarkers setEnabled: YES];
401 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
403 [fCreateChapterMarkers setState: NSOnState];
409 [fDstFile2Field setStringValue: [NSString stringWithFormat:
410 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
413 [fVidEncoderPopUp removeAllItems];
414 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
419 [fVidTargetSizeField setIntValue: 700];
420 [fVidBitrateField setIntValue: 1000];
422 [fVidQualityMatrix selectCell: fVidBitrateCell];
423 [self videoMatrixChanged:nil];
425 /* Video framerate */
426 [fVidRatePopUp removeAllItems];
427 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
428 for( int i = 0; i < hb_video_rates_count; i++ )
430 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
432 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
433 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
435 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
437 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
438 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
440 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
442 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
443 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
447 [fVidRatePopUp addItemWithTitle:
448 [NSString stringWithUTF8String: hb_video_rates[i].string]];
451 [fVidRatePopUp selectItemAtIndex: 0];
453 /* Set Auto Crop to On at launch */
454 [fPictureController setAutoCrop:YES];
457 [fAudTrack1BitratePopUp removeAllItems];
458 for( int i = 0; i < hb_audio_bitrates_count; i++ )
460 [fAudTrack1BitratePopUp addItemWithTitle:
461 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
464 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
466 /* Audio samplerate */
467 [fAudTrack1RatePopUp removeAllItems];
468 for( int i = 0; i < hb_audio_rates_count; i++ )
470 [fAudTrack1RatePopUp addItemWithTitle:
471 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
473 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
476 [fStatusField setStringValue: @""];
481 /* We disable the Turbo 1st pass checkbox since we are not x264 */
482 [fVidTurboPassCheck setEnabled: NO];
483 [fVidTurboPassCheck setState: NSOffState];
486 /* lets get our default prefs here */
487 [self getDefaultPresets:nil];
488 /* lets initialize the current successful scancount here to 0 */
489 currentSuccessfulScanCount = 0;
494 - (void) enableUI: (bool) b
496 NSControl * controls[] =
497 { fSrcTitleField, fSrcTitlePopUp,
498 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
499 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
500 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
501 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
502 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
503 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
504 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
505 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
506 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
507 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
508 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
509 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
510 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
511 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
512 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
513 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
514 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel};
517 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
519 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
521 NSTextField * tf = (NSTextField *) controls[i];
522 if( ![tf isBezeled] )
524 [tf setTextColor: b ? [NSColor controlTextColor] :
525 [NSColor disabledControlTextColor]];
529 [controls[i] setEnabled: b];
535 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
536 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
537 [self setEnabledStateOfAudioMixdownControls:nil];
538 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
539 [self calculatePictureSizing:nil];
543 [fPresetsOutlineView setEnabled: NO];
547 [self videoMatrixChanged:nil];
548 [fAdvancedOptions enableUI:b];
552 /***********************************************************************
554 ***********************************************************************
555 * Shows a progression bar on the dock icon, filled according to
556 * 'progress' (0.0 <= progress <= 1.0).
557 * Called with progress < 0.0 or progress > 1.0, restores the original
559 **********************************************************************/
560 - (void) UpdateDockIcon: (float) progress
563 NSBitmapImageRep * bmp;
565 uint32_t black = htonl( 0x000000FF );
566 uint32_t red = htonl( 0xFF0000FF );
567 uint32_t white = htonl( 0xFFFFFFFF );
568 int row_start, row_end;
571 if( progress < 0.0 || progress > 1.0 )
573 [NSApp setApplicationIconImage: fApplicationIcon];
577 /* Get it in a raw bitmap form */
578 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
579 NSTIFFCompressionNone factor: 1.0];
580 bmp = [NSBitmapImageRep imageRepWithData: tiff];
582 /* Draw the progression bar */
583 /* It's pretty simple (ugly?) now, but I'm no designer */
585 row_start = 3 * (int) [bmp size].height / 4;
586 row_end = 7 * (int) [bmp size].height / 8;
588 for( i = row_start; i < row_start + 2; i++ )
590 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
591 for( j = 0; j < (int) [bmp size].width; j++ )
596 for( i = row_start + 2; i < row_end - 2; i++ )
598 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
601 for( j = 2; j < (int) [bmp size].width - 2; j++ )
603 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
615 for( i = row_end - 2; i < row_end; i++ )
617 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
618 for( j = 0; j < (int) [bmp size].width; j++ )
624 /* Now update the dock icon */
625 tiff = [bmp TIFFRepresentationUsingCompression:
626 NSTIFFCompressionNone factor: 1.0];
627 NSImage* icon = [[NSImage alloc] initWithData: tiff];
628 [NSApp setApplicationIconImage: icon];
632 - (void) updateUI: (NSTimer *) timer
635 /* Update UI for fHandle (user scanning instance of libhb ) */
638 list = hb_get_titles( fHandle );
639 /* check to see if there has been a new scan done
640 this bypasses the constraints of HB_STATE_WORKING
641 not allowing setting a newly scanned source */
642 int checkScanCount = hb_get_scancount( fHandle );
643 if( checkScanCount > currentScanCount )
645 currentScanCount = checkScanCount;
646 [fScanIndicator setIndeterminate: NO];
647 [fScanIndicator setDoubleValue: 0.0];
648 [fScanIndicator setHidden: YES];
649 [self showNewScan:nil];
653 hb_get_state( fHandle, &s );
659 #define p s.param.scanning
660 case HB_STATE_SCANNING:
662 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
663 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
664 p.title_cur, p.title_count]];
665 [fScanIndicator setHidden: NO];
666 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
671 #define p s.param.scandone
672 case HB_STATE_SCANDONE:
674 [fScanIndicator setIndeterminate: NO];
675 [fScanIndicator setDoubleValue: 0.0];
676 [fScanIndicator setHidden: YES];
677 [self writeToActivityLog:"ScanDone state received from fHandle"];
678 [self showNewScan:nil];
679 [[fWindow toolbar] validateVisibleItems];
685 #define p s.param.working
686 case HB_STATE_WORKING:
693 #define p s.param.muxing
694 case HB_STATE_MUXING:
701 case HB_STATE_PAUSED:
704 case HB_STATE_WORKDONE:
711 /* Update UI for fQueueEncodeLibhb */
713 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
714 /* check to see if there has been a new scan done
715 this bypasses the constraints of HB_STATE_WORKING
716 not allowing setting a newly scanned source */
718 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
719 if( checkScanCount > currentScanCount )
721 currentScanCount = checkScanCount;
725 hb_get_state( fQueueEncodeLibhb, &s );
731 #define p s.param.scanning
732 case HB_STATE_SCANNING:
734 [fStatusField setStringValue: [NSString stringWithFormat:
735 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
736 p.title_cur, p.title_count]];
738 /* Set the status string in fQueueController as well */
739 [fQueueController setQueueStatusString: [NSString stringWithFormat:
740 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
741 p.title_cur, p.title_count]];
746 #define p s.param.scandone
747 case HB_STATE_SCANDONE:
749 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
750 [self processNewQueueEncode];
751 [[fWindow toolbar] validateVisibleItems];
757 #define p s.param.working
758 case HB_STATE_WORKING:
760 NSMutableString * string;
761 NSString * pass_desc;
762 /* Update text field */
763 if (p.job_cur == 1 && p.job_count > 1)
765 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
767 pass_desc = @"(subtitle scan)";
779 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
783 [string appendFormat:
784 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
785 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
788 [fStatusField setStringValue: string];
789 /* Set the status string in fQueueController as well */
790 [fQueueController setQueueStatusString: string];
792 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
793 [fRipIndicator setIndeterminate: NO];
794 [fRipIndicator setDoubleValue:100.0 * progress_total];
796 // If progress bar hasn't been revealed at the bottom of the window, do
797 // that now. This code used to be in doRip. I moved it to here to handle
798 // the case where hb_start is called by HBQueueController and not from
800 if( !fRipIndicatorShown )
802 NSRect frame = [fWindow frame];
803 if( frame.size.width <= 591 )
804 frame.size.width = 591;
805 frame.size.height += 36;
806 frame.origin.y -= 36;
807 [fWindow setFrame:frame display:YES animate:YES];
808 fRipIndicatorShown = YES;
812 /* Update dock icon */
813 if( dockIconProgress < 100.0 * progress_total )
815 [self UpdateDockIcon: progress_total];
816 dockIconProgress += 5;
823 #define p s.param.muxing
824 case HB_STATE_MUXING:
826 /* Update text field */
827 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
828 /* Set the status string in fQueueController as well */
829 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
831 [fRipIndicator setIndeterminate: YES];
832 [fRipIndicator startAnimation: nil];
834 /* Update dock icon */
835 [self UpdateDockIcon: 1.0];
841 case HB_STATE_PAUSED:
842 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
843 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
847 case HB_STATE_WORKDONE:
849 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
850 // or someone calling hb_stop. In the latter case, hb_stop does not clear
851 // out the remaining passes/jobs in the queue. We'll do that here.
853 // Delete all remaining jobs of this encode.
854 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
855 /* Set the status string in fQueueController as well */
856 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
857 [fRipIndicator setIndeterminate: NO];
858 [fRipIndicator stopAnimation: nil];
859 [fRipIndicator setDoubleValue: 0.0];
860 [[fWindow toolbar] validateVisibleItems];
862 /* Restore dock icon */
863 [self UpdateDockIcon: -1.0];
864 dockIconProgress = 0;
866 if( fRipIndicatorShown )
868 NSRect frame = [fWindow frame];
869 if( frame.size.width <= 591 )
870 frame.size.width = 591;
871 frame.size.height += -36;
872 frame.origin.y -= -36;
873 [fWindow setFrame:frame display:YES animate:YES];
874 fRipIndicatorShown = NO;
876 /* Since we are done with this encode, tell output to stop writing to the
877 * individual encode log
879 [outputPanel endEncodeLog];
880 /* Check to see if the encode state has not been cancelled
881 to determine if we should check for encode done notifications */
882 if( fEncodeState != 2 )
884 NSString *pathOfFinishedEncode;
885 /* Get the output file name for the finished encode */
886 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
888 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
890 [self showGrowlDoneNotification:pathOfFinishedEncode];
892 [self sendToMetaX:pathOfFinishedEncode];
894 /* since we have successfully completed an encode, we increment the queue counter */
895 [self incrementQueueItemDone:nil];
897 /* all end of queue actions below need to be done after all queue encodes have finished
898 * and there are no pending jobs left to process
900 if (fPendingCount == 0)
902 /* If Alert Window or Window and Growl has been selected */
903 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
904 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
906 /*On Screen Notification*/
909 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
910 [NSApp requestUserAttention:NSCriticalRequest];
913 /* If sleep has been selected */
914 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
917 NSDictionary* errorDict;
918 NSAppleEventDescriptor* returnDescriptor = nil;
919 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
920 @"tell application \"Finder\" to sleep"];
921 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
922 [scriptObject release];
924 /* If Shutdown has been selected */
925 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
928 NSDictionary* errorDict;
929 NSAppleEventDescriptor* returnDescriptor = nil;
930 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
931 @"tell application \"Finder\" to shut down"];
932 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
933 [scriptObject release];
947 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
948 - (void) writeToActivityLog:(const char *) format, ...
951 va_start(args, format);
955 vsnprintf( str, 1024, format, args );
957 time_t _now = time( NULL );
958 struct tm * now = localtime( &_now );
959 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
966 // ============================================================
967 // NSToolbar Related Methods
968 // ============================================================
970 - (void) setupToolbar {
971 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
973 [toolbar setAllowsUserCustomization: YES];
974 [toolbar setAutosavesConfiguration: YES];
975 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
977 [toolbar setDelegate: self];
979 [fWindow setToolbar: toolbar];
982 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
983 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
984 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
986 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
988 [item setLabel: @"Toggle Presets"];
989 [item setPaletteLabel: @"Toggler Presets"];
990 [item setToolTip: @"Open/Close Preset Drawer"];
991 [item setImage: [NSImage imageNamed: @"Drawer"]];
992 [item setTarget: self];
993 [item setAction: @selector(toggleDrawer:)];
994 [item setAutovalidates: NO];
996 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
998 [item setLabel: @"Start"];
999 [item setPaletteLabel: @"Start Encoding"];
1000 [item setToolTip: @"Start Encoding"];
1001 [item setImage: [NSImage imageNamed: @"Play"]];
1002 [item setTarget: self];
1003 [item setAction: @selector(Rip:)];
1005 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1007 [item setLabel: @"Show Queue"];
1008 [item setPaletteLabel: @"Show Queue"];
1009 [item setToolTip: @"Show Queue"];
1010 [item setImage: [NSImage imageNamed: @"Queue"]];
1011 [item setTarget: self];
1012 [item setAction: @selector(showQueueWindow:)];
1013 [item setAutovalidates: NO];
1015 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1017 [item setLabel: @"Add to Queue"];
1018 [item setPaletteLabel: @"Add to Queue"];
1019 [item setToolTip: @"Add to Queue"];
1020 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1021 [item setTarget: self];
1022 [item setAction: @selector(addToQueue:)];
1024 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1026 [item setLabel: @"Pause"];
1027 [item setPaletteLabel: @"Pause Encoding"];
1028 [item setToolTip: @"Pause Encoding"];
1029 [item setImage: [NSImage imageNamed: @"Pause"]];
1030 [item setTarget: self];
1031 [item setAction: @selector(Pause:)];
1033 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1035 [item setLabel: @"Picture Settings"];
1036 [item setPaletteLabel: @"Show Picture Settings"];
1037 [item setToolTip: @"Show Picture Settings"];
1038 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1039 [item setTarget: self];
1040 [item setAction: @selector(showPicturePanel:)];
1042 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1044 [item setLabel: @"Preview Window"];
1045 [item setPaletteLabel: @"Show Preview"];
1046 [item setToolTip: @"Show Preview"];
1047 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1048 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1049 [item setTarget: self];
1050 [item setAction: @selector(showPreviewWindow:)];
1052 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1054 [item setLabel: @"Activity Window"];
1055 [item setPaletteLabel: @"Show Activity Window"];
1056 [item setToolTip: @"Show Activity Window"];
1057 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1058 [item setTarget: self];
1059 [item setAction: @selector(showDebugOutputPanel:)];
1060 [item setAutovalidates: NO];
1062 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1064 [item setLabel: @"Source"];
1065 [item setPaletteLabel: @"Source"];
1066 [item setToolTip: @"Choose Video Source"];
1067 [item setImage: [NSImage imageNamed: @"Source"]];
1068 [item setTarget: self];
1069 [item setAction: @selector(browseSources:)];
1079 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1081 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1082 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1083 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1086 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1088 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1089 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1090 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1091 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1094 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1096 NSString * ident = [toolbarItem itemIdentifier];
1102 hb_get_state( fHandle, &s );
1103 if (s.state == HB_STATE_SCANNING && ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier]))
1106 hb_get_state2( fQueueEncodeLibhb, &s );
1108 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
1110 if ([ident isEqualToString: StartEncodingIdentifier])
1112 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1113 [toolbarItem setLabel: @"Stop"];
1114 [toolbarItem setPaletteLabel: @"Stop"];
1115 [toolbarItem setToolTip: @"Stop Encoding"];
1118 if ([ident isEqualToString: PauseEncodingIdentifier])
1120 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1121 [toolbarItem setLabel: @"Pause"];
1122 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1123 [toolbarItem setToolTip: @"Pause Encoding"];
1128 if ([ident isEqualToString: AddToQueueIdentifier])
1130 if ([ident isEqualToString: ShowPictureIdentifier])
1132 if ([ident isEqualToString: ShowPreviewIdentifier])
1136 else if (s.state == HB_STATE_PAUSED)
1138 if ([ident isEqualToString: PauseEncodingIdentifier])
1140 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1141 [toolbarItem setLabel: @"Resume"];
1142 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1143 [toolbarItem setToolTip: @"Resume Encoding"];
1146 if ([ident isEqualToString: StartEncodingIdentifier])
1148 if ([ident isEqualToString: AddToQueueIdentifier])
1150 if ([ident isEqualToString: ShowPictureIdentifier])
1152 if ([ident isEqualToString: ShowPreviewIdentifier])
1155 else if (s.state == HB_STATE_SCANNING)
1157 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1159 if ([ident isEqualToString: StartEncodingIdentifier])
1161 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1162 if (hb_count(fHandle) > 0)
1163 [toolbarItem setLabel: @"Start Queue"];
1165 [toolbarItem setLabel: @"Start"];
1166 [toolbarItem setPaletteLabel: @"Start Encoding"];
1167 [toolbarItem setToolTip: @"Start Encoding"];
1170 if ([ident isEqualToString: AddToQueueIdentifier])
1172 if ([ident isEqualToString: ShowPictureIdentifier])
1174 if ([ident isEqualToString: ShowPreviewIdentifier])
1179 /* If there are any pending queue items, make sure the start/stop button is active */
1180 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1182 if ([ident isEqualToString: ShowQueueIdentifier])
1184 if ([ident isEqualToString: ToggleDrawerIdentifier])
1186 if ([ident isEqualToString: ChooseSourceIdentifier])
1188 if ([ident isEqualToString: ShowActivityIdentifier])
1194 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1196 SEL action = [menuItem action];
1199 hb_get_state2( fHandle, &s );
1203 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1204 return SuccessfulScan && [fWindow attachedSheet] == nil;
1206 if (action == @selector(browseSources:))
1208 if (s.state == HB_STATE_SCANNING)
1211 return [fWindow attachedSheet] == nil;
1213 if (action == @selector(selectDefaultPreset:))
1214 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1215 if (action == @selector(Pause:))
1217 if (s.state == HB_STATE_WORKING)
1219 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1220 [menuItem setTitle:@"Pause Encoding"];
1223 else if (s.state == HB_STATE_PAUSED)
1225 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1226 [menuItem setTitle:@"Resume Encoding"];
1232 if (action == @selector(Rip:))
1234 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1236 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1237 [menuItem setTitle:@"Stop Encoding"];
1240 else if (SuccessfulScan)
1242 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1243 [menuItem setTitle:@"Start Encoding"];
1244 return [fWindow attachedSheet] == nil;
1250 if( action == @selector(setDefaultPreset:) )
1252 return [fPresetsOutlineView selectedRow] != -1;
1259 #pragma mark Encode Done Actions
1260 // register a test notification and make
1261 // it enabled by default
1262 #define SERVICE_NAME @"Encode Done"
1263 - (NSDictionary *)registrationDictionaryForGrowl
1265 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1266 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1267 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1270 return registrationDictionary;
1273 -(void)showGrowlDoneNotification:(NSString *) filePath
1275 /* This end of encode action is called as each encode rolls off of the queue */
1276 NSString * finishedEncode = filePath;
1277 /* strip off the path to just show the file name */
1278 finishedEncode = [finishedEncode lastPathComponent];
1279 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1280 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1282 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1283 [GrowlApplicationBridge
1284 notifyWithTitle:@"Put down that cocktail..."
1285 description:growlMssg
1286 notificationName:SERVICE_NAME
1294 -(void)sendToMetaX:(NSString *) filePath
1296 /* This end of encode action is called as each encode rolls off of the queue */
1297 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1299 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
1300 [myScript executeAndReturnError: nil];
1305 #pragma mark Get New Source
1307 /*Opens the source browse window, called from Open Source widgets */
1308 - (IBAction) browseSources: (id) sender
1310 NSOpenPanel * panel;
1312 panel = [NSOpenPanel openPanel];
1313 [panel setAllowsMultipleSelection: NO];
1314 [panel setCanChooseFiles: YES];
1315 [panel setCanChooseDirectories: YES ];
1316 NSString * sourceDirectory;
1317 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1319 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1323 sourceDirectory = @"~/Desktop";
1324 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1326 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1327 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1329 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1330 modalForWindow: fWindow modalDelegate: self
1331 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1332 contextInfo: sender];
1335 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1336 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1338 /* we convert the sender content of contextInfo back into a variable called sender
1339 * mostly just for consistency for evaluation later
1341 id sender = (id)contextInfo;
1342 /* User selected a file to open */
1343 if( returnCode == NSOKButton )
1345 /* Free display name allocated previously by this code */
1346 [browsedSourceDisplayName release];
1348 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1349 /* we set the last searched source directory in the prefs here */
1350 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1351 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1352 /* we order out sheet, which is the browse window as we need to open
1353 * the title selection sheet right away
1355 [sheet orderOut: self];
1357 if (sender == fOpenSourceTitleMMenu)
1359 /* We put the chosen source path in the source display text field for the
1360 * source title selection sheet in which the user specifies the specific title to be
1361 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1362 * purposes in the title panel
1365 [fScanSrcTitlePathField setStringValue:scanPath];
1366 NSString *displayTitlescanSourceName;
1368 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1370 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1371 we have to use the title->dvd value so we get the proper name of the volume if a physical dvd is the source*/
1372 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1376 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1377 displayTitlescanSourceName = [scanPath lastPathComponent];
1379 /* we set the source display name in the title selection dialogue */
1380 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1381 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1382 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1383 /* We show the actual sheet where the user specifies the title to be scanned
1384 * as we are going to do a title specific scan
1386 [self showSourceTitleScanPanel:nil];
1390 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1391 NSString *path = [[sheet filenames] objectAtIndex: 0];
1393 /* We check to see if the chosen file at path is a package */
1394 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1396 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1397 /* We check to see if this is an .eyetv package */
1398 if ([[path pathExtension] isEqualToString: @"eyetv"])
1400 [self writeToActivityLog:"trying to open eyetv package"];
1401 /* We're looking at an EyeTV package - try to open its enclosed
1403 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1405 int n = [[path stringByAppendingString: @"/"]
1406 completePathIntoString: &mpgname caseSensitive: YES
1407 matchesIntoArray: nil
1408 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1411 /* Found an mpeg inside the eyetv package, make it our scan path
1412 and call performScan on the enclosed mpeg */
1414 [self writeToActivityLog:"found mpeg in eyetv package"];
1415 [self performScan:path scanTitleNum:0];
1419 /* We did not find an mpeg file in our package, so we do not call performScan */
1420 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1423 /* We check to see if this is a .dvdmedia package */
1424 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1426 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1427 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1428 [self writeToActivityLog:"trying to open dvdmedia package"];
1429 [self performScan:path scanTitleNum:0];
1433 /* The package is not an eyetv package, so we do not call performScan */
1434 [self writeToActivityLog:"unable to open package"];
1437 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1439 /* path is not a package, so we call perform scan directly on our file */
1440 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1442 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1443 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1444 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1448 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1449 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1450 /* make sure we remove any path extension as this can also be an '.mpg' file */
1451 browsedSourceDisplayName = [[path lastPathComponent] retain];
1453 [self performScan:path scanTitleNum:0];
1461 - (IBAction)showAboutPanel:(id)sender
1463 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1464 fApplicationIcon, @"ApplicationIcon",
1466 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1470 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1471 - (IBAction) showSourceTitleScanPanel: (id) sender
1473 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1476 [fScanSrcTitleNumField setStringValue: @"0"];
1477 /* Show the panel */
1478 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1481 - (IBAction) closeSourceTitleScanPanel: (id) sender
1483 [NSApp endSheet: fScanSrcTitlePanel];
1484 [fScanSrcTitlePanel orderOut: self];
1486 if(sender == fScanSrcTitleOpenButton)
1488 /* We setup the scan status in the main window to indicate a source title scan */
1489 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1490 [fScanIndicator setHidden: NO];
1491 [fScanIndicator setIndeterminate: YES];
1492 [fScanIndicator startAnimation: nil];
1494 /* We use the performScan method to actually perform the specified scan passing the path and the title
1497 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1501 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1502 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1504 /* set the bool applyQueueToScan so that we dont apply a queue setting to the final scan */
1505 applyQueueToScan = NO;
1506 /* use a bool to determine whether or not we can decrypt using vlc */
1507 BOOL cancelScanDecrypt = 0;
1508 NSString *path = scanPath;
1509 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1511 // Notify ChapterTitles that there's no title
1512 [fChapterTitlesDelegate resetWithTitle:nil];
1513 [fChapterTable reloadData];
1515 // Notify Subtitles that there's no title
1516 [fSubtitlesDelegate resetWithTitle:nil];
1517 [fSubtitlesTable reloadData];
1519 [self enableUI: NO];
1521 if( [detector isVideoDVD] )
1524 #if defined( __LP64__ )
1533 // The chosen path was actually on a DVD, so use the raw block
1534 // device path instead.
1535 path = [detector devicePath];
1536 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1538 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1539 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1540 NSFileManager * fileManager = [NSFileManager defaultManager];
1541 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1543 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1544 cancelScanDecrypt = 1;
1545 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1547 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");
1548 [NSApp requestUserAttention:NSCriticalRequest];
1550 if (status == NSAlertDefaultReturn)
1552 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1553 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1555 else if (status == NSAlertAlternateReturn)
1557 /* User chose to cancel the scan */
1558 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1562 /* 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 */
1563 cancelScanDecrypt = 0;
1564 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1570 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1571 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1573 /* test for architecture of the vlc app */
1574 NSArray *vlc_architecturesArray = [[NSBundle bundleWithPath:@"/Applications/VLC.app"] executableArchitectures];
1575 BOOL vlcIntel32bit = NO;
1576 BOOL vlcIntel64bit = NO;
1577 BOOL vlcPPC32bit = NO;
1578 BOOL vlcPPC64bit = NO;
1579 /* check the available architectures for vlc and note accordingly */
1580 NSEnumerator *enumerator = [vlc_architecturesArray objectEnumerator];
1582 while (tempObject = [enumerator nextObject])
1585 if ([tempObject intValue] == NSBundleExecutableArchitectureI386)
1587 vlcIntel32bit = YES;
1589 if ([tempObject intValue] == NSBundleExecutableArchitectureX86_64)
1591 vlcIntel64bit = YES;
1593 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC)
1597 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC64)
1603 /* Write vlc architecture findings to activity window */
1606 [self writeToActivityLog: " 32-Bit VLC app found for decrypting physical dvd"];
1610 [self writeToActivityLog: " 64-Bit VLC app found for decrypting physical dvd"];
1615 if (hb_arch == 64 && !vlcIntel64bit && cancelScanDecrypt != 1)
1620 /* Appropriate VLC not found, so cancel */
1621 cancelScanDecrypt = 1;
1622 [self writeToActivityLog: "This version of HandBrake is 64 bit, 64 bit version of vlc not found, scan cancelled"];
1623 /*On Screen Notification*/
1626 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);
1627 [NSApp requestUserAttention:NSCriticalRequest];
1629 if (status == NSAlertDefaultReturn)
1631 /* User chose to cancel the scan */
1632 [self writeToActivityLog: "cannot open physical dvd VLC found but not 64 bit, scan cancelled"];
1633 cancelScanDecrypt = 1;
1635 else if (status == NSAlertDefaultReturn)
1637 [self writeToActivityLog: "user overrode 64-bit warning trying to open physical dvd without proper decryption"];
1638 cancelScanDecrypt = 0;
1642 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1643 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1647 else if (hb_arch == 32 && !vlcIntel32bit && cancelScanDecrypt != 1)
1650 /* Appropriate VLC not found, so cancel */
1651 cancelScanDecrypt = 1;
1652 [self writeToActivityLog: "This version of HandBrake is 32 bit, 32 bit version of vlc not found, scan cancelled"];
1653 /*On Screen Notification*/
1656 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);
1657 [NSApp requestUserAttention:NSCriticalRequest];
1659 if (status == NSAlertDefaultReturn)
1661 /* User chose to cancel the scan */
1662 [self writeToActivityLog: "cannot open physical dvd VLC found but not 32 bit, scan cancelled"];
1663 cancelScanDecrypt = 1;
1665 else if (status == NSAlertDefaultReturn)
1667 [self writeToActivityLog: "user overrode 32-bit warning trying to open physical dvd without proper decryption"];
1668 cancelScanDecrypt = 0;
1672 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1673 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1679 if (cancelScanDecrypt == 0)
1681 /* we actually pass the scan off to libhb here */
1682 /* If there is no title number passed to scan, we use "0"
1683 * which causes the default behavior of a full source scan
1689 if (scanTitleNum > 0)
1691 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1693 /* We use our advance pref to determine how many previews to scan */
1694 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1695 /* set title to NULL */
1697 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1698 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1702 - (IBAction) showNewScan:(id)sender
1706 int indxpri=0; // Used to search the longuest title (default in combobox)
1707 int longuestpri=0; // Used to search the longuest title (default in combobox)
1710 list = hb_get_titles( fHandle );
1712 if( !hb_list_count( list ) )
1714 /* We display a message if a valid dvd source was not chosen */
1715 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1716 SuccessfulScan = NO;
1718 // Notify ChapterTitles that there's no title
1719 [fSubtitlesDelegate resetWithTitle:nil];
1720 [fSubtitlesTable reloadData];
1722 // Notify Subtitles that there's no title
1723 [fChapterTitlesDelegate resetWithTitle:nil];
1724 [fChapterTable reloadData];
1728 /* We increment the successful scancount here by one,
1729 which we use at the end of this function to tell the gui
1730 if this is the first successful scan since launch and whether
1731 or not we should set all settings to the defaults */
1733 currentSuccessfulScanCount++;
1735 [[fWindow toolbar] validateVisibleItems];
1737 [fSrcTitlePopUp removeAllItems];
1738 for( int i = 0; i < hb_list_count( list ); i++ )
1740 title = (hb_title_t *) hb_list_item( list, i );
1742 currentSource = [NSString stringWithUTF8String: title->name];
1743 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1744 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1746 /* Use the dvd name in the default output field here
1747 May want to add code to remove blank spaces for some dvd names*/
1748 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1749 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1751 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1752 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1756 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1757 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1761 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1763 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1767 [fSrcTitlePopUp addItemWithTitle: [NSString
1768 stringWithFormat: @"%d - %02dh%02dm%02ds",
1769 title->index, title->hours, title->minutes,
1773 // Select the longuest title
1774 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1775 [self titlePopUpChanged:nil];
1777 SuccessfulScan = YES;
1778 [self enableUI: YES];
1780 /* if its the initial successful scan after awakeFromNib */
1781 if (currentSuccessfulScanCount == 1)
1783 [self selectDefaultPreset:nil];
1785 // Open preview window now if it was visible when HB was closed
1786 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1787 [self showPreviewWindow:nil];
1789 // Open picture sizing window now if it was visible when HB was closed
1790 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1791 [self showPicturePanel:nil];
1802 #pragma mark New Output Destination
1804 - (IBAction) browseFile: (id) sender
1806 /* Open a panel to let the user choose and update the text field */
1807 NSSavePanel * panel = [NSSavePanel savePanel];
1808 /* We get the current file name and path from the destination field here */
1809 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1810 modalForWindow: fWindow modalDelegate: self
1811 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1815 - (void) browseFileDone: (NSSavePanel *) sheet
1816 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1818 if( returnCode == NSOKButton )
1820 [fDstFile2Field setStringValue: [sheet filename]];
1821 /* Save this path to the prefs so that on next browse destination window it opens there */
1822 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1823 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1829 #pragma mark Main Window Control
1831 - (IBAction) openMainWindow: (id) sender
1833 [fWindow makeKeyAndOrderFront:nil];
1836 - (BOOL) windowShouldClose: (id) sender
1841 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1844 [fWindow makeKeyAndOrderFront:nil];
1852 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1853 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1858 #pragma mark Queue File
1860 - (void) loadQueueFile {
1861 /* We declare the default NSFileManager into fileManager */
1862 NSFileManager * fileManager = [NSFileManager defaultManager];
1863 /*We define the location of the user presets file */
1864 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1865 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1866 /* We check for the presets.plist */
1867 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1869 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1872 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1873 /* lets check to see if there is anything in the queue file .plist */
1874 if (nil == QueueFileArray)
1876 /* if not, then lets initialize an empty array */
1877 QueueFileArray = [[NSMutableArray alloc] init];
1879 /* Initialize our curQueueEncodeIndex to 0
1880 * so we can use it to track which queue
1881 * item is to be used to track our encodes */
1882 /* NOTE: this should be changed if and when we
1883 * are able to get the last unfinished encode
1884 * in the case of a crash or shutdown */
1889 [self clearQueueEncodedItems];
1891 currentQueueEncodeIndex = 0;
1894 - (void)addQueueFileItem
1896 [QueueFileArray addObject:[self createQueueFileItem]];
1897 [self saveQueueFileItem];
1901 - (void) removeQueueFileItem:(int) queueItemToRemove
1904 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
1905 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
1907 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
1908 * by one to keep in sync with the queue array
1910 currentQueueEncodeIndex--;
1911 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
1913 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1914 [self saveQueueFileItem];
1918 - (void)saveQueueFileItem
1920 [QueueFileArray writeToFile:QueueFile atomically:YES];
1921 [fQueueController setQueueArray: QueueFileArray];
1922 [self getQueueStats];
1925 - (void)getQueueStats
1927 /* lets get the stats on the status of the queue array */
1929 fEncodingQueueItem = 0;
1931 fCompletedCount = 0;
1935 /* We use a number system to set the encode status of the queue item
1937 * 0 == already encoded
1938 * 1 == is being encoded
1939 * 2 == is yet to be encoded
1944 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1946 while (tempObject = [enumerator nextObject])
1948 NSDictionary *thisQueueDict = tempObject;
1949 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1953 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1956 fEncodingQueueItem = i;
1958 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
1962 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
1969 /* Set the queue status field in the main window */
1970 NSMutableString * string;
1971 if (fPendingCount == 1)
1973 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
1977 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
1979 [fQueueStatus setStringValue:string];
1982 /* This method will set any item marked as encoding back to pending
1983 * currently used right after a queue reload
1985 - (void) setQueueEncodingItemsAsPending
1987 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1989 NSMutableArray *tempArray;
1990 tempArray = [NSMutableArray array];
1991 /* we look here to see if the preset is we move on to the next one */
1992 while ( tempObject = [enumerator nextObject] )
1994 /* If the queue item is marked as "encoding" (1)
1995 * then change its status back to pending (2) which effectively
1996 * puts it back into the queue to be encoded
1998 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2000 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2002 [tempArray addObject:tempObject];
2005 [QueueFileArray setArray:tempArray];
2006 [self saveQueueFileItem];
2010 /* This method will clear the queue of any encodes that are not still pending
2011 * this includes both successfully completed encodes as well as cancelled encodes */
2012 - (void) clearQueueEncodedItems
2014 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2016 NSMutableArray *tempArray;
2017 tempArray = [NSMutableArray array];
2018 /* we look here to see if the preset is we move on to the next one */
2019 while ( tempObject = [enumerator nextObject] )
2021 /* If the queue item is either completed (0) or cancelled (3) from the
2022 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2023 * NOTE: this means we retain pending (2) and also an item that is marked as
2024 * still encoding (1). If the queue has an item that is still marked as encoding
2025 * from a previous session, we can conlude that HB was either shutdown, or crashed
2026 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2028 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2030 [tempArray addObject:tempObject];
2034 [QueueFileArray removeObjectsInArray:tempArray];
2035 [self saveQueueFileItem];
2038 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2039 - (void) clearQueueAllItems
2041 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2043 NSMutableArray *tempArray;
2044 tempArray = [NSMutableArray array];
2045 /* we look here to see if the preset is we move on to the next one */
2046 while ( tempObject = [enumerator nextObject] )
2048 [tempArray addObject:tempObject];
2051 [QueueFileArray removeObjectsInArray:tempArray];
2052 [self saveQueueFileItem];
2055 /* This method will duplicate prepareJob however into the
2056 * queue .plist instead of into the job structure so it can
2057 * be recalled later */
2058 - (NSDictionary *)createQueueFileItem
2060 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2062 hb_list_t * list = hb_get_titles( fHandle );
2063 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2064 [fSrcTitlePopUp indexOfSelectedItem] );
2065 hb_job_t * job = title->job;
2069 /* We use a number system to set the encode status of the queue item
2070 * 0 == already encoded
2071 * 1 == is being encoded
2072 * 2 == is yet to be encoded
2075 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2076 /* Source and Destination Information */
2078 [queueFileJob setObject:[NSString stringWithUTF8String: title->dvd] forKey:@"SourcePath"];
2079 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2080 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2081 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2082 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2084 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2086 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2088 /* Lets get the preset info if there is any */
2089 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2090 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2092 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2093 /* Chapter Markers*/
2094 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2095 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2097 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2101 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2104 /* We need to get the list of chapter names to put into an array and store
2105 * in our queue, so they can be reapplied in prepareJob when this queue
2106 * item comes up if Chapter Markers is set to on.
2109 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2110 int chaptercount = hb_list_count( fTitle->list_chapter );
2111 for( i = 0; i < chaptercount; i++ )
2113 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2114 if( chapter != NULL )
2116 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2119 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2120 [ChapterNamesArray autorelease];
2122 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2123 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2124 /* Mux mp4 with http optimization */
2125 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2126 /* Add iPod uuid atom */
2127 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2131 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2132 /* x264 Option String */
2133 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2135 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2136 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2137 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2138 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2140 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2142 /* 2 Pass Encoding */
2143 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2144 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2145 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2147 /* Picture Sizing */
2148 /* Use Max Picture settings for whatever the dvd is.*/
2149 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2150 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2151 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2152 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2153 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2154 /* if we are custom anamorphic, store the exact storage, par and display dims */
2155 if (fTitle->job->anamorphic.mode == 3)
2157 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2158 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2160 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2161 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2163 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2164 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2167 NSString * pictureSummary;
2168 pictureSummary = [fPictureSizeField stringValue];
2169 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2170 /* Set crop settings here */
2171 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2172 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2173 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2174 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2175 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2177 /* Picture Filters */
2178 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2179 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2181 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2182 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2183 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2185 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2186 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2188 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2189 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2191 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2193 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2196 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2198 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2199 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2200 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2201 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2202 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2203 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2204 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2206 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2208 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2209 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2210 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2211 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2212 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2213 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2214 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2216 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2218 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2219 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2220 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2221 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2222 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2223 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2224 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2226 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2228 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2229 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2230 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2231 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2232 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2233 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2234 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2238 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] init];
2239 [queueFileJob setObject:[NSArray arrayWithArray: [fSubtitlesDelegate getSubtitleArray: subtitlesArray]] forKey:@"SubtitleList"];
2240 [subtitlesArray autorelease];
2242 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2244 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2246 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2249 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2253 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2256 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2257 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2258 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2260 /* Picture Sizing */
2261 /* Use Max Picture settings for whatever the dvd is.*/
2262 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2263 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2264 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2265 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2266 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2268 /* Set crop settings here */
2269 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2270 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2271 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2272 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2273 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2277 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2279 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2280 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2281 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2282 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2283 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2285 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2287 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2288 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2289 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2290 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2291 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2293 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2295 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2296 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2297 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2298 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2299 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2301 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2303 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2304 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2305 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2306 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2307 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2311 /* we need to auto relase the queueFileJob and return it */
2312 [queueFileJob autorelease];
2313 return queueFileJob;
2317 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2318 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2320 NSUInteger index = [indexSet lastIndex];
2321 NSUInteger aboveInsertIndexCount = 0;
2324 NSUInteger removeIndex;
2326 if (index >= insertIndex)
2328 removeIndex = index + aboveInsertIndexCount;
2329 aboveInsertIndexCount++;
2333 removeIndex = index;
2337 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2338 [QueueFileArray removeObjectAtIndex:removeIndex];
2339 [QueueFileArray insertObject:object atIndex:insertIndex];
2342 index = [indexSet indexLessThanIndex:index];
2344 /* We save all of the Queue data here
2345 * and it also gets sent back to the queue controller*/
2346 [self saveQueueFileItem];
2352 #pragma mark Queue Job Processing
2354 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2356 int i = currentQueueEncodeIndex;
2357 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2359 /* We save all of the Queue data here */
2360 [self saveQueueFileItem];
2361 /* We Reload the New Table data for presets */
2362 //[fPresetsOutlineView reloadData];
2364 /* Since we have now marked a queue item as done
2365 * we can go ahead and increment currentQueueEncodeIndex
2366 * so that if there is anything left in the queue we can
2367 * go ahead and move to the next item if we want to */
2368 currentQueueEncodeIndex++ ;
2369 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2370 int queueItems = [QueueFileArray count];
2371 /* If we still have more items in our queue, lets go to the next one */
2372 if (currentQueueEncodeIndex < queueItems)
2374 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2375 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2379 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2383 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2384 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2386 /* Tell HB to output a new activity log file for this encode */
2387 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2390 /* use a bool to determine whether or not we can decrypt using vlc */
2391 BOOL cancelScanDecrypt = 0;
2392 /* set the bool so that showNewScan knows to apply the appropriate queue
2393 * settings as this is a queue rescan
2395 applyQueueToScan = YES;
2396 NSString *path = scanPath;
2397 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2399 /*On Screen Notification*/
2401 //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2402 //[NSApp requestUserAttention:NSCriticalRequest];
2404 if( [detector isVideoDVD] )
2406 // The chosen path was actually on a DVD, so use the raw block
2407 // device path instead.
2408 path = [detector devicePath];
2409 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2411 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2412 NSString *vlcPath = @"/Applications/VLC.app";
2413 NSFileManager * fileManager = [NSFileManager defaultManager];
2414 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2416 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2417 cancelScanDecrypt = 1;
2418 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2420 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");
2421 [NSApp requestUserAttention:NSCriticalRequest];
2423 if (status == NSAlertDefaultReturn)
2425 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2426 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2428 else if (status == NSAlertAlternateReturn)
2430 /* User chose to cancel the scan */
2431 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2435 /* 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 */
2436 cancelScanDecrypt = 0;
2437 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2443 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2444 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2448 if (cancelScanDecrypt == 0)
2450 /* we actually pass the scan off to libhb here */
2451 /* If there is no title number passed to scan, we use "0"
2452 * which causes the default behavior of a full source scan
2458 if (scanTitleNum > 0)
2460 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2463 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2464 /* We use our advance pref to determine how many previews to scan */
2465 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2466 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2470 /* This method was originally used to load up a new queue item in the gui and
2471 * then start processing it. However we now have modified -prepareJob and use a second
2472 * instance of libhb to do our actual encoding, therefor right now it is not required.
2473 * Nonetheless I want to leave this in here
2474 * because basically its everything we need to be able to actually modify a pending queue
2475 * item in the gui and resave it. At least for now - dynaflash
2478 - (IBAction)applyQueueSettings:(id)sender
2480 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2481 hb_job_t * job = fTitle->job;
2483 /* Set title number and chapters */
2484 /* since the queue only scans a single title, we really don't need to pick a title */
2485 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2487 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2488 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2491 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2492 [self formatPopUpChanged:nil];
2494 /* Chapter Markers*/
2495 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2496 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2497 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2498 /* Mux mp4 with http optimization */
2499 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2502 /* We set the advanced opt string here if applicable*/
2503 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2504 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2506 /* Lets run through the following functions to get variables set there */
2507 [self videoEncoderPopUpChanged:nil];
2508 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2509 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2510 [self calculateBitrate:nil];
2513 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2515 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2516 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2517 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2519 [self videoMatrixChanged:nil];
2521 /* Video framerate */
2522 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2523 detected framerate in the fVidRatePopUp so we use index 0*/
2524 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2526 [fVidRatePopUp selectItemAtIndex: 0];
2530 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2533 /* 2 Pass Encoding */
2534 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2535 [self twoPassCheckboxChanged:nil];
2536 /* Turbo 1st pass for 2 Pass Encoding */
2537 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2540 if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2542 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2544 [fAudLang1PopUp selectItemAtIndex: 1];
2546 [self audioTrackPopUpChanged: fAudLang1PopUp];
2547 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2548 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2549 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2550 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2552 if ([fAudTrack1MixPopUp selectedItem] == nil)
2554 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2556 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2557 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2558 if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2560 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2562 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2563 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2565 if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2567 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2569 [fAudLang2PopUp selectItemAtIndex: 1];
2571 [self audioTrackPopUpChanged: fAudLang2PopUp];
2572 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2573 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2574 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2575 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2577 if ([fAudTrack2MixPopUp selectedItem] == nil)
2579 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2581 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2582 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2583 if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2585 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2587 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2588 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2590 if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2592 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2594 [fAudLang3PopUp selectItemAtIndex: 1];
2596 [self audioTrackPopUpChanged: fAudLang3PopUp];
2597 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2598 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2599 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2600 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2602 if ([fAudTrack3MixPopUp selectedItem] == nil)
2604 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2606 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2607 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2608 if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2610 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2612 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2613 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2615 if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2617 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2619 [fAudLang4PopUp selectItemAtIndex: 1];
2621 [self audioTrackPopUpChanged: fAudLang4PopUp];
2622 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2623 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2624 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2625 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2627 if ([fAudTrack4MixPopUp selectedItem] == nil)
2629 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2631 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2632 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2633 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2635 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2637 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2638 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2643 [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2644 /* Forced Subtitles */
2645 [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2647 /* Picture Settings */
2648 /* we check to make sure the presets width/height does not exceed the sources width/height */
2649 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2651 /* if so, then we use the sources height and width to avoid scaling up */
2652 job->width = fTitle->width;
2653 job->height = fTitle->height;
2655 else // source width/height is >= the preset height/width
2657 /* we can go ahead and use the presets values for height and width */
2658 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2659 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2661 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2662 if (job->keep_ratio == 1)
2664 hb_fix_aspect( job, HB_KEEP_WIDTH );
2665 if( job->height > fTitle->height )
2667 job->height = fTitle->height;
2668 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2671 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2674 /* If Cropping is set to custom, then recall all four crop values from
2675 when the preset was created and apply them */
2676 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2678 [fPictureController setAutoCrop:NO];
2680 /* Here we use the custom crop values saved at the time the preset was saved */
2681 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2682 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2683 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2684 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2687 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2689 [fPictureController setAutoCrop:YES];
2690 /* Here we use the auto crop values determined right after scan */
2691 job->crop[0] = AutoCropTop;
2692 job->crop[1] = AutoCropBottom;
2693 job->crop[2] = AutoCropLeft;
2694 job->crop[3] = AutoCropRight;
2700 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2703 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2705 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2707 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2709 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2711 [fPictureController setGrayscale:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2713 [self calculatePictureSizing:nil];
2716 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2717 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2718 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2719 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2721 /* Deselect the currently selected Preset if there is one*/
2722 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2723 //[self selectPreset:nil];
2725 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2726 /* Change UI to show "Custom" settings are being used */
2727 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2729 curUserPresetChosenNum = nil;
2733 /* Deselect the currently selected Preset if there is one*/
2734 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2735 /* Change UI to show "Custom" settings are being used */
2736 [fPresetSelectedDisplay setStringValue: @"Custom"];
2738 //curUserPresetChosenNum = nil;
2741 /* We need to set this bool back to NO, in case the user wants to do a scan */
2742 //applyQueueToScan = NO;
2744 /* so now we go ahead and process the new settings */
2745 [self processNewQueueEncode];
2750 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2751 - (void) processNewQueueEncode
2753 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2754 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2755 hb_job_t * job = title->job;
2757 if( !hb_list_count( list ) )
2759 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2762 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2763 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2764 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2765 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2766 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2770 * If scanning we need to do some extra setup of the job.
2772 if( job->indepth_scan == 1 )
2777 * When subtitle scan is enabled do a fast pre-scan job
2778 * which will determine which subtitles to enable, if any.
2781 x264opts_tmp = job->x264opts;
2783 job->x264opts = NULL;
2785 job->indepth_scan = 1;
2789 * Add the pre-scan job
2791 hb_add( fQueueEncodeLibhb, job );
2792 job->x264opts = x264opts_tmp;
2796 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2798 job->indepth_scan = 0;
2804 hb_add( fQueueEncodeLibhb, job );
2808 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2809 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2811 hb_add( fQueueEncodeLibhb, job );
2816 job->indepth_scan = 0;
2819 hb_add( fQueueEncodeLibhb, job );
2822 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2823 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2824 /* Lets mark our new encode as 1 or "Encoding" */
2825 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2826 [self saveQueueFileItem];
2828 /* we need to clean up the subtitle tracks after the job(s) have been set */
2829 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2831 for(ii = 0; ii < num_subtitle_tracks; ii++)
2833 hb_subtitle_t * subtitle;
2834 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2837 hb_list_rem(job->list_subtitle, subtitle);
2842 /* We should be all setup so let 'er rip */
2847 #pragma mark Live Preview
2848 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2849 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2852 - (void) prepareJobForPreview
2854 hb_list_t * list = hb_get_titles( fHandle );
2855 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2856 [fSrcTitlePopUp indexOfSelectedItem] );
2857 hb_job_t * job = title->job;
2858 hb_audio_config_t * audio;
2859 /* set job->angle for libdvdnav */
2860 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
2861 /* Chapter selection */
2862 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
2863 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
2865 /* Format (Muxer) and Video Encoder */
2866 job->mux = [[fDstFormatPopUp selectedItem] tag];
2867 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
2869 job->chapter_markers = 0;
2871 if( job->vcodec & HB_VCODEC_X264 )
2873 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2874 Currently only used with Constant Quality setting*/
2875 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
2880 /* Below Sends x264 options to the core library if x264 is selected*/
2881 /* Lets use this as per Nyx, Thanks Nyx!*/
2882 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2883 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
2884 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
2889 /* Video settings */
2890 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
2891 * and detelecine is on, so we handle that in the logic below
2894 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
2896 /* a specific framerate has been chosen */
2897 job->vrate = 27000000;
2898 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
2899 /* We are not same as source so we set job->cfr to 1
2900 * to enable constant frame rate since user has specified
2901 * a specific framerate*/
2906 /* We are same as source (variable) */
2907 job->vrate = title->rate;
2908 job->vrate_base = title->rate_base;
2909 /* We are same as source so we set job->cfr to 0
2910 * to enable true same as source framerate */
2912 /* If we are same as source and we have detelecine on, we need to turn on
2915 if ([fPictureController detelecine] == 1)
2921 switch( [fVidQualityMatrix selectedRow] )
2925 Bitrate should already have been calculated and displayed
2926 in fVidBitrateField, so let's just use it */
2928 job->vquality = -1.0;
2929 job->vbitrate = [fVidBitrateField intValue];
2932 job->vquality = [fVidQualityRFField floatValue];
2937 /* Subtitle settings */
2938 NSMutableArray *subtitlesArray = nil;
2939 subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray: subtitlesArray]];
2947 bool one_burned = FALSE;
2950 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
2952 while (tempObject = [enumerator nextObject])
2955 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
2956 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
2957 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
2958 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
2960 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
2961 * we want to ignore it for display as well as encoding.
2965 /* if i is 0, then we are in the first item of the subtitles which we need to
2966 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
2967 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
2970 /* if we are on the first track and using "Foreign Audio Search" */
2971 if (i == 0 && subtitle == 1)
2973 /* NOTE: Currently foreign language search is borked for preview.
2974 * Commented out but left in for initial commit. */
2977 [self writeToActivityLog: "Foreign Language Search: %d", 1];
2979 job->indepth_scan = 1;
2980 if (burned == 1 || job->mux != HB_MUX_MP4)
2982 if (burned != 1 && job->mux == HB_MUX_MKV)
2984 job->select_subtitle_config.dest = PASSTHRUSUB;
2988 job->select_subtitle_config.dest = RENDERSUB;
2991 job->select_subtitle_config.force = force;
2992 job->select_subtitle_config.default_track = def;
3001 /* for the actual source tracks, we must subtract the non source entries so
3002 * that the menu index matches the source subtitle_list index for convenience */
3005 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3006 * Foreign Language Search is 1) so subtract 2 */
3007 subtitle = subtitle - 2;
3011 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3014 subtitle = subtitle - 1;
3017 /* We are setting a source subtitle so access the source subtitle info */
3018 hb_subtitle_t * subt;
3020 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3022 /* if we are getting the subtitles from an external srt file */
3023 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3025 hb_subtitle_config_t sub_config;
3027 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3029 /* we need to srncpy file path and char code */
3030 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3031 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3033 sub_config.force = 0;
3034 sub_config.dest = PASSTHRUSUB;
3035 sub_config.default_track = def;
3037 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3042 [self writeToActivityLog: "Setting Subtitle: %s", subt];
3044 hb_subtitle_config_t sub_config = subt->config;
3046 if (!burned && job->mux == HB_MUX_MKV &&
3047 subt->format == PICTURESUB)
3049 sub_config.dest = PASSTHRUSUB;
3051 else if (!burned && job->mux == HB_MUX_MP4 &&
3052 subt->format == PICTURESUB)
3054 // Skip any non-burned vobsubs when output is mp4
3057 else if ( burned && subt->format == PICTURESUB )
3059 // Only allow one subtitle to be burned into the video
3064 sub_config.force = force;
3065 sub_config.default_track = def;
3066 hb_subtitle_add( job, &sub_config, subtitle );
3076 [subtitlesArray autorelease];
3079 /* Audio tracks and mixdowns */
3080 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3081 int audiotrack_count = hb_list_count(job->list_audio);
3082 for( int i = 0; i < audiotrack_count;i++)
3084 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3085 hb_list_rem(job->list_audio, temp_audio);
3087 /* Now lets add our new tracks to the audio list here */
3088 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3090 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3091 hb_audio_config_init(audio);
3092 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3093 /* We go ahead and assign values to our audio->out.<properties> */
3094 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3095 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3096 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3097 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3098 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3099 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3101 hb_audio_add( job, audio );
3104 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3106 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3107 hb_audio_config_init(audio);
3108 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3109 /* We go ahead and assign values to our audio->out.<properties> */
3110 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3111 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3112 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3113 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3114 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3115 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3117 hb_audio_add( job, audio );
3122 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3124 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3125 hb_audio_config_init(audio);
3126 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3127 /* We go ahead and assign values to our audio->out.<properties> */
3128 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3129 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3130 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3131 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3132 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3133 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3135 hb_audio_add( job, audio );
3140 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3142 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3143 hb_audio_config_init(audio);
3144 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3145 /* We go ahead and assign values to our audio->out.<properties> */
3146 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3147 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3148 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3149 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3150 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3151 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3153 hb_audio_add( job, audio );
3162 /* Though Grayscale is not really a filter, per se
3163 * we put it here since its in the filters panel
3166 if ([fPictureController grayscale])
3175 /* Initialize the filters list */
3176 job->filters = hb_list_init();
3178 /* Now lets call the filters if applicable.
3179 * The order of the filters is critical
3183 if ([fPictureController detelecine] == 1)
3185 /* use a custom detelecine string */
3186 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3187 hb_list_add( job->filters, &hb_filter_detelecine );
3189 if ([fPictureController detelecine] == 2)
3192 hb_list_add( job->filters, &hb_filter_detelecine );
3197 if ([fPictureController useDecomb] == 1)
3200 /* we add the custom string if present */
3201 if ([fPictureController decomb] == 1)
3203 /* use a custom decomb string */
3204 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3205 hb_list_add( job->filters, &hb_filter_decomb );
3207 if ([fPictureController decomb] == 2)
3209 /* Run old deinterlacer fd by default */
3210 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3211 hb_list_add( job->filters, &hb_filter_decomb );
3218 if ([fPictureController deinterlace] == 1)
3220 /* we add the custom string if present */
3221 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3222 hb_list_add( job->filters, &hb_filter_deinterlace );
3224 else if ([fPictureController deinterlace] == 2)
3226 /* Run old deinterlacer fd by default */
3227 hb_filter_deinterlace.settings = "-1";
3228 hb_list_add( job->filters, &hb_filter_deinterlace );
3230 else if ([fPictureController deinterlace] == 3)
3232 /* Yadif mode 0 (without spatial deinterlacing.) */
3233 hb_filter_deinterlace.settings = "2";
3234 hb_list_add( job->filters, &hb_filter_deinterlace );
3236 else if ([fPictureController deinterlace] == 4)
3238 /* Yadif (with spatial deinterlacing) */
3239 hb_filter_deinterlace.settings = "0";
3240 hb_list_add( job->filters, &hb_filter_deinterlace );
3246 if ([fPictureController denoise] == 1) // custom in popup
3248 /* we add the custom string if present */
3249 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3250 hb_list_add( job->filters, &hb_filter_denoise );
3252 else if ([fPictureController denoise] == 2) // Weak in popup
3254 hb_filter_denoise.settings = "2:1:2:3";
3255 hb_list_add( job->filters, &hb_filter_denoise );
3257 else if ([fPictureController denoise] == 3) // Medium in popup
3259 hb_filter_denoise.settings = "3:2:2:3";
3260 hb_list_add( job->filters, &hb_filter_denoise );
3262 else if ([fPictureController denoise] == 4) // Strong in popup
3264 hb_filter_denoise.settings = "7:7:5:5";
3265 hb_list_add( job->filters, &hb_filter_denoise );
3269 /* Deblock (uses pp7 default) */
3270 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3271 * the macgui's purposes a value of 0 actually means to not even use the filter
3272 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3274 if ([fPictureController deblock] != 0)
3276 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3277 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3278 hb_list_add( job->filters, &hb_filter_deblock );
3285 #pragma mark Job Handling
3291 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3292 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3293 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3294 hb_job_t * job = title->job;
3295 hb_audio_config_t * audio;
3296 /* Title Angle for dvdnav */
3297 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3298 /* Chapter selection */
3299 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3300 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3302 /* Format (Muxer) and Video Encoder */
3303 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3304 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3307 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3308 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3310 job->largeFileSize = 1;
3314 job->largeFileSize = 0;
3316 /* We set http optimized mp4 here */
3317 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3319 job->mp4_optimize = 1;
3323 job->mp4_optimize = 0;
3327 /* We set the chapter marker extraction here based on the format being
3328 mpeg4 or mkv and the checkbox being checked */
3329 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3331 job->chapter_markers = 1;
3333 /* now lets get our saved chapter names out the array in the queue file
3334 * and insert them back into the title chapter list. We have it here,
3335 * because unless we are inserting chapter markers there is no need to
3336 * spend the overhead of iterating through the chapter names array imo
3337 * Also, note that if for some reason we don't apply chapter names, the
3338 * chapters just come out 001, 002, etc. etc.
3341 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3343 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3345 while (tempObject = [enumerator nextObject])
3347 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3348 if( chapter != NULL )
3350 strncpy( chapter->title, [tempObject UTF8String], 1023);
3351 chapter->title[1023] = '\0';
3358 job->chapter_markers = 0;
3361 if( job->vcodec & HB_VCODEC_X264 )
3363 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3373 /* Below Sends x264 options to the core library if x264 is selected*/
3374 /* Lets use this as per Nyx, Thanks Nyx!*/
3375 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3376 /* Turbo first pass if two pass and Turbo First pass is selected */
3377 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3379 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3380 NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3381 /* append the "Turbo" string variable to the existing opts string.
3382 Note: the "Turbo" string must be appended, not prepended to work properly*/
3383 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3384 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3388 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3394 /* Picture Size Settings */
3395 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3396 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3398 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3399 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3400 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3402 /* insert our custom values here for capuj */
3403 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3404 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3406 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3407 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3409 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3410 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3413 /* Here we use the crop values saved at the time the preset was saved */
3414 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3415 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3416 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3417 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3419 /* Video settings */
3422 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3423 * and detelecine is on, so we handle that in the logic below
3426 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3428 /* a specific framerate has been chosen */
3429 job->vrate = 27000000;
3430 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3431 /* We are not same as source so we set job->cfr to 1
3432 * to enable constant frame rate since user has specified
3433 * a specific framerate*/
3438 /* We are same as source (variable) */
3439 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3440 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3441 /* We are same as source so we set job->cfr to 0
3442 * to enable true same as source framerate */
3444 /* If we are same as source and we have detelecine on, we need to turn on
3447 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3453 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3456 Bitrate should already have been calculated and displayed
3457 in fVidBitrateField, so let's just use it same as abr*/
3458 job->vquality = -1.0;
3459 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3461 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3463 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3468 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3473 #pragma mark Process Subtitles to libhb
3475 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3476 * which means that we need to account for the offset of non source language settings in from
3477 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3478 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3479 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3480 * to the source tracks position in title->list_subtitle.
3487 bool one_burned = FALSE;
3490 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3492 while (tempObject = [enumerator nextObject])
3495 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3496 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3497 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3498 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3500 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3501 * we want to ignore it for display as well as encoding.
3505 /* if i is 0, then we are in the first item of the subtitles which we need to
3506 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3507 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3510 /* if we are on the first track and using "Foreign Audio Search" */
3511 if (i == 0 && subtitle == 1)
3513 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3515 job->indepth_scan = 1;
3516 if (burned == 1 || job->mux != HB_MUX_MP4)
3518 if (burned != 1 && job->mux == HB_MUX_MKV)
3520 job->select_subtitle_config.dest = PASSTHRUSUB;
3524 job->select_subtitle_config.dest = RENDERSUB;
3527 job->select_subtitle_config.force = force;
3528 job->select_subtitle_config.default_track = def;
3536 /* for the actual source tracks, we must subtract the non source entries so
3537 * that the menu index matches the source subtitle_list index for convenience */
3540 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3541 * Foreign Language Search is 1) so subtract 2 */
3542 subtitle = subtitle - 2;
3546 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3549 subtitle = subtitle - 1;
3552 /* We are setting a source subtitle so access the source subtitle info */
3553 hb_subtitle_t * subt;
3555 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3557 /* if we are getting the subtitles from an external srt file */
3558 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3560 hb_subtitle_config_t sub_config;
3562 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3564 /* we need to srncpy file name and codeset */
3565 //sub_config.src_filename = [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String];
3566 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3567 //sub_config.src_codeset = [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String];
3568 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3570 sub_config.force = 0;
3571 sub_config.dest = PASSTHRUSUB;
3572 sub_config.default_track = def;
3574 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3580 [self writeToActivityLog: "Setting Subtitle: %s", subt];
3582 hb_subtitle_config_t sub_config = subt->config;
3584 if (!burned && job->mux == HB_MUX_MKV &&
3585 subt->format == PICTURESUB)
3587 sub_config.dest = PASSTHRUSUB;
3589 else if (!burned && job->mux == HB_MUX_MP4 &&
3590 subt->format == PICTURESUB)
3592 // Skip any non-burned vobsubs when output is mp4
3595 else if ( burned && subt->format == PICTURESUB )
3597 // Only allow one subtitle to be burned into the video
3602 sub_config.force = force;
3603 sub_config.default_track = def;
3604 hb_subtitle_add( job, &sub_config, subtitle );
3615 /* Audio tracks and mixdowns */
3616 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3617 int audiotrack_count = hb_list_count(job->list_audio);
3618 for( int i = 0; i < audiotrack_count;i++)
3620 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3621 hb_list_rem(job->list_audio, temp_audio);
3623 /* Now lets add our new tracks to the audio list here */
3624 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3626 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3627 hb_audio_config_init(audio);
3628 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3629 /* We go ahead and assign values to our audio->out.<properties> */
3630 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3631 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3632 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3633 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3634 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3635 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3637 hb_audio_add( job, audio );
3640 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3643 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3644 hb_audio_config_init(audio);
3645 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3646 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3647 /* We go ahead and assign values to our audio->out.<properties> */
3648 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3649 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3650 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3651 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3652 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3653 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3655 hb_audio_add( job, audio );
3659 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3661 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3662 hb_audio_config_init(audio);
3663 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3664 /* We go ahead and assign values to our audio->out.<properties> */
3665 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3666 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3667 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3668 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3669 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3670 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3672 hb_audio_add( job, audio );
3676 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3678 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3679 hb_audio_config_init(audio);
3680 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3681 /* We go ahead and assign values to our audio->out.<properties> */
3682 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3683 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3684 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3685 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3686 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3687 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3689 hb_audio_add( job, audio );
3695 job->filters = hb_list_init();
3697 /* Now lets call the filters if applicable.
3698 * The order of the filters is critical
3701 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3703 /* use a custom detelecine string */
3704 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3705 hb_list_add( job->filters, &hb_filter_detelecine );
3707 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3709 /* Use libhb's default values */
3710 hb_list_add( job->filters, &hb_filter_detelecine );
3713 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3716 /* we add the custom string if present */
3717 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3719 /* use a custom decomb string */
3720 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3721 hb_list_add( job->filters, &hb_filter_decomb );
3723 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3725 /* Use libhb default */
3726 hb_list_add( job->filters, &hb_filter_decomb );
3734 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3736 /* we add the custom string if present */
3737 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3738 hb_list_add( job->filters, &hb_filter_deinterlace );
3740 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3742 /* Run old deinterlacer fd by default */
3743 hb_filter_deinterlace.settings = "-1";
3744 hb_list_add( job->filters, &hb_filter_deinterlace );
3746 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3748 /* Yadif mode 0 (without spatial deinterlacing.) */
3749 hb_filter_deinterlace.settings = "2";
3750 hb_list_add( job->filters, &hb_filter_deinterlace );
3752 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3754 /* Yadif (with spatial deinterlacing) */
3755 hb_filter_deinterlace.settings = "0";
3756 hb_list_add( job->filters, &hb_filter_deinterlace );
3762 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
3764 /* we add the custom string if present */
3765 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3766 hb_list_add( job->filters, &hb_filter_denoise );
3768 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
3770 hb_filter_denoise.settings = "2:1:2:3";
3771 hb_list_add( job->filters, &hb_filter_denoise );
3773 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
3775 hb_filter_denoise.settings = "3:2:2:3";
3776 hb_list_add( job->filters, &hb_filter_denoise );
3778 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
3780 hb_filter_denoise.settings = "7:7:5:5";
3781 hb_list_add( job->filters, &hb_filter_denoise );
3785 /* Deblock (uses pp7 default) */
3786 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3787 * the macgui's purposes a value of 0 actually means to not even use the filter
3788 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3790 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3792 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3793 hb_list_add( job->filters, &hb_filter_deblock );
3795 [self writeToActivityLog: "prepareJob exiting"];
3800 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3802 - (IBAction) addToQueue: (id) sender
3804 /* We get the destination directory from the destination field here */
3805 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3806 /* We check for a valid destination here */
3807 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3809 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3816 BOOL fileExistsInQueue;
3817 fileExistsInQueue = NO;
3819 /* We check for and existing file here */
3820 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3825 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3827 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3829 while (tempObject = [enumerator nextObject])
3831 NSDictionary *thisQueueDict = tempObject;
3832 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3834 fileExistsInQueue = YES;
3840 if(fileExists == YES)
3842 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
3843 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3844 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3845 NULL, NULL, [NSString stringWithFormat:
3846 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3847 [fDstFile2Field stringValue]] );
3849 else if (fileExistsInQueue == YES)
3851 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
3852 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3853 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3854 NULL, NULL, [NSString stringWithFormat:
3855 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3856 [fDstFile2Field stringValue]] );
3860 [self doAddToQueue];
3864 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
3865 the user if they want to overwrite an exiting movie file.
3867 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
3868 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3870 if( returnCode == NSAlertAlternateReturn )
3871 [self doAddToQueue];
3874 - (void) doAddToQueue
3876 [self addQueueFileItem ];
3881 /* Rip: puts up an alert before ultimately calling doRip
3883 - (IBAction) Rip: (id) sender
3885 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
3886 /* Rip or Cancel ? */
3888 hb_get_state2( fQueueEncodeLibhb, &s );
3890 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
3892 [self Cancel: sender];
3896 /* We check to see if we need to warn the user that the computer will go to sleep
3897 or shut down when encoding is finished */
3898 [self remindUserOfSleepOrShutdown];
3900 // If there are pending jobs in the queue, then this is a rip the queue
3901 if (fPendingCount > 0)
3903 /* here lets start the queue with the first pending item */
3904 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3909 // Before adding jobs to the queue, check for a valid destination.
3911 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3912 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3914 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3918 /* We check for duplicate name here */
3919 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
3921 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
3922 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3923 @selector( overWriteAlertDone:returnCode:contextInfo: ),
3924 NULL, NULL, [NSString stringWithFormat:
3925 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3926 [fDstFile2Field stringValue]] );
3928 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
3932 /* if there are no pending jobs in the queue, then add this one to the queue and rip
3933 otherwise, just rip the queue */
3934 if(fPendingCount == 0)
3936 [self doAddToQueue];
3939 /* go right to processing the new queue encode */
3940 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3945 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
3946 want to overwrite an exiting movie file.
3948 - (void) overWriteAlertDone: (NSWindow *) sheet
3949 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3951 if( returnCode == NSAlertAlternateReturn )
3953 /* if there are no jobs in the queue, then add this one to the queue and rip
3954 otherwise, just rip the queue */
3955 if( fPendingCount == 0 )
3957 [self doAddToQueue];
3960 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3961 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
3962 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3967 - (void) remindUserOfSleepOrShutdown
3969 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
3971 /*Warn that computer will sleep after encoding*/
3974 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);
3975 [NSApp requestUserAttention:NSCriticalRequest];
3976 if ( reminduser == NSAlertAlternateReturn )
3978 [self showPreferencesWindow:nil];
3981 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
3983 /*Warn that computer will shut down after encoding*/
3986 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);
3987 [NSApp requestUserAttention:NSCriticalRequest];
3988 if ( reminduser == NSAlertAlternateReturn )
3990 [self showPreferencesWindow:nil];
3999 /* Let libhb do the job */
4000 hb_start( fQueueEncodeLibhb );
4001 /*set the fEncodeState State */
4006 //------------------------------------------------------------------------------------
4007 // Displays an alert asking user if the want to cancel encoding of current job.
4008 // Cancel: returns immediately after posting the alert. Later, when the user
4009 // acknowledges the alert, doCancelCurrentJob is called.
4010 //------------------------------------------------------------------------------------
4011 - (IBAction)Cancel: (id)sender
4013 if (!fQueueController) return;
4015 hb_pause( fQueueEncodeLibhb );
4016 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4018 // Which window to attach the sheet to?
4019 NSWindow * docWindow;
4020 if ([sender respondsToSelector: @selector(window)])
4021 docWindow = [sender window];
4023 docWindow = fWindow;
4025 NSBeginCriticalAlertSheet(
4027 NSLocalizedString(@"Continue Encoding", nil),
4028 NSLocalizedString(@"Cancel Current and Stop", nil),
4029 NSLocalizedString(@"Cancel Current and Continue", nil),
4031 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4032 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4034 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4037 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4039 hb_resume( fQueueEncodeLibhb );
4040 if (returnCode == NSAlertOtherReturn)
4042 [self doCancelCurrentJob]; // <- this also stops libhb
4044 if (returnCode == NSAlertAlternateReturn)
4046 [self doCancelCurrentJobAndStop];
4050 //------------------------------------------------------------------------------------
4051 // Cancels and deletes the current job and stops libhb from processing the remaining
4053 //------------------------------------------------------------------------------------
4054 - (void) doCancelCurrentJob
4056 // Stop the current job. hb_stop will only cancel the current pass and then set
4057 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4058 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4059 // remaining passes of the job and then start the queue back up if there are any
4063 hb_stop( fQueueEncodeLibhb );
4065 // Delete all remaining jobs since libhb doesn't do this on its own.
4067 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4068 hb_rem( fQueueEncodeLibhb, job );
4070 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4072 // now that we've stopped the currently encoding job, lets mark it as cancelled
4073 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4074 // and as always, save it in the queue .plist...
4075 /* We save all of the Queue data here */
4076 [self saveQueueFileItem];
4077 // so now lets move to
4078 currentQueueEncodeIndex++ ;
4079 // ... and see if there are more items left in our queue
4080 int queueItems = [QueueFileArray count];
4081 /* If we still have more items in our queue, lets go to the next one */
4082 if (currentQueueEncodeIndex < queueItems)
4084 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4085 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4087 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4091 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4096 - (void) doCancelCurrentJobAndStop
4098 hb_stop( fQueueEncodeLibhb );
4100 // Delete all remaining jobs since libhb doesn't do this on its own.
4102 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4103 hb_rem( fQueueEncodeLibhb, job );
4106 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4108 // now that we've stopped the currently encoding job, lets mark it as cancelled
4109 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4110 // and as always, save it in the queue .plist...
4111 /* We save all of the Queue data here */
4112 [self saveQueueFileItem];
4113 // so now lets move to
4114 currentQueueEncodeIndex++ ;
4115 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4117 - (IBAction) Pause: (id) sender
4120 hb_get_state2( fQueueEncodeLibhb, &s );
4122 if( s.state == HB_STATE_PAUSED )
4124 hb_resume( fQueueEncodeLibhb );
4128 hb_pause( fQueueEncodeLibhb );
4133 #pragma mark GUI Controls Changed Methods
4135 - (IBAction) titlePopUpChanged: (id) sender
4137 hb_list_t * list = hb_get_titles( fHandle );
4138 hb_title_t * title = (hb_title_t*)
4139 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4141 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4142 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4144 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4145 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4146 [browsedSourceDisplayName stringByDeletingPathExtension],
4148 [[fDstFile2Field stringValue] pathExtension]]];
4151 /* Update chapter popups */
4152 [fSrcChapterStartPopUp removeAllItems];
4153 [fSrcChapterEndPopUp removeAllItems];
4154 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4156 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4157 stringWithFormat: @"%d", i + 1]];
4158 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4159 stringWithFormat: @"%d", i + 1]];
4162 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4163 [fSrcChapterEndPopUp selectItemAtIndex:
4164 hb_list_count( title->list_chapter ) - 1];
4165 [self chapterPopUpChanged:nil];
4167 /* if using dvd nav, show the angle widget */
4168 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4170 [fSrcAngleLabel setHidden:NO];
4171 [fSrcAnglePopUp setHidden:NO];
4173 [fSrcAnglePopUp removeAllItems];
4174 for( int i = 0; i < title->angle_count; i++ )
4176 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4178 [fSrcAnglePopUp selectItemAtIndex: 0];
4182 [fSrcAngleLabel setHidden:YES];
4183 [fSrcAnglePopUp setHidden:YES];
4186 /* Start Get and set the initial pic size for display */
4187 hb_job_t * job = title->job;
4190 /* Set Auto Crop to on upon selecting a new title */
4191 [fPictureController setAutoCrop:YES];
4193 /* We get the originial output picture width and height and put them
4194 in variables for use with some presets later on */
4195 PicOrigOutputWidth = job->width;
4196 PicOrigOutputHeight = job->height;
4197 AutoCropTop = job->crop[0];
4198 AutoCropBottom = job->crop[1];
4199 AutoCropLeft = job->crop[2];
4200 AutoCropRight = job->crop[3];
4202 /* Reset the new title in fPictureController && fPreviewController*/
4203 [fPictureController SetTitle:title];
4206 /* Update Subtitle Table */
4207 [fSubtitlesDelegate resetWithTitle:title];
4208 [fSubtitlesTable reloadData];
4211 /* Update chapter table */
4212 [fChapterTitlesDelegate resetWithTitle:title];
4213 [fChapterTable reloadData];
4215 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4216 int audiotrack_count = hb_list_count(job->list_audio);
4217 for( int i = 0; i < audiotrack_count;i++)
4219 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4220 hb_list_rem(job->list_audio, temp_audio);
4223 /* Update audio popups */
4224 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4225 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4226 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4227 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4228 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4229 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4230 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4231 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4232 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4233 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4235 /* changing the title may have changed the audio channels on offer, */
4236 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4237 [self audioTrackPopUpChanged: fAudLang1PopUp];
4238 [self audioTrackPopUpChanged: fAudLang2PopUp];
4239 [self audioTrackPopUpChanged: fAudLang3PopUp];
4240 [self audioTrackPopUpChanged: fAudLang4PopUp];
4242 [fVidRatePopUp selectItemAtIndex: 0];
4244 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4245 [self calculatePictureSizing:nil];
4247 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4248 [self selectPreset:nil];
4251 - (IBAction) chapterPopUpChanged: (id) sender
4254 /* If start chapter popup is greater than end chapter popup,
4255 we set the end chapter popup to the same as start chapter popup */
4256 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4258 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4262 hb_list_t * list = hb_get_titles( fHandle );
4263 hb_title_t * title = (hb_title_t *)
4264 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4266 hb_chapter_t * chapter;
4267 int64_t duration = 0;
4268 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4269 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4271 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4272 duration += chapter->duration;
4275 duration /= 90000; /* pts -> seconds */
4276 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4277 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4280 [self calculateBitrate: sender];
4282 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4284 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4285 [fCreateChapterMarkers setEnabled: NO];
4286 [fCreateChapterMarkers setState: NSOffState];
4290 [fCreateChapterMarkers setEnabled: YES];
4294 - (IBAction) formatPopUpChanged: (id) sender
4296 NSString * string = [fDstFile2Field stringValue];
4297 int format = [fDstFormatPopUp indexOfSelectedItem];
4299 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4300 [fDstMp4LargeFileCheck setHidden: YES];
4301 [fDstMp4HttpOptFileCheck setHidden: YES];
4302 [fDstMp4iPodFileCheck setHidden: YES];
4304 /* Update the Video Codec PopUp */
4305 /* lets get the tag of the currently selected item first so we might reset it later */
4306 int selectedVidEncoderTag;
4307 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4309 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4310 [fVidEncoderPopUp removeAllItems];
4311 NSMenuItem *menuItem;
4312 /* These video encoders are available to all of our current muxers, so lets list them once here */
4313 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4314 [menuItem setTag: HB_VCODEC_FFMPEG];
4319 /*Get Default MP4 File Extension*/
4320 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4328 /* Add additional video encoders here */
4329 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4330 [menuItem setTag: HB_VCODEC_X264];
4331 /* We show the mp4 option checkboxes here since we are mp4 */
4332 [fCreateChapterMarkers setEnabled: YES];
4333 [fDstMp4LargeFileCheck setHidden: NO];
4334 [fDstMp4HttpOptFileCheck setHidden: NO];
4335 [fDstMp4iPodFileCheck setHidden: NO];
4340 /* Add additional video encoders here */
4341 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4342 [menuItem setTag: HB_VCODEC_X264];
4343 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4344 [menuItem setTag: HB_VCODEC_THEORA];
4345 /* We enable the create chapters checkbox here */
4346 [fCreateChapterMarkers setEnabled: YES];
4351 /* tell fSubtitlesDelegate we have a new video container */
4353 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4354 [fSubtitlesTable reloadData];
4355 /* if we have a previously selected vid encoder tag, then try to select it */
4356 if (selectedVidEncoderTag)
4358 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4362 [fVidEncoderPopUp selectItemAtIndex: 0];
4365 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4366 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4367 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4368 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4371 [self autoSetM4vExtension: sender];
4373 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4375 if( SuccessfulScan )
4377 /* Add/replace to the correct extension */
4378 [self audioTrackPopUpChanged: fAudLang1PopUp];
4379 [self audioTrackPopUpChanged: fAudLang2PopUp];
4380 [self audioTrackPopUpChanged: fAudLang3PopUp];
4381 [self audioTrackPopUpChanged: fAudLang4PopUp];
4383 if( [fVidEncoderPopUp selectedItem] == nil )
4386 [fVidEncoderPopUp selectItemAtIndex:0];
4387 [self videoEncoderPopUpChanged:nil];
4389 /* changing the format may mean that we can / can't offer mono or 6ch, */
4390 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4392 /* We call the method to properly enable/disable turbo 2 pass */
4393 [self twoPassCheckboxChanged: sender];
4394 /* We call method method to change UI to reflect whether a preset is used or not*/
4397 [self customSettingUsed: sender];
4400 - (IBAction) autoSetM4vExtension: (id) sender
4402 if ( [fDstFormatPopUp indexOfSelectedItem] )
4405 NSString * extension = @"mp4";
4407 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4408 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4409 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4410 [fCreateChapterMarkers state] == NSOnState ||
4411 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4416 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4419 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4420 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4423 /* Method to determine if we should change the UI
4424 To reflect whether or not a Preset is being used or if
4425 the user is using "Custom" settings by determining the sender*/
4426 - (IBAction) customSettingUsed: (id) sender
4428 if ([sender stringValue])
4430 /* Deselect the currently selected Preset if there is one*/
4431 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4432 /* Change UI to show "Custom" settings are being used */
4433 [fPresetSelectedDisplay setStringValue: @"Custom"];
4435 curUserPresetChosenNum = nil;
4437 [self calculateBitrate:nil];
4442 #pragma mark - Video
4444 - (IBAction) videoEncoderPopUpChanged: (id) sender
4446 hb_job_t * job = fTitle->job;
4447 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4449 [fAdvancedOptions setHidden:YES];
4450 /* If we are using x264 then show the x264 advanced panel*/
4451 if (videoEncoder == HB_VCODEC_X264)
4453 [fAdvancedOptions setHidden:NO];
4454 [self autoSetM4vExtension: sender];
4457 /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
4458 is being used as it borks up loose anamorphic .
4459 For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
4460 to use the index itself but this is easier */
4461 if (videoEncoder == HB_VCODEC_FFMPEG)
4463 if (job->anamorphic.mode == 2)
4465 job->anamorphic.mode = 0;
4467 [fPictureController setAllowLooseAnamorphic:NO];
4468 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4469 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4470 anything other than MP4.
4472 [fDstMp4iPodFileCheck setEnabled: NO];
4473 [fDstMp4iPodFileCheck setState: NSOffState];
4477 [fPictureController setAllowLooseAnamorphic:YES];
4478 [fDstMp4iPodFileCheck setEnabled: YES];
4480 [self setupQualitySlider];
4481 [self calculatePictureSizing: sender];
4482 [self twoPassCheckboxChanged: sender];
4486 - (IBAction) twoPassCheckboxChanged: (id) sender
4488 /* check to see if x264 is chosen */
4489 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4491 if( [fVidTwoPassCheck state] == NSOnState)
4493 [fVidTurboPassCheck setHidden: NO];
4497 [fVidTurboPassCheck setHidden: YES];
4498 [fVidTurboPassCheck setState: NSOffState];
4500 /* Make sure Two Pass is checked if Turbo is checked */
4501 if( [fVidTurboPassCheck state] == NSOnState)
4503 [fVidTwoPassCheck setState: NSOnState];
4508 [fVidTurboPassCheck setHidden: YES];
4509 [fVidTurboPassCheck setState: NSOffState];
4512 /* We call method method to change UI to reflect whether a preset is used or not*/
4513 [self customSettingUsed: sender];
4516 - (IBAction ) videoFrameRateChanged: (id) sender
4518 /* We call method method to calculatePictureSizing to error check detelecine*/
4519 [self calculatePictureSizing: sender];
4521 /* We call method method to change UI to reflect whether a preset is used or not*/
4522 [self customSettingUsed: sender];
4524 - (IBAction) videoMatrixChanged: (id) sender;
4526 bool target, bitrate, quality;
4528 target = bitrate = quality = false;
4529 if( [fVidQualityMatrix isEnabled] )
4531 switch( [fVidQualityMatrix selectedRow] )
4544 [fVidTargetSizeField setEnabled: target];
4545 [fVidBitrateField setEnabled: bitrate];
4546 [fVidQualitySlider setEnabled: quality];
4547 [fVidQualityRFField setEnabled: quality];
4548 [fVidQualityRFLabel setEnabled: quality];
4549 [fVidTwoPassCheck setEnabled: !quality &&
4550 [fVidQualityMatrix isEnabled]];
4553 [fVidTwoPassCheck setState: NSOffState];
4554 [fVidTurboPassCheck setHidden: YES];
4555 [fVidTurboPassCheck setState: NSOffState];
4558 [self qualitySliderChanged: sender];
4559 [self calculateBitrate: sender];
4560 [self customSettingUsed: sender];
4563 /* Use this method to setup the quality slider for cq/rf values depending on
4564 * the video encoder selected.
4566 - (void) setupQualitySlider
4568 /* Get the current slider maxValue to check for a change in slider scale later
4569 * so that we can choose a new similar value on the new slider scale */
4570 float previousMaxValue = [fVidQualitySlider maxValue];
4571 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4572 NSString * qpRFLabelString = @"QP:";
4574 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4576 [fVidQualitySlider setMinValue:0.0];
4577 [fVidQualitySlider setMaxValue:51.0];
4578 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4579 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4580 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4581 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0)
4583 qpRFLabelString = @"RF:";
4587 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
4589 [fVidQualitySlider setMinValue:1.0];
4590 [fVidQualitySlider setMaxValue:31.0];
4591 [fVidQualitySlider setNumberOfTickMarks:31];
4594 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4596 [fVidQualitySlider setMinValue:0.0];
4597 [fVidQualitySlider setMaxValue:63.0];
4598 [fVidQualitySlider setNumberOfTickMarks:64];
4600 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4602 /* check to see if we have changed slider scales */
4603 if (previousMaxValue != [fVidQualitySlider maxValue])
4605 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4606 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4607 [fVidQualitySlider setFloatValue:rf];
4610 [self qualitySliderChanged:nil];
4613 - (IBAction) qualitySliderChanged: (id) sender
4615 /* Our constant quality slider is in a range based
4616 * on each encoders qp/rf values. The range depends
4617 * on the encoder. Also, the range is inverse of quality
4618 * for all of the encoders *except* for theora
4619 * (ie. as the "quality" goes up, the cq or rf value
4620 * actually goes down). Since the IB sliders always set
4621 * their max value at the right end of the slider, we
4622 * will calculate the inverse, so as the slider floatValue
4623 * goes up, we will show the inverse in the rf field
4624 * so, the floatValue at the right for x264 would be 51
4625 * and our rf field needs to show 0 and vice versa.
4628 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4629 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4630 float sliderRfToPercent;
4631 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4633 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4634 sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4638 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4639 sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4641 [fVidConstantCell setTitle: [NSString stringWithFormat:
4642 NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
4644 [self customSettingUsed: sender];
4647 - (void) controlTextDidChange: (NSNotification *) notification
4649 [self calculateBitrate:nil];
4652 - (IBAction) calculateBitrate: (id) sender
4654 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4659 hb_list_t * list = hb_get_titles( fHandle );
4660 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4661 [fSrcTitlePopUp indexOfSelectedItem] );
4662 hb_job_t * job = title->job;
4663 hb_audio_config_t * audio;
4664 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4665 * Target Size Field, we also need the job info for the Muxer, the Chapters
4666 * as well as all of the audio track info.
4667 * This used to be accomplished by simply calling prepareJob here, however
4668 * since the resilient queue sets the queue array values instead of the job
4669 * values directly, we duplicate the old prepareJob code here for the variables
4672 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4673 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4674 job->mux = [[fDstFormatPopUp selectedItem] tag];
4676 /* Audio goes here */
4677 int audiotrack_count = hb_list_count(job->list_audio);
4678 for( int i = 0; i < audiotrack_count;i++)
4680 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4681 hb_list_rem(job->list_audio, temp_audio);
4683 /* Now we need our audio info here for each track if applicable */
4684 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4686 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4687 hb_audio_config_init(audio);
4688 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4689 /* We go ahead and assign values to our audio->out.<properties> */
4690 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4691 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4692 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4693 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4694 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4695 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4697 hb_audio_add( job, audio );
4700 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4702 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4703 hb_audio_config_init(audio);
4704 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4705 /* We go ahead and assign values to our audio->out.<properties> */
4706 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4707 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4708 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4709 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4710 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4711 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4713 hb_audio_add( job, audio );
4718 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4720 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4721 hb_audio_config_init(audio);
4722 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4723 /* We go ahead and assign values to our audio->out.<properties> */
4724 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4725 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
4726 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
4727 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
4728 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
4729 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
4731 hb_audio_add( job, audio );
4736 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4738 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4739 hb_audio_config_init(audio);
4740 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4741 /* We go ahead and assign values to our audio->out.<properties> */
4742 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4743 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
4744 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
4745 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
4746 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
4747 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
4749 hb_audio_add( job, audio );
4754 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
4758 #pragma mark - Picture
4760 /* lets set the picture size back to the max from right after title scan
4761 Lets use an IBAction here as down the road we could always use a checkbox
4762 in the gui to easily take the user back to max. Remember, the compiler
4763 resolves IBActions down to -(void) during compile anyway */
4764 - (IBAction) revertPictureSizeToMax: (id) sender
4766 hb_job_t * job = fTitle->job;
4767 /* Here we apply the title source and height */
4768 job->width = fTitle->width;
4769 job->height = fTitle->height;
4771 [self calculatePictureSizing: sender];
4772 /* We call method to change UI to reflect whether a preset is used or not*/
4773 [self customSettingUsed: sender];
4777 * Registers changes made in the Picture Settings Window.
4780 - (void)pictureSettingsDidChange
4782 [self calculatePictureSizing:nil];
4785 /* Get and Display Current Pic Settings in main window */
4786 - (IBAction) calculatePictureSizing: (id) sender
4788 if (fTitle->job->anamorphic.mode > 0)
4790 fTitle->job->keep_ratio = 0;
4793 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
4795 NSString *picCropping;
4796 /* Set the display field for crop as per boolean */
4797 if (![fPictureController autoCrop])
4799 picCropping = @"Custom";
4803 picCropping = @"Auto";
4805 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]]];
4807 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
4809 NSString *videoFilters;
4812 if ([fPictureController detelecine] == 2)
4814 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
4816 else if ([fPictureController detelecine] == 1)
4818 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
4822 if ([fPictureController useDecomb] == 1)
4825 if ([fPictureController decomb] == 2)
4827 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
4829 else if ([fPictureController decomb] == 1)
4831 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
4837 if ([fPictureController deinterlace] > 0)
4839 fTitle->job->deinterlace = 1;
4843 fTitle->job->deinterlace = 0;
4846 if ([fPictureController deinterlace] == 2)
4848 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
4850 else if ([fPictureController deinterlace] == 3)
4852 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
4854 else if ([fPictureController deinterlace] == 4)
4856 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
4858 else if ([fPictureController deinterlace] == 1)
4860 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
4866 if ([fPictureController denoise] == 2)
4868 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
4870 else if ([fPictureController denoise] == 3)
4872 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
4874 else if ([fPictureController denoise] == 4)
4876 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
4878 else if ([fPictureController denoise] == 1)
4880 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
4884 if ([fPictureController deblock] > 0)
4886 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
4890 if ([fPictureController grayscale])
4892 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
4894 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
4896 //[fPictureController reloadStillPreview];
4901 #pragma mark - Audio and Subtitles
4902 - (IBAction) audioCodecsPopUpChanged: (id) sender
4905 NSPopUpButton * audiotrackPopUp;
4906 NSPopUpButton * sampleratePopUp;
4907 NSPopUpButton * bitratePopUp;
4908 NSPopUpButton * audiocodecPopUp;
4909 if (sender == fAudTrack1CodecPopUp)
4911 audiotrackPopUp = fAudLang1PopUp;
4912 audiocodecPopUp = fAudTrack1CodecPopUp;
4913 sampleratePopUp = fAudTrack1RatePopUp;
4914 bitratePopUp = fAudTrack1BitratePopUp;
4916 else if (sender == fAudTrack2CodecPopUp)
4918 audiotrackPopUp = fAudLang2PopUp;
4919 audiocodecPopUp = fAudTrack2CodecPopUp;
4920 sampleratePopUp = fAudTrack2RatePopUp;
4921 bitratePopUp = fAudTrack2BitratePopUp;
4923 else if (sender == fAudTrack3CodecPopUp)
4925 audiotrackPopUp = fAudLang3PopUp;
4926 audiocodecPopUp = fAudTrack3CodecPopUp;
4927 sampleratePopUp = fAudTrack3RatePopUp;
4928 bitratePopUp = fAudTrack3BitratePopUp;
4932 audiotrackPopUp = fAudLang4PopUp;
4933 audiocodecPopUp = fAudTrack4CodecPopUp;
4934 sampleratePopUp = fAudTrack4RatePopUp;
4935 bitratePopUp = fAudTrack4BitratePopUp;
4938 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
4939 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4940 [self audioTrackPopUpChanged: audiotrackPopUp];
4944 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
4946 /* We will be setting the enabled/disabled state of each tracks audio controls based on
4947 * the settings of the source audio for that track. We leave the samplerate and bitrate
4948 * to audiotrackMixdownChanged
4951 /* We will first verify that a lower track number has been selected before enabling each track
4952 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
4954 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4956 [fAudLang2PopUp setEnabled: NO];
4957 [fAudLang2PopUp selectItemAtIndex: 0];
4961 [fAudLang2PopUp setEnabled: YES];
4964 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4966 [fAudLang3PopUp setEnabled: NO];
4967 [fAudLang3PopUp selectItemAtIndex: 0];
4971 [fAudLang3PopUp setEnabled: YES];
4973 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4975 [fAudLang4PopUp setEnabled: NO];
4976 [fAudLang4PopUp selectItemAtIndex: 0];
4980 [fAudLang4PopUp setEnabled: YES];
4982 /* enable/disable the mixdown text and popupbutton for audio track 1 */
4983 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4984 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4985 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4986 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4987 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4988 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4989 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4991 [fAudTrack1CodecPopUp removeAllItems];
4992 [fAudTrack1MixPopUp removeAllItems];
4993 [fAudTrack1RatePopUp removeAllItems];
4994 [fAudTrack1BitratePopUp removeAllItems];
4995 [fAudTrack1DrcSlider setFloatValue: 1.00];
4996 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4998 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5000 [fAudTrack1RatePopUp setEnabled: NO];
5001 [fAudTrack1BitratePopUp setEnabled: NO];
5002 [fAudTrack1DrcSlider setEnabled: NO];
5003 [fAudTrack1DrcField setEnabled: NO];
5006 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5007 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5008 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5009 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5010 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5011 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5012 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5013 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5015 [fAudTrack2CodecPopUp removeAllItems];
5016 [fAudTrack2MixPopUp removeAllItems];
5017 [fAudTrack2RatePopUp removeAllItems];
5018 [fAudTrack2BitratePopUp removeAllItems];
5019 [fAudTrack2DrcSlider setFloatValue: 1.00];
5020 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5022 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5024 [fAudTrack2RatePopUp setEnabled: NO];
5025 [fAudTrack2BitratePopUp setEnabled: NO];
5026 [fAudTrack2DrcSlider setEnabled: NO];
5027 [fAudTrack2DrcField setEnabled: NO];
5030 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5031 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5032 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5033 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5034 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5035 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5036 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5037 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5039 [fAudTrack3CodecPopUp removeAllItems];
5040 [fAudTrack3MixPopUp removeAllItems];
5041 [fAudTrack3RatePopUp removeAllItems];
5042 [fAudTrack3BitratePopUp removeAllItems];
5043 [fAudTrack3DrcSlider setFloatValue: 1.00];
5044 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5046 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5048 [fAudTrack3RatePopUp setEnabled: NO];
5049 [fAudTrack3BitratePopUp setEnabled: NO];
5050 [fAudTrack3DrcSlider setEnabled: NO];
5051 [fAudTrack3DrcField setEnabled: NO];
5054 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5055 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5056 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5057 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5058 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5059 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5060 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5061 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5063 [fAudTrack4CodecPopUp removeAllItems];
5064 [fAudTrack4MixPopUp removeAllItems];
5065 [fAudTrack4RatePopUp removeAllItems];
5066 [fAudTrack4BitratePopUp removeAllItems];
5067 [fAudTrack4DrcSlider setFloatValue: 1.00];
5068 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5070 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5072 [fAudTrack4RatePopUp setEnabled: NO];
5073 [fAudTrack4BitratePopUp setEnabled: NO];
5074 [fAudTrack4DrcSlider setEnabled: NO];
5075 [fAudTrack4DrcField setEnabled: NO];
5080 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5083 hb_list_t * list = hb_get_titles( fHandle );
5084 hb_title_t * title = (hb_title_t*)
5085 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5087 hb_audio_config_t * audio;
5089 [sender removeAllItems];
5090 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5091 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5093 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5094 [[sender menu] addItemWithTitle:
5095 [NSString stringWithUTF8String: audio->lang.description]
5096 action: NULL keyEquivalent: @""];
5098 [sender selectItemAtIndex: 0];
5102 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5105 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5106 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5107 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5108 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5110 if (searchPrefixString)
5113 for( int i = 0; i < [sender numberOfItems]; i++ )
5115 /* Try to find the desired search string */
5116 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5118 [sender selectItemAtIndex: i];
5122 /* couldn't find the string, so select the requested "search string not found" item */
5123 /* index of 0 means select the "none" item */
5124 /* index of 1 means select the first audio track */
5125 [sender selectItemAtIndex: selectIndexIfNotFound];
5129 /* if no search string is provided, then select the selectIndexIfNotFound item */
5130 [sender selectItemAtIndex: selectIndexIfNotFound];
5134 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5136 int format = [fDstFormatPopUp indexOfSelectedItem];
5138 /* setup pointers to the appropriate popups for the correct track */
5139 NSPopUpButton * audiocodecPopUp;
5140 NSPopUpButton * audiotrackPopUp;
5141 if (sender == fAudTrack1CodecPopUp)
5143 audiotrackPopUp = fAudLang1PopUp;
5144 audiocodecPopUp = fAudTrack1CodecPopUp;
5146 else if (sender == fAudTrack2CodecPopUp)
5148 audiotrackPopUp = fAudLang2PopUp;
5149 audiocodecPopUp = fAudTrack2CodecPopUp;
5151 else if (sender == fAudTrack3CodecPopUp)
5153 audiotrackPopUp = fAudLang3PopUp;
5154 audiocodecPopUp = fAudTrack3CodecPopUp;
5158 audiotrackPopUp = fAudLang4PopUp;
5159 audiocodecPopUp = fAudTrack4CodecPopUp;
5162 [audiocodecPopUp removeAllItems];
5163 /* Make sure "None" isnt selected in the source track */
5164 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5166 [audiocodecPopUp setEnabled:YES];
5167 NSMenuItem *menuItem;
5168 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5174 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5175 [menuItem setTag: HB_ACODEC_FAAC];
5178 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5179 [menuItem setTag: HB_ACODEC_CA_AAC];
5182 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5183 [menuItem setTag: HB_ACODEC_AC3];
5189 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5190 [menuItem setTag: HB_ACODEC_FAAC];
5192 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5193 [menuItem setTag: HB_ACODEC_CA_AAC];
5195 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5196 [menuItem setTag: HB_ACODEC_AC3];
5198 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5199 [menuItem setTag: HB_ACODEC_DCA];
5201 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5202 [menuItem setTag: HB_ACODEC_LAME];
5204 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5205 [menuItem setTag: HB_ACODEC_VORBIS];
5211 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5212 [menuItem setTag: HB_ACODEC_LAME];
5214 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5215 [menuItem setTag: HB_ACODEC_AC3];
5221 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5222 [menuItem setTag: HB_ACODEC_VORBIS];
5224 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5225 [menuItem setTag: HB_ACODEC_LAME];
5228 [audiocodecPopUp selectItemAtIndex:0];
5232 [audiocodecPopUp setEnabled:NO];
5236 - (IBAction) audioTrackPopUpChanged: (id) sender
5238 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5239 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5242 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5245 /* make sure we have a selected title before continuing */
5246 if (fTitle == NULL) return;
5247 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5248 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5250 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5252 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5254 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5256 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5258 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5260 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5262 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5264 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5267 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5268 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5270 sender = fAudLang1PopUp;
5272 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5274 sender = fAudLang2PopUp;
5276 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5278 sender = fAudLang3PopUp;
5280 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5282 sender = fAudLang4PopUp;
5285 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5286 NSPopUpButton * mixdownPopUp;
5287 NSPopUpButton * audiocodecPopUp;
5288 NSPopUpButton * sampleratePopUp;
5289 NSPopUpButton * bitratePopUp;
5290 if (sender == fAudLang1PopUp)
5292 mixdownPopUp = fAudTrack1MixPopUp;
5293 audiocodecPopUp = fAudTrack1CodecPopUp;
5294 sampleratePopUp = fAudTrack1RatePopUp;
5295 bitratePopUp = fAudTrack1BitratePopUp;
5297 else if (sender == fAudLang2PopUp)
5299 mixdownPopUp = fAudTrack2MixPopUp;
5300 audiocodecPopUp = fAudTrack2CodecPopUp;
5301 sampleratePopUp = fAudTrack2RatePopUp;
5302 bitratePopUp = fAudTrack2BitratePopUp;
5304 else if (sender == fAudLang3PopUp)
5306 mixdownPopUp = fAudTrack3MixPopUp;
5307 audiocodecPopUp = fAudTrack3CodecPopUp;
5308 sampleratePopUp = fAudTrack3RatePopUp;
5309 bitratePopUp = fAudTrack3BitratePopUp;
5313 mixdownPopUp = fAudTrack4MixPopUp;
5314 audiocodecPopUp = fAudTrack4CodecPopUp;
5315 sampleratePopUp = fAudTrack4RatePopUp;
5316 bitratePopUp = fAudTrack4BitratePopUp;
5319 /* get the index of the selected audio Track*/
5320 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5322 /* pointer for the hb_audio_s struct we will use later on */
5323 hb_audio_config_t * audio;
5326 /* check if the audio mixdown controls need their enabled state changing */
5327 [self setEnabledStateOfAudioMixdownControls:nil];
5329 if (thisAudioIndex != -1)
5333 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5335 /* actually manipulate the proper mixdowns here */
5336 /* delete the previous audio mixdown options */
5337 [mixdownPopUp removeAllItems];
5339 acodec = [[audiocodecPopUp selectedItem] tag];
5344 /* find out if our selected output audio codec supports mono and / or 6ch */
5345 /* we also check for an input codec of AC3 or DCA,
5346 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5347 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5348 but this may change in the future, so they are separated for flexibility */
5349 int audioCodecsSupportMono =
5350 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5351 (acodec != HB_ACODEC_LAME);
5352 int audioCodecsSupport6Ch =
5353 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5354 (acodec != HB_ACODEC_LAME);
5356 /* check for AC-3 passthru */
5357 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5360 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5361 [NSString stringWithUTF8String: "AC3 Passthru"]
5362 action: NULL keyEquivalent: @""];
5363 [menuItem setTag: HB_ACODEC_AC3];
5365 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5367 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5368 [NSString stringWithUTF8String: "DTS Passthru"]
5369 action: NULL keyEquivalent: @""];
5370 [menuItem setTag: HB_ACODEC_DCA];
5375 /* add the appropriate audio mixdown menuitems to the popupbutton */
5376 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5377 so that we can reference the mixdown later */
5379 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5380 int minMixdownUsed = 0;
5381 int maxMixdownUsed = 0;
5383 /* get the input channel layout without any lfe channels */
5384 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5386 /* do we want to add a mono option? */
5387 if (audioCodecsSupportMono == 1)
5389 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5390 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5391 action: NULL keyEquivalent: @""];
5392 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5393 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5394 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5397 /* do we want to add a stereo option? */
5398 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5399 /* also offer stereo if we have a stereo-or-better source */
5400 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5402 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5403 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5404 action: NULL keyEquivalent: @""];
5405 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5406 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5407 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5410 /* do we want to add a dolby surround (DPL1) option? */
5411 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5413 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5414 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5415 action: NULL keyEquivalent: @""];
5416 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5417 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5418 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5421 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5422 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5424 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5425 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5426 action: NULL keyEquivalent: @""];
5427 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5428 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5429 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5432 /* do we want to add a 6-channel discrete option? */
5433 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5435 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5436 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5437 action: NULL keyEquivalent: @""];
5438 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5439 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5440 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5443 /* do we want to add an AC-3 passthrough option? */
5444 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5446 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5447 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5448 action: NULL keyEquivalent: @""];
5449 [menuItem setTag: HB_ACODEC_AC3];
5450 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5451 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5454 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5455 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5457 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5458 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5459 action: NULL keyEquivalent: @""];
5460 [menuItem setTag: HB_ACODEC_DCA];
5461 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5462 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5465 /* auto-select the best mixdown based on our saved mixdown preference */
5467 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5468 /* ultimately this should be a prefs option */
5471 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5472 if (mixdownToUse > 0)
5474 useMixdown = mixdownToUse;
5478 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5481 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5482 if (useMixdown > maxMixdownUsed)
5484 useMixdown = maxMixdownUsed;
5487 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5488 if (useMixdown < minMixdownUsed)
5490 useMixdown = minMixdownUsed;
5493 /* select the (possibly-amended) preferred mixdown */
5494 [mixdownPopUp selectItemWithTag: useMixdown];
5497 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5498 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5501 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5503 /* If we are using the avi container, we select MP3 as there is no aac available*/
5504 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5506 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5510 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5514 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5515 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5518 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5520 /* If we are using the avi container, we select MP3 as there is no aac available*/
5521 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5523 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5527 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5531 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5532 [self audioTrackMixdownChanged: mixdownPopUp];
5536 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5538 [self autoSetM4vExtension: sender];
5542 - (IBAction) audioTrackMixdownChanged: (id) sender
5546 /* setup pointers to all of the other audio track controls
5547 * we will need later
5549 NSPopUpButton * mixdownPopUp;
5550 NSPopUpButton * sampleratePopUp;
5551 NSPopUpButton * bitratePopUp;
5552 NSPopUpButton * audiocodecPopUp;
5553 NSPopUpButton * audiotrackPopUp;
5554 NSSlider * drcSlider;
5555 NSTextField * drcField;
5556 if (sender == fAudTrack1MixPopUp)
5558 audiotrackPopUp = fAudLang1PopUp;
5559 audiocodecPopUp = fAudTrack1CodecPopUp;
5560 mixdownPopUp = fAudTrack1MixPopUp;
5561 sampleratePopUp = fAudTrack1RatePopUp;
5562 bitratePopUp = fAudTrack1BitratePopUp;
5563 drcSlider = fAudTrack1DrcSlider;
5564 drcField = fAudTrack1DrcField;
5566 else if (sender == fAudTrack2MixPopUp)
5568 audiotrackPopUp = fAudLang2PopUp;
5569 audiocodecPopUp = fAudTrack2CodecPopUp;
5570 mixdownPopUp = fAudTrack2MixPopUp;
5571 sampleratePopUp = fAudTrack2RatePopUp;
5572 bitratePopUp = fAudTrack2BitratePopUp;
5573 drcSlider = fAudTrack2DrcSlider;
5574 drcField = fAudTrack2DrcField;
5576 else if (sender == fAudTrack3MixPopUp)
5578 audiotrackPopUp = fAudLang3PopUp;
5579 audiocodecPopUp = fAudTrack3CodecPopUp;
5580 mixdownPopUp = fAudTrack3MixPopUp;
5581 sampleratePopUp = fAudTrack3RatePopUp;
5582 bitratePopUp = fAudTrack3BitratePopUp;
5583 drcSlider = fAudTrack3DrcSlider;
5584 drcField = fAudTrack3DrcField;
5588 audiotrackPopUp = fAudLang4PopUp;
5589 audiocodecPopUp = fAudTrack4CodecPopUp;
5590 mixdownPopUp = fAudTrack4MixPopUp;
5591 sampleratePopUp = fAudTrack4RatePopUp;
5592 bitratePopUp = fAudTrack4BitratePopUp;
5593 drcSlider = fAudTrack4DrcSlider;
5594 drcField = fAudTrack4DrcField;
5596 acodec = [[audiocodecPopUp selectedItem] tag];
5597 /* storage variable for the min and max bitrate allowed for this codec */
5603 case HB_ACODEC_FAAC:
5604 /* check if we have a 6ch discrete conversion in either audio track */
5605 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5607 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
5609 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5615 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5617 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5618 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5623 case HB_ACODEC_CA_AAC:
5624 /* check if we have a 6ch discrete conversion in either audio track */
5625 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5638 case HB_ACODEC_LAME:
5639 /* Lame is happy using our min bitrate of 32 kbps */
5641 /* Lame won't encode if the bitrate is higher than 320 kbps */
5645 case HB_ACODEC_VORBIS:
5646 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5648 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5650 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5656 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5658 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5664 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5670 /* make sure we have a selected title before continuing */
5671 if (fTitle == NULL) return;
5672 /* get the audio so we can find out what input rates are*/
5673 hb_audio_config_t * audio;
5674 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5675 int inputbitrate = audio->in.bitrate / 1000;
5676 int inputsamplerate = audio->in.samplerate;
5678 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
5680 [bitratePopUp removeAllItems];
5682 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5684 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5686 /* add a new menuitem for this bitrate */
5687 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5688 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
5689 action: NULL keyEquivalent: @""];
5690 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5691 [menuItem setTag: hb_audio_bitrates[i].rate];
5695 /* select the default bitrate (but use 384 for 6-ch AAC) */
5696 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5698 [bitratePopUp selectItemWithTag: 384];
5702 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5705 /* populate and set the sample rate popup */
5706 /* Audio samplerate */
5707 [sampleratePopUp removeAllItems];
5708 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5709 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5710 [menuItem setTag: inputsamplerate];
5712 for( int i = 0; i < hb_audio_rates_count; i++ )
5714 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5715 [NSString stringWithUTF8String: hb_audio_rates[i].string]
5716 action: NULL keyEquivalent: @""];
5717 [menuItem setTag: hb_audio_rates[i].rate];
5719 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5720 * and there is no compelling reason to use anything else as default, though the users default
5721 * preset will likely override any setting chosen here.
5723 [sampleratePopUp selectItemWithTag: inputsamplerate];
5726 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
5727 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
5728 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
5730 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
5733 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
5734 [bitratePopUp removeAllItems];
5735 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5736 [NSString stringWithFormat:@"%d", inputbitrate]
5737 action: NULL keyEquivalent: @""];
5738 [menuItem setTag: inputbitrate];
5739 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
5740 [bitratePopUp setEnabled: NO];
5741 [sampleratePopUp setEnabled: NO];
5743 [drcSlider setFloatValue: 1.00];
5744 [self audioDRCSliderChanged: drcSlider];
5745 [drcSlider setEnabled: NO];
5746 [drcField setEnabled: NO];
5750 [sampleratePopUp setEnabled: YES];
5751 [bitratePopUp setEnabled: YES];
5752 [drcSlider setEnabled: YES];
5753 [drcField setEnabled: YES];
5755 [self calculateBitrate:nil];
5758 - (IBAction) audioDRCSliderChanged: (id) sender
5760 NSSlider * drcSlider;
5761 NSTextField * drcField;
5762 if (sender == fAudTrack1DrcSlider)
5764 drcSlider = fAudTrack1DrcSlider;
5765 drcField = fAudTrack1DrcField;
5767 else if (sender == fAudTrack2DrcSlider)
5769 drcSlider = fAudTrack2DrcSlider;
5770 drcField = fAudTrack2DrcField;
5772 else if (sender == fAudTrack3DrcSlider)
5774 drcSlider = fAudTrack3DrcSlider;
5775 drcField = fAudTrack3DrcField;
5779 drcSlider = fAudTrack4DrcSlider;
5780 drcField = fAudTrack4DrcField;
5783 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
5784 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
5786 [drcSlider setFloatValue:1.0];
5790 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
5791 /* For now, do not call this until we have an intelligent way to determine audio track selections
5792 * compared to presets
5794 //[self customSettingUsed: sender];
5799 - (IBAction) browseImportSrtFile: (id) sender
5802 NSOpenPanel * panel;
5804 panel = [NSOpenPanel openPanel];
5805 [panel setAllowsMultipleSelection: NO];
5806 [panel setCanChooseFiles: YES];
5807 [panel setCanChooseDirectories: NO ];
5808 NSString * sourceDirectory;
5809 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
5811 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
5815 sourceDirectory = @"~/Desktop";
5816 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
5818 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
5819 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
5820 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
5821 modalForWindow: fWindow modalDelegate: self
5822 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
5823 contextInfo: sender];
5826 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
5827 returnCode: (int) returnCode contextInfo: (void *) contextInfo
5829 if( returnCode == NSOKButton )
5831 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
5832 NSString *importSrtFilePath = [sheet filename];
5833 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
5835 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
5836 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
5838 [fSubtitlesTable reloadData];
5844 #pragma mark Open New Windows
5846 - (IBAction) openHomepage: (id) sender
5848 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5849 URLWithString:@"http://handbrake.fr/"]];
5852 - (IBAction) openForums: (id) sender
5854 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5855 URLWithString:@"http://handbrake.fr/forum/"]];
5857 - (IBAction) openUserGuide: (id) sender
5859 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5860 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
5864 * Shows debug output window.
5866 - (IBAction)showDebugOutputPanel:(id)sender
5868 [outputPanel showOutputPanel:sender];
5872 * Shows preferences window.
5874 - (IBAction) showPreferencesWindow: (id) sender
5876 NSWindow * window = [fPreferencesController window];
5877 if (![window isVisible])
5880 [window makeKeyAndOrderFront: nil];
5884 * Shows queue window.
5886 - (IBAction) showQueueWindow:(id)sender
5888 [fQueueController showQueueWindow:sender];
5892 - (IBAction) toggleDrawer:(id)sender {
5893 [fPresetDrawer toggle:self];
5897 * Shows Picture Settings Window.
5900 - (IBAction) showPicturePanel: (id) sender
5902 [fPictureController showPictureWindow:sender];
5905 - (void) picturePanelFullScreen
5907 [fPictureController setToFullScreenMode];
5910 - (void) picturePanelWindowed
5912 [fPictureController setToWindowedMode];
5915 - (IBAction) showPreviewWindow: (id) sender
5917 [fPictureController showPreviewWindow:sender];
5921 #pragma mark Preset Outline View Methods
5922 #pragma mark - Required
5923 /* These are required by the NSOutlineView Datasource Delegate */
5926 /* used to specify the number of levels to show for each item */
5927 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
5929 /* currently use no levels to test outline view viability */
5930 if (item == nil) // for an outline view the root level of the hierarchy is always nil
5932 return [UserPresets count];
5936 /* we need to return the count of the array in ChildrenArray for this folder */
5937 NSArray *children = nil;
5938 children = [item objectForKey:@"ChildrenArray"];
5939 if ([children count] > 0)
5941 return [children count];
5950 /* We use this to deterimine children of an item */
5951 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
5954 /* we need to return the count of the array in ChildrenArray for this folder */
5955 NSArray *children = nil;
5958 children = UserPresets;
5962 if ([item objectForKey:@"ChildrenArray"])
5964 children = [item objectForKey:@"ChildrenArray"];
5967 if ((children == nil) || ( [children count] <= (NSUInteger) index))
5973 return [children objectAtIndex:index];
5977 // We are only one level deep, so we can't be asked about children
5978 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
5982 /* We use this to determine if an item should be expandable */
5983 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
5986 /* we need to return the count of the array in ChildrenArray for this folder */
5987 NSArray *children= nil;
5990 children = UserPresets;
5994 if ([item objectForKey:@"ChildrenArray"])
5996 children = [item objectForKey:@"ChildrenArray"];
6000 /* To deterimine if an item should show a disclosure triangle
6001 * we could do it by the children count as so:
6002 * if ([children count] < 1)
6003 * However, lets leave the triangle show even if there are no
6004 * children to help indicate a folder, just like folder in the
6005 * finder can show a disclosure triangle even when empty
6008 /* We need to determine if the item is a folder */
6009 if ([[item objectForKey:@"Folder"] intValue] == 1)
6020 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6022 // Our outline view has no levels, but we can still expand every item. Doing so
6023 // just makes the row taller. See heightOfRowByItem below.
6024 //return ![(HBQueueOutlineView*)outlineView isDragging];
6030 /* Used to tell the outline view which information is to be displayed per item */
6031 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6033 /* We have two columns right now, icon and PresetName */
6035 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6037 return [item objectForKey:@"PresetName"];
6046 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6048 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6050 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6052 return [NSKeyedArchiver archivedDataWithRootObject:item];
6055 #pragma mark - Added Functionality (optional)
6056 /* Use to customize the font and display characteristics of the title cell */
6057 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6059 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6063 NSColor *shadowColor;
6064 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6065 /*check to see if its a selected row */
6066 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6069 fontColor = [NSColor blackColor];
6070 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6074 if ([[item objectForKey:@"Type"] intValue] == 0)
6076 fontColor = [NSColor blueColor];
6078 else // User created preset, use a black font
6080 fontColor = [NSColor blackColor];
6082 /* check to see if its a folder */
6083 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6085 //fontColor = [NSColor greenColor];
6090 /* We use Bold Text for the HB Default */
6091 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6093 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6095 /* We use Bold Text for the User Specified Default */
6096 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6098 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6102 [cell setTextColor:fontColor];
6103 [cell setFont:txtFont];
6108 /* We use this to edit the name field in the outline view */
6109 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6111 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6116 [theRecord setObject:object forKey:@"PresetName"];
6120 [fPresetsOutlineView reloadData];
6121 /* We save all of the preset data here */
6125 /* We use this to provide tooltips for the items in the presets outline view */
6126 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6128 //if ([[tc identifier] isEqualToString:@"PresetName"])
6130 /* initialize the tooltip contents variable */
6132 /* if there is a description for the preset, we show it in the tooltip */
6133 if ([item objectForKey:@"PresetDescription"])
6135 loc_tip = [item objectForKey:@"PresetDescription"];
6140 loc_tip = @"No description available";
6147 #pragma mark Preset Outline View Methods (dragging related)
6150 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6152 // Dragging is only allowed for custom presets.
6153 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6154 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6158 // Don't retain since this is just holding temporaral drag information, and it is
6159 //only used during a drag! We could put this in the pboard actually.
6160 fDraggedNodes = items;
6161 // Provide data for our custom type, and simple NSStrings.
6162 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6164 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6165 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6170 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6173 // Don't allow dropping ONTO an item since they can't really contain any children.
6175 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6176 if (isOnDropTypeProposal)
6177 return NSDragOperationNone;
6179 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6182 index = [fPresetsOutlineView rowForItem: item] + 1;
6186 // Don't allow dropping into the Built In Presets.
6187 if (index < presetCurrentBuiltInCount)
6189 return NSDragOperationNone;
6190 index = MAX (index, presetCurrentBuiltInCount);
6193 [outlineView setDropItem:item dropChildIndex:index];
6194 return NSDragOperationGeneric;
6199 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6201 /* first, lets see if we are dropping into a folder */
6202 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6204 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6205 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6206 [childrenArray addObject:item];
6207 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6208 [childrenArray autorelease];
6210 else // We are not, so we just move the preset into the existing array
6212 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6214 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6215 while (obj = [enumerator nextObject])
6217 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6219 // Successful drop, lets rearrange the view and save it all
6220 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6222 [fPresetsOutlineView reloadData];
6227 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6229 NSUInteger index = [indexSet lastIndex];
6230 NSUInteger aboveInsertIndexCount = 0;
6232 NSUInteger removeIndex;
6234 if (index >= insertIndex)
6236 removeIndex = index + aboveInsertIndexCount;
6237 aboveInsertIndexCount++;
6241 removeIndex = index;
6245 id object = [[array objectAtIndex:removeIndex] retain];
6246 [array removeObjectAtIndex:removeIndex];
6247 [array insertObject:object atIndex:insertIndex];
6250 index = [indexSet indexLessThanIndex:index];
6255 #pragma mark - Functional Preset NSOutlineView Methods
6257 - (IBAction)selectPreset:(id)sender
6260 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6262 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6263 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6265 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6267 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6271 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6275 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6276 [self formatPopUpChanged:nil];
6278 /* Chapter Markers*/
6279 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6280 /* check to see if we have only one chapter */
6281 [self chapterPopUpChanged:nil];
6283 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6284 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6285 /* Mux mp4 with http optimization */
6286 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6289 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6290 /* We set the advanced opt string here if applicable*/
6291 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6293 /* Lets run through the following functions to get variables set there */
6294 [self videoEncoderPopUpChanged:nil];
6295 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6296 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6297 [self calculateBitrate:nil];
6300 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6302 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6303 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6305 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6306 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6307 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6308 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6309 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6310 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6312 /* For the quality slider we need to convert the old percent's to the new rf scales */
6313 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6314 [fVidQualitySlider setFloatValue:rf];
6319 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6320 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6322 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6326 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6327 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6331 [self videoMatrixChanged:nil];
6333 /* Video framerate */
6334 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6335 detected framerate in the fVidRatePopUp so we use index 0*/
6336 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6338 [fVidRatePopUp selectItemAtIndex: 0];
6342 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6346 /* 2 Pass Encoding */
6347 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6348 [self twoPassCheckboxChanged:nil];
6350 /* Turbo 1st pass for 2 Pass Encoding */
6351 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6354 /* First we check to see if we are using the current audio track layout based on AudioList array */
6355 if ([chosenPreset objectForKey:@"AudioList"])
6358 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6359 NSPopUpButton * trackLangPopUp = nil;
6360 NSPopUpButton * mixdownPopUp = nil;
6361 NSPopUpButton * audiocodecPopUp = nil;
6362 NSPopUpButton * sampleratePopUp = nil;
6363 NSPopUpButton * bitratePopUp = nil;
6364 NSSlider * drcSlider = nil;
6367 /* Populate the audio widgets based on the contents of the AudioList array */
6369 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6371 while (tempObject = [enumerator nextObject])
6376 trackLangPopUp = fAudLang1PopUp;
6377 mixdownPopUp = fAudTrack1MixPopUp;
6378 audiocodecPopUp = fAudTrack1CodecPopUp;
6379 sampleratePopUp = fAudTrack1RatePopUp;
6380 bitratePopUp = fAudTrack1BitratePopUp;
6381 drcSlider = fAudTrack1DrcSlider;
6385 trackLangPopUp = fAudLang2PopUp;
6386 mixdownPopUp = fAudTrack2MixPopUp;
6387 audiocodecPopUp = fAudTrack2CodecPopUp;
6388 sampleratePopUp = fAudTrack2RatePopUp;
6389 bitratePopUp = fAudTrack2BitratePopUp;
6390 drcSlider = fAudTrack2DrcSlider;
6394 trackLangPopUp = fAudLang3PopUp;
6395 mixdownPopUp = fAudTrack3MixPopUp;
6396 audiocodecPopUp = fAudTrack3CodecPopUp;
6397 sampleratePopUp = fAudTrack3RatePopUp;
6398 bitratePopUp = fAudTrack3BitratePopUp;
6399 drcSlider = fAudTrack3DrcSlider;
6403 trackLangPopUp = fAudLang4PopUp;
6404 mixdownPopUp = fAudTrack4MixPopUp;
6405 audiocodecPopUp = fAudTrack4CodecPopUp;
6406 sampleratePopUp = fAudTrack4RatePopUp;
6407 bitratePopUp = fAudTrack4BitratePopUp;
6408 drcSlider = fAudTrack4DrcSlider;
6412 if ([trackLangPopUp indexOfSelectedItem] == 0)
6414 [trackLangPopUp selectItemAtIndex: 1];
6416 [self audioTrackPopUpChanged: trackLangPopUp];
6417 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6418 /* check our pref for core audio and use it in place of faac if applicable */
6419 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6420 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6422 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6425 [self audioTrackPopUpChanged: audiocodecPopUp];
6426 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6427 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6429 if ([mixdownPopUp selectedItem] == nil)
6431 [self audioTrackPopUpChanged: audiocodecPopUp];
6433 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6434 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6435 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6437 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6439 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6440 [self audioDRCSliderChanged: drcSlider];
6443 /* 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,
6444 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6448 /* 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". */
6449 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6451 hb_audio_config_t * audio;
6452 /* get the audio source audio codec */
6453 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6454 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6455 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6457 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6458 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6460 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6462 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6464 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6466 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6467 [trackLangPopUp selectItemAtIndex: 0];
6468 [self audioTrackPopUpChanged: trackLangPopUp];
6474 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6478 [fAudLang4PopUp selectItemAtIndex: 0];
6479 [self audioTrackPopUpChanged: fAudLang4PopUp];
6483 [fAudLang3PopUp selectItemAtIndex: 0];
6484 [self audioTrackPopUpChanged: fAudLang3PopUp];
6488 [fAudLang2PopUp selectItemAtIndex: 0];
6489 [self audioTrackPopUpChanged: fAudLang2PopUp];
6497 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6499 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6501 [fAudLang1PopUp selectItemAtIndex: 1];
6503 [self audioTrackPopUpChanged: fAudLang1PopUp];
6504 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6505 /* check our pref for core audio and use it in place of faac if applicable */
6506 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6507 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6509 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6511 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6512 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6513 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6515 if ([fAudTrack1MixPopUp selectedItem] == nil)
6517 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6519 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6520 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6521 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6523 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6525 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6526 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6529 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6531 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6533 [fAudLang2PopUp selectItemAtIndex: 1];
6535 [self audioTrackPopUpChanged: fAudLang2PopUp];
6536 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6537 /* check our pref for core audio and use it in place of faac if applicable */
6538 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6539 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6541 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6543 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6544 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6545 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6547 if ([fAudTrack2MixPopUp selectedItem] == nil)
6549 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6551 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6552 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6553 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6555 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6557 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6558 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6560 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6562 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6564 [fAudLang3PopUp selectItemAtIndex: 1];
6566 [self audioTrackPopUpChanged: fAudLang3PopUp];
6567 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6568 /* check our pref for core audio and use it in place of faac if applicable */
6569 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6570 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6572 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6574 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6575 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6576 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6578 if ([fAudTrack3MixPopUp selectedItem] == nil)
6580 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6582 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6583 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6584 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6586 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6588 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6589 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6591 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6593 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6595 [fAudLang4PopUp selectItemAtIndex: 1];
6597 [self audioTrackPopUpChanged: fAudLang4PopUp];
6598 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6599 /* check our pref for core audio and use it in place of faac if applicable */
6600 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6601 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6603 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6605 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6606 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6607 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6609 if ([fAudTrack4MixPopUp selectedItem] == nil)
6611 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6613 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
6614 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6615 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
6617 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
6619 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
6620 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
6623 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6625 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
6627 [fAudLang2PopUp selectItemAtIndex: 0];
6628 [self audioTrackPopUpChanged: fAudLang2PopUp];
6630 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
6632 [fAudLang3PopUp selectItemAtIndex: 0];
6633 [self audioTrackPopUpChanged: fAudLang3PopUp];
6635 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
6637 [fAudLang4PopUp selectItemAtIndex: 0];
6638 [self audioTrackPopUpChanged: fAudLang4PopUp];
6643 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
6644 /* Forced Subtitles */
6645 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
6647 /* Picture Settings */
6648 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
6649 * height, width, keep ar, anamorphic and crop settings.
6650 * picture filters are handled separately below.
6652 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
6653 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
6654 * preset completely ignores any picture sizing values in the preset.
6656 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
6658 hb_job_t * job = fTitle->job;
6660 /* If Cropping is set to custom, then recall all four crop values from
6661 when the preset was created and apply them */
6662 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
6664 [fPictureController setAutoCrop:NO];
6666 /* Here we use the custom crop values saved at the time the preset was saved */
6667 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
6668 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
6669 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
6670 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
6673 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
6675 [fPictureController setAutoCrop:YES];
6676 /* Here we use the auto crop values determined right after scan */
6677 job->crop[0] = AutoCropTop;
6678 job->crop[1] = AutoCropBottom;
6679 job->crop[2] = AutoCropLeft;
6680 job->crop[3] = AutoCropRight;
6685 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
6686 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
6688 /* Use Max Picture settings for whatever the dvd is.*/
6689 [self revertPictureSizeToMax:nil];
6690 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6691 if (job->keep_ratio == 1)
6693 hb_fix_aspect( job, HB_KEEP_WIDTH );
6694 if( job->height > fTitle->height )
6696 job->height = fTitle->height;
6697 hb_fix_aspect( job, HB_KEEP_HEIGHT );
6700 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
6702 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
6704 /* we check to make sure the presets width/height does not exceed the sources width/height */
6705 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
6707 /* if so, then we use the sources height and width to avoid scaling up */
6708 //job->width = fTitle->width;
6709 //job->height = fTitle->height;
6710 [self revertPictureSizeToMax:nil];
6712 else // source width/height is >= the preset height/width
6714 /* we can go ahead and use the presets values for height and width */
6715 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
6716 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
6718 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6719 if (job->keep_ratio == 1)
6721 hb_fix_aspect( job, HB_KEEP_WIDTH );
6722 if( job->height > fTitle->height )
6724 job->height = fTitle->height;
6725 hb_fix_aspect( job, HB_KEEP_HEIGHT );
6728 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
6734 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
6735 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
6739 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
6740 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
6741 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
6744 [fPictureController setUseDecomb:1];
6745 [fPictureController setDecomb:0];
6746 [fPictureController setDeinterlace:0];
6747 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
6749 /* we are using decomb */
6751 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
6753 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
6755 /* if we are using "Custom" in the decomb setting, also set the custom string*/
6756 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
6758 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
6764 /* We are using Deinterlace */
6766 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
6768 [fPictureController setUseDecomb:0];
6769 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
6770 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
6771 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
6773 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
6780 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
6782 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
6783 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
6784 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
6786 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
6791 [fPictureController setDetelecine:0];
6795 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
6797 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
6798 /* if we are using "Custom" in the denoise setting, also set the custom string*/
6799 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
6801 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
6806 [fPictureController setDenoise:0];
6810 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
6812 /* if its a one, then its the old on/off deblock, set on to 5*/
6813 [fPictureController setDeblock:5];
6817 /* use the settings intValue */
6818 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
6821 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
6823 [fPictureController setGrayscale:1];
6827 [fPictureController setGrayscale:0];
6830 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
6831 [fPictureController SetTitle:fTitle];
6832 [fPictureController SetTitle:fTitle];
6833 [self calculatePictureSizing:nil];
6839 #pragma mark Manage Presets
6841 - (void) loadPresets {
6842 /* We declare the default NSFileManager into fileManager */
6843 NSFileManager * fileManager = [NSFileManager defaultManager];
6844 /*We define the location of the user presets file */
6845 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
6846 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
6847 /* We check for the presets.plist */
6848 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
6850 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
6853 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
6854 if (nil == UserPresets)
6856 UserPresets = [[NSMutableArray alloc] init];
6857 [self addFactoryPresets:nil];
6859 [fPresetsOutlineView reloadData];
6861 [self checkBuiltInsForUpdates];
6864 - (void) checkBuiltInsForUpdates {
6866 BOOL updateBuiltInPresets = NO;
6868 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6870 while (tempObject = [enumerator nextObject])
6872 /* iterate through the built in presets to see if any have an old build number */
6873 NSMutableDictionary *thisPresetDict = tempObject;
6874 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
6875 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
6877 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
6879 updateBuiltInPresets = YES;
6884 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
6885 if ( updateBuiltInPresets == YES)
6887 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
6889 /* Show an alert window that built in presets will be updated */
6890 /*On Screen Notification*/
6893 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
6894 [NSApp requestUserAttention:NSCriticalRequest];
6896 /* when alert is dismissed, go ahead and update the built in presets */
6897 [self addFactoryPresets:nil];
6903 - (IBAction) showAddPresetPanel: (id) sender
6905 /* Deselect the currently selected Preset if there is one*/
6906 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
6908 /* Populate the preset picture settings popup here */
6909 [fPresetNewPicSettingsPopUp removeAllItems];
6910 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
6911 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
6912 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
6913 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
6914 /* Uncheck the preset use filters checkbox */
6915 [fPresetNewPicFiltersCheck setState:NSOffState];
6916 // fPresetNewFolderCheck
6917 [fPresetNewFolderCheck setState:NSOffState];
6918 /* Erase info from the input fields*/
6919 [fPresetNewName setStringValue: @""];
6920 [fPresetNewDesc setStringValue: @""];
6921 /* Show the panel */
6922 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
6925 - (IBAction) closeAddPresetPanel: (id) sender
6927 [NSApp endSheet: fAddPresetPanel];
6928 [fAddPresetPanel orderOut: self];
6931 - (IBAction)addUserPreset:(id)sender
6933 if (![[fPresetNewName stringValue] length])
6934 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
6937 /* Here we create a custom user preset */
6938 [UserPresets addObject:[self createPreset]];
6941 [self closeAddPresetPanel:nil];
6948 /* We Reload the New Table data for presets */
6949 [fPresetsOutlineView reloadData];
6950 /* We save all of the preset data here */
6958 /* We Sort the Presets By Factory or Custom */
6959 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
6960 ascending:YES] autorelease];
6961 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
6963 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
6964 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
6965 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
6968 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
6969 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
6970 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
6971 [UserPresets setArray:sortedArray];
6976 - (IBAction)insertPreset:(id)sender
6978 int index = [fPresetsOutlineView selectedRow];
6979 [UserPresets insertObject:[self createPreset] atIndex:index];
6980 [fPresetsOutlineView reloadData];
6984 - (NSDictionary *)createPreset
6986 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
6987 /* Preset build number */
6988 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
6989 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
6990 /* Get the New Preset Name from the field in the AddPresetPanel */
6991 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
6992 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
6993 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
6994 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
6995 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
6996 /*Set whether or not this is default, at creation set to 0*/
6997 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6998 if ([fPresetNewFolderCheck state] == YES)
7000 /* initialize and set an empty array for children here since we are a new folder */
7001 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7002 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7003 [childrenArray autorelease];
7005 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7007 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7008 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7009 /* Get whether or not to use the current Picture Filter settings for the preset */
7010 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7012 /* Get New Preset Description from the field in the AddPresetPanel*/
7013 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7015 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7016 /* Chapter Markers fCreateChapterMarkers*/
7017 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7018 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7019 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7020 /* Mux mp4 with http optimization */
7021 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7022 /* Add iPod uuid atom */
7023 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7027 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7028 /* x264 Option String */
7029 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7031 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7032 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7033 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7034 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7036 /* Video framerate */
7037 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7039 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7041 else // we can record the actual titleOfSelectedItem
7043 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7046 /* 2 Pass Encoding */
7047 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7048 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7049 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7050 /*Picture Settings*/
7051 hb_job_t * job = fTitle->job;
7052 /* Picture Sizing */
7053 /* Use Max Picture settings for whatever the dvd is.*/
7054 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7055 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7056 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7057 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7058 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7060 /* Set crop settings here */
7061 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7062 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7063 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7064 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7065 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7067 /* Picture Filters */
7068 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7069 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7070 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7071 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7072 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7073 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7074 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7075 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7076 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7077 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7078 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7081 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7082 /* we actually call the methods for the nests here */
7083 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7085 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7086 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7087 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7088 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7089 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7090 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7091 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7092 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7093 [audioTrack1Array autorelease];
7094 [audioListArray addObject:audioTrack1Array];
7097 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7099 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7100 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7101 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7102 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7103 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7104 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7105 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7106 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7107 [audioTrack2Array autorelease];
7108 [audioListArray addObject:audioTrack2Array];
7111 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7113 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7114 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7115 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7116 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7117 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7118 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7119 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7120 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7121 [audioTrack3Array autorelease];
7122 [audioListArray addObject:audioTrack3Array];
7125 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7127 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7128 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7129 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7130 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7131 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7132 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7133 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7134 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7135 [audioTrack4Array autorelease];
7136 [audioListArray addObject:audioTrack4Array];
7140 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7143 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7144 * subititle array code. */
7146 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7147 /* Forced Subtitles */
7148 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7150 [preset autorelease];
7157 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7158 /* We get the default preset in case it changed */
7159 [self getDefaultPresets:nil];
7163 - (IBAction)deletePreset:(id)sender
7167 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7171 /* Alert user before deleting preset */
7173 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7175 if ( status == NSAlertDefaultReturn )
7177 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7178 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7179 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7181 NSEnumerator *enumerator;
7182 NSMutableArray *presetsArrayToMod;
7183 NSMutableArray *tempArray;
7185 /* If we are a root level preset, we are modding the UserPresets array */
7186 if (presetToModLevel == 0)
7188 presetsArrayToMod = UserPresets;
7190 else // We have a parent preset, so we modify the chidren array object for key
7192 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7195 enumerator = [presetsArrayToMod objectEnumerator];
7196 tempArray = [NSMutableArray array];
7198 while (tempObject = [enumerator nextObject])
7200 NSDictionary *thisPresetDict = tempObject;
7201 if (thisPresetDict == presetToMod)
7203 [tempArray addObject:tempObject];
7207 [presetsArrayToMod removeObjectsInArray:tempArray];
7208 [fPresetsOutlineView reloadData];
7215 #pragma mark Import Export Preset(s)
7217 - (IBAction) browseExportPresetFile: (id) sender
7219 /* Open a panel to let the user choose where and how to save the export file */
7220 NSSavePanel * panel = [NSSavePanel savePanel];
7221 /* We get the current file name and path from the destination field here */
7222 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7224 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7225 modalForWindow: fWindow modalDelegate: self
7226 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7230 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7231 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7233 if( returnCode == NSOKButton )
7235 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7236 NSString *exportPresetsFile = [sheet filename];
7237 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7238 /* We check for the presets.plist */
7239 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7241 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7243 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7244 if (nil == presetsToExport)
7246 presetsToExport = [[NSMutableArray alloc] init];
7248 /* now get and add selected presets to export */
7251 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7253 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7254 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7262 - (IBAction) browseImportPresetFile: (id) sender
7265 NSOpenPanel * panel;
7267 panel = [NSOpenPanel openPanel];
7268 [panel setAllowsMultipleSelection: NO];
7269 [panel setCanChooseFiles: YES];
7270 [panel setCanChooseDirectories: NO ];
7271 NSString * sourceDirectory;
7272 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7274 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7278 sourceDirectory = @"~/Desktop";
7279 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7281 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7282 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7284 /* set this for allowed file types, not sure if we should allow xml or not */
7285 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7286 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7287 modalForWindow: fWindow modalDelegate: self
7288 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7289 contextInfo: sender];
7292 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7293 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7295 if( returnCode == NSOKButton )
7297 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7298 NSString *importPresetsFile = [sheet filename];
7299 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7300 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7301 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7302 /* iterate though the new array of presets to import and add them to our presets array */
7304 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7306 while (tempObject = [enumerator nextObject])
7308 /* make any changes to the incoming preset we see fit */
7309 /* make sure the incoming preset is not tagged as default */
7310 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7311 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7312 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7313 [tempObject setObject:prependedName forKey:@"PresetName"];
7315 /* actually add the new preset to our presets array */
7316 [UserPresets addObject:tempObject];
7319 [presetsToImport autorelease];
7327 #pragma mark Manage Default Preset
7329 - (IBAction)getDefaultPresets:(id)sender
7331 presetHbDefault = nil;
7332 presetUserDefault = nil;
7333 presetUserDefaultParent = nil;
7334 presetUserDefaultParentParent = nil;
7335 NSMutableDictionary *presetHbDefaultParent = nil;
7336 NSMutableDictionary *presetHbDefaultParentParent = nil;
7339 BOOL userDefaultFound = NO;
7340 presetCurrentBuiltInCount = 0;
7341 /* First we iterate through the root UserPresets array to check for defaults */
7342 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7344 while (tempObject = [enumerator nextObject])
7346 NSMutableDictionary *thisPresetDict = tempObject;
7347 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7349 presetHbDefault = thisPresetDict;
7351 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7353 presetUserDefault = thisPresetDict;
7354 userDefaultFound = YES;
7356 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7358 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7362 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7363 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7365 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7366 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7368 while (tempObject = [enumerator nextObject])
7370 NSMutableDictionary *thisPresetDict = tempObject;
7371 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7373 presetHbDefault = thisPresetDict;
7374 presetHbDefaultParent = thisPresetDictParent;
7376 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7378 presetUserDefault = thisPresetDict;
7379 presetUserDefaultParent = thisPresetDictParent;
7380 userDefaultFound = YES;
7383 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7384 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7386 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7387 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7389 while (tempObject = [enumerator nextObject])
7391 NSMutableDictionary *thisPresetDict = tempObject;
7392 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7394 presetHbDefault = thisPresetDict;
7395 presetHbDefaultParent = thisPresetDictParent;
7396 presetHbDefaultParentParent = thisPresetDictParentParent;
7398 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7400 presetUserDefault = thisPresetDict;
7401 presetUserDefaultParent = thisPresetDictParent;
7402 presetUserDefaultParentParent = thisPresetDictParentParent;
7403 userDefaultFound = YES;
7412 /* check to see if a user specified preset was found, if not then assign the parents for
7413 * the presetHbDefault so that we can open the parents for the nested presets
7415 if (userDefaultFound == NO)
7417 presetUserDefaultParent = presetHbDefaultParent;
7418 presetUserDefaultParentParent = presetHbDefaultParentParent;
7422 - (IBAction)setDefaultPreset:(id)sender
7424 /* We need to determine if the item is a folder */
7425 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7431 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7433 /* First make sure the old user specified default preset is removed */
7434 while (tempObject = [enumerator nextObject])
7436 NSMutableDictionary *thisPresetDict = tempObject;
7437 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7439 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7442 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7443 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7445 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7448 while (tempObject = [enumerator nextObject])
7450 NSMutableDictionary *thisPresetDict1 = tempObject;
7451 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7453 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7455 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7456 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7458 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7461 while (tempObject = [enumerator nextObject])
7463 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7465 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7478 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7479 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7480 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7483 NSMutableArray *presetsArrayToMod;
7484 NSMutableArray *tempArray;
7486 /* If we are a root level preset, we are modding the UserPresets array */
7487 if (presetToModLevel == 0)
7489 presetsArrayToMod = UserPresets;
7491 else // We have a parent preset, so we modify the chidren array object for key
7493 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7496 enumerator = [presetsArrayToMod objectEnumerator];
7497 tempArray = [NSMutableArray array];
7499 while (tempObject = [enumerator nextObject])
7501 NSDictionary *thisPresetDict = tempObject;
7502 if (thisPresetDict == presetToMod)
7504 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7506 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7513 /* We save all of the preset data here */
7515 /* We Reload the New Table data for presets */
7516 [fPresetsOutlineView reloadData];
7519 - (IBAction)selectDefaultPreset:(id)sender
7521 NSMutableDictionary *presetToMod;
7522 /* if there is a user specified default, we use it */
7523 if (presetUserDefault)
7525 presetToMod = presetUserDefault;
7527 else if (presetHbDefault) //else we use the built in default presetHbDefault
7529 presetToMod = presetHbDefault;
7536 if (presetUserDefaultParent != nil)
7538 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7541 if (presetUserDefaultParentParent != nil)
7543 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7547 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7548 [self selectPreset:nil];
7553 #pragma mark Manage Built In Presets
7556 - (IBAction)deleteFactoryPresets:(id)sender
7559 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7563 NSMutableArray *tempArray;
7566 tempArray = [NSMutableArray array];
7567 /* we look here to see if the preset is we move on to the next one */
7568 while ( tempObject = [enumerator nextObject] )
7570 /* if the preset is "Factory" then we put it in the array of
7571 presets to delete */
7572 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7574 [tempArray addObject:tempObject];
7578 [UserPresets removeObjectsInArray:tempArray];
7579 [fPresetsOutlineView reloadData];
7584 /* We use this method to recreate new, updated factory presets */
7585 - (IBAction)addFactoryPresets:(id)sender
7588 /* First, we delete any existing built in presets */
7589 [self deleteFactoryPresets: sender];
7590 /* Then we generate new built in presets programmatically with fPresetsBuiltin
7591 * which is all setup in HBPresets.h and HBPresets.m*/
7592 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
7593 /* update build number for built in presets */
7594 /* iterate though the new array of presets to import and add them to our presets array */
7596 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7598 while (tempObject = [enumerator nextObject])
7600 /* Record the apps current build number in the PresetBuildNumber key */
7601 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7603 /* Preset build number */
7604 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7608 /* report the built in preset updating to the activity log */
7609 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
7619 /*******************************
7620 * Subclass of the HBPresetsOutlineView *
7621 *******************************/
7623 @implementation HBPresetsOutlineView
7624 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
7628 // By default, NSTableView only drags an image of the first column. Change this to
7629 // drag an image of the queue's icon and PresetName columns.
7630 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
7631 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
7636 - (void) mouseDown:(NSEvent *)theEvent
7638 [super mouseDown:theEvent];
7644 - (BOOL) isDragging;