1 /* $Id: Controller.mm,v 1.79 2005/11/04 19:41:32 titer Exp $
3 This file is part of the HandBrake source code.
4 Homepage: <http://handbrake.fr/>.
5 It may be used under the terms of the GNU General Public License. */
8 #import "HBOutputPanelController.h"
9 #import "HBPreferencesController.h"
10 #import "HBDVDDetector.h"
12 #import "HBPreviewController.h"
14 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
16 /* We setup the toolbar values here ShowPreviewIdentifier */
17 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
18 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
19 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
20 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
21 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
22 static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
23 static NSString * ShowPreviewIdentifier = @"Show Preview Window Item Identifier";
24 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
25 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
28 /*******************************
29 * HBController implementation *
30 *******************************/
31 @implementation HBController
41 /* replace bundled app icon with one which is 32/64-bit savvy */
42 #if defined( __LP64__ )
43 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
45 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
47 if( fApplicationIcon != nil )
48 [NSApp setApplicationIconImage:fApplicationIcon];
50 [HBPreferencesController registerUserDefaults];
52 fQueueEncodeLibhb = NULL;
53 /* Check for check for the app support directory here as
54 * outputPanel needs it right away, as may other future methods
56 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
58 YES ) objectAtIndex:0];
59 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
60 stringByAppendingPathComponent:@"HandBrake"];
61 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
63 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
66 /* Check for and create the App Support Preview directory if necessary */
67 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
68 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
70 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
73 outputPanel = [[HBOutputPanelController alloc] init];
74 fPictureController = [[PictureController alloc] init];
75 fQueueController = [[HBQueueController alloc] init];
76 fAdvancedOptions = [[HBAdvancedController alloc] init];
77 /* we init the HBPresets class which currently is only used
78 * for updating built in presets, may move more functionality
81 fPresetsBuiltin = [[HBPresets alloc] init];
82 fPreferencesController = [[HBPreferencesController alloc] init];
83 /* Lets report the HandBrake version number here to the activity log and text log file */
84 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
85 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
91 - (void) applicationDidFinishLaunching: (NSNotification *) notification
93 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
94 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
95 fHandle = hb_init(loggingLevel, 0);
96 /* Optional dvd nav UseDvdNav*/
97 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
98 /* Init a separate instance of libhb for user scanning and setting up jobs */
99 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
101 // Set the Growl Delegate
102 [GrowlApplicationBridge setGrowlDelegate: self];
103 /* Init others controllers */
104 [fPictureController SetHandle: fHandle];
105 [fPictureController setHBController: self];
107 [fQueueController setHandle: fQueueEncodeLibhb];
108 [fQueueController setHBController: self];
110 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
111 [fChapterTable setDataSource:fChapterTitlesDelegate];
112 [fChapterTable setDelegate:fChapterTitlesDelegate];
114 /* setup the subtitles delegate and connections to table */
115 fSubtitlesDelegate = [[HBSubtitles alloc] init];
116 [fSubtitlesTable setDataSource:fSubtitlesDelegate];
117 [fSubtitlesTable setDelegate:fSubtitlesDelegate];
118 [fSubtitlesTable setRowHeight:25.0];
120 [fPresetsOutlineView setAutosaveName:@"Presets View"];
121 [fPresetsOutlineView setAutosaveExpandedItems:YES];
123 dockIconProgress = 0;
125 /* Call UpdateUI every 1/2 sec */
126 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
127 scheduledTimerWithTimeInterval:0.5 target:self
128 selector:@selector(updateUI:) userInfo:nil repeats:YES]
129 forMode:NSDefaultRunLoopMode];
131 // Open debug output window now if it was visible when HB was closed
132 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
133 [self showDebugOutputPanel:nil];
135 // Open queue window now if it was visible when HB was closed
136 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
137 [self showQueueWindow:nil];
139 [self openMainWindow:nil];
141 /* We have to set the bool to tell hb what to do after a scan
142 * Initially we set it to NO until we start processing the queue
144 applyQueueToScan = NO;
146 /* Now we re-check the queue array to see if there are
147 * any remaining encodes to be done in it and ask the
148 * user if they want to reload the queue */
149 if ([QueueFileArray count] > 0)
151 /* run getQueueStats to see whats in the queue file */
152 [self getQueueStats];
153 /* this results in these values
154 * fEncodingQueueItem = 0;
156 * fCompletedCount = 0;
157 * fCanceledCount = 0;
161 /*On Screen Notification*/
162 NSString * alertTitle;
164 /* We check to see if there is already another instance of hb running.
165 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
167 if ([self hbInstances] > 1)
169 alertTitle = [NSString stringWithFormat:
170 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
171 NSBeginCriticalAlertSheet(
173 NSLocalizedString(@"Reload Queue", nil),
177 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
178 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
182 if (fWorkingCount > 0)
184 alertTitle = [NSString stringWithFormat:
185 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
186 fWorkingCount,fPendingCount];
190 alertTitle = [NSString stringWithFormat:
191 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
195 NSBeginCriticalAlertSheet(
197 NSLocalizedString(@"Reload Queue", nil),
199 NSLocalizedString(@"Empty Queue", nil),
201 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
202 NSLocalizedString(@" Do you want to reload them ?", nil));
208 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
209 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
211 [self browseSources:nil];
214 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
216 [self browseSources:(id)fOpenSourceTitleMMenu];
223 /* check to see if another instance of HandBrake.app is running */
224 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
225 NSDictionary *aDictionary;
227 for (aDictionary in runningAppDictionaries)
229 if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
237 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
239 if (returnCode == NSAlertOtherReturn)
241 [self clearQueueAllItems];
242 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
243 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
245 [self browseSources:nil];
248 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
250 [self browseSources:(id)fOpenSourceTitleMMenu];
255 if ([self hbInstances] == 1)
257 [self setQueueEncodingItemsAsPending];
259 [self showQueueWindow:NULL];
263 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
265 /* if we are in preview full screen mode, we need to go to
266 * windowed mode and release the display before we terminate.
267 * We do it here (instead of applicationWillTerminate) so we
268 * release the displays and can then see the alerts below.
270 if ([fPictureController previewFullScreenMode] == YES)
272 [fPictureController previewGoWindowed:nil];
276 hb_get_state( fQueueEncodeLibhb, &s );
278 if ( s.state != HB_STATE_IDLE )
280 int result = NSRunCriticalAlertPanel(
281 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
282 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
283 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
285 if (result == NSAlertDefaultReturn)
287 return NSTerminateNow;
290 return NSTerminateCancel;
293 // Warn if items still in the queue
294 else if ( fPendingCount > 0 )
296 int result = NSRunCriticalAlertPanel(
297 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
298 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
299 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
301 if ( result == NSAlertDefaultReturn )
302 return NSTerminateNow;
304 return NSTerminateCancel;
307 return NSTerminateNow;
310 - (void)applicationWillTerminate:(NSNotification *)aNotification
313 [browsedSourceDisplayName release];
314 [outputPanel release];
315 [fQueueController release];
316 [fPreviewController release];
317 [fPictureController release];
318 [fApplicationIcon release];
321 hb_close(&fQueueEncodeLibhb);
325 - (void) awakeFromNib
328 [fWindow setExcludedFromWindowsMenu:YES];
329 [fAdvancedOptions setView:fAdvancedView];
331 /* lets setup our presets drawer for drag and drop here */
332 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
333 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
334 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
336 /* Initialize currentScanCount so HB can use it to
337 evaluate successive scans */
338 currentScanCount = 0;
341 /* Init UserPresets .plist */
344 /* Init QueueFile .plist */
345 [self loadQueueFile];
347 fRipIndicatorShown = NO; // initially out of view in the nib
349 /* For 64 bit builds, the threaded animation in the progress
350 * indicators conflicts with the animation in the advanced tab
351 * for reasons not completely clear. jbrjake found a note in the
352 * 10.5 dev notes regarding this possiblility. It was also noted
353 * that unless specified, setUsesThreadedAnimation defaults to true.
354 * So, at least for now we set the indicator animation to NO for
355 * both the scan and regular progress indicators for both 32 and 64 bit
356 * as it test out fine on both and there is no reason our progress indicators
357 * should require their own thread.
360 [fScanIndicator setUsesThreadedAnimation:NO];
361 [fRipIndicator setUsesThreadedAnimation:NO];
365 /* Show/Dont Show Presets drawer upon launch based
366 on user preference DefaultPresetsDrawerShow*/
367 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
369 [fPresetDrawer setDelegate:self];
370 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
371 stringForKey:@"Drawer Size"] );
372 if( drawerSize.width )
373 [fPresetDrawer setContentSize: drawerSize];
374 [fPresetDrawer open];
377 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
378 [fSrcAngleLabel setHidden:YES];
379 [fSrcAnglePopUp setHidden:YES];
381 /* Setup the start / stop popup */
382 [fEncodeStartStopPopUp removeAllItems];
383 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
384 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
385 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
386 /* Align the start / stop widgets with the chapter popups */
387 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
388 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
390 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
391 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
394 NSMenuItem *menuItem;
395 [fDstFormatPopUp removeAllItems];
397 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
398 [menuItem setTag: HB_MUX_MP4];
400 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
401 [menuItem setTag: HB_MUX_MKV];
403 [fDstFormatPopUp selectItemAtIndex: 0];
405 [self formatPopUpChanged:nil];
407 /* We enable the create chapters checkbox here since we are .mp4 */
408 [fCreateChapterMarkers setEnabled: YES];
409 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
411 [fCreateChapterMarkers setState: NSOnState];
417 [fDstFile2Field setStringValue: [NSString stringWithFormat:
418 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
421 [fVidEncoderPopUp removeAllItems];
422 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
426 [fVidTargetSizeField setIntValue: 700];
427 [fVidBitrateField setIntValue: 1000];
429 [fVidQualityMatrix selectCell: fVidBitrateCell];
430 [self videoMatrixChanged:nil];
432 /* Video framerate */
433 [fVidRatePopUp removeAllItems];
434 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
435 for( int i = 0; i < hb_video_rates_count; i++ )
437 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
439 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
440 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
442 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
444 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
445 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
447 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
449 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
450 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
454 [fVidRatePopUp addItemWithTitle:
455 [NSString stringWithUTF8String: hb_video_rates[i].string]];
458 [fVidRatePopUp selectItemAtIndex: 0];
460 /* Set Auto Crop to On at launch */
461 [fPictureController setAutoCrop:YES];
464 [fAudTrack1BitratePopUp removeAllItems];
465 for( int i = 0; i < hb_audio_bitrates_count; i++ )
467 [fAudTrack1BitratePopUp addItemWithTitle:
468 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
471 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
473 /* Audio samplerate */
474 [fAudTrack1RatePopUp removeAllItems];
475 for( int i = 0; i < hb_audio_rates_count; i++ )
477 [fAudTrack1RatePopUp addItemWithTitle:
478 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
480 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
483 [fStatusField setStringValue: @""];
488 /* We disable the Turbo 1st pass checkbox since we are not x264 */
489 [fVidTurboPassCheck setEnabled: NO];
490 [fVidTurboPassCheck setState: NSOffState];
493 /* lets get our default prefs here */
494 [self getDefaultPresets:nil];
495 /* lets initialize the current successful scancount here to 0 */
496 currentSuccessfulScanCount = 0;
501 - (void) enableUI: (bool) b
503 NSControl * controls[] =
504 { fSrcTitleField, fSrcTitlePopUp,
505 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
506 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
507 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
508 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
509 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
510 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
511 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
512 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
513 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
514 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
515 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
516 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
517 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
518 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
519 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
520 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
521 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
522 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,fSrcFrameEndEncodingField};
525 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
527 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
529 NSTextField * tf = (NSTextField *) controls[i];
530 if( ![tf isBezeled] )
532 [tf setTextColor: b ? [NSColor controlTextColor] :
533 [NSColor disabledControlTextColor]];
537 [controls[i] setEnabled: b];
543 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
544 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
545 [self setEnabledStateOfAudioMixdownControls:nil];
546 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
547 [self calculatePictureSizing:nil];
551 [fPresetsOutlineView setEnabled: NO];
555 [self videoMatrixChanged:nil];
556 [fAdvancedOptions enableUI:b];
560 /***********************************************************************
562 ***********************************************************************
563 * Shows a progression bar on the dock icon, filled according to
564 * 'progress' (0.0 <= progress <= 1.0).
565 * Called with progress < 0.0 or progress > 1.0, restores the original
567 **********************************************************************/
568 - (void) UpdateDockIcon: (float) progress
571 NSBitmapImageRep * bmp;
573 uint32_t black = htonl( 0x000000FF );
574 uint32_t red = htonl( 0xFF0000FF );
575 uint32_t white = htonl( 0xFFFFFFFF );
576 int row_start, row_end;
579 if( progress < 0.0 || progress > 1.0 )
581 [NSApp setApplicationIconImage: fApplicationIcon];
585 /* Get it in a raw bitmap form */
586 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
587 NSTIFFCompressionNone factor: 1.0];
588 bmp = [NSBitmapImageRep imageRepWithData: tiff];
590 /* Draw the progression bar */
591 /* It's pretty simple (ugly?) now, but I'm no designer */
593 row_start = 3 * (int) [bmp size].height / 4;
594 row_end = 7 * (int) [bmp size].height / 8;
596 for( i = row_start; i < row_start + 2; i++ )
598 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
599 for( j = 0; j < (int) [bmp size].width; j++ )
604 for( i = row_start + 2; i < row_end - 2; i++ )
606 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
609 for( j = 2; j < (int) [bmp size].width - 2; j++ )
611 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
623 for( i = row_end - 2; i < row_end; i++ )
625 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
626 for( j = 0; j < (int) [bmp size].width; j++ )
632 /* Now update the dock icon */
633 tiff = [bmp TIFFRepresentationUsingCompression:
634 NSTIFFCompressionNone factor: 1.0];
635 NSImage* icon = [[NSImage alloc] initWithData: tiff];
636 [NSApp setApplicationIconImage: icon];
640 - (void) updateUI: (NSTimer *) timer
643 /* Update UI for fHandle (user scanning instance of libhb ) */
646 list = hb_get_titles( fHandle );
647 /* check to see if there has been a new scan done
648 this bypasses the constraints of HB_STATE_WORKING
649 not allowing setting a newly scanned source */
650 int checkScanCount = hb_get_scancount( fHandle );
651 if( checkScanCount > currentScanCount )
653 currentScanCount = checkScanCount;
654 [fScanIndicator setIndeterminate: NO];
655 [fScanIndicator setDoubleValue: 0.0];
656 [fScanIndicator setHidden: YES];
657 [self showNewScan:nil];
661 hb_get_state( fHandle, &s );
667 #define p s.param.scanning
668 case HB_STATE_SCANNING:
670 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
671 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
672 p.title_cur, p.title_count]];
673 [fScanIndicator setHidden: NO];
674 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
679 #define p s.param.scandone
680 case HB_STATE_SCANDONE:
682 [fScanIndicator setIndeterminate: NO];
683 [fScanIndicator setDoubleValue: 0.0];
684 [fScanIndicator setHidden: YES];
685 [self writeToActivityLog:"ScanDone state received from fHandle"];
686 [self showNewScan:nil];
687 [[fWindow toolbar] validateVisibleItems];
693 #define p s.param.working
694 case HB_STATE_WORKING:
701 #define p s.param.muxing
702 case HB_STATE_MUXING:
709 case HB_STATE_PAUSED:
712 case HB_STATE_WORKDONE:
719 /* Update UI for fQueueEncodeLibhb */
721 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
722 /* check to see if there has been a new scan done
723 this bypasses the constraints of HB_STATE_WORKING
724 not allowing setting a newly scanned source */
726 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
727 if( checkScanCount > currentScanCount )
729 currentScanCount = checkScanCount;
733 hb_get_state( fQueueEncodeLibhb, &s );
739 #define p s.param.scanning
740 case HB_STATE_SCANNING:
742 [fStatusField setStringValue: [NSString stringWithFormat:
743 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
744 p.title_cur, p.title_count]];
746 /* Set the status string in fQueueController as well */
747 [fQueueController setQueueStatusString: [NSString stringWithFormat:
748 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
749 p.title_cur, p.title_count]];
754 #define p s.param.scandone
755 case HB_STATE_SCANDONE:
757 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
758 [self processNewQueueEncode];
759 [[fWindow toolbar] validateVisibleItems];
766 #define p s.param.working
768 case HB_STATE_SEARCHING:
770 NSMutableString * string;
771 NSString * pass_desc;
773 /* Update text field */
775 //string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
776 /* For now, do not announce "pass x of x for the search phase ... */
777 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
781 [string appendFormat:
782 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
785 [fStatusField setStringValue: string];
786 /* Set the status string in fQueueController as well */
787 [fQueueController setQueueStatusString: string];
789 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
790 [fRipIndicator setIndeterminate: NO];
791 [fRipIndicator setDoubleValue:100.0 * progress_total];
793 // If progress bar hasn't been revealed at the bottom of the window, do
794 // that now. This code used to be in doRip. I moved it to here to handle
795 // the case where hb_start is called by HBQueueController and not from
797 if( !fRipIndicatorShown )
799 NSRect frame = [fWindow frame];
800 if( frame.size.width <= 591 )
801 frame.size.width = 591;
802 frame.size.height += 36;
803 frame.origin.y -= 36;
804 [fWindow setFrame:frame display:YES animate:YES];
805 fRipIndicatorShown = YES;
809 /* Update dock icon */
810 /* Note not done yet */
815 case HB_STATE_WORKING:
817 NSMutableString * string;
818 NSString * pass_desc;
819 /* Update text field */
820 if (p.job_cur == 1 && p.job_count > 1)
822 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
824 pass_desc = @"(subtitle scan)";
836 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
840 [string appendFormat:
841 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
842 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
845 [fStatusField setStringValue: string];
846 /* Set the status string in fQueueController as well */
847 [fQueueController setQueueStatusString: string];
849 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
850 [fRipIndicator setIndeterminate: NO];
851 [fRipIndicator setDoubleValue:100.0 * progress_total];
853 // If progress bar hasn't been revealed at the bottom of the window, do
854 // that now. This code used to be in doRip. I moved it to here to handle
855 // the case where hb_start is called by HBQueueController and not from
857 if( !fRipIndicatorShown )
859 NSRect frame = [fWindow frame];
860 if( frame.size.width <= 591 )
861 frame.size.width = 591;
862 frame.size.height += 36;
863 frame.origin.y -= 36;
864 [fWindow setFrame:frame display:YES animate:YES];
865 fRipIndicatorShown = YES;
869 /* Update dock icon */
870 if( dockIconProgress < 100.0 * progress_total )
872 [self UpdateDockIcon: progress_total];
873 dockIconProgress += 5;
880 #define p s.param.muxing
881 case HB_STATE_MUXING:
883 /* Update text field */
884 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
885 /* Set the status string in fQueueController as well */
886 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
888 [fRipIndicator setIndeterminate: YES];
889 [fRipIndicator startAnimation: nil];
891 /* Update dock icon */
892 [self UpdateDockIcon: 1.0];
898 case HB_STATE_PAUSED:
899 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
900 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
904 case HB_STATE_WORKDONE:
906 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
907 // or someone calling hb_stop. In the latter case, hb_stop does not clear
908 // out the remaining passes/jobs in the queue. We'll do that here.
910 // Delete all remaining jobs of this encode.
911 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
912 /* Set the status string in fQueueController as well */
913 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
914 [fRipIndicator setIndeterminate: NO];
915 [fRipIndicator stopAnimation: nil];
916 [fRipIndicator setDoubleValue: 0.0];
917 [[fWindow toolbar] validateVisibleItems];
919 /* Restore dock icon */
920 [self UpdateDockIcon: -1.0];
921 dockIconProgress = 0;
923 if( fRipIndicatorShown )
925 NSRect frame = [fWindow frame];
926 if( frame.size.width <= 591 )
927 frame.size.width = 591;
928 frame.size.height += -36;
929 frame.origin.y -= -36;
930 [fWindow setFrame:frame display:YES animate:YES];
931 fRipIndicatorShown = NO;
933 /* Since we are done with this encode, tell output to stop writing to the
934 * individual encode log
936 [outputPanel endEncodeLog];
937 /* Check to see if the encode state has not been cancelled
938 to determine if we should check for encode done notifications */
939 if( fEncodeState != 2 )
941 NSString *pathOfFinishedEncode;
942 /* Get the output file name for the finished encode */
943 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
945 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
947 [self showGrowlDoneNotification:pathOfFinishedEncode];
949 [self sendToMetaX:pathOfFinishedEncode];
951 /* since we have successfully completed an encode, we increment the queue counter */
952 [self incrementQueueItemDone:nil];
954 /* all end of queue actions below need to be done after all queue encodes have finished
955 * and there are no pending jobs left to process
957 if (fPendingCount == 0)
959 /* If Alert Window or Window and Growl has been selected */
960 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
961 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
963 /*On Screen Notification*/
966 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
967 [NSApp requestUserAttention:NSCriticalRequest];
970 /* If sleep has been selected */
971 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
974 NSDictionary* errorDict;
975 NSAppleEventDescriptor* returnDescriptor = nil;
976 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
977 @"tell application \"Finder\" to sleep"];
978 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
979 [scriptObject release];
981 /* If Shutdown has been selected */
982 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
985 NSDictionary* errorDict;
986 NSAppleEventDescriptor* returnDescriptor = nil;
987 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
988 @"tell application \"Finder\" to shut down"];
989 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
990 [scriptObject release];
1004 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1005 - (void) writeToActivityLog:(const char *) format, ...
1008 va_start(args, format);
1012 vsnprintf( str, 1024, format, args );
1014 time_t _now = time( NULL );
1015 struct tm * now = localtime( &_now );
1016 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1022 #pragma mark Toolbar
1023 // ============================================================
1024 // NSToolbar Related Methods
1025 // ============================================================
1027 - (void) setupToolbar {
1028 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1030 [toolbar setAllowsUserCustomization: YES];
1031 [toolbar setAutosavesConfiguration: YES];
1032 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1034 [toolbar setDelegate: self];
1036 [fWindow setToolbar: toolbar];
1039 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1040 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1041 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1043 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1045 [item setLabel: @"Toggle Presets"];
1046 [item setPaletteLabel: @"Toggler Presets"];
1047 [item setToolTip: @"Open/Close Preset Drawer"];
1048 [item setImage: [NSImage imageNamed: @"Drawer"]];
1049 [item setTarget: self];
1050 [item setAction: @selector(toggleDrawer:)];
1051 [item setAutovalidates: NO];
1053 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1055 [item setLabel: @"Start"];
1056 [item setPaletteLabel: @"Start Encoding"];
1057 [item setToolTip: @"Start Encoding"];
1058 [item setImage: [NSImage imageNamed: @"Play"]];
1059 [item setTarget: self];
1060 [item setAction: @selector(Rip:)];
1062 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1064 [item setLabel: @"Show Queue"];
1065 [item setPaletteLabel: @"Show Queue"];
1066 [item setToolTip: @"Show Queue"];
1067 [item setImage: [NSImage imageNamed: @"Queue"]];
1068 [item setTarget: self];
1069 [item setAction: @selector(showQueueWindow:)];
1070 [item setAutovalidates: NO];
1072 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1074 [item setLabel: @"Add to Queue"];
1075 [item setPaletteLabel: @"Add to Queue"];
1076 [item setToolTip: @"Add to Queue"];
1077 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1078 [item setTarget: self];
1079 [item setAction: @selector(addToQueue:)];
1081 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1083 [item setLabel: @"Pause"];
1084 [item setPaletteLabel: @"Pause Encoding"];
1085 [item setToolTip: @"Pause Encoding"];
1086 [item setImage: [NSImage imageNamed: @"Pause"]];
1087 [item setTarget: self];
1088 [item setAction: @selector(Pause:)];
1090 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1092 [item setLabel: @"Picture Settings"];
1093 [item setPaletteLabel: @"Show Picture Settings"];
1094 [item setToolTip: @"Show Picture Settings"];
1095 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1096 [item setTarget: self];
1097 [item setAction: @selector(showPicturePanel:)];
1099 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1101 [item setLabel: @"Preview Window"];
1102 [item setPaletteLabel: @"Show Preview"];
1103 [item setToolTip: @"Show Preview"];
1104 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1105 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1106 [item setTarget: self];
1107 [item setAction: @selector(showPreviewWindow:)];
1109 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1111 [item setLabel: @"Activity Window"];
1112 [item setPaletteLabel: @"Show Activity Window"];
1113 [item setToolTip: @"Show Activity Window"];
1114 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1115 [item setTarget: self];
1116 [item setAction: @selector(showDebugOutputPanel:)];
1117 [item setAutovalidates: NO];
1119 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1121 [item setLabel: @"Source"];
1122 [item setPaletteLabel: @"Source"];
1123 [item setToolTip: @"Choose Video Source"];
1124 [item setImage: [NSImage imageNamed: @"Source"]];
1125 [item setTarget: self];
1126 [item setAction: @selector(browseSources:)];
1136 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1138 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1139 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1140 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1143 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1145 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1146 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1147 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1148 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1151 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1153 NSString * ident = [toolbarItem itemIdentifier];
1159 hb_get_state( fHandle, &s );
1160 if (s.state == HB_STATE_SCANNING)
1163 if ([ident isEqualToString: ChooseSourceIdentifier])
1165 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1166 [toolbarItem setLabel: @"Cancel Scan"];
1167 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1168 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1172 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1177 if ([ident isEqualToString: ChooseSourceIdentifier])
1179 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1180 [toolbarItem setLabel: @"Source"];
1181 [toolbarItem setPaletteLabel: @"Source"];
1182 [toolbarItem setToolTip: @"Choose Video Source"];
1187 hb_get_state2( fQueueEncodeLibhb, &s );
1189 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1191 if ([ident isEqualToString: StartEncodingIdentifier])
1193 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1194 [toolbarItem setLabel: @"Stop"];
1195 [toolbarItem setPaletteLabel: @"Stop"];
1196 [toolbarItem setToolTip: @"Stop Encoding"];
1199 if ([ident isEqualToString: PauseEncodingIdentifier])
1201 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1202 [toolbarItem setLabel: @"Pause"];
1203 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1204 [toolbarItem setToolTip: @"Pause Encoding"];
1209 if ([ident isEqualToString: AddToQueueIdentifier])
1211 if ([ident isEqualToString: ShowPictureIdentifier])
1213 if ([ident isEqualToString: ShowPreviewIdentifier])
1217 else if (s.state == HB_STATE_PAUSED)
1219 if ([ident isEqualToString: PauseEncodingIdentifier])
1221 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1222 [toolbarItem setLabel: @"Resume"];
1223 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1224 [toolbarItem setToolTip: @"Resume Encoding"];
1227 if ([ident isEqualToString: StartEncodingIdentifier])
1229 if ([ident isEqualToString: AddToQueueIdentifier])
1231 if ([ident isEqualToString: ShowPictureIdentifier])
1233 if ([ident isEqualToString: ShowPreviewIdentifier])
1236 else if (s.state == HB_STATE_SCANNING)
1238 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1240 if ([ident isEqualToString: StartEncodingIdentifier])
1242 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1243 if (hb_count(fHandle) > 0)
1244 [toolbarItem setLabel: @"Start Queue"];
1246 [toolbarItem setLabel: @"Start"];
1247 [toolbarItem setPaletteLabel: @"Start Encoding"];
1248 [toolbarItem setToolTip: @"Start Encoding"];
1251 if ([ident isEqualToString: AddToQueueIdentifier])
1253 if ([ident isEqualToString: ShowPictureIdentifier])
1255 if ([ident isEqualToString: ShowPreviewIdentifier])
1260 /* If there are any pending queue items, make sure the start/stop button is active */
1261 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1263 if ([ident isEqualToString: ShowQueueIdentifier])
1265 if ([ident isEqualToString: ToggleDrawerIdentifier])
1267 if ([ident isEqualToString: ChooseSourceIdentifier])
1269 if ([ident isEqualToString: ShowActivityIdentifier])
1275 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1277 SEL action = [menuItem action];
1280 hb_get_state2( fHandle, &s );
1284 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1285 return SuccessfulScan && [fWindow attachedSheet] == nil;
1287 if (action == @selector(browseSources:))
1289 if (s.state == HB_STATE_SCANNING)
1292 return [fWindow attachedSheet] == nil;
1294 if (action == @selector(selectDefaultPreset:))
1295 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1296 if (action == @selector(Pause:))
1298 if (s.state == HB_STATE_WORKING)
1300 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1301 [menuItem setTitle:@"Pause Encoding"];
1304 else if (s.state == HB_STATE_PAUSED)
1306 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1307 [menuItem setTitle:@"Resume Encoding"];
1313 if (action == @selector(Rip:))
1315 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1317 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1318 [menuItem setTitle:@"Stop Encoding"];
1321 else if (SuccessfulScan)
1323 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1324 [menuItem setTitle:@"Start Encoding"];
1325 return [fWindow attachedSheet] == nil;
1331 if( action == @selector(setDefaultPreset:) )
1333 return [fPresetsOutlineView selectedRow] != -1;
1340 #pragma mark Encode Done Actions
1341 // register a test notification and make
1342 // it enabled by default
1343 #define SERVICE_NAME @"Encode Done"
1344 - (NSDictionary *)registrationDictionaryForGrowl
1346 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1347 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1348 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1351 return registrationDictionary;
1354 -(void)showGrowlDoneNotification:(NSString *) filePath
1356 /* This end of encode action is called as each encode rolls off of the queue */
1357 NSString * finishedEncode = filePath;
1358 /* strip off the path to just show the file name */
1359 finishedEncode = [finishedEncode lastPathComponent];
1360 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1361 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1363 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1364 [GrowlApplicationBridge
1365 notifyWithTitle:@"Put down that cocktail..."
1366 description:growlMssg
1367 notificationName:SERVICE_NAME
1375 -(void)sendToMetaX:(NSString *) filePath
1377 /* This end of encode action is called as each encode rolls off of the queue */
1378 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1380 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1381 if (![sendToApp isEqualToString:@"None"])
1383 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1384 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1385 [myScript executeAndReturnError: nil];
1392 #pragma mark Get New Source
1394 /*Opens the source browse window, called from Open Source widgets */
1395 - (IBAction) browseSources: (id) sender
1399 hb_get_state( fHandle, &s );
1400 if (s.state == HB_STATE_SCANNING)
1402 [self cancelScanning:nil];
1407 NSOpenPanel * panel;
1409 panel = [NSOpenPanel openPanel];
1410 [panel setAllowsMultipleSelection: NO];
1411 [panel setCanChooseFiles: YES];
1412 [panel setCanChooseDirectories: YES ];
1413 NSString * sourceDirectory;
1414 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1416 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1420 sourceDirectory = @"~/Desktop";
1421 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1423 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1424 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1426 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1427 modalForWindow: fWindow modalDelegate: self
1428 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1429 contextInfo: sender];
1432 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1433 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1435 /* we convert the sender content of contextInfo back into a variable called sender
1436 * mostly just for consistency for evaluation later
1438 id sender = (id)contextInfo;
1439 /* User selected a file to open */
1440 if( returnCode == NSOKButton )
1442 /* Free display name allocated previously by this code */
1443 [browsedSourceDisplayName release];
1445 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1446 /* we set the last searched source directory in the prefs here */
1447 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1448 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1449 /* we order out sheet, which is the browse window as we need to open
1450 * the title selection sheet right away
1452 [sheet orderOut: self];
1454 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1456 /* We put the chosen source path in the source display text field for the
1457 * source title selection sheet in which the user specifies the specific title to be
1458 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1459 * purposes in the title panel
1462 [fScanSrcTitlePathField setStringValue:scanPath];
1463 NSString *displayTitlescanSourceName;
1465 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1467 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1468 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1469 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1473 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1474 displayTitlescanSourceName = [scanPath lastPathComponent];
1476 /* we set the source display name in the title selection dialogue */
1477 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1478 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1479 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1480 /* We show the actual sheet where the user specifies the title to be scanned
1481 * as we are going to do a title specific scan
1483 [self showSourceTitleScanPanel:nil];
1487 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1488 NSString *path = [[sheet filenames] objectAtIndex: 0];
1490 /* We check to see if the chosen file at path is a package */
1491 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1493 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1494 /* We check to see if this is an .eyetv package */
1495 if ([[path pathExtension] isEqualToString: @"eyetv"])
1497 [self writeToActivityLog:"trying to open eyetv package"];
1498 /* We're looking at an EyeTV package - try to open its enclosed
1500 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1502 int n = [[path stringByAppendingString: @"/"]
1503 completePathIntoString: &mpgname caseSensitive: YES
1504 matchesIntoArray: nil
1505 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1508 /* Found an mpeg inside the eyetv package, make it our scan path
1509 and call performScan on the enclosed mpeg */
1511 [self writeToActivityLog:"found mpeg in eyetv package"];
1512 [self performScan:path scanTitleNum:0];
1516 /* We did not find an mpeg file in our package, so we do not call performScan */
1517 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1520 /* We check to see if this is a .dvdmedia package */
1521 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1523 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1524 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1525 [self writeToActivityLog:"trying to open dvdmedia package"];
1526 [self performScan:path scanTitleNum:0];
1530 /* The package is not an eyetv package, so we do not call performScan */
1531 [self writeToActivityLog:"unable to open package"];
1534 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1536 /* path is not a package, so we call perform scan directly on our file */
1537 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1539 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1540 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1541 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1545 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1546 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1547 /* make sure we remove any path extension as this can also be an '.mpg' file */
1548 browsedSourceDisplayName = [[path lastPathComponent] retain];
1550 applyQueueToScan = NO;
1551 [self performScan:path scanTitleNum:0];
1559 - (IBAction)showAboutPanel:(id)sender
1561 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1562 fApplicationIcon, @"ApplicationIcon",
1564 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1568 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1569 - (IBAction) showSourceTitleScanPanel: (id) sender
1571 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1574 [fScanSrcTitleNumField setStringValue: @"0"];
1575 /* Show the panel */
1576 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1579 - (IBAction) closeSourceTitleScanPanel: (id) sender
1581 [NSApp endSheet: fScanSrcTitlePanel];
1582 [fScanSrcTitlePanel orderOut: self];
1584 if(sender == fScanSrcTitleOpenButton)
1586 /* We setup the scan status in the main window to indicate a source title scan */
1587 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1588 [fScanIndicator setHidden: NO];
1589 [fScanIndicator setIndeterminate: YES];
1590 [fScanIndicator startAnimation: nil];
1592 /* We use the performScan method to actually perform the specified scan passing the path and the title
1595 applyQueueToScan = NO;
1596 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1600 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1601 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1604 /* use a bool to determine whether or not we can decrypt using vlc */
1605 BOOL cancelScanDecrypt = 0;
1607 NSString *path = scanPath;
1608 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1610 // Notify ChapterTitles that there's no title
1611 [fChapterTitlesDelegate resetWithTitle:nil];
1612 [fChapterTable reloadData];
1614 // Notify Subtitles that there's no title
1615 [fSubtitlesDelegate resetWithTitle:nil];
1616 [fSubtitlesTable reloadData];
1618 [self enableUI: NO];
1620 if( [detector isVideoDVD] )
1623 #if defined( __LP64__ )
1632 // The chosen path was actually on a DVD, so use the raw block
1633 // device path instead.
1634 path = [detector devicePath];
1635 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1637 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1638 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1639 NSFileManager * fileManager = [NSFileManager defaultManager];
1640 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1642 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1643 cancelScanDecrypt = 1;
1644 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1646 status = NSRunAlertPanel(@"HandBrake could not find VLC or your VLC is out of date.",@"Please download and install VLC media player in your /Applications folder if you wish to read encrypted DVDs.", @"Get VLC", @"Cancel Scan", @"Attempt Scan Anyway");
1647 [NSApp requestUserAttention:NSCriticalRequest];
1649 if (status == NSAlertDefaultReturn)
1651 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1652 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1654 else if (status == NSAlertAlternateReturn)
1656 /* User chose to cancel the scan */
1657 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1661 /* User chose to override our warning and scan the physical dvd anyway, at their own peril. on an encrypted dvd this produces massive log files and fails */
1662 cancelScanDecrypt = 0;
1663 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1669 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1670 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1673 /* test for architecture of the vlc app */
1674 NSArray *vlc_architecturesArray = [[NSBundle bundleWithPath:@"/Applications/VLC.app"] executableArchitectures];
1675 BOOL vlcIntel32bit = NO;
1676 BOOL vlcIntel64bit = NO;
1677 BOOL vlcPPC32bit = NO;
1678 BOOL vlcPPC64bit = NO;
1679 /* check the available architectures for vlc and note accordingly */
1680 NSEnumerator *enumerator = [vlc_architecturesArray objectEnumerator];
1682 while (tempObject = [enumerator nextObject])
1685 if ([tempObject intValue] == NSBundleExecutableArchitectureI386)
1687 vlcIntel32bit = YES;
1689 if ([tempObject intValue] == NSBundleExecutableArchitectureX86_64)
1691 vlcIntel64bit = YES;
1693 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC)
1697 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC64)
1703 /* Write vlc architecture findings to activity window */
1706 [self writeToActivityLog: " 32-Bit VLC app found for decrypting physical dvd"];
1710 [self writeToActivityLog: " 64-Bit VLC app found for decrypting physical dvd"];
1715 if (vlcFound && hb_arch == 64 && !vlcIntel64bit && cancelScanDecrypt != 1)
1720 /* Appropriate VLC not found, so cancel */
1721 cancelScanDecrypt = 1;
1722 [self writeToActivityLog: "This version of HandBrake is 64 bit, 64 bit version of vlc not found, scan cancelled"];
1723 /*On Screen Notification*/
1726 status = NSRunAlertPanel(@"This version of HandBrake is 64 bit, VLC found but not 64 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 64 bit VLC", nil);
1727 [NSApp requestUserAttention:NSCriticalRequest];
1729 if (status == NSAlertDefaultReturn)
1731 /* User chose to cancel the scan */
1732 [self writeToActivityLog: "cannot open physical dvd VLC found but not 64 bit, scan cancelled"];
1733 cancelScanDecrypt = 1;
1735 else if (status == NSAlertAlternateReturn)
1737 [self writeToActivityLog: "user overrode 64-bit warning trying to open physical dvd without proper decryption"];
1738 cancelScanDecrypt = 0;
1742 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1743 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1747 else if (vlcFound && hb_arch == 32 && !vlcIntel32bit && cancelScanDecrypt != 1)
1750 /* Appropriate VLC not found, so cancel */
1751 cancelScanDecrypt = 1;
1752 [self writeToActivityLog: "This version of HandBrake is 32 bit, 32 bit version of vlc not found, scan cancelled"];
1753 /*On Screen Notification*/
1756 status = NSRunAlertPanel(@"This version of HandBrake is 32 bit, VLC found but not 32 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 32 bit VLC", nil);
1757 [NSApp requestUserAttention:NSCriticalRequest];
1759 if (status == NSAlertDefaultReturn)
1761 /* User chose to cancel the scan */
1762 [self writeToActivityLog: "cannot open physical dvd VLC found but not 32 bit, scan cancelled"];
1763 cancelScanDecrypt = 1;
1765 else if (status == NSAlertAlternateReturn)
1767 [self writeToActivityLog: "user overrode 32-bit warning trying to open physical dvd without proper decryption"];
1768 cancelScanDecrypt = 0;
1772 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1773 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1779 if (cancelScanDecrypt == 0)
1781 /* we actually pass the scan off to libhb here */
1782 /* If there is no title number passed to scan, we use "0"
1783 * which causes the default behavior of a full source scan
1789 if (scanTitleNum > 0)
1791 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1793 /* We use our advance pref to determine how many previews to scan */
1794 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1795 /* set title to NULL */
1797 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1798 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1802 - (IBAction) cancelScanning:(id)sender
1804 hb_scan_stop(fHandle);
1807 - (IBAction) showNewScan:(id)sender
1811 int indxpri=0; // Used to search the longuest title (default in combobox)
1812 int longuestpri=0; // Used to search the longuest title (default in combobox)
1815 list = hb_get_titles( fHandle );
1817 if( !hb_list_count( list ) )
1819 /* We display a message if a valid dvd source was not chosen */
1820 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1821 SuccessfulScan = NO;
1823 // Notify ChapterTitles that there's no title
1824 [fSubtitlesDelegate resetWithTitle:nil];
1825 [fSubtitlesTable reloadData];
1827 // Notify Subtitles that there's no title
1828 [fChapterTitlesDelegate resetWithTitle:nil];
1829 [fChapterTable reloadData];
1833 if (applyQueueToScan == YES)
1835 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1836 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1839 else if (applyQueueToScan == NO)
1841 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1845 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1848 /* We increment the successful scancount here by one,
1849 which we use at the end of this function to tell the gui
1850 if this is the first successful scan since launch and whether
1851 or not we should set all settings to the defaults */
1852 currentSuccessfulScanCount++;
1854 [[fWindow toolbar] validateVisibleItems];
1856 [fSrcTitlePopUp removeAllItems];
1857 for( int i = 0; i < hb_list_count( list ); i++ )
1859 title = (hb_title_t *) hb_list_item( list, i );
1861 currentSource = [NSString stringWithUTF8String: title->name];
1862 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1863 if (!browsedSourceDisplayName)
1865 browsedSourceDisplayName = @"NoNameDetected";
1867 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1869 /* If its a queue rescan for edit, get the queue item output path */
1870 /* if not, its a new source scan. */
1871 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1872 if (applyQueueToScan == YES)
1874 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1876 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1878 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1879 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1883 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1884 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1888 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1890 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1894 [fSrcTitlePopUp addItemWithTitle: [NSString
1895 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1896 title->name,title->index, title->hours, title->minutes,
1900 /* if we are a stream, select the first title */
1901 if (title->type == HB_STREAM_TYPE)
1903 [fSrcTitlePopUp selectItemAtIndex: 0];
1907 /* if not then select the longest title (dvd) */
1908 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1910 [self titlePopUpChanged:nil];
1912 SuccessfulScan = YES;
1913 [self enableUI: YES];
1915 /* if its the initial successful scan after awakeFromNib */
1916 if (currentSuccessfulScanCount == 1)
1918 [self encodeStartStopPopUpChanged:nil];
1920 [self selectDefaultPreset:nil];
1922 // Open preview window now if it was visible when HB was closed
1923 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1924 [self showPreviewWindow:nil];
1926 // Open picture sizing window now if it was visible when HB was closed
1927 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1928 [self showPicturePanel:nil];
1931 if (applyQueueToScan == YES)
1933 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1934 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1935 [self applyQueueSettingsToMainWindow:nil];
1946 #pragma mark New Output Destination
1948 - (IBAction) browseFile: (id) sender
1950 /* Open a panel to let the user choose and update the text field */
1951 NSSavePanel * panel = [NSSavePanel savePanel];
1952 /* We get the current file name and path from the destination field here */
1953 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1954 modalForWindow: fWindow modalDelegate: self
1955 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1959 - (void) browseFileDone: (NSSavePanel *) sheet
1960 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1962 if( returnCode == NSOKButton )
1964 [fDstFile2Field setStringValue: [sheet filename]];
1965 /* Save this path to the prefs so that on next browse destination window it opens there */
1966 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1967 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1973 #pragma mark Main Window Control
1975 - (IBAction) openMainWindow: (id) sender
1977 [fWindow makeKeyAndOrderFront:nil];
1980 - (BOOL) windowShouldClose: (id) sender
1985 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1988 [fWindow makeKeyAndOrderFront:nil];
1996 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1997 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
2002 #pragma mark Queue File
2004 - (void) loadQueueFile {
2005 /* We declare the default NSFileManager into fileManager */
2006 NSFileManager * fileManager = [NSFileManager defaultManager];
2007 /*We define the location of the user presets file */
2008 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
2009 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
2010 /* We check for the presets.plist */
2011 if ([fileManager fileExistsAtPath:QueueFile] == 0)
2013 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
2016 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
2017 /* lets check to see if there is anything in the queue file .plist */
2018 if (nil == QueueFileArray)
2020 /* if not, then lets initialize an empty array */
2021 QueueFileArray = [[NSMutableArray alloc] init];
2023 /* Initialize our curQueueEncodeIndex to 0
2024 * so we can use it to track which queue
2025 * item is to be used to track our encodes */
2026 /* NOTE: this should be changed if and when we
2027 * are able to get the last unfinished encode
2028 * in the case of a crash or shutdown */
2033 [self clearQueueEncodedItems];
2035 currentQueueEncodeIndex = 0;
2038 - (void)addQueueFileItem
2040 [QueueFileArray addObject:[self createQueueFileItem]];
2041 [self saveQueueFileItem];
2045 - (void) removeQueueFileItem:(int) queueItemToRemove
2048 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
2049 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
2051 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
2052 * by one to keep in sync with the queue array
2054 currentQueueEncodeIndex--;
2055 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
2057 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2058 [self saveQueueFileItem];
2062 - (void)saveQueueFileItem
2064 [QueueFileArray writeToFile:QueueFile atomically:YES];
2065 [fQueueController setQueueArray: QueueFileArray];
2066 [self getQueueStats];
2069 - (void)getQueueStats
2071 /* lets get the stats on the status of the queue array */
2073 fEncodingQueueItem = 0;
2075 fCompletedCount = 0;
2079 /* We use a number system to set the encode status of the queue item
2081 * 0 == already encoded
2082 * 1 == is being encoded
2083 * 2 == is yet to be encoded
2088 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2090 while (tempObject = [enumerator nextObject])
2092 NSDictionary *thisQueueDict = tempObject;
2093 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2097 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2100 fEncodingQueueItem = i;
2102 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2106 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2113 /* Set the queue status field in the main window */
2114 NSMutableString * string;
2115 if (fPendingCount == 1)
2117 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2121 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2123 [fQueueStatus setStringValue:string];
2126 /* This method will set any item marked as encoding back to pending
2127 * currently used right after a queue reload
2129 - (void) setQueueEncodingItemsAsPending
2131 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2133 NSMutableArray *tempArray;
2134 tempArray = [NSMutableArray array];
2135 /* we look here to see if the preset is we move on to the next one */
2136 while ( tempObject = [enumerator nextObject] )
2138 /* If the queue item is marked as "encoding" (1)
2139 * then change its status back to pending (2) which effectively
2140 * puts it back into the queue to be encoded
2142 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2144 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2146 [tempArray addObject:tempObject];
2149 [QueueFileArray setArray:tempArray];
2150 [self saveQueueFileItem];
2154 /* This method will clear the queue of any encodes that are not still pending
2155 * this includes both successfully completed encodes as well as cancelled encodes */
2156 - (void) clearQueueEncodedItems
2158 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2160 NSMutableArray *tempArray;
2161 tempArray = [NSMutableArray array];
2162 /* we look here to see if the preset is we move on to the next one */
2163 while ( tempObject = [enumerator nextObject] )
2165 /* If the queue item is either completed (0) or cancelled (3) from the
2166 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2167 * NOTE: this means we retain pending (2) and also an item that is marked as
2168 * still encoding (1). If the queue has an item that is still marked as encoding
2169 * from a previous session, we can conlude that HB was either shutdown, or crashed
2170 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2172 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2174 [tempArray addObject:tempObject];
2178 [QueueFileArray removeObjectsInArray:tempArray];
2179 [self saveQueueFileItem];
2182 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2183 - (void) clearQueueAllItems
2185 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2187 NSMutableArray *tempArray;
2188 tempArray = [NSMutableArray array];
2189 /* we look here to see if the preset is we move on to the next one */
2190 while ( tempObject = [enumerator nextObject] )
2192 [tempArray addObject:tempObject];
2195 [QueueFileArray removeObjectsInArray:tempArray];
2196 [self saveQueueFileItem];
2199 /* This method will duplicate prepareJob however into the
2200 * queue .plist instead of into the job structure so it can
2201 * be recalled later */
2202 - (NSDictionary *)createQueueFileItem
2204 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2206 hb_list_t * list = hb_get_titles( fHandle );
2207 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2208 [fSrcTitlePopUp indexOfSelectedItem] );
2209 hb_job_t * job = title->job;
2213 /* We use a number system to set the encode status of the queue item
2214 * 0 == already encoded
2215 * 1 == is being encoded
2216 * 2 == is yet to be encoded
2219 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2220 /* Source and Destination Information */
2222 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2223 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2224 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2225 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2227 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2228 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2230 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2232 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2234 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2236 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2238 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2240 /* Chapter encode info */
2241 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2242 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2243 /* Time (pts) encode info */
2244 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2245 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2246 /* Frame number encode info */
2247 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2248 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2251 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2252 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2253 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2255 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2257 /* Lets get the preset info if there is any */
2258 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2259 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2261 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2262 /* Chapter Markers*/
2263 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2264 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2266 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2270 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2273 /* We need to get the list of chapter names to put into an array and store
2274 * in our queue, so they can be reapplied in prepareJob when this queue
2275 * item comes up if Chapter Markers is set to on.
2278 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2279 int chaptercount = hb_list_count( fTitle->list_chapter );
2280 for( i = 0; i < chaptercount; i++ )
2282 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2283 if( chapter != NULL )
2285 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2288 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2289 [ChapterNamesArray autorelease];
2291 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2292 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2293 /* Mux mp4 with http optimization */
2294 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2295 /* Add iPod uuid atom */
2296 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2300 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2301 /* x264 Option String */
2302 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2304 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2305 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2306 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2307 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2309 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2311 /* 2 Pass Encoding */
2312 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2313 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2314 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2316 /* Picture Sizing */
2317 /* Use Max Picture settings for whatever the dvd is.*/
2318 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2319 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2320 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2321 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2322 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2323 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2324 /* if we are custom anamorphic, store the exact storage, par and display dims */
2325 if (fTitle->job->anamorphic.mode == 3)
2327 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2329 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2330 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2332 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2333 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2335 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2336 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2339 NSString * pictureSummary;
2340 pictureSummary = [fPictureSizeField stringValue];
2341 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2342 /* Set crop settings here */
2343 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2344 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2345 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2346 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2347 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2349 /* Picture Filters */
2350 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2351 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2353 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2354 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2355 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2357 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2358 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2360 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2361 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2363 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2365 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2368 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2370 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2371 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2372 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2373 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2374 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2375 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2376 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2378 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2380 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2381 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2382 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2383 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2384 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2385 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2386 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2388 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2390 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2391 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2392 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2393 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2394 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2395 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2396 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2398 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2400 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2401 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2402 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2403 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2404 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2405 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2406 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2410 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2411 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2412 [subtitlesArray autorelease];
2414 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2416 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2418 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2421 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2425 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2428 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2429 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2430 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2432 /* Picture Sizing */
2433 /* Use Max Picture settings for whatever the dvd is.*/
2434 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2435 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2436 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2437 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2438 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2440 /* Set crop settings here */
2441 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2442 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2443 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2444 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2445 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2449 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2451 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2452 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2453 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2454 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2455 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2457 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2459 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2460 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2461 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2462 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2463 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2465 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2467 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2468 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2469 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2470 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2471 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2473 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2475 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2476 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2477 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2478 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2479 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2483 /* we need to auto relase the queueFileJob and return it */
2484 [queueFileJob autorelease];
2485 return queueFileJob;
2489 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2490 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2492 NSUInteger index = [indexSet lastIndex];
2493 NSUInteger aboveInsertIndexCount = 0;
2496 NSUInteger removeIndex;
2498 if (index >= insertIndex)
2500 removeIndex = index + aboveInsertIndexCount;
2501 aboveInsertIndexCount++;
2505 removeIndex = index;
2509 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2510 [QueueFileArray removeObjectAtIndex:removeIndex];
2511 [QueueFileArray insertObject:object atIndex:insertIndex];
2514 index = [indexSet indexLessThanIndex:index];
2516 /* We save all of the Queue data here
2517 * and it also gets sent back to the queue controller*/
2518 [self saveQueueFileItem];
2524 #pragma mark Queue Job Processing
2526 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2528 int i = currentQueueEncodeIndex;
2529 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2531 /* We save all of the Queue data here */
2532 [self saveQueueFileItem];
2533 /* We Reload the New Table data for presets */
2534 //[fPresetsOutlineView reloadData];
2536 /* Since we have now marked a queue item as done
2537 * we can go ahead and increment currentQueueEncodeIndex
2538 * so that if there is anything left in the queue we can
2539 * go ahead and move to the next item if we want to */
2540 currentQueueEncodeIndex++ ;
2541 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2542 int queueItems = [QueueFileArray count];
2543 /* If we still have more items in our queue, lets go to the next one */
2544 if (currentQueueEncodeIndex < queueItems)
2546 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2547 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2551 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2555 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2556 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2558 /* Tell HB to output a new activity log file for this encode */
2559 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2562 /* use a bool to determine whether or not we can decrypt using vlc */
2563 BOOL cancelScanDecrypt = 0;
2564 /* set the bool so that showNewScan knows to apply the appropriate queue
2565 * settings as this is a queue rescan
2567 //applyQueueToScan = YES;
2568 NSString *path = scanPath;
2569 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2571 if( [detector isVideoDVD] )
2573 // The chosen path was actually on a DVD, so use the raw block
2574 // device path instead.
2575 path = [detector devicePath];
2576 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2578 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2579 NSString *vlcPath = @"/Applications/VLC.app";
2580 NSFileManager * fileManager = [NSFileManager defaultManager];
2581 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2583 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2584 cancelScanDecrypt = 1;
2585 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2587 status = NSRunAlertPanel(@"HandBrake could not find VLC.",@"Please download and install VLC media player in your /Applications folder if you wish to read encrypted DVDs.", @"Get VLC", @"Cancel Scan", @"Attempt Scan Anyway");
2588 [NSApp requestUserAttention:NSCriticalRequest];
2590 if (status == NSAlertDefaultReturn)
2592 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2593 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2595 else if (status == NSAlertAlternateReturn)
2597 /* User chose to cancel the scan */
2598 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2602 /* User chose to override our warning and scan the physical dvd anyway, at their own peril. on an encrypted dvd this produces massive log files and fails */
2603 cancelScanDecrypt = 0;
2604 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2610 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2611 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2615 if (cancelScanDecrypt == 0)
2617 /* we actually pass the scan off to libhb here */
2618 /* If there is no title number passed to scan, we use "0"
2619 * which causes the default behavior of a full source scan
2625 if (scanTitleNum > 0)
2627 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2630 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2631 /* We use our advance pref to determine how many previews to scan */
2632 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2633 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2637 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2638 - (void) processNewQueueEncode
2640 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2641 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2642 hb_job_t * job = title->job;
2644 if( !hb_list_count( list ) )
2646 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2649 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2650 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2651 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2652 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2653 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2657 * If scanning we need to do some extra setup of the job.
2659 if( job->indepth_scan == 1 )
2664 * When subtitle scan is enabled do a fast pre-scan job
2665 * which will determine which subtitles to enable, if any.
2668 x264opts_tmp = job->x264opts;
2670 job->x264opts = NULL;
2672 job->indepth_scan = 1;
2676 * Add the pre-scan job
2678 hb_add( fQueueEncodeLibhb, job );
2679 job->x264opts = x264opts_tmp;
2683 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2685 job->indepth_scan = 0;
2691 hb_add( fQueueEncodeLibhb, job );
2695 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2696 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2698 hb_add( fQueueEncodeLibhb, job );
2703 job->indepth_scan = 0;
2706 hb_add( fQueueEncodeLibhb, job );
2709 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2710 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2711 /* Lets mark our new encode as 1 or "Encoding" */
2712 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2713 [self saveQueueFileItem];
2715 /* we need to clean up the subtitle tracks after the job(s) have been set */
2716 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2718 for(ii = 0; ii < num_subtitle_tracks; ii++)
2720 hb_subtitle_t * subtitle;
2721 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2724 hb_list_rem(job->list_subtitle, subtitle);
2729 /* We should be all setup so let 'er rip */
2736 #pragma mark Queue Item Editing
2738 /* Rescans the chosen queue item back into the main window */
2739 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2741 fqueueEditRescanItemNum = selectedQueueItem;
2742 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2743 applyQueueToScan = YES;
2744 /* Set the browsedSourceDisplayName for showNewScan */
2745 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2746 [self performScan:scanPath scanTitleNum:scanTitleNum];
2750 /* We use this method after a queue item rescan for edit.
2751 * it largely mirrors -selectPreset in terms of structure.
2752 * Assumes that a queue item has been reloaded into the main window.
2754 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2756 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2757 hb_job_t * job = fTitle->job;
2760 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2762 /* Set title number and chapters */
2763 /* since the queue only scans a single title, we really don't need to pick a title */
2764 [fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2766 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2767 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2770 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2771 [self formatPopUpChanged:nil];
2773 /* Chapter Markers*/
2774 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2775 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2776 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2777 /* Mux mp4 with http optimization */
2778 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2781 /* We set the advanced opt string here if applicable*/
2782 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2783 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2785 /* Lets run through the following functions to get variables set there */
2786 [self videoEncoderPopUpChanged:nil];
2787 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2788 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2789 [self calculateBitrate:nil];
2792 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2794 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2795 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2796 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2797 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2798 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2799 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2800 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2801 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2803 /* For the quality slider we need to convert the old percent's to the new rf scales */
2804 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2805 [fVidQualitySlider setFloatValue:rf];
2810 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2811 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2813 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2817 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2818 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2822 [self videoMatrixChanged:nil];
2823 [self writeToActivityLog: "applyQueueSettingsToMainWindow: video matrix changed"];
2824 /* Video framerate */
2825 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2826 detected framerate in the fVidRatePopUp so we use index 0*/
2827 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2829 [fVidRatePopUp selectItemAtIndex: 0];
2833 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2836 /* 2 Pass Encoding */
2837 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2838 [self twoPassCheckboxChanged:nil];
2839 /* Turbo 1st pass for 2 Pass Encoding */
2840 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2845 /* Now lets add our new tracks to the audio list here */
2846 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2848 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2849 [self audioTrackPopUpChanged: fAudLang1PopUp];
2850 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2851 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2853 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2855 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2856 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2858 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2859 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2863 [fAudLang1PopUp selectItemAtIndex: 0];
2864 [self audioTrackPopUpChanged: fAudLang1PopUp];
2866 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2868 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2869 [self audioTrackPopUpChanged: fAudLang2PopUp];
2870 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2871 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2873 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2875 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2876 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2878 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2879 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2883 [fAudLang2PopUp selectItemAtIndex: 0];
2884 [self audioTrackPopUpChanged: fAudLang2PopUp];
2886 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2888 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2889 [self audioTrackPopUpChanged: fAudLang3PopUp];
2890 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2891 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2893 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2895 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2896 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2898 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2899 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2903 [fAudLang3PopUp selectItemAtIndex: 0];
2904 [self audioTrackPopUpChanged: fAudLang3PopUp];
2906 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2908 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2909 [self audioTrackPopUpChanged: fAudLang4PopUp];
2910 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2911 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2913 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2915 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2916 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2918 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2919 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2923 [fAudLang4PopUp selectItemAtIndex: 0];
2924 [self audioTrackPopUpChanged: fAudLang4PopUp];
2927 [self writeToActivityLog: "applyQueueSettingsToMainWindow: audio set up"];
2929 /* Crashy crashy right now, working on it */
2930 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2931 [fSubtitlesTable reloadData];
2932 /* Picture Settings */
2934 /* If Cropping is set to custom, then recall all four crop values from
2935 when the preset was created and apply them */
2936 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2938 [fPictureController setAutoCrop:NO];
2940 /* Here we use the custom crop values saved at the time the preset was saved */
2941 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2942 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2943 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2944 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2947 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2949 [fPictureController setAutoCrop:YES];
2950 /* Here we use the auto crop values determined right after scan */
2951 job->crop[0] = AutoCropTop;
2952 job->crop[1] = AutoCropBottom;
2953 job->crop[2] = AutoCropLeft;
2954 job->crop[3] = AutoCropRight;
2958 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2960 /* we check to make sure the presets width/height does not exceed the sources width/height */
2961 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2963 /* if so, then we use the sources height and width to avoid scaling up */
2964 //job->width = fTitle->width;
2965 //job->height = fTitle->height;
2966 [self revertPictureSizeToMax:nil];
2968 else // source width/height is >= the preset height/width
2970 /* we can go ahead and use the presets values for height and width */
2971 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2972 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2974 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2975 if (job->keep_ratio == 1)
2977 hb_fix_aspect( job, HB_KEEP_WIDTH );
2978 if( job->height > fTitle->height )
2980 job->height = fTitle->height;
2981 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2984 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2985 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2987 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture sizing set up"];
2992 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2993 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2994 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2997 [fPictureController setUseDecomb:1];
2998 [fPictureController setDecomb:0];
2999 [fPictureController setDeinterlace:0];
3000 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3002 /* we are using decomb */
3004 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3006 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3008 /* if we are using "Custom" in the decomb setting, also set the custom string*/
3009 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3011 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
3017 /* We are using Deinterlace */
3019 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3021 [fPictureController setUseDecomb:0];
3022 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3023 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3024 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3026 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
3033 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3035 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3036 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3037 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3039 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
3044 [fPictureController setDetelecine:0];
3048 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3050 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3051 /* if we are using "Custom" in the denoise setting, also set the custom string*/
3052 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3054 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
3059 [fPictureController setDenoise:0];
3063 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3065 /* if its a one, then its the old on/off deblock, set on to 5*/
3066 [fPictureController setDeblock:5];
3070 /* use the settings intValue */
3071 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3074 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3076 [fPictureController setGrayscale:1];
3080 [fPictureController setGrayscale:0];
3083 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3084 [fPictureController SetTitle:fTitle];
3085 [self calculatePictureSizing:nil];
3087 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture filters set up"];
3088 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3089 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3090 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3091 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3093 /* Deselect the currently selected Preset if there is one*/
3094 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3095 //[self selectPreset:nil];
3097 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3098 /* Change UI to show "Custom" settings are being used */
3099 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3101 curUserPresetChosenNum = nil;
3105 /* Deselect the currently selected Preset if there is one*/
3106 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3107 /* Change UI to show "Custom" settings are being used */
3108 [fPresetSelectedDisplay setStringValue: @"Custom"];
3110 //curUserPresetChosenNum = nil;
3113 /* We need to set this bool back to NO, in case the user wants to do a scan */
3114 //applyQueueToScan = NO;
3116 /* Not that source is loaded and settings applied, delete the queue item from the queue */
3117 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3118 [self removeQueueFileItem:fqueueEditRescanItemNum];
3124 #pragma mark Live Preview
3125 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3126 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3129 - (void) prepareJobForPreview
3131 hb_list_t * list = hb_get_titles( fHandle );
3132 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3133 [fSrcTitlePopUp indexOfSelectedItem] );
3134 hb_job_t * job = title->job;
3135 hb_audio_config_t * audio;
3136 /* set job->angle for libdvdnav */
3137 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3138 /* Chapter selection */
3139 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3140 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3142 /* Format (Muxer) and Video Encoder */
3143 job->mux = [[fDstFormatPopUp selectedItem] tag];
3144 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3146 job->chapter_markers = 0;
3148 if( job->vcodec & HB_VCODEC_X264 )
3151 /* Below Sends x264 options to the core library if x264 is selected*/
3152 /* Lets use this as per Nyx, Thanks Nyx!*/
3153 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3154 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3155 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3160 /* Video settings */
3161 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3162 * and detelecine is on, so we handle that in the logic below
3165 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3167 /* a specific framerate has been chosen */
3168 job->vrate = 27000000;
3169 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3170 /* We are not same as source so we set job->cfr to 1
3171 * to enable constant frame rate since user has specified
3172 * a specific framerate*/
3177 /* We are same as source (variable) */
3178 job->vrate = title->rate;
3179 job->vrate_base = title->rate_base;
3180 /* We are same as source so we set job->cfr to 0
3181 * to enable true same as source framerate */
3183 /* If we are same as source and we have detelecine on, we need to turn on
3186 if ([fPictureController detelecine] == 1)
3192 switch( [fVidQualityMatrix selectedRow] )
3196 Bitrate should already have been calculated and displayed
3197 in fVidBitrateField, so let's just use it */
3199 job->vquality = -1.0;
3200 job->vbitrate = [fVidBitrateField intValue];
3203 job->vquality = [fVidQualityRFField floatValue];
3208 /* Subtitle settings */
3209 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3216 bool one_burned = FALSE;
3219 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3221 while (tempObject = [enumerator nextObject])
3224 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3225 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3226 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3227 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3229 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3230 * we want to ignore it for display as well as encoding.
3234 /* if i is 0, then we are in the first item of the subtitles which we need to
3235 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3236 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3239 /* if we are on the first track and using "Foreign Audio Search" */
3240 if (i == 0 && subtitle == 1)
3242 /* NOTE: Currently foreign language search is borked for preview.
3243 * Commented out but left in for initial commit. */
3246 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3248 job->indepth_scan = 1;
3249 if (burned == 1 || job->mux != HB_MUX_MP4)
3251 if (burned != 1 && job->mux == HB_MUX_MKV)
3253 job->select_subtitle_config.dest = PASSTHRUSUB;
3257 job->select_subtitle_config.dest = RENDERSUB;
3260 job->select_subtitle_config.force = force;
3261 job->select_subtitle_config.default_track = def;
3270 /* for the actual source tracks, we must subtract the non source entries so
3271 * that the menu index matches the source subtitle_list index for convenience */
3274 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3275 * Foreign Language Search is 1) so subtract 2 */
3276 subtitle = subtitle - 2;
3280 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3283 subtitle = subtitle - 1;
3286 /* We are setting a source subtitle so access the source subtitle info */
3287 hb_subtitle_t * subt;
3289 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3291 /* if we are getting the subtitles from an external srt file */
3292 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3294 hb_subtitle_config_t sub_config;
3296 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3298 /* we need to srncpy file path and char code */
3299 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3300 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3302 sub_config.force = 0;
3303 sub_config.dest = PASSTHRUSUB;
3304 sub_config.default_track = def;
3306 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3311 hb_subtitle_config_t sub_config = subt->config;
3313 if (!burned && job->mux == HB_MUX_MKV &&
3314 subt->format == PICTURESUB)
3316 sub_config.dest = PASSTHRUSUB;
3318 else if (!burned && job->mux == HB_MUX_MP4 &&
3319 subt->format == PICTURESUB)
3321 // Skip any non-burned vobsubs when output is mp4
3324 else if ( burned && subt->format == PICTURESUB )
3326 // Only allow one subtitle to be burned into the video
3331 sub_config.force = force;
3332 sub_config.default_track = def;
3333 hb_subtitle_add( job, &sub_config, subtitle );
3343 [subtitlesArray autorelease];
3346 /* Audio tracks and mixdowns */
3347 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3348 int audiotrack_count = hb_list_count(job->list_audio);
3349 for( int i = 0; i < audiotrack_count;i++)
3351 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3352 hb_list_rem(job->list_audio, temp_audio);
3354 /* Now lets add our new tracks to the audio list here */
3355 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3357 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3358 hb_audio_config_init(audio);
3359 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3360 /* We go ahead and assign values to our audio->out.<properties> */
3361 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3362 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3363 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3364 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3365 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3366 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3368 hb_audio_add( job, audio );
3371 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3373 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3374 hb_audio_config_init(audio);
3375 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3376 /* We go ahead and assign values to our audio->out.<properties> */
3377 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3378 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3379 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3380 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3381 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3382 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3384 hb_audio_add( job, audio );
3389 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3391 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3392 hb_audio_config_init(audio);
3393 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3394 /* We go ahead and assign values to our audio->out.<properties> */
3395 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3396 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3397 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3398 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3399 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3400 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3402 hb_audio_add( job, audio );
3407 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3409 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3410 hb_audio_config_init(audio);
3411 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3412 /* We go ahead and assign values to our audio->out.<properties> */
3413 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3414 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3415 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3416 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3417 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3418 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3420 hb_audio_add( job, audio );
3429 /* Though Grayscale is not really a filter, per se
3430 * we put it here since its in the filters panel
3433 if ([fPictureController grayscale])
3442 /* Initialize the filters list */
3443 job->filters = hb_list_init();
3445 /* Now lets call the filters if applicable.
3446 * The order of the filters is critical
3450 if ([fPictureController detelecine] == 1)
3452 /* use a custom detelecine string */
3453 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3454 hb_list_add( job->filters, &hb_filter_detelecine );
3456 if ([fPictureController detelecine] == 2)
3459 hb_list_add( job->filters, &hb_filter_detelecine );
3464 if ([fPictureController useDecomb] == 1)
3467 /* we add the custom string if present */
3468 if ([fPictureController decomb] == 1)
3470 /* use a custom decomb string */
3471 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3472 hb_list_add( job->filters, &hb_filter_decomb );
3474 if ([fPictureController decomb] == 2)
3476 /* Run old deinterlacer fd by default */
3477 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3478 hb_list_add( job->filters, &hb_filter_decomb );
3485 if ([fPictureController deinterlace] == 1)
3487 /* we add the custom string if present */
3488 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3489 hb_list_add( job->filters, &hb_filter_deinterlace );
3491 else if ([fPictureController deinterlace] == 2)
3493 /* Run old deinterlacer fd by default */
3494 hb_filter_deinterlace.settings = "-1";
3495 hb_list_add( job->filters, &hb_filter_deinterlace );
3497 else if ([fPictureController deinterlace] == 3)
3499 /* Yadif mode 0 (without spatial deinterlacing.) */
3500 hb_filter_deinterlace.settings = "2";
3501 hb_list_add( job->filters, &hb_filter_deinterlace );
3503 else if ([fPictureController deinterlace] == 4)
3505 /* Yadif (with spatial deinterlacing) */
3506 hb_filter_deinterlace.settings = "0";
3507 hb_list_add( job->filters, &hb_filter_deinterlace );
3513 if ([fPictureController denoise] == 1) // custom in popup
3515 /* we add the custom string if present */
3516 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3517 hb_list_add( job->filters, &hb_filter_denoise );
3519 else if ([fPictureController denoise] == 2) // Weak in popup
3521 hb_filter_denoise.settings = "2:1:2:3";
3522 hb_list_add( job->filters, &hb_filter_denoise );
3524 else if ([fPictureController denoise] == 3) // Medium in popup
3526 hb_filter_denoise.settings = "3:2:2:3";
3527 hb_list_add( job->filters, &hb_filter_denoise );
3529 else if ([fPictureController denoise] == 4) // Strong in popup
3531 hb_filter_denoise.settings = "7:7:5:5";
3532 hb_list_add( job->filters, &hb_filter_denoise );
3536 /* Deblock (uses pp7 default) */
3537 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3538 * the macgui's purposes a value of 0 actually means to not even use the filter
3539 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3541 if ([fPictureController deblock] != 0)
3543 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3544 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3545 hb_list_add( job->filters, &hb_filter_deblock );
3552 #pragma mark Job Handling
3558 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3559 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3560 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3561 hb_job_t * job = title->job;
3562 hb_audio_config_t * audio;
3563 /* Title Angle for dvdnav */
3564 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3566 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3568 /* Chapter selection */
3569 [self writeToActivityLog: "Start / Stop set to chapters"];
3570 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3571 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3573 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3575 /* we are pts based start / stop */
3576 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3578 /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3579 * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3581 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3582 /* get the start seconds from the start seconds field */
3583 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3584 //job->start_at_preview = start_seconds;
3585 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3586 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3587 job->pts_to_start = start_seconds * 90000LL;
3588 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3589 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3590 job->pts_to_stop = stop_seconds * 90000LL;
3592 /* A bunch of verbose activity log messages to check on what should be expected */
3593 [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3594 [self writeToActivityLog: "point a to b should start at (hh:mm:ss): %d:%d:%d", start_seconds / 3600, ( start_seconds / 60 ) % 60,start_seconds % 60];
3595 [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3596 [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3597 [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3598 [self writeToActivityLog: "point a to b should end at (hh:mm:ss): %d:%d:%d", (start_seconds + stop_seconds) / 3600, ( (start_seconds + stop_seconds) / 60 ) % 60,(start_seconds + stop_seconds) % 60];
3600 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3602 /* we are frame based start / stop */
3603 [self writeToActivityLog: "Start / Stop set to frames ..."];
3605 /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3606 * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3608 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3609 /* get the start seconds from the start seconds field */
3610 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3611 //job->start_at_preview = start_seconds;
3612 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3613 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3614 job->frame_to_start = start_frame;
3615 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3616 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3617 job->frame_to_stop = stop_frame;
3619 /* A bunch of verbose activity log messages to check on what should be expected */
3620 [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3621 [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3622 [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3628 /* Format (Muxer) and Video Encoder */
3629 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3630 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3633 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3634 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3636 job->largeFileSize = 1;
3640 job->largeFileSize = 0;
3642 /* We set http optimized mp4 here */
3643 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3645 job->mp4_optimize = 1;
3649 job->mp4_optimize = 0;
3653 /* We set the chapter marker extraction here based on the format being
3654 mpeg4 or mkv and the checkbox being checked */
3655 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3657 job->chapter_markers = 1;
3659 /* now lets get our saved chapter names out the array in the queue file
3660 * and insert them back into the title chapter list. We have it here,
3661 * because unless we are inserting chapter markers there is no need to
3662 * spend the overhead of iterating through the chapter names array imo
3663 * Also, note that if for some reason we don't apply chapter names, the
3664 * chapters just come out 001, 002, etc. etc.
3667 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3669 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3671 while (tempObject = [enumerator nextObject])
3673 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3674 if( chapter != NULL )
3676 strncpy( chapter->title, [tempObject UTF8String], 1023);
3677 chapter->title[1023] = '\0';
3684 job->chapter_markers = 0;
3687 if( job->vcodec & HB_VCODEC_X264 )
3689 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3699 /* Below Sends x264 options to the core library if x264 is selected*/
3700 /* Lets use this as per Nyx, Thanks Nyx!*/
3701 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3702 /* Turbo first pass if two pass and Turbo First pass is selected */
3703 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3705 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3706 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3707 /* append the "Turbo" string variable to the existing opts string.
3708 Note: the "Turbo" string must be appended, not prepended to work properly*/
3709 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3710 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3714 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3720 /* Picture Size Settings */
3721 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3722 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3724 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3725 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3726 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3727 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3729 /* insert our custom values here for capuj */
3730 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3731 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3733 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3735 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3736 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3738 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3739 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3742 /* Here we use the crop values saved at the time the preset was saved */
3743 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3744 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3745 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3746 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3748 /* Video settings */
3751 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3752 * and detelecine is on, so we handle that in the logic below
3755 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3757 /* a specific framerate has been chosen */
3758 job->vrate = 27000000;
3759 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3760 /* We are not same as source so we set job->cfr to 1
3761 * to enable constant frame rate since user has specified
3762 * a specific framerate*/
3767 /* We are same as source (variable) */
3768 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3769 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3770 /* We are same as source so we set job->cfr to 0
3771 * to enable true same as source framerate */
3773 /* If we are same as source and we have detelecine on, we need to turn on
3776 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3782 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3785 Bitrate should already have been calculated and displayed
3786 in fVidBitrateField, so let's just use it same as abr*/
3787 job->vquality = -1.0;
3788 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3790 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3792 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3797 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3802 #pragma mark Process Subtitles to libhb
3804 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3805 * which means that we need to account for the offset of non source language settings in from
3806 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3807 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3808 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3809 * to the source tracks position in title->list_subtitle.
3816 bool one_burned = FALSE;
3819 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3821 while (tempObject = [enumerator nextObject])
3824 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3825 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3826 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3827 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3829 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3830 * we want to ignore it for display as well as encoding.
3834 /* if i is 0, then we are in the first item of the subtitles which we need to
3835 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3836 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3839 /* if we are on the first track and using "Foreign Audio Search" */
3840 if (i == 0 && subtitle == 1)
3842 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3844 job->indepth_scan = 1;
3845 if (burned == 1 || job->mux != HB_MUX_MP4)
3847 if (burned != 1 && job->mux == HB_MUX_MKV)
3849 job->select_subtitle_config.dest = PASSTHRUSUB;
3853 job->select_subtitle_config.dest = RENDERSUB;
3856 job->select_subtitle_config.force = force;
3857 job->select_subtitle_config.default_track = def;
3865 /* for the actual source tracks, we must subtract the non source entries so
3866 * that the menu index matches the source subtitle_list index for convenience */
3869 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3870 * Foreign Language Search is 1) so subtract 2 */
3871 subtitle = subtitle - 2;
3875 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3878 subtitle = subtitle - 1;
3881 /* We are setting a source subtitle so access the source subtitle info */
3882 hb_subtitle_t * subt;
3884 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3886 /* if we are getting the subtitles from an external srt file */
3887 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3889 hb_subtitle_config_t sub_config;
3891 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3893 /* we need to srncpy file name and codeset */
3894 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3895 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3897 sub_config.force = 0;
3898 sub_config.dest = PASSTHRUSUB;
3899 sub_config.default_track = def;
3901 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3907 hb_subtitle_config_t sub_config = subt->config;
3909 if (!burned && job->mux == HB_MUX_MKV &&
3910 subt->format == PICTURESUB)
3912 sub_config.dest = PASSTHRUSUB;
3914 else if (!burned && job->mux == HB_MUX_MP4 &&
3915 subt->format == PICTURESUB)
3917 // Skip any non-burned vobsubs when output is mp4
3920 else if ( burned && subt->format == PICTURESUB )
3922 // Only allow one subtitle to be burned into the video
3927 sub_config.force = force;
3928 sub_config.default_track = def;
3929 hb_subtitle_add( job, &sub_config, subtitle );
3940 /* Audio tracks and mixdowns */
3941 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3942 int audiotrack_count = hb_list_count(job->list_audio);
3943 for( int i = 0; i < audiotrack_count;i++)
3945 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3946 hb_list_rem(job->list_audio, temp_audio);
3948 /* Now lets add our new tracks to the audio list here */
3949 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3951 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3952 hb_audio_config_init(audio);
3953 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3954 /* We go ahead and assign values to our audio->out.<properties> */
3955 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3956 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3957 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3958 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3959 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3960 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3962 hb_audio_add( job, audio );
3965 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3968 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3969 hb_audio_config_init(audio);
3970 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3971 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3972 /* We go ahead and assign values to our audio->out.<properties> */
3973 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3974 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3975 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3976 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3977 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3978 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3980 hb_audio_add( job, audio );
3984 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3986 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3987 hb_audio_config_init(audio);
3988 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3989 /* We go ahead and assign values to our audio->out.<properties> */
3990 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3991 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3992 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3993 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3994 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3995 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3997 hb_audio_add( job, audio );
4001 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
4003 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4004 hb_audio_config_init(audio);
4005 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4006 /* We go ahead and assign values to our audio->out.<properties> */
4007 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4008 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
4009 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
4010 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
4011 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
4012 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
4014 hb_audio_add( job, audio );
4020 job->filters = hb_list_init();
4022 /* Now lets call the filters if applicable.
4023 * The order of the filters is critical
4026 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4028 /* use a custom detelecine string */
4029 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4030 hb_list_add( job->filters, &hb_filter_detelecine );
4032 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4034 /* Use libhb's default values */
4035 hb_list_add( job->filters, &hb_filter_detelecine );
4038 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4041 /* we add the custom string if present */
4042 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4044 /* use a custom decomb string */
4045 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4046 hb_list_add( job->filters, &hb_filter_decomb );
4048 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4050 /* Use libhb default */
4051 hb_list_add( job->filters, &hb_filter_decomb );
4059 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4061 /* we add the custom string if present */
4062 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4063 hb_list_add( job->filters, &hb_filter_deinterlace );
4065 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4067 /* Run old deinterlacer fd by default */
4068 hb_filter_deinterlace.settings = "-1";
4069 hb_list_add( job->filters, &hb_filter_deinterlace );
4071 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4073 /* Yadif mode 0 (without spatial deinterlacing.) */
4074 hb_filter_deinterlace.settings = "2";
4075 hb_list_add( job->filters, &hb_filter_deinterlace );
4077 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4079 /* Yadif (with spatial deinterlacing) */
4080 hb_filter_deinterlace.settings = "0";
4081 hb_list_add( job->filters, &hb_filter_deinterlace );
4087 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4089 /* we add the custom string if present */
4090 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4091 hb_list_add( job->filters, &hb_filter_denoise );
4093 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4095 hb_filter_denoise.settings = "2:1:2:3";
4096 hb_list_add( job->filters, &hb_filter_denoise );
4098 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4100 hb_filter_denoise.settings = "3:2:2:3";
4101 hb_list_add( job->filters, &hb_filter_denoise );
4103 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4105 hb_filter_denoise.settings = "7:7:5:5";
4106 hb_list_add( job->filters, &hb_filter_denoise );
4110 /* Deblock (uses pp7 default) */
4111 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
4112 * the macgui's purposes a value of 0 actually means to not even use the filter
4113 * current hb_filter_deblock.settings valid ranges are from 5 - 15
4115 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4117 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4118 hb_list_add( job->filters, &hb_filter_deblock );
4120 [self writeToActivityLog: "prepareJob exiting"];
4125 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4127 - (IBAction) addToQueue: (id) sender
4129 /* We get the destination directory from the destination field here */
4130 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4131 /* We check for a valid destination here */
4132 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4134 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4141 BOOL fileExistsInQueue;
4142 fileExistsInQueue = NO;
4144 /* We check for and existing file here */
4145 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4150 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4152 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4154 while (tempObject = [enumerator nextObject])
4156 NSDictionary *thisQueueDict = tempObject;
4157 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4159 fileExistsInQueue = YES;
4165 if(fileExists == YES)
4167 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4168 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4169 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4170 NULL, NULL, [NSString stringWithFormat:
4171 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4172 [fDstFile2Field stringValue]] );
4174 else if (fileExistsInQueue == YES)
4176 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4177 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4178 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4179 NULL, NULL, [NSString stringWithFormat:
4180 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4181 [fDstFile2Field stringValue]] );
4185 [self doAddToQueue];
4189 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4190 the user if they want to overwrite an exiting movie file.
4192 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4193 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4195 if( returnCode == NSAlertAlternateReturn )
4196 [self doAddToQueue];
4199 - (void) doAddToQueue
4201 [self addQueueFileItem ];
4206 /* Rip: puts up an alert before ultimately calling doRip
4208 - (IBAction) Rip: (id) sender
4210 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4211 /* Rip or Cancel ? */
4213 hb_get_state2( fQueueEncodeLibhb, &s );
4215 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4217 [self Cancel: sender];
4221 /* We check to see if we need to warn the user that the computer will go to sleep
4222 or shut down when encoding is finished */
4223 [self remindUserOfSleepOrShutdown];
4225 // If there are pending jobs in the queue, then this is a rip the queue
4226 if (fPendingCount > 0)
4228 /* here lets start the queue with the first pending item */
4229 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4234 // Before adding jobs to the queue, check for a valid destination.
4236 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4237 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4239 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4243 /* We check for duplicate name here */
4244 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4246 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4247 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4248 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4249 NULL, NULL, [NSString stringWithFormat:
4250 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4251 [fDstFile2Field stringValue]] );
4253 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4257 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4258 otherwise, just rip the queue */
4259 if(fPendingCount == 0)
4261 [self doAddToQueue];
4264 /* go right to processing the new queue encode */
4265 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4270 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4271 want to overwrite an exiting movie file.
4273 - (void) overWriteAlertDone: (NSWindow *) sheet
4274 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4276 if( returnCode == NSAlertAlternateReturn )
4278 /* if there are no jobs in the queue, then add this one to the queue and rip
4279 otherwise, just rip the queue */
4280 if( fPendingCount == 0 )
4282 [self doAddToQueue];
4285 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4286 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4287 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4292 - (void) remindUserOfSleepOrShutdown
4294 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4296 /*Warn that computer will sleep after encoding*/
4299 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);
4300 [NSApp requestUserAttention:NSCriticalRequest];
4301 if ( reminduser == NSAlertAlternateReturn )
4303 [self showPreferencesWindow:nil];
4306 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4308 /*Warn that computer will shut down after encoding*/
4311 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);
4312 [NSApp requestUserAttention:NSCriticalRequest];
4313 if ( reminduser == NSAlertAlternateReturn )
4315 [self showPreferencesWindow:nil];
4324 /* Let libhb do the job */
4325 hb_start( fQueueEncodeLibhb );
4326 /*set the fEncodeState State */
4331 //------------------------------------------------------------------------------------
4332 // Displays an alert asking user if the want to cancel encoding of current job.
4333 // Cancel: returns immediately after posting the alert. Later, when the user
4334 // acknowledges the alert, doCancelCurrentJob is called.
4335 //------------------------------------------------------------------------------------
4336 - (IBAction)Cancel: (id)sender
4338 if (!fQueueController) return;
4340 hb_pause( fQueueEncodeLibhb );
4341 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4343 // Which window to attach the sheet to?
4344 NSWindow * docWindow;
4345 if ([sender respondsToSelector: @selector(window)])
4346 docWindow = [sender window];
4348 docWindow = fWindow;
4350 NSBeginCriticalAlertSheet(
4352 NSLocalizedString(@"Continue Encoding", nil),
4353 NSLocalizedString(@"Cancel Current and Stop", nil),
4354 NSLocalizedString(@"Cancel Current and Continue", nil),
4356 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4357 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4359 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4362 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4364 hb_resume( fQueueEncodeLibhb );
4365 if (returnCode == NSAlertOtherReturn)
4367 [self doCancelCurrentJob]; // <- this also stops libhb
4369 if (returnCode == NSAlertAlternateReturn)
4371 [self doCancelCurrentJobAndStop];
4375 //------------------------------------------------------------------------------------
4376 // Cancels and deletes the current job and stops libhb from processing the remaining
4378 //------------------------------------------------------------------------------------
4379 - (void) doCancelCurrentJob
4381 // Stop the current job. hb_stop will only cancel the current pass and then set
4382 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4383 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4384 // remaining passes of the job and then start the queue back up if there are any
4388 hb_stop( fQueueEncodeLibhb );
4390 // Delete all remaining jobs since libhb doesn't do this on its own.
4392 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4393 hb_rem( fQueueEncodeLibhb, job );
4395 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4397 // now that we've stopped the currently encoding job, lets mark it as cancelled
4398 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4399 // and as always, save it in the queue .plist...
4400 /* We save all of the Queue data here */
4401 [self saveQueueFileItem];
4402 // so now lets move to
4403 currentQueueEncodeIndex++ ;
4404 // ... and see if there are more items left in our queue
4405 int queueItems = [QueueFileArray count];
4406 /* If we still have more items in our queue, lets go to the next one */
4407 if (currentQueueEncodeIndex < queueItems)
4409 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4410 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4412 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4416 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4421 - (void) doCancelCurrentJobAndStop
4423 hb_stop( fQueueEncodeLibhb );
4425 // Delete all remaining jobs since libhb doesn't do this on its own.
4427 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4428 hb_rem( fQueueEncodeLibhb, job );
4431 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4433 // now that we've stopped the currently encoding job, lets mark it as cancelled
4434 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4435 // and as always, save it in the queue .plist...
4436 /* We save all of the Queue data here */
4437 [self saveQueueFileItem];
4438 // so now lets move to
4439 currentQueueEncodeIndex++ ;
4440 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4442 - (IBAction) Pause: (id) sender
4445 hb_get_state2( fQueueEncodeLibhb, &s );
4447 if( s.state == HB_STATE_PAUSED )
4449 hb_resume( fQueueEncodeLibhb );
4453 hb_pause( fQueueEncodeLibhb );
4458 #pragma mark GUI Controls Changed Methods
4460 - (IBAction) titlePopUpChanged: (id) sender
4462 hb_list_t * list = hb_get_titles( fHandle );
4463 hb_title_t * title = (hb_title_t*)
4464 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4466 /* If we are a stream type, grok the output file name from title->name upon title change */
4467 if (title->type == HB_STREAM_TYPE)
4469 /* we set the default name according to the new title->name */
4470 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4471 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4472 [NSString stringWithUTF8String: title->name],
4473 [[fDstFile2Field stringValue] pathExtension]]];
4474 /* If we have more than one title and are stream then we have a batch, change the source to read out the parent folder also */
4475 if ( hb_list_count( list ) > 1 )
4477 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4481 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4482 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4483 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4484 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4485 /* For point a to point b frame encoding, set the start and end fields to 0 and the title duration * announced fps in seconds respectively */
4486 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4487 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4488 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4490 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4491 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4493 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4494 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4495 [browsedSourceDisplayName stringByDeletingPathExtension],
4497 [[fDstFile2Field stringValue] pathExtension]]];
4499 /* Update encode start / stop variables */
4503 /* Update chapter popups */
4504 [fSrcChapterStartPopUp removeAllItems];
4505 [fSrcChapterEndPopUp removeAllItems];
4506 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4508 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4509 stringWithFormat: @"%d", i + 1]];
4510 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4511 stringWithFormat: @"%d", i + 1]];
4514 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4515 [fSrcChapterEndPopUp selectItemAtIndex:
4516 hb_list_count( title->list_chapter ) - 1];
4517 [self chapterPopUpChanged:nil];
4519 /* if using dvd nav, show the angle widget */
4520 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4522 [fSrcAngleLabel setHidden:NO];
4523 [fSrcAnglePopUp setHidden:NO];
4525 [fSrcAnglePopUp removeAllItems];
4526 for( int i = 0; i < title->angle_count; i++ )
4528 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4530 [fSrcAnglePopUp selectItemAtIndex: 0];
4534 [fSrcAngleLabel setHidden:YES];
4535 [fSrcAnglePopUp setHidden:YES];
4538 /* Start Get and set the initial pic size for display */
4539 hb_job_t * job = title->job;
4542 /* Set Auto Crop to on upon selecting a new title */
4543 [fPictureController setAutoCrop:YES];
4545 /* We get the originial output picture width and height and put them
4546 in variables for use with some presets later on */
4547 PicOrigOutputWidth = job->width;
4548 PicOrigOutputHeight = job->height;
4549 AutoCropTop = job->crop[0];
4550 AutoCropBottom = job->crop[1];
4551 AutoCropLeft = job->crop[2];
4552 AutoCropRight = job->crop[3];
4554 /* Reset the new title in fPictureController && fPreviewController*/
4555 [fPictureController SetTitle:title];
4558 /* Update Subtitle Table */
4559 [fSubtitlesDelegate resetWithTitle:title];
4560 [fSubtitlesTable reloadData];
4563 /* Update chapter table */
4564 [fChapterTitlesDelegate resetWithTitle:title];
4565 [fChapterTable reloadData];
4567 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4568 int audiotrack_count = hb_list_count(job->list_audio);
4569 for( int i = 0; i < audiotrack_count;i++)
4571 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4572 hb_list_rem(job->list_audio, temp_audio);
4575 /* Update audio popups */
4576 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4577 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4578 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4579 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4580 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4581 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4582 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4583 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4584 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4585 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4587 /* changing the title may have changed the audio channels on offer, */
4588 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4589 [self audioTrackPopUpChanged: fAudLang1PopUp];
4590 [self audioTrackPopUpChanged: fAudLang2PopUp];
4591 [self audioTrackPopUpChanged: fAudLang3PopUp];
4592 [self audioTrackPopUpChanged: fAudLang4PopUp];
4594 [fVidRatePopUp selectItemAtIndex: 0];
4596 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4597 [self calculatePictureSizing:nil];
4599 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4600 [self selectPreset:nil];
4603 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4605 if( [fEncodeStartStopPopUp isEnabled] )
4607 /* We are chapters */
4608 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4610 [fSrcChapterStartPopUp setHidden: NO];
4611 [fSrcChapterEndPopUp setHidden: NO];
4613 [fSrcTimeStartEncodingField setHidden: YES];
4614 [fSrcTimeEndEncodingField setHidden: YES];
4616 [fSrcFrameStartEncodingField setHidden: YES];
4617 [fSrcFrameEndEncodingField setHidden: YES];
4619 [self chapterPopUpChanged:nil];
4621 /* We are time based (seconds) */
4622 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4624 [fSrcChapterStartPopUp setHidden: YES];
4625 [fSrcChapterEndPopUp setHidden: YES];
4627 [fSrcTimeStartEncodingField setHidden: NO];
4628 [fSrcTimeEndEncodingField setHidden: NO];
4630 [fSrcFrameStartEncodingField setHidden: YES];
4631 [fSrcFrameEndEncodingField setHidden: YES];
4633 [self startEndSecValueChanged:nil];
4635 /* We are frame based */
4636 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4638 [fSrcChapterStartPopUp setHidden: YES];
4639 [fSrcChapterEndPopUp setHidden: YES];
4641 [fSrcTimeStartEncodingField setHidden: YES];
4642 [fSrcTimeEndEncodingField setHidden: YES];
4644 [fSrcFrameStartEncodingField setHidden: NO];
4645 [fSrcFrameEndEncodingField setHidden: NO];
4647 [self startEndFrameValueChanged:nil];
4652 - (IBAction) chapterPopUpChanged: (id) sender
4655 /* If start chapter popup is greater than end chapter popup,
4656 we set the end chapter popup to the same as start chapter popup */
4657 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4659 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4663 hb_list_t * list = hb_get_titles( fHandle );
4664 hb_title_t * title = (hb_title_t *)
4665 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4667 hb_chapter_t * chapter;
4668 int64_t duration = 0;
4669 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4670 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4672 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4673 duration += chapter->duration;
4676 duration /= 90000; /* pts -> seconds */
4677 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4678 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4681 [self calculateBitrate: sender];
4683 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4685 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4686 [fCreateChapterMarkers setEnabled: NO];
4687 [fCreateChapterMarkers setState: NSOffState];
4691 [fCreateChapterMarkers setEnabled: YES];
4695 - (IBAction) startEndSecValueChanged: (id) sender
4698 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4699 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4700 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4703 //[self calculateBitrate: sender];
4707 - (IBAction) startEndFrameValueChanged: (id) sender
4709 hb_list_t * list = hb_get_titles( fHandle );
4710 hb_title_t * title = (hb_title_t*)
4711 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4713 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4714 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4715 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4718 //[self calculateBitrate: sender];
4722 - (IBAction) formatPopUpChanged: (id) sender
4724 NSString * string = [fDstFile2Field stringValue];
4725 int format = [fDstFormatPopUp indexOfSelectedItem];
4727 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4728 [fDstMp4LargeFileCheck setHidden: YES];
4729 [fDstMp4HttpOptFileCheck setHidden: YES];
4730 [fDstMp4iPodFileCheck setHidden: YES];
4732 /* Update the Video Codec PopUp */
4733 /* lets get the tag of the currently selected item first so we might reset it later */
4734 int selectedVidEncoderTag;
4735 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4737 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4738 [fVidEncoderPopUp removeAllItems];
4739 NSMenuItem *menuItem;
4740 /* These video encoders are available to all of our current muxers, so lets list them once here */
4741 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4742 [menuItem setTag: HB_VCODEC_FFMPEG];
4747 /*Get Default MP4 File Extension*/
4748 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4756 /* Add additional video encoders here */
4757 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4758 [menuItem setTag: HB_VCODEC_X264];
4759 /* We show the mp4 option checkboxes here since we are mp4 */
4760 [fCreateChapterMarkers setEnabled: YES];
4761 [fDstMp4LargeFileCheck setHidden: NO];
4762 [fDstMp4HttpOptFileCheck setHidden: NO];
4763 [fDstMp4iPodFileCheck setHidden: NO];
4768 /* Add additional video encoders here */
4769 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4770 [menuItem setTag: HB_VCODEC_X264];
4771 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4772 [menuItem setTag: HB_VCODEC_THEORA];
4773 /* We enable the create chapters checkbox here */
4774 [fCreateChapterMarkers setEnabled: YES];
4779 /* tell fSubtitlesDelegate we have a new video container */
4781 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4782 [fSubtitlesTable reloadData];
4783 /* if we have a previously selected vid encoder tag, then try to select it */
4784 if (selectedVidEncoderTag)
4786 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4790 [fVidEncoderPopUp selectItemAtIndex: 0];
4793 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4794 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4795 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4796 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4799 [self autoSetM4vExtension: sender];
4801 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4803 if( SuccessfulScan )
4805 /* Add/replace to the correct extension */
4806 [self audioTrackPopUpChanged: fAudLang1PopUp];
4807 [self audioTrackPopUpChanged: fAudLang2PopUp];
4808 [self audioTrackPopUpChanged: fAudLang3PopUp];
4809 [self audioTrackPopUpChanged: fAudLang4PopUp];
4811 if( [fVidEncoderPopUp selectedItem] == nil )
4814 [fVidEncoderPopUp selectItemAtIndex:0];
4815 [self videoEncoderPopUpChanged:nil];
4817 /* changing the format may mean that we can / can't offer mono or 6ch, */
4818 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4820 /* We call the method to properly enable/disable turbo 2 pass */
4821 [self twoPassCheckboxChanged: sender];
4822 /* We call method method to change UI to reflect whether a preset is used or not*/
4825 [self customSettingUsed: sender];
4828 - (IBAction) autoSetM4vExtension: (id) sender
4830 if ( [fDstFormatPopUp indexOfSelectedItem] )
4833 NSString * extension = @"mp4";
4835 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4836 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4837 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4838 [fCreateChapterMarkers state] == NSOnState ||
4839 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4844 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4847 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4848 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4851 /* Method to determine if we should change the UI
4852 To reflect whether or not a Preset is being used or if
4853 the user is using "Custom" settings by determining the sender*/
4854 - (IBAction) customSettingUsed: (id) sender
4856 if ([sender stringValue])
4858 /* Deselect the currently selected Preset if there is one*/
4859 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4860 /* Change UI to show "Custom" settings are being used */
4861 [fPresetSelectedDisplay setStringValue: @"Custom"];
4863 curUserPresetChosenNum = nil;
4865 [self calculateBitrate:nil];
4870 #pragma mark - Video
4872 - (IBAction) videoEncoderPopUpChanged: (id) sender
4874 hb_job_t * job = fTitle->job;
4875 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4877 [fAdvancedOptions setHidden:YES];
4878 /* If we are using x264 then show the x264 advanced panel*/
4879 if (videoEncoder == HB_VCODEC_X264)
4881 [fAdvancedOptions setHidden:NO];
4882 [self autoSetM4vExtension: sender];
4885 if (videoEncoder == HB_VCODEC_FFMPEG)
4887 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4888 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4889 anything other than MP4.
4891 [fDstMp4iPodFileCheck setEnabled: NO];
4892 [fDstMp4iPodFileCheck setState: NSOffState];
4896 [fDstMp4iPodFileCheck setEnabled: YES];
4898 [self setupQualitySlider];
4899 [self calculatePictureSizing: sender];
4900 [self twoPassCheckboxChanged: sender];
4904 - (IBAction) twoPassCheckboxChanged: (id) sender
4906 /* check to see if x264 is chosen */
4907 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4909 if( [fVidTwoPassCheck state] == NSOnState)
4911 [fVidTurboPassCheck setHidden: NO];
4915 [fVidTurboPassCheck setHidden: YES];
4916 [fVidTurboPassCheck setState: NSOffState];
4918 /* Make sure Two Pass is checked if Turbo is checked */
4919 if( [fVidTurboPassCheck state] == NSOnState)
4921 [fVidTwoPassCheck setState: NSOnState];
4926 [fVidTurboPassCheck setHidden: YES];
4927 [fVidTurboPassCheck setState: NSOffState];
4930 /* We call method method to change UI to reflect whether a preset is used or not*/
4931 [self customSettingUsed: sender];
4934 - (IBAction ) videoFrameRateChanged: (id) sender
4936 /* We call method method to calculatePictureSizing to error check detelecine*/
4937 [self calculatePictureSizing: sender];
4939 /* We call method method to change UI to reflect whether a preset is used or not*/
4940 [self customSettingUsed: sender];
4942 - (IBAction) videoMatrixChanged: (id) sender;
4944 bool target, bitrate, quality;
4946 target = bitrate = quality = false;
4947 if( [fVidQualityMatrix isEnabled] )
4949 switch( [fVidQualityMatrix selectedRow] )
4962 [fVidTargetSizeField setEnabled: target];
4963 [fVidBitrateField setEnabled: bitrate];
4964 [fVidQualitySlider setEnabled: quality];
4965 [fVidQualityRFField setEnabled: quality];
4966 [fVidQualityRFLabel setEnabled: quality];
4967 [fVidTwoPassCheck setEnabled: !quality &&
4968 [fVidQualityMatrix isEnabled]];
4971 [fVidTwoPassCheck setState: NSOffState];
4972 [fVidTurboPassCheck setHidden: YES];
4973 [fVidTurboPassCheck setState: NSOffState];
4976 [self qualitySliderChanged: sender];
4977 [self calculateBitrate: sender];
4978 [self customSettingUsed: sender];
4981 /* Use this method to setup the quality slider for cq/rf values depending on
4982 * the video encoder selected.
4984 - (void) setupQualitySlider
4986 /* Get the current slider maxValue to check for a change in slider scale later
4987 * so that we can choose a new similar value on the new slider scale */
4988 float previousMaxValue = [fVidQualitySlider maxValue];
4989 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4990 NSString * qpRFLabelString = @"QP:";
4992 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4994 [fVidQualitySlider setMinValue:0.0];
4995 [fVidQualitySlider setMaxValue:51.0];
4996 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4997 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4998 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4999 qpRFLabelString = @"RF:";
5002 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
5004 [fVidQualitySlider setMinValue:1.0];
5005 [fVidQualitySlider setMaxValue:31.0];
5006 [fVidQualitySlider setNumberOfTickMarks:31];
5009 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5011 [fVidQualitySlider setMinValue:0.0];
5012 [fVidQualitySlider setMaxValue:63.0];
5013 [fVidQualitySlider setNumberOfTickMarks:64];
5015 [fVidQualityRFLabel setStringValue:qpRFLabelString];
5017 /* check to see if we have changed slider scales */
5018 if (previousMaxValue != [fVidQualitySlider maxValue])
5020 /* if so, convert the old setting to the new scale as close as possible based on percentages */
5021 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
5022 [fVidQualitySlider setFloatValue:rf];
5025 [self qualitySliderChanged:nil];
5028 - (IBAction) qualitySliderChanged: (id) sender
5030 /* Our constant quality slider is in a range based
5031 * on each encoders qp/rf values. The range depends
5032 * on the encoder. Also, the range is inverse of quality
5033 * for all of the encoders *except* for theora
5034 * (ie. as the "quality" goes up, the cq or rf value
5035 * actually goes down). Since the IB sliders always set
5036 * their max value at the right end of the slider, we
5037 * will calculate the inverse, so as the slider floatValue
5038 * goes up, we will show the inverse in the rf field
5039 * so, the floatValue at the right for x264 would be 51
5040 * and our rf field needs to show 0 and vice versa.
5043 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5044 /* If the encoder is theora, use the float, otherwise use the inverse float*/
5045 //float sliderRfToPercent;
5046 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5048 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
5052 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5054 [self customSettingUsed: sender];
5057 - (void) controlTextDidChange: (NSNotification *) notification
5059 [self calculateBitrate:nil];
5062 - (IBAction) calculateBitrate: (id) sender
5064 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5069 hb_list_t * list = hb_get_titles( fHandle );
5070 hb_title_t * title = (hb_title_t *) hb_list_item( list,
5071 [fSrcTitlePopUp indexOfSelectedItem] );
5072 hb_job_t * job = title->job;
5073 hb_audio_config_t * audio;
5074 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
5075 * Target Size Field, we also need the job info for the Muxer, the Chapters
5076 * as well as all of the audio track info.
5077 * This used to be accomplished by simply calling prepareJob here, however
5078 * since the resilient queue sets the queue array values instead of the job
5079 * values directly, we duplicate the old prepareJob code here for the variables
5082 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5083 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
5084 job->mux = [[fDstFormatPopUp selectedItem] tag];
5086 /* Audio goes here */
5087 int audiotrack_count = hb_list_count(job->list_audio);
5088 for( int i = 0; i < audiotrack_count;i++)
5090 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5091 hb_list_rem(job->list_audio, temp_audio);
5093 /* Now we need our audio info here for each track if applicable */
5094 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5096 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5097 hb_audio_config_init(audio);
5098 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5099 /* We go ahead and assign values to our audio->out.<properties> */
5100 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5101 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5102 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5103 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5104 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5105 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5107 hb_audio_add( job, audio );
5110 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5112 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5113 hb_audio_config_init(audio);
5114 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5115 /* We go ahead and assign values to our audio->out.<properties> */
5116 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5117 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5118 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5119 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5120 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5121 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5123 hb_audio_add( job, audio );
5128 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5130 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5131 hb_audio_config_init(audio);
5132 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5133 /* We go ahead and assign values to our audio->out.<properties> */
5134 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5135 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5136 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5137 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5138 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5139 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5141 hb_audio_add( job, audio );
5146 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5148 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5149 hb_audio_config_init(audio);
5150 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5151 /* We go ahead and assign values to our audio->out.<properties> */
5152 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5153 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5154 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5155 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5156 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5157 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5159 hb_audio_add( job, audio );
5164 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5168 #pragma mark - Picture
5170 /* lets set the picture size back to the max from right after title scan
5171 Lets use an IBAction here as down the road we could always use a checkbox
5172 in the gui to easily take the user back to max. Remember, the compiler
5173 resolves IBActions down to -(void) during compile anyway */
5174 - (IBAction) revertPictureSizeToMax: (id) sender
5176 hb_job_t * job = fTitle->job;
5177 /* Here we apply the title source and height */
5178 job->width = fTitle->width;
5179 job->height = fTitle->height;
5181 [self calculatePictureSizing: sender];
5182 /* We call method to change UI to reflect whether a preset is used or not*/
5183 [self customSettingUsed: sender];
5187 * Registers changes made in the Picture Settings Window.
5190 - (void)pictureSettingsDidChange
5192 [self calculatePictureSizing:nil];
5195 /* Get and Display Current Pic Settings in main window */
5196 - (IBAction) calculatePictureSizing: (id) sender
5198 if (fTitle->job->anamorphic.mode > 0)
5200 fTitle->job->keep_ratio = 0;
5203 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5205 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5209 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5211 NSString *picCropping;
5212 /* Set the display field for crop as per boolean */
5213 if (![fPictureController autoCrop])
5215 picCropping = @"Custom";
5219 picCropping = @"Auto";
5221 picCropping = [picCropping stringByAppendingString:[NSString stringWithFormat:@" %d/%d/%d/%d",fTitle->job->crop[0],fTitle->job->crop[1],fTitle->job->crop[2],fTitle->job->crop[3]]];
5223 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5225 NSString *videoFilters;
5228 if ([fPictureController detelecine] == 2)
5230 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5232 else if ([fPictureController detelecine] == 1)
5234 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5238 if ([fPictureController useDecomb] == 1)
5241 if ([fPictureController decomb] == 2)
5243 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5245 else if ([fPictureController decomb] == 1)
5247 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5253 if ([fPictureController deinterlace] > 0)
5255 fTitle->job->deinterlace = 1;
5259 fTitle->job->deinterlace = 0;
5262 if ([fPictureController deinterlace] == 2)
5264 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5266 else if ([fPictureController deinterlace] == 3)
5268 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5270 else if ([fPictureController deinterlace] == 4)
5272 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5274 else if ([fPictureController deinterlace] == 1)
5276 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5282 if ([fPictureController denoise] == 2)
5284 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5286 else if ([fPictureController denoise] == 3)
5288 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5290 else if ([fPictureController denoise] == 4)
5292 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5294 else if ([fPictureController denoise] == 1)
5296 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5300 if ([fPictureController deblock] > 0)
5302 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5306 if ([fPictureController grayscale])
5308 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5310 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5312 //[fPictureController reloadStillPreview];
5317 #pragma mark - Audio and Subtitles
5318 - (IBAction) audioCodecsPopUpChanged: (id) sender
5321 NSPopUpButton * audiotrackPopUp;
5322 NSPopUpButton * sampleratePopUp;
5323 NSPopUpButton * bitratePopUp;
5324 NSPopUpButton * audiocodecPopUp;
5325 if (sender == fAudTrack1CodecPopUp)
5327 audiotrackPopUp = fAudLang1PopUp;
5328 audiocodecPopUp = fAudTrack1CodecPopUp;
5329 sampleratePopUp = fAudTrack1RatePopUp;
5330 bitratePopUp = fAudTrack1BitratePopUp;
5332 else if (sender == fAudTrack2CodecPopUp)
5334 audiotrackPopUp = fAudLang2PopUp;
5335 audiocodecPopUp = fAudTrack2CodecPopUp;
5336 sampleratePopUp = fAudTrack2RatePopUp;
5337 bitratePopUp = fAudTrack2BitratePopUp;
5339 else if (sender == fAudTrack3CodecPopUp)
5341 audiotrackPopUp = fAudLang3PopUp;
5342 audiocodecPopUp = fAudTrack3CodecPopUp;
5343 sampleratePopUp = fAudTrack3RatePopUp;
5344 bitratePopUp = fAudTrack3BitratePopUp;
5348 audiotrackPopUp = fAudLang4PopUp;
5349 audiocodecPopUp = fAudTrack4CodecPopUp;
5350 sampleratePopUp = fAudTrack4RatePopUp;
5351 bitratePopUp = fAudTrack4BitratePopUp;
5354 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5355 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5356 [self audioTrackPopUpChanged: audiotrackPopUp];
5360 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5362 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5363 * the settings of the source audio for that track. We leave the samplerate and bitrate
5364 * to audiotrackMixdownChanged
5367 /* We will first verify that a lower track number has been selected before enabling each track
5368 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5370 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5372 [fAudLang2PopUp setEnabled: NO];
5373 [fAudLang2PopUp selectItemAtIndex: 0];
5377 [fAudLang2PopUp setEnabled: YES];
5380 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5382 [fAudLang3PopUp setEnabled: NO];
5383 [fAudLang3PopUp selectItemAtIndex: 0];
5387 [fAudLang3PopUp setEnabled: YES];
5389 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5391 [fAudLang4PopUp setEnabled: NO];
5392 [fAudLang4PopUp selectItemAtIndex: 0];
5396 [fAudLang4PopUp setEnabled: YES];
5398 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5399 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5400 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5401 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5402 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5403 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5404 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5405 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5407 [fAudTrack1CodecPopUp removeAllItems];
5408 [fAudTrack1MixPopUp removeAllItems];
5409 [fAudTrack1RatePopUp removeAllItems];
5410 [fAudTrack1BitratePopUp removeAllItems];
5411 [fAudTrack1DrcSlider setFloatValue: 0.00];
5412 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5414 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5416 [fAudTrack1RatePopUp setEnabled: NO];
5417 [fAudTrack1BitratePopUp setEnabled: NO];
5418 [fAudTrack1DrcSlider setEnabled: NO];
5419 [fAudTrack1DrcField setEnabled: NO];
5422 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5423 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5424 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5425 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5426 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5427 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5428 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5429 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5431 [fAudTrack2CodecPopUp removeAllItems];
5432 [fAudTrack2MixPopUp removeAllItems];
5433 [fAudTrack2RatePopUp removeAllItems];
5434 [fAudTrack2BitratePopUp removeAllItems];
5435 [fAudTrack2DrcSlider setFloatValue: 0.00];
5436 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5438 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5440 [fAudTrack2RatePopUp setEnabled: NO];
5441 [fAudTrack2BitratePopUp setEnabled: NO];
5442 [fAudTrack2DrcSlider setEnabled: NO];
5443 [fAudTrack2DrcField setEnabled: NO];
5446 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5447 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5448 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5449 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5450 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5451 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5452 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5453 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5455 [fAudTrack3CodecPopUp removeAllItems];
5456 [fAudTrack3MixPopUp removeAllItems];
5457 [fAudTrack3RatePopUp removeAllItems];
5458 [fAudTrack3BitratePopUp removeAllItems];
5459 [fAudTrack3DrcSlider setFloatValue: 0.00];
5460 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5462 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5464 [fAudTrack3RatePopUp setEnabled: NO];
5465 [fAudTrack3BitratePopUp setEnabled: NO];
5466 [fAudTrack3DrcSlider setEnabled: NO];
5467 [fAudTrack3DrcField setEnabled: NO];
5470 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5471 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5472 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5473 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5474 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5475 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5476 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5477 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5479 [fAudTrack4CodecPopUp removeAllItems];
5480 [fAudTrack4MixPopUp removeAllItems];
5481 [fAudTrack4RatePopUp removeAllItems];
5482 [fAudTrack4BitratePopUp removeAllItems];
5483 [fAudTrack4DrcSlider setFloatValue: 0.00];
5484 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5486 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5488 [fAudTrack4RatePopUp setEnabled: NO];
5489 [fAudTrack4BitratePopUp setEnabled: NO];
5490 [fAudTrack4DrcSlider setEnabled: NO];
5491 [fAudTrack4DrcField setEnabled: NO];
5496 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5499 hb_list_t * list = hb_get_titles( fHandle );
5500 hb_title_t * title = (hb_title_t*)
5501 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5503 hb_audio_config_t * audio;
5505 [sender removeAllItems];
5506 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5507 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5509 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5510 [[sender menu] addItemWithTitle:
5511 [NSString stringWithUTF8String: audio->lang.description]
5512 action: NULL keyEquivalent: @""];
5514 [sender selectItemAtIndex: 0];
5518 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5521 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5522 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5523 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5524 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5526 if (searchPrefixString)
5529 for( int i = 0; i < [sender numberOfItems]; i++ )
5531 /* Try to find the desired search string */
5532 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5534 [sender selectItemAtIndex: i];
5538 /* couldn't find the string, so select the requested "search string not found" item */
5539 /* index of 0 means select the "none" item */
5540 /* index of 1 means select the first audio track */
5541 [sender selectItemAtIndex: selectIndexIfNotFound];
5545 /* if no search string is provided, then select the selectIndexIfNotFound item */
5546 [sender selectItemAtIndex: selectIndexIfNotFound];
5550 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5552 int format = [fDstFormatPopUp indexOfSelectedItem];
5554 /* setup pointers to the appropriate popups for the correct track */
5555 NSPopUpButton * audiocodecPopUp;
5556 NSPopUpButton * audiotrackPopUp;
5557 if (sender == fAudTrack1CodecPopUp)
5559 audiotrackPopUp = fAudLang1PopUp;
5560 audiocodecPopUp = fAudTrack1CodecPopUp;
5562 else if (sender == fAudTrack2CodecPopUp)
5564 audiotrackPopUp = fAudLang2PopUp;
5565 audiocodecPopUp = fAudTrack2CodecPopUp;
5567 else if (sender == fAudTrack3CodecPopUp)
5569 audiotrackPopUp = fAudLang3PopUp;
5570 audiocodecPopUp = fAudTrack3CodecPopUp;
5574 audiotrackPopUp = fAudLang4PopUp;
5575 audiocodecPopUp = fAudTrack4CodecPopUp;
5578 [audiocodecPopUp removeAllItems];
5579 /* Make sure "None" isnt selected in the source track */
5580 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5582 [audiocodecPopUp setEnabled:YES];
5583 NSMenuItem *menuItem;
5584 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5590 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5591 [menuItem setTag: HB_ACODEC_FAAC];
5594 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5595 [menuItem setTag: HB_ACODEC_CA_AAC];
5598 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5599 [menuItem setTag: HB_ACODEC_AC3];
5605 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5606 [menuItem setTag: HB_ACODEC_FAAC];
5608 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5609 [menuItem setTag: HB_ACODEC_CA_AAC];
5611 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5612 [menuItem setTag: HB_ACODEC_AC3];
5614 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5615 [menuItem setTag: HB_ACODEC_DCA];
5617 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5618 [menuItem setTag: HB_ACODEC_LAME];
5620 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5621 [menuItem setTag: HB_ACODEC_VORBIS];
5627 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5628 [menuItem setTag: HB_ACODEC_LAME];
5630 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5631 [menuItem setTag: HB_ACODEC_AC3];
5637 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5638 [menuItem setTag: HB_ACODEC_VORBIS];
5640 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5641 [menuItem setTag: HB_ACODEC_LAME];
5644 [audiocodecPopUp selectItemAtIndex:0];
5648 [audiocodecPopUp setEnabled:NO];
5652 - (IBAction) audioTrackPopUpChanged: (id) sender
5654 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5655 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5658 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5661 /* make sure we have a selected title before continuing */
5662 if (fTitle == NULL) return;
5663 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5664 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5666 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5668 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5670 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5672 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5674 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5676 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5678 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5680 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5683 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5684 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5686 sender = fAudLang1PopUp;
5688 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5690 sender = fAudLang2PopUp;
5692 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5694 sender = fAudLang3PopUp;
5696 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5698 sender = fAudLang4PopUp;
5701 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5702 NSPopUpButton * mixdownPopUp;
5703 NSPopUpButton * audiocodecPopUp;
5704 NSPopUpButton * sampleratePopUp;
5705 NSPopUpButton * bitratePopUp;
5706 if (sender == fAudLang1PopUp)
5708 mixdownPopUp = fAudTrack1MixPopUp;
5709 audiocodecPopUp = fAudTrack1CodecPopUp;
5710 sampleratePopUp = fAudTrack1RatePopUp;
5711 bitratePopUp = fAudTrack1BitratePopUp;
5713 else if (sender == fAudLang2PopUp)
5715 mixdownPopUp = fAudTrack2MixPopUp;
5716 audiocodecPopUp = fAudTrack2CodecPopUp;
5717 sampleratePopUp = fAudTrack2RatePopUp;
5718 bitratePopUp = fAudTrack2BitratePopUp;
5720 else if (sender == fAudLang3PopUp)
5722 mixdownPopUp = fAudTrack3MixPopUp;
5723 audiocodecPopUp = fAudTrack3CodecPopUp;
5724 sampleratePopUp = fAudTrack3RatePopUp;
5725 bitratePopUp = fAudTrack3BitratePopUp;
5729 mixdownPopUp = fAudTrack4MixPopUp;
5730 audiocodecPopUp = fAudTrack4CodecPopUp;
5731 sampleratePopUp = fAudTrack4RatePopUp;
5732 bitratePopUp = fAudTrack4BitratePopUp;
5735 /* get the index of the selected audio Track*/
5736 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5738 /* pointer for the hb_audio_s struct we will use later on */
5739 hb_audio_config_t * audio;
5742 /* check if the audio mixdown controls need their enabled state changing */
5743 [self setEnabledStateOfAudioMixdownControls:nil];
5745 if (thisAudioIndex != -1)
5749 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5751 /* actually manipulate the proper mixdowns here */
5752 /* delete the previous audio mixdown options */
5753 [mixdownPopUp removeAllItems];
5755 acodec = [[audiocodecPopUp selectedItem] tag];
5760 /* find out if our selected output audio codec supports mono and / or 6ch */
5761 /* we also check for an input codec of AC3 or DCA,
5762 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5763 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5764 but this may change in the future, so they are separated for flexibility */
5765 int audioCodecsSupportMono =
5766 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5767 (acodec != HB_ACODEC_LAME);
5768 int audioCodecsSupport6Ch =
5769 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5770 (acodec != HB_ACODEC_LAME);
5772 /* check for AC-3 passthru */
5773 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5776 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5777 [NSString stringWithUTF8String: "AC3 Passthru"]
5778 action: NULL keyEquivalent: @""];
5779 [menuItem setTag: HB_ACODEC_AC3];
5781 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5783 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5784 [NSString stringWithUTF8String: "DTS Passthru"]
5785 action: NULL keyEquivalent: @""];
5786 [menuItem setTag: HB_ACODEC_DCA];
5791 /* add the appropriate audio mixdown menuitems to the popupbutton */
5792 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5793 so that we can reference the mixdown later */
5795 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5796 int minMixdownUsed = 0;
5797 int maxMixdownUsed = 0;
5799 /* get the input channel layout without any lfe channels */
5800 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5802 /* do we want to add a mono option? */
5803 if (audioCodecsSupportMono == 1)
5805 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5806 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5807 action: NULL keyEquivalent: @""];
5808 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5809 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5810 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5813 /* do we want to add a stereo option? */
5814 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5815 /* also offer stereo if we have a stereo-or-better source */
5816 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5818 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5819 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5820 action: NULL keyEquivalent: @""];
5821 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5822 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5823 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5826 /* do we want to add a dolby surround (DPL1) option? */
5827 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5829 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5830 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5831 action: NULL keyEquivalent: @""];
5832 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5833 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5834 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5837 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5838 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5840 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5841 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5842 action: NULL keyEquivalent: @""];
5843 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5844 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5845 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5848 /* do we want to add a 6-channel discrete option? */
5849 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5851 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5852 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5853 action: NULL keyEquivalent: @""];
5854 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5855 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5856 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5859 /* do we want to add an AC-3 passthrough option? */
5860 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5862 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5863 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5864 action: NULL keyEquivalent: @""];
5865 [menuItem setTag: HB_ACODEC_AC3];
5866 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5867 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5870 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5871 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5873 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5874 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5875 action: NULL keyEquivalent: @""];
5876 [menuItem setTag: HB_ACODEC_DCA];
5877 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5878 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5881 /* auto-select the best mixdown based on our saved mixdown preference */
5883 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5884 /* ultimately this should be a prefs option */
5887 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5888 if (mixdownToUse > 0)
5890 useMixdown = mixdownToUse;
5894 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5897 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5898 if (useMixdown > maxMixdownUsed)
5900 useMixdown = maxMixdownUsed;
5903 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5904 if (useMixdown < minMixdownUsed)
5906 useMixdown = minMixdownUsed;
5909 /* select the (possibly-amended) preferred mixdown */
5910 [mixdownPopUp selectItemWithTag: useMixdown];
5913 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5914 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5917 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5919 /* If we are using the avi container, we select MP3 as there is no aac available*/
5920 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5922 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5926 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5930 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5931 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5934 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5936 /* If we are using the avi container, we select MP3 as there is no aac available*/
5937 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5939 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5943 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5947 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5948 [self audioTrackMixdownChanged: mixdownPopUp];
5952 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5954 [self autoSetM4vExtension: sender];
5958 - (IBAction) audioTrackMixdownChanged: (id) sender
5962 /* setup pointers to all of the other audio track controls
5963 * we will need later
5965 NSPopUpButton * mixdownPopUp;
5966 NSPopUpButton * sampleratePopUp;
5967 NSPopUpButton * bitratePopUp;
5968 NSPopUpButton * audiocodecPopUp;
5969 NSPopUpButton * audiotrackPopUp;
5970 NSSlider * drcSlider;
5971 NSTextField * drcField;
5972 if (sender == fAudTrack1MixPopUp)
5974 audiotrackPopUp = fAudLang1PopUp;
5975 audiocodecPopUp = fAudTrack1CodecPopUp;
5976 mixdownPopUp = fAudTrack1MixPopUp;
5977 sampleratePopUp = fAudTrack1RatePopUp;
5978 bitratePopUp = fAudTrack1BitratePopUp;
5979 drcSlider = fAudTrack1DrcSlider;
5980 drcField = fAudTrack1DrcField;
5982 else if (sender == fAudTrack2MixPopUp)
5984 audiotrackPopUp = fAudLang2PopUp;
5985 audiocodecPopUp = fAudTrack2CodecPopUp;
5986 mixdownPopUp = fAudTrack2MixPopUp;
5987 sampleratePopUp = fAudTrack2RatePopUp;
5988 bitratePopUp = fAudTrack2BitratePopUp;
5989 drcSlider = fAudTrack2DrcSlider;
5990 drcField = fAudTrack2DrcField;
5992 else if (sender == fAudTrack3MixPopUp)
5994 audiotrackPopUp = fAudLang3PopUp;
5995 audiocodecPopUp = fAudTrack3CodecPopUp;
5996 mixdownPopUp = fAudTrack3MixPopUp;
5997 sampleratePopUp = fAudTrack3RatePopUp;
5998 bitratePopUp = fAudTrack3BitratePopUp;
5999 drcSlider = fAudTrack3DrcSlider;
6000 drcField = fAudTrack3DrcField;
6004 audiotrackPopUp = fAudLang4PopUp;
6005 audiocodecPopUp = fAudTrack4CodecPopUp;
6006 mixdownPopUp = fAudTrack4MixPopUp;
6007 sampleratePopUp = fAudTrack4RatePopUp;
6008 bitratePopUp = fAudTrack4BitratePopUp;
6009 drcSlider = fAudTrack4DrcSlider;
6010 drcField = fAudTrack4DrcField;
6012 acodec = [[audiocodecPopUp selectedItem] tag];
6013 /* storage variable for the min and max bitrate allowed for this codec */
6019 case HB_ACODEC_FAAC:
6020 /* check if we have a 6ch discrete conversion in either audio track */
6021 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6023 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
6025 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
6031 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
6033 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
6034 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
6039 case HB_ACODEC_CA_AAC:
6040 /* check if we have a 6ch discrete conversion in either audio track */
6041 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6054 case HB_ACODEC_LAME:
6055 /* Lame is happy using our min bitrate of 32 kbps */
6057 /* Lame won't encode if the bitrate is higher than 320 kbps */
6061 case HB_ACODEC_VORBIS:
6062 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6064 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6066 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6072 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6074 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6080 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6086 /* make sure we have a selected title before continuing */
6087 if (fTitle == NULL) return;
6088 /* get the audio so we can find out what input rates are*/
6089 hb_audio_config_t * audio;
6090 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6091 int inputbitrate = audio->in.bitrate / 1000;
6092 int inputsamplerate = audio->in.samplerate;
6094 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6096 [bitratePopUp removeAllItems];
6098 for( int i = 0; i < hb_audio_bitrates_count; i++ )
6100 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6102 /* add a new menuitem for this bitrate */
6103 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6104 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6105 action: NULL keyEquivalent: @""];
6106 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6107 [menuItem setTag: hb_audio_bitrates[i].rate];
6111 /* select the default bitrate (but use 384 for 6-ch AAC) */
6112 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6114 [bitratePopUp selectItemWithTag: 384];
6118 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6121 /* populate and set the sample rate popup */
6122 /* Audio samplerate */
6123 [sampleratePopUp removeAllItems];
6124 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6125 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6126 [menuItem setTag: inputsamplerate];
6128 for( int i = 0; i < hb_audio_rates_count; i++ )
6130 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6131 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6132 action: NULL keyEquivalent: @""];
6133 [menuItem setTag: hb_audio_rates[i].rate];
6135 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6136 * and there is no compelling reason to use anything else as default, though the users default
6137 * preset will likely override any setting chosen here.
6139 [sampleratePopUp selectItemWithTag: inputsamplerate];
6142 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6143 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6144 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6146 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6149 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6150 [bitratePopUp removeAllItems];
6151 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6152 [NSString stringWithFormat:@"%d", inputbitrate]
6153 action: NULL keyEquivalent: @""];
6154 [menuItem setTag: inputbitrate];
6155 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6156 [bitratePopUp setEnabled: NO];
6157 [sampleratePopUp setEnabled: NO];
6159 [drcSlider setFloatValue: 0.00];
6160 [self audioDRCSliderChanged: drcSlider];
6161 [drcSlider setEnabled: NO];
6162 [drcField setEnabled: NO];
6166 [sampleratePopUp setEnabled: YES];
6167 [bitratePopUp setEnabled: YES];
6168 [drcSlider setEnabled: YES];
6169 [drcField setEnabled: YES];
6171 [self calculateBitrate:nil];
6174 - (IBAction) audioDRCSliderChanged: (id) sender
6176 NSSlider * drcSlider;
6177 NSTextField * drcField;
6178 if (sender == fAudTrack1DrcSlider)
6180 drcSlider = fAudTrack1DrcSlider;
6181 drcField = fAudTrack1DrcField;
6183 else if (sender == fAudTrack2DrcSlider)
6185 drcSlider = fAudTrack2DrcSlider;
6186 drcField = fAudTrack2DrcField;
6188 else if (sender == fAudTrack3DrcSlider)
6190 drcSlider = fAudTrack3DrcSlider;
6191 drcField = fAudTrack3DrcField;
6195 drcSlider = fAudTrack4DrcSlider;
6196 drcField = fAudTrack4DrcField;
6199 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6200 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6202 [drcSlider setFloatValue:1.0];
6206 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6207 /* For now, do not call this until we have an intelligent way to determine audio track selections
6208 * compared to presets
6210 //[self customSettingUsed: sender];
6215 - (IBAction) browseImportSrtFile: (id) sender
6218 NSOpenPanel * panel;
6220 panel = [NSOpenPanel openPanel];
6221 [panel setAllowsMultipleSelection: NO];
6222 [panel setCanChooseFiles: YES];
6223 [panel setCanChooseDirectories: NO ];
6224 NSString * sourceDirectory;
6225 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6227 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6231 sourceDirectory = @"~/Desktop";
6232 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6234 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6235 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6236 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6237 modalForWindow: fWindow modalDelegate: self
6238 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6239 contextInfo: sender];
6242 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6243 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6245 if( returnCode == NSOKButton )
6247 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6248 NSString *importSrtFilePath = [sheet filename];
6249 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6251 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6252 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6254 [fSubtitlesTable reloadData];
6260 #pragma mark Open New Windows
6262 - (IBAction) openHomepage: (id) sender
6264 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6265 URLWithString:@"http://handbrake.fr/"]];
6268 - (IBAction) openForums: (id) sender
6270 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6271 URLWithString:@"http://handbrake.fr/forum/"]];
6273 - (IBAction) openUserGuide: (id) sender
6275 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6276 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6280 * Shows debug output window.
6282 - (IBAction)showDebugOutputPanel:(id)sender
6284 [outputPanel showOutputPanel:sender];
6288 * Shows preferences window.
6290 - (IBAction) showPreferencesWindow: (id) sender
6292 NSWindow * window = [fPreferencesController window];
6293 if (![window isVisible])
6296 [window makeKeyAndOrderFront: nil];
6300 * Shows queue window.
6302 - (IBAction) showQueueWindow:(id)sender
6304 [fQueueController showQueueWindow:sender];
6308 - (IBAction) toggleDrawer:(id)sender {
6309 [fPresetDrawer toggle:self];
6313 * Shows Picture Settings Window.
6316 - (IBAction) showPicturePanel: (id) sender
6318 [fPictureController showPictureWindow:sender];
6321 - (void) picturePanelFullScreen
6323 [fPictureController setToFullScreenMode];
6326 - (void) picturePanelWindowed
6328 [fPictureController setToWindowedMode];
6331 - (IBAction) showPreviewWindow: (id) sender
6333 [fPictureController showPreviewWindow:sender];
6337 #pragma mark Preset Outline View Methods
6338 #pragma mark - Required
6339 /* These are required by the NSOutlineView Datasource Delegate */
6342 /* used to specify the number of levels to show for each item */
6343 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6345 /* currently use no levels to test outline view viability */
6346 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6348 return [UserPresets count];
6352 /* we need to return the count of the array in ChildrenArray for this folder */
6353 NSArray *children = nil;
6354 children = [item objectForKey:@"ChildrenArray"];
6355 if ([children count] > 0)
6357 return [children count];
6366 /* We use this to deterimine children of an item */
6367 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6370 /* we need to return the count of the array in ChildrenArray for this folder */
6371 NSArray *children = nil;
6374 children = UserPresets;
6378 if ([item objectForKey:@"ChildrenArray"])
6380 children = [item objectForKey:@"ChildrenArray"];
6383 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6389 return [children objectAtIndex:index];
6393 // We are only one level deep, so we can't be asked about children
6394 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6398 /* We use this to determine if an item should be expandable */
6399 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6402 /* we need to return the count of the array in ChildrenArray for this folder */
6403 NSArray *children= nil;
6406 children = UserPresets;
6410 if ([item objectForKey:@"ChildrenArray"])
6412 children = [item objectForKey:@"ChildrenArray"];
6416 /* To deterimine if an item should show a disclosure triangle
6417 * we could do it by the children count as so:
6418 * if ([children count] < 1)
6419 * However, lets leave the triangle show even if there are no
6420 * children to help indicate a folder, just like folder in the
6421 * finder can show a disclosure triangle even when empty
6424 /* We need to determine if the item is a folder */
6425 if ([[item objectForKey:@"Folder"] intValue] == 1)
6436 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6438 // Our outline view has no levels, but we can still expand every item. Doing so
6439 // just makes the row taller. See heightOfRowByItem below.
6440 //return ![(HBQueueOutlineView*)outlineView isDragging];
6446 /* Used to tell the outline view which information is to be displayed per item */
6447 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6449 /* We have two columns right now, icon and PresetName */
6451 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6453 return [item objectForKey:@"PresetName"];
6462 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6464 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6466 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6468 return [NSKeyedArchiver archivedDataWithRootObject:item];
6471 #pragma mark - Added Functionality (optional)
6472 /* Use to customize the font and display characteristics of the title cell */
6473 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6475 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6479 NSColor *shadowColor;
6480 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6481 /*check to see if its a selected row */
6482 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6485 fontColor = [NSColor blackColor];
6486 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6490 if ([[item objectForKey:@"Type"] intValue] == 0)
6492 fontColor = [NSColor blueColor];
6494 else // User created preset, use a black font
6496 fontColor = [NSColor blackColor];
6498 /* check to see if its a folder */
6499 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6501 //fontColor = [NSColor greenColor];
6506 /* We use Bold Text for the HB Default */
6507 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6509 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6511 /* We use Bold Text for the User Specified Default */
6512 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6514 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6518 [cell setTextColor:fontColor];
6519 [cell setFont:txtFont];
6524 /* We use this to edit the name field in the outline view */
6525 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6527 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6532 [theRecord setObject:object forKey:@"PresetName"];
6536 [fPresetsOutlineView reloadData];
6537 /* We save all of the preset data here */
6541 /* We use this to provide tooltips for the items in the presets outline view */
6542 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6544 //if ([[tc identifier] isEqualToString:@"PresetName"])
6546 /* initialize the tooltip contents variable */
6548 /* if there is a description for the preset, we show it in the tooltip */
6549 if ([item objectForKey:@"PresetDescription"])
6551 loc_tip = [item objectForKey:@"PresetDescription"];
6556 loc_tip = @"No description available";
6563 #pragma mark Preset Outline View Methods (dragging related)
6566 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6568 // Dragging is only allowed for custom presets.
6569 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6570 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6574 // Don't retain since this is just holding temporaral drag information, and it is
6575 //only used during a drag! We could put this in the pboard actually.
6576 fDraggedNodes = items;
6577 // Provide data for our custom type, and simple NSStrings.
6578 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6580 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6581 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6586 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6589 // Don't allow dropping ONTO an item since they can't really contain any children.
6591 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6592 if (isOnDropTypeProposal)
6593 return NSDragOperationNone;
6595 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6598 index = [fPresetsOutlineView rowForItem: item] + 1;
6602 // Don't allow dropping into the Built In Presets.
6603 if (index < presetCurrentBuiltInCount)
6605 return NSDragOperationNone;
6606 index = MAX (index, presetCurrentBuiltInCount);
6609 [outlineView setDropItem:item dropChildIndex:index];
6610 return NSDragOperationGeneric;
6615 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6617 /* first, lets see if we are dropping into a folder */
6618 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6620 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6621 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6622 [childrenArray addObject:item];
6623 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6624 [childrenArray autorelease];
6626 else // We are not, so we just move the preset into the existing array
6628 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6630 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6631 while (obj = [enumerator nextObject])
6633 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6635 // Successful drop, lets rearrange the view and save it all
6636 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6638 [fPresetsOutlineView reloadData];
6643 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6645 NSUInteger index = [indexSet lastIndex];
6646 NSUInteger aboveInsertIndexCount = 0;
6648 NSUInteger removeIndex;
6650 if (index >= insertIndex)
6652 removeIndex = index + aboveInsertIndexCount;
6653 aboveInsertIndexCount++;
6657 removeIndex = index;
6661 id object = [[array objectAtIndex:removeIndex] retain];
6662 [array removeObjectAtIndex:removeIndex];
6663 [array insertObject:object atIndex:insertIndex];
6666 index = [indexSet indexLessThanIndex:index];
6671 #pragma mark - Functional Preset NSOutlineView Methods
6673 - (IBAction)selectPreset:(id)sender
6676 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6678 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6679 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6681 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6683 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6687 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6691 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6692 [self formatPopUpChanged:nil];
6694 /* Chapter Markers*/
6695 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6696 /* check to see if we have only one chapter */
6697 [self chapterPopUpChanged:nil];
6699 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6700 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6701 /* Mux mp4 with http optimization */
6702 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6705 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6706 /* We set the advanced opt string here if applicable*/
6707 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6709 /* Lets run through the following functions to get variables set there */
6710 [self videoEncoderPopUpChanged:nil];
6711 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6712 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6713 [self calculateBitrate:nil];
6716 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6718 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6719 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6721 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6722 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6723 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6724 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6725 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6726 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6728 /* For the quality slider we need to convert the old percent's to the new rf scales */
6729 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6730 [fVidQualitySlider setFloatValue:rf];
6735 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6736 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6738 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6742 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6743 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6747 [self videoMatrixChanged:nil];
6749 /* Video framerate */
6750 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6751 detected framerate in the fVidRatePopUp so we use index 0*/
6752 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6754 [fVidRatePopUp selectItemAtIndex: 0];
6758 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6762 /* 2 Pass Encoding */
6763 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6764 [self twoPassCheckboxChanged:nil];
6766 /* Turbo 1st pass for 2 Pass Encoding */
6767 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6770 /* First we check to see if we are using the current audio track layout based on AudioList array */
6771 if ([chosenPreset objectForKey:@"AudioList"])
6774 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6775 NSPopUpButton * trackLangPopUp = nil;
6776 NSPopUpButton * mixdownPopUp = nil;
6777 NSPopUpButton * audiocodecPopUp = nil;
6778 NSPopUpButton * sampleratePopUp = nil;
6779 NSPopUpButton * bitratePopUp = nil;
6780 NSSlider * drcSlider = nil;
6783 /* Populate the audio widgets based on the contents of the AudioList array */
6785 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6787 while (tempObject = [enumerator nextObject])
6792 trackLangPopUp = fAudLang1PopUp;
6793 mixdownPopUp = fAudTrack1MixPopUp;
6794 audiocodecPopUp = fAudTrack1CodecPopUp;
6795 sampleratePopUp = fAudTrack1RatePopUp;
6796 bitratePopUp = fAudTrack1BitratePopUp;
6797 drcSlider = fAudTrack1DrcSlider;
6801 trackLangPopUp = fAudLang2PopUp;
6802 mixdownPopUp = fAudTrack2MixPopUp;
6803 audiocodecPopUp = fAudTrack2CodecPopUp;
6804 sampleratePopUp = fAudTrack2RatePopUp;
6805 bitratePopUp = fAudTrack2BitratePopUp;
6806 drcSlider = fAudTrack2DrcSlider;
6810 trackLangPopUp = fAudLang3PopUp;
6811 mixdownPopUp = fAudTrack3MixPopUp;
6812 audiocodecPopUp = fAudTrack3CodecPopUp;
6813 sampleratePopUp = fAudTrack3RatePopUp;
6814 bitratePopUp = fAudTrack3BitratePopUp;
6815 drcSlider = fAudTrack3DrcSlider;
6819 trackLangPopUp = fAudLang4PopUp;
6820 mixdownPopUp = fAudTrack4MixPopUp;
6821 audiocodecPopUp = fAudTrack4CodecPopUp;
6822 sampleratePopUp = fAudTrack4RatePopUp;
6823 bitratePopUp = fAudTrack4BitratePopUp;
6824 drcSlider = fAudTrack4DrcSlider;
6828 if ([trackLangPopUp indexOfSelectedItem] == 0)
6830 [trackLangPopUp selectItemAtIndex: 1];
6832 [self audioTrackPopUpChanged: trackLangPopUp];
6833 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6834 /* check our pref for core audio and use it in place of faac if applicable */
6835 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6836 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6838 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6841 [self audioTrackPopUpChanged: audiocodecPopUp];
6842 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6843 [self audioTrackMixdownChanged: mixdownPopUp];
6844 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6846 if ([mixdownPopUp selectedItem] == nil)
6848 [self audioTrackPopUpChanged: audiocodecPopUp];
6849 [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6851 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6852 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6853 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6855 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6856 /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6857 *default mixdown bitrate*/
6858 if ([bitratePopUp selectedItem] == nil)
6860 [self audioTrackMixdownChanged: mixdownPopUp];
6863 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6864 [self audioDRCSliderChanged: drcSlider];
6867 /* 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,
6868 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6872 /* 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". */
6873 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6875 hb_audio_config_t * audio;
6876 /* get the audio source audio codec */
6877 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6878 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6879 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6881 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6882 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6884 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6886 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6888 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6890 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6891 [trackLangPopUp selectItemAtIndex: 0];
6892 [self audioTrackPopUpChanged: trackLangPopUp];
6898 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6902 [fAudLang4PopUp selectItemAtIndex: 0];
6903 [self audioTrackPopUpChanged: fAudLang4PopUp];
6907 [fAudLang3PopUp selectItemAtIndex: 0];
6908 [self audioTrackPopUpChanged: fAudLang3PopUp];
6912 [fAudLang2PopUp selectItemAtIndex: 0];
6913 [self audioTrackPopUpChanged: fAudLang2PopUp];
6921 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6923 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6925 [fAudLang1PopUp selectItemAtIndex: 1];
6927 [self audioTrackPopUpChanged: fAudLang1PopUp];
6928 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6929 /* check our pref for core audio and use it in place of faac if applicable */
6930 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6931 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6933 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6935 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6936 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6937 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6939 if ([fAudTrack1MixPopUp selectedItem] == nil)
6941 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6943 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6944 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6945 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6947 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6949 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6950 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6953 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6955 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6957 [fAudLang2PopUp selectItemAtIndex: 1];
6959 [self audioTrackPopUpChanged: fAudLang2PopUp];
6960 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6961 /* check our pref for core audio and use it in place of faac if applicable */
6962 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6963 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6965 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6967 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6968 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6969 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6971 if ([fAudTrack2MixPopUp selectedItem] == nil)
6973 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6975 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6976 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6977 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6979 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6981 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6982 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6984 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6986 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6988 [fAudLang3PopUp selectItemAtIndex: 1];
6990 [self audioTrackPopUpChanged: fAudLang3PopUp];
6991 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6992 /* check our pref for core audio and use it in place of faac if applicable */
6993 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6994 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6996 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6998 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6999 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
7000 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7002 if ([fAudTrack3MixPopUp selectedItem] == nil)
7004 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
7006 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
7007 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7008 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
7010 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
7012 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
7013 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
7015 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
7017 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
7019 [fAudLang4PopUp selectItemAtIndex: 1];
7021 [self audioTrackPopUpChanged: fAudLang4PopUp];
7022 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
7023 /* check our pref for core audio and use it in place of faac if applicable */
7024 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
7025 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
7027 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
7029 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7030 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
7031 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7033 if ([fAudTrack4MixPopUp selectedItem] == nil)
7035 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7037 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7038 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7039 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7041 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7043 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7044 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7047 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7049 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7051 [fAudLang2PopUp selectItemAtIndex: 0];
7052 [self audioTrackPopUpChanged: fAudLang2PopUp];
7054 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7056 [fAudLang3PopUp selectItemAtIndex: 0];
7057 [self audioTrackPopUpChanged: fAudLang3PopUp];
7059 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7061 [fAudLang4PopUp selectItemAtIndex: 0];
7062 [self audioTrackPopUpChanged: fAudLang4PopUp];
7067 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7068 /* Forced Subtitles */
7069 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7071 /* Picture Settings */
7072 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7073 * height, width, keep ar, anamorphic and crop settings.
7074 * picture filters are handled separately below.
7076 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
7077 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
7078 * preset completely ignores any picture sizing values in the preset.
7080 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
7082 hb_job_t * job = fTitle->job;
7084 /* If Cropping is set to custom, then recall all four crop values from
7085 when the preset was created and apply them */
7086 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
7088 [fPictureController setAutoCrop:NO];
7090 /* Here we use the custom crop values saved at the time the preset was saved */
7091 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
7092 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
7093 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
7094 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
7097 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7099 [fPictureController setAutoCrop:YES];
7100 /* Here we use the auto crop values determined right after scan */
7101 job->crop[0] = AutoCropTop;
7102 job->crop[1] = AutoCropBottom;
7103 job->crop[2] = AutoCropLeft;
7104 job->crop[3] = AutoCropRight;
7109 if ([chosenPreset objectForKey:@"PictureModulus"])
7111 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
7118 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7119 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
7121 /* Use Max Picture settings for whatever the dvd is.*/
7122 [self revertPictureSizeToMax:nil];
7123 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7124 if (job->keep_ratio == 1)
7126 hb_fix_aspect( job, HB_KEEP_WIDTH );
7127 if( job->height > fTitle->height )
7129 job->height = fTitle->height;
7130 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7133 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7135 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7137 /* we check to make sure the presets width/height does not exceed the sources width/height */
7138 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
7140 /* if so, then we use the sources height and width to avoid scaling up */
7141 //job->width = fTitle->width;
7142 //job->height = fTitle->height;
7143 [self revertPictureSizeToMax:nil];
7145 else // source width/height is >= the preset height/width
7147 /* we can go ahead and use the presets values for height and width */
7148 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
7149 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
7151 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7152 if (job->keep_ratio == 1)
7154 hb_fix_aspect( job, HB_KEEP_WIDTH );
7155 if( job->height > fTitle->height )
7157 job->height = fTitle->height;
7158 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7161 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7167 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7168 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7172 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7173 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7174 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7177 [fPictureController setUseDecomb:1];
7178 [fPictureController setDecomb:0];
7179 [fPictureController setDeinterlace:0];
7180 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7182 /* we are using decomb */
7184 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7186 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7188 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7189 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7191 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7197 /* We are using Deinterlace */
7199 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7201 [fPictureController setUseDecomb:0];
7202 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7203 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7204 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7206 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7213 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7215 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7216 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7217 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7219 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7224 [fPictureController setDetelecine:0];
7228 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7230 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7231 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7232 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7234 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7239 [fPictureController setDenoise:0];
7243 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7245 /* if its a one, then its the old on/off deblock, set on to 5*/
7246 [fPictureController setDeblock:5];
7250 /* use the settings intValue */
7251 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7254 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7256 [fPictureController setGrayscale:1];
7260 [fPictureController setGrayscale:0];
7263 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7264 [fPictureController SetTitle:fTitle];
7265 [fPictureController SetTitle:fTitle];
7266 [self calculatePictureSizing:nil];
7272 #pragma mark Manage Presets
7274 - (void) loadPresets {
7275 /* We declare the default NSFileManager into fileManager */
7276 NSFileManager * fileManager = [NSFileManager defaultManager];
7277 /*We define the location of the user presets file */
7278 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7279 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7280 /* We check for the presets.plist */
7281 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7283 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7286 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7287 if (nil == UserPresets)
7289 UserPresets = [[NSMutableArray alloc] init];
7290 [self addFactoryPresets:nil];
7292 [fPresetsOutlineView reloadData];
7294 [self checkBuiltInsForUpdates];
7297 - (void) checkBuiltInsForUpdates {
7299 BOOL updateBuiltInPresets = NO;
7301 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7303 while (tempObject = [enumerator nextObject])
7305 /* iterate through the built in presets to see if any have an old build number */
7306 NSMutableDictionary *thisPresetDict = tempObject;
7307 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7308 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7310 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7312 updateBuiltInPresets = YES;
7317 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7318 if ( updateBuiltInPresets == YES)
7320 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7322 /* Show an alert window that built in presets will be updated */
7323 /*On Screen Notification*/
7326 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7327 [NSApp requestUserAttention:NSCriticalRequest];
7329 /* when alert is dismissed, go ahead and update the built in presets */
7330 [self addFactoryPresets:nil];
7336 - (IBAction) showAddPresetPanel: (id) sender
7338 /* Deselect the currently selected Preset if there is one*/
7339 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7341 /* Populate the preset picture settings popup here */
7342 [fPresetNewPicSettingsPopUp removeAllItems];
7343 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7344 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7345 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7346 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7347 /* Uncheck the preset use filters checkbox */
7348 [fPresetNewPicFiltersCheck setState:NSOffState];
7349 // fPresetNewFolderCheck
7350 [fPresetNewFolderCheck setState:NSOffState];
7351 /* Erase info from the input fields*/
7352 [fPresetNewName setStringValue: @""];
7353 [fPresetNewDesc setStringValue: @""];
7354 /* Show the panel */
7355 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7358 - (IBAction) closeAddPresetPanel: (id) sender
7360 [NSApp endSheet: fAddPresetPanel];
7361 [fAddPresetPanel orderOut: self];
7364 - (IBAction)addUserPreset:(id)sender
7366 if (![[fPresetNewName stringValue] length])
7367 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7370 /* Here we create a custom user preset */
7371 [UserPresets addObject:[self createPreset]];
7374 [self closeAddPresetPanel:nil];
7381 /* We Reload the New Table data for presets */
7382 [fPresetsOutlineView reloadData];
7383 /* We save all of the preset data here */
7391 /* We Sort the Presets By Factory or Custom */
7392 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7393 ascending:YES] autorelease];
7394 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7396 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7397 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7398 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7401 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7402 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7403 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7404 [UserPresets setArray:sortedArray];
7409 - (IBAction)insertPreset:(id)sender
7411 int index = [fPresetsOutlineView selectedRow];
7412 [UserPresets insertObject:[self createPreset] atIndex:index];
7413 [fPresetsOutlineView reloadData];
7417 - (NSDictionary *)createPreset
7419 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7420 /* Preset build number */
7421 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7422 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7423 /* Get the New Preset Name from the field in the AddPresetPanel */
7424 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7425 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7426 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7427 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7428 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7429 /*Set whether or not this is default, at creation set to 0*/
7430 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7431 if ([fPresetNewFolderCheck state] == YES)
7433 /* initialize and set an empty array for children here since we are a new folder */
7434 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7435 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7436 [childrenArray autorelease];
7438 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7440 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7441 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7442 /* Get whether or not to use the current Picture Filter settings for the preset */
7443 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7445 /* Get New Preset Description from the field in the AddPresetPanel*/
7446 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7448 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7449 /* Chapter Markers fCreateChapterMarkers*/
7450 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7451 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7452 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7453 /* Mux mp4 with http optimization */
7454 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7455 /* Add iPod uuid atom */
7456 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7460 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7461 /* x264 Option String */
7462 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7464 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7465 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7466 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7467 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7469 /* Video framerate */
7470 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7472 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7474 else // we can record the actual titleOfSelectedItem
7476 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7479 /* 2 Pass Encoding */
7480 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7481 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7482 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7483 /*Picture Settings*/
7484 hb_job_t * job = fTitle->job;
7485 /* Picture Sizing */
7486 /* Use Max Picture settings for whatever the dvd is.*/
7487 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7488 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7489 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7490 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7491 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7492 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7494 /* Set crop settings here */
7495 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7496 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7497 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7498 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7499 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7501 /* Picture Filters */
7502 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7503 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7504 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7505 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7506 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7507 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7508 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7509 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7510 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7511 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7512 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7515 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7516 /* we actually call the methods for the nests here */
7517 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7519 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7520 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7521 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7522 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7523 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7524 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7525 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7526 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7527 [audioTrack1Array autorelease];
7528 [audioListArray addObject:audioTrack1Array];
7531 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7533 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7534 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7535 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7536 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7537 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7538 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7539 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7540 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7541 [audioTrack2Array autorelease];
7542 [audioListArray addObject:audioTrack2Array];
7545 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7547 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7548 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7549 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7550 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7551 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7552 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7553 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7554 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7555 [audioTrack3Array autorelease];
7556 [audioListArray addObject:audioTrack3Array];
7559 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7561 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7562 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7563 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7564 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7565 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7566 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7567 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7568 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7569 [audioTrack4Array autorelease];
7570 [audioListArray addObject:audioTrack4Array];
7574 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7577 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7578 * subititle array code. */
7580 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7581 /* Forced Subtitles */
7582 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7584 [preset autorelease];
7591 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7592 /* We get the default preset in case it changed */
7593 [self getDefaultPresets:nil];
7597 - (IBAction)deletePreset:(id)sender
7601 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7605 /* Alert user before deleting preset */
7607 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7609 if ( status == NSAlertDefaultReturn )
7611 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7612 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7613 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7615 NSEnumerator *enumerator;
7616 NSMutableArray *presetsArrayToMod;
7617 NSMutableArray *tempArray;
7619 /* If we are a root level preset, we are modding the UserPresets array */
7620 if (presetToModLevel == 0)
7622 presetsArrayToMod = UserPresets;
7624 else // We have a parent preset, so we modify the chidren array object for key
7626 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7629 enumerator = [presetsArrayToMod objectEnumerator];
7630 tempArray = [NSMutableArray array];
7632 while (tempObject = [enumerator nextObject])
7634 NSDictionary *thisPresetDict = tempObject;
7635 if (thisPresetDict == presetToMod)
7637 [tempArray addObject:tempObject];
7641 [presetsArrayToMod removeObjectsInArray:tempArray];
7642 [fPresetsOutlineView reloadData];
7649 #pragma mark Import Export Preset(s)
7651 - (IBAction) browseExportPresetFile: (id) sender
7653 /* Open a panel to let the user choose where and how to save the export file */
7654 NSSavePanel * panel = [NSSavePanel savePanel];
7655 /* We get the current file name and path from the destination field here */
7656 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7658 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7659 modalForWindow: fWindow modalDelegate: self
7660 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7664 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7665 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7667 if( returnCode == NSOKButton )
7669 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7670 NSString *exportPresetsFile = [sheet filename];
7671 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7672 /* We check for the presets.plist */
7673 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7675 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7677 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7678 if (nil == presetsToExport)
7680 presetsToExport = [[NSMutableArray alloc] init];
7682 /* now get and add selected presets to export */
7685 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7687 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7688 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7696 - (IBAction) browseImportPresetFile: (id) sender
7699 NSOpenPanel * panel;
7701 panel = [NSOpenPanel openPanel];
7702 [panel setAllowsMultipleSelection: NO];
7703 [panel setCanChooseFiles: YES];
7704 [panel setCanChooseDirectories: NO ];
7705 NSString * sourceDirectory;
7706 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7708 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7712 sourceDirectory = @"~/Desktop";
7713 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7715 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7716 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7718 /* set this for allowed file types, not sure if we should allow xml or not */
7719 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7720 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7721 modalForWindow: fWindow modalDelegate: self
7722 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7723 contextInfo: sender];
7726 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7727 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7729 if( returnCode == NSOKButton )
7731 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7732 NSString *importPresetsFile = [sheet filename];
7733 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7734 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7735 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7736 /* iterate though the new array of presets to import and add them to our presets array */
7738 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7740 while (tempObject = [enumerator nextObject])
7742 /* make any changes to the incoming preset we see fit */
7743 /* make sure the incoming preset is not tagged as default */
7744 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7745 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7746 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7747 [tempObject setObject:prependedName forKey:@"PresetName"];
7749 /* actually add the new preset to our presets array */
7750 [UserPresets addObject:tempObject];
7753 [presetsToImport autorelease];
7761 #pragma mark Manage Default Preset
7763 - (IBAction)getDefaultPresets:(id)sender
7765 presetHbDefault = nil;
7766 presetUserDefault = nil;
7767 presetUserDefaultParent = nil;
7768 presetUserDefaultParentParent = nil;
7769 NSMutableDictionary *presetHbDefaultParent = nil;
7770 NSMutableDictionary *presetHbDefaultParentParent = nil;
7773 BOOL userDefaultFound = NO;
7774 presetCurrentBuiltInCount = 0;
7775 /* First we iterate through the root UserPresets array to check for defaults */
7776 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7778 while (tempObject = [enumerator nextObject])
7780 NSMutableDictionary *thisPresetDict = tempObject;
7781 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7783 presetHbDefault = thisPresetDict;
7785 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7787 presetUserDefault = thisPresetDict;
7788 userDefaultFound = YES;
7790 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7792 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7796 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7797 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7799 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7800 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7802 while (tempObject = [enumerator nextObject])
7804 NSMutableDictionary *thisPresetDict = tempObject;
7805 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7807 presetHbDefault = thisPresetDict;
7808 presetHbDefaultParent = thisPresetDictParent;
7810 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7812 presetUserDefault = thisPresetDict;
7813 presetUserDefaultParent = thisPresetDictParent;
7814 userDefaultFound = YES;
7817 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7818 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7820 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7821 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7823 while (tempObject = [enumerator nextObject])
7825 NSMutableDictionary *thisPresetDict = tempObject;
7826 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7828 presetHbDefault = thisPresetDict;
7829 presetHbDefaultParent = thisPresetDictParent;
7830 presetHbDefaultParentParent = thisPresetDictParentParent;
7832 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7834 presetUserDefault = thisPresetDict;
7835 presetUserDefaultParent = thisPresetDictParent;
7836 presetUserDefaultParentParent = thisPresetDictParentParent;
7837 userDefaultFound = YES;
7846 /* check to see if a user specified preset was found, if not then assign the parents for
7847 * the presetHbDefault so that we can open the parents for the nested presets
7849 if (userDefaultFound == NO)
7851 presetUserDefaultParent = presetHbDefaultParent;
7852 presetUserDefaultParentParent = presetHbDefaultParentParent;
7856 - (IBAction)setDefaultPreset:(id)sender
7858 /* We need to determine if the item is a folder */
7859 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7865 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7867 /* First make sure the old user specified default preset is removed */
7868 while (tempObject = [enumerator nextObject])
7870 NSMutableDictionary *thisPresetDict = tempObject;
7871 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7873 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7876 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7877 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7879 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7882 while (tempObject = [enumerator nextObject])
7884 NSMutableDictionary *thisPresetDict1 = tempObject;
7885 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7887 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7889 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7890 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7892 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7895 while (tempObject = [enumerator nextObject])
7897 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7899 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7912 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7913 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7914 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7917 NSMutableArray *presetsArrayToMod;
7918 NSMutableArray *tempArray;
7920 /* If we are a root level preset, we are modding the UserPresets array */
7921 if (presetToModLevel == 0)
7923 presetsArrayToMod = UserPresets;
7925 else // We have a parent preset, so we modify the chidren array object for key
7927 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7930 enumerator = [presetsArrayToMod objectEnumerator];
7931 tempArray = [NSMutableArray array];
7933 while (tempObject = [enumerator nextObject])
7935 NSDictionary *thisPresetDict = tempObject;
7936 if (thisPresetDict == presetToMod)
7938 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7940 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7947 /* We save all of the preset data here */
7949 /* We Reload the New Table data for presets */
7950 [fPresetsOutlineView reloadData];
7953 - (IBAction)selectDefaultPreset:(id)sender
7955 NSMutableDictionary *presetToMod;
7956 /* if there is a user specified default, we use it */
7957 if (presetUserDefault)
7959 presetToMod = presetUserDefault;
7961 else if (presetHbDefault) //else we use the built in default presetHbDefault
7963 presetToMod = presetHbDefault;
7970 if (presetUserDefaultParent != nil)
7972 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7975 if (presetUserDefaultParentParent != nil)
7977 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7981 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7982 [self selectPreset:nil];
7987 #pragma mark Manage Built In Presets
7990 - (IBAction)deleteFactoryPresets:(id)sender
7993 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7997 NSMutableArray *tempArray;
8000 tempArray = [NSMutableArray array];
8001 /* we look here to see if the preset is we move on to the next one */
8002 while ( tempObject = [enumerator nextObject] )
8004 /* if the preset is "Factory" then we put it in the array of
8005 presets to delete */
8006 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
8008 [tempArray addObject:tempObject];
8012 [UserPresets removeObjectsInArray:tempArray];
8013 [fPresetsOutlineView reloadData];
8018 /* We use this method to recreate new, updated factory presets */
8019 - (IBAction)addFactoryPresets:(id)sender
8022 /* First, we delete any existing built in presets */
8023 [self deleteFactoryPresets: sender];
8024 /* Then we generate new built in presets programmatically with fPresetsBuiltin
8025 * which is all setup in HBPresets.h and HBPresets.m*/
8026 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
8027 /* update build number for built in presets */
8028 /* iterate though the new array of presets to import and add them to our presets array */
8030 NSEnumerator *enumerator = [UserPresets objectEnumerator];
8032 while (tempObject = [enumerator nextObject])
8034 /* Record the apps current build number in the PresetBuildNumber key */
8035 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
8037 /* Preset build number */
8038 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8042 /* report the built in preset updating to the activity log */
8043 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8053 /*******************************
8054 * Subclass of the HBPresetsOutlineView *
8055 *******************************/
8057 @implementation HBPresetsOutlineView
8058 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8062 // By default, NSTableView only drags an image of the first column. Change this to
8063 // drag an image of the queue's icon and PresetName columns.
8064 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8065 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8070 - (void) mouseDown:(NSEvent *)theEvent
8072 [super mouseDown:theEvent];
8078 - (BOOL) isDragging;