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 /* if we are custom anamorphic, store the exact storage, par and display dims */
2324 if (fTitle->job->anamorphic.mode == 3)
2326 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.modulus] forKey:@"PicturePARModulus"];
2328 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2329 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2331 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2332 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2334 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2335 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2338 NSString * pictureSummary;
2339 pictureSummary = [fPictureSizeField stringValue];
2340 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2341 /* Set crop settings here */
2342 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2343 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2344 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2345 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2346 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2348 /* Picture Filters */
2349 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2350 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2352 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2353 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2354 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2356 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2357 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2359 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2360 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2362 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2364 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2367 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2369 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2370 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2371 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2372 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2373 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2374 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2375 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2377 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2379 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2380 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2381 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2382 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2383 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2384 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2385 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2387 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2389 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2390 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2391 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2392 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2393 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2394 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2395 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2397 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2399 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2400 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2401 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2402 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2403 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2404 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2405 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2409 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2410 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2411 [subtitlesArray autorelease];
2413 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2415 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2417 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2420 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2424 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2427 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2428 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2429 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2431 /* Picture Sizing */
2432 /* Use Max Picture settings for whatever the dvd is.*/
2433 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2434 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2435 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2436 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2437 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2439 /* Set crop settings here */
2440 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2441 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2442 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2443 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2444 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2448 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2450 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2451 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2452 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2453 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2454 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2456 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2458 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2459 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2460 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2461 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2462 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2464 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2466 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2467 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2468 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2469 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2470 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2472 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2474 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2475 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2476 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2477 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2478 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2482 /* we need to auto relase the queueFileJob and return it */
2483 [queueFileJob autorelease];
2484 return queueFileJob;
2488 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2489 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2491 NSUInteger index = [indexSet lastIndex];
2492 NSUInteger aboveInsertIndexCount = 0;
2495 NSUInteger removeIndex;
2497 if (index >= insertIndex)
2499 removeIndex = index + aboveInsertIndexCount;
2500 aboveInsertIndexCount++;
2504 removeIndex = index;
2508 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2509 [QueueFileArray removeObjectAtIndex:removeIndex];
2510 [QueueFileArray insertObject:object atIndex:insertIndex];
2513 index = [indexSet indexLessThanIndex:index];
2515 /* We save all of the Queue data here
2516 * and it also gets sent back to the queue controller*/
2517 [self saveQueueFileItem];
2523 #pragma mark Queue Job Processing
2525 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2527 int i = currentQueueEncodeIndex;
2528 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2530 /* We save all of the Queue data here */
2531 [self saveQueueFileItem];
2532 /* We Reload the New Table data for presets */
2533 //[fPresetsOutlineView reloadData];
2535 /* Since we have now marked a queue item as done
2536 * we can go ahead and increment currentQueueEncodeIndex
2537 * so that if there is anything left in the queue we can
2538 * go ahead and move to the next item if we want to */
2539 currentQueueEncodeIndex++ ;
2540 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2541 int queueItems = [QueueFileArray count];
2542 /* If we still have more items in our queue, lets go to the next one */
2543 if (currentQueueEncodeIndex < queueItems)
2545 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2546 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2550 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2554 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2555 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2557 /* Tell HB to output a new activity log file for this encode */
2558 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2561 /* use a bool to determine whether or not we can decrypt using vlc */
2562 BOOL cancelScanDecrypt = 0;
2563 /* set the bool so that showNewScan knows to apply the appropriate queue
2564 * settings as this is a queue rescan
2566 //applyQueueToScan = YES;
2567 NSString *path = scanPath;
2568 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2570 if( [detector isVideoDVD] )
2572 // The chosen path was actually on a DVD, so use the raw block
2573 // device path instead.
2574 path = [detector devicePath];
2575 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2577 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2578 NSString *vlcPath = @"/Applications/VLC.app";
2579 NSFileManager * fileManager = [NSFileManager defaultManager];
2580 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2582 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2583 cancelScanDecrypt = 1;
2584 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2586 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");
2587 [NSApp requestUserAttention:NSCriticalRequest];
2589 if (status == NSAlertDefaultReturn)
2591 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2592 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2594 else if (status == NSAlertAlternateReturn)
2596 /* User chose to cancel the scan */
2597 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2601 /* 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 */
2602 cancelScanDecrypt = 0;
2603 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2609 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2610 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2614 if (cancelScanDecrypt == 0)
2616 /* we actually pass the scan off to libhb here */
2617 /* If there is no title number passed to scan, we use "0"
2618 * which causes the default behavior of a full source scan
2624 if (scanTitleNum > 0)
2626 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2629 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2630 /* We use our advance pref to determine how many previews to scan */
2631 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2632 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2636 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2637 - (void) processNewQueueEncode
2639 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2640 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2641 hb_job_t * job = title->job;
2643 if( !hb_list_count( list ) )
2645 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2648 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2649 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2650 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2651 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2652 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2656 * If scanning we need to do some extra setup of the job.
2658 if( job->indepth_scan == 1 )
2663 * When subtitle scan is enabled do a fast pre-scan job
2664 * which will determine which subtitles to enable, if any.
2667 x264opts_tmp = job->x264opts;
2669 job->x264opts = NULL;
2671 job->indepth_scan = 1;
2675 * Add the pre-scan job
2677 hb_add( fQueueEncodeLibhb, job );
2678 job->x264opts = x264opts_tmp;
2682 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2684 job->indepth_scan = 0;
2690 hb_add( fQueueEncodeLibhb, job );
2694 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2695 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2697 hb_add( fQueueEncodeLibhb, job );
2702 job->indepth_scan = 0;
2705 hb_add( fQueueEncodeLibhb, job );
2708 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2709 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2710 /* Lets mark our new encode as 1 or "Encoding" */
2711 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2712 [self saveQueueFileItem];
2714 /* we need to clean up the subtitle tracks after the job(s) have been set */
2715 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2717 for(ii = 0; ii < num_subtitle_tracks; ii++)
2719 hb_subtitle_t * subtitle;
2720 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2723 hb_list_rem(job->list_subtitle, subtitle);
2728 /* We should be all setup so let 'er rip */
2735 #pragma mark Queue Item Editing
2737 /* Rescans the chosen queue item back into the main window */
2738 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2740 fqueueEditRescanItemNum = selectedQueueItem;
2741 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2742 applyQueueToScan = YES;
2743 /* Set the browsedSourceDisplayName for showNewScan */
2744 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2745 [self performScan:scanPath scanTitleNum:scanTitleNum];
2749 /* We use this method after a queue item rescan for edit.
2750 * it largely mirrors -selectPreset in terms of structure.
2751 * Assumes that a queue item has been reloaded into the main window.
2753 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2755 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2756 hb_job_t * job = fTitle->job;
2759 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2761 /* Set title number and chapters */
2762 /* since the queue only scans a single title, we really don't need to pick a title */
2763 [fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2765 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2766 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2769 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2770 [self formatPopUpChanged:nil];
2772 /* Chapter Markers*/
2773 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2774 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2775 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2776 /* Mux mp4 with http optimization */
2777 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2780 /* We set the advanced opt string here if applicable*/
2781 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2782 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2784 /* Lets run through the following functions to get variables set there */
2785 [self videoEncoderPopUpChanged:nil];
2786 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2787 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2788 [self calculateBitrate:nil];
2791 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2793 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2794 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2795 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2796 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2797 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2798 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2799 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2800 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2802 /* For the quality slider we need to convert the old percent's to the new rf scales */
2803 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2804 [fVidQualitySlider setFloatValue:rf];
2809 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2810 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2812 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2816 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2817 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2821 [self videoMatrixChanged:nil];
2822 [self writeToActivityLog: "applyQueueSettingsToMainWindow: video matrix changed"];
2823 /* Video framerate */
2824 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2825 detected framerate in the fVidRatePopUp so we use index 0*/
2826 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2828 [fVidRatePopUp selectItemAtIndex: 0];
2832 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2835 /* 2 Pass Encoding */
2836 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2837 [self twoPassCheckboxChanged:nil];
2838 /* Turbo 1st pass for 2 Pass Encoding */
2839 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2844 /* Now lets add our new tracks to the audio list here */
2845 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2847 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2848 [self audioTrackPopUpChanged: fAudLang1PopUp];
2849 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2850 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2852 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2854 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2855 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2857 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2858 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2862 [fAudLang1PopUp selectItemAtIndex: 0];
2863 [self audioTrackPopUpChanged: fAudLang1PopUp];
2865 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2867 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2868 [self audioTrackPopUpChanged: fAudLang2PopUp];
2869 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2870 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2872 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2874 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2875 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2877 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2878 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2882 [fAudLang2PopUp selectItemAtIndex: 0];
2883 [self audioTrackPopUpChanged: fAudLang2PopUp];
2885 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2887 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2888 [self audioTrackPopUpChanged: fAudLang3PopUp];
2889 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2890 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2892 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2894 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2895 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2897 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2898 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2902 [fAudLang3PopUp selectItemAtIndex: 0];
2903 [self audioTrackPopUpChanged: fAudLang3PopUp];
2905 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2907 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2908 [self audioTrackPopUpChanged: fAudLang4PopUp];
2909 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2910 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2912 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2914 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2915 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2917 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2918 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2922 [fAudLang4PopUp selectItemAtIndex: 0];
2923 [self audioTrackPopUpChanged: fAudLang4PopUp];
2926 [self writeToActivityLog: "applyQueueSettingsToMainWindow: audio set up"];
2928 /* Crashy crashy right now, working on it */
2929 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2930 [fSubtitlesTable reloadData];
2931 /* Picture Settings */
2933 /* If Cropping is set to custom, then recall all four crop values from
2934 when the preset was created and apply them */
2935 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2937 [fPictureController setAutoCrop:NO];
2939 /* Here we use the custom crop values saved at the time the preset was saved */
2940 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2941 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2942 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2943 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2946 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2948 [fPictureController setAutoCrop:YES];
2949 /* Here we use the auto crop values determined right after scan */
2950 job->crop[0] = AutoCropTop;
2951 job->crop[1] = AutoCropBottom;
2952 job->crop[2] = AutoCropLeft;
2953 job->crop[3] = AutoCropRight;
2958 /* we check to make sure the presets width/height does not exceed the sources width/height */
2959 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2961 /* if so, then we use the sources height and width to avoid scaling up */
2962 //job->width = fTitle->width;
2963 //job->height = fTitle->height;
2964 [self revertPictureSizeToMax:nil];
2966 else // source width/height is >= the preset height/width
2968 /* we can go ahead and use the presets values for height and width */
2969 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2970 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2972 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2973 if (job->keep_ratio == 1)
2975 hb_fix_aspect( job, HB_KEEP_WIDTH );
2976 if( job->height > fTitle->height )
2978 job->height = fTitle->height;
2979 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2982 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2985 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture sizing set up"];
2990 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2991 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2992 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2995 [fPictureController setUseDecomb:1];
2996 [fPictureController setDecomb:0];
2997 [fPictureController setDeinterlace:0];
2998 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3000 /* we are using decomb */
3002 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3004 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3006 /* if we are using "Custom" in the decomb setting, also set the custom string*/
3007 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3009 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
3015 /* We are using Deinterlace */
3017 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3019 [fPictureController setUseDecomb:0];
3020 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3021 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3022 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3024 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
3031 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3033 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3034 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3035 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3037 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
3042 [fPictureController setDetelecine:0];
3046 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3048 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3049 /* if we are using "Custom" in the denoise setting, also set the custom string*/
3050 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3052 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
3057 [fPictureController setDenoise:0];
3061 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3063 /* if its a one, then its the old on/off deblock, set on to 5*/
3064 [fPictureController setDeblock:5];
3068 /* use the settings intValue */
3069 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3072 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3074 [fPictureController setGrayscale:1];
3078 [fPictureController setGrayscale:0];
3081 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3082 [fPictureController SetTitle:fTitle];
3083 [fPictureController SetTitle:fTitle];
3084 [self calculatePictureSizing:nil];
3086 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture filters set up"];
3087 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3088 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3089 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3090 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3092 /* Deselect the currently selected Preset if there is one*/
3093 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3094 //[self selectPreset:nil];
3096 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3097 /* Change UI to show "Custom" settings are being used */
3098 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3100 curUserPresetChosenNum = nil;
3104 /* Deselect the currently selected Preset if there is one*/
3105 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3106 /* Change UI to show "Custom" settings are being used */
3107 [fPresetSelectedDisplay setStringValue: @"Custom"];
3109 //curUserPresetChosenNum = nil;
3112 /* We need to set this bool back to NO, in case the user wants to do a scan */
3113 //applyQueueToScan = NO;
3115 /* Not that source is loaded and settings applied, delete the queue item from the queue */
3116 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3117 [self removeQueueFileItem:fqueueEditRescanItemNum];
3123 #pragma mark Live Preview
3124 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3125 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3128 - (void) prepareJobForPreview
3130 hb_list_t * list = hb_get_titles( fHandle );
3131 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3132 [fSrcTitlePopUp indexOfSelectedItem] );
3133 hb_job_t * job = title->job;
3134 hb_audio_config_t * audio;
3135 /* set job->angle for libdvdnav */
3136 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3137 /* Chapter selection */
3138 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3139 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3141 /* Format (Muxer) and Video Encoder */
3142 job->mux = [[fDstFormatPopUp selectedItem] tag];
3143 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3145 job->chapter_markers = 0;
3147 if( job->vcodec & HB_VCODEC_X264 )
3150 /* Below Sends x264 options to the core library if x264 is selected*/
3151 /* Lets use this as per Nyx, Thanks Nyx!*/
3152 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3153 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3154 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3159 /* Video settings */
3160 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3161 * and detelecine is on, so we handle that in the logic below
3164 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3166 /* a specific framerate has been chosen */
3167 job->vrate = 27000000;
3168 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3169 /* We are not same as source so we set job->cfr to 1
3170 * to enable constant frame rate since user has specified
3171 * a specific framerate*/
3176 /* We are same as source (variable) */
3177 job->vrate = title->rate;
3178 job->vrate_base = title->rate_base;
3179 /* We are same as source so we set job->cfr to 0
3180 * to enable true same as source framerate */
3182 /* If we are same as source and we have detelecine on, we need to turn on
3185 if ([fPictureController detelecine] == 1)
3191 switch( [fVidQualityMatrix selectedRow] )
3195 Bitrate should already have been calculated and displayed
3196 in fVidBitrateField, so let's just use it */
3198 job->vquality = -1.0;
3199 job->vbitrate = [fVidBitrateField intValue];
3202 job->vquality = [fVidQualityRFField floatValue];
3207 /* Subtitle settings */
3208 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3215 bool one_burned = FALSE;
3218 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3220 while (tempObject = [enumerator nextObject])
3223 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3224 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3225 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3226 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3228 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3229 * we want to ignore it for display as well as encoding.
3233 /* if i is 0, then we are in the first item of the subtitles which we need to
3234 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3235 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3238 /* if we are on the first track and using "Foreign Audio Search" */
3239 if (i == 0 && subtitle == 1)
3241 /* NOTE: Currently foreign language search is borked for preview.
3242 * Commented out but left in for initial commit. */
3245 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3247 job->indepth_scan = 1;
3248 if (burned == 1 || job->mux != HB_MUX_MP4)
3250 if (burned != 1 && job->mux == HB_MUX_MKV)
3252 job->select_subtitle_config.dest = PASSTHRUSUB;
3256 job->select_subtitle_config.dest = RENDERSUB;
3259 job->select_subtitle_config.force = force;
3260 job->select_subtitle_config.default_track = def;
3269 /* for the actual source tracks, we must subtract the non source entries so
3270 * that the menu index matches the source subtitle_list index for convenience */
3273 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3274 * Foreign Language Search is 1) so subtract 2 */
3275 subtitle = subtitle - 2;
3279 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3282 subtitle = subtitle - 1;
3285 /* We are setting a source subtitle so access the source subtitle info */
3286 hb_subtitle_t * subt;
3288 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3290 /* if we are getting the subtitles from an external srt file */
3291 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3293 hb_subtitle_config_t sub_config;
3295 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3297 /* we need to srncpy file path and char code */
3298 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3299 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3301 sub_config.force = 0;
3302 sub_config.dest = PASSTHRUSUB;
3303 sub_config.default_track = def;
3305 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3310 hb_subtitle_config_t sub_config = subt->config;
3312 if (!burned && job->mux == HB_MUX_MKV &&
3313 subt->format == PICTURESUB)
3315 sub_config.dest = PASSTHRUSUB;
3317 else if (!burned && job->mux == HB_MUX_MP4 &&
3318 subt->format == PICTURESUB)
3320 // Skip any non-burned vobsubs when output is mp4
3323 else if ( burned && subt->format == PICTURESUB )
3325 // Only allow one subtitle to be burned into the video
3330 sub_config.force = force;
3331 sub_config.default_track = def;
3332 hb_subtitle_add( job, &sub_config, subtitle );
3342 [subtitlesArray autorelease];
3345 /* Audio tracks and mixdowns */
3346 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3347 int audiotrack_count = hb_list_count(job->list_audio);
3348 for( int i = 0; i < audiotrack_count;i++)
3350 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3351 hb_list_rem(job->list_audio, temp_audio);
3353 /* Now lets add our new tracks to the audio list here */
3354 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3356 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3357 hb_audio_config_init(audio);
3358 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3359 /* We go ahead and assign values to our audio->out.<properties> */
3360 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3361 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3362 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3363 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3364 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3365 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3367 hb_audio_add( job, audio );
3370 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3372 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3373 hb_audio_config_init(audio);
3374 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3375 /* We go ahead and assign values to our audio->out.<properties> */
3376 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3377 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3378 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3379 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3380 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3381 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3383 hb_audio_add( job, audio );
3388 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3390 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3391 hb_audio_config_init(audio);
3392 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3393 /* We go ahead and assign values to our audio->out.<properties> */
3394 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3395 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3396 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3397 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3398 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3399 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3401 hb_audio_add( job, audio );
3406 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3408 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3409 hb_audio_config_init(audio);
3410 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3411 /* We go ahead and assign values to our audio->out.<properties> */
3412 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3413 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3414 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3415 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3416 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3417 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3419 hb_audio_add( job, audio );
3428 /* Though Grayscale is not really a filter, per se
3429 * we put it here since its in the filters panel
3432 if ([fPictureController grayscale])
3441 /* Initialize the filters list */
3442 job->filters = hb_list_init();
3444 /* Now lets call the filters if applicable.
3445 * The order of the filters is critical
3449 if ([fPictureController detelecine] == 1)
3451 /* use a custom detelecine string */
3452 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3453 hb_list_add( job->filters, &hb_filter_detelecine );
3455 if ([fPictureController detelecine] == 2)
3458 hb_list_add( job->filters, &hb_filter_detelecine );
3463 if ([fPictureController useDecomb] == 1)
3466 /* we add the custom string if present */
3467 if ([fPictureController decomb] == 1)
3469 /* use a custom decomb string */
3470 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3471 hb_list_add( job->filters, &hb_filter_decomb );
3473 if ([fPictureController decomb] == 2)
3475 /* Run old deinterlacer fd by default */
3476 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3477 hb_list_add( job->filters, &hb_filter_decomb );
3484 if ([fPictureController deinterlace] == 1)
3486 /* we add the custom string if present */
3487 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3488 hb_list_add( job->filters, &hb_filter_deinterlace );
3490 else if ([fPictureController deinterlace] == 2)
3492 /* Run old deinterlacer fd by default */
3493 hb_filter_deinterlace.settings = "-1";
3494 hb_list_add( job->filters, &hb_filter_deinterlace );
3496 else if ([fPictureController deinterlace] == 3)
3498 /* Yadif mode 0 (without spatial deinterlacing.) */
3499 hb_filter_deinterlace.settings = "2";
3500 hb_list_add( job->filters, &hb_filter_deinterlace );
3502 else if ([fPictureController deinterlace] == 4)
3504 /* Yadif (with spatial deinterlacing) */
3505 hb_filter_deinterlace.settings = "0";
3506 hb_list_add( job->filters, &hb_filter_deinterlace );
3512 if ([fPictureController denoise] == 1) // custom in popup
3514 /* we add the custom string if present */
3515 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3516 hb_list_add( job->filters, &hb_filter_denoise );
3518 else if ([fPictureController denoise] == 2) // Weak in popup
3520 hb_filter_denoise.settings = "2:1:2:3";
3521 hb_list_add( job->filters, &hb_filter_denoise );
3523 else if ([fPictureController denoise] == 3) // Medium in popup
3525 hb_filter_denoise.settings = "3:2:2:3";
3526 hb_list_add( job->filters, &hb_filter_denoise );
3528 else if ([fPictureController denoise] == 4) // Strong in popup
3530 hb_filter_denoise.settings = "7:7:5:5";
3531 hb_list_add( job->filters, &hb_filter_denoise );
3535 /* Deblock (uses pp7 default) */
3536 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3537 * the macgui's purposes a value of 0 actually means to not even use the filter
3538 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3540 if ([fPictureController deblock] != 0)
3542 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3543 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3544 hb_list_add( job->filters, &hb_filter_deblock );
3551 #pragma mark Job Handling
3557 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3558 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3559 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3560 hb_job_t * job = title->job;
3561 hb_audio_config_t * audio;
3562 /* Title Angle for dvdnav */
3563 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3565 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3567 /* Chapter selection */
3568 [self writeToActivityLog: "Start / Stop set to chapters"];
3569 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3570 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3572 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3574 /* we are pts based start / stop */
3575 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3577 /* 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
3578 * 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.
3580 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3581 /* get the start seconds from the start seconds field */
3582 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3583 //job->start_at_preview = start_seconds;
3584 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3585 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3586 job->pts_to_start = start_seconds * 90000LL;
3587 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3588 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3589 job->pts_to_stop = stop_seconds * 90000LL;
3591 /* A bunch of verbose activity log messages to check on what should be expected */
3592 [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3593 [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];
3594 [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3595 [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3596 [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3597 [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];
3599 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3601 /* we are frame based start / stop */
3602 [self writeToActivityLog: "Start / Stop set to frames ..."];
3604 /* 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
3605 * 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.
3607 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3608 /* get the start seconds from the start seconds field */
3609 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3610 //job->start_at_preview = start_seconds;
3611 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3612 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3613 job->frame_to_start = start_frame;
3614 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3615 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3616 job->frame_to_stop = stop_frame;
3618 /* A bunch of verbose activity log messages to check on what should be expected */
3619 [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3620 [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3621 [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3627 /* Format (Muxer) and Video Encoder */
3628 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3629 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3632 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3633 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3635 job->largeFileSize = 1;
3639 job->largeFileSize = 0;
3641 /* We set http optimized mp4 here */
3642 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3644 job->mp4_optimize = 1;
3648 job->mp4_optimize = 0;
3652 /* We set the chapter marker extraction here based on the format being
3653 mpeg4 or mkv and the checkbox being checked */
3654 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3656 job->chapter_markers = 1;
3658 /* now lets get our saved chapter names out the array in the queue file
3659 * and insert them back into the title chapter list. We have it here,
3660 * because unless we are inserting chapter markers there is no need to
3661 * spend the overhead of iterating through the chapter names array imo
3662 * Also, note that if for some reason we don't apply chapter names, the
3663 * chapters just come out 001, 002, etc. etc.
3666 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3668 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3670 while (tempObject = [enumerator nextObject])
3672 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3673 if( chapter != NULL )
3675 strncpy( chapter->title, [tempObject UTF8String], 1023);
3676 chapter->title[1023] = '\0';
3683 job->chapter_markers = 0;
3686 if( job->vcodec & HB_VCODEC_X264 )
3688 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3698 /* Below Sends x264 options to the core library if x264 is selected*/
3699 /* Lets use this as per Nyx, Thanks Nyx!*/
3700 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3701 /* Turbo first pass if two pass and Turbo First pass is selected */
3702 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3704 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3705 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3706 /* append the "Turbo" string variable to the existing opts string.
3707 Note: the "Turbo" string must be appended, not prepended to work properly*/
3708 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3709 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3713 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3719 /* Picture Size Settings */
3720 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3721 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3723 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3724 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3725 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3727 /* insert our custom values here for capuj */
3728 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3729 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3731 job->anamorphic.modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3733 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3734 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3736 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3737 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3740 /* Here we use the crop values saved at the time the preset was saved */
3741 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3742 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3743 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3744 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3746 /* Video settings */
3749 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3750 * and detelecine is on, so we handle that in the logic below
3753 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3755 /* a specific framerate has been chosen */
3756 job->vrate = 27000000;
3757 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3758 /* We are not same as source so we set job->cfr to 1
3759 * to enable constant frame rate since user has specified
3760 * a specific framerate*/
3765 /* We are same as source (variable) */
3766 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3767 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3768 /* We are same as source so we set job->cfr to 0
3769 * to enable true same as source framerate */
3771 /* If we are same as source and we have detelecine on, we need to turn on
3774 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3780 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3783 Bitrate should already have been calculated and displayed
3784 in fVidBitrateField, so let's just use it same as abr*/
3785 job->vquality = -1.0;
3786 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3788 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3790 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3795 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3800 #pragma mark Process Subtitles to libhb
3802 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3803 * which means that we need to account for the offset of non source language settings in from
3804 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3805 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3806 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3807 * to the source tracks position in title->list_subtitle.
3814 bool one_burned = FALSE;
3817 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3819 while (tempObject = [enumerator nextObject])
3822 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3823 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3824 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3825 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3827 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3828 * we want to ignore it for display as well as encoding.
3832 /* if i is 0, then we are in the first item of the subtitles which we need to
3833 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3834 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3837 /* if we are on the first track and using "Foreign Audio Search" */
3838 if (i == 0 && subtitle == 1)
3840 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3842 job->indepth_scan = 1;
3843 if (burned == 1 || job->mux != HB_MUX_MP4)
3845 if (burned != 1 && job->mux == HB_MUX_MKV)
3847 job->select_subtitle_config.dest = PASSTHRUSUB;
3851 job->select_subtitle_config.dest = RENDERSUB;
3854 job->select_subtitle_config.force = force;
3855 job->select_subtitle_config.default_track = def;
3863 /* for the actual source tracks, we must subtract the non source entries so
3864 * that the menu index matches the source subtitle_list index for convenience */
3867 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3868 * Foreign Language Search is 1) so subtract 2 */
3869 subtitle = subtitle - 2;
3873 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3876 subtitle = subtitle - 1;
3879 /* We are setting a source subtitle so access the source subtitle info */
3880 hb_subtitle_t * subt;
3882 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3884 /* if we are getting the subtitles from an external srt file */
3885 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3887 hb_subtitle_config_t sub_config;
3889 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3891 /* we need to srncpy file name and codeset */
3892 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3893 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3895 sub_config.force = 0;
3896 sub_config.dest = PASSTHRUSUB;
3897 sub_config.default_track = def;
3899 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3905 hb_subtitle_config_t sub_config = subt->config;
3907 if (!burned && job->mux == HB_MUX_MKV &&
3908 subt->format == PICTURESUB)
3910 sub_config.dest = PASSTHRUSUB;
3912 else if (!burned && job->mux == HB_MUX_MP4 &&
3913 subt->format == PICTURESUB)
3915 // Skip any non-burned vobsubs when output is mp4
3918 else if ( burned && subt->format == PICTURESUB )
3920 // Only allow one subtitle to be burned into the video
3925 sub_config.force = force;
3926 sub_config.default_track = def;
3927 hb_subtitle_add( job, &sub_config, subtitle );
3938 /* Audio tracks and mixdowns */
3939 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3940 int audiotrack_count = hb_list_count(job->list_audio);
3941 for( int i = 0; i < audiotrack_count;i++)
3943 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3944 hb_list_rem(job->list_audio, temp_audio);
3946 /* Now lets add our new tracks to the audio list here */
3947 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3949 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3950 hb_audio_config_init(audio);
3951 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3952 /* We go ahead and assign values to our audio->out.<properties> */
3953 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3954 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3955 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3956 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3957 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3958 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3960 hb_audio_add( job, audio );
3963 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3966 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3967 hb_audio_config_init(audio);
3968 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3969 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3970 /* We go ahead and assign values to our audio->out.<properties> */
3971 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3972 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3973 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3974 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3975 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3976 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3978 hb_audio_add( job, audio );
3982 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3984 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3985 hb_audio_config_init(audio);
3986 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3987 /* We go ahead and assign values to our audio->out.<properties> */
3988 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3989 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3990 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3991 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3992 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3993 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3995 hb_audio_add( job, audio );
3999 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
4001 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4002 hb_audio_config_init(audio);
4003 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4004 /* We go ahead and assign values to our audio->out.<properties> */
4005 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4006 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
4007 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
4008 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
4009 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
4010 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
4012 hb_audio_add( job, audio );
4018 job->filters = hb_list_init();
4020 /* Now lets call the filters if applicable.
4021 * The order of the filters is critical
4024 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4026 /* use a custom detelecine string */
4027 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4028 hb_list_add( job->filters, &hb_filter_detelecine );
4030 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4032 /* Use libhb's default values */
4033 hb_list_add( job->filters, &hb_filter_detelecine );
4036 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4039 /* we add the custom string if present */
4040 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4042 /* use a custom decomb string */
4043 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4044 hb_list_add( job->filters, &hb_filter_decomb );
4046 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4048 /* Use libhb default */
4049 hb_list_add( job->filters, &hb_filter_decomb );
4057 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4059 /* we add the custom string if present */
4060 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4061 hb_list_add( job->filters, &hb_filter_deinterlace );
4063 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4065 /* Run old deinterlacer fd by default */
4066 hb_filter_deinterlace.settings = "-1";
4067 hb_list_add( job->filters, &hb_filter_deinterlace );
4069 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4071 /* Yadif mode 0 (without spatial deinterlacing.) */
4072 hb_filter_deinterlace.settings = "2";
4073 hb_list_add( job->filters, &hb_filter_deinterlace );
4075 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4077 /* Yadif (with spatial deinterlacing) */
4078 hb_filter_deinterlace.settings = "0";
4079 hb_list_add( job->filters, &hb_filter_deinterlace );
4085 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4087 /* we add the custom string if present */
4088 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4089 hb_list_add( job->filters, &hb_filter_denoise );
4091 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4093 hb_filter_denoise.settings = "2:1:2:3";
4094 hb_list_add( job->filters, &hb_filter_denoise );
4096 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4098 hb_filter_denoise.settings = "3:2:2:3";
4099 hb_list_add( job->filters, &hb_filter_denoise );
4101 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4103 hb_filter_denoise.settings = "7:7:5:5";
4104 hb_list_add( job->filters, &hb_filter_denoise );
4108 /* Deblock (uses pp7 default) */
4109 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
4110 * the macgui's purposes a value of 0 actually means to not even use the filter
4111 * current hb_filter_deblock.settings valid ranges are from 5 - 15
4113 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4115 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4116 hb_list_add( job->filters, &hb_filter_deblock );
4118 [self writeToActivityLog: "prepareJob exiting"];
4123 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4125 - (IBAction) addToQueue: (id) sender
4127 /* We get the destination directory from the destination field here */
4128 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4129 /* We check for a valid destination here */
4130 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4132 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4139 BOOL fileExistsInQueue;
4140 fileExistsInQueue = NO;
4142 /* We check for and existing file here */
4143 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4148 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4150 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4152 while (tempObject = [enumerator nextObject])
4154 NSDictionary *thisQueueDict = tempObject;
4155 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4157 fileExistsInQueue = YES;
4163 if(fileExists == YES)
4165 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4166 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4167 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4168 NULL, NULL, [NSString stringWithFormat:
4169 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4170 [fDstFile2Field stringValue]] );
4172 else if (fileExistsInQueue == YES)
4174 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4175 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4176 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4177 NULL, NULL, [NSString stringWithFormat:
4178 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4179 [fDstFile2Field stringValue]] );
4183 [self doAddToQueue];
4187 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4188 the user if they want to overwrite an exiting movie file.
4190 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4191 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4193 if( returnCode == NSAlertAlternateReturn )
4194 [self doAddToQueue];
4197 - (void) doAddToQueue
4199 [self addQueueFileItem ];
4204 /* Rip: puts up an alert before ultimately calling doRip
4206 - (IBAction) Rip: (id) sender
4208 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4209 /* Rip or Cancel ? */
4211 hb_get_state2( fQueueEncodeLibhb, &s );
4213 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4215 [self Cancel: sender];
4219 /* We check to see if we need to warn the user that the computer will go to sleep
4220 or shut down when encoding is finished */
4221 [self remindUserOfSleepOrShutdown];
4223 // If there are pending jobs in the queue, then this is a rip the queue
4224 if (fPendingCount > 0)
4226 /* here lets start the queue with the first pending item */
4227 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4232 // Before adding jobs to the queue, check for a valid destination.
4234 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4235 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4237 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4241 /* We check for duplicate name here */
4242 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4244 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4245 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4246 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4247 NULL, NULL, [NSString stringWithFormat:
4248 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4249 [fDstFile2Field stringValue]] );
4251 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4255 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4256 otherwise, just rip the queue */
4257 if(fPendingCount == 0)
4259 [self doAddToQueue];
4262 /* go right to processing the new queue encode */
4263 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4268 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4269 want to overwrite an exiting movie file.
4271 - (void) overWriteAlertDone: (NSWindow *) sheet
4272 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4274 if( returnCode == NSAlertAlternateReturn )
4276 /* if there are no jobs in the queue, then add this one to the queue and rip
4277 otherwise, just rip the queue */
4278 if( fPendingCount == 0 )
4280 [self doAddToQueue];
4283 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4284 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4285 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4290 - (void) remindUserOfSleepOrShutdown
4292 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4294 /*Warn that computer will sleep after encoding*/
4297 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);
4298 [NSApp requestUserAttention:NSCriticalRequest];
4299 if ( reminduser == NSAlertAlternateReturn )
4301 [self showPreferencesWindow:nil];
4304 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4306 /*Warn that computer will shut down after encoding*/
4309 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);
4310 [NSApp requestUserAttention:NSCriticalRequest];
4311 if ( reminduser == NSAlertAlternateReturn )
4313 [self showPreferencesWindow:nil];
4322 /* Let libhb do the job */
4323 hb_start( fQueueEncodeLibhb );
4324 /*set the fEncodeState State */
4329 //------------------------------------------------------------------------------------
4330 // Displays an alert asking user if the want to cancel encoding of current job.
4331 // Cancel: returns immediately after posting the alert. Later, when the user
4332 // acknowledges the alert, doCancelCurrentJob is called.
4333 //------------------------------------------------------------------------------------
4334 - (IBAction)Cancel: (id)sender
4336 if (!fQueueController) return;
4338 hb_pause( fQueueEncodeLibhb );
4339 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4341 // Which window to attach the sheet to?
4342 NSWindow * docWindow;
4343 if ([sender respondsToSelector: @selector(window)])
4344 docWindow = [sender window];
4346 docWindow = fWindow;
4348 NSBeginCriticalAlertSheet(
4350 NSLocalizedString(@"Continue Encoding", nil),
4351 NSLocalizedString(@"Cancel Current and Stop", nil),
4352 NSLocalizedString(@"Cancel Current and Continue", nil),
4354 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4355 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4357 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4360 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4362 hb_resume( fQueueEncodeLibhb );
4363 if (returnCode == NSAlertOtherReturn)
4365 [self doCancelCurrentJob]; // <- this also stops libhb
4367 if (returnCode == NSAlertAlternateReturn)
4369 [self doCancelCurrentJobAndStop];
4373 //------------------------------------------------------------------------------------
4374 // Cancels and deletes the current job and stops libhb from processing the remaining
4376 //------------------------------------------------------------------------------------
4377 - (void) doCancelCurrentJob
4379 // Stop the current job. hb_stop will only cancel the current pass and then set
4380 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4381 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4382 // remaining passes of the job and then start the queue back up if there are any
4386 hb_stop( fQueueEncodeLibhb );
4388 // Delete all remaining jobs since libhb doesn't do this on its own.
4390 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4391 hb_rem( fQueueEncodeLibhb, job );
4393 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4395 // now that we've stopped the currently encoding job, lets mark it as cancelled
4396 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4397 // and as always, save it in the queue .plist...
4398 /* We save all of the Queue data here */
4399 [self saveQueueFileItem];
4400 // so now lets move to
4401 currentQueueEncodeIndex++ ;
4402 // ... and see if there are more items left in our queue
4403 int queueItems = [QueueFileArray count];
4404 /* If we still have more items in our queue, lets go to the next one */
4405 if (currentQueueEncodeIndex < queueItems)
4407 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4408 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4410 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4414 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4419 - (void) doCancelCurrentJobAndStop
4421 hb_stop( fQueueEncodeLibhb );
4423 // Delete all remaining jobs since libhb doesn't do this on its own.
4425 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4426 hb_rem( fQueueEncodeLibhb, job );
4429 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4431 // now that we've stopped the currently encoding job, lets mark it as cancelled
4432 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4433 // and as always, save it in the queue .plist...
4434 /* We save all of the Queue data here */
4435 [self saveQueueFileItem];
4436 // so now lets move to
4437 currentQueueEncodeIndex++ ;
4438 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4440 - (IBAction) Pause: (id) sender
4443 hb_get_state2( fQueueEncodeLibhb, &s );
4445 if( s.state == HB_STATE_PAUSED )
4447 hb_resume( fQueueEncodeLibhb );
4451 hb_pause( fQueueEncodeLibhb );
4456 #pragma mark GUI Controls Changed Methods
4458 - (IBAction) titlePopUpChanged: (id) sender
4460 hb_list_t * list = hb_get_titles( fHandle );
4461 hb_title_t * title = (hb_title_t*)
4462 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4464 /* If we are a stream type, grok the output file name from title->name upon title change */
4465 if (title->type == HB_STREAM_TYPE)
4467 /* we set the default name according to the new title->name */
4468 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4469 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4470 [NSString stringWithUTF8String: title->name],
4471 [[fDstFile2Field stringValue] pathExtension]]];
4472 /* 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 */
4473 if ( hb_list_count( list ) > 1 )
4475 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4479 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4480 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4481 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4482 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4483 /* 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 */
4484 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4485 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4486 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4488 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4489 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4491 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4492 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4493 [browsedSourceDisplayName stringByDeletingPathExtension],
4495 [[fDstFile2Field stringValue] pathExtension]]];
4497 /* Update encode start / stop variables */
4501 /* Update chapter popups */
4502 [fSrcChapterStartPopUp removeAllItems];
4503 [fSrcChapterEndPopUp removeAllItems];
4504 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4506 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4507 stringWithFormat: @"%d", i + 1]];
4508 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4509 stringWithFormat: @"%d", i + 1]];
4512 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4513 [fSrcChapterEndPopUp selectItemAtIndex:
4514 hb_list_count( title->list_chapter ) - 1];
4515 [self chapterPopUpChanged:nil];
4517 /* if using dvd nav, show the angle widget */
4518 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4520 [fSrcAngleLabel setHidden:NO];
4521 [fSrcAnglePopUp setHidden:NO];
4523 [fSrcAnglePopUp removeAllItems];
4524 for( int i = 0; i < title->angle_count; i++ )
4526 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4528 [fSrcAnglePopUp selectItemAtIndex: 0];
4532 [fSrcAngleLabel setHidden:YES];
4533 [fSrcAnglePopUp setHidden:YES];
4536 /* Start Get and set the initial pic size for display */
4537 hb_job_t * job = title->job;
4540 /* Set Auto Crop to on upon selecting a new title */
4541 [fPictureController setAutoCrop:YES];
4543 /* We get the originial output picture width and height and put them
4544 in variables for use with some presets later on */
4545 PicOrigOutputWidth = job->width;
4546 PicOrigOutputHeight = job->height;
4547 AutoCropTop = job->crop[0];
4548 AutoCropBottom = job->crop[1];
4549 AutoCropLeft = job->crop[2];
4550 AutoCropRight = job->crop[3];
4552 /* Reset the new title in fPictureController && fPreviewController*/
4553 [fPictureController SetTitle:title];
4556 /* Update Subtitle Table */
4557 [fSubtitlesDelegate resetWithTitle:title];
4558 [fSubtitlesTable reloadData];
4561 /* Update chapter table */
4562 [fChapterTitlesDelegate resetWithTitle:title];
4563 [fChapterTable reloadData];
4565 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4566 int audiotrack_count = hb_list_count(job->list_audio);
4567 for( int i = 0; i < audiotrack_count;i++)
4569 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4570 hb_list_rem(job->list_audio, temp_audio);
4573 /* Update audio popups */
4574 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4575 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4576 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4577 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4578 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4579 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4580 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4581 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4582 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4583 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4585 /* changing the title may have changed the audio channels on offer, */
4586 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4587 [self audioTrackPopUpChanged: fAudLang1PopUp];
4588 [self audioTrackPopUpChanged: fAudLang2PopUp];
4589 [self audioTrackPopUpChanged: fAudLang3PopUp];
4590 [self audioTrackPopUpChanged: fAudLang4PopUp];
4592 [fVidRatePopUp selectItemAtIndex: 0];
4594 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4595 [self calculatePictureSizing:nil];
4597 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4598 [self selectPreset:nil];
4601 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4603 if( [fEncodeStartStopPopUp isEnabled] )
4605 /* We are chapters */
4606 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4608 [fSrcChapterStartPopUp setHidden: NO];
4609 [fSrcChapterEndPopUp setHidden: NO];
4611 [fSrcTimeStartEncodingField setHidden: YES];
4612 [fSrcTimeEndEncodingField setHidden: YES];
4614 [fSrcFrameStartEncodingField setHidden: YES];
4615 [fSrcFrameEndEncodingField setHidden: YES];
4617 [self chapterPopUpChanged:nil];
4619 /* We are time based (seconds) */
4620 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4622 [fSrcChapterStartPopUp setHidden: YES];
4623 [fSrcChapterEndPopUp setHidden: YES];
4625 [fSrcTimeStartEncodingField setHidden: NO];
4626 [fSrcTimeEndEncodingField setHidden: NO];
4628 [fSrcFrameStartEncodingField setHidden: YES];
4629 [fSrcFrameEndEncodingField setHidden: YES];
4631 [self startEndSecValueChanged:nil];
4633 /* We are frame based */
4634 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4636 [fSrcChapterStartPopUp setHidden: YES];
4637 [fSrcChapterEndPopUp setHidden: YES];
4639 [fSrcTimeStartEncodingField setHidden: YES];
4640 [fSrcTimeEndEncodingField setHidden: YES];
4642 [fSrcFrameStartEncodingField setHidden: NO];
4643 [fSrcFrameEndEncodingField setHidden: NO];
4645 [self startEndFrameValueChanged:nil];
4650 - (IBAction) chapterPopUpChanged: (id) sender
4653 /* If start chapter popup is greater than end chapter popup,
4654 we set the end chapter popup to the same as start chapter popup */
4655 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4657 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4661 hb_list_t * list = hb_get_titles( fHandle );
4662 hb_title_t * title = (hb_title_t *)
4663 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4665 hb_chapter_t * chapter;
4666 int64_t duration = 0;
4667 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4668 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4670 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4671 duration += chapter->duration;
4674 duration /= 90000; /* pts -> seconds */
4675 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4676 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4679 [self calculateBitrate: sender];
4681 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4683 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4684 [fCreateChapterMarkers setEnabled: NO];
4685 [fCreateChapterMarkers setState: NSOffState];
4689 [fCreateChapterMarkers setEnabled: YES];
4693 - (IBAction) startEndSecValueChanged: (id) sender
4696 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4697 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4698 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4701 //[self calculateBitrate: sender];
4705 - (IBAction) startEndFrameValueChanged: (id) sender
4707 hb_list_t * list = hb_get_titles( fHandle );
4708 hb_title_t * title = (hb_title_t*)
4709 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4711 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4712 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4713 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4716 //[self calculateBitrate: sender];
4720 - (IBAction) formatPopUpChanged: (id) sender
4722 NSString * string = [fDstFile2Field stringValue];
4723 int format = [fDstFormatPopUp indexOfSelectedItem];
4725 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4726 [fDstMp4LargeFileCheck setHidden: YES];
4727 [fDstMp4HttpOptFileCheck setHidden: YES];
4728 [fDstMp4iPodFileCheck setHidden: YES];
4730 /* Update the Video Codec PopUp */
4731 /* lets get the tag of the currently selected item first so we might reset it later */
4732 int selectedVidEncoderTag;
4733 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4735 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4736 [fVidEncoderPopUp removeAllItems];
4737 NSMenuItem *menuItem;
4738 /* These video encoders are available to all of our current muxers, so lets list them once here */
4739 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4740 [menuItem setTag: HB_VCODEC_FFMPEG];
4745 /*Get Default MP4 File Extension*/
4746 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4754 /* Add additional video encoders here */
4755 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4756 [menuItem setTag: HB_VCODEC_X264];
4757 /* We show the mp4 option checkboxes here since we are mp4 */
4758 [fCreateChapterMarkers setEnabled: YES];
4759 [fDstMp4LargeFileCheck setHidden: NO];
4760 [fDstMp4HttpOptFileCheck setHidden: NO];
4761 [fDstMp4iPodFileCheck setHidden: NO];
4766 /* Add additional video encoders here */
4767 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4768 [menuItem setTag: HB_VCODEC_X264];
4769 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4770 [menuItem setTag: HB_VCODEC_THEORA];
4771 /* We enable the create chapters checkbox here */
4772 [fCreateChapterMarkers setEnabled: YES];
4777 /* tell fSubtitlesDelegate we have a new video container */
4779 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4780 [fSubtitlesTable reloadData];
4781 /* if we have a previously selected vid encoder tag, then try to select it */
4782 if (selectedVidEncoderTag)
4784 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4788 [fVidEncoderPopUp selectItemAtIndex: 0];
4791 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4792 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4793 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4794 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4797 [self autoSetM4vExtension: sender];
4799 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4801 if( SuccessfulScan )
4803 /* Add/replace to the correct extension */
4804 [self audioTrackPopUpChanged: fAudLang1PopUp];
4805 [self audioTrackPopUpChanged: fAudLang2PopUp];
4806 [self audioTrackPopUpChanged: fAudLang3PopUp];
4807 [self audioTrackPopUpChanged: fAudLang4PopUp];
4809 if( [fVidEncoderPopUp selectedItem] == nil )
4812 [fVidEncoderPopUp selectItemAtIndex:0];
4813 [self videoEncoderPopUpChanged:nil];
4815 /* changing the format may mean that we can / can't offer mono or 6ch, */
4816 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4818 /* We call the method to properly enable/disable turbo 2 pass */
4819 [self twoPassCheckboxChanged: sender];
4820 /* We call method method to change UI to reflect whether a preset is used or not*/
4823 [self customSettingUsed: sender];
4826 - (IBAction) autoSetM4vExtension: (id) sender
4828 if ( [fDstFormatPopUp indexOfSelectedItem] )
4831 NSString * extension = @"mp4";
4833 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4834 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4835 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4836 [fCreateChapterMarkers state] == NSOnState ||
4837 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4842 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4845 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4846 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4849 /* Method to determine if we should change the UI
4850 To reflect whether or not a Preset is being used or if
4851 the user is using "Custom" settings by determining the sender*/
4852 - (IBAction) customSettingUsed: (id) sender
4854 if ([sender stringValue])
4856 /* Deselect the currently selected Preset if there is one*/
4857 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4858 /* Change UI to show "Custom" settings are being used */
4859 [fPresetSelectedDisplay setStringValue: @"Custom"];
4861 curUserPresetChosenNum = nil;
4863 [self calculateBitrate:nil];
4868 #pragma mark - Video
4870 - (IBAction) videoEncoderPopUpChanged: (id) sender
4872 hb_job_t * job = fTitle->job;
4873 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4875 [fAdvancedOptions setHidden:YES];
4876 /* If we are using x264 then show the x264 advanced panel*/
4877 if (videoEncoder == HB_VCODEC_X264)
4879 [fAdvancedOptions setHidden:NO];
4880 [self autoSetM4vExtension: sender];
4883 if (videoEncoder == HB_VCODEC_FFMPEG)
4885 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4886 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4887 anything other than MP4.
4889 [fDstMp4iPodFileCheck setEnabled: NO];
4890 [fDstMp4iPodFileCheck setState: NSOffState];
4894 [fDstMp4iPodFileCheck setEnabled: YES];
4896 [self setupQualitySlider];
4897 [self calculatePictureSizing: sender];
4898 [self twoPassCheckboxChanged: sender];
4902 - (IBAction) twoPassCheckboxChanged: (id) sender
4904 /* check to see if x264 is chosen */
4905 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4907 if( [fVidTwoPassCheck state] == NSOnState)
4909 [fVidTurboPassCheck setHidden: NO];
4913 [fVidTurboPassCheck setHidden: YES];
4914 [fVidTurboPassCheck setState: NSOffState];
4916 /* Make sure Two Pass is checked if Turbo is checked */
4917 if( [fVidTurboPassCheck state] == NSOnState)
4919 [fVidTwoPassCheck setState: NSOnState];
4924 [fVidTurboPassCheck setHidden: YES];
4925 [fVidTurboPassCheck setState: NSOffState];
4928 /* We call method method to change UI to reflect whether a preset is used or not*/
4929 [self customSettingUsed: sender];
4932 - (IBAction ) videoFrameRateChanged: (id) sender
4934 /* We call method method to calculatePictureSizing to error check detelecine*/
4935 [self calculatePictureSizing: sender];
4937 /* We call method method to change UI to reflect whether a preset is used or not*/
4938 [self customSettingUsed: sender];
4940 - (IBAction) videoMatrixChanged: (id) sender;
4942 bool target, bitrate, quality;
4944 target = bitrate = quality = false;
4945 if( [fVidQualityMatrix isEnabled] )
4947 switch( [fVidQualityMatrix selectedRow] )
4960 [fVidTargetSizeField setEnabled: target];
4961 [fVidBitrateField setEnabled: bitrate];
4962 [fVidQualitySlider setEnabled: quality];
4963 [fVidQualityRFField setEnabled: quality];
4964 [fVidQualityRFLabel setEnabled: quality];
4965 [fVidTwoPassCheck setEnabled: !quality &&
4966 [fVidQualityMatrix isEnabled]];
4969 [fVidTwoPassCheck setState: NSOffState];
4970 [fVidTurboPassCheck setHidden: YES];
4971 [fVidTurboPassCheck setState: NSOffState];
4974 [self qualitySliderChanged: sender];
4975 [self calculateBitrate: sender];
4976 [self customSettingUsed: sender];
4979 /* Use this method to setup the quality slider for cq/rf values depending on
4980 * the video encoder selected.
4982 - (void) setupQualitySlider
4984 /* Get the current slider maxValue to check for a change in slider scale later
4985 * so that we can choose a new similar value on the new slider scale */
4986 float previousMaxValue = [fVidQualitySlider maxValue];
4987 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4988 NSString * qpRFLabelString = @"QP:";
4990 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4992 [fVidQualitySlider setMinValue:0.0];
4993 [fVidQualitySlider setMaxValue:51.0];
4994 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4995 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4996 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4997 qpRFLabelString = @"RF:";
5000 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
5002 [fVidQualitySlider setMinValue:1.0];
5003 [fVidQualitySlider setMaxValue:31.0];
5004 [fVidQualitySlider setNumberOfTickMarks:31];
5007 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5009 [fVidQualitySlider setMinValue:0.0];
5010 [fVidQualitySlider setMaxValue:63.0];
5011 [fVidQualitySlider setNumberOfTickMarks:64];
5013 [fVidQualityRFLabel setStringValue:qpRFLabelString];
5015 /* check to see if we have changed slider scales */
5016 if (previousMaxValue != [fVidQualitySlider maxValue])
5018 /* if so, convert the old setting to the new scale as close as possible based on percentages */
5019 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
5020 [fVidQualitySlider setFloatValue:rf];
5023 [self qualitySliderChanged:nil];
5026 - (IBAction) qualitySliderChanged: (id) sender
5028 /* Our constant quality slider is in a range based
5029 * on each encoders qp/rf values. The range depends
5030 * on the encoder. Also, the range is inverse of quality
5031 * for all of the encoders *except* for theora
5032 * (ie. as the "quality" goes up, the cq or rf value
5033 * actually goes down). Since the IB sliders always set
5034 * their max value at the right end of the slider, we
5035 * will calculate the inverse, so as the slider floatValue
5036 * goes up, we will show the inverse in the rf field
5037 * so, the floatValue at the right for x264 would be 51
5038 * and our rf field needs to show 0 and vice versa.
5041 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5042 /* If the encoder is theora, use the float, otherwise use the inverse float*/
5043 float sliderRfToPercent;
5044 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5046 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
5047 sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
5051 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5052 sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
5054 [fVidConstantCell setTitle: [NSString stringWithFormat:
5055 NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
5057 [self customSettingUsed: sender];
5060 - (void) controlTextDidChange: (NSNotification *) notification
5062 [self calculateBitrate:nil];
5065 - (IBAction) calculateBitrate: (id) sender
5067 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5072 hb_list_t * list = hb_get_titles( fHandle );
5073 hb_title_t * title = (hb_title_t *) hb_list_item( list,
5074 [fSrcTitlePopUp indexOfSelectedItem] );
5075 hb_job_t * job = title->job;
5076 hb_audio_config_t * audio;
5077 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
5078 * Target Size Field, we also need the job info for the Muxer, the Chapters
5079 * as well as all of the audio track info.
5080 * This used to be accomplished by simply calling prepareJob here, however
5081 * since the resilient queue sets the queue array values instead of the job
5082 * values directly, we duplicate the old prepareJob code here for the variables
5085 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5086 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
5087 job->mux = [[fDstFormatPopUp selectedItem] tag];
5089 /* Audio goes here */
5090 int audiotrack_count = hb_list_count(job->list_audio);
5091 for( int i = 0; i < audiotrack_count;i++)
5093 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5094 hb_list_rem(job->list_audio, temp_audio);
5096 /* Now we need our audio info here for each track if applicable */
5097 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5099 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5100 hb_audio_config_init(audio);
5101 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5102 /* We go ahead and assign values to our audio->out.<properties> */
5103 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5104 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5105 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5106 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5107 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5108 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5110 hb_audio_add( job, audio );
5113 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5115 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5116 hb_audio_config_init(audio);
5117 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5118 /* We go ahead and assign values to our audio->out.<properties> */
5119 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5120 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5121 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5122 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5123 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5124 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5126 hb_audio_add( job, audio );
5131 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5133 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5134 hb_audio_config_init(audio);
5135 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5136 /* We go ahead and assign values to our audio->out.<properties> */
5137 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5138 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5139 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5140 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5141 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5142 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5144 hb_audio_add( job, audio );
5149 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5151 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5152 hb_audio_config_init(audio);
5153 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5154 /* We go ahead and assign values to our audio->out.<properties> */
5155 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5156 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5157 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5158 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5159 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5160 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5162 hb_audio_add( job, audio );
5167 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5171 #pragma mark - Picture
5173 /* lets set the picture size back to the max from right after title scan
5174 Lets use an IBAction here as down the road we could always use a checkbox
5175 in the gui to easily take the user back to max. Remember, the compiler
5176 resolves IBActions down to -(void) during compile anyway */
5177 - (IBAction) revertPictureSizeToMax: (id) sender
5179 hb_job_t * job = fTitle->job;
5180 /* Here we apply the title source and height */
5181 job->width = fTitle->width;
5182 job->height = fTitle->height;
5184 [self calculatePictureSizing: sender];
5185 /* We call method to change UI to reflect whether a preset is used or not*/
5186 [self customSettingUsed: sender];
5190 * Registers changes made in the Picture Settings Window.
5193 - (void)pictureSettingsDidChange
5195 [self calculatePictureSizing:nil];
5198 /* Get and Display Current Pic Settings in main window */
5199 - (IBAction) calculatePictureSizing: (id) sender
5201 if (fTitle->job->anamorphic.mode > 0)
5203 fTitle->job->keep_ratio = 0;
5206 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5208 NSString *picCropping;
5209 /* Set the display field for crop as per boolean */
5210 if (![fPictureController autoCrop])
5212 picCropping = @"Custom";
5216 picCropping = @"Auto";
5218 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]]];
5220 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5222 NSString *videoFilters;
5225 if ([fPictureController detelecine] == 2)
5227 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5229 else if ([fPictureController detelecine] == 1)
5231 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5235 if ([fPictureController useDecomb] == 1)
5238 if ([fPictureController decomb] == 2)
5240 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5242 else if ([fPictureController decomb] == 1)
5244 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5250 if ([fPictureController deinterlace] > 0)
5252 fTitle->job->deinterlace = 1;
5256 fTitle->job->deinterlace = 0;
5259 if ([fPictureController deinterlace] == 2)
5261 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5263 else if ([fPictureController deinterlace] == 3)
5265 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5267 else if ([fPictureController deinterlace] == 4)
5269 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5271 else if ([fPictureController deinterlace] == 1)
5273 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5279 if ([fPictureController denoise] == 2)
5281 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5283 else if ([fPictureController denoise] == 3)
5285 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5287 else if ([fPictureController denoise] == 4)
5289 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5291 else if ([fPictureController denoise] == 1)
5293 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5297 if ([fPictureController deblock] > 0)
5299 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5303 if ([fPictureController grayscale])
5305 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5307 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5309 //[fPictureController reloadStillPreview];
5314 #pragma mark - Audio and Subtitles
5315 - (IBAction) audioCodecsPopUpChanged: (id) sender
5318 NSPopUpButton * audiotrackPopUp;
5319 NSPopUpButton * sampleratePopUp;
5320 NSPopUpButton * bitratePopUp;
5321 NSPopUpButton * audiocodecPopUp;
5322 if (sender == fAudTrack1CodecPopUp)
5324 audiotrackPopUp = fAudLang1PopUp;
5325 audiocodecPopUp = fAudTrack1CodecPopUp;
5326 sampleratePopUp = fAudTrack1RatePopUp;
5327 bitratePopUp = fAudTrack1BitratePopUp;
5329 else if (sender == fAudTrack2CodecPopUp)
5331 audiotrackPopUp = fAudLang2PopUp;
5332 audiocodecPopUp = fAudTrack2CodecPopUp;
5333 sampleratePopUp = fAudTrack2RatePopUp;
5334 bitratePopUp = fAudTrack2BitratePopUp;
5336 else if (sender == fAudTrack3CodecPopUp)
5338 audiotrackPopUp = fAudLang3PopUp;
5339 audiocodecPopUp = fAudTrack3CodecPopUp;
5340 sampleratePopUp = fAudTrack3RatePopUp;
5341 bitratePopUp = fAudTrack3BitratePopUp;
5345 audiotrackPopUp = fAudLang4PopUp;
5346 audiocodecPopUp = fAudTrack4CodecPopUp;
5347 sampleratePopUp = fAudTrack4RatePopUp;
5348 bitratePopUp = fAudTrack4BitratePopUp;
5351 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5352 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5353 [self audioTrackPopUpChanged: audiotrackPopUp];
5357 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5359 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5360 * the settings of the source audio for that track. We leave the samplerate and bitrate
5361 * to audiotrackMixdownChanged
5364 /* We will first verify that a lower track number has been selected before enabling each track
5365 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5367 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5369 [fAudLang2PopUp setEnabled: NO];
5370 [fAudLang2PopUp selectItemAtIndex: 0];
5374 [fAudLang2PopUp setEnabled: YES];
5377 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5379 [fAudLang3PopUp setEnabled: NO];
5380 [fAudLang3PopUp selectItemAtIndex: 0];
5384 [fAudLang3PopUp setEnabled: YES];
5386 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5388 [fAudLang4PopUp setEnabled: NO];
5389 [fAudLang4PopUp selectItemAtIndex: 0];
5393 [fAudLang4PopUp setEnabled: YES];
5395 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5396 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5397 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5398 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5399 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5400 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5401 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5402 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5404 [fAudTrack1CodecPopUp removeAllItems];
5405 [fAudTrack1MixPopUp removeAllItems];
5406 [fAudTrack1RatePopUp removeAllItems];
5407 [fAudTrack1BitratePopUp removeAllItems];
5408 [fAudTrack1DrcSlider setFloatValue: 0.00];
5409 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5411 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5413 [fAudTrack1RatePopUp setEnabled: NO];
5414 [fAudTrack1BitratePopUp setEnabled: NO];
5415 [fAudTrack1DrcSlider setEnabled: NO];
5416 [fAudTrack1DrcField setEnabled: NO];
5419 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5420 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5421 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5422 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5423 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5424 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5425 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5426 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5428 [fAudTrack2CodecPopUp removeAllItems];
5429 [fAudTrack2MixPopUp removeAllItems];
5430 [fAudTrack2RatePopUp removeAllItems];
5431 [fAudTrack2BitratePopUp removeAllItems];
5432 [fAudTrack2DrcSlider setFloatValue: 0.00];
5433 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5435 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5437 [fAudTrack2RatePopUp setEnabled: NO];
5438 [fAudTrack2BitratePopUp setEnabled: NO];
5439 [fAudTrack2DrcSlider setEnabled: NO];
5440 [fAudTrack2DrcField setEnabled: NO];
5443 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5444 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5445 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5446 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5447 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5448 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5449 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5450 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5452 [fAudTrack3CodecPopUp removeAllItems];
5453 [fAudTrack3MixPopUp removeAllItems];
5454 [fAudTrack3RatePopUp removeAllItems];
5455 [fAudTrack3BitratePopUp removeAllItems];
5456 [fAudTrack3DrcSlider setFloatValue: 0.00];
5457 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5459 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5461 [fAudTrack3RatePopUp setEnabled: NO];
5462 [fAudTrack3BitratePopUp setEnabled: NO];
5463 [fAudTrack3DrcSlider setEnabled: NO];
5464 [fAudTrack3DrcField setEnabled: NO];
5467 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5468 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5469 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5470 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5471 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5472 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5473 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5474 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5476 [fAudTrack4CodecPopUp removeAllItems];
5477 [fAudTrack4MixPopUp removeAllItems];
5478 [fAudTrack4RatePopUp removeAllItems];
5479 [fAudTrack4BitratePopUp removeAllItems];
5480 [fAudTrack4DrcSlider setFloatValue: 0.00];
5481 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5483 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5485 [fAudTrack4RatePopUp setEnabled: NO];
5486 [fAudTrack4BitratePopUp setEnabled: NO];
5487 [fAudTrack4DrcSlider setEnabled: NO];
5488 [fAudTrack4DrcField setEnabled: NO];
5493 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5496 hb_list_t * list = hb_get_titles( fHandle );
5497 hb_title_t * title = (hb_title_t*)
5498 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5500 hb_audio_config_t * audio;
5502 [sender removeAllItems];
5503 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5504 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5506 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5507 [[sender menu] addItemWithTitle:
5508 [NSString stringWithUTF8String: audio->lang.description]
5509 action: NULL keyEquivalent: @""];
5511 [sender selectItemAtIndex: 0];
5515 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5518 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5519 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5520 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5521 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5523 if (searchPrefixString)
5526 for( int i = 0; i < [sender numberOfItems]; i++ )
5528 /* Try to find the desired search string */
5529 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5531 [sender selectItemAtIndex: i];
5535 /* couldn't find the string, so select the requested "search string not found" item */
5536 /* index of 0 means select the "none" item */
5537 /* index of 1 means select the first audio track */
5538 [sender selectItemAtIndex: selectIndexIfNotFound];
5542 /* if no search string is provided, then select the selectIndexIfNotFound item */
5543 [sender selectItemAtIndex: selectIndexIfNotFound];
5547 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5549 int format = [fDstFormatPopUp indexOfSelectedItem];
5551 /* setup pointers to the appropriate popups for the correct track */
5552 NSPopUpButton * audiocodecPopUp;
5553 NSPopUpButton * audiotrackPopUp;
5554 if (sender == fAudTrack1CodecPopUp)
5556 audiotrackPopUp = fAudLang1PopUp;
5557 audiocodecPopUp = fAudTrack1CodecPopUp;
5559 else if (sender == fAudTrack2CodecPopUp)
5561 audiotrackPopUp = fAudLang2PopUp;
5562 audiocodecPopUp = fAudTrack2CodecPopUp;
5564 else if (sender == fAudTrack3CodecPopUp)
5566 audiotrackPopUp = fAudLang3PopUp;
5567 audiocodecPopUp = fAudTrack3CodecPopUp;
5571 audiotrackPopUp = fAudLang4PopUp;
5572 audiocodecPopUp = fAudTrack4CodecPopUp;
5575 [audiocodecPopUp removeAllItems];
5576 /* Make sure "None" isnt selected in the source track */
5577 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5579 [audiocodecPopUp setEnabled:YES];
5580 NSMenuItem *menuItem;
5581 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5587 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5588 [menuItem setTag: HB_ACODEC_FAAC];
5591 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5592 [menuItem setTag: HB_ACODEC_CA_AAC];
5595 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5596 [menuItem setTag: HB_ACODEC_AC3];
5602 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5603 [menuItem setTag: HB_ACODEC_FAAC];
5605 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5606 [menuItem setTag: HB_ACODEC_CA_AAC];
5608 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5609 [menuItem setTag: HB_ACODEC_AC3];
5611 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5612 [menuItem setTag: HB_ACODEC_DCA];
5614 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5615 [menuItem setTag: HB_ACODEC_LAME];
5617 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5618 [menuItem setTag: HB_ACODEC_VORBIS];
5624 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5625 [menuItem setTag: HB_ACODEC_LAME];
5627 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5628 [menuItem setTag: HB_ACODEC_AC3];
5634 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5635 [menuItem setTag: HB_ACODEC_VORBIS];
5637 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5638 [menuItem setTag: HB_ACODEC_LAME];
5641 [audiocodecPopUp selectItemAtIndex:0];
5645 [audiocodecPopUp setEnabled:NO];
5649 - (IBAction) audioTrackPopUpChanged: (id) sender
5651 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5652 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5655 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5658 /* make sure we have a selected title before continuing */
5659 if (fTitle == NULL) return;
5660 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5661 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5663 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5665 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5667 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5669 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5671 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5673 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5675 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5677 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5680 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5681 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5683 sender = fAudLang1PopUp;
5685 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5687 sender = fAudLang2PopUp;
5689 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5691 sender = fAudLang3PopUp;
5693 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5695 sender = fAudLang4PopUp;
5698 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5699 NSPopUpButton * mixdownPopUp;
5700 NSPopUpButton * audiocodecPopUp;
5701 NSPopUpButton * sampleratePopUp;
5702 NSPopUpButton * bitratePopUp;
5703 if (sender == fAudLang1PopUp)
5705 mixdownPopUp = fAudTrack1MixPopUp;
5706 audiocodecPopUp = fAudTrack1CodecPopUp;
5707 sampleratePopUp = fAudTrack1RatePopUp;
5708 bitratePopUp = fAudTrack1BitratePopUp;
5710 else if (sender == fAudLang2PopUp)
5712 mixdownPopUp = fAudTrack2MixPopUp;
5713 audiocodecPopUp = fAudTrack2CodecPopUp;
5714 sampleratePopUp = fAudTrack2RatePopUp;
5715 bitratePopUp = fAudTrack2BitratePopUp;
5717 else if (sender == fAudLang3PopUp)
5719 mixdownPopUp = fAudTrack3MixPopUp;
5720 audiocodecPopUp = fAudTrack3CodecPopUp;
5721 sampleratePopUp = fAudTrack3RatePopUp;
5722 bitratePopUp = fAudTrack3BitratePopUp;
5726 mixdownPopUp = fAudTrack4MixPopUp;
5727 audiocodecPopUp = fAudTrack4CodecPopUp;
5728 sampleratePopUp = fAudTrack4RatePopUp;
5729 bitratePopUp = fAudTrack4BitratePopUp;
5732 /* get the index of the selected audio Track*/
5733 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5735 /* pointer for the hb_audio_s struct we will use later on */
5736 hb_audio_config_t * audio;
5739 /* check if the audio mixdown controls need their enabled state changing */
5740 [self setEnabledStateOfAudioMixdownControls:nil];
5742 if (thisAudioIndex != -1)
5746 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5748 /* actually manipulate the proper mixdowns here */
5749 /* delete the previous audio mixdown options */
5750 [mixdownPopUp removeAllItems];
5752 acodec = [[audiocodecPopUp selectedItem] tag];
5757 /* find out if our selected output audio codec supports mono and / or 6ch */
5758 /* we also check for an input codec of AC3 or DCA,
5759 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5760 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5761 but this may change in the future, so they are separated for flexibility */
5762 int audioCodecsSupportMono =
5763 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5764 (acodec != HB_ACODEC_LAME);
5765 int audioCodecsSupport6Ch =
5766 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5767 (acodec != HB_ACODEC_LAME);
5769 /* check for AC-3 passthru */
5770 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5773 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5774 [NSString stringWithUTF8String: "AC3 Passthru"]
5775 action: NULL keyEquivalent: @""];
5776 [menuItem setTag: HB_ACODEC_AC3];
5778 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5780 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5781 [NSString stringWithUTF8String: "DTS Passthru"]
5782 action: NULL keyEquivalent: @""];
5783 [menuItem setTag: HB_ACODEC_DCA];
5788 /* add the appropriate audio mixdown menuitems to the popupbutton */
5789 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5790 so that we can reference the mixdown later */
5792 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5793 int minMixdownUsed = 0;
5794 int maxMixdownUsed = 0;
5796 /* get the input channel layout without any lfe channels */
5797 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5799 /* do we want to add a mono option? */
5800 if (audioCodecsSupportMono == 1)
5802 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5803 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5804 action: NULL keyEquivalent: @""];
5805 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5806 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5807 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5810 /* do we want to add a stereo option? */
5811 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5812 /* also offer stereo if we have a stereo-or-better source */
5813 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5815 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5816 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5817 action: NULL keyEquivalent: @""];
5818 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5819 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5820 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5823 /* do we want to add a dolby surround (DPL1) option? */
5824 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5826 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5827 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5828 action: NULL keyEquivalent: @""];
5829 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5830 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5831 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5834 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5835 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5837 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5838 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5839 action: NULL keyEquivalent: @""];
5840 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5841 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5842 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5845 /* do we want to add a 6-channel discrete option? */
5846 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5848 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5849 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5850 action: NULL keyEquivalent: @""];
5851 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5852 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5853 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5856 /* do we want to add an AC-3 passthrough option? */
5857 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5859 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5860 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5861 action: NULL keyEquivalent: @""];
5862 [menuItem setTag: HB_ACODEC_AC3];
5863 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5864 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5867 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5868 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5870 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5871 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5872 action: NULL keyEquivalent: @""];
5873 [menuItem setTag: HB_ACODEC_DCA];
5874 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5875 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5878 /* auto-select the best mixdown based on our saved mixdown preference */
5880 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5881 /* ultimately this should be a prefs option */
5884 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5885 if (mixdownToUse > 0)
5887 useMixdown = mixdownToUse;
5891 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5894 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5895 if (useMixdown > maxMixdownUsed)
5897 useMixdown = maxMixdownUsed;
5900 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5901 if (useMixdown < minMixdownUsed)
5903 useMixdown = minMixdownUsed;
5906 /* select the (possibly-amended) preferred mixdown */
5907 [mixdownPopUp selectItemWithTag: useMixdown];
5910 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5911 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5914 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5916 /* If we are using the avi container, we select MP3 as there is no aac available*/
5917 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5919 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5923 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5927 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5928 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5931 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5933 /* If we are using the avi container, we select MP3 as there is no aac available*/
5934 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5936 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5940 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5944 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5945 [self audioTrackMixdownChanged: mixdownPopUp];
5949 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5951 [self autoSetM4vExtension: sender];
5955 - (IBAction) audioTrackMixdownChanged: (id) sender
5959 /* setup pointers to all of the other audio track controls
5960 * we will need later
5962 NSPopUpButton * mixdownPopUp;
5963 NSPopUpButton * sampleratePopUp;
5964 NSPopUpButton * bitratePopUp;
5965 NSPopUpButton * audiocodecPopUp;
5966 NSPopUpButton * audiotrackPopUp;
5967 NSSlider * drcSlider;
5968 NSTextField * drcField;
5969 if (sender == fAudTrack1MixPopUp)
5971 audiotrackPopUp = fAudLang1PopUp;
5972 audiocodecPopUp = fAudTrack1CodecPopUp;
5973 mixdownPopUp = fAudTrack1MixPopUp;
5974 sampleratePopUp = fAudTrack1RatePopUp;
5975 bitratePopUp = fAudTrack1BitratePopUp;
5976 drcSlider = fAudTrack1DrcSlider;
5977 drcField = fAudTrack1DrcField;
5979 else if (sender == fAudTrack2MixPopUp)
5981 audiotrackPopUp = fAudLang2PopUp;
5982 audiocodecPopUp = fAudTrack2CodecPopUp;
5983 mixdownPopUp = fAudTrack2MixPopUp;
5984 sampleratePopUp = fAudTrack2RatePopUp;
5985 bitratePopUp = fAudTrack2BitratePopUp;
5986 drcSlider = fAudTrack2DrcSlider;
5987 drcField = fAudTrack2DrcField;
5989 else if (sender == fAudTrack3MixPopUp)
5991 audiotrackPopUp = fAudLang3PopUp;
5992 audiocodecPopUp = fAudTrack3CodecPopUp;
5993 mixdownPopUp = fAudTrack3MixPopUp;
5994 sampleratePopUp = fAudTrack3RatePopUp;
5995 bitratePopUp = fAudTrack3BitratePopUp;
5996 drcSlider = fAudTrack3DrcSlider;
5997 drcField = fAudTrack3DrcField;
6001 audiotrackPopUp = fAudLang4PopUp;
6002 audiocodecPopUp = fAudTrack4CodecPopUp;
6003 mixdownPopUp = fAudTrack4MixPopUp;
6004 sampleratePopUp = fAudTrack4RatePopUp;
6005 bitratePopUp = fAudTrack4BitratePopUp;
6006 drcSlider = fAudTrack4DrcSlider;
6007 drcField = fAudTrack4DrcField;
6009 acodec = [[audiocodecPopUp selectedItem] tag];
6010 /* storage variable for the min and max bitrate allowed for this codec */
6016 case HB_ACODEC_FAAC:
6017 /* check if we have a 6ch discrete conversion in either audio track */
6018 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6020 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
6022 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
6028 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
6030 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
6031 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
6036 case HB_ACODEC_CA_AAC:
6037 /* check if we have a 6ch discrete conversion in either audio track */
6038 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6051 case HB_ACODEC_LAME:
6052 /* Lame is happy using our min bitrate of 32 kbps */
6054 /* Lame won't encode if the bitrate is higher than 320 kbps */
6058 case HB_ACODEC_VORBIS:
6059 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6061 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6063 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6069 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6071 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6077 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6083 /* make sure we have a selected title before continuing */
6084 if (fTitle == NULL) return;
6085 /* get the audio so we can find out what input rates are*/
6086 hb_audio_config_t * audio;
6087 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6088 int inputbitrate = audio->in.bitrate / 1000;
6089 int inputsamplerate = audio->in.samplerate;
6091 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6093 [bitratePopUp removeAllItems];
6095 for( int i = 0; i < hb_audio_bitrates_count; i++ )
6097 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6099 /* add a new menuitem for this bitrate */
6100 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6101 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6102 action: NULL keyEquivalent: @""];
6103 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6104 [menuItem setTag: hb_audio_bitrates[i].rate];
6108 /* select the default bitrate (but use 384 for 6-ch AAC) */
6109 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6111 [bitratePopUp selectItemWithTag: 384];
6115 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6118 /* populate and set the sample rate popup */
6119 /* Audio samplerate */
6120 [sampleratePopUp removeAllItems];
6121 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6122 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6123 [menuItem setTag: inputsamplerate];
6125 for( int i = 0; i < hb_audio_rates_count; i++ )
6127 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6128 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6129 action: NULL keyEquivalent: @""];
6130 [menuItem setTag: hb_audio_rates[i].rate];
6132 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6133 * and there is no compelling reason to use anything else as default, though the users default
6134 * preset will likely override any setting chosen here.
6136 [sampleratePopUp selectItemWithTag: inputsamplerate];
6139 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6140 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6141 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6143 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6146 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6147 [bitratePopUp removeAllItems];
6148 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6149 [NSString stringWithFormat:@"%d", inputbitrate]
6150 action: NULL keyEquivalent: @""];
6151 [menuItem setTag: inputbitrate];
6152 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6153 [bitratePopUp setEnabled: NO];
6154 [sampleratePopUp setEnabled: NO];
6156 [drcSlider setFloatValue: 0.00];
6157 [self audioDRCSliderChanged: drcSlider];
6158 [drcSlider setEnabled: NO];
6159 [drcField setEnabled: NO];
6163 [sampleratePopUp setEnabled: YES];
6164 [bitratePopUp setEnabled: YES];
6165 [drcSlider setEnabled: YES];
6166 [drcField setEnabled: YES];
6168 [self calculateBitrate:nil];
6171 - (IBAction) audioDRCSliderChanged: (id) sender
6173 NSSlider * drcSlider;
6174 NSTextField * drcField;
6175 if (sender == fAudTrack1DrcSlider)
6177 drcSlider = fAudTrack1DrcSlider;
6178 drcField = fAudTrack1DrcField;
6180 else if (sender == fAudTrack2DrcSlider)
6182 drcSlider = fAudTrack2DrcSlider;
6183 drcField = fAudTrack2DrcField;
6185 else if (sender == fAudTrack3DrcSlider)
6187 drcSlider = fAudTrack3DrcSlider;
6188 drcField = fAudTrack3DrcField;
6192 drcSlider = fAudTrack4DrcSlider;
6193 drcField = fAudTrack4DrcField;
6196 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6197 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6199 [drcSlider setFloatValue:1.0];
6203 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6204 /* For now, do not call this until we have an intelligent way to determine audio track selections
6205 * compared to presets
6207 //[self customSettingUsed: sender];
6212 - (IBAction) browseImportSrtFile: (id) sender
6215 NSOpenPanel * panel;
6217 panel = [NSOpenPanel openPanel];
6218 [panel setAllowsMultipleSelection: NO];
6219 [panel setCanChooseFiles: YES];
6220 [panel setCanChooseDirectories: NO ];
6221 NSString * sourceDirectory;
6222 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6224 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6228 sourceDirectory = @"~/Desktop";
6229 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6231 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6232 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6233 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6234 modalForWindow: fWindow modalDelegate: self
6235 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6236 contextInfo: sender];
6239 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6240 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6242 if( returnCode == NSOKButton )
6244 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6245 NSString *importSrtFilePath = [sheet filename];
6246 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6248 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6249 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6251 [fSubtitlesTable reloadData];
6257 #pragma mark Open New Windows
6259 - (IBAction) openHomepage: (id) sender
6261 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6262 URLWithString:@"http://handbrake.fr/"]];
6265 - (IBAction) openForums: (id) sender
6267 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6268 URLWithString:@"http://handbrake.fr/forum/"]];
6270 - (IBAction) openUserGuide: (id) sender
6272 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6273 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6277 * Shows debug output window.
6279 - (IBAction)showDebugOutputPanel:(id)sender
6281 [outputPanel showOutputPanel:sender];
6285 * Shows preferences window.
6287 - (IBAction) showPreferencesWindow: (id) sender
6289 NSWindow * window = [fPreferencesController window];
6290 if (![window isVisible])
6293 [window makeKeyAndOrderFront: nil];
6297 * Shows queue window.
6299 - (IBAction) showQueueWindow:(id)sender
6301 [fQueueController showQueueWindow:sender];
6305 - (IBAction) toggleDrawer:(id)sender {
6306 [fPresetDrawer toggle:self];
6310 * Shows Picture Settings Window.
6313 - (IBAction) showPicturePanel: (id) sender
6315 [fPictureController showPictureWindow:sender];
6318 - (void) picturePanelFullScreen
6320 [fPictureController setToFullScreenMode];
6323 - (void) picturePanelWindowed
6325 [fPictureController setToWindowedMode];
6328 - (IBAction) showPreviewWindow: (id) sender
6330 [fPictureController showPreviewWindow:sender];
6334 #pragma mark Preset Outline View Methods
6335 #pragma mark - Required
6336 /* These are required by the NSOutlineView Datasource Delegate */
6339 /* used to specify the number of levels to show for each item */
6340 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6342 /* currently use no levels to test outline view viability */
6343 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6345 return [UserPresets count];
6349 /* we need to return the count of the array in ChildrenArray for this folder */
6350 NSArray *children = nil;
6351 children = [item objectForKey:@"ChildrenArray"];
6352 if ([children count] > 0)
6354 return [children count];
6363 /* We use this to deterimine children of an item */
6364 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6367 /* we need to return the count of the array in ChildrenArray for this folder */
6368 NSArray *children = nil;
6371 children = UserPresets;
6375 if ([item objectForKey:@"ChildrenArray"])
6377 children = [item objectForKey:@"ChildrenArray"];
6380 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6386 return [children objectAtIndex:index];
6390 // We are only one level deep, so we can't be asked about children
6391 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6395 /* We use this to determine if an item should be expandable */
6396 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6399 /* we need to return the count of the array in ChildrenArray for this folder */
6400 NSArray *children= nil;
6403 children = UserPresets;
6407 if ([item objectForKey:@"ChildrenArray"])
6409 children = [item objectForKey:@"ChildrenArray"];
6413 /* To deterimine if an item should show a disclosure triangle
6414 * we could do it by the children count as so:
6415 * if ([children count] < 1)
6416 * However, lets leave the triangle show even if there are no
6417 * children to help indicate a folder, just like folder in the
6418 * finder can show a disclosure triangle even when empty
6421 /* We need to determine if the item is a folder */
6422 if ([[item objectForKey:@"Folder"] intValue] == 1)
6433 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6435 // Our outline view has no levels, but we can still expand every item. Doing so
6436 // just makes the row taller. See heightOfRowByItem below.
6437 //return ![(HBQueueOutlineView*)outlineView isDragging];
6443 /* Used to tell the outline view which information is to be displayed per item */
6444 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6446 /* We have two columns right now, icon and PresetName */
6448 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6450 return [item objectForKey:@"PresetName"];
6459 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6461 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6463 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6465 return [NSKeyedArchiver archivedDataWithRootObject:item];
6468 #pragma mark - Added Functionality (optional)
6469 /* Use to customize the font and display characteristics of the title cell */
6470 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6472 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6476 NSColor *shadowColor;
6477 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6478 /*check to see if its a selected row */
6479 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6482 fontColor = [NSColor blackColor];
6483 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6487 if ([[item objectForKey:@"Type"] intValue] == 0)
6489 fontColor = [NSColor blueColor];
6491 else // User created preset, use a black font
6493 fontColor = [NSColor blackColor];
6495 /* check to see if its a folder */
6496 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6498 //fontColor = [NSColor greenColor];
6503 /* We use Bold Text for the HB Default */
6504 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6506 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6508 /* We use Bold Text for the User Specified Default */
6509 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6511 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6515 [cell setTextColor:fontColor];
6516 [cell setFont:txtFont];
6521 /* We use this to edit the name field in the outline view */
6522 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6524 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6529 [theRecord setObject:object forKey:@"PresetName"];
6533 [fPresetsOutlineView reloadData];
6534 /* We save all of the preset data here */
6538 /* We use this to provide tooltips for the items in the presets outline view */
6539 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6541 //if ([[tc identifier] isEqualToString:@"PresetName"])
6543 /* initialize the tooltip contents variable */
6545 /* if there is a description for the preset, we show it in the tooltip */
6546 if ([item objectForKey:@"PresetDescription"])
6548 loc_tip = [item objectForKey:@"PresetDescription"];
6553 loc_tip = @"No description available";
6560 #pragma mark Preset Outline View Methods (dragging related)
6563 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6565 // Dragging is only allowed for custom presets.
6566 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6567 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6571 // Don't retain since this is just holding temporaral drag information, and it is
6572 //only used during a drag! We could put this in the pboard actually.
6573 fDraggedNodes = items;
6574 // Provide data for our custom type, and simple NSStrings.
6575 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6577 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6578 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6583 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6586 // Don't allow dropping ONTO an item since they can't really contain any children.
6588 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6589 if (isOnDropTypeProposal)
6590 return NSDragOperationNone;
6592 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6595 index = [fPresetsOutlineView rowForItem: item] + 1;
6599 // Don't allow dropping into the Built In Presets.
6600 if (index < presetCurrentBuiltInCount)
6602 return NSDragOperationNone;
6603 index = MAX (index, presetCurrentBuiltInCount);
6606 [outlineView setDropItem:item dropChildIndex:index];
6607 return NSDragOperationGeneric;
6612 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6614 /* first, lets see if we are dropping into a folder */
6615 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6617 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6618 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6619 [childrenArray addObject:item];
6620 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6621 [childrenArray autorelease];
6623 else // We are not, so we just move the preset into the existing array
6625 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6627 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6628 while (obj = [enumerator nextObject])
6630 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6632 // Successful drop, lets rearrange the view and save it all
6633 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6635 [fPresetsOutlineView reloadData];
6640 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6642 NSUInteger index = [indexSet lastIndex];
6643 NSUInteger aboveInsertIndexCount = 0;
6645 NSUInteger removeIndex;
6647 if (index >= insertIndex)
6649 removeIndex = index + aboveInsertIndexCount;
6650 aboveInsertIndexCount++;
6654 removeIndex = index;
6658 id object = [[array objectAtIndex:removeIndex] retain];
6659 [array removeObjectAtIndex:removeIndex];
6660 [array insertObject:object atIndex:insertIndex];
6663 index = [indexSet indexLessThanIndex:index];
6668 #pragma mark - Functional Preset NSOutlineView Methods
6670 - (IBAction)selectPreset:(id)sender
6673 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6675 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6676 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6678 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6680 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6684 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6688 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6689 [self formatPopUpChanged:nil];
6691 /* Chapter Markers*/
6692 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6693 /* check to see if we have only one chapter */
6694 [self chapterPopUpChanged:nil];
6696 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6697 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6698 /* Mux mp4 with http optimization */
6699 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6702 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6703 /* We set the advanced opt string here if applicable*/
6704 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6706 /* Lets run through the following functions to get variables set there */
6707 [self videoEncoderPopUpChanged:nil];
6708 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6709 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6710 [self calculateBitrate:nil];
6713 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6715 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6716 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6718 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6719 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6720 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6721 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6722 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6723 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6725 /* For the quality slider we need to convert the old percent's to the new rf scales */
6726 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6727 [fVidQualitySlider setFloatValue:rf];
6732 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6733 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6735 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6739 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6740 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6744 [self videoMatrixChanged:nil];
6746 /* Video framerate */
6747 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6748 detected framerate in the fVidRatePopUp so we use index 0*/
6749 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6751 [fVidRatePopUp selectItemAtIndex: 0];
6755 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6759 /* 2 Pass Encoding */
6760 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6761 [self twoPassCheckboxChanged:nil];
6763 /* Turbo 1st pass for 2 Pass Encoding */
6764 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6767 /* First we check to see if we are using the current audio track layout based on AudioList array */
6768 if ([chosenPreset objectForKey:@"AudioList"])
6771 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6772 NSPopUpButton * trackLangPopUp = nil;
6773 NSPopUpButton * mixdownPopUp = nil;
6774 NSPopUpButton * audiocodecPopUp = nil;
6775 NSPopUpButton * sampleratePopUp = nil;
6776 NSPopUpButton * bitratePopUp = nil;
6777 NSSlider * drcSlider = nil;
6780 /* Populate the audio widgets based on the contents of the AudioList array */
6782 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6784 while (tempObject = [enumerator nextObject])
6789 trackLangPopUp = fAudLang1PopUp;
6790 mixdownPopUp = fAudTrack1MixPopUp;
6791 audiocodecPopUp = fAudTrack1CodecPopUp;
6792 sampleratePopUp = fAudTrack1RatePopUp;
6793 bitratePopUp = fAudTrack1BitratePopUp;
6794 drcSlider = fAudTrack1DrcSlider;
6798 trackLangPopUp = fAudLang2PopUp;
6799 mixdownPopUp = fAudTrack2MixPopUp;
6800 audiocodecPopUp = fAudTrack2CodecPopUp;
6801 sampleratePopUp = fAudTrack2RatePopUp;
6802 bitratePopUp = fAudTrack2BitratePopUp;
6803 drcSlider = fAudTrack2DrcSlider;
6807 trackLangPopUp = fAudLang3PopUp;
6808 mixdownPopUp = fAudTrack3MixPopUp;
6809 audiocodecPopUp = fAudTrack3CodecPopUp;
6810 sampleratePopUp = fAudTrack3RatePopUp;
6811 bitratePopUp = fAudTrack3BitratePopUp;
6812 drcSlider = fAudTrack3DrcSlider;
6816 trackLangPopUp = fAudLang4PopUp;
6817 mixdownPopUp = fAudTrack4MixPopUp;
6818 audiocodecPopUp = fAudTrack4CodecPopUp;
6819 sampleratePopUp = fAudTrack4RatePopUp;
6820 bitratePopUp = fAudTrack4BitratePopUp;
6821 drcSlider = fAudTrack4DrcSlider;
6825 if ([trackLangPopUp indexOfSelectedItem] == 0)
6827 [trackLangPopUp selectItemAtIndex: 1];
6829 [self audioTrackPopUpChanged: trackLangPopUp];
6830 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6831 /* check our pref for core audio and use it in place of faac if applicable */
6832 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6833 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6835 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6838 [self audioTrackPopUpChanged: audiocodecPopUp];
6839 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6840 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6842 if ([mixdownPopUp selectedItem] == nil)
6844 [self audioTrackPopUpChanged: audiocodecPopUp];
6846 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6847 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6848 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6850 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6852 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6853 [self audioDRCSliderChanged: drcSlider];
6856 /* 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,
6857 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6861 /* 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". */
6862 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6864 hb_audio_config_t * audio;
6865 /* get the audio source audio codec */
6866 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6867 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6868 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6870 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6871 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6873 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6875 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6877 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6879 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6880 [trackLangPopUp selectItemAtIndex: 0];
6881 [self audioTrackPopUpChanged: trackLangPopUp];
6887 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6891 [fAudLang4PopUp selectItemAtIndex: 0];
6892 [self audioTrackPopUpChanged: fAudLang4PopUp];
6896 [fAudLang3PopUp selectItemAtIndex: 0];
6897 [self audioTrackPopUpChanged: fAudLang3PopUp];
6901 [fAudLang2PopUp selectItemAtIndex: 0];
6902 [self audioTrackPopUpChanged: fAudLang2PopUp];
6910 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6912 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6914 [fAudLang1PopUp selectItemAtIndex: 1];
6916 [self audioTrackPopUpChanged: fAudLang1PopUp];
6917 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6918 /* check our pref for core audio and use it in place of faac if applicable */
6919 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6920 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6922 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6924 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6925 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6926 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6928 if ([fAudTrack1MixPopUp selectedItem] == nil)
6930 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6932 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6933 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6934 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6936 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6938 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6939 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6942 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6944 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6946 [fAudLang2PopUp selectItemAtIndex: 1];
6948 [self audioTrackPopUpChanged: fAudLang2PopUp];
6949 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6950 /* check our pref for core audio and use it in place of faac if applicable */
6951 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6952 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6954 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6956 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6957 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6958 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6960 if ([fAudTrack2MixPopUp selectedItem] == nil)
6962 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6964 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6965 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6966 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6968 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6970 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6971 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6973 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6975 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6977 [fAudLang3PopUp selectItemAtIndex: 1];
6979 [self audioTrackPopUpChanged: fAudLang3PopUp];
6980 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6981 /* check our pref for core audio and use it in place of faac if applicable */
6982 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6983 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6985 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6987 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6988 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6989 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6991 if ([fAudTrack3MixPopUp selectedItem] == nil)
6993 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6995 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6996 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6997 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6999 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
7001 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
7002 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
7004 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
7006 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
7008 [fAudLang4PopUp selectItemAtIndex: 1];
7010 [self audioTrackPopUpChanged: fAudLang4PopUp];
7011 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
7012 /* check our pref for core audio and use it in place of faac if applicable */
7013 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
7014 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
7016 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
7018 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7019 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
7020 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7022 if ([fAudTrack4MixPopUp selectedItem] == nil)
7024 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7026 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7027 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7028 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7030 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7032 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7033 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7036 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7038 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7040 [fAudLang2PopUp selectItemAtIndex: 0];
7041 [self audioTrackPopUpChanged: fAudLang2PopUp];
7043 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7045 [fAudLang3PopUp selectItemAtIndex: 0];
7046 [self audioTrackPopUpChanged: fAudLang3PopUp];
7048 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7050 [fAudLang4PopUp selectItemAtIndex: 0];
7051 [self audioTrackPopUpChanged: fAudLang4PopUp];
7056 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7057 /* Forced Subtitles */
7058 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7060 /* Picture Settings */
7061 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7062 * height, width, keep ar, anamorphic and crop settings.
7063 * picture filters are handled separately below.
7065 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
7066 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
7067 * preset completely ignores any picture sizing values in the preset.
7069 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
7071 hb_job_t * job = fTitle->job;
7073 /* If Cropping is set to custom, then recall all four crop values from
7074 when the preset was created and apply them */
7075 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
7077 [fPictureController setAutoCrop:NO];
7079 /* Here we use the custom crop values saved at the time the preset was saved */
7080 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
7081 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
7082 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
7083 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
7086 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7088 [fPictureController setAutoCrop:YES];
7089 /* Here we use the auto crop values determined right after scan */
7090 job->crop[0] = AutoCropTop;
7091 job->crop[1] = AutoCropBottom;
7092 job->crop[2] = AutoCropLeft;
7093 job->crop[3] = AutoCropRight;
7098 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7099 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
7101 /* Use Max Picture settings for whatever the dvd is.*/
7102 [self revertPictureSizeToMax:nil];
7103 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7104 if (job->keep_ratio == 1)
7106 hb_fix_aspect( job, HB_KEEP_WIDTH );
7107 if( job->height > fTitle->height )
7109 job->height = fTitle->height;
7110 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7113 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7115 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7117 /* we check to make sure the presets width/height does not exceed the sources width/height */
7118 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
7120 /* if so, then we use the sources height and width to avoid scaling up */
7121 //job->width = fTitle->width;
7122 //job->height = fTitle->height;
7123 [self revertPictureSizeToMax:nil];
7125 else // source width/height is >= the preset height/width
7127 /* we can go ahead and use the presets values for height and width */
7128 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
7129 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
7131 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7132 if (job->keep_ratio == 1)
7134 hb_fix_aspect( job, HB_KEEP_WIDTH );
7135 if( job->height > fTitle->height )
7137 job->height = fTitle->height;
7138 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7141 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7147 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7148 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7152 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7153 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7154 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7157 [fPictureController setUseDecomb:1];
7158 [fPictureController setDecomb:0];
7159 [fPictureController setDeinterlace:0];
7160 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7162 /* we are using decomb */
7164 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7166 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7168 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7169 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7171 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7177 /* We are using Deinterlace */
7179 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7181 [fPictureController setUseDecomb:0];
7182 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7183 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7184 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7186 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7193 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7195 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7196 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7197 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7199 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7204 [fPictureController setDetelecine:0];
7208 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7210 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7211 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7212 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7214 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7219 [fPictureController setDenoise:0];
7223 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7225 /* if its a one, then its the old on/off deblock, set on to 5*/
7226 [fPictureController setDeblock:5];
7230 /* use the settings intValue */
7231 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7234 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7236 [fPictureController setGrayscale:1];
7240 [fPictureController setGrayscale:0];
7243 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7244 [fPictureController SetTitle:fTitle];
7245 [fPictureController SetTitle:fTitle];
7246 [self calculatePictureSizing:nil];
7252 #pragma mark Manage Presets
7254 - (void) loadPresets {
7255 /* We declare the default NSFileManager into fileManager */
7256 NSFileManager * fileManager = [NSFileManager defaultManager];
7257 /*We define the location of the user presets file */
7258 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7259 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7260 /* We check for the presets.plist */
7261 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7263 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7266 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7267 if (nil == UserPresets)
7269 UserPresets = [[NSMutableArray alloc] init];
7270 [self addFactoryPresets:nil];
7272 [fPresetsOutlineView reloadData];
7274 [self checkBuiltInsForUpdates];
7277 - (void) checkBuiltInsForUpdates {
7279 BOOL updateBuiltInPresets = NO;
7281 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7283 while (tempObject = [enumerator nextObject])
7285 /* iterate through the built in presets to see if any have an old build number */
7286 NSMutableDictionary *thisPresetDict = tempObject;
7287 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7288 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7290 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7292 updateBuiltInPresets = YES;
7297 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7298 if ( updateBuiltInPresets == YES)
7300 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7302 /* Show an alert window that built in presets will be updated */
7303 /*On Screen Notification*/
7306 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7307 [NSApp requestUserAttention:NSCriticalRequest];
7309 /* when alert is dismissed, go ahead and update the built in presets */
7310 [self addFactoryPresets:nil];
7316 - (IBAction) showAddPresetPanel: (id) sender
7318 /* Deselect the currently selected Preset if there is one*/
7319 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7321 /* Populate the preset picture settings popup here */
7322 [fPresetNewPicSettingsPopUp removeAllItems];
7323 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7324 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7325 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7326 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7327 /* Uncheck the preset use filters checkbox */
7328 [fPresetNewPicFiltersCheck setState:NSOffState];
7329 // fPresetNewFolderCheck
7330 [fPresetNewFolderCheck setState:NSOffState];
7331 /* Erase info from the input fields*/
7332 [fPresetNewName setStringValue: @""];
7333 [fPresetNewDesc setStringValue: @""];
7334 /* Show the panel */
7335 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7338 - (IBAction) closeAddPresetPanel: (id) sender
7340 [NSApp endSheet: fAddPresetPanel];
7341 [fAddPresetPanel orderOut: self];
7344 - (IBAction)addUserPreset:(id)sender
7346 if (![[fPresetNewName stringValue] length])
7347 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7350 /* Here we create a custom user preset */
7351 [UserPresets addObject:[self createPreset]];
7354 [self closeAddPresetPanel:nil];
7361 /* We Reload the New Table data for presets */
7362 [fPresetsOutlineView reloadData];
7363 /* We save all of the preset data here */
7371 /* We Sort the Presets By Factory or Custom */
7372 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7373 ascending:YES] autorelease];
7374 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7376 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7377 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7378 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7381 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7382 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7383 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7384 [UserPresets setArray:sortedArray];
7389 - (IBAction)insertPreset:(id)sender
7391 int index = [fPresetsOutlineView selectedRow];
7392 [UserPresets insertObject:[self createPreset] atIndex:index];
7393 [fPresetsOutlineView reloadData];
7397 - (NSDictionary *)createPreset
7399 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7400 /* Preset build number */
7401 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7402 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7403 /* Get the New Preset Name from the field in the AddPresetPanel */
7404 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7405 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7406 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7407 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7408 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7409 /*Set whether or not this is default, at creation set to 0*/
7410 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7411 if ([fPresetNewFolderCheck state] == YES)
7413 /* initialize and set an empty array for children here since we are a new folder */
7414 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7415 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7416 [childrenArray autorelease];
7418 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7420 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7421 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7422 /* Get whether or not to use the current Picture Filter settings for the preset */
7423 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7425 /* Get New Preset Description from the field in the AddPresetPanel*/
7426 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7428 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7429 /* Chapter Markers fCreateChapterMarkers*/
7430 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7431 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7432 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7433 /* Mux mp4 with http optimization */
7434 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7435 /* Add iPod uuid atom */
7436 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7440 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7441 /* x264 Option String */
7442 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7444 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7445 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7446 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7447 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7449 /* Video framerate */
7450 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7452 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7454 else // we can record the actual titleOfSelectedItem
7456 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7459 /* 2 Pass Encoding */
7460 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7461 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7462 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7463 /*Picture Settings*/
7464 hb_job_t * job = fTitle->job;
7465 /* Picture Sizing */
7466 /* Use Max Picture settings for whatever the dvd is.*/
7467 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7468 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7469 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7470 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7471 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7473 /* Set crop settings here */
7474 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7475 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7476 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7477 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7478 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7480 /* Picture Filters */
7481 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7482 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7483 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7484 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7485 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7486 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7487 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7488 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7489 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7490 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7491 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7494 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7495 /* we actually call the methods for the nests here */
7496 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7498 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7499 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7500 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7501 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7502 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7503 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7504 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7505 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7506 [audioTrack1Array autorelease];
7507 [audioListArray addObject:audioTrack1Array];
7510 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7512 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7513 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7514 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7515 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7516 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7517 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7518 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7519 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7520 [audioTrack2Array autorelease];
7521 [audioListArray addObject:audioTrack2Array];
7524 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7526 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7527 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7528 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7529 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7530 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7531 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7532 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7533 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7534 [audioTrack3Array autorelease];
7535 [audioListArray addObject:audioTrack3Array];
7538 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7540 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7541 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7542 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7543 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7544 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7545 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7546 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7547 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7548 [audioTrack4Array autorelease];
7549 [audioListArray addObject:audioTrack4Array];
7553 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7556 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7557 * subititle array code. */
7559 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7560 /* Forced Subtitles */
7561 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7563 [preset autorelease];
7570 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7571 /* We get the default preset in case it changed */
7572 [self getDefaultPresets:nil];
7576 - (IBAction)deletePreset:(id)sender
7580 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7584 /* Alert user before deleting preset */
7586 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7588 if ( status == NSAlertDefaultReturn )
7590 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7591 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7592 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7594 NSEnumerator *enumerator;
7595 NSMutableArray *presetsArrayToMod;
7596 NSMutableArray *tempArray;
7598 /* If we are a root level preset, we are modding the UserPresets array */
7599 if (presetToModLevel == 0)
7601 presetsArrayToMod = UserPresets;
7603 else // We have a parent preset, so we modify the chidren array object for key
7605 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7608 enumerator = [presetsArrayToMod objectEnumerator];
7609 tempArray = [NSMutableArray array];
7611 while (tempObject = [enumerator nextObject])
7613 NSDictionary *thisPresetDict = tempObject;
7614 if (thisPresetDict == presetToMod)
7616 [tempArray addObject:tempObject];
7620 [presetsArrayToMod removeObjectsInArray:tempArray];
7621 [fPresetsOutlineView reloadData];
7628 #pragma mark Import Export Preset(s)
7630 - (IBAction) browseExportPresetFile: (id) sender
7632 /* Open a panel to let the user choose where and how to save the export file */
7633 NSSavePanel * panel = [NSSavePanel savePanel];
7634 /* We get the current file name and path from the destination field here */
7635 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7637 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7638 modalForWindow: fWindow modalDelegate: self
7639 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7643 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7644 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7646 if( returnCode == NSOKButton )
7648 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7649 NSString *exportPresetsFile = [sheet filename];
7650 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7651 /* We check for the presets.plist */
7652 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7654 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7656 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7657 if (nil == presetsToExport)
7659 presetsToExport = [[NSMutableArray alloc] init];
7661 /* now get and add selected presets to export */
7664 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7666 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7667 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7675 - (IBAction) browseImportPresetFile: (id) sender
7678 NSOpenPanel * panel;
7680 panel = [NSOpenPanel openPanel];
7681 [panel setAllowsMultipleSelection: NO];
7682 [panel setCanChooseFiles: YES];
7683 [panel setCanChooseDirectories: NO ];
7684 NSString * sourceDirectory;
7685 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7687 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7691 sourceDirectory = @"~/Desktop";
7692 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7694 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7695 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7697 /* set this for allowed file types, not sure if we should allow xml or not */
7698 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7699 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7700 modalForWindow: fWindow modalDelegate: self
7701 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7702 contextInfo: sender];
7705 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7706 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7708 if( returnCode == NSOKButton )
7710 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7711 NSString *importPresetsFile = [sheet filename];
7712 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7713 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7714 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7715 /* iterate though the new array of presets to import and add them to our presets array */
7717 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7719 while (tempObject = [enumerator nextObject])
7721 /* make any changes to the incoming preset we see fit */
7722 /* make sure the incoming preset is not tagged as default */
7723 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7724 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7725 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7726 [tempObject setObject:prependedName forKey:@"PresetName"];
7728 /* actually add the new preset to our presets array */
7729 [UserPresets addObject:tempObject];
7732 [presetsToImport autorelease];
7740 #pragma mark Manage Default Preset
7742 - (IBAction)getDefaultPresets:(id)sender
7744 presetHbDefault = nil;
7745 presetUserDefault = nil;
7746 presetUserDefaultParent = nil;
7747 presetUserDefaultParentParent = nil;
7748 NSMutableDictionary *presetHbDefaultParent = nil;
7749 NSMutableDictionary *presetHbDefaultParentParent = nil;
7752 BOOL userDefaultFound = NO;
7753 presetCurrentBuiltInCount = 0;
7754 /* First we iterate through the root UserPresets array to check for defaults */
7755 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7757 while (tempObject = [enumerator nextObject])
7759 NSMutableDictionary *thisPresetDict = tempObject;
7760 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7762 presetHbDefault = thisPresetDict;
7764 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7766 presetUserDefault = thisPresetDict;
7767 userDefaultFound = YES;
7769 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7771 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7775 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7776 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7778 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7779 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7781 while (tempObject = [enumerator nextObject])
7783 NSMutableDictionary *thisPresetDict = tempObject;
7784 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7786 presetHbDefault = thisPresetDict;
7787 presetHbDefaultParent = thisPresetDictParent;
7789 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7791 presetUserDefault = thisPresetDict;
7792 presetUserDefaultParent = thisPresetDictParent;
7793 userDefaultFound = YES;
7796 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7797 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7799 NSMutableDictionary *thisPresetDictParentParent = 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;
7809 presetHbDefaultParentParent = thisPresetDictParentParent;
7811 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7813 presetUserDefault = thisPresetDict;
7814 presetUserDefaultParent = thisPresetDictParent;
7815 presetUserDefaultParentParent = thisPresetDictParentParent;
7816 userDefaultFound = YES;
7825 /* check to see if a user specified preset was found, if not then assign the parents for
7826 * the presetHbDefault so that we can open the parents for the nested presets
7828 if (userDefaultFound == NO)
7830 presetUserDefaultParent = presetHbDefaultParent;
7831 presetUserDefaultParentParent = presetHbDefaultParentParent;
7835 - (IBAction)setDefaultPreset:(id)sender
7837 /* We need to determine if the item is a folder */
7838 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7844 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7846 /* First make sure the old user specified default preset is removed */
7847 while (tempObject = [enumerator nextObject])
7849 NSMutableDictionary *thisPresetDict = tempObject;
7850 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7852 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7855 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7856 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7858 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7861 while (tempObject = [enumerator nextObject])
7863 NSMutableDictionary *thisPresetDict1 = tempObject;
7864 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7866 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7868 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7869 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7871 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7874 while (tempObject = [enumerator nextObject])
7876 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7878 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7891 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7892 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7893 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7896 NSMutableArray *presetsArrayToMod;
7897 NSMutableArray *tempArray;
7899 /* If we are a root level preset, we are modding the UserPresets array */
7900 if (presetToModLevel == 0)
7902 presetsArrayToMod = UserPresets;
7904 else // We have a parent preset, so we modify the chidren array object for key
7906 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7909 enumerator = [presetsArrayToMod objectEnumerator];
7910 tempArray = [NSMutableArray array];
7912 while (tempObject = [enumerator nextObject])
7914 NSDictionary *thisPresetDict = tempObject;
7915 if (thisPresetDict == presetToMod)
7917 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7919 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7926 /* We save all of the preset data here */
7928 /* We Reload the New Table data for presets */
7929 [fPresetsOutlineView reloadData];
7932 - (IBAction)selectDefaultPreset:(id)sender
7934 NSMutableDictionary *presetToMod;
7935 /* if there is a user specified default, we use it */
7936 if (presetUserDefault)
7938 presetToMod = presetUserDefault;
7940 else if (presetHbDefault) //else we use the built in default presetHbDefault
7942 presetToMod = presetHbDefault;
7949 if (presetUserDefaultParent != nil)
7951 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7954 if (presetUserDefaultParentParent != nil)
7956 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7960 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7961 [self selectPreset:nil];
7966 #pragma mark Manage Built In Presets
7969 - (IBAction)deleteFactoryPresets:(id)sender
7972 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7976 NSMutableArray *tempArray;
7979 tempArray = [NSMutableArray array];
7980 /* we look here to see if the preset is we move on to the next one */
7981 while ( tempObject = [enumerator nextObject] )
7983 /* if the preset is "Factory" then we put it in the array of
7984 presets to delete */
7985 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7987 [tempArray addObject:tempObject];
7991 [UserPresets removeObjectsInArray:tempArray];
7992 [fPresetsOutlineView reloadData];
7997 /* We use this method to recreate new, updated factory presets */
7998 - (IBAction)addFactoryPresets:(id)sender
8001 /* First, we delete any existing built in presets */
8002 [self deleteFactoryPresets: sender];
8003 /* Then we generate new built in presets programmatically with fPresetsBuiltin
8004 * which is all setup in HBPresets.h and HBPresets.m*/
8005 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
8006 /* update build number for built in presets */
8007 /* iterate though the new array of presets to import and add them to our presets array */
8009 NSEnumerator *enumerator = [UserPresets objectEnumerator];
8011 while (tempObject = [enumerator nextObject])
8013 /* Record the apps current build number in the PresetBuildNumber key */
8014 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
8016 /* Preset build number */
8017 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8021 /* report the built in preset updating to the activity log */
8022 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8032 /*******************************
8033 * Subclass of the HBPresetsOutlineView *
8034 *******************************/
8036 @implementation HBPresetsOutlineView
8037 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8041 // By default, NSTableView only drags an image of the first column. Change this to
8042 // drag an image of the queue's icon and PresetName columns.
8043 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8044 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8049 - (void) mouseDown:(NSEvent *)theEvent
8051 [super mouseDown:theEvent];
8057 - (BOOL) isDragging;