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:NO];
330 [fAdvancedOptions setView:fAdvancedView];
332 /* lets setup our presets drawer for drag and drop here */
333 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
334 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
335 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
337 /* Initialize currentScanCount so HB can use it to
338 evaluate successive scans */
339 currentScanCount = 0;
342 /* Init UserPresets .plist */
345 /* Init QueueFile .plist */
346 [self loadQueueFile];
348 fRipIndicatorShown = NO; // initially out of view in the nib
350 /* For 64 bit builds, the threaded animation in the progress
351 * indicators conflicts with the animation in the advanced tab
352 * for reasons not completely clear. jbrjake found a note in the
353 * 10.5 dev notes regarding this possiblility. It was also noted
354 * that unless specified, setUsesThreadedAnimation defaults to true.
355 * So, at least for now we set the indicator animation to NO for
356 * both the scan and regular progress indicators for both 32 and 64 bit
357 * as it test out fine on both and there is no reason our progress indicators
358 * should require their own thread.
361 [fScanIndicator setUsesThreadedAnimation:NO];
362 [fRipIndicator setUsesThreadedAnimation:NO];
366 /* Show/Dont Show Presets drawer upon launch based
367 on user preference DefaultPresetsDrawerShow*/
368 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
370 [fPresetDrawer setDelegate:self];
371 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
372 stringForKey:@"Drawer Size"] );
373 if( drawerSize.width )
374 [fPresetDrawer setContentSize: drawerSize];
375 [fPresetDrawer open];
378 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
379 [fSrcAngleLabel setHidden:YES];
380 [fSrcAnglePopUp setHidden:YES];
382 /* Setup the start / stop popup */
383 [fEncodeStartStopPopUp removeAllItems];
384 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
385 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
386 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
387 /* Align the start / stop widgets with the chapter popups */
388 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
389 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
391 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
392 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
395 NSMenuItem *menuItem;
396 [fDstFormatPopUp removeAllItems];
398 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
399 [menuItem setTag: HB_MUX_MP4];
401 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
402 [menuItem setTag: HB_MUX_MKV];
404 [fDstFormatPopUp selectItemAtIndex: 0];
406 [self formatPopUpChanged:nil];
408 /* We enable the create chapters checkbox here since we are .mp4 */
409 [fCreateChapterMarkers setEnabled: YES];
410 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
412 [fCreateChapterMarkers setState: NSOnState];
418 [fDstFile2Field setStringValue: [NSString stringWithFormat:
419 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
422 [fVidEncoderPopUp removeAllItems];
423 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
427 [fVidTargetSizeField setIntValue: 700];
428 [fVidBitrateField setIntValue: 1000];
430 [fVidQualityMatrix selectCell: fVidBitrateCell];
431 [self videoMatrixChanged:nil];
433 /* Video framerate */
434 [fVidRatePopUp removeAllItems];
435 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
436 for( int i = 0; i < hb_video_rates_count; i++ )
438 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
440 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
441 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
443 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
445 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
446 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
448 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
450 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
451 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
455 [fVidRatePopUp addItemWithTitle:
456 [NSString stringWithUTF8String: hb_video_rates[i].string]];
459 [fVidRatePopUp selectItemAtIndex: 0];
461 /* Set Auto Crop to On at launch */
462 [fPictureController setAutoCrop:YES];
465 [fAudTrack1BitratePopUp removeAllItems];
466 for( int i = 0; i < hb_audio_bitrates_count; i++ )
468 [fAudTrack1BitratePopUp addItemWithTitle:
469 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
472 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
474 /* Audio samplerate */
475 [fAudTrack1RatePopUp removeAllItems];
476 for( int i = 0; i < hb_audio_rates_count; i++ )
478 [fAudTrack1RatePopUp addItemWithTitle:
479 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
481 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
484 [fStatusField setStringValue: @""];
489 /* We disable the Turbo 1st pass checkbox since we are not x264 */
490 [fVidTurboPassCheck setEnabled: NO];
491 [fVidTurboPassCheck setState: NSOffState];
494 /* lets get our default prefs here */
495 [self getDefaultPresets:nil];
496 /* lets initialize the current successful scancount here to 0 */
497 currentSuccessfulScanCount = 0;
502 - (void) enableUI: (bool) b
504 NSControl * controls[] =
505 { fSrcTitleField, fSrcTitlePopUp,
506 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
507 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
508 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
509 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
510 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
511 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
512 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
513 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
514 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
515 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
516 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
517 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
518 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
519 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
520 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
521 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
522 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
523 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,fSrcFrameEndEncodingField};
526 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
528 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
530 NSTextField * tf = (NSTextField *) controls[i];
531 if( ![tf isBezeled] )
533 [tf setTextColor: b ? [NSColor controlTextColor] :
534 [NSColor disabledControlTextColor]];
538 [controls[i] setEnabled: b];
544 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
545 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
546 [self setEnabledStateOfAudioMixdownControls:nil];
547 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
548 [self calculatePictureSizing:nil];
552 [fPresetsOutlineView setEnabled: NO];
556 [self videoMatrixChanged:nil];
557 [fAdvancedOptions enableUI:b];
561 /***********************************************************************
563 ***********************************************************************
564 * Shows a progression bar on the dock icon, filled according to
565 * 'progress' (0.0 <= progress <= 1.0).
566 * Called with progress < 0.0 or progress > 1.0, restores the original
568 **********************************************************************/
569 - (void) UpdateDockIcon: (float) progress
572 NSBitmapImageRep * bmp;
574 uint32_t black = htonl( 0x000000FF );
575 uint32_t red = htonl( 0xFF0000FF );
576 uint32_t white = htonl( 0xFFFFFFFF );
577 int row_start, row_end;
580 if( progress < 0.0 || progress > 1.0 )
582 [NSApp setApplicationIconImage: fApplicationIcon];
586 /* Get it in a raw bitmap form */
587 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
588 NSTIFFCompressionNone factor: 1.0];
589 bmp = [NSBitmapImageRep imageRepWithData: tiff];
591 /* Draw the progression bar */
592 /* It's pretty simple (ugly?) now, but I'm no designer */
594 row_start = 3 * (int) [bmp size].height / 4;
595 row_end = 7 * (int) [bmp size].height / 8;
597 for( i = row_start; i < row_start + 2; i++ )
599 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
600 for( j = 0; j < (int) [bmp size].width; j++ )
605 for( i = row_start + 2; i < row_end - 2; i++ )
607 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
610 for( j = 2; j < (int) [bmp size].width - 2; j++ )
612 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
624 for( i = row_end - 2; i < row_end; i++ )
626 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
627 for( j = 0; j < (int) [bmp size].width; j++ )
633 /* Now update the dock icon */
634 tiff = [bmp TIFFRepresentationUsingCompression:
635 NSTIFFCompressionNone factor: 1.0];
636 NSImage* icon = [[NSImage alloc] initWithData: tiff];
637 [NSApp setApplicationIconImage: icon];
641 - (void) updateUI: (NSTimer *) timer
644 /* Update UI for fHandle (user scanning instance of libhb ) */
647 list = hb_get_titles( fHandle );
648 /* check to see if there has been a new scan done
649 this bypasses the constraints of HB_STATE_WORKING
650 not allowing setting a newly scanned source */
651 int checkScanCount = hb_get_scancount( fHandle );
652 if( checkScanCount > currentScanCount )
654 currentScanCount = checkScanCount;
655 [fScanIndicator setIndeterminate: NO];
656 [fScanIndicator setDoubleValue: 0.0];
657 [fScanIndicator setHidden: YES];
658 [self showNewScan:nil];
662 hb_get_state( fHandle, &s );
668 #define p s.param.scanning
669 case HB_STATE_SCANNING:
671 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
672 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
673 p.title_cur, p.title_count]];
674 [fScanIndicator setHidden: NO];
675 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
680 #define p s.param.scandone
681 case HB_STATE_SCANDONE:
683 [fScanIndicator setIndeterminate: NO];
684 [fScanIndicator setDoubleValue: 0.0];
685 [fScanIndicator setHidden: YES];
686 [self writeToActivityLog:"ScanDone state received from fHandle"];
687 [self showNewScan:nil];
688 [[fWindow toolbar] validateVisibleItems];
694 #define p s.param.working
695 case HB_STATE_WORKING:
702 #define p s.param.muxing
703 case HB_STATE_MUXING:
710 case HB_STATE_PAUSED:
713 case HB_STATE_WORKDONE:
720 /* Update UI for fQueueEncodeLibhb */
722 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
723 /* check to see if there has been a new scan done
724 this bypasses the constraints of HB_STATE_WORKING
725 not allowing setting a newly scanned source */
727 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
728 if( checkScanCount > currentScanCount )
730 currentScanCount = checkScanCount;
734 hb_get_state( fQueueEncodeLibhb, &s );
740 #define p s.param.scanning
741 case HB_STATE_SCANNING:
743 [fStatusField setStringValue: [NSString stringWithFormat:
744 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
745 p.title_cur, p.title_count]];
747 /* Set the status string in fQueueController as well */
748 [fQueueController setQueueStatusString: [NSString stringWithFormat:
749 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
750 p.title_cur, p.title_count]];
755 #define p s.param.scandone
756 case HB_STATE_SCANDONE:
758 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
759 [self processNewQueueEncode];
760 [[fWindow toolbar] validateVisibleItems];
767 #define p s.param.working
769 case HB_STATE_SEARCHING:
771 NSMutableString * string;
772 NSString * pass_desc;
774 /* Update text field */
776 //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];
777 /* For now, do not announce "pass x of x for the search phase ... */
778 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
782 [string appendFormat:
783 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
786 [fStatusField setStringValue: string];
787 /* Set the status string in fQueueController as well */
788 [fQueueController setQueueStatusString: string];
790 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
791 [fRipIndicator setIndeterminate: NO];
792 [fRipIndicator setDoubleValue:100.0 * progress_total];
794 // If progress bar hasn't been revealed at the bottom of the window, do
795 // that now. This code used to be in doRip. I moved it to here to handle
796 // the case where hb_start is called by HBQueueController and not from
798 if( !fRipIndicatorShown )
800 NSRect frame = [fWindow frame];
801 if( frame.size.width <= 591 )
802 frame.size.width = 591;
803 frame.size.height += 36;
804 frame.origin.y -= 36;
805 [fWindow setFrame:frame display:YES animate:YES];
806 fRipIndicatorShown = YES;
810 /* Update dock icon */
811 /* Note not done yet */
816 case HB_STATE_WORKING:
818 NSMutableString * string;
819 NSString * pass_desc;
820 /* Update text field */
821 if (p.job_cur == 1 && p.job_count > 1)
823 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
825 pass_desc = @"(subtitle scan)";
837 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
841 [string appendFormat:
842 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
843 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
846 [fStatusField setStringValue: string];
847 /* Set the status string in fQueueController as well */
848 [fQueueController setQueueStatusString: string];
850 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
851 [fRipIndicator setIndeterminate: NO];
852 [fRipIndicator setDoubleValue:100.0 * progress_total];
854 // If progress bar hasn't been revealed at the bottom of the window, do
855 // that now. This code used to be in doRip. I moved it to here to handle
856 // the case where hb_start is called by HBQueueController and not from
858 if( !fRipIndicatorShown )
860 NSRect frame = [fWindow frame];
861 if( frame.size.width <= 591 )
862 frame.size.width = 591;
863 frame.size.height += 36;
864 frame.origin.y -= 36;
865 [fWindow setFrame:frame display:YES animate:YES];
866 fRipIndicatorShown = YES;
870 /* Update dock icon */
871 if( dockIconProgress < 100.0 * progress_total )
873 [self UpdateDockIcon: progress_total];
874 dockIconProgress += 5;
881 #define p s.param.muxing
882 case HB_STATE_MUXING:
884 /* Update text field */
885 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
886 /* Set the status string in fQueueController as well */
887 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
889 [fRipIndicator setIndeterminate: YES];
890 [fRipIndicator startAnimation: nil];
892 /* Update dock icon */
893 [self UpdateDockIcon: 1.0];
899 case HB_STATE_PAUSED:
900 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
901 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
905 case HB_STATE_WORKDONE:
907 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
908 // or someone calling hb_stop. In the latter case, hb_stop does not clear
909 // out the remaining passes/jobs in the queue. We'll do that here.
911 // Delete all remaining jobs of this encode.
912 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
913 /* Set the status string in fQueueController as well */
914 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
915 [fRipIndicator setIndeterminate: NO];
916 [fRipIndicator stopAnimation: nil];
917 [fRipIndicator setDoubleValue: 0.0];
918 [[fWindow toolbar] validateVisibleItems];
920 /* Restore dock icon */
921 [self UpdateDockIcon: -1.0];
922 dockIconProgress = 0;
924 if( fRipIndicatorShown )
926 NSRect frame = [fWindow frame];
927 if( frame.size.width <= 591 )
928 frame.size.width = 591;
929 frame.size.height += -36;
930 frame.origin.y -= -36;
931 [fWindow setFrame:frame display:YES animate:YES];
932 fRipIndicatorShown = NO;
934 /* Since we are done with this encode, tell output to stop writing to the
935 * individual encode log
937 [outputPanel endEncodeLog];
938 /* Check to see if the encode state has not been cancelled
939 to determine if we should check for encode done notifications */
940 if( fEncodeState != 2 )
942 NSString *pathOfFinishedEncode;
943 /* Get the output file name for the finished encode */
944 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
946 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
948 [self showGrowlDoneNotification:pathOfFinishedEncode];
950 [self sendToMetaX:pathOfFinishedEncode];
952 /* since we have successfully completed an encode, we increment the queue counter */
953 [self incrementQueueItemDone:nil];
955 /* all end of queue actions below need to be done after all queue encodes have finished
956 * and there are no pending jobs left to process
958 if (fPendingCount == 0)
960 /* If Alert Window or Window and Growl has been selected */
961 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
962 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
964 /*On Screen Notification*/
967 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
968 [NSApp requestUserAttention:NSCriticalRequest];
971 /* If sleep has been selected */
972 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
975 NSDictionary* errorDict;
976 NSAppleEventDescriptor* returnDescriptor = nil;
977 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
978 @"tell application \"Finder\" to sleep"];
979 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
980 [scriptObject release];
982 /* If Shutdown has been selected */
983 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
986 NSDictionary* errorDict;
987 NSAppleEventDescriptor* returnDescriptor = nil;
988 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
989 @"tell application \"Finder\" to shut down"];
990 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
991 [scriptObject release];
1005 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1006 - (void) writeToActivityLog:(const char *) format, ...
1009 va_start(args, format);
1013 vsnprintf( str, 1024, format, args );
1015 time_t _now = time( NULL );
1016 struct tm * now = localtime( &_now );
1017 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1023 #pragma mark Toolbar
1024 // ============================================================
1025 // NSToolbar Related Methods
1026 // ============================================================
1028 - (void) setupToolbar {
1029 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1031 [toolbar setAllowsUserCustomization: YES];
1032 [toolbar setAutosavesConfiguration: YES];
1033 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1035 [toolbar setDelegate: self];
1037 [fWindow setToolbar: toolbar];
1040 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1041 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1042 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1044 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1046 [item setLabel: @"Toggle Presets"];
1047 [item setPaletteLabel: @"Toggler Presets"];
1048 [item setToolTip: @"Open/Close Preset Drawer"];
1049 [item setImage: [NSImage imageNamed: @"Drawer"]];
1050 [item setTarget: self];
1051 [item setAction: @selector(toggleDrawer:)];
1052 [item setAutovalidates: NO];
1054 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1056 [item setLabel: @"Start"];
1057 [item setPaletteLabel: @"Start Encoding"];
1058 [item setToolTip: @"Start Encoding"];
1059 [item setImage: [NSImage imageNamed: @"Play"]];
1060 [item setTarget: self];
1061 [item setAction: @selector(Rip:)];
1063 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1065 [item setLabel: @"Show Queue"];
1066 [item setPaletteLabel: @"Show Queue"];
1067 [item setToolTip: @"Show Queue"];
1068 [item setImage: [NSImage imageNamed: @"Queue"]];
1069 [item setTarget: self];
1070 [item setAction: @selector(showQueueWindow:)];
1071 [item setAutovalidates: NO];
1073 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1075 [item setLabel: @"Add to Queue"];
1076 [item setPaletteLabel: @"Add to Queue"];
1077 [item setToolTip: @"Add to Queue"];
1078 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1079 [item setTarget: self];
1080 [item setAction: @selector(addToQueue:)];
1082 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1084 [item setLabel: @"Pause"];
1085 [item setPaletteLabel: @"Pause Encoding"];
1086 [item setToolTip: @"Pause Encoding"];
1087 [item setImage: [NSImage imageNamed: @"Pause"]];
1088 [item setTarget: self];
1089 [item setAction: @selector(Pause:)];
1091 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1093 [item setLabel: @"Picture Settings"];
1094 [item setPaletteLabel: @"Show Picture Settings"];
1095 [item setToolTip: @"Show Picture Settings"];
1096 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1097 [item setTarget: self];
1098 [item setAction: @selector(showPicturePanel:)];
1100 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1102 [item setLabel: @"Preview Window"];
1103 [item setPaletteLabel: @"Show Preview"];
1104 [item setToolTip: @"Show Preview"];
1105 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1106 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1107 [item setTarget: self];
1108 [item setAction: @selector(showPreviewWindow:)];
1110 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1112 [item setLabel: @"Activity Window"];
1113 [item setPaletteLabel: @"Show Activity Window"];
1114 [item setToolTip: @"Show Activity Window"];
1115 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1116 [item setTarget: self];
1117 [item setAction: @selector(showDebugOutputPanel:)];
1118 [item setAutovalidates: NO];
1120 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1122 [item setLabel: @"Source"];
1123 [item setPaletteLabel: @"Source"];
1124 [item setToolTip: @"Choose Video Source"];
1125 [item setImage: [NSImage imageNamed: @"Source"]];
1126 [item setTarget: self];
1127 [item setAction: @selector(browseSources:)];
1137 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1139 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1140 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1141 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1144 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1146 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1147 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1148 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1149 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1152 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1154 NSString * ident = [toolbarItem itemIdentifier];
1160 hb_get_state( fHandle, &s );
1161 if (s.state == HB_STATE_SCANNING)
1164 if ([ident isEqualToString: ChooseSourceIdentifier])
1166 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1167 [toolbarItem setLabel: @"Cancel Scan"];
1168 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1169 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1173 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1178 if ([ident isEqualToString: ChooseSourceIdentifier])
1180 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1181 [toolbarItem setLabel: @"Source"];
1182 [toolbarItem setPaletteLabel: @"Source"];
1183 [toolbarItem setToolTip: @"Choose Video Source"];
1188 hb_get_state2( fQueueEncodeLibhb, &s );
1190 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1192 if ([ident isEqualToString: StartEncodingIdentifier])
1194 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1195 [toolbarItem setLabel: @"Stop"];
1196 [toolbarItem setPaletteLabel: @"Stop"];
1197 [toolbarItem setToolTip: @"Stop Encoding"];
1200 if ([ident isEqualToString: PauseEncodingIdentifier])
1202 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1203 [toolbarItem setLabel: @"Pause"];
1204 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1205 [toolbarItem setToolTip: @"Pause Encoding"];
1210 if ([ident isEqualToString: AddToQueueIdentifier])
1212 if ([ident isEqualToString: ShowPictureIdentifier])
1214 if ([ident isEqualToString: ShowPreviewIdentifier])
1218 else if (s.state == HB_STATE_PAUSED)
1220 if ([ident isEqualToString: PauseEncodingIdentifier])
1222 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1223 [toolbarItem setLabel: @"Resume"];
1224 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1225 [toolbarItem setToolTip: @"Resume Encoding"];
1228 if ([ident isEqualToString: StartEncodingIdentifier])
1230 if ([ident isEqualToString: AddToQueueIdentifier])
1232 if ([ident isEqualToString: ShowPictureIdentifier])
1234 if ([ident isEqualToString: ShowPreviewIdentifier])
1237 else if (s.state == HB_STATE_SCANNING)
1239 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1241 if ([ident isEqualToString: StartEncodingIdentifier])
1243 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1244 if (hb_count(fHandle) > 0)
1245 [toolbarItem setLabel: @"Start Queue"];
1247 [toolbarItem setLabel: @"Start"];
1248 [toolbarItem setPaletteLabel: @"Start Encoding"];
1249 [toolbarItem setToolTip: @"Start Encoding"];
1252 if ([ident isEqualToString: AddToQueueIdentifier])
1254 if ([ident isEqualToString: ShowPictureIdentifier])
1256 if ([ident isEqualToString: ShowPreviewIdentifier])
1261 /* If there are any pending queue items, make sure the start/stop button is active */
1262 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1264 if ([ident isEqualToString: ShowQueueIdentifier])
1266 if ([ident isEqualToString: ToggleDrawerIdentifier])
1268 if ([ident isEqualToString: ChooseSourceIdentifier])
1270 if ([ident isEqualToString: ShowActivityIdentifier])
1276 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1278 SEL action = [menuItem action];
1281 hb_get_state2( fHandle, &s );
1285 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1286 return SuccessfulScan && [fWindow attachedSheet] == nil;
1288 if (action == @selector(browseSources:))
1290 if (s.state == HB_STATE_SCANNING)
1293 return [fWindow attachedSheet] == nil;
1295 if (action == @selector(selectDefaultPreset:))
1296 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1297 if (action == @selector(Pause:))
1299 if (s.state == HB_STATE_WORKING)
1301 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1302 [menuItem setTitle:@"Pause Encoding"];
1305 else if (s.state == HB_STATE_PAUSED)
1307 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1308 [menuItem setTitle:@"Resume Encoding"];
1314 if (action == @selector(Rip:))
1316 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1318 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1319 [menuItem setTitle:@"Stop Encoding"];
1322 else if (SuccessfulScan)
1324 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1325 [menuItem setTitle:@"Start Encoding"];
1326 return [fWindow attachedSheet] == nil;
1332 if( action == @selector(setDefaultPreset:) )
1334 return [fPresetsOutlineView selectedRow] != -1;
1341 #pragma mark Encode Done Actions
1342 // register a test notification and make
1343 // it enabled by default
1344 #define SERVICE_NAME @"Encode Done"
1345 - (NSDictionary *)registrationDictionaryForGrowl
1347 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1348 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1349 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1352 return registrationDictionary;
1355 -(void)showGrowlDoneNotification:(NSString *) filePath
1357 /* This end of encode action is called as each encode rolls off of the queue */
1358 NSString * finishedEncode = filePath;
1359 /* strip off the path to just show the file name */
1360 finishedEncode = [finishedEncode lastPathComponent];
1361 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1362 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1364 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1365 [GrowlApplicationBridge
1366 notifyWithTitle:@"Put down that cocktail..."
1367 description:growlMssg
1368 notificationName:SERVICE_NAME
1376 -(void)sendToMetaX:(NSString *) filePath
1378 /* This end of encode action is called as each encode rolls off of the queue */
1379 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1381 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1382 if (![sendToApp isEqualToString:@"None"])
1384 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1385 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1386 [myScript executeAndReturnError: nil];
1393 #pragma mark Get New Source
1395 /*Opens the source browse window, called from Open Source widgets */
1396 - (IBAction) browseSources: (id) sender
1400 hb_get_state( fHandle, &s );
1401 if (s.state == HB_STATE_SCANNING)
1403 [self cancelScanning:nil];
1408 NSOpenPanel * panel;
1410 panel = [NSOpenPanel openPanel];
1411 [panel setAllowsMultipleSelection: NO];
1412 [panel setCanChooseFiles: YES];
1413 [panel setCanChooseDirectories: YES ];
1414 NSString * sourceDirectory;
1415 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1417 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1421 sourceDirectory = @"~/Desktop";
1422 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1424 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1425 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1427 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1428 modalForWindow: fWindow modalDelegate: self
1429 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1430 contextInfo: sender];
1433 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1434 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1436 /* we convert the sender content of contextInfo back into a variable called sender
1437 * mostly just for consistency for evaluation later
1439 id sender = (id)contextInfo;
1440 /* User selected a file to open */
1441 if( returnCode == NSOKButton )
1443 /* Free display name allocated previously by this code */
1444 [browsedSourceDisplayName release];
1446 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1447 /* we set the last searched source directory in the prefs here */
1448 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1449 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1450 /* we order out sheet, which is the browse window as we need to open
1451 * the title selection sheet right away
1453 [sheet orderOut: self];
1455 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1457 /* We put the chosen source path in the source display text field for the
1458 * source title selection sheet in which the user specifies the specific title to be
1459 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1460 * purposes in the title panel
1463 [fScanSrcTitlePathField setStringValue:scanPath];
1464 NSString *displayTitlescanSourceName;
1466 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1468 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1469 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1470 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1474 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1475 displayTitlescanSourceName = [scanPath lastPathComponent];
1477 /* we set the source display name in the title selection dialogue */
1478 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1479 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1480 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1481 /* We show the actual sheet where the user specifies the title to be scanned
1482 * as we are going to do a title specific scan
1484 [self showSourceTitleScanPanel:nil];
1488 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1489 NSString *path = [[sheet filenames] objectAtIndex: 0];
1491 /* We check to see if the chosen file at path is a package */
1492 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1494 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1495 /* We check to see if this is an .eyetv package */
1496 if ([[path pathExtension] isEqualToString: @"eyetv"])
1498 [self writeToActivityLog:"trying to open eyetv package"];
1499 /* We're looking at an EyeTV package - try to open its enclosed
1501 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1503 int n = [[path stringByAppendingString: @"/"]
1504 completePathIntoString: &mpgname caseSensitive: YES
1505 matchesIntoArray: nil
1506 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1509 /* Found an mpeg inside the eyetv package, make it our scan path
1510 and call performScan on the enclosed mpeg */
1512 [self writeToActivityLog:"found mpeg in eyetv package"];
1513 [self performScan:path scanTitleNum:0];
1517 /* We did not find an mpeg file in our package, so we do not call performScan */
1518 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1521 /* We check to see if this is a .dvdmedia package */
1522 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1524 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1525 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1526 [self writeToActivityLog:"trying to open dvdmedia package"];
1527 [self performScan:path scanTitleNum:0];
1531 /* The package is not an eyetv package, so we do not call performScan */
1532 [self writeToActivityLog:"unable to open package"];
1535 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1537 /* path is not a package, so we call perform scan directly on our file */
1538 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1540 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1541 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1542 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1546 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1547 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1548 /* make sure we remove any path extension as this can also be an '.mpg' file */
1549 browsedSourceDisplayName = [[path lastPathComponent] retain];
1551 applyQueueToScan = NO;
1552 [self performScan:path scanTitleNum:0];
1560 - (IBAction)showAboutPanel:(id)sender
1562 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1563 fApplicationIcon, @"ApplicationIcon",
1565 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1569 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1570 - (IBAction) showSourceTitleScanPanel: (id) sender
1572 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1575 [fScanSrcTitleNumField setStringValue: @"0"];
1576 /* Show the panel */
1577 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1580 - (IBAction) closeSourceTitleScanPanel: (id) sender
1582 [NSApp endSheet: fScanSrcTitlePanel];
1583 [fScanSrcTitlePanel orderOut: self];
1585 if(sender == fScanSrcTitleOpenButton)
1587 /* We setup the scan status in the main window to indicate a source title scan */
1588 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1589 [fScanIndicator setHidden: NO];
1590 [fScanIndicator setIndeterminate: YES];
1591 [fScanIndicator startAnimation: nil];
1593 /* We use the performScan method to actually perform the specified scan passing the path and the title
1596 applyQueueToScan = NO;
1597 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1601 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1602 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1605 /* use a bool to determine whether or not we can decrypt using vlc */
1606 BOOL cancelScanDecrypt = 0;
1608 NSString *path = scanPath;
1609 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1611 // Notify ChapterTitles that there's no title
1612 [fChapterTitlesDelegate resetWithTitle:nil];
1613 [fChapterTable reloadData];
1615 // Notify Subtitles that there's no title
1616 [fSubtitlesDelegate resetWithTitle:nil];
1617 [fSubtitlesTable reloadData];
1619 [self enableUI: NO];
1621 if( [detector isVideoDVD] )
1624 #if defined( __LP64__ )
1633 // The chosen path was actually on a DVD, so use the raw block
1634 // device path instead.
1635 path = [detector devicePath];
1636 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1638 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1639 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1640 NSFileManager * fileManager = [NSFileManager defaultManager];
1641 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1643 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1644 cancelScanDecrypt = 1;
1645 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1647 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");
1648 [NSApp requestUserAttention:NSCriticalRequest];
1650 if (status == NSAlertDefaultReturn)
1652 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1653 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1655 else if (status == NSAlertAlternateReturn)
1657 /* User chose to cancel the scan */
1658 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1662 /* 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 */
1663 cancelScanDecrypt = 0;
1664 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1670 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1671 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1674 /* test for architecture of the vlc app */
1675 NSArray *vlc_architecturesArray = [[NSBundle bundleWithPath:@"/Applications/VLC.app"] executableArchitectures];
1676 BOOL vlcIntel32bit = NO;
1677 BOOL vlcIntel64bit = NO;
1678 BOOL vlcPPC32bit = NO;
1679 BOOL vlcPPC64bit = NO;
1680 /* check the available architectures for vlc and note accordingly */
1681 NSEnumerator *enumerator = [vlc_architecturesArray objectEnumerator];
1683 while (tempObject = [enumerator nextObject])
1686 if ([tempObject intValue] == NSBundleExecutableArchitectureI386)
1688 vlcIntel32bit = YES;
1690 if ([tempObject intValue] == NSBundleExecutableArchitectureX86_64)
1692 vlcIntel64bit = YES;
1694 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC)
1698 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC64)
1704 /* Write vlc architecture findings to activity window */
1707 [self writeToActivityLog: " 32-Bit VLC app found for decrypting physical dvd"];
1711 [self writeToActivityLog: " 64-Bit VLC app found for decrypting physical dvd"];
1716 if (vlcFound && hb_arch == 64 && !vlcIntel64bit && cancelScanDecrypt != 1)
1721 /* Appropriate VLC not found, so cancel */
1722 cancelScanDecrypt = 1;
1723 [self writeToActivityLog: "This version of HandBrake is 64 bit, 64 bit version of vlc not found, scan cancelled"];
1724 /*On Screen Notification*/
1727 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);
1728 [NSApp requestUserAttention:NSCriticalRequest];
1730 if (status == NSAlertDefaultReturn)
1732 /* User chose to cancel the scan */
1733 [self writeToActivityLog: "cannot open physical dvd VLC found but not 64 bit, scan cancelled"];
1734 cancelScanDecrypt = 1;
1736 else if (status == NSAlertAlternateReturn)
1738 [self writeToActivityLog: "user overrode 64-bit warning trying to open physical dvd without proper decryption"];
1739 cancelScanDecrypt = 0;
1743 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1744 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1748 else if (vlcFound && hb_arch == 32 && !vlcIntel32bit && cancelScanDecrypt != 1)
1751 /* Appropriate VLC not found, so cancel */
1752 cancelScanDecrypt = 1;
1753 [self writeToActivityLog: "This version of HandBrake is 32 bit, 32 bit version of vlc not found, scan cancelled"];
1754 /*On Screen Notification*/
1757 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);
1758 [NSApp requestUserAttention:NSCriticalRequest];
1760 if (status == NSAlertDefaultReturn)
1762 /* User chose to cancel the scan */
1763 [self writeToActivityLog: "cannot open physical dvd VLC found but not 32 bit, scan cancelled"];
1764 cancelScanDecrypt = 1;
1766 else if (status == NSAlertAlternateReturn)
1768 [self writeToActivityLog: "user overrode 32-bit warning trying to open physical dvd without proper decryption"];
1769 cancelScanDecrypt = 0;
1773 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1774 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1780 if (cancelScanDecrypt == 0)
1782 /* we actually pass the scan off to libhb here */
1783 /* If there is no title number passed to scan, we use "0"
1784 * which causes the default behavior of a full source scan
1790 if (scanTitleNum > 0)
1792 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1794 /* We use our advance pref to determine how many previews to scan */
1795 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1796 /* set title to NULL */
1798 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1799 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1803 - (IBAction) cancelScanning:(id)sender
1805 hb_scan_stop(fHandle);
1808 - (IBAction) showNewScan:(id)sender
1812 int indxpri=0; // Used to search the longuest title (default in combobox)
1813 int longuestpri=0; // Used to search the longuest title (default in combobox)
1816 list = hb_get_titles( fHandle );
1818 if( !hb_list_count( list ) )
1820 /* We display a message if a valid dvd source was not chosen */
1821 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1822 SuccessfulScan = NO;
1824 // Notify ChapterTitles that there's no title
1825 [fSubtitlesDelegate resetWithTitle:nil];
1826 [fSubtitlesTable reloadData];
1828 // Notify Subtitles that there's no title
1829 [fChapterTitlesDelegate resetWithTitle:nil];
1830 [fChapterTable reloadData];
1834 if (applyQueueToScan == YES)
1836 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1837 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1840 else if (applyQueueToScan == NO)
1842 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1846 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1849 /* We increment the successful scancount here by one,
1850 which we use at the end of this function to tell the gui
1851 if this is the first successful scan since launch and whether
1852 or not we should set all settings to the defaults */
1853 currentSuccessfulScanCount++;
1855 [[fWindow toolbar] validateVisibleItems];
1857 [fSrcTitlePopUp removeAllItems];
1858 for( int i = 0; i < hb_list_count( list ); i++ )
1860 title = (hb_title_t *) hb_list_item( list, i );
1862 currentSource = [NSString stringWithUTF8String: title->name];
1863 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1864 if (!browsedSourceDisplayName)
1866 browsedSourceDisplayName = @"NoNameDetected";
1868 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1870 /* If its a queue rescan for edit, get the queue item output path */
1871 /* if not, its a new source scan. */
1872 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1873 if (applyQueueToScan == YES)
1875 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1877 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1879 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1880 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1884 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1885 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1889 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1891 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1895 [fSrcTitlePopUp addItemWithTitle: [NSString
1896 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1897 title->name,title->index, title->hours, title->minutes,
1901 /* if we are a stream, select the first title */
1902 if (title->type == HB_STREAM_TYPE)
1904 [fSrcTitlePopUp selectItemAtIndex: 0];
1908 /* if not then select the longest title (dvd) */
1909 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1911 [self titlePopUpChanged:nil];
1913 SuccessfulScan = YES;
1914 [self enableUI: YES];
1916 /* if its the initial successful scan after awakeFromNib */
1917 if (currentSuccessfulScanCount == 1)
1919 [self encodeStartStopPopUpChanged:nil];
1921 [self selectDefaultPreset:nil];
1923 // Open preview window now if it was visible when HB was closed
1924 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1925 [self showPreviewWindow:nil];
1927 // Open picture sizing window now if it was visible when HB was closed
1928 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1929 [self showPicturePanel:nil];
1932 if (applyQueueToScan == YES)
1934 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1935 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1936 [self applyQueueSettingsToMainWindow:nil];
1947 #pragma mark New Output Destination
1949 - (IBAction) browseFile: (id) sender
1951 /* Open a panel to let the user choose and update the text field */
1952 NSSavePanel * panel = [NSSavePanel savePanel];
1953 /* We get the current file name and path from the destination field here */
1954 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1955 modalForWindow: fWindow modalDelegate: self
1956 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1960 - (void) browseFileDone: (NSSavePanel *) sheet
1961 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1963 if( returnCode == NSOKButton )
1965 [fDstFile2Field setStringValue: [sheet filename]];
1966 /* Save this path to the prefs so that on next browse destination window it opens there */
1967 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1968 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1974 #pragma mark Main Window Control
1976 - (IBAction) openMainWindow: (id) sender
1978 [fWindow makeKeyAndOrderFront:nil];
1981 - (BOOL) windowShouldClose: (id) sender
1986 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1989 [fWindow makeKeyAndOrderFront:nil];
1997 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1998 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
2003 #pragma mark Queue File
2005 - (void) loadQueueFile {
2006 /* We declare the default NSFileManager into fileManager */
2007 NSFileManager * fileManager = [NSFileManager defaultManager];
2008 /*We define the location of the user presets file */
2009 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
2010 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
2011 /* We check for the presets.plist */
2012 if ([fileManager fileExistsAtPath:QueueFile] == 0)
2014 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
2017 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
2018 /* lets check to see if there is anything in the queue file .plist */
2019 if (nil == QueueFileArray)
2021 /* if not, then lets initialize an empty array */
2022 QueueFileArray = [[NSMutableArray alloc] init];
2024 /* Initialize our curQueueEncodeIndex to 0
2025 * so we can use it to track which queue
2026 * item is to be used to track our encodes */
2027 /* NOTE: this should be changed if and when we
2028 * are able to get the last unfinished encode
2029 * in the case of a crash or shutdown */
2034 [self clearQueueEncodedItems];
2036 currentQueueEncodeIndex = 0;
2039 - (void)addQueueFileItem
2041 [QueueFileArray addObject:[self createQueueFileItem]];
2042 [self saveQueueFileItem];
2046 - (void) removeQueueFileItem:(int) queueItemToRemove
2049 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
2050 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
2052 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
2053 * by one to keep in sync with the queue array
2055 currentQueueEncodeIndex--;
2056 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
2058 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2059 [self saveQueueFileItem];
2063 - (void)saveQueueFileItem
2065 [QueueFileArray writeToFile:QueueFile atomically:YES];
2066 [fQueueController setQueueArray: QueueFileArray];
2067 [self getQueueStats];
2070 - (void)getQueueStats
2072 /* lets get the stats on the status of the queue array */
2074 fEncodingQueueItem = 0;
2076 fCompletedCount = 0;
2080 /* We use a number system to set the encode status of the queue item
2082 * 0 == already encoded
2083 * 1 == is being encoded
2084 * 2 == is yet to be encoded
2089 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2091 while (tempObject = [enumerator nextObject])
2093 NSDictionary *thisQueueDict = tempObject;
2094 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2098 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2101 fEncodingQueueItem = i;
2103 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2107 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2114 /* Set the queue status field in the main window */
2115 NSMutableString * string;
2116 if (fPendingCount == 1)
2118 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2122 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2124 [fQueueStatus setStringValue:string];
2127 /* This method will set any item marked as encoding back to pending
2128 * currently used right after a queue reload
2130 - (void) setQueueEncodingItemsAsPending
2132 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2134 NSMutableArray *tempArray;
2135 tempArray = [NSMutableArray array];
2136 /* we look here to see if the preset is we move on to the next one */
2137 while ( tempObject = [enumerator nextObject] )
2139 /* If the queue item is marked as "encoding" (1)
2140 * then change its status back to pending (2) which effectively
2141 * puts it back into the queue to be encoded
2143 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2145 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2147 [tempArray addObject:tempObject];
2150 [QueueFileArray setArray:tempArray];
2151 [self saveQueueFileItem];
2155 /* This method will clear the queue of any encodes that are not still pending
2156 * this includes both successfully completed encodes as well as cancelled encodes */
2157 - (void) clearQueueEncodedItems
2159 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2161 NSMutableArray *tempArray;
2162 tempArray = [NSMutableArray array];
2163 /* we look here to see if the preset is we move on to the next one */
2164 while ( tempObject = [enumerator nextObject] )
2166 /* If the queue item is either completed (0) or cancelled (3) from the
2167 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2168 * NOTE: this means we retain pending (2) and also an item that is marked as
2169 * still encoding (1). If the queue has an item that is still marked as encoding
2170 * from a previous session, we can conlude that HB was either shutdown, or crashed
2171 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2173 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2175 [tempArray addObject:tempObject];
2179 [QueueFileArray removeObjectsInArray:tempArray];
2180 [self saveQueueFileItem];
2183 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2184 - (void) clearQueueAllItems
2186 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2188 NSMutableArray *tempArray;
2189 tempArray = [NSMutableArray array];
2190 /* we look here to see if the preset is we move on to the next one */
2191 while ( tempObject = [enumerator nextObject] )
2193 [tempArray addObject:tempObject];
2196 [QueueFileArray removeObjectsInArray:tempArray];
2197 [self saveQueueFileItem];
2200 /* This method will duplicate prepareJob however into the
2201 * queue .plist instead of into the job structure so it can
2202 * be recalled later */
2203 - (NSDictionary *)createQueueFileItem
2205 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2207 hb_list_t * list = hb_get_titles( fHandle );
2208 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2209 [fSrcTitlePopUp indexOfSelectedItem] );
2210 hb_job_t * job = title->job;
2214 /* We use a number system to set the encode status of the queue item
2215 * 0 == already encoded
2216 * 1 == is being encoded
2217 * 2 == is yet to be encoded
2220 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2221 /* Source and Destination Information */
2223 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2224 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2225 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2226 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2228 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2229 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2231 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2233 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2235 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2237 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2239 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2241 /* Chapter encode info */
2242 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2243 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2244 /* Time (pts) encode info */
2245 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2246 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2247 /* Frame number encode info */
2248 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2249 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2252 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2253 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2254 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2256 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2258 /* Lets get the preset info if there is any */
2259 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2260 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2262 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2263 /* Chapter Markers*/
2264 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2265 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2267 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2271 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2274 /* We need to get the list of chapter names to put into an array and store
2275 * in our queue, so they can be reapplied in prepareJob when this queue
2276 * item comes up if Chapter Markers is set to on.
2279 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2280 int chaptercount = hb_list_count( fTitle->list_chapter );
2281 for( i = 0; i < chaptercount; i++ )
2283 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2284 if( chapter != NULL )
2286 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2289 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2290 [ChapterNamesArray autorelease];
2292 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2293 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2294 /* Mux mp4 with http optimization */
2295 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2296 /* Add iPod uuid atom */
2297 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2301 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2302 /* x264 Option String */
2303 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2305 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2306 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2307 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2308 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2310 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2312 /* 2 Pass Encoding */
2313 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2314 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2315 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2317 /* Picture Sizing */
2318 /* Use Max Picture settings for whatever the dvd is.*/
2319 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2320 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2321 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2322 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2323 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2324 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2325 /* if we are custom anamorphic, store the exact storage, par and display dims */
2326 if (fTitle->job->anamorphic.mode == 3)
2328 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2330 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2331 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2333 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2334 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2336 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2337 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2340 NSString * pictureSummary;
2341 pictureSummary = [fPictureSizeField stringValue];
2342 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2343 /* Set crop settings here */
2344 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2345 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2346 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2347 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2348 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2350 /* Picture Filters */
2351 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2352 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2354 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2355 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2356 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2358 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2359 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2361 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2362 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2364 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2366 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2369 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2371 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2372 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2373 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2374 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2375 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2376 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2377 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2379 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2381 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2382 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2383 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2384 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2385 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2386 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2387 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2389 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2391 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2392 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2393 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2394 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2395 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2396 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2397 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2399 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2401 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2402 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2403 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2404 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2405 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2406 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2407 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2411 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2412 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2413 [subtitlesArray autorelease];
2415 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2417 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2419 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2422 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2426 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2429 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2430 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2431 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2433 /* Picture Sizing */
2434 /* Use Max Picture settings for whatever the dvd is.*/
2435 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2436 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2437 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2438 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2439 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2441 /* Set crop settings here */
2442 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2443 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2444 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2445 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2446 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2450 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2452 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2453 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2454 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2455 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2456 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2458 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2460 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2461 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2462 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2463 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2464 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2466 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2468 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2469 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2470 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2471 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2472 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2474 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2476 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2477 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2478 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2479 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2480 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2484 /* we need to auto relase the queueFileJob and return it */
2485 [queueFileJob autorelease];
2486 return queueFileJob;
2490 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2491 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2493 NSUInteger index = [indexSet lastIndex];
2494 NSUInteger aboveInsertIndexCount = 0;
2497 NSUInteger removeIndex;
2499 if (index >= insertIndex)
2501 removeIndex = index + aboveInsertIndexCount;
2502 aboveInsertIndexCount++;
2506 removeIndex = index;
2510 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2511 [QueueFileArray removeObjectAtIndex:removeIndex];
2512 [QueueFileArray insertObject:object atIndex:insertIndex];
2515 index = [indexSet indexLessThanIndex:index];
2517 /* We save all of the Queue data here
2518 * and it also gets sent back to the queue controller*/
2519 [self saveQueueFileItem];
2525 #pragma mark Queue Job Processing
2527 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2529 int i = currentQueueEncodeIndex;
2530 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2532 /* We save all of the Queue data here */
2533 [self saveQueueFileItem];
2534 /* We Reload the New Table data for presets */
2535 //[fPresetsOutlineView reloadData];
2537 /* Since we have now marked a queue item as done
2538 * we can go ahead and increment currentQueueEncodeIndex
2539 * so that if there is anything left in the queue we can
2540 * go ahead and move to the next item if we want to */
2541 currentQueueEncodeIndex++ ;
2542 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2543 int queueItems = [QueueFileArray count];
2544 /* If we still have more items in our queue, lets go to the next one */
2545 if (currentQueueEncodeIndex < queueItems)
2547 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2548 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2552 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2556 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2557 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2559 /* Tell HB to output a new activity log file for this encode */
2560 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2563 /* use a bool to determine whether or not we can decrypt using vlc */
2564 BOOL cancelScanDecrypt = 0;
2565 /* set the bool so that showNewScan knows to apply the appropriate queue
2566 * settings as this is a queue rescan
2568 //applyQueueToScan = YES;
2569 NSString *path = scanPath;
2570 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2572 if( [detector isVideoDVD] )
2574 // The chosen path was actually on a DVD, so use the raw block
2575 // device path instead.
2576 path = [detector devicePath];
2577 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2579 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2580 NSString *vlcPath = @"/Applications/VLC.app";
2581 NSFileManager * fileManager = [NSFileManager defaultManager];
2582 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2584 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2585 cancelScanDecrypt = 1;
2586 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2588 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");
2589 [NSApp requestUserAttention:NSCriticalRequest];
2591 if (status == NSAlertDefaultReturn)
2593 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2594 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2596 else if (status == NSAlertAlternateReturn)
2598 /* User chose to cancel the scan */
2599 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2603 /* 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 */
2604 cancelScanDecrypt = 0;
2605 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2611 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2612 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2616 if (cancelScanDecrypt == 0)
2618 /* we actually pass the scan off to libhb here */
2619 /* If there is no title number passed to scan, we use "0"
2620 * which causes the default behavior of a full source scan
2626 if (scanTitleNum > 0)
2628 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2631 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2632 /* We use our advance pref to determine how many previews to scan */
2633 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2634 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2638 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2639 - (void) processNewQueueEncode
2641 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2642 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2643 hb_job_t * job = title->job;
2645 if( !hb_list_count( list ) )
2647 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2650 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2651 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2652 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2653 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2654 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2658 * If scanning we need to do some extra setup of the job.
2660 if( job->indepth_scan == 1 )
2665 * When subtitle scan is enabled do a fast pre-scan job
2666 * which will determine which subtitles to enable, if any.
2669 x264opts_tmp = job->x264opts;
2671 job->x264opts = NULL;
2673 job->indepth_scan = 1;
2677 * Add the pre-scan job
2679 hb_add( fQueueEncodeLibhb, job );
2680 job->x264opts = x264opts_tmp;
2684 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2686 job->indepth_scan = 0;
2692 hb_add( fQueueEncodeLibhb, job );
2696 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2697 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2699 hb_add( fQueueEncodeLibhb, job );
2704 job->indepth_scan = 0;
2707 hb_add( fQueueEncodeLibhb, job );
2710 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2711 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2712 /* Lets mark our new encode as 1 or "Encoding" */
2713 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2714 [self saveQueueFileItem];
2716 /* we need to clean up the subtitle tracks after the job(s) have been set */
2717 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2719 for(ii = 0; ii < num_subtitle_tracks; ii++)
2721 hb_subtitle_t * subtitle;
2722 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2725 hb_list_rem(job->list_subtitle, subtitle);
2730 /* We should be all setup so let 'er rip */
2737 #pragma mark Queue Item Editing
2739 /* Rescans the chosen queue item back into the main window */
2740 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2742 fqueueEditRescanItemNum = selectedQueueItem;
2743 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2744 applyQueueToScan = YES;
2745 /* Set the browsedSourceDisplayName for showNewScan */
2746 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2747 [self performScan:scanPath scanTitleNum:scanTitleNum];
2751 /* We use this method after a queue item rescan for edit.
2752 * it largely mirrors -selectPreset in terms of structure.
2753 * Assumes that a queue item has been reloaded into the main window.
2755 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2757 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2758 hb_job_t * job = fTitle->job;
2761 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2763 /* Set title number and chapters */
2764 /* since the queue only scans a single title, its already been selected in showNewScan
2765 so do not try to reset it here. However if we do decide to do full source scans on
2766 a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2767 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2769 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2770 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2773 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2774 [self formatPopUpChanged:nil];
2776 /* Chapter Markers*/
2777 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2778 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2779 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2780 /* Mux mp4 with http optimization */
2781 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2784 /* We set the advanced opt string here if applicable*/
2785 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2786 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2788 /* Lets run through the following functions to get variables set there */
2789 [self videoEncoderPopUpChanged:nil];
2790 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2791 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2792 [self calculateBitrate:nil];
2795 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2797 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2798 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2799 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2800 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2801 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2802 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2803 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2804 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2806 /* For the quality slider we need to convert the old percent's to the new rf scales */
2807 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2808 [fVidQualitySlider setFloatValue:rf];
2813 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2814 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2816 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2820 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2821 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2825 [self videoMatrixChanged:nil];
2826 [self writeToActivityLog: "applyQueueSettingsToMainWindow: video matrix changed"];
2827 /* Video framerate */
2828 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2829 detected framerate in the fVidRatePopUp so we use index 0*/
2830 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2832 [fVidRatePopUp selectItemAtIndex: 0];
2836 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2839 /* 2 Pass Encoding */
2840 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2841 [self twoPassCheckboxChanged:nil];
2842 /* Turbo 1st pass for 2 Pass Encoding */
2843 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2848 /* Now lets add our new tracks to the audio list here */
2849 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2851 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2852 [self audioTrackPopUpChanged: fAudLang1PopUp];
2853 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2854 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2856 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2858 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2859 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2861 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2862 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2866 [fAudLang1PopUp selectItemAtIndex: 0];
2867 [self audioTrackPopUpChanged: fAudLang1PopUp];
2869 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2871 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2872 [self audioTrackPopUpChanged: fAudLang2PopUp];
2873 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2874 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2876 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2878 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2879 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2881 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2882 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2886 [fAudLang2PopUp selectItemAtIndex: 0];
2887 [self audioTrackPopUpChanged: fAudLang2PopUp];
2889 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2891 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2892 [self audioTrackPopUpChanged: fAudLang3PopUp];
2893 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2894 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2896 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2898 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2899 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2901 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2902 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2906 [fAudLang3PopUp selectItemAtIndex: 0];
2907 [self audioTrackPopUpChanged: fAudLang3PopUp];
2909 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2911 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2912 [self audioTrackPopUpChanged: fAudLang4PopUp];
2913 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2914 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2916 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2918 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2919 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2921 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2922 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2926 [fAudLang4PopUp selectItemAtIndex: 0];
2927 [self audioTrackPopUpChanged: fAudLang4PopUp];
2930 [self writeToActivityLog: "applyQueueSettingsToMainWindow: audio set up"];
2932 /* Crashy crashy right now, working on it */
2933 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2934 [fSubtitlesTable reloadData];
2935 /* Picture Settings */
2937 /* If Cropping is set to custom, then recall all four crop values from
2938 when the preset was created and apply them */
2939 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2941 [fPictureController setAutoCrop:NO];
2943 /* Here we use the custom crop values saved at the time the preset was saved */
2944 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2945 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2946 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2947 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2950 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2952 [fPictureController setAutoCrop:YES];
2953 /* Here we use the auto crop values determined right after scan */
2954 job->crop[0] = AutoCropTop;
2955 job->crop[1] = AutoCropBottom;
2956 job->crop[2] = AutoCropLeft;
2957 job->crop[3] = AutoCropRight;
2961 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2963 /* we check to make sure the presets width/height does not exceed the sources width/height */
2964 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2966 /* if so, then we use the sources height and width to avoid scaling up */
2967 //job->width = fTitle->width;
2968 //job->height = fTitle->height;
2969 [self revertPictureSizeToMax:nil];
2971 else // source width/height is >= the preset height/width
2973 /* we can go ahead and use the presets values for height and width */
2974 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2975 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2977 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2978 if (job->keep_ratio == 1)
2980 hb_fix_aspect( job, HB_KEEP_WIDTH );
2981 if( job->height > fTitle->height )
2983 job->height = fTitle->height;
2984 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2987 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2988 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2990 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture sizing set up"];
2995 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2996 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2997 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
3000 [fPictureController setUseDecomb:1];
3001 [fPictureController setDecomb:0];
3002 [fPictureController setDeinterlace:0];
3003 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3005 /* we are using decomb */
3007 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
3009 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
3011 /* if we are using "Custom" in the decomb setting, also set the custom string*/
3012 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3014 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
3020 /* We are using Deinterlace */
3022 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
3024 [fPictureController setUseDecomb:0];
3025 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
3026 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
3027 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3029 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
3036 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
3038 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
3039 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
3040 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3042 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
3047 [fPictureController setDetelecine:0];
3051 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
3053 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
3054 /* if we are using "Custom" in the denoise setting, also set the custom string*/
3055 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
3057 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
3062 [fPictureController setDenoise:0];
3066 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
3068 /* if its a one, then its the old on/off deblock, set on to 5*/
3069 [fPictureController setDeblock:5];
3073 /* use the settings intValue */
3074 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3077 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3079 [fPictureController setGrayscale:1];
3083 [fPictureController setGrayscale:0];
3086 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3087 [fPictureController SetTitle:fTitle];
3088 [self calculatePictureSizing:nil];
3090 [self writeToActivityLog: "applyQueueSettingsToMainWindow: picture filters set up"];
3091 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3092 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3093 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3094 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3096 /* Deselect the currently selected Preset if there is one*/
3097 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3098 //[self selectPreset:nil];
3100 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3101 /* Change UI to show "Custom" settings are being used */
3102 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3104 curUserPresetChosenNum = nil;
3108 /* Deselect the currently selected Preset if there is one*/
3109 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3110 /* Change UI to show "Custom" settings are being used */
3111 [fPresetSelectedDisplay setStringValue: @"Custom"];
3113 //curUserPresetChosenNum = nil;
3116 /* We need to set this bool back to NO, in case the user wants to do a scan */
3117 //applyQueueToScan = NO;
3119 /* Not that source is loaded and settings applied, delete the queue item from the queue */
3120 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3121 [self removeQueueFileItem:fqueueEditRescanItemNum];
3127 #pragma mark Live Preview
3128 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3129 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3132 - (void) prepareJobForPreview
3134 hb_list_t * list = hb_get_titles( fHandle );
3135 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3136 [fSrcTitlePopUp indexOfSelectedItem] );
3137 hb_job_t * job = title->job;
3138 hb_audio_config_t * audio;
3139 /* set job->angle for libdvdnav */
3140 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3141 /* Chapter selection */
3142 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3143 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3145 /* Format (Muxer) and Video Encoder */
3146 job->mux = [[fDstFormatPopUp selectedItem] tag];
3147 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3149 job->chapter_markers = 0;
3151 if( job->vcodec & HB_VCODEC_X264 )
3154 /* Below Sends x264 options to the core library if x264 is selected*/
3155 /* Lets use this as per Nyx, Thanks Nyx!*/
3156 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3157 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3158 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3163 /* Video settings */
3164 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3165 * and detelecine is on, so we handle that in the logic below
3168 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3170 /* a specific framerate has been chosen */
3171 job->vrate = 27000000;
3172 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3173 /* We are not same as source so we set job->cfr to 1
3174 * to enable constant frame rate since user has specified
3175 * a specific framerate*/
3180 /* We are same as source (variable) */
3181 job->vrate = title->rate;
3182 job->vrate_base = title->rate_base;
3183 /* We are same as source so we set job->cfr to 0
3184 * to enable true same as source framerate */
3186 /* If we are same as source and we have detelecine on, we need to turn on
3189 if ([fPictureController detelecine] == 1)
3195 switch( [fVidQualityMatrix selectedRow] )
3199 Bitrate should already have been calculated and displayed
3200 in fVidBitrateField, so let's just use it */
3202 job->vquality = -1.0;
3203 job->vbitrate = [fVidBitrateField intValue];
3206 job->vquality = [fVidQualityRFField floatValue];
3211 /* Subtitle settings */
3212 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3219 bool one_burned = FALSE;
3222 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3224 while (tempObject = [enumerator nextObject])
3227 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3228 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3229 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3230 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3232 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3233 * we want to ignore it for display as well as encoding.
3237 /* if i is 0, then we are in the first item of the subtitles which we need to
3238 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3239 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3242 /* if we are on the first track and using "Foreign Audio Search" */
3243 if (i == 0 && subtitle == 1)
3245 /* NOTE: Currently foreign language search is borked for preview.
3246 * Commented out but left in for initial commit. */
3249 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3251 job->indepth_scan = 1;
3252 if (burned == 1 || job->mux != HB_MUX_MP4)
3254 if (burned != 1 && job->mux == HB_MUX_MKV)
3256 job->select_subtitle_config.dest = PASSTHRUSUB;
3260 job->select_subtitle_config.dest = RENDERSUB;
3263 job->select_subtitle_config.force = force;
3264 job->select_subtitle_config.default_track = def;
3273 /* for the actual source tracks, we must subtract the non source entries so
3274 * that the menu index matches the source subtitle_list index for convenience */
3277 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3278 * Foreign Language Search is 1) so subtract 2 */
3279 subtitle = subtitle - 2;
3283 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3286 subtitle = subtitle - 1;
3289 /* We are setting a source subtitle so access the source subtitle info */
3290 hb_subtitle_t * subt;
3292 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3294 /* if we are getting the subtitles from an external srt file */
3295 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3297 hb_subtitle_config_t sub_config;
3299 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3301 /* we need to srncpy file path and char code */
3302 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3303 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3305 sub_config.force = 0;
3306 sub_config.dest = PASSTHRUSUB;
3307 sub_config.default_track = def;
3309 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3314 hb_subtitle_config_t sub_config = subt->config;
3316 if (!burned && job->mux == HB_MUX_MKV &&
3317 subt->format == PICTURESUB)
3319 sub_config.dest = PASSTHRUSUB;
3321 else if (!burned && job->mux == HB_MUX_MP4 &&
3322 subt->format == PICTURESUB)
3324 // Skip any non-burned vobsubs when output is mp4
3327 else if ( burned && subt->format == PICTURESUB )
3329 // Only allow one subtitle to be burned into the video
3334 sub_config.force = force;
3335 sub_config.default_track = def;
3336 hb_subtitle_add( job, &sub_config, subtitle );
3346 [subtitlesArray autorelease];
3349 /* Audio tracks and mixdowns */
3350 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3351 int audiotrack_count = hb_list_count(job->list_audio);
3352 for( int i = 0; i < audiotrack_count;i++)
3354 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3355 hb_list_rem(job->list_audio, temp_audio);
3357 /* Now lets add our new tracks to the audio list here */
3358 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3360 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3361 hb_audio_config_init(audio);
3362 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3363 /* We go ahead and assign values to our audio->out.<properties> */
3364 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3365 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3366 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3367 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3368 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3369 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3371 hb_audio_add( job, audio );
3374 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3376 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3377 hb_audio_config_init(audio);
3378 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3379 /* We go ahead and assign values to our audio->out.<properties> */
3380 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3381 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3382 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3383 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3384 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3385 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3387 hb_audio_add( job, audio );
3392 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3394 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3395 hb_audio_config_init(audio);
3396 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3397 /* We go ahead and assign values to our audio->out.<properties> */
3398 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3399 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3400 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3401 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3402 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3403 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3405 hb_audio_add( job, audio );
3410 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3412 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3413 hb_audio_config_init(audio);
3414 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3415 /* We go ahead and assign values to our audio->out.<properties> */
3416 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3417 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3418 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3419 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3420 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3421 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3423 hb_audio_add( job, audio );
3432 /* Though Grayscale is not really a filter, per se
3433 * we put it here since its in the filters panel
3436 if ([fPictureController grayscale])
3445 /* Initialize the filters list */
3446 job->filters = hb_list_init();
3448 /* Now lets call the filters if applicable.
3449 * The order of the filters is critical
3453 if ([fPictureController detelecine] == 1)
3455 /* use a custom detelecine string */
3456 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3457 hb_list_add( job->filters, &hb_filter_detelecine );
3459 if ([fPictureController detelecine] == 2)
3462 hb_list_add( job->filters, &hb_filter_detelecine );
3467 if ([fPictureController useDecomb] == 1)
3470 /* we add the custom string if present */
3471 if ([fPictureController decomb] == 1)
3473 /* use a custom decomb string */
3474 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3475 hb_list_add( job->filters, &hb_filter_decomb );
3477 if ([fPictureController decomb] == 2)
3479 /* Run old deinterlacer fd by default */
3480 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3481 hb_list_add( job->filters, &hb_filter_decomb );
3488 if ([fPictureController deinterlace] == 1)
3490 /* we add the custom string if present */
3491 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3492 hb_list_add( job->filters, &hb_filter_deinterlace );
3494 else if ([fPictureController deinterlace] == 2)
3496 /* Run old deinterlacer fd by default */
3497 hb_filter_deinterlace.settings = "-1";
3498 hb_list_add( job->filters, &hb_filter_deinterlace );
3500 else if ([fPictureController deinterlace] == 3)
3502 /* Yadif mode 0 (without spatial deinterlacing.) */
3503 hb_filter_deinterlace.settings = "2";
3504 hb_list_add( job->filters, &hb_filter_deinterlace );
3506 else if ([fPictureController deinterlace] == 4)
3508 /* Yadif (with spatial deinterlacing) */
3509 hb_filter_deinterlace.settings = "0";
3510 hb_list_add( job->filters, &hb_filter_deinterlace );
3516 if ([fPictureController denoise] == 1) // custom in popup
3518 /* we add the custom string if present */
3519 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3520 hb_list_add( job->filters, &hb_filter_denoise );
3522 else if ([fPictureController denoise] == 2) // Weak in popup
3524 hb_filter_denoise.settings = "2:1:2:3";
3525 hb_list_add( job->filters, &hb_filter_denoise );
3527 else if ([fPictureController denoise] == 3) // Medium in popup
3529 hb_filter_denoise.settings = "3:2:2:3";
3530 hb_list_add( job->filters, &hb_filter_denoise );
3532 else if ([fPictureController denoise] == 4) // Strong in popup
3534 hb_filter_denoise.settings = "7:7:5:5";
3535 hb_list_add( job->filters, &hb_filter_denoise );
3539 /* Deblock (uses pp7 default) */
3540 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3541 * the macgui's purposes a value of 0 actually means to not even use the filter
3542 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3544 if ([fPictureController deblock] != 0)
3546 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3547 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3548 hb_list_add( job->filters, &hb_filter_deblock );
3555 #pragma mark Job Handling
3561 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3562 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3563 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3564 hb_job_t * job = title->job;
3565 hb_audio_config_t * audio;
3566 /* Title Angle for dvdnav */
3567 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3569 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3571 /* Chapter selection */
3572 [self writeToActivityLog: "Start / Stop set to chapters"];
3573 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3574 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3576 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3578 /* we are pts based start / stop */
3579 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3581 /* 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
3582 * 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.
3584 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3585 /* get the start seconds from the start seconds field */
3586 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3587 //job->start_at_preview = start_seconds;
3588 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3589 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3590 job->pts_to_start = start_seconds * 90000LL;
3591 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3592 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3593 job->pts_to_stop = stop_seconds * 90000LL;
3595 /* A bunch of verbose activity log messages to check on what should be expected */
3596 [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3597 [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];
3598 [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3599 [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3600 [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3601 [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];
3603 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3605 /* we are frame based start / stop */
3606 [self writeToActivityLog: "Start / Stop set to frames ..."];
3608 /* 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
3609 * 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.
3611 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3612 /* get the start seconds from the start seconds field */
3613 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3614 //job->start_at_preview = start_seconds;
3615 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3616 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3617 job->frame_to_start = start_frame;
3618 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3619 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3620 job->frame_to_stop = stop_frame;
3622 /* A bunch of verbose activity log messages to check on what should be expected */
3623 [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3624 [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3625 [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3631 /* Format (Muxer) and Video Encoder */
3632 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3633 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3636 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3637 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3639 job->largeFileSize = 1;
3643 job->largeFileSize = 0;
3645 /* We set http optimized mp4 here */
3646 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3648 job->mp4_optimize = 1;
3652 job->mp4_optimize = 0;
3656 /* We set the chapter marker extraction here based on the format being
3657 mpeg4 or mkv and the checkbox being checked */
3658 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3660 job->chapter_markers = 1;
3662 /* now lets get our saved chapter names out the array in the queue file
3663 * and insert them back into the title chapter list. We have it here,
3664 * because unless we are inserting chapter markers there is no need to
3665 * spend the overhead of iterating through the chapter names array imo
3666 * Also, note that if for some reason we don't apply chapter names, the
3667 * chapters just come out 001, 002, etc. etc.
3670 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3672 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3674 while (tempObject = [enumerator nextObject])
3676 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3677 if( chapter != NULL )
3679 strncpy( chapter->title, [tempObject UTF8String], 1023);
3680 chapter->title[1023] = '\0';
3687 job->chapter_markers = 0;
3690 if( job->vcodec & HB_VCODEC_X264 )
3692 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3702 /* Below Sends x264 options to the core library if x264 is selected*/
3703 /* Lets use this as per Nyx, Thanks Nyx!*/
3704 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3705 /* Turbo first pass if two pass and Turbo First pass is selected */
3706 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3708 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3709 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3710 /* append the "Turbo" string variable to the existing opts string.
3711 Note: the "Turbo" string must be appended, not prepended to work properly*/
3712 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3713 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3717 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3723 /* Picture Size Settings */
3724 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3725 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3727 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3728 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3729 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3730 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3732 /* insert our custom values here for capuj */
3733 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3734 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3736 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3738 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3739 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3741 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3742 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3745 /* Here we use the crop values saved at the time the preset was saved */
3746 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3747 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3748 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3749 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3751 /* Video settings */
3754 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3755 * and detelecine is on, so we handle that in the logic below
3758 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3760 /* a specific framerate has been chosen */
3761 job->vrate = 27000000;
3762 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3763 /* We are not same as source so we set job->cfr to 1
3764 * to enable constant frame rate since user has specified
3765 * a specific framerate*/
3770 /* We are same as source (variable) */
3771 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3772 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3773 /* We are same as source so we set job->cfr to 0
3774 * to enable true same as source framerate */
3776 /* If we are same as source and we have detelecine on, we need to turn on
3779 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3785 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3788 Bitrate should already have been calculated and displayed
3789 in fVidBitrateField, so let's just use it same as abr*/
3790 job->vquality = -1.0;
3791 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3793 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3795 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3800 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3805 #pragma mark Process Subtitles to libhb
3807 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3808 * which means that we need to account for the offset of non source language settings in from
3809 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3810 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3811 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3812 * to the source tracks position in title->list_subtitle.
3819 bool one_burned = FALSE;
3822 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3824 while (tempObject = [enumerator nextObject])
3827 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3828 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3829 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3830 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3832 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3833 * we want to ignore it for display as well as encoding.
3837 /* if i is 0, then we are in the first item of the subtitles which we need to
3838 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3839 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3842 /* if we are on the first track and using "Foreign Audio Search" */
3843 if (i == 0 && subtitle == 1)
3845 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3847 job->indepth_scan = 1;
3848 if (burned == 1 || job->mux != HB_MUX_MP4)
3850 if (burned != 1 && job->mux == HB_MUX_MKV)
3852 job->select_subtitle_config.dest = PASSTHRUSUB;
3856 job->select_subtitle_config.dest = RENDERSUB;
3859 job->select_subtitle_config.force = force;
3860 job->select_subtitle_config.default_track = def;
3868 /* for the actual source tracks, we must subtract the non source entries so
3869 * that the menu index matches the source subtitle_list index for convenience */
3872 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3873 * Foreign Language Search is 1) so subtract 2 */
3874 subtitle = subtitle - 2;
3878 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3881 subtitle = subtitle - 1;
3884 /* We are setting a source subtitle so access the source subtitle info */
3885 hb_subtitle_t * subt;
3887 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3889 /* if we are getting the subtitles from an external srt file */
3890 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3892 hb_subtitle_config_t sub_config;
3894 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3896 /* we need to srncpy file name and codeset */
3897 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3898 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3900 sub_config.force = 0;
3901 sub_config.dest = PASSTHRUSUB;
3902 sub_config.default_track = def;
3904 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3910 hb_subtitle_config_t sub_config = subt->config;
3912 if (!burned && job->mux == HB_MUX_MKV &&
3913 subt->format == PICTURESUB)
3915 sub_config.dest = PASSTHRUSUB;
3917 else if (!burned && job->mux == HB_MUX_MP4 &&
3918 subt->format == PICTURESUB)
3920 // Skip any non-burned vobsubs when output is mp4
3923 else if ( burned && subt->format == PICTURESUB )
3925 // Only allow one subtitle to be burned into the video
3930 sub_config.force = force;
3931 sub_config.default_track = def;
3932 hb_subtitle_add( job, &sub_config, subtitle );
3943 /* Audio tracks and mixdowns */
3944 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3945 int audiotrack_count = hb_list_count(job->list_audio);
3946 for( int i = 0; i < audiotrack_count;i++)
3948 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3949 hb_list_rem(job->list_audio, temp_audio);
3951 /* Now lets add our new tracks to the audio list here */
3952 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3954 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3955 hb_audio_config_init(audio);
3956 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3957 /* We go ahead and assign values to our audio->out.<properties> */
3958 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3959 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3960 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3961 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3962 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3963 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3965 hb_audio_add( job, audio );
3968 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3971 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3972 hb_audio_config_init(audio);
3973 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3974 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3975 /* We go ahead and assign values to our audio->out.<properties> */
3976 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3977 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3978 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3979 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3980 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3981 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3983 hb_audio_add( job, audio );
3987 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3989 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3990 hb_audio_config_init(audio);
3991 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3992 /* We go ahead and assign values to our audio->out.<properties> */
3993 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3994 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3995 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3996 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3997 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3998 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
4000 hb_audio_add( job, audio );
4004 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
4006 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4007 hb_audio_config_init(audio);
4008 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4009 /* We go ahead and assign values to our audio->out.<properties> */
4010 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
4011 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
4012 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
4013 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
4014 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
4015 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
4017 hb_audio_add( job, audio );
4023 job->filters = hb_list_init();
4025 /* Now lets call the filters if applicable.
4026 * The order of the filters is critical
4029 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
4031 /* use a custom detelecine string */
4032 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
4033 hb_list_add( job->filters, &hb_filter_detelecine );
4035 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
4037 /* Use libhb's default values */
4038 hb_list_add( job->filters, &hb_filter_detelecine );
4041 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
4044 /* we add the custom string if present */
4045 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
4047 /* use a custom decomb string */
4048 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
4049 hb_list_add( job->filters, &hb_filter_decomb );
4051 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
4053 /* Use libhb default */
4054 hb_list_add( job->filters, &hb_filter_decomb );
4062 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
4064 /* we add the custom string if present */
4065 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
4066 hb_list_add( job->filters, &hb_filter_deinterlace );
4068 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
4070 /* Run old deinterlacer fd by default */
4071 hb_filter_deinterlace.settings = "-1";
4072 hb_list_add( job->filters, &hb_filter_deinterlace );
4074 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
4076 /* Yadif mode 0 (without spatial deinterlacing.) */
4077 hb_filter_deinterlace.settings = "2";
4078 hb_list_add( job->filters, &hb_filter_deinterlace );
4080 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
4082 /* Yadif (with spatial deinterlacing) */
4083 hb_filter_deinterlace.settings = "0";
4084 hb_list_add( job->filters, &hb_filter_deinterlace );
4090 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
4092 /* we add the custom string if present */
4093 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
4094 hb_list_add( job->filters, &hb_filter_denoise );
4096 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
4098 hb_filter_denoise.settings = "2:1:2:3";
4099 hb_list_add( job->filters, &hb_filter_denoise );
4101 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
4103 hb_filter_denoise.settings = "3:2:2:3";
4104 hb_list_add( job->filters, &hb_filter_denoise );
4106 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4108 hb_filter_denoise.settings = "7:7:5:5";
4109 hb_list_add( job->filters, &hb_filter_denoise );
4113 /* Deblock (uses pp7 default) */
4114 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
4115 * the macgui's purposes a value of 0 actually means to not even use the filter
4116 * current hb_filter_deblock.settings valid ranges are from 5 - 15
4118 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4120 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4121 hb_list_add( job->filters, &hb_filter_deblock );
4123 [self writeToActivityLog: "prepareJob exiting"];
4128 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4130 - (IBAction) addToQueue: (id) sender
4132 /* We get the destination directory from the destination field here */
4133 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4134 /* We check for a valid destination here */
4135 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4137 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4144 BOOL fileExistsInQueue;
4145 fileExistsInQueue = NO;
4147 /* We check for and existing file here */
4148 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4153 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4155 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4157 while (tempObject = [enumerator nextObject])
4159 NSDictionary *thisQueueDict = tempObject;
4160 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4162 fileExistsInQueue = YES;
4168 if(fileExists == YES)
4170 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4171 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4172 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4173 NULL, NULL, [NSString stringWithFormat:
4174 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4175 [fDstFile2Field stringValue]] );
4177 else if (fileExistsInQueue == YES)
4179 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4180 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4181 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4182 NULL, NULL, [NSString stringWithFormat:
4183 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4184 [fDstFile2Field stringValue]] );
4188 [self doAddToQueue];
4192 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4193 the user if they want to overwrite an exiting movie file.
4195 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4196 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4198 if( returnCode == NSAlertAlternateReturn )
4199 [self doAddToQueue];
4202 - (void) doAddToQueue
4204 [self addQueueFileItem ];
4209 /* Rip: puts up an alert before ultimately calling doRip
4211 - (IBAction) Rip: (id) sender
4213 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4214 /* Rip or Cancel ? */
4216 hb_get_state2( fQueueEncodeLibhb, &s );
4218 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4220 [self Cancel: sender];
4224 /* We check to see if we need to warn the user that the computer will go to sleep
4225 or shut down when encoding is finished */
4226 [self remindUserOfSleepOrShutdown];
4228 // If there are pending jobs in the queue, then this is a rip the queue
4229 if (fPendingCount > 0)
4231 /* here lets start the queue with the first pending item */
4232 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4237 // Before adding jobs to the queue, check for a valid destination.
4239 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4240 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4242 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4246 /* We check for duplicate name here */
4247 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4249 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4250 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4251 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4252 NULL, NULL, [NSString stringWithFormat:
4253 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4254 [fDstFile2Field stringValue]] );
4256 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4260 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4261 otherwise, just rip the queue */
4262 if(fPendingCount == 0)
4264 [self doAddToQueue];
4267 /* go right to processing the new queue encode */
4268 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4273 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4274 want to overwrite an exiting movie file.
4276 - (void) overWriteAlertDone: (NSWindow *) sheet
4277 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4279 if( returnCode == NSAlertAlternateReturn )
4281 /* if there are no jobs in the queue, then add this one to the queue and rip
4282 otherwise, just rip the queue */
4283 if( fPendingCount == 0 )
4285 [self doAddToQueue];
4288 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4289 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4290 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4295 - (void) remindUserOfSleepOrShutdown
4297 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4299 /*Warn that computer will sleep after encoding*/
4302 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);
4303 [NSApp requestUserAttention:NSCriticalRequest];
4304 if ( reminduser == NSAlertAlternateReturn )
4306 [self showPreferencesWindow:nil];
4309 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4311 /*Warn that computer will shut down after encoding*/
4314 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);
4315 [NSApp requestUserAttention:NSCriticalRequest];
4316 if ( reminduser == NSAlertAlternateReturn )
4318 [self showPreferencesWindow:nil];
4327 /* Let libhb do the job */
4328 hb_start( fQueueEncodeLibhb );
4329 /*set the fEncodeState State */
4334 //------------------------------------------------------------------------------------
4335 // Displays an alert asking user if the want to cancel encoding of current job.
4336 // Cancel: returns immediately after posting the alert. Later, when the user
4337 // acknowledges the alert, doCancelCurrentJob is called.
4338 //------------------------------------------------------------------------------------
4339 - (IBAction)Cancel: (id)sender
4341 if (!fQueueController) return;
4343 hb_pause( fQueueEncodeLibhb );
4344 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4346 // Which window to attach the sheet to?
4347 NSWindow * docWindow;
4348 if ([sender respondsToSelector: @selector(window)])
4349 docWindow = [sender window];
4351 docWindow = fWindow;
4353 NSBeginCriticalAlertSheet(
4355 NSLocalizedString(@"Continue Encoding", nil),
4356 NSLocalizedString(@"Cancel Current and Stop", nil),
4357 NSLocalizedString(@"Cancel Current and Continue", nil),
4359 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4360 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4362 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4365 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4367 hb_resume( fQueueEncodeLibhb );
4368 if (returnCode == NSAlertOtherReturn)
4370 [self doCancelCurrentJob]; // <- this also stops libhb
4372 if (returnCode == NSAlertAlternateReturn)
4374 [self doCancelCurrentJobAndStop];
4378 //------------------------------------------------------------------------------------
4379 // Cancels and deletes the current job and stops libhb from processing the remaining
4381 //------------------------------------------------------------------------------------
4382 - (void) doCancelCurrentJob
4384 // Stop the current job. hb_stop will only cancel the current pass and then set
4385 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4386 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4387 // remaining passes of the job and then start the queue back up if there are any
4391 hb_stop( fQueueEncodeLibhb );
4393 // Delete all remaining jobs since libhb doesn't do this on its own.
4395 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4396 hb_rem( fQueueEncodeLibhb, job );
4398 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4400 // now that we've stopped the currently encoding job, lets mark it as cancelled
4401 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4402 // and as always, save it in the queue .plist...
4403 /* We save all of the Queue data here */
4404 [self saveQueueFileItem];
4405 // so now lets move to
4406 currentQueueEncodeIndex++ ;
4407 // ... and see if there are more items left in our queue
4408 int queueItems = [QueueFileArray count];
4409 /* If we still have more items in our queue, lets go to the next one */
4410 if (currentQueueEncodeIndex < queueItems)
4412 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4413 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4415 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4419 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4424 - (void) doCancelCurrentJobAndStop
4426 hb_stop( fQueueEncodeLibhb );
4428 // Delete all remaining jobs since libhb doesn't do this on its own.
4430 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4431 hb_rem( fQueueEncodeLibhb, job );
4434 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4436 // now that we've stopped the currently encoding job, lets mark it as cancelled
4437 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4438 // and as always, save it in the queue .plist...
4439 /* We save all of the Queue data here */
4440 [self saveQueueFileItem];
4441 // so now lets move to
4442 currentQueueEncodeIndex++ ;
4443 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4445 - (IBAction) Pause: (id) sender
4448 hb_get_state2( fQueueEncodeLibhb, &s );
4450 if( s.state == HB_STATE_PAUSED )
4452 hb_resume( fQueueEncodeLibhb );
4456 hb_pause( fQueueEncodeLibhb );
4461 #pragma mark GUI Controls Changed Methods
4463 - (IBAction) titlePopUpChanged: (id) sender
4465 hb_list_t * list = hb_get_titles( fHandle );
4466 hb_title_t * title = (hb_title_t*)
4467 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4469 /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4470 if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4472 /* we set the default name according to the new title->name */
4473 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4474 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4475 [NSString stringWithUTF8String: title->name],
4476 [[fDstFile2Field stringValue] pathExtension]]];
4478 /* Change the source to read out the parent folder also */
4479 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4482 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4483 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4484 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4485 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4486 /* 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 */
4487 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4488 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4489 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4491 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4492 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4494 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4495 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4496 [browsedSourceDisplayName stringByDeletingPathExtension],
4498 [[fDstFile2Field stringValue] pathExtension]]];
4500 /* Update encode start / stop variables */
4504 /* Update chapter popups */
4505 [fSrcChapterStartPopUp removeAllItems];
4506 [fSrcChapterEndPopUp removeAllItems];
4507 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4509 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4510 stringWithFormat: @"%d", i + 1]];
4511 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4512 stringWithFormat: @"%d", i + 1]];
4515 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4516 [fSrcChapterEndPopUp selectItemAtIndex:
4517 hb_list_count( title->list_chapter ) - 1];
4518 [self chapterPopUpChanged:nil];
4520 /* if using dvd nav, show the angle widget */
4521 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4523 [fSrcAngleLabel setHidden:NO];
4524 [fSrcAnglePopUp setHidden:NO];
4526 [fSrcAnglePopUp removeAllItems];
4527 for( int i = 0; i < title->angle_count; i++ )
4529 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4531 [fSrcAnglePopUp selectItemAtIndex: 0];
4535 [fSrcAngleLabel setHidden:YES];
4536 [fSrcAnglePopUp setHidden:YES];
4539 /* Start Get and set the initial pic size for display */
4540 hb_job_t * job = title->job;
4543 /* Set Auto Crop to on upon selecting a new title */
4544 [fPictureController setAutoCrop:YES];
4546 /* We get the originial output picture width and height and put them
4547 in variables for use with some presets later on */
4548 PicOrigOutputWidth = job->width;
4549 PicOrigOutputHeight = job->height;
4550 AutoCropTop = job->crop[0];
4551 AutoCropBottom = job->crop[1];
4552 AutoCropLeft = job->crop[2];
4553 AutoCropRight = job->crop[3];
4555 /* Reset the new title in fPictureController && fPreviewController*/
4556 [fPictureController SetTitle:title];
4559 /* Update Subtitle Table */
4560 [fSubtitlesDelegate resetWithTitle:title];
4561 [fSubtitlesTable reloadData];
4564 /* Update chapter table */
4565 [fChapterTitlesDelegate resetWithTitle:title];
4566 [fChapterTable reloadData];
4568 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4569 int audiotrack_count = hb_list_count(job->list_audio);
4570 for( int i = 0; i < audiotrack_count;i++)
4572 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4573 hb_list_rem(job->list_audio, temp_audio);
4576 /* Update audio popups */
4577 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4578 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4579 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4580 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4581 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4582 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4583 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4584 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4585 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4586 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4588 /* changing the title may have changed the audio channels on offer, */
4589 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4590 [self audioTrackPopUpChanged: fAudLang1PopUp];
4591 [self audioTrackPopUpChanged: fAudLang2PopUp];
4592 [self audioTrackPopUpChanged: fAudLang3PopUp];
4593 [self audioTrackPopUpChanged: fAudLang4PopUp];
4595 [fVidRatePopUp selectItemAtIndex: 0];
4597 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4598 [self calculatePictureSizing:nil];
4600 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4601 [self selectPreset:nil];
4604 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4606 if( [fEncodeStartStopPopUp isEnabled] )
4608 /* We are chapters */
4609 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4611 [fSrcChapterStartPopUp setHidden: NO];
4612 [fSrcChapterEndPopUp setHidden: NO];
4614 [fSrcTimeStartEncodingField setHidden: YES];
4615 [fSrcTimeEndEncodingField setHidden: YES];
4617 [fSrcFrameStartEncodingField setHidden: YES];
4618 [fSrcFrameEndEncodingField setHidden: YES];
4620 [self chapterPopUpChanged:nil];
4622 /* We are time based (seconds) */
4623 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4625 [fSrcChapterStartPopUp setHidden: YES];
4626 [fSrcChapterEndPopUp setHidden: YES];
4628 [fSrcTimeStartEncodingField setHidden: NO];
4629 [fSrcTimeEndEncodingField setHidden: NO];
4631 [fSrcFrameStartEncodingField setHidden: YES];
4632 [fSrcFrameEndEncodingField setHidden: YES];
4634 [self startEndSecValueChanged:nil];
4636 /* We are frame based */
4637 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4639 [fSrcChapterStartPopUp setHidden: YES];
4640 [fSrcChapterEndPopUp setHidden: YES];
4642 [fSrcTimeStartEncodingField setHidden: YES];
4643 [fSrcTimeEndEncodingField setHidden: YES];
4645 [fSrcFrameStartEncodingField setHidden: NO];
4646 [fSrcFrameEndEncodingField setHidden: NO];
4648 [self startEndFrameValueChanged:nil];
4653 - (IBAction) chapterPopUpChanged: (id) sender
4656 /* If start chapter popup is greater than end chapter popup,
4657 we set the end chapter popup to the same as start chapter popup */
4658 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4660 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4664 hb_list_t * list = hb_get_titles( fHandle );
4665 hb_title_t * title = (hb_title_t *)
4666 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4668 hb_chapter_t * chapter;
4669 int64_t duration = 0;
4670 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4671 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4673 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4674 duration += chapter->duration;
4677 duration /= 90000; /* pts -> seconds */
4678 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4679 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4682 [self calculateBitrate: sender];
4684 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4686 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4687 [fCreateChapterMarkers setEnabled: NO];
4688 [fCreateChapterMarkers setState: NSOffState];
4692 [fCreateChapterMarkers setEnabled: YES];
4696 - (IBAction) startEndSecValueChanged: (id) sender
4699 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4700 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4701 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4704 //[self calculateBitrate: sender];
4708 - (IBAction) startEndFrameValueChanged: (id) sender
4710 hb_list_t * list = hb_get_titles( fHandle );
4711 hb_title_t * title = (hb_title_t*)
4712 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4714 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4715 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4716 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4719 //[self calculateBitrate: sender];
4723 - (IBAction) formatPopUpChanged: (id) sender
4725 NSString * string = [fDstFile2Field stringValue];
4726 int format = [fDstFormatPopUp indexOfSelectedItem];
4728 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4729 [fDstMp4LargeFileCheck setHidden: YES];
4730 [fDstMp4HttpOptFileCheck setHidden: YES];
4731 [fDstMp4iPodFileCheck setHidden: YES];
4733 /* Update the Video Codec PopUp */
4734 /* lets get the tag of the currently selected item first so we might reset it later */
4735 int selectedVidEncoderTag;
4736 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4738 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4739 [fVidEncoderPopUp removeAllItems];
4740 NSMenuItem *menuItem;
4741 /* These video encoders are available to all of our current muxers, so lets list them once here */
4742 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4743 [menuItem setTag: HB_VCODEC_FFMPEG];
4748 /*Get Default MP4 File Extension*/
4749 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4757 /* Add additional video encoders here */
4758 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4759 [menuItem setTag: HB_VCODEC_X264];
4760 /* We show the mp4 option checkboxes here since we are mp4 */
4761 [fCreateChapterMarkers setEnabled: YES];
4762 [fDstMp4LargeFileCheck setHidden: NO];
4763 [fDstMp4HttpOptFileCheck setHidden: NO];
4764 [fDstMp4iPodFileCheck setHidden: NO];
4769 /* Add additional video encoders here */
4770 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4771 [menuItem setTag: HB_VCODEC_X264];
4772 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4773 [menuItem setTag: HB_VCODEC_THEORA];
4774 /* We enable the create chapters checkbox here */
4775 [fCreateChapterMarkers setEnabled: YES];
4780 /* tell fSubtitlesDelegate we have a new video container */
4782 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4783 [fSubtitlesTable reloadData];
4784 /* if we have a previously selected vid encoder tag, then try to select it */
4785 if (selectedVidEncoderTag)
4787 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4791 [fVidEncoderPopUp selectItemAtIndex: 0];
4794 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4795 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4796 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4797 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4800 [self autoSetM4vExtension: sender];
4802 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4804 if( SuccessfulScan )
4806 /* Add/replace to the correct extension */
4807 [self audioTrackPopUpChanged: fAudLang1PopUp];
4808 [self audioTrackPopUpChanged: fAudLang2PopUp];
4809 [self audioTrackPopUpChanged: fAudLang3PopUp];
4810 [self audioTrackPopUpChanged: fAudLang4PopUp];
4812 if( [fVidEncoderPopUp selectedItem] == nil )
4815 [fVidEncoderPopUp selectItemAtIndex:0];
4816 [self videoEncoderPopUpChanged:nil];
4818 /* changing the format may mean that we can / can't offer mono or 6ch, */
4819 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4821 /* We call the method to properly enable/disable turbo 2 pass */
4822 [self twoPassCheckboxChanged: sender];
4823 /* We call method method to change UI to reflect whether a preset is used or not*/
4826 [self customSettingUsed: sender];
4829 - (IBAction) autoSetM4vExtension: (id) sender
4831 if ( [fDstFormatPopUp indexOfSelectedItem] )
4834 NSString * extension = @"mp4";
4836 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4837 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4838 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4839 [fCreateChapterMarkers state] == NSOnState ||
4840 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4845 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4848 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4849 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4852 /* Method to determine if we should change the UI
4853 To reflect whether or not a Preset is being used or if
4854 the user is using "Custom" settings by determining the sender*/
4855 - (IBAction) customSettingUsed: (id) sender
4857 if ([sender stringValue])
4859 /* Deselect the currently selected Preset if there is one*/
4860 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4861 /* Change UI to show "Custom" settings are being used */
4862 [fPresetSelectedDisplay setStringValue: @"Custom"];
4864 curUserPresetChosenNum = nil;
4866 [self calculateBitrate:nil];
4871 #pragma mark - Video
4873 - (IBAction) videoEncoderPopUpChanged: (id) sender
4875 hb_job_t * job = fTitle->job;
4876 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4878 [fAdvancedOptions setHidden:YES];
4879 /* If we are using x264 then show the x264 advanced panel*/
4880 if (videoEncoder == HB_VCODEC_X264)
4882 [fAdvancedOptions setHidden:NO];
4883 [self autoSetM4vExtension: sender];
4886 if (videoEncoder == HB_VCODEC_FFMPEG)
4888 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4889 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4890 anything other than MP4.
4892 [fDstMp4iPodFileCheck setEnabled: NO];
4893 [fDstMp4iPodFileCheck setState: NSOffState];
4897 [fDstMp4iPodFileCheck setEnabled: YES];
4899 [self setupQualitySlider];
4900 [self calculatePictureSizing: sender];
4901 [self twoPassCheckboxChanged: sender];
4905 - (IBAction) twoPassCheckboxChanged: (id) sender
4907 /* check to see if x264 is chosen */
4908 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4910 if( [fVidTwoPassCheck state] == NSOnState)
4912 [fVidTurboPassCheck setHidden: NO];
4916 [fVidTurboPassCheck setHidden: YES];
4917 [fVidTurboPassCheck setState: NSOffState];
4919 /* Make sure Two Pass is checked if Turbo is checked */
4920 if( [fVidTurboPassCheck state] == NSOnState)
4922 [fVidTwoPassCheck setState: NSOnState];
4927 [fVidTurboPassCheck setHidden: YES];
4928 [fVidTurboPassCheck setState: NSOffState];
4931 /* We call method method to change UI to reflect whether a preset is used or not*/
4932 [self customSettingUsed: sender];
4935 - (IBAction ) videoFrameRateChanged: (id) sender
4937 /* We call method method to calculatePictureSizing to error check detelecine*/
4938 [self calculatePictureSizing: sender];
4940 /* We call method method to change UI to reflect whether a preset is used or not*/
4941 [self customSettingUsed: sender];
4943 - (IBAction) videoMatrixChanged: (id) sender;
4945 bool target, bitrate, quality;
4947 target = bitrate = quality = false;
4948 if( [fVidQualityMatrix isEnabled] )
4950 switch( [fVidQualityMatrix selectedRow] )
4963 [fVidTargetSizeField setEnabled: target];
4964 [fVidBitrateField setEnabled: bitrate];
4965 [fVidQualitySlider setEnabled: quality];
4966 [fVidQualityRFField setEnabled: quality];
4967 [fVidQualityRFLabel setEnabled: quality];
4968 [fVidTwoPassCheck setEnabled: !quality &&
4969 [fVidQualityMatrix isEnabled]];
4972 [fVidTwoPassCheck setState: NSOffState];
4973 [fVidTurboPassCheck setHidden: YES];
4974 [fVidTurboPassCheck setState: NSOffState];
4977 [self qualitySliderChanged: sender];
4978 [self calculateBitrate: sender];
4979 [self customSettingUsed: sender];
4982 /* Use this method to setup the quality slider for cq/rf values depending on
4983 * the video encoder selected.
4985 - (void) setupQualitySlider
4987 /* Get the current slider maxValue to check for a change in slider scale later
4988 * so that we can choose a new similar value on the new slider scale */
4989 float previousMaxValue = [fVidQualitySlider maxValue];
4990 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4991 NSString * qpRFLabelString = @"QP:";
4993 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4995 [fVidQualitySlider setMinValue:0.0];
4996 [fVidQualitySlider setMaxValue:51.0];
4997 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4998 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4999 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
5000 qpRFLabelString = @"RF:";
5003 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
5005 [fVidQualitySlider setMinValue:1.0];
5006 [fVidQualitySlider setMaxValue:31.0];
5007 [fVidQualitySlider setNumberOfTickMarks:31];
5010 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5012 [fVidQualitySlider setMinValue:0.0];
5013 [fVidQualitySlider setMaxValue:63.0];
5014 [fVidQualitySlider setNumberOfTickMarks:64];
5016 [fVidQualityRFLabel setStringValue:qpRFLabelString];
5018 /* check to see if we have changed slider scales */
5019 if (previousMaxValue != [fVidQualitySlider maxValue])
5021 /* if so, convert the old setting to the new scale as close as possible based on percentages */
5022 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
5023 [fVidQualitySlider setFloatValue:rf];
5026 [self qualitySliderChanged:nil];
5029 - (IBAction) qualitySliderChanged: (id) sender
5031 /* Our constant quality slider is in a range based
5032 * on each encoders qp/rf values. The range depends
5033 * on the encoder. Also, the range is inverse of quality
5034 * for all of the encoders *except* for theora
5035 * (ie. as the "quality" goes up, the cq or rf value
5036 * actually goes down). Since the IB sliders always set
5037 * their max value at the right end of the slider, we
5038 * will calculate the inverse, so as the slider floatValue
5039 * goes up, we will show the inverse in the rf field
5040 * so, the floatValue at the right for x264 would be 51
5041 * and our rf field needs to show 0 and vice versa.
5044 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
5045 /* If the encoder is theora, use the float, otherwise use the inverse float*/
5046 //float sliderRfToPercent;
5047 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5049 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
5053 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
5055 [self customSettingUsed: sender];
5058 - (void) controlTextDidChange: (NSNotification *) notification
5060 [self calculateBitrate:nil];
5063 - (IBAction) calculateBitrate: (id) sender
5065 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
5070 hb_list_t * list = hb_get_titles( fHandle );
5071 hb_title_t * title = (hb_title_t *) hb_list_item( list,
5072 [fSrcTitlePopUp indexOfSelectedItem] );
5073 hb_job_t * job = title->job;
5074 hb_audio_config_t * audio;
5075 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
5076 * Target Size Field, we also need the job info for the Muxer, the Chapters
5077 * as well as all of the audio track info.
5078 * This used to be accomplished by simply calling prepareJob here, however
5079 * since the resilient queue sets the queue array values instead of the job
5080 * values directly, we duplicate the old prepareJob code here for the variables
5083 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
5084 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
5085 job->mux = [[fDstFormatPopUp selectedItem] tag];
5087 /* Audio goes here */
5088 int audiotrack_count = hb_list_count(job->list_audio);
5089 for( int i = 0; i < audiotrack_count;i++)
5091 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5092 hb_list_rem(job->list_audio, temp_audio);
5094 /* Now we need our audio info here for each track if applicable */
5095 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5097 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5098 hb_audio_config_init(audio);
5099 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5100 /* We go ahead and assign values to our audio->out.<properties> */
5101 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5102 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5103 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5104 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5105 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5106 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5108 hb_audio_add( job, audio );
5111 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5113 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5114 hb_audio_config_init(audio);
5115 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5116 /* We go ahead and assign values to our audio->out.<properties> */
5117 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5118 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5119 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5120 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5121 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5122 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5124 hb_audio_add( job, audio );
5129 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5131 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5132 hb_audio_config_init(audio);
5133 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5134 /* We go ahead and assign values to our audio->out.<properties> */
5135 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5136 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5137 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5138 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5139 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5140 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5142 hb_audio_add( job, audio );
5147 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5149 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5150 hb_audio_config_init(audio);
5151 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5152 /* We go ahead and assign values to our audio->out.<properties> */
5153 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5154 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5155 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5156 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5157 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5158 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5160 hb_audio_add( job, audio );
5165 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5169 #pragma mark - Picture
5171 /* lets set the picture size back to the max from right after title scan
5172 Lets use an IBAction here as down the road we could always use a checkbox
5173 in the gui to easily take the user back to max. Remember, the compiler
5174 resolves IBActions down to -(void) during compile anyway */
5175 - (IBAction) revertPictureSizeToMax: (id) sender
5177 hb_job_t * job = fTitle->job;
5178 /* Here we apply the title source and height */
5179 job->width = fTitle->width;
5180 job->height = fTitle->height;
5182 [self calculatePictureSizing: sender];
5183 /* We call method to change UI to reflect whether a preset is used or not*/
5184 [self customSettingUsed: sender];
5188 * Registers changes made in the Picture Settings Window.
5191 - (void)pictureSettingsDidChange
5193 [self calculatePictureSizing:nil];
5196 /* Get and Display Current Pic Settings in main window */
5197 - (IBAction) calculatePictureSizing: (id) sender
5199 if (fTitle->job->anamorphic.mode > 0)
5201 fTitle->job->keep_ratio = 0;
5204 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5206 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5210 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5212 NSString *picCropping;
5213 /* Set the display field for crop as per boolean */
5214 if (![fPictureController autoCrop])
5216 picCropping = @"Custom";
5220 picCropping = @"Auto";
5222 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]]];
5224 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5226 NSString *videoFilters;
5229 if ([fPictureController detelecine] == 2)
5231 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5233 else if ([fPictureController detelecine] == 1)
5235 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5239 if ([fPictureController useDecomb] == 1)
5242 if ([fPictureController decomb] == 2)
5244 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5246 else if ([fPictureController decomb] == 1)
5248 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5254 if ([fPictureController deinterlace] > 0)
5256 fTitle->job->deinterlace = 1;
5260 fTitle->job->deinterlace = 0;
5263 if ([fPictureController deinterlace] == 2)
5265 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5267 else if ([fPictureController deinterlace] == 3)
5269 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5271 else if ([fPictureController deinterlace] == 4)
5273 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5275 else if ([fPictureController deinterlace] == 1)
5277 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5283 if ([fPictureController denoise] == 2)
5285 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5287 else if ([fPictureController denoise] == 3)
5289 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5291 else if ([fPictureController denoise] == 4)
5293 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5295 else if ([fPictureController denoise] == 1)
5297 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5301 if ([fPictureController deblock] > 0)
5303 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5307 if ([fPictureController grayscale])
5309 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5311 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5313 //[fPictureController reloadStillPreview];
5318 #pragma mark - Audio and Subtitles
5319 - (IBAction) audioCodecsPopUpChanged: (id) sender
5322 NSPopUpButton * audiotrackPopUp;
5323 NSPopUpButton * sampleratePopUp;
5324 NSPopUpButton * bitratePopUp;
5325 NSPopUpButton * audiocodecPopUp;
5326 if (sender == fAudTrack1CodecPopUp)
5328 audiotrackPopUp = fAudLang1PopUp;
5329 audiocodecPopUp = fAudTrack1CodecPopUp;
5330 sampleratePopUp = fAudTrack1RatePopUp;
5331 bitratePopUp = fAudTrack1BitratePopUp;
5333 else if (sender == fAudTrack2CodecPopUp)
5335 audiotrackPopUp = fAudLang2PopUp;
5336 audiocodecPopUp = fAudTrack2CodecPopUp;
5337 sampleratePopUp = fAudTrack2RatePopUp;
5338 bitratePopUp = fAudTrack2BitratePopUp;
5340 else if (sender == fAudTrack3CodecPopUp)
5342 audiotrackPopUp = fAudLang3PopUp;
5343 audiocodecPopUp = fAudTrack3CodecPopUp;
5344 sampleratePopUp = fAudTrack3RatePopUp;
5345 bitratePopUp = fAudTrack3BitratePopUp;
5349 audiotrackPopUp = fAudLang4PopUp;
5350 audiocodecPopUp = fAudTrack4CodecPopUp;
5351 sampleratePopUp = fAudTrack4RatePopUp;
5352 bitratePopUp = fAudTrack4BitratePopUp;
5355 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5356 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5357 [self audioTrackPopUpChanged: audiotrackPopUp];
5361 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5363 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5364 * the settings of the source audio for that track. We leave the samplerate and bitrate
5365 * to audiotrackMixdownChanged
5368 /* We will first verify that a lower track number has been selected before enabling each track
5369 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5371 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5373 [fAudLang2PopUp setEnabled: NO];
5374 [fAudLang2PopUp selectItemAtIndex: 0];
5378 [fAudLang2PopUp setEnabled: YES];
5381 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5383 [fAudLang3PopUp setEnabled: NO];
5384 [fAudLang3PopUp selectItemAtIndex: 0];
5388 [fAudLang3PopUp setEnabled: YES];
5390 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5392 [fAudLang4PopUp setEnabled: NO];
5393 [fAudLang4PopUp selectItemAtIndex: 0];
5397 [fAudLang4PopUp setEnabled: YES];
5399 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5400 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5401 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5402 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5403 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5404 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5405 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5406 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5408 [fAudTrack1CodecPopUp removeAllItems];
5409 [fAudTrack1MixPopUp removeAllItems];
5410 [fAudTrack1RatePopUp removeAllItems];
5411 [fAudTrack1BitratePopUp removeAllItems];
5412 [fAudTrack1DrcSlider setFloatValue: 0.00];
5413 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5415 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5417 [fAudTrack1RatePopUp setEnabled: NO];
5418 [fAudTrack1BitratePopUp setEnabled: NO];
5419 [fAudTrack1DrcSlider setEnabled: NO];
5420 [fAudTrack1DrcField setEnabled: NO];
5423 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5424 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5425 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5426 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5427 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5428 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5429 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5430 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5432 [fAudTrack2CodecPopUp removeAllItems];
5433 [fAudTrack2MixPopUp removeAllItems];
5434 [fAudTrack2RatePopUp removeAllItems];
5435 [fAudTrack2BitratePopUp removeAllItems];
5436 [fAudTrack2DrcSlider setFloatValue: 0.00];
5437 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5439 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5441 [fAudTrack2RatePopUp setEnabled: NO];
5442 [fAudTrack2BitratePopUp setEnabled: NO];
5443 [fAudTrack2DrcSlider setEnabled: NO];
5444 [fAudTrack2DrcField setEnabled: NO];
5447 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5448 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5449 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5450 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5451 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5452 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5453 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5454 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5456 [fAudTrack3CodecPopUp removeAllItems];
5457 [fAudTrack3MixPopUp removeAllItems];
5458 [fAudTrack3RatePopUp removeAllItems];
5459 [fAudTrack3BitratePopUp removeAllItems];
5460 [fAudTrack3DrcSlider setFloatValue: 0.00];
5461 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5463 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5465 [fAudTrack3RatePopUp setEnabled: NO];
5466 [fAudTrack3BitratePopUp setEnabled: NO];
5467 [fAudTrack3DrcSlider setEnabled: NO];
5468 [fAudTrack3DrcField setEnabled: NO];
5471 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5472 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5473 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5474 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5475 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5476 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5477 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5478 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5480 [fAudTrack4CodecPopUp removeAllItems];
5481 [fAudTrack4MixPopUp removeAllItems];
5482 [fAudTrack4RatePopUp removeAllItems];
5483 [fAudTrack4BitratePopUp removeAllItems];
5484 [fAudTrack4DrcSlider setFloatValue: 0.00];
5485 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5487 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5489 [fAudTrack4RatePopUp setEnabled: NO];
5490 [fAudTrack4BitratePopUp setEnabled: NO];
5491 [fAudTrack4DrcSlider setEnabled: NO];
5492 [fAudTrack4DrcField setEnabled: NO];
5497 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5500 hb_list_t * list = hb_get_titles( fHandle );
5501 hb_title_t * title = (hb_title_t*)
5502 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5504 hb_audio_config_t * audio;
5506 [sender removeAllItems];
5507 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5508 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5510 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5511 [[sender menu] addItemWithTitle:
5512 [NSString stringWithUTF8String: audio->lang.description]
5513 action: NULL keyEquivalent: @""];
5515 [sender selectItemAtIndex: 0];
5519 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5522 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5523 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5524 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5525 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5527 if (searchPrefixString)
5530 for( int i = 0; i < [sender numberOfItems]; i++ )
5532 /* Try to find the desired search string */
5533 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5535 [sender selectItemAtIndex: i];
5539 /* couldn't find the string, so select the requested "search string not found" item */
5540 /* index of 0 means select the "none" item */
5541 /* index of 1 means select the first audio track */
5542 [sender selectItemAtIndex: selectIndexIfNotFound];
5546 /* if no search string is provided, then select the selectIndexIfNotFound item */
5547 [sender selectItemAtIndex: selectIndexIfNotFound];
5551 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5553 int format = [fDstFormatPopUp indexOfSelectedItem];
5555 /* setup pointers to the appropriate popups for the correct track */
5556 NSPopUpButton * audiocodecPopUp;
5557 NSPopUpButton * audiotrackPopUp;
5558 if (sender == fAudTrack1CodecPopUp)
5560 audiotrackPopUp = fAudLang1PopUp;
5561 audiocodecPopUp = fAudTrack1CodecPopUp;
5563 else if (sender == fAudTrack2CodecPopUp)
5565 audiotrackPopUp = fAudLang2PopUp;
5566 audiocodecPopUp = fAudTrack2CodecPopUp;
5568 else if (sender == fAudTrack3CodecPopUp)
5570 audiotrackPopUp = fAudLang3PopUp;
5571 audiocodecPopUp = fAudTrack3CodecPopUp;
5575 audiotrackPopUp = fAudLang4PopUp;
5576 audiocodecPopUp = fAudTrack4CodecPopUp;
5579 [audiocodecPopUp removeAllItems];
5580 /* Make sure "None" isnt selected in the source track */
5581 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5583 [audiocodecPopUp setEnabled:YES];
5584 NSMenuItem *menuItem;
5585 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5591 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5592 [menuItem setTag: HB_ACODEC_CA_AAC];
5594 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5595 [menuItem setTag: HB_ACODEC_FAAC];
5597 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5598 [menuItem setTag: HB_ACODEC_AC3];
5604 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5605 [menuItem setTag: HB_ACODEC_CA_AAC];
5607 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5608 [menuItem setTag: HB_ACODEC_FAAC];
5610 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5611 [menuItem setTag: HB_ACODEC_AC3];
5613 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5614 [menuItem setTag: HB_ACODEC_DCA];
5616 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5617 [menuItem setTag: HB_ACODEC_LAME];
5619 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5620 [menuItem setTag: HB_ACODEC_VORBIS];
5623 [audiocodecPopUp selectItemAtIndex:0];
5627 [audiocodecPopUp setEnabled:NO];
5631 - (IBAction) audioTrackPopUpChanged: (id) sender
5633 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5634 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5637 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5640 /* make sure we have a selected title before continuing */
5641 if (fTitle == NULL) return;
5642 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5643 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5645 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5647 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5649 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5651 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5653 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5655 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5657 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5659 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5662 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5663 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5665 sender = fAudLang1PopUp;
5667 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5669 sender = fAudLang2PopUp;
5671 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5673 sender = fAudLang3PopUp;
5675 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5677 sender = fAudLang4PopUp;
5680 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5681 NSPopUpButton * mixdownPopUp;
5682 NSPopUpButton * audiocodecPopUp;
5683 NSPopUpButton * sampleratePopUp;
5684 NSPopUpButton * bitratePopUp;
5685 if (sender == fAudLang1PopUp)
5687 mixdownPopUp = fAudTrack1MixPopUp;
5688 audiocodecPopUp = fAudTrack1CodecPopUp;
5689 sampleratePopUp = fAudTrack1RatePopUp;
5690 bitratePopUp = fAudTrack1BitratePopUp;
5692 else if (sender == fAudLang2PopUp)
5694 mixdownPopUp = fAudTrack2MixPopUp;
5695 audiocodecPopUp = fAudTrack2CodecPopUp;
5696 sampleratePopUp = fAudTrack2RatePopUp;
5697 bitratePopUp = fAudTrack2BitratePopUp;
5699 else if (sender == fAudLang3PopUp)
5701 mixdownPopUp = fAudTrack3MixPopUp;
5702 audiocodecPopUp = fAudTrack3CodecPopUp;
5703 sampleratePopUp = fAudTrack3RatePopUp;
5704 bitratePopUp = fAudTrack3BitratePopUp;
5708 mixdownPopUp = fAudTrack4MixPopUp;
5709 audiocodecPopUp = fAudTrack4CodecPopUp;
5710 sampleratePopUp = fAudTrack4RatePopUp;
5711 bitratePopUp = fAudTrack4BitratePopUp;
5714 /* get the index of the selected audio Track*/
5715 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5717 /* pointer for the hb_audio_s struct we will use later on */
5718 hb_audio_config_t * audio;
5721 /* check if the audio mixdown controls need their enabled state changing */
5722 [self setEnabledStateOfAudioMixdownControls:nil];
5724 if (thisAudioIndex != -1)
5728 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5730 /* actually manipulate the proper mixdowns here */
5731 /* delete the previous audio mixdown options */
5732 [mixdownPopUp removeAllItems];
5734 acodec = [[audiocodecPopUp selectedItem] tag];
5739 /* find out if our selected output audio codec supports mono and / or 6ch */
5740 /* we also check for an input codec of AC3 or DCA,
5741 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5742 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5743 but this may change in the future, so they are separated for flexibility */
5744 int audioCodecsSupportMono =
5745 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5746 (acodec != HB_ACODEC_LAME);
5747 int audioCodecsSupport6Ch =
5748 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5749 (acodec != HB_ACODEC_LAME);
5751 /* check for AC-3 passthru */
5752 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5755 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5756 [NSString stringWithUTF8String: "AC3 Passthru"]
5757 action: NULL keyEquivalent: @""];
5758 [menuItem setTag: HB_ACODEC_AC3];
5760 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5762 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5763 [NSString stringWithUTF8String: "DTS Passthru"]
5764 action: NULL keyEquivalent: @""];
5765 [menuItem setTag: HB_ACODEC_DCA];
5770 /* add the appropriate audio mixdown menuitems to the popupbutton */
5771 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5772 so that we can reference the mixdown later */
5774 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5775 int minMixdownUsed = 0;
5776 int maxMixdownUsed = 0;
5778 /* get the input channel layout without any lfe channels */
5779 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5781 /* do we want to add a mono option? */
5782 if (audioCodecsSupportMono == 1)
5784 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5785 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5786 action: NULL keyEquivalent: @""];
5787 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5788 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5789 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5792 /* do we want to add a stereo option? */
5793 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5794 /* also offer stereo if we have a stereo-or-better source */
5795 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5797 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5798 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5799 action: NULL keyEquivalent: @""];
5800 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5801 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5802 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5805 /* do we want to add a dolby surround (DPL1) option? */
5806 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5808 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5809 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5810 action: NULL keyEquivalent: @""];
5811 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5812 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5813 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5816 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5817 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5819 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5820 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5821 action: NULL keyEquivalent: @""];
5822 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5823 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5824 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5827 /* do we want to add a 6-channel discrete option? */
5828 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5830 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5831 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5832 action: NULL keyEquivalent: @""];
5833 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5834 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5835 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5838 /* do we want to add an AC-3 passthrough option? */
5839 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5841 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5842 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5843 action: NULL keyEquivalent: @""];
5844 [menuItem setTag: HB_ACODEC_AC3];
5845 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5846 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5849 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5850 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5852 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5853 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5854 action: NULL keyEquivalent: @""];
5855 [menuItem setTag: HB_ACODEC_DCA];
5856 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5857 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5860 /* auto-select the best mixdown based on our saved mixdown preference */
5862 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5863 /* ultimately this should be a prefs option */
5866 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5867 if (mixdownToUse > 0)
5869 useMixdown = mixdownToUse;
5873 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5876 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5877 if (useMixdown > maxMixdownUsed)
5879 useMixdown = maxMixdownUsed;
5882 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5883 if (useMixdown < minMixdownUsed)
5885 useMixdown = minMixdownUsed;
5888 /* select the (possibly-amended) preferred mixdown */
5889 [mixdownPopUp selectItemWithTag: useMixdown];
5892 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5893 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5895 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5897 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5900 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5901 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5903 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5905 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5908 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5909 [self audioTrackMixdownChanged: mixdownPopUp];
5913 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5915 [self autoSetM4vExtension: sender];
5919 - (IBAction) audioTrackMixdownChanged: (id) sender
5923 /* setup pointers to all of the other audio track controls
5924 * we will need later
5926 NSPopUpButton * mixdownPopUp;
5927 NSPopUpButton * sampleratePopUp;
5928 NSPopUpButton * bitratePopUp;
5929 NSPopUpButton * audiocodecPopUp;
5930 NSPopUpButton * audiotrackPopUp;
5931 NSSlider * drcSlider;
5932 NSTextField * drcField;
5933 if (sender == fAudTrack1MixPopUp)
5935 audiotrackPopUp = fAudLang1PopUp;
5936 audiocodecPopUp = fAudTrack1CodecPopUp;
5937 mixdownPopUp = fAudTrack1MixPopUp;
5938 sampleratePopUp = fAudTrack1RatePopUp;
5939 bitratePopUp = fAudTrack1BitratePopUp;
5940 drcSlider = fAudTrack1DrcSlider;
5941 drcField = fAudTrack1DrcField;
5943 else if (sender == fAudTrack2MixPopUp)
5945 audiotrackPopUp = fAudLang2PopUp;
5946 audiocodecPopUp = fAudTrack2CodecPopUp;
5947 mixdownPopUp = fAudTrack2MixPopUp;
5948 sampleratePopUp = fAudTrack2RatePopUp;
5949 bitratePopUp = fAudTrack2BitratePopUp;
5950 drcSlider = fAudTrack2DrcSlider;
5951 drcField = fAudTrack2DrcField;
5953 else if (sender == fAudTrack3MixPopUp)
5955 audiotrackPopUp = fAudLang3PopUp;
5956 audiocodecPopUp = fAudTrack3CodecPopUp;
5957 mixdownPopUp = fAudTrack3MixPopUp;
5958 sampleratePopUp = fAudTrack3RatePopUp;
5959 bitratePopUp = fAudTrack3BitratePopUp;
5960 drcSlider = fAudTrack3DrcSlider;
5961 drcField = fAudTrack3DrcField;
5965 audiotrackPopUp = fAudLang4PopUp;
5966 audiocodecPopUp = fAudTrack4CodecPopUp;
5967 mixdownPopUp = fAudTrack4MixPopUp;
5968 sampleratePopUp = fAudTrack4RatePopUp;
5969 bitratePopUp = fAudTrack4BitratePopUp;
5970 drcSlider = fAudTrack4DrcSlider;
5971 drcField = fAudTrack4DrcField;
5973 acodec = [[audiocodecPopUp selectedItem] tag];
5974 /* storage variable for the min and max bitrate allowed for this codec */
5980 case HB_ACODEC_FAAC:
5981 /* check if we have a 6ch discrete conversion in either audio track */
5982 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5984 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5986 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
5992 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5994 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5995 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
6000 case HB_ACODEC_CA_AAC:
6001 /* check if we have a 6ch discrete conversion in either audio track */
6002 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6015 case HB_ACODEC_LAME:
6016 /* Lame is happy using our min bitrate of 32 kbps */
6018 /* Lame won't encode if the bitrate is higher than 320 kbps */
6022 case HB_ACODEC_VORBIS:
6023 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6025 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
6027 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
6033 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
6035 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
6041 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
6047 /* make sure we have a selected title before continuing */
6048 if (fTitle == NULL) return;
6049 /* get the audio so we can find out what input rates are*/
6050 hb_audio_config_t * audio;
6051 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
6052 int inputbitrate = audio->in.bitrate / 1000;
6053 int inputsamplerate = audio->in.samplerate;
6055 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
6057 [bitratePopUp removeAllItems];
6059 for( int i = 0; i < hb_audio_bitrates_count; i++ )
6061 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
6063 /* add a new menuitem for this bitrate */
6064 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6065 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
6066 action: NULL keyEquivalent: @""];
6067 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
6068 [menuItem setTag: hb_audio_bitrates[i].rate];
6072 /* select the default bitrate (but use 384 for 6-ch AAC) */
6073 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
6075 [bitratePopUp selectItemWithTag: 384];
6079 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6082 /* populate and set the sample rate popup */
6083 /* Audio samplerate */
6084 [sampleratePopUp removeAllItems];
6085 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6086 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6087 [menuItem setTag: inputsamplerate];
6089 for( int i = 0; i < hb_audio_rates_count; i++ )
6091 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6092 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6093 action: NULL keyEquivalent: @""];
6094 [menuItem setTag: hb_audio_rates[i].rate];
6096 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6097 * and there is no compelling reason to use anything else as default, though the users default
6098 * preset will likely override any setting chosen here.
6100 [sampleratePopUp selectItemWithTag: inputsamplerate];
6103 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6104 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6105 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6107 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6110 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6111 [bitratePopUp removeAllItems];
6112 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6113 [NSString stringWithFormat:@"%d", inputbitrate]
6114 action: NULL keyEquivalent: @""];
6115 [menuItem setTag: inputbitrate];
6116 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6117 [bitratePopUp setEnabled: NO];
6118 [sampleratePopUp setEnabled: NO];
6120 [drcSlider setFloatValue: 0.00];
6121 [self audioDRCSliderChanged: drcSlider];
6122 [drcSlider setEnabled: NO];
6123 [drcField setEnabled: NO];
6127 [sampleratePopUp setEnabled: YES];
6128 [bitratePopUp setEnabled: YES];
6129 [drcSlider setEnabled: YES];
6130 [drcField setEnabled: YES];
6132 [self calculateBitrate:nil];
6135 - (IBAction) audioDRCSliderChanged: (id) sender
6137 NSSlider * drcSlider;
6138 NSTextField * drcField;
6139 if (sender == fAudTrack1DrcSlider)
6141 drcSlider = fAudTrack1DrcSlider;
6142 drcField = fAudTrack1DrcField;
6144 else if (sender == fAudTrack2DrcSlider)
6146 drcSlider = fAudTrack2DrcSlider;
6147 drcField = fAudTrack2DrcField;
6149 else if (sender == fAudTrack3DrcSlider)
6151 drcSlider = fAudTrack3DrcSlider;
6152 drcField = fAudTrack3DrcField;
6156 drcSlider = fAudTrack4DrcSlider;
6157 drcField = fAudTrack4DrcField;
6160 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6161 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6163 [drcSlider setFloatValue:1.0];
6167 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6168 /* For now, do not call this until we have an intelligent way to determine audio track selections
6169 * compared to presets
6171 //[self customSettingUsed: sender];
6176 - (IBAction) browseImportSrtFile: (id) sender
6179 NSOpenPanel * panel;
6181 panel = [NSOpenPanel openPanel];
6182 [panel setAllowsMultipleSelection: NO];
6183 [panel setCanChooseFiles: YES];
6184 [panel setCanChooseDirectories: NO ];
6185 NSString * sourceDirectory;
6186 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6188 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6192 sourceDirectory = @"~/Desktop";
6193 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6195 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6196 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6197 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6198 modalForWindow: fWindow modalDelegate: self
6199 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6200 contextInfo: sender];
6203 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6204 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6206 if( returnCode == NSOKButton )
6208 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6209 NSString *importSrtFilePath = [sheet filename];
6210 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6212 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6213 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6215 [fSubtitlesTable reloadData];
6221 #pragma mark Open New Windows
6223 - (IBAction) openHomepage: (id) sender
6225 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6226 URLWithString:@"http://handbrake.fr/"]];
6229 - (IBAction) openForums: (id) sender
6231 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6232 URLWithString:@"http://handbrake.fr/forum/"]];
6234 - (IBAction) openUserGuide: (id) sender
6236 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6237 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6241 * Shows debug output window.
6243 - (IBAction)showDebugOutputPanel:(id)sender
6245 [outputPanel showOutputPanel:sender];
6249 * Shows preferences window.
6251 - (IBAction) showPreferencesWindow: (id) sender
6253 NSWindow * window = [fPreferencesController window];
6254 if (![window isVisible])
6257 [window makeKeyAndOrderFront: nil];
6261 * Shows queue window.
6263 - (IBAction) showQueueWindow:(id)sender
6265 [fQueueController showQueueWindow:sender];
6269 - (IBAction) toggleDrawer:(id)sender {
6270 [fPresetDrawer toggle:self];
6274 * Shows Picture Settings Window.
6277 - (IBAction) showPicturePanel: (id) sender
6279 [fPictureController showPictureWindow:sender];
6282 - (void) picturePanelFullScreen
6284 [fPictureController setToFullScreenMode];
6287 - (void) picturePanelWindowed
6289 [fPictureController setToWindowedMode];
6292 - (IBAction) showPreviewWindow: (id) sender
6294 [fPictureController showPreviewWindow:sender];
6298 #pragma mark Preset Outline View Methods
6299 #pragma mark - Required
6300 /* These are required by the NSOutlineView Datasource Delegate */
6303 /* used to specify the number of levels to show for each item */
6304 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6306 /* currently use no levels to test outline view viability */
6307 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6309 return [UserPresets count];
6313 /* we need to return the count of the array in ChildrenArray for this folder */
6314 NSArray *children = nil;
6315 children = [item objectForKey:@"ChildrenArray"];
6316 if ([children count] > 0)
6318 return [children count];
6327 /* We use this to deterimine children of an item */
6328 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6331 /* we need to return the count of the array in ChildrenArray for this folder */
6332 NSArray *children = nil;
6335 children = UserPresets;
6339 if ([item objectForKey:@"ChildrenArray"])
6341 children = [item objectForKey:@"ChildrenArray"];
6344 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6350 return [children objectAtIndex:index];
6354 // We are only one level deep, so we can't be asked about children
6355 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6359 /* We use this to determine if an item should be expandable */
6360 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6363 /* we need to return the count of the array in ChildrenArray for this folder */
6364 NSArray *children= nil;
6367 children = UserPresets;
6371 if ([item objectForKey:@"ChildrenArray"])
6373 children = [item objectForKey:@"ChildrenArray"];
6377 /* To deterimine if an item should show a disclosure triangle
6378 * we could do it by the children count as so:
6379 * if ([children count] < 1)
6380 * However, lets leave the triangle show even if there are no
6381 * children to help indicate a folder, just like folder in the
6382 * finder can show a disclosure triangle even when empty
6385 /* We need to determine if the item is a folder */
6386 if ([[item objectForKey:@"Folder"] intValue] == 1)
6397 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6399 // Our outline view has no levels, but we can still expand every item. Doing so
6400 // just makes the row taller. See heightOfRowByItem below.
6401 //return ![(HBQueueOutlineView*)outlineView isDragging];
6407 /* Used to tell the outline view which information is to be displayed per item */
6408 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6410 /* We have two columns right now, icon and PresetName */
6412 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6414 return [item objectForKey:@"PresetName"];
6423 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6425 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6427 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6429 return [NSKeyedArchiver archivedDataWithRootObject:item];
6432 #pragma mark - Added Functionality (optional)
6433 /* Use to customize the font and display characteristics of the title cell */
6434 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6436 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6440 NSColor *shadowColor;
6441 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6442 /*check to see if its a selected row */
6443 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6446 fontColor = [NSColor blackColor];
6447 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6451 if ([[item objectForKey:@"Type"] intValue] == 0)
6453 fontColor = [NSColor blueColor];
6455 else // User created preset, use a black font
6457 fontColor = [NSColor blackColor];
6459 /* check to see if its a folder */
6460 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6462 //fontColor = [NSColor greenColor];
6467 /* We use Bold Text for the HB Default */
6468 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6470 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6472 /* We use Bold Text for the User Specified Default */
6473 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6475 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6479 [cell setTextColor:fontColor];
6480 [cell setFont:txtFont];
6485 /* We use this to edit the name field in the outline view */
6486 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6488 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6493 [theRecord setObject:object forKey:@"PresetName"];
6497 [fPresetsOutlineView reloadData];
6498 /* We save all of the preset data here */
6502 /* We use this to provide tooltips for the items in the presets outline view */
6503 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6505 //if ([[tc identifier] isEqualToString:@"PresetName"])
6507 /* initialize the tooltip contents variable */
6509 /* if there is a description for the preset, we show it in the tooltip */
6510 if ([item objectForKey:@"PresetDescription"])
6512 loc_tip = [item objectForKey:@"PresetDescription"];
6517 loc_tip = @"No description available";
6524 #pragma mark Preset Outline View Methods (dragging related)
6527 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6529 // Dragging is only allowed for custom presets.
6530 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6531 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6535 // Don't retain since this is just holding temporaral drag information, and it is
6536 //only used during a drag! We could put this in the pboard actually.
6537 fDraggedNodes = items;
6538 // Provide data for our custom type, and simple NSStrings.
6539 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6541 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6542 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6547 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6550 // Don't allow dropping ONTO an item since they can't really contain any children.
6552 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6553 if (isOnDropTypeProposal)
6554 return NSDragOperationNone;
6556 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6559 index = [fPresetsOutlineView rowForItem: item] + 1;
6563 // Don't allow dropping into the Built In Presets.
6564 if (index < presetCurrentBuiltInCount)
6566 return NSDragOperationNone;
6567 index = MAX (index, presetCurrentBuiltInCount);
6570 [outlineView setDropItem:item dropChildIndex:index];
6571 return NSDragOperationGeneric;
6576 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6578 /* first, lets see if we are dropping into a folder */
6579 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6581 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6582 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6583 [childrenArray addObject:item];
6584 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6585 [childrenArray autorelease];
6587 else // We are not, so we just move the preset into the existing array
6589 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6591 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6592 while (obj = [enumerator nextObject])
6594 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6596 // Successful drop, lets rearrange the view and save it all
6597 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6599 [fPresetsOutlineView reloadData];
6604 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6606 NSUInteger index = [indexSet lastIndex];
6607 NSUInteger aboveInsertIndexCount = 0;
6609 NSUInteger removeIndex;
6611 if (index >= insertIndex)
6613 removeIndex = index + aboveInsertIndexCount;
6614 aboveInsertIndexCount++;
6618 removeIndex = index;
6622 id object = [[array objectAtIndex:removeIndex] retain];
6623 [array removeObjectAtIndex:removeIndex];
6624 [array insertObject:object atIndex:insertIndex];
6627 index = [indexSet indexLessThanIndex:index];
6632 #pragma mark - Functional Preset NSOutlineView Methods
6634 - (IBAction)selectPreset:(id)sender
6637 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6639 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6640 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6642 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6644 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6648 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6652 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6653 [self formatPopUpChanged:nil];
6655 /* Chapter Markers*/
6656 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6657 /* check to see if we have only one chapter */
6658 [self chapterPopUpChanged:nil];
6660 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6661 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6662 /* Mux mp4 with http optimization */
6663 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6666 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6667 /* We set the advanced opt string here if applicable*/
6668 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6670 /* Lets run through the following functions to get variables set there */
6671 [self videoEncoderPopUpChanged:nil];
6672 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6673 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6674 [self calculateBitrate:nil];
6677 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6679 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6680 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6682 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6683 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6684 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6685 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6686 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6687 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6689 /* For the quality slider we need to convert the old percent's to the new rf scales */
6690 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6691 [fVidQualitySlider setFloatValue:rf];
6696 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6697 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6699 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6703 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6704 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6708 [self videoMatrixChanged:nil];
6710 /* Video framerate */
6711 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6712 detected framerate in the fVidRatePopUp so we use index 0*/
6713 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6715 [fVidRatePopUp selectItemAtIndex: 0];
6719 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6723 /* 2 Pass Encoding */
6724 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6725 [self twoPassCheckboxChanged:nil];
6727 /* Turbo 1st pass for 2 Pass Encoding */
6728 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6731 /* First we check to see if we are using the current audio track layout based on AudioList array */
6732 if ([chosenPreset objectForKey:@"AudioList"])
6735 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6736 NSPopUpButton * trackLangPopUp = nil;
6737 NSPopUpButton * mixdownPopUp = nil;
6738 NSPopUpButton * audiocodecPopUp = nil;
6739 NSPopUpButton * sampleratePopUp = nil;
6740 NSPopUpButton * bitratePopUp = nil;
6741 NSSlider * drcSlider = nil;
6744 /* Populate the audio widgets based on the contents of the AudioList array */
6746 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6748 while (tempObject = [enumerator nextObject])
6753 trackLangPopUp = fAudLang1PopUp;
6754 mixdownPopUp = fAudTrack1MixPopUp;
6755 audiocodecPopUp = fAudTrack1CodecPopUp;
6756 sampleratePopUp = fAudTrack1RatePopUp;
6757 bitratePopUp = fAudTrack1BitratePopUp;
6758 drcSlider = fAudTrack1DrcSlider;
6762 trackLangPopUp = fAudLang2PopUp;
6763 mixdownPopUp = fAudTrack2MixPopUp;
6764 audiocodecPopUp = fAudTrack2CodecPopUp;
6765 sampleratePopUp = fAudTrack2RatePopUp;
6766 bitratePopUp = fAudTrack2BitratePopUp;
6767 drcSlider = fAudTrack2DrcSlider;
6771 trackLangPopUp = fAudLang3PopUp;
6772 mixdownPopUp = fAudTrack3MixPopUp;
6773 audiocodecPopUp = fAudTrack3CodecPopUp;
6774 sampleratePopUp = fAudTrack3RatePopUp;
6775 bitratePopUp = fAudTrack3BitratePopUp;
6776 drcSlider = fAudTrack3DrcSlider;
6780 trackLangPopUp = fAudLang4PopUp;
6781 mixdownPopUp = fAudTrack4MixPopUp;
6782 audiocodecPopUp = fAudTrack4CodecPopUp;
6783 sampleratePopUp = fAudTrack4RatePopUp;
6784 bitratePopUp = fAudTrack4BitratePopUp;
6785 drcSlider = fAudTrack4DrcSlider;
6789 if ([trackLangPopUp indexOfSelectedItem] == 0)
6791 [trackLangPopUp selectItemAtIndex: 1];
6793 [self audioTrackPopUpChanged: trackLangPopUp];
6794 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6795 /* check our pref for core audio and use it in place of faac if preset is a built in */
6796 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6797 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6798 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6800 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6803 [self audioTrackPopUpChanged: audiocodecPopUp];
6804 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6805 [self audioTrackMixdownChanged: mixdownPopUp];
6806 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6808 if ([mixdownPopUp selectedItem] == nil)
6810 [self audioTrackPopUpChanged: audiocodecPopUp];
6811 [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6813 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6814 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6815 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6817 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6818 /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6819 *default mixdown bitrate*/
6820 if ([bitratePopUp selectedItem] == nil)
6822 [self audioTrackMixdownChanged: mixdownPopUp];
6825 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6826 [self audioDRCSliderChanged: drcSlider];
6829 /* 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,
6830 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6834 /* 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". */
6835 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6837 hb_audio_config_t * audio;
6838 /* get the audio source audio codec */
6839 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6840 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6841 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6843 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6844 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6846 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6848 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6850 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6852 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6853 [trackLangPopUp selectItemAtIndex: 0];
6854 [self audioTrackPopUpChanged: trackLangPopUp];
6860 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6864 [fAudLang4PopUp selectItemAtIndex: 0];
6865 [self audioTrackPopUpChanged: fAudLang4PopUp];
6869 [fAudLang3PopUp selectItemAtIndex: 0];
6870 [self audioTrackPopUpChanged: fAudLang3PopUp];
6874 [fAudLang2PopUp selectItemAtIndex: 0];
6875 [self audioTrackPopUpChanged: fAudLang2PopUp];
6883 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6885 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6887 [fAudLang1PopUp selectItemAtIndex: 1];
6889 [self audioTrackPopUpChanged: fAudLang1PopUp];
6890 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6891 /* check our pref for core audio and use it in place of faac if preset is built in */
6892 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6893 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6894 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6896 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6899 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6900 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6901 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6903 if ([fAudTrack1MixPopUp selectedItem] == nil)
6905 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6907 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6908 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6909 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6911 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6913 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6914 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6917 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6919 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6921 [fAudLang2PopUp selectItemAtIndex: 1];
6923 [self audioTrackPopUpChanged: fAudLang2PopUp];
6924 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6925 /* check our pref for core audio and use it in place of faac if preset is built in */
6926 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6927 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6928 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6930 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6932 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6933 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6934 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6936 if ([fAudTrack2MixPopUp selectedItem] == nil)
6938 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6940 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6941 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6942 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6944 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6946 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6947 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6949 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6951 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6953 [fAudLang3PopUp selectItemAtIndex: 1];
6955 [self audioTrackPopUpChanged: fAudLang3PopUp];
6956 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6957 /* check our pref for core audio and use it in place of faac if preset is built in */
6958 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6959 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6960 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6962 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6964 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6965 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6966 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6968 if ([fAudTrack3MixPopUp selectedItem] == nil)
6970 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6972 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6973 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6974 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6976 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6978 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6979 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6981 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6983 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6985 [fAudLang4PopUp selectItemAtIndex: 1];
6987 [self audioTrackPopUpChanged: fAudLang4PopUp];
6988 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6989 /* check our pref for core audio and use it in place of faac if preset is built in */
6990 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6991 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6992 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6994 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6996 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6997 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6998 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
7000 if ([fAudTrack4MixPopUp selectedItem] == nil)
7002 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
7004 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
7005 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
7006 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
7008 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
7010 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
7011 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
7014 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
7016 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
7018 [fAudLang2PopUp selectItemAtIndex: 0];
7019 [self audioTrackPopUpChanged: fAudLang2PopUp];
7021 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
7023 [fAudLang3PopUp selectItemAtIndex: 0];
7024 [self audioTrackPopUpChanged: fAudLang3PopUp];
7026 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
7028 [fAudLang4PopUp selectItemAtIndex: 0];
7029 [self audioTrackPopUpChanged: fAudLang4PopUp];
7034 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
7035 /* Forced Subtitles */
7036 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
7038 /* Picture Settings */
7039 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
7040 * height, width, keep ar, anamorphic and crop settings.
7041 * picture filters are handled separately below.
7043 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
7044 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
7045 * preset completely ignores any picture sizing values in the preset.
7047 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
7049 hb_job_t * job = fTitle->job;
7051 /* If Cropping is set to custom, then recall all four crop values from
7052 when the preset was created and apply them */
7053 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
7055 [fPictureController setAutoCrop:NO];
7057 /* Here we use the custom crop values saved at the time the preset was saved */
7058 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
7059 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
7060 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
7061 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
7064 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7066 [fPictureController setAutoCrop:YES];
7067 /* Here we use the auto crop values determined right after scan */
7068 job->crop[0] = AutoCropTop;
7069 job->crop[1] = AutoCropBottom;
7070 job->crop[2] = AutoCropLeft;
7071 job->crop[3] = AutoCropRight;
7076 if ([chosenPreset objectForKey:@"PictureModulus"])
7078 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
7085 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7086 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
7088 /* Use Max Picture settings for whatever the dvd is.*/
7089 [self revertPictureSizeToMax:nil];
7090 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7091 if (job->keep_ratio == 1)
7093 hb_fix_aspect( job, HB_KEEP_WIDTH );
7094 if( job->height > fTitle->height )
7096 job->height = fTitle->height;
7097 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7100 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7102 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7104 /* we check to make sure the presets width/height does not exceed the sources width/height */
7105 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
7107 /* if so, then we use the sources height and width to avoid scaling up */
7108 //job->width = fTitle->width;
7109 //job->height = fTitle->height;
7110 [self revertPictureSizeToMax:nil];
7112 else // source width/height is >= the preset height/width
7114 /* we can go ahead and use the presets values for height and width */
7115 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
7116 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
7118 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7119 if (job->keep_ratio == 1)
7121 hb_fix_aspect( job, HB_KEEP_WIDTH );
7122 if( job->height > fTitle->height )
7124 job->height = fTitle->height;
7125 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7128 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7134 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7135 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7139 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7140 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7141 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7144 [fPictureController setUseDecomb:1];
7145 [fPictureController setDecomb:0];
7146 [fPictureController setDeinterlace:0];
7147 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7149 /* we are using decomb */
7151 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7153 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7155 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7156 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7158 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7164 /* We are using Deinterlace */
7166 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7168 [fPictureController setUseDecomb:0];
7169 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7170 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7171 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7173 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7180 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7182 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7183 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7184 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7186 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7191 [fPictureController setDetelecine:0];
7195 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7197 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7198 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7199 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7201 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7206 [fPictureController setDenoise:0];
7210 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7212 /* if its a one, then its the old on/off deblock, set on to 5*/
7213 [fPictureController setDeblock:5];
7217 /* use the settings intValue */
7218 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7221 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7223 [fPictureController setGrayscale:1];
7227 [fPictureController setGrayscale:0];
7230 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7231 [fPictureController SetTitle:fTitle];
7232 [fPictureController SetTitle:fTitle];
7233 [self calculatePictureSizing:nil];
7239 #pragma mark Manage Presets
7241 - (void) loadPresets {
7242 /* We declare the default NSFileManager into fileManager */
7243 NSFileManager * fileManager = [NSFileManager defaultManager];
7244 /*We define the location of the user presets file */
7245 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7246 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7247 /* We check for the presets.plist */
7248 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7250 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7253 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7254 if (nil == UserPresets)
7256 UserPresets = [[NSMutableArray alloc] init];
7257 [self addFactoryPresets:nil];
7259 [fPresetsOutlineView reloadData];
7261 [self checkBuiltInsForUpdates];
7264 - (void) checkBuiltInsForUpdates {
7266 BOOL updateBuiltInPresets = NO;
7268 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7270 while (tempObject = [enumerator nextObject])
7272 /* iterate through the built in presets to see if any have an old build number */
7273 NSMutableDictionary *thisPresetDict = tempObject;
7274 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7275 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7277 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7279 updateBuiltInPresets = YES;
7284 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7285 if ( updateBuiltInPresets == YES)
7287 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7289 /* Show an alert window that built in presets will be updated */
7290 /*On Screen Notification*/
7293 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7294 [NSApp requestUserAttention:NSCriticalRequest];
7296 /* when alert is dismissed, go ahead and update the built in presets */
7297 [self addFactoryPresets:nil];
7303 - (IBAction) showAddPresetPanel: (id) sender
7305 /* Deselect the currently selected Preset if there is one*/
7306 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7308 /* Populate the preset picture settings popup here */
7309 [fPresetNewPicSettingsPopUp removeAllItems];
7310 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7311 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7312 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7313 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7314 /* Uncheck the preset use filters checkbox */
7315 [fPresetNewPicFiltersCheck setState:NSOffState];
7316 // fPresetNewFolderCheck
7317 [fPresetNewFolderCheck setState:NSOffState];
7318 /* Erase info from the input fields*/
7319 [fPresetNewName setStringValue: @""];
7320 [fPresetNewDesc setStringValue: @""];
7321 /* Show the panel */
7322 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7325 - (IBAction) closeAddPresetPanel: (id) sender
7327 [NSApp endSheet: fAddPresetPanel];
7328 [fAddPresetPanel orderOut: self];
7331 - (IBAction)addUserPreset:(id)sender
7333 if (![[fPresetNewName stringValue] length])
7334 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7337 /* Here we create a custom user preset */
7338 [UserPresets addObject:[self createPreset]];
7341 [self closeAddPresetPanel:nil];
7348 /* We Reload the New Table data for presets */
7349 [fPresetsOutlineView reloadData];
7350 /* We save all of the preset data here */
7358 /* We Sort the Presets By Factory or Custom */
7359 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7360 ascending:YES] autorelease];
7361 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7363 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7364 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7365 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7368 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7369 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7370 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7371 [UserPresets setArray:sortedArray];
7376 - (IBAction)insertPreset:(id)sender
7378 int index = [fPresetsOutlineView selectedRow];
7379 [UserPresets insertObject:[self createPreset] atIndex:index];
7380 [fPresetsOutlineView reloadData];
7384 - (NSDictionary *)createPreset
7386 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7387 /* Preset build number */
7388 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7389 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7390 /* Get the New Preset Name from the field in the AddPresetPanel */
7391 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7392 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7393 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7394 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7395 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7396 /*Set whether or not this is default, at creation set to 0*/
7397 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7398 if ([fPresetNewFolderCheck state] == YES)
7400 /* initialize and set an empty array for children here since we are a new folder */
7401 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7402 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7403 [childrenArray autorelease];
7405 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7407 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7408 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7409 /* Get whether or not to use the current Picture Filter settings for the preset */
7410 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7412 /* Get New Preset Description from the field in the AddPresetPanel*/
7413 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7415 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7416 /* Chapter Markers fCreateChapterMarkers*/
7417 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7418 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7419 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7420 /* Mux mp4 with http optimization */
7421 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7422 /* Add iPod uuid atom */
7423 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7427 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7428 /* x264 Option String */
7429 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7431 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7432 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7433 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7434 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7436 /* Video framerate */
7437 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7439 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7441 else // we can record the actual titleOfSelectedItem
7443 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7446 /* 2 Pass Encoding */
7447 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7448 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7449 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7450 /*Picture Settings*/
7451 hb_job_t * job = fTitle->job;
7452 /* Picture Sizing */
7453 /* Use Max Picture settings for whatever the dvd is.*/
7454 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7455 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7456 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7457 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7458 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7459 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7461 /* Set crop settings here */
7462 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7463 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7464 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7465 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7466 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7468 /* Picture Filters */
7469 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7470 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7471 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7472 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7473 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7474 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7475 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7476 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7477 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7478 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7479 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7482 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7483 /* we actually call the methods for the nests here */
7484 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7486 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7487 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7488 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7489 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7490 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7491 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7492 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7493 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7494 [audioTrack1Array autorelease];
7495 [audioListArray addObject:audioTrack1Array];
7498 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7500 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7501 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7502 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7503 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7504 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7505 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7506 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7507 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7508 [audioTrack2Array autorelease];
7509 [audioListArray addObject:audioTrack2Array];
7512 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7514 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7515 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7516 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7517 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7518 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7519 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7520 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7521 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7522 [audioTrack3Array autorelease];
7523 [audioListArray addObject:audioTrack3Array];
7526 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7528 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7529 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7530 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7531 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7532 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7533 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7534 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7535 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7536 [audioTrack4Array autorelease];
7537 [audioListArray addObject:audioTrack4Array];
7541 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7544 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7545 * subititle array code. */
7547 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7548 /* Forced Subtitles */
7549 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7551 [preset autorelease];
7558 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7559 /* We get the default preset in case it changed */
7560 [self getDefaultPresets:nil];
7564 - (IBAction)deletePreset:(id)sender
7568 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7572 /* Alert user before deleting preset */
7574 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7576 if ( status == NSAlertDefaultReturn )
7578 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7579 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7580 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7582 NSEnumerator *enumerator;
7583 NSMutableArray *presetsArrayToMod;
7584 NSMutableArray *tempArray;
7586 /* If we are a root level preset, we are modding the UserPresets array */
7587 if (presetToModLevel == 0)
7589 presetsArrayToMod = UserPresets;
7591 else // We have a parent preset, so we modify the chidren array object for key
7593 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7596 enumerator = [presetsArrayToMod objectEnumerator];
7597 tempArray = [NSMutableArray array];
7599 while (tempObject = [enumerator nextObject])
7601 NSDictionary *thisPresetDict = tempObject;
7602 if (thisPresetDict == presetToMod)
7604 [tempArray addObject:tempObject];
7608 [presetsArrayToMod removeObjectsInArray:tempArray];
7609 [fPresetsOutlineView reloadData];
7616 #pragma mark Import Export Preset(s)
7618 - (IBAction) browseExportPresetFile: (id) sender
7620 /* Open a panel to let the user choose where and how to save the export file */
7621 NSSavePanel * panel = [NSSavePanel savePanel];
7622 /* We get the current file name and path from the destination field here */
7623 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7625 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7626 modalForWindow: fWindow modalDelegate: self
7627 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7631 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7632 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7634 if( returnCode == NSOKButton )
7636 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7637 NSString *exportPresetsFile = [sheet filename];
7638 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7639 /* We check for the presets.plist */
7640 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7642 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7644 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7645 if (nil == presetsToExport)
7647 presetsToExport = [[NSMutableArray alloc] init];
7649 /* now get and add selected presets to export */
7652 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7654 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7655 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7663 - (IBAction) browseImportPresetFile: (id) sender
7666 NSOpenPanel * panel;
7668 panel = [NSOpenPanel openPanel];
7669 [panel setAllowsMultipleSelection: NO];
7670 [panel setCanChooseFiles: YES];
7671 [panel setCanChooseDirectories: NO ];
7672 NSString * sourceDirectory;
7673 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7675 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7679 sourceDirectory = @"~/Desktop";
7680 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7682 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7683 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7685 /* set this for allowed file types, not sure if we should allow xml or not */
7686 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7687 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7688 modalForWindow: fWindow modalDelegate: self
7689 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7690 contextInfo: sender];
7693 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7694 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7696 if( returnCode == NSOKButton )
7698 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7699 NSString *importPresetsFile = [sheet filename];
7700 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7701 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7702 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7703 /* iterate though the new array of presets to import and add them to our presets array */
7705 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7707 while (tempObject = [enumerator nextObject])
7709 /* make any changes to the incoming preset we see fit */
7710 /* make sure the incoming preset is not tagged as default */
7711 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7712 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7713 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7714 [tempObject setObject:prependedName forKey:@"PresetName"];
7716 /* actually add the new preset to our presets array */
7717 [UserPresets addObject:tempObject];
7720 [presetsToImport autorelease];
7728 #pragma mark Manage Default Preset
7730 - (IBAction)getDefaultPresets:(id)sender
7732 presetHbDefault = nil;
7733 presetUserDefault = nil;
7734 presetUserDefaultParent = nil;
7735 presetUserDefaultParentParent = nil;
7736 NSMutableDictionary *presetHbDefaultParent = nil;
7737 NSMutableDictionary *presetHbDefaultParentParent = nil;
7740 BOOL userDefaultFound = NO;
7741 presetCurrentBuiltInCount = 0;
7742 /* First we iterate through the root UserPresets array to check for defaults */
7743 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7745 while (tempObject = [enumerator nextObject])
7747 NSMutableDictionary *thisPresetDict = tempObject;
7748 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7750 presetHbDefault = thisPresetDict;
7752 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7754 presetUserDefault = thisPresetDict;
7755 userDefaultFound = YES;
7757 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7759 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7763 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7764 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7766 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7767 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7769 while (tempObject = [enumerator nextObject])
7771 NSMutableDictionary *thisPresetDict = tempObject;
7772 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7774 presetHbDefault = thisPresetDict;
7775 presetHbDefaultParent = thisPresetDictParent;
7777 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7779 presetUserDefault = thisPresetDict;
7780 presetUserDefaultParent = thisPresetDictParent;
7781 userDefaultFound = YES;
7784 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7785 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7787 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7788 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7790 while (tempObject = [enumerator nextObject])
7792 NSMutableDictionary *thisPresetDict = tempObject;
7793 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7795 presetHbDefault = thisPresetDict;
7796 presetHbDefaultParent = thisPresetDictParent;
7797 presetHbDefaultParentParent = thisPresetDictParentParent;
7799 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7801 presetUserDefault = thisPresetDict;
7802 presetUserDefaultParent = thisPresetDictParent;
7803 presetUserDefaultParentParent = thisPresetDictParentParent;
7804 userDefaultFound = YES;
7813 /* check to see if a user specified preset was found, if not then assign the parents for
7814 * the presetHbDefault so that we can open the parents for the nested presets
7816 if (userDefaultFound == NO)
7818 presetUserDefaultParent = presetHbDefaultParent;
7819 presetUserDefaultParentParent = presetHbDefaultParentParent;
7823 - (IBAction)setDefaultPreset:(id)sender
7825 /* We need to determine if the item is a folder */
7826 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7832 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7834 /* First make sure the old user specified default preset is removed */
7835 while (tempObject = [enumerator nextObject])
7837 NSMutableDictionary *thisPresetDict = tempObject;
7838 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7840 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7843 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7844 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7846 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7849 while (tempObject = [enumerator nextObject])
7851 NSMutableDictionary *thisPresetDict1 = tempObject;
7852 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7854 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7856 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7857 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7859 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7862 while (tempObject = [enumerator nextObject])
7864 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7866 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7879 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7880 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7881 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7884 NSMutableArray *presetsArrayToMod;
7885 NSMutableArray *tempArray;
7887 /* If we are a root level preset, we are modding the UserPresets array */
7888 if (presetToModLevel == 0)
7890 presetsArrayToMod = UserPresets;
7892 else // We have a parent preset, so we modify the chidren array object for key
7894 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7897 enumerator = [presetsArrayToMod objectEnumerator];
7898 tempArray = [NSMutableArray array];
7900 while (tempObject = [enumerator nextObject])
7902 NSDictionary *thisPresetDict = tempObject;
7903 if (thisPresetDict == presetToMod)
7905 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7907 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7914 /* We save all of the preset data here */
7916 /* We Reload the New Table data for presets */
7917 [fPresetsOutlineView reloadData];
7920 - (IBAction)selectDefaultPreset:(id)sender
7922 NSMutableDictionary *presetToMod;
7923 /* if there is a user specified default, we use it */
7924 if (presetUserDefault)
7926 presetToMod = presetUserDefault;
7928 else if (presetHbDefault) //else we use the built in default presetHbDefault
7930 presetToMod = presetHbDefault;
7937 if (presetUserDefaultParent != nil)
7939 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7942 if (presetUserDefaultParentParent != nil)
7944 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7948 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7949 [self selectPreset:nil];
7954 #pragma mark Manage Built In Presets
7957 - (IBAction)deleteFactoryPresets:(id)sender
7960 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7964 NSMutableArray *tempArray;
7967 tempArray = [NSMutableArray array];
7968 /* we look here to see if the preset is we move on to the next one */
7969 while ( tempObject = [enumerator nextObject] )
7971 /* if the preset is "Factory" then we put it in the array of
7972 presets to delete */
7973 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7975 [tempArray addObject:tempObject];
7979 [UserPresets removeObjectsInArray:tempArray];
7980 [fPresetsOutlineView reloadData];
7985 /* We use this method to recreate new, updated factory presets */
7986 - (IBAction)addFactoryPresets:(id)sender
7989 /* First, we delete any existing built in presets */
7990 [self deleteFactoryPresets: sender];
7991 /* Then we generate new built in presets programmatically with fPresetsBuiltin
7992 * which is all setup in HBPresets.h and HBPresets.m*/
7993 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
7994 /* update build number for built in presets */
7995 /* iterate though the new array of presets to import and add them to our presets array */
7997 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7999 while (tempObject = [enumerator nextObject])
8001 /* Record the apps current build number in the PresetBuildNumber key */
8002 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
8004 /* Preset build number */
8005 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
8009 /* report the built in preset updating to the activity log */
8010 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
8020 /*******************************
8021 * Subclass of the HBPresetsOutlineView *
8022 *******************************/
8024 @implementation HBPresetsOutlineView
8025 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8029 // By default, NSTableView only drags an image of the first column. Change this to
8030 // drag an image of the queue's icon and PresetName columns.
8031 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8032 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8037 - (void) mouseDown:(NSEvent *)theEvent
8039 [super mouseDown:theEvent];
8045 - (BOOL) isDragging;