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 */
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 * ShowActivityIdentifier = @"Debug Output Item Identifier";
24 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
27 /*******************************
28 * HBController implementation *
29 *******************************/
30 @implementation HBController
40 [HBPreferencesController registerUserDefaults];
42 fQueueEncodeLibhb = NULL;
43 /* Check for check for the app support directory here as
44 * outputPanel needs it right away, as may other future methods
46 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
48 YES ) objectAtIndex:0];
49 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
50 stringByAppendingPathComponent:@"HandBrake"];
51 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
53 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
56 /* Check for and create the App Support Preview directory if necessary */
57 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
58 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
60 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
63 outputPanel = [[HBOutputPanelController alloc] init];
64 fPictureController = [[PictureController alloc] init];
65 fQueueController = [[HBQueueController alloc] init];
66 fAdvancedOptions = [[HBAdvancedController alloc] init];
67 /* we init the HBPresets class which currently is only used
68 * for updating built in presets, may move more functionality
71 fPresetsBuiltin = [[HBPresets alloc] init];
72 fPreferencesController = [[HBPreferencesController alloc] init];
73 /* Lets report the HandBrake version number here to the activity log and text log file */
74 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
75 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
81 - (void) applicationDidFinishLaunching: (NSNotification *) notification
83 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
84 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
85 fHandle = hb_init(loggingLevel, 0);
86 /* Optional dvd nav UseDvdNav*/
87 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
88 /* Init a separate instance of libhb for user scanning and setting up jobs */
89 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
91 // Set the Growl Delegate
92 [GrowlApplicationBridge setGrowlDelegate: self];
93 /* Init others controllers */
94 [fPictureController SetHandle: fHandle];
95 [fPictureController setHBController: self];
97 [fQueueController setHandle: fQueueEncodeLibhb];
98 [fQueueController setHBController: self];
100 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
101 [fChapterTable setDataSource:fChapterTitlesDelegate];
102 [fChapterTable setDelegate:fChapterTitlesDelegate];
104 [fPresetsOutlineView setAutosaveName:@"Presets View"];
105 [fPresetsOutlineView setAutosaveExpandedItems:YES];
107 dockIconProgress = 0;
109 /* Call UpdateUI every 1/2 sec */
110 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
111 scheduledTimerWithTimeInterval:0.5 target:self
112 selector:@selector(updateUI:) userInfo:nil repeats:YES]
113 forMode:NSDefaultRunLoopMode];
115 // Open debug output window now if it was visible when HB was closed
116 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
117 [self showDebugOutputPanel:nil];
119 // Open queue window now if it was visible when HB was closed
120 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
121 [self showQueueWindow:nil];
123 [self openMainWindow:nil];
125 /* We have to set the bool to tell hb what to do after a scan
126 * Initially we set it to NO until we start processing the queue
128 applyQueueToScan = NO;
130 /* Now we re-check the queue array to see if there are
131 * any remaining encodes to be done in it and ask the
132 * user if they want to reload the queue */
133 if ([QueueFileArray count] > 0)
135 /* run getQueueStats to see whats in the queue file */
136 [self getQueueStats];
137 /* this results in these values
138 * fEncodingQueueItem = 0;
140 * fCompletedCount = 0;
141 * fCanceledCount = 0;
145 /*On Screen Notification*/
146 NSString * alertTitle;
148 /* We check to see if there is already another instance of hb running.
149 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
151 if ([self hbInstances] > 1)
153 alertTitle = [NSString stringWithFormat:
154 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
155 NSBeginCriticalAlertSheet(
157 NSLocalizedString(@"Reload Queue", nil),
161 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
162 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
166 if (fWorkingCount > 0)
168 alertTitle = [NSString stringWithFormat:
169 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
170 fWorkingCount,fPendingCount];
174 alertTitle = [NSString stringWithFormat:
175 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
179 NSBeginCriticalAlertSheet(
181 NSLocalizedString(@"Reload Queue", nil),
183 NSLocalizedString(@"Empty Queue", nil),
185 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
186 NSLocalizedString(@" Do you want to reload them ?", nil));
189 // call didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
190 // right below to either clear the old queue or keep it loaded up.
194 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
195 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
197 [self browseSources:nil];
200 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
202 [self browseSources:(id)fOpenSourceTitleMMenu];
209 /* check to see if another instance of HandBrake.app is running */
210 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
211 NSDictionary *aDictionary;
213 for (aDictionary in runningAppDictionaries)
215 // NSLog(@"Open App: %@", [aDictionary valueForKey:@"NSApplicationName"]);
217 if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
225 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
227 if (returnCode == NSAlertOtherReturn)
229 [self clearQueueAllItems];
230 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
231 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
233 [self browseSources:nil];
236 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
238 [self browseSources:(id)fOpenSourceTitleMMenu];
243 if ([self hbInstances] == 1)
245 [self setQueueEncodingItemsAsPending];
247 [self showQueueWindow:NULL];
251 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
253 /* if we are in preview full screen mode, we need to go to
254 * windowed mode and release the display before we terminate.
255 * We do it here (instead of applicationWillTerminate) so we
256 * release the displays and can then see the alerts below.
258 if ([fPictureController previewFullScreenMode] == YES)
260 [fPictureController previewGoWindowed:nil];
264 hb_get_state( fQueueEncodeLibhb, &s );
266 if ( s.state != HB_STATE_IDLE )
268 int result = NSRunCriticalAlertPanel(
269 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
270 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
271 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
273 if (result == NSAlertDefaultReturn)
275 return NSTerminateNow;
278 return NSTerminateCancel;
281 // Warn if items still in the queue
282 else if ( fPendingCount > 0 )
284 int result = NSRunCriticalAlertPanel(
285 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
286 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
287 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
289 if ( result == NSAlertDefaultReturn )
290 return NSTerminateNow;
292 return NSTerminateCancel;
295 return NSTerminateNow;
298 - (void)applicationWillTerminate:(NSNotification *)aNotification
301 [browsedSourceDisplayName release];
302 [outputPanel release];
303 [fQueueController release];
304 [fPreviewController release];
305 [fPictureController release];
308 hb_close(&fQueueEncodeLibhb);
312 - (void) awakeFromNib
315 [fWindow setExcludedFromWindowsMenu:YES];
316 [fAdvancedOptions setView:fAdvancedView];
318 /* lets setup our presets drawer for drag and drop here */
319 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
320 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
321 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
323 /* Initialize currentScanCount so HB can use it to
324 evaluate successive scans */
325 currentScanCount = 0;
328 /* Init UserPresets .plist */
331 /* Init QueueFile .plist */
332 [self loadQueueFile];
334 fRipIndicatorShown = NO; // initially out of view in the nib
336 /* For 64 bit builds, the threaded animation in the progress
337 * indicators conflicts with the animation in the advanced tab
338 * for reasons not completely clear. jbrjake found a note in the
339 * 10.5 dev notes regarding this possiblility. It was also noted
340 * that unless specified, setUsesThreadedAnimation defaults to true.
341 * So, at least for now we set the indicator animation to NO for
342 * both the scan and regular progress indicators for both 32 and 64 bit
343 * as it test out fine on both and there is no reason our progress indicators
344 * should require their own thread.
347 [fScanIndicator setUsesThreadedAnimation:NO];
348 [fRipIndicator setUsesThreadedAnimation:NO];
352 /* Show/Dont Show Presets drawer upon launch based
353 on user preference DefaultPresetsDrawerShow*/
354 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
356 [fPresetDrawer setDelegate:self];
357 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
358 stringForKey:@"Drawer Size"] );
359 if( drawerSize.width )
360 [fPresetDrawer setContentSize: drawerSize];
361 [fPresetDrawer open];
364 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
365 [fSrcAngleLabel setHidden:YES];
366 [fSrcAnglePopUp setHidden:YES];
369 NSMenuItem *menuItem;
370 [fDstFormatPopUp removeAllItems];
372 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
373 [menuItem setTag: HB_MUX_MP4];
375 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
376 [menuItem setTag: HB_MUX_MKV];
378 [fDstFormatPopUp selectItemAtIndex: 0];
380 [self formatPopUpChanged:nil];
382 /* We enable the create chapters checkbox here since we are .mp4 */
383 [fCreateChapterMarkers setEnabled: YES];
384 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
386 [fCreateChapterMarkers setState: NSOnState];
392 [fDstFile2Field setStringValue: [NSString stringWithFormat:
393 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
396 [fVidEncoderPopUp removeAllItems];
397 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
398 [fVidEncoderPopUp addItemWithTitle: @"XviD"];
403 [fVidTargetSizeField setIntValue: 700];
404 [fVidBitrateField setIntValue: 1000];
406 [fVidQualityMatrix selectCell: fVidBitrateCell];
407 [self videoMatrixChanged:nil];
409 /* Video framerate */
410 [fVidRatePopUp removeAllItems];
411 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
412 for( int i = 0; i < hb_video_rates_count; i++ )
414 if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
416 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
417 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
419 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
421 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
422 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
424 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
426 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
427 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
431 [fVidRatePopUp addItemWithTitle:
432 [NSString stringWithCString: hb_video_rates[i].string]];
435 [fVidRatePopUp selectItemAtIndex: 0];
437 /* Set Auto Crop to On at launch */
438 [fPictureController setAutoCrop:YES];
441 [fAudTrack1BitratePopUp removeAllItems];
442 for( int i = 0; i < hb_audio_bitrates_count; i++ )
444 [fAudTrack1BitratePopUp addItemWithTitle:
445 [NSString stringWithCString: hb_audio_bitrates[i].string]];
448 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
450 /* Audio samplerate */
451 [fAudTrack1RatePopUp removeAllItems];
452 for( int i = 0; i < hb_audio_rates_count; i++ )
454 [fAudTrack1RatePopUp addItemWithTitle:
455 [NSString stringWithCString: hb_audio_rates[i].string]];
457 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
460 [fStatusField setStringValue: @""];
465 /* We disable the Turbo 1st pass checkbox since we are not x264 */
466 [fVidTurboPassCheck setEnabled: NO];
467 [fVidTurboPassCheck setState: NSOffState];
470 /* lets get our default prefs here */
471 [self getDefaultPresets:nil];
472 /* lets initialize the current successful scancount here to 0 */
473 currentSuccessfulScanCount = 0;
478 - (void) enableUI: (bool) b
480 NSControl * controls[] =
481 { fSrcTitleField, fSrcTitlePopUp,
482 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
483 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
484 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
485 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
486 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
487 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
488 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
489 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
490 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
491 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
492 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
493 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
494 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
495 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
496 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
497 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
498 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel};
501 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
503 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
505 NSTextField * tf = (NSTextField *) controls[i];
506 if( ![tf isBezeled] )
508 [tf setTextColor: b ? [NSColor controlTextColor] :
509 [NSColor disabledControlTextColor]];
513 [controls[i] setEnabled: b];
519 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
520 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
521 [self setEnabledStateOfAudioMixdownControls:nil];
522 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
523 [self calculatePictureSizing:nil];
527 [fPresetsOutlineView setEnabled: NO];
531 [self videoMatrixChanged:nil];
532 [fAdvancedOptions enableUI:b];
536 /***********************************************************************
538 ***********************************************************************
539 * Shows a progression bar on the dock icon, filled according to
540 * 'progress' (0.0 <= progress <= 1.0).
541 * Called with progress < 0.0 or progress > 1.0, restores the original
543 **********************************************************************/
544 - (void) UpdateDockIcon: (float) progress
548 NSBitmapImageRep * bmp;
550 uint32_t black = htonl( 0x000000FF );
551 uint32_t red = htonl( 0xFF0000FF );
552 uint32_t white = htonl( 0xFFFFFFFF );
553 int row_start, row_end;
556 /* Get application original icon */
557 icon = [NSImage imageNamed: @"NSApplicationIcon"];
559 if( progress < 0.0 || progress > 1.0 )
561 [NSApp setApplicationIconImage: icon];
565 /* Get it in a raw bitmap form */
566 tiff = [icon TIFFRepresentationUsingCompression:
567 NSTIFFCompressionNone factor: 1.0];
568 bmp = [NSBitmapImageRep imageRepWithData: tiff];
570 /* Draw the progression bar */
571 /* It's pretty simple (ugly?) now, but I'm no designer */
573 row_start = 3 * (int) [bmp size].height / 4;
574 row_end = 7 * (int) [bmp size].height / 8;
576 for( i = row_start; i < row_start + 2; i++ )
578 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
579 for( j = 0; j < (int) [bmp size].width; j++ )
584 for( i = row_start + 2; i < row_end - 2; i++ )
586 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
589 for( j = 2; j < (int) [bmp size].width - 2; j++ )
591 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
603 for( i = row_end - 2; i < row_end; i++ )
605 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
606 for( j = 0; j < (int) [bmp size].width; j++ )
612 /* Now update the dock icon */
613 tiff = [bmp TIFFRepresentationUsingCompression:
614 NSTIFFCompressionNone factor: 1.0];
615 icon = [[NSImage alloc] initWithData: tiff];
616 [NSApp setApplicationIconImage: icon];
620 - (void) updateUI: (NSTimer *) timer
623 /* Update UI for fHandle (user scanning instance of libhb ) */
626 list = hb_get_titles( fHandle );
627 /* check to see if there has been a new scan done
628 this bypasses the constraints of HB_STATE_WORKING
629 not allowing setting a newly scanned source */
630 int checkScanCount = hb_get_scancount( fHandle );
631 if( checkScanCount > currentScanCount )
633 currentScanCount = checkScanCount;
634 [fScanIndicator setIndeterminate: NO];
635 [fScanIndicator setDoubleValue: 0.0];
636 [fScanIndicator setHidden: YES];
637 [self showNewScan:nil];
641 hb_get_state( fHandle, &s );
647 #define p s.param.scanning
648 case HB_STATE_SCANNING:
650 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
651 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
652 p.title_cur, p.title_count]];
653 [fScanIndicator setHidden: NO];
654 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
659 #define p s.param.scandone
660 case HB_STATE_SCANDONE:
662 [fScanIndicator setIndeterminate: NO];
663 [fScanIndicator setDoubleValue: 0.0];
664 [fScanIndicator setHidden: YES];
665 [self writeToActivityLog:"ScanDone state received from fHandle"];
666 [self showNewScan:nil];
667 [[fWindow toolbar] validateVisibleItems];
673 #define p s.param.working
674 case HB_STATE_WORKING:
681 #define p s.param.muxing
682 case HB_STATE_MUXING:
689 case HB_STATE_PAUSED:
692 case HB_STATE_WORKDONE:
699 /* Update UI for fQueueEncodeLibhb */
701 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
702 /* check to see if there has been a new scan done
703 this bypasses the constraints of HB_STATE_WORKING
704 not allowing setting a newly scanned source */
706 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
707 if( checkScanCount > currentScanCount )
709 currentScanCount = checkScanCount;
710 [self writeToActivityLog:"currentScanCount received from fQueueEncodeLibhb"];
714 hb_get_state( fQueueEncodeLibhb, &s );
720 #define p s.param.scanning
721 case HB_STATE_SCANNING:
723 [fStatusField setStringValue: [NSString stringWithFormat:
724 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
725 p.title_cur, p.title_count]];
727 /* Set the status string in fQueueController as well */
728 [fQueueController setQueueStatusString: [NSString stringWithFormat:
729 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
730 p.title_cur, p.title_count]];
735 #define p s.param.scandone
736 case HB_STATE_SCANDONE:
738 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
739 [self processNewQueueEncode];
740 [[fWindow toolbar] validateVisibleItems];
746 #define p s.param.working
747 case HB_STATE_WORKING:
749 NSMutableString * string;
750 /* Update text field */
751 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d of %d, %.2f %%", @"" ), p.job_cur, p.job_count, 100.0 * p.progress];
755 [string appendFormat:
756 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
757 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
760 [fStatusField setStringValue: string];
761 /* Set the status string in fQueueController as well */
762 [fQueueController setQueueStatusString: string];
764 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
765 [fRipIndicator setIndeterminate: NO];
766 [fRipIndicator setDoubleValue:100.0 * progress_total];
768 // If progress bar hasn't been revealed at the bottom of the window, do
769 // that now. This code used to be in doRip. I moved it to here to handle
770 // the case where hb_start is called by HBQueueController and not from
772 if( !fRipIndicatorShown )
774 NSRect frame = [fWindow frame];
775 if( frame.size.width <= 591 )
776 frame.size.width = 591;
777 frame.size.height += 36;
778 frame.origin.y -= 36;
779 [fWindow setFrame:frame display:YES animate:YES];
780 fRipIndicatorShown = YES;
784 /* Update dock icon */
785 if( dockIconProgress < 100.0 * progress_total )
787 [self UpdateDockIcon: progress_total];
788 dockIconProgress += 5;
795 #define p s.param.muxing
796 case HB_STATE_MUXING:
798 /* Update text field */
799 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
800 /* Set the status string in fQueueController as well */
801 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
803 [fRipIndicator setIndeterminate: YES];
804 [fRipIndicator startAnimation: nil];
806 /* Update dock icon */
807 [self UpdateDockIcon: 1.0];
813 case HB_STATE_PAUSED:
814 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
815 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
819 case HB_STATE_WORKDONE:
821 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
822 // or someone calling hb_stop. In the latter case, hb_stop does not clear
823 // out the remaining passes/jobs in the queue. We'll do that here.
825 // Delete all remaining jobs of this encode.
826 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
827 /* Set the status string in fQueueController as well */
828 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
829 [fRipIndicator setIndeterminate: NO];
830 [fRipIndicator stopAnimation: nil];
831 [fRipIndicator setDoubleValue: 0.0];
832 [[fWindow toolbar] validateVisibleItems];
834 /* Restore dock icon */
835 [self UpdateDockIcon: -1.0];
836 dockIconProgress = 0;
838 if( fRipIndicatorShown )
840 NSRect frame = [fWindow frame];
841 if( frame.size.width <= 591 )
842 frame.size.width = 591;
843 frame.size.height += -36;
844 frame.origin.y -= -36;
845 [fWindow setFrame:frame display:YES animate:YES];
846 fRipIndicatorShown = NO;
848 /* Since we are done with this encode, tell output to stop writing to the
849 * individual encode log
851 [outputPanel endEncodeLog];
852 /* Check to see if the encode state has not been cancelled
853 to determine if we should check for encode done notifications */
854 if( fEncodeState != 2 )
856 NSString *pathOfFinishedEncode;
857 /* Get the output file name for the finished encode */
858 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
860 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
862 [self showGrowlDoneNotification:pathOfFinishedEncode];
864 [self sendToMetaX:pathOfFinishedEncode];
866 /* since we have successfully completed an encode, we increment the queue counter */
867 [self incrementQueueItemDone:nil];
869 /* all end of queue actions below need to be done after all queue encodes have finished
870 * and there are no pending jobs left to process
872 if (fPendingCount == 0)
874 /* If Alert Window or Window and Growl has been selected */
875 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
876 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
878 /*On Screen Notification*/
881 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
882 [NSApp requestUserAttention:NSCriticalRequest];
885 /* If sleep has been selected */
886 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
889 NSDictionary* errorDict;
890 NSAppleEventDescriptor* returnDescriptor = nil;
891 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
892 @"tell application \"Finder\" to sleep"];
893 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
894 [scriptObject release];
896 /* If Shutdown has been selected */
897 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
900 NSDictionary* errorDict;
901 NSAppleEventDescriptor* returnDescriptor = nil;
902 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
903 @"tell application \"Finder\" to shut down"];
904 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
905 [scriptObject release];
919 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
920 - (void) writeToActivityLog:(const char *) format, ...
923 va_start(args, format);
927 vsnprintf( str, 1024, format, args );
929 time_t _now = time( NULL );
930 struct tm * now = localtime( &_now );
931 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
938 // ============================================================
939 // NSToolbar Related Methods
940 // ============================================================
942 - (void) setupToolbar {
943 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
945 [toolbar setAllowsUserCustomization: YES];
946 [toolbar setAutosavesConfiguration: YES];
947 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
949 [toolbar setDelegate: self];
951 [fWindow setToolbar: toolbar];
954 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
955 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
956 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
958 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
960 [item setLabel: @"Toggle Presets"];
961 [item setPaletteLabel: @"Toggler Presets"];
962 [item setToolTip: @"Open/Close Preset Drawer"];
963 [item setImage: [NSImage imageNamed: @"Drawer"]];
964 [item setTarget: self];
965 [item setAction: @selector(toggleDrawer:)];
966 [item setAutovalidates: NO];
968 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
970 [item setLabel: @"Start"];
971 [item setPaletteLabel: @"Start Encoding"];
972 [item setToolTip: @"Start Encoding"];
973 [item setImage: [NSImage imageNamed: @"Play"]];
974 [item setTarget: self];
975 [item setAction: @selector(Rip:)];
977 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
979 [item setLabel: @"Show Queue"];
980 [item setPaletteLabel: @"Show Queue"];
981 [item setToolTip: @"Show Queue"];
982 [item setImage: [NSImage imageNamed: @"Queue"]];
983 [item setTarget: self];
984 [item setAction: @selector(showQueueWindow:)];
985 [item setAutovalidates: NO];
987 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
989 [item setLabel: @"Add to Queue"];
990 [item setPaletteLabel: @"Add to Queue"];
991 [item setToolTip: @"Add to Queue"];
992 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
993 [item setTarget: self];
994 [item setAction: @selector(addToQueue:)];
996 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
998 [item setLabel: @"Pause"];
999 [item setPaletteLabel: @"Pause Encoding"];
1000 [item setToolTip: @"Pause Encoding"];
1001 [item setImage: [NSImage imageNamed: @"Pause"]];
1002 [item setTarget: self];
1003 [item setAction: @selector(Pause:)];
1005 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1007 [item setLabel: @"Picture Settings"];
1008 [item setPaletteLabel: @"Show Picture Settings"];
1009 [item setToolTip: @"Show Picture Settings"];
1010 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1011 [item setTarget: self];
1012 [item setAction: @selector(showPicturePanel:)];
1014 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1016 [item setLabel: @"Activity Window"];
1017 [item setPaletteLabel: @"Show Activity Window"];
1018 [item setToolTip: @"Show Activity Window"];
1019 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1020 [item setTarget: self];
1021 [item setAction: @selector(showDebugOutputPanel:)];
1022 [item setAutovalidates: NO];
1024 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1026 [item setLabel: @"Source"];
1027 [item setPaletteLabel: @"Source"];
1028 [item setToolTip: @"Choose Video Source"];
1029 [item setImage: [NSImage imageNamed: @"Source"]];
1030 [item setTarget: self];
1031 [item setAction: @selector(browseSources:)];
1041 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1043 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1044 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1045 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1048 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1050 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1051 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1052 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1053 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1056 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1058 NSString * ident = [toolbarItem itemIdentifier];
1063 hb_get_state2( fQueueEncodeLibhb, &s );
1065 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
1067 if ([ident isEqualToString: StartEncodingIdentifier])
1069 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1070 [toolbarItem setLabel: @"Stop"];
1071 [toolbarItem setPaletteLabel: @"Stop"];
1072 [toolbarItem setToolTip: @"Stop Encoding"];
1075 if ([ident isEqualToString: PauseEncodingIdentifier])
1077 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1078 [toolbarItem setLabel: @"Pause"];
1079 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1080 [toolbarItem setToolTip: @"Pause Encoding"];
1085 if ([ident isEqualToString: AddToQueueIdentifier])
1087 if ([ident isEqualToString: ShowPictureIdentifier])
1091 else if (s.state == HB_STATE_PAUSED)
1093 if ([ident isEqualToString: PauseEncodingIdentifier])
1095 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1096 [toolbarItem setLabel: @"Resume"];
1097 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1098 [toolbarItem setToolTip: @"Resume Encoding"];
1101 if ([ident isEqualToString: StartEncodingIdentifier])
1103 if ([ident isEqualToString: AddToQueueIdentifier])
1105 if ([ident isEqualToString: ShowPictureIdentifier])
1108 else if (s.state == HB_STATE_SCANNING)
1110 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1112 if ([ident isEqualToString: StartEncodingIdentifier])
1114 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1115 if (hb_count(fHandle) > 0)
1116 [toolbarItem setLabel: @"Start Queue"];
1118 [toolbarItem setLabel: @"Start"];
1119 [toolbarItem setPaletteLabel: @"Start Encoding"];
1120 [toolbarItem setToolTip: @"Start Encoding"];
1123 if ([ident isEqualToString: AddToQueueIdentifier])
1125 if ([ident isEqualToString: ShowPictureIdentifier])
1130 /* If there are any pending queue items, make sure the start/stop button is active */
1131 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1133 if ([ident isEqualToString: ShowQueueIdentifier])
1135 if ([ident isEqualToString: ToggleDrawerIdentifier])
1137 if ([ident isEqualToString: ChooseSourceIdentifier])
1139 if ([ident isEqualToString: ShowActivityIdentifier])
1145 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1147 SEL action = [menuItem action];
1150 hb_get_state2( fHandle, &s );
1154 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1155 return SuccessfulScan && [fWindow attachedSheet] == nil;
1157 if (action == @selector(browseSources:))
1159 if (s.state == HB_STATE_SCANNING)
1162 return [fWindow attachedSheet] == nil;
1164 if (action == @selector(selectDefaultPreset:))
1165 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1166 if (action == @selector(Pause:))
1168 if (s.state == HB_STATE_WORKING)
1170 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1171 [menuItem setTitle:@"Pause Encoding"];
1174 else if (s.state == HB_STATE_PAUSED)
1176 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1177 [menuItem setTitle:@"Resume Encoding"];
1183 if (action == @selector(Rip:))
1185 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1187 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1188 [menuItem setTitle:@"Stop Encoding"];
1191 else if (SuccessfulScan)
1193 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1194 [menuItem setTitle:@"Start Encoding"];
1195 return [fWindow attachedSheet] == nil;
1201 if( action == @selector(setDefaultPreset:) )
1203 return [fPresetsOutlineView selectedRow] != -1;
1210 #pragma mark Encode Done Actions
1211 // register a test notification and make
1212 // it enabled by default
1213 #define SERVICE_NAME @"Encode Done"
1214 - (NSDictionary *)registrationDictionaryForGrowl
1216 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1217 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1218 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1221 return registrationDictionary;
1224 -(void)showGrowlDoneNotification:(NSString *) filePath
1226 /* This end of encode action is called as each encode rolls off of the queue */
1227 NSString * finishedEncode = filePath;
1228 /* strip off the path to just show the file name */
1229 finishedEncode = [finishedEncode lastPathComponent];
1230 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1231 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1233 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1234 [GrowlApplicationBridge
1235 notifyWithTitle:@"Put down that cocktail..."
1236 description:growlMssg
1237 notificationName:SERVICE_NAME
1245 -(void)sendToMetaX:(NSString *) filePath
1247 /* This end of encode action is called as each encode rolls off of the queue */
1248 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1250 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
1251 [myScript executeAndReturnError: nil];
1256 #pragma mark Get New Source
1258 /*Opens the source browse window, called from Open Source widgets */
1259 - (IBAction) browseSources: (id) sender
1261 NSOpenPanel * panel;
1263 panel = [NSOpenPanel openPanel];
1264 [panel setAllowsMultipleSelection: NO];
1265 [panel setCanChooseFiles: YES];
1266 [panel setCanChooseDirectories: YES ];
1267 NSString * sourceDirectory;
1268 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1270 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1274 sourceDirectory = @"~/Desktop";
1275 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1277 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1278 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1280 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1281 modalForWindow: fWindow modalDelegate: self
1282 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1283 contextInfo: sender];
1286 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1287 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1289 /* we convert the sender content of contextInfo back into a variable called sender
1290 * mostly just for consistency for evaluation later
1292 id sender = (id)contextInfo;
1293 /* User selected a file to open */
1294 if( returnCode == NSOKButton )
1296 /* Free display name allocated previously by this code */
1297 [browsedSourceDisplayName release];
1299 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1300 /* we set the last searched source directory in the prefs here */
1301 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1302 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1303 /* we order out sheet, which is the browse window as we need to open
1304 * the title selection sheet right away
1306 [sheet orderOut: self];
1308 if (sender == fOpenSourceTitleMMenu)
1310 /* We put the chosen source path in the source display text field for the
1311 * source title selection sheet in which the user specifies the specific title to be
1312 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1313 * purposes in the title panel
1316 [fScanSrcTitlePathField setStringValue:scanPath];
1317 NSString *displayTitlescanSourceName;
1319 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1321 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1322 we have to use the title->dvd value so we get the proper name of the volume if a physical dvd is the source*/
1323 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1327 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1328 displayTitlescanSourceName = [scanPath lastPathComponent];
1330 /* we set the source display name in the title selection dialogue */
1331 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1332 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1333 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1334 /* We show the actual sheet where the user specifies the title to be scanned
1335 * as we are going to do a title specific scan
1337 [self showSourceTitleScanPanel:nil];
1341 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1342 NSString *path = [[sheet filenames] objectAtIndex: 0];
1344 /* We check to see if the chosen file at path is a package */
1345 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1347 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1348 /* We check to see if this is an .eyetv package */
1349 if ([[path pathExtension] isEqualToString: @"eyetv"])
1351 [self writeToActivityLog:"trying to open eyetv package"];
1352 /* We're looking at an EyeTV package - try to open its enclosed
1354 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1356 int n = [[path stringByAppendingString: @"/"]
1357 completePathIntoString: &mpgname caseSensitive: NO
1358 matchesIntoArray: nil
1359 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1362 /* Found an mpeg inside the eyetv package, make it our scan path
1363 and call performScan on the enclosed mpeg */
1365 [self writeToActivityLog:"found mpeg in eyetv package"];
1366 [self performScan:path scanTitleNum:0];
1370 /* We did not find an mpeg file in our package, so we do not call performScan */
1371 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1374 /* We check to see if this is a .dvdmedia package */
1375 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1377 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1378 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1379 [self writeToActivityLog:"trying to open dvdmedia package"];
1380 [self performScan:path scanTitleNum:0];
1384 /* The package is not an eyetv package, so we do not call performScan */
1385 [self writeToActivityLog:"unable to open package"];
1388 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1390 /* path is not a package, so we call perform scan directly on our file */
1391 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1393 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1394 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1395 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1399 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1400 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1401 /* make sure we remove any path extension as this can also be an '.mpg' file */
1402 browsedSourceDisplayName = [[path lastPathComponent] retain];
1404 [self performScan:path scanTitleNum:0];
1412 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1413 - (IBAction) showSourceTitleScanPanel: (id) sender
1415 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1418 [fScanSrcTitleNumField setStringValue: @"0"];
1419 /* Show the panel */
1420 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1423 - (IBAction) closeSourceTitleScanPanel: (id) sender
1425 [NSApp endSheet: fScanSrcTitlePanel];
1426 [fScanSrcTitlePanel orderOut: self];
1428 if(sender == fScanSrcTitleOpenButton)
1430 /* We setup the scan status in the main window to indicate a source title scan */
1431 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1432 [fScanIndicator setHidden: NO];
1433 [fScanIndicator setIndeterminate: YES];
1434 [fScanIndicator startAnimation: nil];
1436 /* We use the performScan method to actually perform the specified scan passing the path and the title
1439 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1443 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1444 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1446 /* set the bool applyQueueToScan so that we dont apply a queue setting to the final scan */
1447 applyQueueToScan = NO;
1448 /* use a bool to determine whether or not we can decrypt using vlc */
1449 BOOL cancelScanDecrypt = 0;
1450 NSString *path = scanPath;
1451 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1453 // Notify ChapterTitles that there's no title
1454 [fChapterTitlesDelegate resetWithTitle:nil];
1455 [fChapterTable reloadData];
1457 [self enableUI: NO];
1459 if( [detector isVideoDVD] )
1461 // The chosen path was actually on a DVD, so use the raw block
1462 // device path instead.
1463 path = [detector devicePath];
1464 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1467 /* If we are 64 bit, we cannot read encrypted dvd's as vlc is 32 bit only */
1468 cancelScanDecrypt = 1;
1469 [self writeToActivityLog: "64 bit mode cannot read dvd's, scan cancelled"];
1470 /*On Screen Notification*/
1473 status = NSRunAlertPanel(@"64-bit HandBrake cannot read encrypted dvds!",@"", @"Cancel Scan", @"Attempt Scan Anyway", nil);
1474 [NSApp requestUserAttention:NSCriticalRequest];
1476 if (status == NSAlertDefaultReturn)
1478 /* User chose to cancel the scan */
1479 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1480 cancelScanDecrypt = 1;
1484 [self writeToActivityLog: "user overrode 64-bit warning trying to open physical dvd without decryption"];
1485 cancelScanDecrypt = 0;
1489 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1490 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1491 NSFileManager * fileManager = [NSFileManager defaultManager];
1492 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1494 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1495 cancelScanDecrypt = 1;
1496 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1498 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");
1499 [NSApp requestUserAttention:NSCriticalRequest];
1501 if (status == NSAlertDefaultReturn)
1503 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1504 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
1506 else if (status == NSAlertAlternateReturn)
1508 /* User chose to cancel the scan */
1509 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1513 /* 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 */
1514 cancelScanDecrypt = 0;
1515 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1521 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1522 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1527 if (cancelScanDecrypt == 0)
1529 /* we actually pass the scan off to libhb here */
1530 /* If there is no title number passed to scan, we use "0"
1531 * which causes the default behavior of a full source scan
1537 if (scanTitleNum > 0)
1539 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1541 /* We use our advance pref to determine how many previews to scan */
1542 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1543 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1544 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1548 - (IBAction) showNewScan:(id)sender
1552 int indxpri=0; // Used to search the longuest title (default in combobox)
1553 int longuestpri=0; // Used to search the longuest title (default in combobox)
1556 list = hb_get_titles( fHandle );
1558 if( !hb_list_count( list ) )
1560 /* We display a message if a valid dvd source was not chosen */
1561 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1562 SuccessfulScan = NO;
1564 // Notify ChapterTitles that there's no title
1565 [fChapterTitlesDelegate resetWithTitle:nil];
1566 [fChapterTable reloadData];
1570 /* We increment the successful scancount here by one,
1571 which we use at the end of this function to tell the gui
1572 if this is the first successful scan since launch and whether
1573 or not we should set all settings to the defaults */
1575 currentSuccessfulScanCount++;
1577 [[fWindow toolbar] validateVisibleItems];
1579 [fSrcTitlePopUp removeAllItems];
1580 for( int i = 0; i < hb_list_count( list ); i++ )
1582 title = (hb_title_t *) hb_list_item( list, i );
1584 currentSource = [NSString stringWithUTF8String: title->name];
1585 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1586 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1588 /* Use the dvd name in the default output field here
1589 May want to add code to remove blank spaces for some dvd names*/
1590 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1591 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1593 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1594 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1598 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1599 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1603 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1605 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1609 [fSrcTitlePopUp addItemWithTitle: [NSString
1610 stringWithFormat: @"%d - %02dh%02dm%02ds",
1611 title->index, title->hours, title->minutes,
1615 // Select the longuest title
1616 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1617 [self titlePopUpChanged:nil];
1619 SuccessfulScan = YES;
1620 [self enableUI: YES];
1622 /* if its the initial successful scan after awakeFromNib */
1623 if (currentSuccessfulScanCount == 1)
1625 [self selectDefaultPreset:nil];
1627 // Open preview window now if it was visible when HB was closed
1628 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1629 [self showPreviewWindow:nil];
1631 // Open picture sizing window now if it was visible when HB was closed
1632 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1633 [self showPicturePanel:nil];
1644 #pragma mark New Output Destination
1646 - (IBAction) browseFile: (id) sender
1648 /* Open a panel to let the user choose and update the text field */
1649 NSSavePanel * panel = [NSSavePanel savePanel];
1650 /* We get the current file name and path from the destination field here */
1651 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1652 modalForWindow: fWindow modalDelegate: self
1653 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1657 - (void) browseFileDone: (NSSavePanel *) sheet
1658 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1660 if( returnCode == NSOKButton )
1662 [fDstFile2Field setStringValue: [sheet filename]];
1663 /* Save this path to the prefs so that on next browse destination window it opens there */
1664 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1665 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1671 #pragma mark Main Window Control
1673 - (IBAction) openMainWindow: (id) sender
1675 [fWindow makeKeyAndOrderFront:nil];
1678 - (BOOL) windowShouldClose: (id) sender
1683 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1686 [fWindow makeKeyAndOrderFront:nil];
1694 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1695 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1700 #pragma mark Queue File
1702 - (void) loadQueueFile {
1703 /* We declare the default NSFileManager into fileManager */
1704 NSFileManager * fileManager = [NSFileManager defaultManager];
1705 /*We define the location of the user presets file */
1706 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1707 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1708 /* We check for the presets.plist */
1709 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1711 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1714 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1715 /* lets check to see if there is anything in the queue file .plist */
1716 if (nil == QueueFileArray)
1718 /* if not, then lets initialize an empty array */
1719 QueueFileArray = [[NSMutableArray alloc] init];
1721 /* Initialize our curQueueEncodeIndex to 0
1722 * so we can use it to track which queue
1723 * item is to be used to track our encodes */
1724 /* NOTE: this should be changed if and when we
1725 * are able to get the last unfinished encode
1726 * in the case of a crash or shutdown */
1731 [self clearQueueEncodedItems];
1733 currentQueueEncodeIndex = 0;
1736 - (void)addQueueFileItem
1738 [QueueFileArray addObject:[self createQueueFileItem]];
1739 [self saveQueueFileItem];
1743 - (void) removeQueueFileItem:(int) queueItemToRemove
1746 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
1747 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
1749 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
1750 * by one to keep in sync with the queue array
1752 currentQueueEncodeIndex--;
1753 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
1755 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1756 [self saveQueueFileItem];
1760 - (void)saveQueueFileItem
1762 [QueueFileArray writeToFile:QueueFile atomically:YES];
1763 [fQueueController setQueueArray: QueueFileArray];
1764 [self getQueueStats];
1767 - (void)getQueueStats
1769 /* lets get the stats on the status of the queue array */
1771 fEncodingQueueItem = 0;
1773 fCompletedCount = 0;
1777 /* We use a number system to set the encode status of the queue item
1779 * 0 == already encoded
1780 * 1 == is being encoded
1781 * 2 == is yet to be encoded
1786 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1788 while (tempObject = [enumerator nextObject])
1790 NSDictionary *thisQueueDict = tempObject;
1791 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1795 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1798 fEncodingQueueItem = i;
1800 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
1804 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
1811 /* Set the queue status field in the main window */
1812 NSMutableString * string;
1813 if (fPendingCount == 1)
1815 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
1819 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
1821 [fQueueStatus setStringValue:string];
1824 /* This method will set any item marked as encoding back to pending
1825 * currently used right after a queue reload
1827 - (void) setQueueEncodingItemsAsPending
1829 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1831 NSMutableArray *tempArray;
1832 tempArray = [NSMutableArray array];
1833 /* we look here to see if the preset is we move on to the next one */
1834 while ( tempObject = [enumerator nextObject] )
1836 /* If the queue item is marked as "encoding" (1)
1837 * then change its status back to pending (2) which effectively
1838 * puts it back into the queue to be encoded
1840 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
1842 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
1844 [tempArray addObject:tempObject];
1847 [QueueFileArray setArray:tempArray];
1848 [self saveQueueFileItem];
1852 /* This method will clear the queue of any encodes that are not still pending
1853 * this includes both successfully completed encodes as well as cancelled encodes */
1854 - (void) clearQueueEncodedItems
1856 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1858 NSMutableArray *tempArray;
1859 tempArray = [NSMutableArray array];
1860 /* we look here to see if the preset is we move on to the next one */
1861 while ( tempObject = [enumerator nextObject] )
1863 /* If the queue item is either completed (0) or cancelled (3) from the
1864 * last session, then we put it in tempArray to be deleted from QueueFileArray.
1865 * NOTE: this means we retain pending (2) and also an item that is marked as
1866 * still encoding (1). If the queue has an item that is still marked as encoding
1867 * from a previous session, we can conlude that HB was either shutdown, or crashed
1868 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
1870 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
1872 [tempArray addObject:tempObject];
1876 [QueueFileArray removeObjectsInArray:tempArray];
1877 [self saveQueueFileItem];
1880 /* This method will clear the queue of all encodes. effectively creating an empty queue */
1881 - (void) clearQueueAllItems
1883 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1885 NSMutableArray *tempArray;
1886 tempArray = [NSMutableArray array];
1887 /* we look here to see if the preset is we move on to the next one */
1888 while ( tempObject = [enumerator nextObject] )
1890 [tempArray addObject:tempObject];
1893 [QueueFileArray removeObjectsInArray:tempArray];
1894 [self saveQueueFileItem];
1897 /* This method will duplicate prepareJob however into the
1898 * queue .plist instead of into the job structure so it can
1899 * be recalled later */
1900 - (NSDictionary *)createQueueFileItem
1902 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
1904 hb_list_t * list = hb_get_titles( fHandle );
1905 hb_title_t * title = (hb_title_t *) hb_list_item( list,
1906 [fSrcTitlePopUp indexOfSelectedItem] );
1907 hb_job_t * job = title->job;
1911 /* We use a number system to set the encode status of the queue item
1912 * 0 == already encoded
1913 * 1 == is being encoded
1914 * 2 == is yet to be encoded
1917 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
1918 /* Source and Destination Information */
1920 [queueFileJob setObject:[NSString stringWithUTF8String: title->dvd] forKey:@"SourcePath"];
1921 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
1922 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
1923 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
1924 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
1926 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
1928 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
1930 /* Lets get the preset info if there is any */
1931 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
1932 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
1934 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
1935 /* Chapter Markers*/
1936 /* If we have only one chapter or a title without chapters, set chapter markers to off */
1937 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
1939 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
1943 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
1946 /* We need to get the list of chapter names to put into an array and store
1947 * in our queue, so they can be reapplied in prepareJob when this queue
1948 * item comes up if Chapter Markers is set to on.
1951 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
1952 int chaptercount = hb_list_count( fTitle->list_chapter );
1953 for( i = 0; i < chaptercount; i++ )
1955 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
1956 if( chapter != NULL )
1958 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
1961 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
1962 [ChapterNamesArray autorelease];
1964 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
1965 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
1966 /* Mux mp4 with http optimization */
1967 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
1968 /* Add iPod uuid atom */
1969 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
1973 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
1974 /* x264 Option String */
1975 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
1977 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
1978 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
1979 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
1980 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
1982 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
1984 /* 2 Pass Encoding */
1985 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
1986 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
1987 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
1989 /* Picture Sizing */
1990 /* Use Max Picture settings for whatever the dvd is.*/
1991 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1992 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1993 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1994 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1995 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
1996 /* if we are custom anamorphic, store the exact storage, par and display dims */
1997 if (fTitle->job->anamorphic.mode == 3)
1999 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2000 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2002 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2003 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2005 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2006 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2009 NSString * pictureSummary;
2010 pictureSummary = [fPictureSizeField stringValue];
2011 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2012 /* Set crop settings here */
2013 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2014 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2015 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2016 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2017 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2019 /* Picture Filters */
2020 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2021 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2023 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2024 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2025 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2027 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2028 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2030 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2031 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2033 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2035 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2038 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2040 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2041 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2042 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2043 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2044 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2045 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2046 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2048 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2050 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2051 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2052 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2053 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2054 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2055 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2056 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2058 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2060 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2061 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2062 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2063 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2064 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2065 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2066 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2068 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2070 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2071 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2072 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2073 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2074 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2075 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2076 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2080 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
2081 [queueFileJob setObject:[NSNumber numberWithInt:[fSubPopUp indexOfSelectedItem]] forKey:@"JobSubtitlesIndex"];
2082 /* Forced Subtitles */
2083 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
2087 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2089 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2091 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2094 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2098 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2101 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2102 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2103 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2105 /* Picture Sizing */
2106 /* Use Max Picture settings for whatever the dvd is.*/
2107 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2108 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2109 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2110 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2111 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2113 /* Set crop settings here */
2114 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2115 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2116 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2117 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2118 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2120 /* Picture Filters */
2121 //[queueFileJob setObject:[fPicSettingDecomb stringValue] forKey:@"JobPictureDecomb"];
2124 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2126 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2127 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2128 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2129 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2130 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2132 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2134 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2135 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2136 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2137 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2138 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2140 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2142 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2143 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2144 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2145 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2146 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2148 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2150 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2151 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2152 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2153 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2154 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2157 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
2158 /* Forced Subtitles */
2159 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
2161 /* we need to auto relase the queueFileJob and return it */
2162 [queueFileJob autorelease];
2163 return queueFileJob;
2167 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2168 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2170 NSUInteger index = [indexSet lastIndex];
2171 NSUInteger aboveInsertIndexCount = 0;
2174 NSUInteger removeIndex;
2176 if (index >= insertIndex)
2178 removeIndex = index + aboveInsertIndexCount;
2179 aboveInsertIndexCount++;
2183 removeIndex = index;
2187 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2188 [QueueFileArray removeObjectAtIndex:removeIndex];
2189 [QueueFileArray insertObject:object atIndex:insertIndex];
2192 index = [indexSet indexLessThanIndex:index];
2194 /* We save all of the Queue data here
2195 * and it also gets sent back to the queue controller*/
2196 [self saveQueueFileItem];
2202 #pragma mark Queue Job Processing
2204 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2206 int i = currentQueueEncodeIndex;
2207 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2209 /* We save all of the Queue data here */
2210 [self saveQueueFileItem];
2211 /* We Reload the New Table data for presets */
2212 //[fPresetsOutlineView reloadData];
2214 /* Since we have now marked a queue item as done
2215 * we can go ahead and increment currentQueueEncodeIndex
2216 * so that if there is anything left in the queue we can
2217 * go ahead and move to the next item if we want to */
2218 currentQueueEncodeIndex++ ;
2219 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2220 int queueItems = [QueueFileArray count];
2221 /* If we still have more items in our queue, lets go to the next one */
2222 if (currentQueueEncodeIndex < queueItems)
2224 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2225 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2229 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2233 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2234 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2236 /* Tell HB to output a new activity log file for this encode */
2237 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2240 /* use a bool to determine whether or not we can decrypt using vlc */
2241 BOOL cancelScanDecrypt = 0;
2242 /* set the bool so that showNewScan knows to apply the appropriate queue
2243 * settings as this is a queue rescan
2245 applyQueueToScan = YES;
2246 NSString *path = scanPath;
2247 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2249 /*On Screen Notification*/
2251 //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2252 //[NSApp requestUserAttention:NSCriticalRequest];
2254 if( [detector isVideoDVD] )
2256 // The chosen path was actually on a DVD, so use the raw block
2257 // device path instead.
2258 path = [detector devicePath];
2259 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2261 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2262 NSString *vlcPath = @"/Applications/VLC.app";
2263 NSFileManager * fileManager = [NSFileManager defaultManager];
2264 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2266 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2267 cancelScanDecrypt = 1;
2268 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2270 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");
2271 [NSApp requestUserAttention:NSCriticalRequest];
2273 if (status == NSAlertDefaultReturn)
2275 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2276 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2278 else if (status == NSAlertAlternateReturn)
2280 /* User chose to cancel the scan */
2281 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2285 /* 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 */
2286 cancelScanDecrypt = 0;
2287 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2293 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2294 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2298 if (cancelScanDecrypt == 0)
2300 /* we actually pass the scan off to libhb here */
2301 /* If there is no title number passed to scan, we use "0"
2302 * which causes the default behavior of a full source scan
2308 if (scanTitleNum > 0)
2310 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2313 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2314 /* We use our advance pref to determine how many previews to scan */
2315 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2316 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2320 /* This method was originally used to load up a new queue item in the gui and
2321 * then start processing it. However we now have modified -prepareJob and use a second
2322 * instance of libhb to do our actual encoding, therefor right now it is not required.
2323 * Nonetheless I want to leave this in here
2324 * because basically its everything we need to be able to actually modify a pending queue
2325 * item in the gui and resave it. At least for now - dynaflash
2328 - (IBAction)applyQueueSettings:(id)sender
2330 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2331 hb_job_t * job = fTitle->job;
2333 /* Set title number and chapters */
2334 /* since the queue only scans a single title, we really don't need to pick a title */
2335 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2337 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2338 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2341 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2342 [self formatPopUpChanged:nil];
2344 /* Chapter Markers*/
2345 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2346 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2347 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2348 /* Mux mp4 with http optimization */
2349 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2352 /* We set the advanced opt string here if applicable*/
2353 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2354 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2356 /* Lets run through the following functions to get variables set there */
2357 [self videoEncoderPopUpChanged:nil];
2358 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2359 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2360 [self calculateBitrate:nil];
2363 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2365 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2366 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2367 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2369 [self videoMatrixChanged:nil];
2371 /* Video framerate */
2372 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2373 detected framerate in the fVidRatePopUp so we use index 0*/
2374 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2376 [fVidRatePopUp selectItemAtIndex: 0];
2380 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2383 /* 2 Pass Encoding */
2384 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2385 [self twoPassCheckboxChanged:nil];
2386 /* Turbo 1st pass for 2 Pass Encoding */
2387 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2390 if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2392 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2394 [fAudLang1PopUp selectItemAtIndex: 1];
2396 [self audioTrackPopUpChanged: fAudLang1PopUp];
2397 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2398 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2399 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2400 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2402 if ([fAudTrack1MixPopUp selectedItem] == nil)
2404 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2406 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2407 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2408 if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2410 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2412 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2413 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2415 if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2417 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2419 [fAudLang2PopUp selectItemAtIndex: 1];
2421 [self audioTrackPopUpChanged: fAudLang2PopUp];
2422 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2423 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2424 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2425 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2427 if ([fAudTrack2MixPopUp selectedItem] == nil)
2429 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2431 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2432 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2433 if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2435 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2437 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2438 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2440 if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2442 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2444 [fAudLang3PopUp selectItemAtIndex: 1];
2446 [self audioTrackPopUpChanged: fAudLang3PopUp];
2447 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2448 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2449 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2450 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2452 if ([fAudTrack3MixPopUp selectedItem] == nil)
2454 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2456 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2457 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2458 if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2460 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2462 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2463 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2465 if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2467 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2469 [fAudLang4PopUp selectItemAtIndex: 1];
2471 [self audioTrackPopUpChanged: fAudLang4PopUp];
2472 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2473 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2474 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2475 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2477 if ([fAudTrack4MixPopUp selectedItem] == nil)
2479 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2481 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2482 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2483 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2485 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2487 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2488 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2493 [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2494 /* Forced Subtitles */
2495 [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2497 /* Picture Settings */
2498 /* we check to make sure the presets width/height does not exceed the sources width/height */
2499 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2501 /* if so, then we use the sources height and width to avoid scaling up */
2502 job->width = fTitle->width;
2503 job->height = fTitle->height;
2505 else // source width/height is >= the preset height/width
2507 /* we can go ahead and use the presets values for height and width */
2508 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2509 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2511 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2512 if (job->keep_ratio == 1)
2514 hb_fix_aspect( job, HB_KEEP_WIDTH );
2515 if( job->height > fTitle->height )
2517 job->height = fTitle->height;
2518 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2521 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2524 /* If Cropping is set to custom, then recall all four crop values from
2525 when the preset was created and apply them */
2526 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2528 [fPictureController setAutoCrop:NO];
2530 /* Here we use the custom crop values saved at the time the preset was saved */
2531 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2532 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2533 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2534 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2537 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2539 [fPictureController setAutoCrop:YES];
2540 /* Here we use the auto crop values determined right after scan */
2541 job->crop[0] = AutoCropTop;
2542 job->crop[1] = AutoCropBottom;
2543 job->crop[2] = AutoCropLeft;
2544 job->crop[3] = AutoCropRight;
2550 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2553 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2555 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2557 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2559 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2561 [fPictureController setGrayscale:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2563 [self calculatePictureSizing:nil];
2566 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2567 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2568 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2569 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2571 /* Deselect the currently selected Preset if there is one*/
2572 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2573 //[self selectPreset:nil];
2575 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2576 /* Change UI to show "Custom" settings are being used */
2577 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2579 curUserPresetChosenNum = nil;
2583 /* Deselect the currently selected Preset if there is one*/
2584 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2585 /* Change UI to show "Custom" settings are being used */
2586 [fPresetSelectedDisplay setStringValue: @"Custom"];
2588 //curUserPresetChosenNum = nil;
2591 /* We need to set this bool back to NO, in case the user wants to do a scan */
2592 //applyQueueToScan = NO;
2594 /* so now we go ahead and process the new settings */
2595 [self processNewQueueEncode];
2600 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2601 - (void) processNewQueueEncode
2603 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2604 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2605 hb_job_t * job = title->job;
2607 if( !hb_list_count( list ) )
2609 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2613 [self writeToActivityLog: "processNewQueueEncode title list is: %d", hb_list_count( list )];
2616 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2617 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2618 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2619 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2620 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2622 if( [[queueToApply objectForKey:@"SubtitlesForced"] intValue] == 1 )
2623 job->subtitle_force = 1;
2625 job->subtitle_force = 0;
2628 * If scanning we need to do some extra setup of the job.
2630 if( job->indepth_scan == 1 )
2635 * When subtitle scan is enabled do a fast pre-scan job
2636 * which will determine which subtitles to enable, if any.
2639 x264opts_tmp = job->x264opts;
2641 job->x264opts = NULL;
2643 job->indepth_scan = 1;
2645 job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
2646 *(job->select_subtitle) = NULL;
2649 * Add the pre-scan job
2651 hb_add( fQueueEncodeLibhb, job );
2652 job->x264opts = x264opts_tmp;
2655 job->select_subtitle = NULL;
2657 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2659 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
2660 job->indepth_scan = 0;
2663 * Do not autoselect subtitles on the first pass of a two pass
2665 job->select_subtitle = NULL;
2669 hb_add( fQueueEncodeLibhb, job );
2673 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2674 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2676 job->select_subtitle = subtitle_tmp;
2678 hb_add( fQueueEncodeLibhb, job );
2683 job->indepth_scan = 0;
2686 hb_add( fQueueEncodeLibhb, job );
2689 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2690 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2691 /* Lets mark our new encode as 1 or "Encoding" */
2692 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2693 [self saveQueueFileItem];
2694 /* We should be all setup so let 'er rip */
2699 #pragma mark Live Preview
2700 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2701 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2704 - (void) prepareJobForPreview
2706 hb_list_t * list = hb_get_titles( fHandle );
2707 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2708 [fSrcTitlePopUp indexOfSelectedItem] );
2709 hb_job_t * job = title->job;
2710 hb_audio_config_t * audio;
2711 /* set job->angle for libdvdnav */
2712 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
2713 /* Chapter selection */
2714 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
2715 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
2717 /* Format (Muxer) and Video Encoder */
2718 job->mux = [[fDstFormatPopUp selectedItem] tag];
2719 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
2721 job->chapter_markers = 0;
2723 if( job->vcodec & HB_VCODEC_X264 )
2725 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2726 Currently only used with Constant Quality setting*/
2727 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
2732 /* Below Sends x264 options to the core library if x264 is selected*/
2733 /* Lets use this as per Nyx, Thanks Nyx!*/
2734 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2735 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
2736 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
2741 /* Video settings */
2742 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
2743 * and detelecine is on, so we handle that in the logic below
2746 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
2748 /* a specific framerate has been chosen */
2749 job->vrate = 27000000;
2750 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
2751 /* We are not same as source so we set job->cfr to 1
2752 * to enable constant frame rate since user has specified
2753 * a specific framerate*/
2758 /* We are same as source (variable) */
2759 job->vrate = title->rate;
2760 job->vrate_base = title->rate_base;
2761 /* We are same as source so we set job->cfr to 0
2762 * to enable true same as source framerate */
2764 /* If we are same as source and we have detelecine on, we need to turn on
2767 if ([fPictureController detelecine] == 1)
2773 switch( [fVidQualityMatrix selectedRow] )
2777 Bitrate should already have been calculated and displayed
2778 in fVidBitrateField, so let's just use it */
2780 job->vquality = -1.0;
2781 job->vbitrate = [fVidBitrateField intValue];
2784 job->vquality = [fVidQualityRFField floatValue];
2789 /* Subtitle settings */
2790 switch( [fSubPopUp indexOfSelectedItem] - 2 )
2794 * No subtitles selected
2799 * Subtitle scan selected
2801 job->indepth_scan = 1;
2805 * Subtitle selected, add it into the job from the title.
2807 job->indepth_scan = 0;
2808 hb_subtitle_t *subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, [fSubPopUp indexOfSelectedItem] - 2 );
2809 hb_list_add( job->list_subtitle, subtitle );
2813 /* Audio tracks and mixdowns */
2814 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
2815 int audiotrack_count = hb_list_count(job->list_audio);
2816 for( int i = 0; i < audiotrack_count;i++)
2818 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
2819 hb_list_rem(job->list_audio, temp_audio);
2821 /* Now lets add our new tracks to the audio list here */
2822 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2824 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2825 hb_audio_config_init(audio);
2826 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2827 /* We go ahead and assign values to our audio->out.<properties> */
2828 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2829 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
2830 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
2831 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
2832 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
2833 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
2835 hb_audio_add( job, audio );
2838 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2840 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2841 hb_audio_config_init(audio);
2842 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2843 /* We go ahead and assign values to our audio->out.<properties> */
2844 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2845 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
2846 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
2847 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
2848 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
2849 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
2851 hb_audio_add( job, audio );
2856 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2858 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2859 hb_audio_config_init(audio);
2860 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2861 /* We go ahead and assign values to our audio->out.<properties> */
2862 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2863 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
2864 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
2865 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
2866 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
2867 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
2869 hb_audio_add( job, audio );
2874 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2876 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2877 hb_audio_config_init(audio);
2878 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2879 /* We go ahead and assign values to our audio->out.<properties> */
2880 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2881 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
2882 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
2883 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
2884 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
2885 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
2887 hb_audio_add( job, audio );
2896 /* Though Grayscale is not really a filter, per se
2897 * we put it here since its in the filters panel
2900 if ([fPictureController grayscale])
2909 /* Initialize the filters list */
2910 job->filters = hb_list_init();
2912 /* Now lets call the filters if applicable.
2913 * The order of the filters is critical
2917 if ([fPictureController detelecine] == 1)
2919 hb_list_add( job->filters, &hb_filter_detelecine );
2921 if ([fPictureController detelecine] == 2)
2923 /* use a custom detelecine string */
2924 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
2925 hb_list_add( job->filters, &hb_filter_detelecine );
2927 if ([fPictureController useDecomb] == 1)
2930 if ([fPictureController decomb] == 1)
2932 /* Run old deinterlacer fd by default */
2933 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
2934 hb_list_add( job->filters, &hb_filter_decomb );
2936 /* we add the custom string if present */
2937 if ([fPictureController decomb] == 2)
2939 /* use a custom decomb string */
2940 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
2941 hb_list_add( job->filters, &hb_filter_decomb );
2948 if ([fPictureController deinterlace] == 1)
2950 /* Run old deinterlacer fd by default */
2951 hb_filter_deinterlace.settings = "-1";
2952 hb_list_add( job->filters, &hb_filter_deinterlace );
2954 else if ([fPictureController deinterlace] == 2)
2956 /* Yadif mode 0 (without spatial deinterlacing.) */
2957 hb_filter_deinterlace.settings = "2";
2958 hb_list_add( job->filters, &hb_filter_deinterlace );
2960 else if ([fPictureController deinterlace] == 3)
2962 /* Yadif (with spatial deinterlacing) */
2963 hb_filter_deinterlace.settings = "0";
2964 hb_list_add( job->filters, &hb_filter_deinterlace );
2966 else if ([fPictureController deinterlace] == 4)
2968 /* we add the custom string if present */
2969 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
2970 hb_list_add( job->filters, &hb_filter_deinterlace );
2975 if ([fPictureController denoise] == 1) // Weak in popup
2977 hb_filter_denoise.settings = "2:1:2:3";
2978 hb_list_add( job->filters, &hb_filter_denoise );
2980 else if ([fPictureController denoise] == 2) // Medium in popup
2982 hb_filter_denoise.settings = "3:2:2:3";
2983 hb_list_add( job->filters, &hb_filter_denoise );
2985 else if ([fPictureController denoise] == 3) // Strong in popup
2987 hb_filter_denoise.settings = "7:7:5:5";
2988 hb_list_add( job->filters, &hb_filter_denoise );
2990 else if ([fPictureController denoise] == 4) // custom in popup
2992 /* we add the custom string if present */
2993 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
2994 hb_list_add( job->filters, &hb_filter_denoise );
2997 /* Deblock (uses pp7 default) */
2998 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
2999 * the macgui's purposes a value of 0 actually means to not even use the filter
3000 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3002 if ([fPictureController deblock] != 0)
3004 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3005 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3006 hb_list_add( job->filters, &hb_filter_deblock );
3013 #pragma mark Job Handling
3019 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3020 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3021 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3022 hb_job_t * job = title->job;
3023 hb_audio_config_t * audio;
3024 /* Title Angle for dvdnav */
3025 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3026 /* Chapter selection */
3027 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3028 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3030 /* Format (Muxer) and Video Encoder */
3031 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3032 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3035 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3036 //if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
3038 /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
3039 mpeg4 and the checkbox being checked
3040 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
3041 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3043 job->largeFileSize = 1;
3047 job->largeFileSize = 0;
3049 /* We set http optimized mp4 here */
3050 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3052 job->mp4_optimize = 1;
3056 job->mp4_optimize = 0;
3061 /* We set the chapter marker extraction here based on the format being
3062 mpeg4 or mkv and the checkbox being checked */
3063 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3065 job->chapter_markers = 1;
3067 /* now lets get our saved chapter names out the array in the queue file
3068 * and insert them back into the title chapter list. We have it here,
3069 * because unless we are inserting chapter markers there is no need to
3070 * spend the overhead of iterating through the chapter names array imo
3071 * Also, note that if for some reason we don't apply chapter names, the
3072 * chapters just come out 001, 002, etc. etc.
3075 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3077 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3079 while (tempObject = [enumerator nextObject])
3081 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3082 if( chapter != NULL )
3084 strncpy( chapter->title, [tempObject UTF8String], 1023);
3085 chapter->title[1023] = '\0';
3092 job->chapter_markers = 0;
3095 if( job->vcodec & HB_VCODEC_X264 )
3097 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3106 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
3107 Currently only used with Constant Quality setting*/
3108 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2)
3112 /* Below Sends x264 options to the core library if x264 is selected*/
3113 /* Lets use this as per Nyx, Thanks Nyx!*/
3114 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3115 /* Turbo first pass if two pass and Turbo First pass is selected */
3116 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3118 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3119 NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3120 /* append the "Turbo" string variable to the existing opts string.
3121 Note: the "Turbo" string must be appended, not prepended to work properly*/
3122 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3123 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3127 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3133 /* Picture Size Settings */
3134 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3135 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3137 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3138 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3139 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3141 /* insert our custom values here for capuj */
3142 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3143 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3145 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3146 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3148 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3149 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3152 /* Here we use the crop values saved at the time the preset was saved */
3153 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3154 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3155 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3156 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3158 /* Video settings */
3161 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3162 * and detelecine is on, so we handle that in the logic below
3165 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3167 /* a specific framerate has been chosen */
3168 job->vrate = 27000000;
3169 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3170 /* We are not same as source so we set job->cfr to 1
3171 * to enable constant frame rate since user has specified
3172 * a specific framerate*/
3177 /* We are same as source (variable) */
3178 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3179 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3180 /* We are same as source so we set job->cfr to 0
3181 * to enable true same as source framerate */
3183 /* If we are same as source and we have detelecine on, we need to turn on
3186 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3192 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3195 Bitrate should already have been calculated and displayed
3196 in fVidBitrateField, so let's just use it same as abr*/
3197 job->vquality = -1.0;
3198 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3200 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3202 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3207 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3208 /* Subtitle settings */
3210 switch( [[queueToApply objectForKey:@"JobSubtitlesIndex"] intValue] - 2 )
3214 * No subtitles selected
3219 * Subtitle scan selected
3221 job->indepth_scan = 1;
3225 * Subtitle selected, add it into the job from the title.
3227 job->indepth_scan = 0;
3228 hb_subtitle_t *subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle,
3229 [[queueToApply objectForKey:@"JobSubtitlesIndex"] intValue] - 2 );
3230 hb_list_add( job->list_subtitle, subtitle );
3234 /* Audio tracks and mixdowns */
3235 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3236 int audiotrack_count = hb_list_count(job->list_audio);
3237 for( int i = 0; i < audiotrack_count;i++)
3239 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3240 hb_list_rem(job->list_audio, temp_audio);
3242 /* Now lets add our new tracks to the audio list here */
3243 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3245 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3246 hb_audio_config_init(audio);
3247 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3248 /* We go ahead and assign values to our audio->out.<properties> */
3249 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3250 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3251 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3252 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3253 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3254 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3256 hb_audio_add( job, audio );
3259 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3262 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3263 hb_audio_config_init(audio);
3264 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3265 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3266 /* We go ahead and assign values to our audio->out.<properties> */
3267 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3268 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3269 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3270 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3271 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3272 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3274 hb_audio_add( job, audio );
3278 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3280 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3281 hb_audio_config_init(audio);
3282 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3283 /* We go ahead and assign values to our audio->out.<properties> */
3284 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3285 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3286 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3287 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3288 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3289 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3291 hb_audio_add( job, audio );
3295 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3297 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3298 hb_audio_config_init(audio);
3299 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3300 /* We go ahead and assign values to our audio->out.<properties> */
3301 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3302 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3303 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3304 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3305 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3306 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3308 hb_audio_add( job, audio );
3313 job->filters = hb_list_init();
3315 /* Now lets call the filters if applicable.
3316 * The order of the filters is critical
3319 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3321 //if ([queueToApply objectForKey:@"PictureDetelecineCustom"])
3322 hb_list_add( job->filters, &hb_filter_detelecine );
3324 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3326 /* use a custom detelecine string */
3327 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3328 hb_list_add( job->filters, &hb_filter_detelecine );
3331 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3334 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3336 /* Run old deinterlacer fd by default */
3337 hb_list_add( job->filters, &hb_filter_decomb );
3339 /* we add the custom string if present */
3340 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3342 /* use a custom decomb string */
3343 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3344 hb_list_add( job->filters, &hb_filter_decomb );
3352 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3354 /* Run old deinterlacer fd by default */
3355 hb_filter_deinterlace.settings = "-1";
3356 hb_list_add( job->filters, &hb_filter_deinterlace );
3358 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3360 /* Yadif mode 0 (without spatial deinterlacing.) */
3361 hb_filter_deinterlace.settings = "2";
3362 hb_list_add( job->filters, &hb_filter_deinterlace );
3364 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3366 /* Yadif (with spatial deinterlacing) */
3367 hb_filter_deinterlace.settings = "0";
3368 hb_list_add( job->filters, &hb_filter_deinterlace );
3370 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3372 /* we add the custom string if present */
3373 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3374 hb_list_add( job->filters, &hb_filter_deinterlace );
3380 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Weak in popup
3382 hb_filter_denoise.settings = "2:1:2:3";
3383 hb_list_add( job->filters, &hb_filter_denoise );
3385 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Medium in popup
3387 hb_filter_denoise.settings = "3:2:2:3";
3388 hb_list_add( job->filters, &hb_filter_denoise );
3390 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Strong in popup
3392 hb_filter_denoise.settings = "7:7:5:5";
3393 hb_list_add( job->filters, &hb_filter_denoise );
3395 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Custom in popup
3397 /* we add the custom string if present */
3398 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3399 hb_list_add( job->filters, &hb_filter_denoise );
3402 /* Deblock (uses pp7 default) */
3403 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3404 * the macgui's purposes a value of 0 actually means to not even use the filter
3405 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3407 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3409 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3410 hb_list_add( job->filters, &hb_filter_deblock );
3412 [self writeToActivityLog: "prepareJob exiting"];
3417 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3419 - (IBAction) addToQueue: (id) sender
3421 /* We get the destination directory from the destination field here */
3422 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3423 /* We check for a valid destination here */
3424 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3426 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3433 BOOL fileExistsInQueue;
3434 fileExistsInQueue = NO;
3436 /* We check for and existing file here */
3437 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3442 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3444 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3446 while (tempObject = [enumerator nextObject])
3448 NSDictionary *thisQueueDict = tempObject;
3449 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3451 fileExistsInQueue = YES;
3457 if(fileExists == YES)
3459 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
3460 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3461 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3462 NULL, NULL, [NSString stringWithFormat:
3463 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3464 [fDstFile2Field stringValue]] );
3466 else if (fileExistsInQueue == YES)
3468 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
3469 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3470 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3471 NULL, NULL, [NSString stringWithFormat:
3472 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3473 [fDstFile2Field stringValue]] );
3477 [self doAddToQueue];
3481 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
3482 the user if they want to overwrite an exiting movie file.
3484 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
3485 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3487 if( returnCode == NSAlertAlternateReturn )
3488 [self doAddToQueue];
3491 - (void) doAddToQueue
3493 [self addQueueFileItem ];
3498 /* Rip: puts up an alert before ultimately calling doRip
3500 - (IBAction) Rip: (id) sender
3502 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
3503 /* Rip or Cancel ? */
3505 hb_get_state2( fQueueEncodeLibhb, &s );
3507 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
3509 [self Cancel: sender];
3513 /* We check to see if we need to warn the user that the computer will go to sleep
3514 or shut down when encoding is finished */
3515 [self remindUserOfSleepOrShutdown];
3517 // If there are pending jobs in the queue, then this is a rip the queue
3518 if (fPendingCount > 0)
3520 /* here lets start the queue with the first pending item */
3521 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3526 // Before adding jobs to the queue, check for a valid destination.
3528 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3529 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3531 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3535 /* We check for duplicate name here */
3536 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
3538 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
3539 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3540 @selector( overWriteAlertDone:returnCode:contextInfo: ),
3541 NULL, NULL, [NSString stringWithFormat:
3542 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3543 [fDstFile2Field stringValue]] );
3545 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
3549 /* if there are no pending jobs in the queue, then add this one to the queue and rip
3550 otherwise, just rip the queue */
3551 if(fPendingCount == 0)
3553 [self writeToActivityLog: "Rip: No pending jobs, so sending this one to doAddToQueue"];
3554 [self doAddToQueue];
3557 /* go right to processing the new queue encode */
3558 [self writeToActivityLog: "Rip: Going right to performNewQueueScan"];
3559 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3564 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
3565 want to overwrite an exiting movie file.
3567 - (void) overWriteAlertDone: (NSWindow *) sheet
3568 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3570 if( returnCode == NSAlertAlternateReturn )
3572 /* if there are no jobs in the queue, then add this one to the queue and rip
3573 otherwise, just rip the queue */
3574 if( fPendingCount == 0 )
3576 [self doAddToQueue];
3579 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3580 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
3581 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3586 - (void) remindUserOfSleepOrShutdown
3588 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
3590 /*Warn that computer will sleep after encoding*/
3593 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);
3594 [NSApp requestUserAttention:NSCriticalRequest];
3595 if ( reminduser == NSAlertAlternateReturn )
3597 [self showPreferencesWindow:nil];
3600 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
3602 /*Warn that computer will shut down after encoding*/
3605 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);
3606 [NSApp requestUserAttention:NSCriticalRequest];
3607 if ( reminduser == NSAlertAlternateReturn )
3609 [self showPreferencesWindow:nil];
3618 /* Let libhb do the job */
3619 hb_start( fQueueEncodeLibhb );
3620 /*set the fEncodeState State */
3625 //------------------------------------------------------------------------------------
3626 // Displays an alert asking user if the want to cancel encoding of current job.
3627 // Cancel: returns immediately after posting the alert. Later, when the user
3628 // acknowledges the alert, doCancelCurrentJob is called.
3629 //------------------------------------------------------------------------------------
3630 - (IBAction)Cancel: (id)sender
3632 if (!fQueueController) return;
3634 hb_pause( fQueueEncodeLibhb );
3635 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
3637 // Which window to attach the sheet to?
3638 NSWindow * docWindow;
3639 if ([sender respondsToSelector: @selector(window)])
3640 docWindow = [sender window];
3642 docWindow = fWindow;
3644 NSBeginCriticalAlertSheet(
3646 NSLocalizedString(@"Continue Encoding", nil),
3647 NSLocalizedString(@"Cancel Current and Stop", nil),
3648 NSLocalizedString(@"Cancel Current and Continue", nil),
3650 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
3651 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
3653 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
3656 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
3658 hb_resume( fQueueEncodeLibhb );
3659 if (returnCode == NSAlertOtherReturn)
3661 [self doCancelCurrentJob]; // <- this also stops libhb
3663 if (returnCode == NSAlertAlternateReturn)
3665 [self doCancelCurrentJobAndStop];
3669 //------------------------------------------------------------------------------------
3670 // Cancels and deletes the current job and stops libhb from processing the remaining
3672 //------------------------------------------------------------------------------------
3673 - (void) doCancelCurrentJob
3675 // Stop the current job. hb_stop will only cancel the current pass and then set
3676 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
3677 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
3678 // remaining passes of the job and then start the queue back up if there are any
3682 hb_stop( fQueueEncodeLibhb );
3684 // Delete all remaining jobs since libhb doesn't do this on its own.
3686 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3687 hb_rem( fQueueEncodeLibhb, job );
3689 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3691 // now that we've stopped the currently encoding job, lets mark it as cancelled
3692 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3693 // and as always, save it in the queue .plist...
3694 /* We save all of the Queue data here */
3695 [self saveQueueFileItem];
3696 // so now lets move to
3697 currentQueueEncodeIndex++ ;
3698 // ... and see if there are more items left in our queue
3699 int queueItems = [QueueFileArray count];
3700 /* If we still have more items in our queue, lets go to the next one */
3701 if (currentQueueEncodeIndex < queueItems)
3703 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
3704 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
3706 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3710 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
3715 - (void) doCancelCurrentJobAndStop
3717 hb_stop( fQueueEncodeLibhb );
3719 // Delete all remaining jobs since libhb doesn't do this on its own.
3721 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3722 hb_rem( fQueueEncodeLibhb, job );
3725 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3727 // now that we've stopped the currently encoding job, lets mark it as cancelled
3728 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3729 // and as always, save it in the queue .plist...
3730 /* We save all of the Queue data here */
3731 [self saveQueueFileItem];
3732 // so now lets move to
3733 currentQueueEncodeIndex++ ;
3734 [self writeToActivityLog: "cancelling current job and stopping the queue"];
3736 - (IBAction) Pause: (id) sender
3739 hb_get_state2( fQueueEncodeLibhb, &s );
3741 if( s.state == HB_STATE_PAUSED )
3743 hb_resume( fQueueEncodeLibhb );
3747 hb_pause( fQueueEncodeLibhb );
3752 #pragma mark GUI Controls Changed Methods
3754 - (IBAction) titlePopUpChanged: (id) sender
3756 hb_list_t * list = hb_get_titles( fHandle );
3757 hb_title_t * title = (hb_title_t*)
3758 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3760 /* If Auto Naming is on. We create an output filename of dvd name - title number */
3761 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
3763 [fDstFile2Field setStringValue: [NSString stringWithFormat:
3764 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
3765 [browsedSourceDisplayName stringByDeletingPathExtension],
3767 [[fDstFile2Field stringValue] pathExtension]]];
3770 /* Update chapter popups */
3771 [fSrcChapterStartPopUp removeAllItems];
3772 [fSrcChapterEndPopUp removeAllItems];
3773 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
3775 [fSrcChapterStartPopUp addItemWithTitle: [NSString
3776 stringWithFormat: @"%d", i + 1]];
3777 [fSrcChapterEndPopUp addItemWithTitle: [NSString
3778 stringWithFormat: @"%d", i + 1]];
3781 [fSrcChapterStartPopUp selectItemAtIndex: 0];
3782 [fSrcChapterEndPopUp selectItemAtIndex:
3783 hb_list_count( title->list_chapter ) - 1];
3784 [self chapterPopUpChanged:nil];
3786 /* if using dvd nav, show the angle widget */
3787 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
3789 [fSrcAngleLabel setHidden:NO];
3790 [fSrcAnglePopUp setHidden:NO];
3792 [fSrcAnglePopUp removeAllItems];
3793 for( int i = 0; i < title->angle_count; i++ )
3795 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
3797 [fSrcAnglePopUp selectItemAtIndex: 0];
3801 [fSrcAngleLabel setHidden:YES];
3802 [fSrcAnglePopUp setHidden:YES];
3805 /* Start Get and set the initial pic size for display */
3806 hb_job_t * job = title->job;
3809 /* Set Auto Crop to on upon selecting a new title */
3810 [fPictureController setAutoCrop:YES];
3812 /* We get the originial output picture width and height and put them
3813 in variables for use with some presets later on */
3814 PicOrigOutputWidth = job->width;
3815 PicOrigOutputHeight = job->height;
3816 AutoCropTop = job->crop[0];
3817 AutoCropBottom = job->crop[1];
3818 AutoCropLeft = job->crop[2];
3819 AutoCropRight = job->crop[3];
3821 /* Reset the new title in fPictureController && fPreviewController*/
3822 [fPictureController SetTitle:title];
3824 /* Update subtitle popups */
3825 hb_subtitle_t * subtitle;
3826 [fSubPopUp removeAllItems];
3827 [fSubPopUp addItemWithTitle: @"None"];
3828 [fSubPopUp addItemWithTitle: @"Autoselect"];
3829 for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
3831 subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
3833 /* We cannot use NSPopUpButton's addItemWithTitle because
3834 it checks for duplicate entries */
3835 [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
3836 subtitle->lang] action: NULL keyEquivalent: @""];
3838 [fSubPopUp selectItemAtIndex: 0];
3840 [self subtitleSelectionChanged:nil];
3842 /* Update chapter table */
3843 [fChapterTitlesDelegate resetWithTitle:title];
3844 [fChapterTable reloadData];
3846 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3847 int audiotrack_count = hb_list_count(job->list_audio);
3848 for( int i = 0; i < audiotrack_count;i++)
3850 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3851 hb_list_rem(job->list_audio, temp_audio);
3854 /* Update audio popups */
3855 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
3856 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
3857 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
3858 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
3859 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
3860 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
3861 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
3862 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3863 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3864 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3866 /* changing the title may have changed the audio channels on offer, */
3867 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3868 [self audioTrackPopUpChanged: fAudLang1PopUp];
3869 [self audioTrackPopUpChanged: fAudLang2PopUp];
3870 [self audioTrackPopUpChanged: fAudLang3PopUp];
3871 [self audioTrackPopUpChanged: fAudLang4PopUp];
3873 [fVidRatePopUp selectItemAtIndex: 0];
3875 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
3876 [self calculatePictureSizing:nil];
3878 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
3879 [self selectPreset:nil];
3882 - (IBAction) chapterPopUpChanged: (id) sender
3885 /* If start chapter popup is greater than end chapter popup,
3886 we set the end chapter popup to the same as start chapter popup */
3887 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
3889 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
3893 hb_list_t * list = hb_get_titles( fHandle );
3894 hb_title_t * title = (hb_title_t *)
3895 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3897 hb_chapter_t * chapter;
3898 int64_t duration = 0;
3899 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
3900 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
3902 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3903 duration += chapter->duration;
3906 duration /= 90000; /* pts -> seconds */
3907 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
3908 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
3911 [self calculateBitrate: sender];
3913 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
3915 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
3916 [fCreateChapterMarkers setEnabled: NO];
3917 [fCreateChapterMarkers setState: NSOffState];
3921 [fCreateChapterMarkers setEnabled: YES];
3925 - (IBAction) formatPopUpChanged: (id) sender
3927 NSString * string = [fDstFile2Field stringValue];
3928 int format = [fDstFormatPopUp indexOfSelectedItem];
3930 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
3931 [fDstMp4LargeFileCheck setHidden: YES];
3932 [fDstMp4HttpOptFileCheck setHidden: YES];
3933 [fDstMp4iPodFileCheck setHidden: YES];
3935 /* Update the Video Codec PopUp */
3936 /* lets get the tag of the currently selected item first so we might reset it later */
3937 int selectedVidEncoderTag;
3938 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
3940 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
3941 [fVidEncoderPopUp removeAllItems];
3942 NSMenuItem *menuItem;
3943 /* These video encoders are available to all of our current muxers, so lets list them once here */
3944 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
3945 [menuItem setTag: HB_VCODEC_FFMPEG];
3950 /*Get Default MP4 File Extension*/
3951 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
3959 /* Add additional video encoders here */
3960 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3961 [menuItem setTag: HB_VCODEC_X264];
3962 /* We show the mp4 option checkboxes here since we are mp4 */
3963 [fCreateChapterMarkers setEnabled: YES];
3964 [fDstMp4LargeFileCheck setHidden: NO];
3965 [fDstMp4HttpOptFileCheck setHidden: NO];
3966 [fDstMp4iPodFileCheck setHidden: NO];
3971 /* Add additional video encoders here */
3972 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3973 [menuItem setTag: HB_VCODEC_X264];
3974 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3975 [menuItem setTag: HB_VCODEC_THEORA];
3976 /* We enable the create chapters checkbox here */
3977 [fCreateChapterMarkers setEnabled: YES];
3982 /* if we have a previously selected vid encoder tag, then try to select it */
3983 if (selectedVidEncoderTag)
3985 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
3989 [fVidEncoderPopUp selectItemAtIndex: 0];
3992 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
3993 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
3994 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
3995 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
3998 [self autoSetM4vExtension: sender];
4000 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4002 if( SuccessfulScan )
4004 /* Add/replace to the correct extension */
4005 [self audioTrackPopUpChanged: fAudLang1PopUp];
4006 [self audioTrackPopUpChanged: fAudLang2PopUp];
4007 [self audioTrackPopUpChanged: fAudLang3PopUp];
4008 [self audioTrackPopUpChanged: fAudLang4PopUp];
4010 if( [fVidEncoderPopUp selectedItem] == nil )
4013 [fVidEncoderPopUp selectItemAtIndex:0];
4014 [self videoEncoderPopUpChanged:nil];
4016 /* changing the format may mean that we can / can't offer mono or 6ch, */
4017 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4019 /* We call the method to properly enable/disable turbo 2 pass */
4020 [self twoPassCheckboxChanged: sender];
4021 /* We call method method to change UI to reflect whether a preset is used or not*/
4024 [self customSettingUsed: sender];
4027 - (IBAction) autoSetM4vExtension: (id) sender
4029 if ( [fDstFormatPopUp indexOfSelectedItem] )
4032 NSString * extension = @"mp4";
4034 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4035 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4036 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4037 [fCreateChapterMarkers state] == NSOnState ||
4038 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4043 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4046 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4047 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4050 /* Method to determine if we should change the UI
4051 To reflect whether or not a Preset is being used or if
4052 the user is using "Custom" settings by determining the sender*/
4053 - (IBAction) customSettingUsed: (id) sender
4055 if ([sender stringValue])
4057 /* Deselect the currently selected Preset if there is one*/
4058 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4059 /* Change UI to show "Custom" settings are being used */
4060 [fPresetSelectedDisplay setStringValue: @"Custom"];
4062 curUserPresetChosenNum = nil;
4064 [self calculateBitrate:nil];
4069 #pragma mark - Video
4071 - (IBAction) videoEncoderPopUpChanged: (id) sender
4073 hb_job_t * job = fTitle->job;
4074 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4076 [fAdvancedOptions setHidden:YES];
4077 /* If we are using x264 then show the x264 advanced panel*/
4078 if (videoEncoder == HB_VCODEC_X264)
4080 [fAdvancedOptions setHidden:NO];
4081 [self autoSetM4vExtension: sender];
4084 /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
4085 is being used as it borks up loose anamorphic .
4086 For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
4087 to use the index itself but this is easier */
4088 if (videoEncoder == HB_VCODEC_FFMPEG)
4090 if (job->anamorphic.mode == 2)
4092 job->anamorphic.mode = 0;
4094 [fPictureController setAllowLooseAnamorphic:NO];
4095 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4096 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4097 anything other than MP4.
4099 [fDstMp4iPodFileCheck setEnabled: NO];
4100 [fDstMp4iPodFileCheck setState: NSOffState];
4104 [fPictureController setAllowLooseAnamorphic:YES];
4105 [fDstMp4iPodFileCheck setEnabled: YES];
4107 [self setupQualitySlider];
4108 [self calculatePictureSizing: sender];
4109 [self twoPassCheckboxChanged: sender];
4113 - (IBAction) twoPassCheckboxChanged: (id) sender
4115 /* check to see if x264 is chosen */
4116 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4118 if( [fVidTwoPassCheck state] == NSOnState)
4120 [fVidTurboPassCheck setHidden: NO];
4124 [fVidTurboPassCheck setHidden: YES];
4125 [fVidTurboPassCheck setState: NSOffState];
4127 /* Make sure Two Pass is checked if Turbo is checked */
4128 if( [fVidTurboPassCheck state] == NSOnState)
4130 [fVidTwoPassCheck setState: NSOnState];
4135 [fVidTurboPassCheck setHidden: YES];
4136 [fVidTurboPassCheck setState: NSOffState];
4139 /* We call method method to change UI to reflect whether a preset is used or not*/
4140 [self customSettingUsed: sender];
4143 - (IBAction ) videoFrameRateChanged: (id) sender
4145 /* We call method method to calculatePictureSizing to error check detelecine*/
4146 [self calculatePictureSizing: sender];
4148 /* We call method method to change UI to reflect whether a preset is used or not*/
4149 [self customSettingUsed: sender];
4151 - (IBAction) videoMatrixChanged: (id) sender;
4153 bool target, bitrate, quality;
4155 target = bitrate = quality = false;
4156 if( [fVidQualityMatrix isEnabled] )
4158 switch( [fVidQualityMatrix selectedRow] )
4171 [fVidTargetSizeField setEnabled: target];
4172 [fVidBitrateField setEnabled: bitrate];
4173 [fVidQualitySlider setEnabled: quality];
4174 [fVidQualityRFField setEnabled: quality];
4175 [fVidQualityRFLabel setEnabled: quality];
4176 [fVidTwoPassCheck setEnabled: !quality &&
4177 [fVidQualityMatrix isEnabled]];
4180 [fVidTwoPassCheck setState: NSOffState];
4181 [fVidTurboPassCheck setHidden: YES];
4182 [fVidTurboPassCheck setState: NSOffState];
4185 [self qualitySliderChanged: sender];
4186 [self calculateBitrate: sender];
4187 [self customSettingUsed: sender];
4190 /* Use this method to setup the quality slider for cq/rf values depending on
4191 * the video encoder selected.
4193 - (void) setupQualitySlider
4195 /* Get the current slider maxValue to check for a change in slider scale later
4196 * so that we can choose a new similar value on the new slider scale */
4197 float previousMaxValue = [fVidQualitySlider maxValue];
4198 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4199 NSString * qpRFLabelString = @"QP:";
4201 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4203 [fVidQualitySlider setMinValue:0.0];
4204 [fVidQualitySlider setMaxValue:51.0];
4205 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4206 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4207 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4208 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0)
4210 qpRFLabelString = @"RF:";
4213 /* ffmpeg and xvid 1-31 */
4214 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG || [[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_XVID)
4216 [fVidQualitySlider setMinValue:1.0];
4217 [fVidQualitySlider setMaxValue:31.0];
4218 [fVidQualitySlider setNumberOfTickMarks:31];
4221 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4223 [fVidQualitySlider setMinValue:0.0];
4224 [fVidQualitySlider setMaxValue:63.0];
4225 [fVidQualitySlider setNumberOfTickMarks:64];
4227 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4229 /* check to see if we have changed slider scales */
4230 if (previousMaxValue != [fVidQualitySlider maxValue])
4232 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4233 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4234 [fVidQualitySlider setFloatValue:rf];
4237 [self qualitySliderChanged:nil];
4240 - (IBAction) qualitySliderChanged: (id) sender
4242 /* Our constant quality slider is in a range based
4243 * on each encoders qp/rf values. The range depends
4244 * on the encoder. Also, the range is inverse of quality
4245 * for all of the encoders *except* for theora
4246 * (ie. as the "quality" goes up, the cq or rf value
4247 * actually goes down). Since the IB sliders always set
4248 * their max value at the right end of the slider, we
4249 * will calculate the inverse, so as the slider floatValue
4250 * goes up, we will show the inverse in the rf field
4251 * so, the floatValue at the right for x264 would be 51
4252 * and our rf field needs to show 0 and vice versa.
4255 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4256 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4257 float sliderRfToPercent;
4258 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4260 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4261 sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4265 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4266 sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4268 [fVidConstantCell setTitle: [NSString stringWithFormat:
4269 NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
4271 [self customSettingUsed: sender];
4274 - (void) controlTextDidChange: (NSNotification *) notification
4276 [self calculateBitrate:nil];
4279 - (IBAction) calculateBitrate: (id) sender
4281 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4286 hb_list_t * list = hb_get_titles( fHandle );
4287 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4288 [fSrcTitlePopUp indexOfSelectedItem] );
4289 hb_job_t * job = title->job;
4290 hb_audio_config_t * audio;
4291 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4292 * Target Size Field, we also need the job info for the Muxer, the Chapters
4293 * as well as all of the audio track info.
4294 * This used to be accomplished by simply calling prepareJob here, however
4295 * since the resilient queue sets the queue array values instead of the job
4296 * values directly, we duplicate the old prepareJob code here for the variables
4299 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4300 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4301 job->mux = [[fDstFormatPopUp selectedItem] tag];
4303 /* Audio goes here */
4304 int audiotrack_count = hb_list_count(job->list_audio);
4305 for( int i = 0; i < audiotrack_count;i++)
4307 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4308 hb_list_rem(job->list_audio, temp_audio);
4310 /* Now we need our audio info here for each track if applicable */
4311 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4313 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4314 hb_audio_config_init(audio);
4315 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4316 /* We go ahead and assign values to our audio->out.<properties> */
4317 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4318 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4319 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4320 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4321 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4322 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4324 hb_audio_add( job, audio );
4327 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4329 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4330 hb_audio_config_init(audio);
4331 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4332 /* We go ahead and assign values to our audio->out.<properties> */
4333 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4334 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4335 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4336 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4337 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4338 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4340 hb_audio_add( job, audio );
4345 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4347 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4348 hb_audio_config_init(audio);
4349 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4350 /* We go ahead and assign values to our audio->out.<properties> */
4351 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4352 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
4353 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
4354 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
4355 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
4356 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
4358 hb_audio_add( job, audio );
4363 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4365 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4366 hb_audio_config_init(audio);
4367 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4368 /* We go ahead and assign values to our audio->out.<properties> */
4369 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4370 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
4371 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
4372 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
4373 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
4374 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
4376 hb_audio_add( job, audio );
4381 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
4385 #pragma mark - Picture
4387 /* lets set the picture size back to the max from right after title scan
4388 Lets use an IBAction here as down the road we could always use a checkbox
4389 in the gui to easily take the user back to max. Remember, the compiler
4390 resolves IBActions down to -(void) during compile anyway */
4391 - (IBAction) revertPictureSizeToMax: (id) sender
4393 hb_job_t * job = fTitle->job;
4394 /* Here we apply the title source and height */
4395 job->width = fTitle->width;
4396 job->height = fTitle->height;
4398 [self calculatePictureSizing: sender];
4399 /* We call method to change UI to reflect whether a preset is used or not*/
4400 [self customSettingUsed: sender];
4404 * Registers changes made in the Picture Settings Window.
4407 - (void)pictureSettingsDidChange
4409 [self calculatePictureSizing:nil];
4412 /* Get and Display Current Pic Settings in main window */
4413 - (IBAction) calculatePictureSizing: (id) sender
4415 if (fTitle->job->anamorphic.mode > 0)
4417 fTitle->job->keep_ratio = 0;
4420 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
4422 NSString *picCropping;
4423 /* Set the display field for crop as per boolean */
4424 if (![fPictureController autoCrop])
4426 picCropping = @"Custom";
4430 picCropping = @"Auto";
4432 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]]];
4434 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
4436 NSString *videoFilters;
4439 if ([fPictureController detelecine] == 1)
4441 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
4443 else if ([fPictureController detelecine] == 2)
4445 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
4449 if ([fPictureController useDecomb] == 1)
4452 if ([fPictureController decomb] == 1)
4454 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
4456 else if ([fPictureController decomb] == 2)
4458 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
4464 if ([fPictureController deinterlace] > 0)
4466 fTitle->job->deinterlace = 1;
4470 fTitle->job->deinterlace = 0;
4473 if ([fPictureController deinterlace] == 1)
4475 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
4477 else if ([fPictureController deinterlace] == 2)
4479 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
4481 else if ([fPictureController deinterlace] == 3)
4483 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
4485 else if ([fPictureController deinterlace] == 4)
4487 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
4493 if ([fPictureController denoise] == 1)
4495 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
4497 else if ([fPictureController denoise] == 2)
4499 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
4501 else if ([fPictureController denoise] == 3)
4503 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
4505 else if ([fPictureController denoise] == 4)
4507 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
4511 if ([fPictureController deblock] > 0)
4513 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
4517 if ([fPictureController grayscale])
4519 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
4521 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
4523 //[fPictureController reloadStillPreview];
4528 #pragma mark - Audio and Subtitles
4529 - (IBAction) audioCodecsPopUpChanged: (id) sender
4532 NSPopUpButton * audiotrackPopUp;
4533 NSPopUpButton * sampleratePopUp;
4534 NSPopUpButton * bitratePopUp;
4535 NSPopUpButton * audiocodecPopUp;
4536 if (sender == fAudTrack1CodecPopUp)
4538 audiotrackPopUp = fAudLang1PopUp;
4539 audiocodecPopUp = fAudTrack1CodecPopUp;
4540 sampleratePopUp = fAudTrack1RatePopUp;
4541 bitratePopUp = fAudTrack1BitratePopUp;
4543 else if (sender == fAudTrack2CodecPopUp)
4545 audiotrackPopUp = fAudLang2PopUp;
4546 audiocodecPopUp = fAudTrack2CodecPopUp;
4547 sampleratePopUp = fAudTrack2RatePopUp;
4548 bitratePopUp = fAudTrack2BitratePopUp;
4550 else if (sender == fAudTrack3CodecPopUp)
4552 audiotrackPopUp = fAudLang3PopUp;
4553 audiocodecPopUp = fAudTrack3CodecPopUp;
4554 sampleratePopUp = fAudTrack3RatePopUp;
4555 bitratePopUp = fAudTrack3BitratePopUp;
4559 audiotrackPopUp = fAudLang4PopUp;
4560 audiocodecPopUp = fAudTrack4CodecPopUp;
4561 sampleratePopUp = fAudTrack4RatePopUp;
4562 bitratePopUp = fAudTrack4BitratePopUp;
4565 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
4566 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4567 [self audioTrackPopUpChanged: audiotrackPopUp];
4571 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
4573 /* We will be setting the enabled/disabled state of each tracks audio controls based on
4574 * the settings of the source audio for that track. We leave the samplerate and bitrate
4575 * to audiotrackMixdownChanged
4578 /* We will first verify that a lower track number has been selected before enabling each track
4579 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
4581 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4583 [fAudLang2PopUp setEnabled: NO];
4584 [fAudLang2PopUp selectItemAtIndex: 0];
4588 [fAudLang2PopUp setEnabled: YES];
4591 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4593 [fAudLang3PopUp setEnabled: NO];
4594 [fAudLang3PopUp selectItemAtIndex: 0];
4598 [fAudLang3PopUp setEnabled: YES];
4600 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4602 [fAudLang4PopUp setEnabled: NO];
4603 [fAudLang4PopUp selectItemAtIndex: 0];
4607 [fAudLang4PopUp setEnabled: YES];
4609 /* enable/disable the mixdown text and popupbutton for audio track 1 */
4610 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4611 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4612 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4613 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4614 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4615 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4616 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4618 [fAudTrack1CodecPopUp removeAllItems];
4619 [fAudTrack1MixPopUp removeAllItems];
4620 [fAudTrack1RatePopUp removeAllItems];
4621 [fAudTrack1BitratePopUp removeAllItems];
4622 [fAudTrack1DrcSlider setFloatValue: 1.00];
4623 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4625 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4627 [fAudTrack1RatePopUp setEnabled: NO];
4628 [fAudTrack1BitratePopUp setEnabled: NO];
4629 [fAudTrack1DrcSlider setEnabled: NO];
4630 [fAudTrack1DrcField setEnabled: NO];
4633 /* enable/disable the mixdown text and popupbutton for audio track 2 */
4634 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4635 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4636 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4637 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4638 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4639 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4640 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4642 [fAudTrack2CodecPopUp removeAllItems];
4643 [fAudTrack2MixPopUp removeAllItems];
4644 [fAudTrack2RatePopUp removeAllItems];
4645 [fAudTrack2BitratePopUp removeAllItems];
4646 [fAudTrack2DrcSlider setFloatValue: 1.00];
4647 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
4649 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4651 [fAudTrack2RatePopUp setEnabled: NO];
4652 [fAudTrack2BitratePopUp setEnabled: NO];
4653 [fAudTrack2DrcSlider setEnabled: NO];
4654 [fAudTrack2DrcField setEnabled: NO];
4657 /* enable/disable the mixdown text and popupbutton for audio track 3 */
4658 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4659 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4660 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4661 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4662 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4663 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4664 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4666 [fAudTrack3CodecPopUp removeAllItems];
4667 [fAudTrack3MixPopUp removeAllItems];
4668 [fAudTrack3RatePopUp removeAllItems];
4669 [fAudTrack3BitratePopUp removeAllItems];
4670 [fAudTrack3DrcSlider setFloatValue: 1.00];
4671 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
4673 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4675 [fAudTrack3RatePopUp setEnabled: NO];
4676 [fAudTrack3BitratePopUp setEnabled: NO];
4677 [fAudTrack3DrcSlider setEnabled: NO];
4678 [fAudTrack3DrcField setEnabled: NO];
4681 /* enable/disable the mixdown text and popupbutton for audio track 4 */
4682 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4683 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4684 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4685 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4686 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4687 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4688 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
4690 [fAudTrack4CodecPopUp removeAllItems];
4691 [fAudTrack4MixPopUp removeAllItems];
4692 [fAudTrack4RatePopUp removeAllItems];
4693 [fAudTrack4BitratePopUp removeAllItems];
4694 [fAudTrack4DrcSlider setFloatValue: 1.00];
4695 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
4697 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4699 [fAudTrack4RatePopUp setEnabled: NO];
4700 [fAudTrack4BitratePopUp setEnabled: NO];
4701 [fAudTrack4DrcSlider setEnabled: NO];
4702 [fAudTrack4DrcField setEnabled: NO];
4707 - (IBAction) addAllAudioTracksToPopUp: (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 hb_audio_config_t * audio;
4716 [sender removeAllItems];
4717 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
4718 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
4720 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
4721 [[sender menu] addItemWithTitle:
4722 [NSString stringWithCString: audio->lang.description]
4723 action: NULL keyEquivalent: @""];
4725 [sender selectItemAtIndex: 0];
4729 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
4732 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
4733 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
4734 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
4735 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
4737 if (searchPrefixString)
4740 for( int i = 0; i < [sender numberOfItems]; i++ )
4742 /* Try to find the desired search string */
4743 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
4745 [sender selectItemAtIndex: i];
4749 /* couldn't find the string, so select the requested "search string not found" item */
4750 /* index of 0 means select the "none" item */
4751 /* index of 1 means select the first audio track */
4752 [sender selectItemAtIndex: selectIndexIfNotFound];
4756 /* if no search string is provided, then select the selectIndexIfNotFound item */
4757 [sender selectItemAtIndex: selectIndexIfNotFound];
4761 - (IBAction) audioAddAudioTrackCodecs: (id)sender
4763 int format = [fDstFormatPopUp indexOfSelectedItem];
4765 /* setup pointers to the appropriate popups for the correct track */
4766 NSPopUpButton * audiocodecPopUp;
4767 NSPopUpButton * audiotrackPopUp;
4768 if (sender == fAudTrack1CodecPopUp)
4770 audiotrackPopUp = fAudLang1PopUp;
4771 audiocodecPopUp = fAudTrack1CodecPopUp;
4773 else if (sender == fAudTrack2CodecPopUp)
4775 audiotrackPopUp = fAudLang2PopUp;
4776 audiocodecPopUp = fAudTrack2CodecPopUp;
4778 else if (sender == fAudTrack3CodecPopUp)
4780 audiotrackPopUp = fAudLang3PopUp;
4781 audiocodecPopUp = fAudTrack3CodecPopUp;
4785 audiotrackPopUp = fAudLang4PopUp;
4786 audiocodecPopUp = fAudTrack4CodecPopUp;
4789 [audiocodecPopUp removeAllItems];
4790 /* Make sure "None" isnt selected in the source track */
4791 if ([audiotrackPopUp indexOfSelectedItem] > 0)
4793 [audiocodecPopUp setEnabled:YES];
4794 NSMenuItem *menuItem;
4795 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
4801 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4802 [menuItem setTag: HB_ACODEC_FAAC];
4805 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4806 [menuItem setTag: HB_ACODEC_AC3];
4812 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4813 [menuItem setTag: HB_ACODEC_FAAC];
4815 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4816 [menuItem setTag: HB_ACODEC_AC3];
4818 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4819 [menuItem setTag: HB_ACODEC_LAME];
4821 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4822 [menuItem setTag: HB_ACODEC_VORBIS];
4828 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4829 [menuItem setTag: HB_ACODEC_LAME];
4831 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4832 [menuItem setTag: HB_ACODEC_AC3];
4838 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4839 [menuItem setTag: HB_ACODEC_VORBIS];
4841 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4842 [menuItem setTag: HB_ACODEC_LAME];
4845 [audiocodecPopUp selectItemAtIndex:0];
4849 [audiocodecPopUp setEnabled:NO];
4853 - (IBAction) audioTrackPopUpChanged: (id) sender
4855 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
4856 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
4859 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
4862 /* make sure we have a selected title before continuing */
4863 if (fTitle == NULL) return;
4864 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
4865 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
4867 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
4869 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4871 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
4873 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4875 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
4877 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4879 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
4881 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4884 /* Now lets make the sender the appropriate Audio Track popup from this point on */
4885 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
4887 sender = fAudLang1PopUp;
4889 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
4891 sender = fAudLang2PopUp;
4893 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
4895 sender = fAudLang3PopUp;
4897 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
4899 sender = fAudLang4PopUp;
4902 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
4903 NSPopUpButton * mixdownPopUp;
4904 NSPopUpButton * audiocodecPopUp;
4905 NSPopUpButton * sampleratePopUp;
4906 NSPopUpButton * bitratePopUp;
4907 if (sender == fAudLang1PopUp)
4909 mixdownPopUp = fAudTrack1MixPopUp;
4910 audiocodecPopUp = fAudTrack1CodecPopUp;
4911 sampleratePopUp = fAudTrack1RatePopUp;
4912 bitratePopUp = fAudTrack1BitratePopUp;
4914 else if (sender == fAudLang2PopUp)
4916 mixdownPopUp = fAudTrack2MixPopUp;
4917 audiocodecPopUp = fAudTrack2CodecPopUp;
4918 sampleratePopUp = fAudTrack2RatePopUp;
4919 bitratePopUp = fAudTrack2BitratePopUp;
4921 else if (sender == fAudLang3PopUp)
4923 mixdownPopUp = fAudTrack3MixPopUp;
4924 audiocodecPopUp = fAudTrack3CodecPopUp;
4925 sampleratePopUp = fAudTrack3RatePopUp;
4926 bitratePopUp = fAudTrack3BitratePopUp;
4930 mixdownPopUp = fAudTrack4MixPopUp;
4931 audiocodecPopUp = fAudTrack4CodecPopUp;
4932 sampleratePopUp = fAudTrack4RatePopUp;
4933 bitratePopUp = fAudTrack4BitratePopUp;
4936 /* get the index of the selected audio Track*/
4937 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
4939 /* pointer for the hb_audio_s struct we will use later on */
4940 hb_audio_config_t * audio;
4943 /* check if the audio mixdown controls need their enabled state changing */
4944 [self setEnabledStateOfAudioMixdownControls:nil];
4946 if (thisAudioIndex != -1)
4950 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
4952 /* actually manipulate the proper mixdowns here */
4953 /* delete the previous audio mixdown options */
4954 [mixdownPopUp removeAllItems];
4956 acodec = [[audiocodecPopUp selectedItem] tag];
4961 /* find out if our selected output audio codec supports mono and / or 6ch */
4962 /* we also check for an input codec of AC3 or DCA,
4963 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
4964 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
4965 but this may change in the future, so they are separated for flexibility */
4966 int audioCodecsSupportMono =
4967 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4968 (acodec != HB_ACODEC_LAME);
4969 int audioCodecsSupport6Ch =
4970 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4971 (acodec != HB_ACODEC_LAME);
4973 /* check for AC-3 passthru */
4974 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4977 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4978 [NSString stringWithCString: "AC3 Passthru"]
4979 action: NULL keyEquivalent: @""];
4980 [menuItem setTag: HB_ACODEC_AC3];
4985 /* add the appropriate audio mixdown menuitems to the popupbutton */
4986 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
4987 so that we can reference the mixdown later */
4989 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
4990 int minMixdownUsed = 0;
4991 int maxMixdownUsed = 0;
4993 /* get the input channel layout without any lfe channels */
4994 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4996 /* do we want to add a mono option? */
4997 if (audioCodecsSupportMono == 1)
4999 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5000 [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
5001 action: NULL keyEquivalent: @""];
5002 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5003 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5004 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5007 /* do we want to add a stereo option? */
5008 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5009 /* also offer stereo if we have a stereo-or-better source */
5010 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5012 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5013 [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
5014 action: NULL keyEquivalent: @""];
5015 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5016 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5017 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5020 /* do we want to add a dolby surround (DPL1) option? */
5021 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5023 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5024 [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
5025 action: NULL keyEquivalent: @""];
5026 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5027 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5028 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5031 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5032 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5034 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5035 [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
5036 action: NULL keyEquivalent: @""];
5037 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5038 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5039 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5042 /* do we want to add a 6-channel discrete option? */
5043 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5045 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5046 [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
5047 action: NULL keyEquivalent: @""];
5048 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5049 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5050 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5053 /* do we want to add an AC-3 passthrough option? */
5054 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5056 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5057 [NSString stringWithCString: hb_audio_mixdowns[5].human_readable_name]
5058 action: NULL keyEquivalent: @""];
5059 [menuItem setTag: HB_ACODEC_AC3];
5060 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5061 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5064 /* auto-select the best mixdown based on our saved mixdown preference */
5066 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5067 /* ultimately this should be a prefs option */
5070 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5071 if (mixdownToUse > 0)
5073 useMixdown = mixdownToUse;
5077 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5080 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5081 if (useMixdown > maxMixdownUsed)
5083 useMixdown = maxMixdownUsed;
5086 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5087 if (useMixdown < minMixdownUsed)
5089 useMixdown = minMixdownUsed;
5092 /* select the (possibly-amended) preferred mixdown */
5093 [mixdownPopUp selectItemWithTag: useMixdown];
5096 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5097 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5100 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5102 /* If we are using the avi container, we select MP3 as there is no aac available*/
5103 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5105 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5109 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5112 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5113 [self audioTrackMixdownChanged: mixdownPopUp];
5117 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5119 [self autoSetM4vExtension: sender];
5123 - (IBAction) audioTrackMixdownChanged: (id) sender
5127 /* setup pointers to all of the other audio track controls
5128 * we will need later
5130 NSPopUpButton * mixdownPopUp;
5131 NSPopUpButton * sampleratePopUp;
5132 NSPopUpButton * bitratePopUp;
5133 NSPopUpButton * audiocodecPopUp;
5134 NSPopUpButton * audiotrackPopUp;
5135 NSSlider * drcSlider;
5136 NSTextField * drcField;
5137 if (sender == fAudTrack1MixPopUp)
5139 audiotrackPopUp = fAudLang1PopUp;
5140 audiocodecPopUp = fAudTrack1CodecPopUp;
5141 mixdownPopUp = fAudTrack1MixPopUp;
5142 sampleratePopUp = fAudTrack1RatePopUp;
5143 bitratePopUp = fAudTrack1BitratePopUp;
5144 drcSlider = fAudTrack1DrcSlider;
5145 drcField = fAudTrack1DrcField;
5147 else if (sender == fAudTrack2MixPopUp)
5149 audiotrackPopUp = fAudLang2PopUp;
5150 audiocodecPopUp = fAudTrack2CodecPopUp;
5151 mixdownPopUp = fAudTrack2MixPopUp;
5152 sampleratePopUp = fAudTrack2RatePopUp;
5153 bitratePopUp = fAudTrack2BitratePopUp;
5154 drcSlider = fAudTrack2DrcSlider;
5155 drcField = fAudTrack2DrcField;
5157 else if (sender == fAudTrack3MixPopUp)
5159 audiotrackPopUp = fAudLang3PopUp;
5160 audiocodecPopUp = fAudTrack3CodecPopUp;
5161 mixdownPopUp = fAudTrack3MixPopUp;
5162 sampleratePopUp = fAudTrack3RatePopUp;
5163 bitratePopUp = fAudTrack3BitratePopUp;
5164 drcSlider = fAudTrack3DrcSlider;
5165 drcField = fAudTrack3DrcField;
5169 audiotrackPopUp = fAudLang4PopUp;
5170 audiocodecPopUp = fAudTrack4CodecPopUp;
5171 mixdownPopUp = fAudTrack4MixPopUp;
5172 sampleratePopUp = fAudTrack4RatePopUp;
5173 bitratePopUp = fAudTrack4BitratePopUp;
5174 drcSlider = fAudTrack4DrcSlider;
5175 drcField = fAudTrack4DrcField;
5177 acodec = [[audiocodecPopUp selectedItem] tag];
5178 /* storage variable for the min and max bitrate allowed for this codec */
5184 case HB_ACODEC_FAAC:
5185 /* check if we have a 6ch discrete conversion in either audio track */
5186 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5188 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
5190 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5196 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5198 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5199 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5204 case HB_ACODEC_LAME:
5205 /* Lame is happy using our min bitrate of 32 kbps */
5207 /* Lame won't encode if the bitrate is higher than 320 kbps */
5211 case HB_ACODEC_VORBIS:
5212 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5214 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5216 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5222 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5224 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5230 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5236 /* make sure we have a selected title before continuing */
5237 if (fTitle == NULL) return;
5238 /* get the audio so we can find out what input rates are*/
5239 hb_audio_config_t * audio;
5240 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5241 int inputbitrate = audio->in.bitrate / 1000;
5242 int inputsamplerate = audio->in.samplerate;
5244 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3)
5246 [bitratePopUp removeAllItems];
5248 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5250 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5252 /* add a new menuitem for this bitrate */
5253 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5254 [NSString stringWithCString: hb_audio_bitrates[i].string]
5255 action: NULL keyEquivalent: @""];
5256 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5257 [menuItem setTag: hb_audio_bitrates[i].rate];
5261 /* select the default bitrate (but use 384 for 6-ch AAC) */
5262 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5264 [bitratePopUp selectItemWithTag: 384];
5268 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5271 /* populate and set the sample rate popup */
5272 /* Audio samplerate */
5273 [sampleratePopUp removeAllItems];
5274 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5275 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5276 [menuItem setTag: inputsamplerate];
5278 for( int i = 0; i < hb_audio_rates_count; i++ )
5280 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5281 [NSString stringWithCString: hb_audio_rates[i].string]
5282 action: NULL keyEquivalent: @""];
5283 [menuItem setTag: hb_audio_rates[i].rate];
5285 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5286 * and there is no compelling reason to use anything else as default, though the users default
5287 * preset will likely override any setting chosen here.
5289 [sampleratePopUp selectItemWithTag: inputsamplerate];
5292 /* Since AC3 Pass Thru uses the input ac3 bitrate and sample rate, we get the input tracks
5293 * bitrate and dispay it in the bitrate popup even though libhb happily ignores any bitrate input from
5294 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
5296 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3)
5299 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
5300 [bitratePopUp removeAllItems];
5301 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5302 [NSString stringWithFormat:@"%d", inputbitrate]
5303 action: NULL keyEquivalent: @""];
5304 [menuItem setTag: inputbitrate];
5305 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
5306 [bitratePopUp setEnabled: NO];
5307 [sampleratePopUp setEnabled: NO];
5309 [drcSlider setFloatValue: 1.00];
5310 [self audioDRCSliderChanged: drcSlider];
5311 [drcSlider setEnabled: NO];
5312 [drcField setEnabled: NO];
5316 [sampleratePopUp setEnabled: YES];
5317 [bitratePopUp setEnabled: YES];
5318 [drcSlider setEnabled: YES];
5319 [drcField setEnabled: YES];
5321 [self calculateBitrate:nil];
5324 - (IBAction) audioDRCSliderChanged: (id) sender
5326 NSSlider * drcSlider;
5327 NSTextField * drcField;
5328 if (sender == fAudTrack1DrcSlider)
5330 drcSlider = fAudTrack1DrcSlider;
5331 drcField = fAudTrack1DrcField;
5333 else if (sender == fAudTrack2DrcSlider)
5335 drcSlider = fAudTrack2DrcSlider;
5336 drcField = fAudTrack2DrcField;
5338 else if (sender == fAudTrack3DrcSlider)
5340 drcSlider = fAudTrack3DrcSlider;
5341 drcField = fAudTrack3DrcField;
5345 drcSlider = fAudTrack4DrcSlider;
5346 drcField = fAudTrack4DrcField;
5349 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
5350 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
5352 [drcSlider setFloatValue:1.0];
5356 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
5357 /* For now, do not call this until we have an intelligent way to determine audio track selections
5358 * compared to presets
5360 //[self customSettingUsed: sender];
5363 - (IBAction) subtitleSelectionChanged: (id) sender
5365 if ([fSubPopUp indexOfSelectedItem] == 0)
5367 [fSubForcedCheck setState: NSOffState];
5368 [fSubForcedCheck setEnabled: NO];
5372 [fSubForcedCheck setEnabled: YES];
5381 #pragma mark Open New Windows
5383 - (IBAction) openHomepage: (id) sender
5385 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5386 URLWithString:@"http://handbrake.fr/"]];
5389 - (IBAction) openForums: (id) sender
5391 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5392 URLWithString:@"http://handbrake.fr/forum/"]];
5394 - (IBAction) openUserGuide: (id) sender
5396 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5397 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
5401 * Shows debug output window.
5403 - (IBAction)showDebugOutputPanel:(id)sender
5405 [outputPanel showOutputPanel:sender];
5409 * Shows preferences window.
5411 - (IBAction) showPreferencesWindow: (id) sender
5413 NSWindow * window = [fPreferencesController window];
5414 if (![window isVisible])
5417 [window makeKeyAndOrderFront: nil];
5421 * Shows queue window.
5423 - (IBAction) showQueueWindow:(id)sender
5425 [fQueueController showQueueWindow:sender];
5429 - (IBAction) toggleDrawer:(id)sender {
5430 [fPresetDrawer toggle:self];
5434 * Shows Picture Settings Window.
5437 - (IBAction) showPicturePanel: (id) sender
5439 [fPictureController showPictureWindow:sender];
5442 - (void) picturePanelFullScreen
5444 [fPictureController setToFullScreenMode];
5447 - (void) picturePanelWindowed
5449 [fPictureController setToWindowedMode];
5452 - (IBAction) showPreviewWindow: (id) sender
5454 [fPictureController showPreviewWindow:sender];
5458 #pragma mark Preset Outline View Methods
5459 #pragma mark - Required
5460 /* These are required by the NSOutlineView Datasource Delegate */
5463 /* used to specify the number of levels to show for each item */
5464 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
5466 /* currently use no levels to test outline view viability */
5467 if (item == nil) // for an outline view the root level of the hierarchy is always nil
5469 return [UserPresets count];
5473 /* we need to return the count of the array in ChildrenArray for this folder */
5474 NSArray *children = nil;
5475 children = [item objectForKey:@"ChildrenArray"];
5476 if ([children count] > 0)
5478 return [children count];
5487 /* We use this to deterimine children of an item */
5488 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
5491 /* we need to return the count of the array in ChildrenArray for this folder */
5492 NSArray *children = nil;
5495 children = UserPresets;
5499 if ([item objectForKey:@"ChildrenArray"])
5501 children = [item objectForKey:@"ChildrenArray"];
5504 if ((children == nil) || ( [children count] <= (NSUInteger) index))
5510 return [children objectAtIndex:index];
5514 // We are only one level deep, so we can't be asked about children
5515 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
5519 /* We use this to determine if an item should be expandable */
5520 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
5523 /* we need to return the count of the array in ChildrenArray for this folder */
5524 NSArray *children= nil;
5527 children = UserPresets;
5531 if ([item objectForKey:@"ChildrenArray"])
5533 children = [item objectForKey:@"ChildrenArray"];
5537 /* To deterimine if an item should show a disclosure triangle
5538 * we could do it by the children count as so:
5539 * if ([children count] < 1)
5540 * However, lets leave the triangle show even if there are no
5541 * children to help indicate a folder, just like folder in the
5542 * finder can show a disclosure triangle even when empty
5545 /* We need to determine if the item is a folder */
5546 if ([[item objectForKey:@"Folder"] intValue] == 1)
5557 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
5559 // Our outline view has no levels, but we can still expand every item. Doing so
5560 // just makes the row taller. See heightOfRowByItem below.
5561 //return ![(HBQueueOutlineView*)outlineView isDragging];
5567 /* Used to tell the outline view which information is to be displayed per item */
5568 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5570 /* We have two columns right now, icon and PresetName */
5572 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5574 return [item objectForKey:@"PresetName"];
5583 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
5585 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
5587 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
5589 return [NSKeyedArchiver archivedDataWithRootObject:item];
5592 #pragma mark - Added Functionality (optional)
5593 /* Use to customize the font and display characteristics of the title cell */
5594 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
5596 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5600 NSColor *shadowColor;
5601 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
5602 /*check to see if its a selected row */
5603 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
5606 fontColor = [NSColor blackColor];
5607 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
5611 if ([[item objectForKey:@"Type"] intValue] == 0)
5613 fontColor = [NSColor blueColor];
5615 else // User created preset, use a black font
5617 fontColor = [NSColor blackColor];
5619 /* check to see if its a folder */
5620 //if ([[item objectForKey:@"Folder"] intValue] == 1)
5622 //fontColor = [NSColor greenColor];
5627 /* We use Bold Text for the HB Default */
5628 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
5630 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5632 /* We use Bold Text for the User Specified Default */
5633 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
5635 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5639 [cell setTextColor:fontColor];
5640 [cell setFont:txtFont];
5645 /* We use this to edit the name field in the outline view */
5646 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5648 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5653 [theRecord setObject:object forKey:@"PresetName"];
5657 [fPresetsOutlineView reloadData];
5658 /* We save all of the preset data here */
5662 /* We use this to provide tooltips for the items in the presets outline view */
5663 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
5665 //if ([[tc identifier] isEqualToString:@"PresetName"])
5667 /* initialize the tooltip contents variable */
5669 /* if there is a description for the preset, we show it in the tooltip */
5670 if ([item objectForKey:@"PresetDescription"])
5672 loc_tip = [item objectForKey:@"PresetDescription"];
5677 loc_tip = @"No description available";
5684 #pragma mark Preset Outline View Methods (dragging related)
5687 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
5689 // Dragging is only allowed for custom presets.
5690 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
5691 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
5695 // Don't retain since this is just holding temporaral drag information, and it is
5696 //only used during a drag! We could put this in the pboard actually.
5697 fDraggedNodes = items;
5698 // Provide data for our custom type, and simple NSStrings.
5699 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
5701 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
5702 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
5707 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
5710 // Don't allow dropping ONTO an item since they can't really contain any children.
5712 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
5713 if (isOnDropTypeProposal)
5714 return NSDragOperationNone;
5716 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
5719 index = [fPresetsOutlineView rowForItem: item] + 1;
5723 // Don't allow dropping into the Built In Presets.
5724 if (index < presetCurrentBuiltInCount)
5726 return NSDragOperationNone;
5727 index = MAX (index, presetCurrentBuiltInCount);
5730 [outlineView setDropItem:item dropChildIndex:index];
5731 return NSDragOperationGeneric;
5736 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
5738 /* first, lets see if we are dropping into a folder */
5739 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
5741 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
5742 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
5743 [childrenArray addObject:item];
5744 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
5745 [childrenArray autorelease];
5747 else // We are not, so we just move the preset into the existing array
5749 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
5751 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
5752 while (obj = [enumerator nextObject])
5754 [moveItems addIndex:[UserPresets indexOfObject:obj]];
5756 // Successful drop, lets rearrange the view and save it all
5757 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
5759 [fPresetsOutlineView reloadData];
5764 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
5766 NSUInteger index = [indexSet lastIndex];
5767 NSUInteger aboveInsertIndexCount = 0;
5769 NSUInteger removeIndex;
5771 if (index >= insertIndex)
5773 removeIndex = index + aboveInsertIndexCount;
5774 aboveInsertIndexCount++;
5778 removeIndex = index;
5782 id object = [[array objectAtIndex:removeIndex] retain];
5783 [array removeObjectAtIndex:removeIndex];
5784 [array insertObject:object atIndex:insertIndex];
5787 index = [indexSet indexLessThanIndex:index];
5792 #pragma mark - Functional Preset NSOutlineView Methods
5794 - (IBAction)selectPreset:(id)sender
5797 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
5799 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
5800 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5802 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
5804 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
5808 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5812 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
5813 [self formatPopUpChanged:nil];
5815 /* Chapter Markers*/
5816 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
5817 /* check to see if we have only one chapter */
5818 [self chapterPopUpChanged:nil];
5820 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
5821 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
5822 /* Mux mp4 with http optimization */
5823 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
5826 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
5827 /* We set the advanced opt string here if applicable*/
5828 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
5830 /* Lets run through the following functions to get variables set there */
5831 [self videoEncoderPopUpChanged:nil];
5832 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
5833 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
5834 [self calculateBitrate:nil];
5837 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
5839 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
5840 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
5842 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
5843 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
5844 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
5845 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
5846 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
5847 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
5849 /* For the quality slider we need to convert the old percent's to the new rf scales */
5850 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
5851 [fVidQualitySlider setFloatValue:rf];
5856 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
5859 [self videoMatrixChanged:nil];
5861 /* Video framerate */
5862 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
5863 detected framerate in the fVidRatePopUp so we use index 0*/
5864 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
5866 [fVidRatePopUp selectItemAtIndex: 0];
5870 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
5874 /* 2 Pass Encoding */
5875 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
5876 [self twoPassCheckboxChanged:nil];
5878 /* Turbo 1st pass for 2 Pass Encoding */
5879 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
5883 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
5885 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5887 [fAudLang1PopUp selectItemAtIndex: 1];
5889 [self audioTrackPopUpChanged: fAudLang1PopUp];
5890 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
5891 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5892 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
5893 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5895 if ([fAudTrack1MixPopUp selectedItem] == nil)
5897 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5899 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
5900 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5901 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
5903 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
5905 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
5906 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5908 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
5910 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5912 [fAudLang2PopUp selectItemAtIndex: 1];
5914 [self audioTrackPopUpChanged: fAudLang2PopUp];
5915 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
5916 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5917 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
5918 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5920 if ([fAudTrack2MixPopUp selectedItem] == nil)
5922 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5924 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
5925 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5926 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
5928 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
5930 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
5931 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5933 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
5935 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5937 [fAudLang3PopUp selectItemAtIndex: 1];
5939 [self audioTrackPopUpChanged: fAudLang3PopUp];
5940 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
5941 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5942 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
5943 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5945 if ([fAudTrack3MixPopUp selectedItem] == nil)
5947 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5949 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
5950 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5951 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
5953 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
5955 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
5956 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5958 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
5960 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5962 [fAudLang4PopUp selectItemAtIndex: 1];
5964 [self audioTrackPopUpChanged: fAudLang4PopUp];
5965 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
5966 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5967 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
5968 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5970 if ([fAudTrack4MixPopUp selectedItem] == nil)
5972 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5974 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
5975 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5976 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
5978 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
5980 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
5981 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5984 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
5986 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
5988 [fAudLang2PopUp selectItemAtIndex: 0];
5989 [self audioTrackPopUpChanged: fAudLang2PopUp];
5991 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
5993 [fAudLang3PopUp selectItemAtIndex: 0];
5994 [self audioTrackPopUpChanged: fAudLang3PopUp];
5996 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
5998 [fAudLang4PopUp selectItemAtIndex: 0];
5999 [self audioTrackPopUpChanged: fAudLang4PopUp];
6003 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
6004 /* Forced Subtitles */
6005 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
6007 /* Picture Settings */
6008 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
6009 * height, width, keep ar, anamorphic and crop settings.
6010 * picture filters are handled separately below.
6012 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
6013 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
6014 * preset completely ignores any picture sizing values in the preset.
6016 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
6018 hb_job_t * job = fTitle->job;
6020 /* If Cropping is set to custom, then recall all four crop values from
6021 when the preset was created and apply them */
6022 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
6024 [fPictureController setAutoCrop:NO];
6026 /* Here we use the custom crop values saved at the time the preset was saved */
6027 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
6028 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
6029 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
6030 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
6033 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
6035 [fPictureController setAutoCrop:YES];
6036 /* Here we use the auto crop values determined right after scan */
6037 job->crop[0] = AutoCropTop;
6038 job->crop[1] = AutoCropBottom;
6039 job->crop[2] = AutoCropLeft;
6040 job->crop[3] = AutoCropRight;
6045 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
6046 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
6048 /* Use Max Picture settings for whatever the dvd is.*/
6049 [self revertPictureSizeToMax:nil];
6050 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6051 if (job->keep_ratio == 1)
6053 hb_fix_aspect( job, HB_KEEP_WIDTH );
6054 if( job->height > fTitle->height )
6056 job->height = fTitle->height;
6057 hb_fix_aspect( job, HB_KEEP_HEIGHT );
6060 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
6062 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
6064 /* we check to make sure the presets width/height does not exceed the sources width/height */
6065 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
6067 /* if so, then we use the sources height and width to avoid scaling up */
6068 //job->width = fTitle->width;
6069 //job->height = fTitle->height;
6070 [self revertPictureSizeToMax:nil];
6072 else // source width/height is >= the preset height/width
6074 /* we can go ahead and use the presets values for height and width */
6075 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
6076 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
6078 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6079 if (job->keep_ratio == 1)
6081 hb_fix_aspect( job, HB_KEEP_WIDTH );
6082 if( job->height > fTitle->height )
6084 job->height = fTitle->height;
6085 hb_fix_aspect( job, HB_KEEP_HEIGHT );
6088 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
6094 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
6095 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
6099 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
6100 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
6101 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
6104 [fPictureController setUseDecomb:1];
6105 [fPictureController setDecomb:0];
6106 [fPictureController setDeinterlace:0];
6107 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
6109 /* we are using decomb */
6111 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
6113 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
6115 /* if we are using "Custom" in the decomb setting, also set the custom string*/
6116 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 2)
6118 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
6124 /* We are using Deinterlace */
6126 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
6128 [fPictureController setUseDecomb:0];
6129 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
6130 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
6131 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
6133 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
6140 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
6142 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
6143 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
6144 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 2)
6146 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
6151 [fPictureController setDetelecine:0];
6155 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
6157 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
6158 /* if we are using "Custom" in the denoise setting, also set the custom string*/
6159 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 4)
6161 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
6166 [fPictureController setDenoise:0];
6170 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
6172 /* if its a one, then its the old on/off deblock, set on to 5*/
6173 [fPictureController setDeblock:5];
6177 /* use the settings intValue */
6178 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
6181 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
6183 [fPictureController setGrayscale:1];
6187 [fPictureController setGrayscale:0];
6190 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
6191 [fPictureController SetTitle:fTitle];
6192 [fPictureController SetTitle:fTitle];
6193 [self calculatePictureSizing:nil];
6199 #pragma mark Manage Presets
6201 - (void) loadPresets {
6202 /* We declare the default NSFileManager into fileManager */
6203 NSFileManager * fileManager = [NSFileManager defaultManager];
6204 /*We define the location of the user presets file */
6205 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
6206 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
6207 /* We check for the presets.plist */
6208 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
6210 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
6213 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
6214 if (nil == UserPresets)
6216 UserPresets = [[NSMutableArray alloc] init];
6217 [self addFactoryPresets:nil];
6219 [fPresetsOutlineView reloadData];
6223 - (IBAction) showAddPresetPanel: (id) sender
6225 /* Deselect the currently selected Preset if there is one*/
6226 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
6228 /* Populate the preset picture settings popup here */
6229 [fPresetNewPicSettingsPopUp removeAllItems];
6230 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
6231 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
6232 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
6233 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
6234 /* Uncheck the preset use filters checkbox */
6235 [fPresetNewPicFiltersCheck setState:NSOffState];
6236 // fPresetNewFolderCheck
6237 [fPresetNewFolderCheck setState:NSOffState];
6238 /* Erase info from the input fields*/
6239 [fPresetNewName setStringValue: @""];
6240 [fPresetNewDesc setStringValue: @""];
6241 /* Show the panel */
6242 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
6245 - (IBAction) closeAddPresetPanel: (id) sender
6247 [NSApp endSheet: fAddPresetPanel];
6248 [fAddPresetPanel orderOut: self];
6251 - (IBAction)addUserPreset:(id)sender
6253 if (![[fPresetNewName stringValue] length])
6254 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
6257 /* Here we create a custom user preset */
6258 [UserPresets addObject:[self createPreset]];
6261 [self closeAddPresetPanel:nil];
6268 /* We Reload the New Table data for presets */
6269 [fPresetsOutlineView reloadData];
6270 /* We save all of the preset data here */
6278 /* We Sort the Presets By Factory or Custom */
6279 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
6280 ascending:YES] autorelease];
6281 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
6283 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
6284 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
6285 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
6288 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
6289 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
6290 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
6291 [UserPresets setArray:sortedArray];
6296 - (IBAction)insertPreset:(id)sender
6298 int index = [fPresetsOutlineView selectedRow];
6299 [UserPresets insertObject:[self createPreset] atIndex:index];
6300 [fPresetsOutlineView reloadData];
6304 - (NSDictionary *)createPreset
6306 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
6307 /* Get the New Preset Name from the field in the AddPresetPanel */
6308 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
6309 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
6310 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
6311 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
6312 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
6313 /*Set whether or not this is default, at creation set to 0*/
6314 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6315 if ([fPresetNewFolderCheck state] == YES)
6317 /* initialize and set an empty array for children here since we are a new folder */
6318 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6319 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6320 [childrenArray autorelease];
6322 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
6324 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
6325 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
6326 /* Get whether or not to use the current Picture Filter settings for the preset */
6327 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
6329 /* Get New Preset Description from the field in the AddPresetPanel*/
6330 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
6332 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
6333 /* Chapter Markers fCreateChapterMarkers*/
6334 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
6335 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6336 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
6337 /* Mux mp4 with http optimization */
6338 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
6339 /* Add iPod uuid atom */
6340 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
6344 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
6345 /* x264 Option String */
6346 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
6348 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
6349 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
6350 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
6351 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
6353 /* Video framerate */
6354 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
6356 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
6358 else // we can record the actual titleOfSelectedItem
6360 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
6363 /* 2 Pass Encoding */
6364 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
6365 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
6366 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
6367 /*Picture Settings*/
6368 hb_job_t * job = fTitle->job;
6369 /* Picture Sizing */
6370 /* Use Max Picture settings for whatever the dvd is.*/
6371 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
6372 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
6373 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
6374 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
6375 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
6377 /* Set crop settings here */
6378 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
6379 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
6380 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
6381 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
6382 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
6384 /* Picture Filters */
6385 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
6386 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
6387 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
6388 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
6389 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
6390 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
6391 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
6392 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
6393 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
6394 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
6395 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
6399 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
6401 [preset setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
6402 [preset setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
6403 [preset setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
6404 [preset setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
6405 [preset setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
6406 [preset setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
6407 [preset setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
6409 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
6411 [preset setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
6412 [preset setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
6413 [preset setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
6414 [preset setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
6415 [preset setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
6416 [preset setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
6417 [preset setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
6419 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
6421 [preset setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
6422 [preset setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
6423 [preset setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
6424 [preset setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
6425 [preset setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
6426 [preset setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
6427 [preset setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
6429 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
6431 [preset setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
6432 [preset setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
6433 [preset setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
6434 [preset setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
6435 [preset setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
6436 [preset setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
6437 [preset setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
6441 [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
6442 /* Forced Subtitles */
6443 [preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
6445 [preset autorelease];
6452 [UserPresets writeToFile:UserPresetsFile atomically:YES];
6453 /* We get the default preset in case it changed */
6454 [self getDefaultPresets:nil];
6458 - (IBAction)deletePreset:(id)sender
6462 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
6466 /* Alert user before deleting preset */
6468 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
6470 if ( status == NSAlertDefaultReturn )
6472 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6473 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6474 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6476 NSEnumerator *enumerator;
6477 NSMutableArray *presetsArrayToMod;
6478 NSMutableArray *tempArray;
6480 /* If we are a root level preset, we are modding the UserPresets array */
6481 if (presetToModLevel == 0)
6483 presetsArrayToMod = UserPresets;
6485 else // We have a parent preset, so we modify the chidren array object for key
6487 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6490 enumerator = [presetsArrayToMod objectEnumerator];
6491 tempArray = [NSMutableArray array];
6493 while (tempObject = [enumerator nextObject])
6495 NSDictionary *thisPresetDict = tempObject;
6496 if (thisPresetDict == presetToMod)
6498 [tempArray addObject:tempObject];
6502 [presetsArrayToMod removeObjectsInArray:tempArray];
6503 [fPresetsOutlineView reloadData];
6509 #pragma mark Manage Default Preset
6511 - (IBAction)getDefaultPresets:(id)sender
6513 presetHbDefault = nil;
6514 presetUserDefault = nil;
6515 presetUserDefaultParent = nil;
6516 presetUserDefaultParentParent = nil;
6517 NSMutableDictionary *presetHbDefaultParent = nil;
6518 NSMutableDictionary *presetHbDefaultParentParent = nil;
6521 BOOL userDefaultFound = NO;
6522 presetCurrentBuiltInCount = 0;
6523 /* First we iterate through the root UserPresets array to check for defaults */
6524 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6526 while (tempObject = [enumerator nextObject])
6528 NSMutableDictionary *thisPresetDict = tempObject;
6529 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6531 presetHbDefault = thisPresetDict;
6533 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6535 presetUserDefault = thisPresetDict;
6536 userDefaultFound = YES;
6538 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
6540 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
6544 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6545 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6547 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
6548 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6550 while (tempObject = [enumerator nextObject])
6552 NSMutableDictionary *thisPresetDict = tempObject;
6553 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6555 presetHbDefault = thisPresetDict;
6556 presetHbDefaultParent = thisPresetDictParent;
6558 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6560 presetUserDefault = thisPresetDict;
6561 presetUserDefaultParent = thisPresetDictParent;
6562 userDefaultFound = YES;
6565 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6566 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6568 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
6569 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6571 while (tempObject = [enumerator nextObject])
6573 NSMutableDictionary *thisPresetDict = tempObject;
6574 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6576 presetHbDefault = thisPresetDict;
6577 presetHbDefaultParent = thisPresetDictParent;
6578 presetHbDefaultParentParent = thisPresetDictParentParent;
6580 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6582 presetUserDefault = thisPresetDict;
6583 presetUserDefaultParent = thisPresetDictParent;
6584 presetUserDefaultParentParent = thisPresetDictParentParent;
6585 userDefaultFound = YES;
6594 /* check to see if a user specified preset was found, if not then assign the parents for
6595 * the presetHbDefault so that we can open the parents for the nested presets
6597 if (userDefaultFound == NO)
6599 presetUserDefaultParent = presetHbDefaultParent;
6600 presetUserDefaultParentParent = presetHbDefaultParentParent;
6604 - (IBAction)setDefaultPreset:(id)sender
6606 /* We need to determine if the item is a folder */
6607 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
6613 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6615 /* First make sure the old user specified default preset is removed */
6616 while (tempObject = [enumerator nextObject])
6618 NSMutableDictionary *thisPresetDict = tempObject;
6619 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6621 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6624 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6625 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6627 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6630 while (tempObject = [enumerator nextObject])
6632 NSMutableDictionary *thisPresetDict1 = tempObject;
6633 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6635 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6637 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6638 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
6640 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
6643 while (tempObject = [enumerator nextObject])
6645 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6647 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6660 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6661 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6662 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6665 NSMutableArray *presetsArrayToMod;
6666 NSMutableArray *tempArray;
6668 /* If we are a root level preset, we are modding the UserPresets array */
6669 if (presetToModLevel == 0)
6671 presetsArrayToMod = UserPresets;
6673 else // We have a parent preset, so we modify the chidren array object for key
6675 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6678 enumerator = [presetsArrayToMod objectEnumerator];
6679 tempArray = [NSMutableArray array];
6681 while (tempObject = [enumerator nextObject])
6683 NSDictionary *thisPresetDict = tempObject;
6684 if (thisPresetDict == presetToMod)
6686 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
6688 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
6695 /* We save all of the preset data here */
6697 /* We Reload the New Table data for presets */
6698 [fPresetsOutlineView reloadData];
6701 - (IBAction)selectDefaultPreset:(id)sender
6703 NSMutableDictionary *presetToMod;
6704 /* if there is a user specified default, we use it */
6705 if (presetUserDefault)
6707 presetToMod = presetUserDefault;
6709 else if (presetHbDefault) //else we use the built in default presetHbDefault
6711 presetToMod = presetHbDefault;
6718 if (presetUserDefaultParent != nil)
6720 [fPresetsOutlineView expandItem:presetUserDefaultParent];
6723 if (presetUserDefaultParentParent != nil)
6725 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
6729 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
6730 [self selectPreset:nil];
6735 #pragma mark Manage Built In Presets
6738 - (IBAction)deleteFactoryPresets:(id)sender
6741 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6745 NSMutableArray *tempArray;
6748 tempArray = [NSMutableArray array];
6749 /* we look here to see if the preset is we move on to the next one */
6750 while ( tempObject = [enumerator nextObject] )
6752 /* if the preset is "Factory" then we put it in the array of
6753 presets to delete */
6754 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
6756 [tempArray addObject:tempObject];
6760 [UserPresets removeObjectsInArray:tempArray];
6761 [fPresetsOutlineView reloadData];
6766 /* We use this method to recreate new, updated factory
6768 - (IBAction)addFactoryPresets:(id)sender
6771 /* First, we delete any existing built in presets */
6772 [self deleteFactoryPresets: sender];
6773 /* Then we generate new built in presets programmatically with fPresetsBuiltin
6774 * which is all setup in HBPresets.h and HBPresets.m*/
6775 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
6787 /*******************************
6788 * Subclass of the HBPresetsOutlineView *
6789 *******************************/
6791 @implementation HBPresetsOutlineView
6792 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
6796 // By default, NSTableView only drags an image of the first column. Change this to
6797 // drag an image of the queue's icon and PresetName columns.
6798 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
6799 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
6804 - (void) mouseDown:(NSEvent *)theEvent
6806 [super mouseDown:theEvent];
6812 - (BOOL) isDragging;