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 /* Init a separate instance of libhb for user scanning and setting up jobs */
87 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
89 // Set the Growl Delegate
90 [GrowlApplicationBridge setGrowlDelegate: self];
91 /* Init others controllers */
92 [fPictureController SetHandle: fHandle];
93 [fPictureController setHBController: self];
95 [fQueueController setHandle: fQueueEncodeLibhb];
96 [fQueueController setHBController: self];
98 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
99 [fChapterTable setDataSource:fChapterTitlesDelegate];
100 [fChapterTable setDelegate:fChapterTitlesDelegate];
102 [fPresetsOutlineView setAutosaveName:@"Presets View"];
103 [fPresetsOutlineView setAutosaveExpandedItems:YES];
105 dockIconProgress = 0;
107 /* Call UpdateUI every 1/2 sec */
108 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
109 scheduledTimerWithTimeInterval:0.5 target:self
110 selector:@selector(updateUI:) userInfo:nil repeats:YES]
111 forMode:NSDefaultRunLoopMode];
113 // Open debug output window now if it was visible when HB was closed
114 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
115 [self showDebugOutputPanel:nil];
117 // Open queue window now if it was visible when HB was closed
118 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
119 [self showQueueWindow:nil];
121 [self openMainWindow:nil];
123 /* We have to set the bool to tell hb what to do after a scan
124 * Initially we set it to NO until we start processing the queue
126 applyQueueToScan = NO;
128 /* Now we re-check the queue array to see if there are
129 * any remaining encodes to be done in it and ask the
130 * user if they want to reload the queue */
131 if ([QueueFileArray count] > 0)
133 /* run getQueueStats to see whats in the queue file */
134 [self getQueueStats];
135 /* this results in these values
136 * fEncodingQueueItem = 0;
138 * fCompletedCount = 0;
139 * fCanceledCount = 0;
143 /*On Screen Notification*/
144 NSString * alertTitle;
146 /* We check to see if there is already another instance of hb running.
147 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
149 if ([self hbInstances] > 1)
151 alertTitle = [NSString stringWithFormat:
152 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
153 NSBeginCriticalAlertSheet(
155 NSLocalizedString(@"Reload Queue", nil),
159 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
160 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
164 if (fWorkingCount > 0)
166 alertTitle = [NSString stringWithFormat:
167 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
168 fWorkingCount,fPendingCount];
172 alertTitle = [NSString stringWithFormat:
173 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
177 NSBeginCriticalAlertSheet(
179 NSLocalizedString(@"Reload Queue", nil),
181 NSLocalizedString(@"Empty Queue", nil),
183 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
184 NSLocalizedString(@" Do you want to reload them ?", nil));
187 // call didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
188 // right below to either clear the old queue or keep it loaded up.
192 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
193 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
195 [self browseSources:nil];
198 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
200 [self browseSources:(id)fOpenSourceTitleMMenu];
207 /* check to see if another instance of HandBrake.app is running */
208 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
209 NSDictionary *aDictionary;
211 for (aDictionary in runningAppDictionaries)
213 // NSLog(@"Open App: %@", [aDictionary valueForKey:@"NSApplicationName"]);
215 if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
223 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
225 if (returnCode == NSAlertOtherReturn)
227 [self clearQueueAllItems];
228 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
229 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
231 [self browseSources:nil];
234 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
236 [self browseSources:(id)fOpenSourceTitleMMenu];
241 if ([self hbInstances] == 1)
243 [self setQueueEncodingItemsAsPending];
245 [self showQueueWindow:NULL];
249 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
251 /* if we are in preview full screen mode, we need to go to
252 * windowed mode and release the display before we terminate.
253 * We do it here (instead of applicationWillTerminate) so we
254 * release the displays and can then see the alerts below.
256 if ([fPictureController previewFullScreenMode] == YES)
258 [fPictureController previewGoWindowed:nil];
262 hb_get_state( fQueueEncodeLibhb, &s );
264 if ( s.state != HB_STATE_IDLE )
266 int result = NSRunCriticalAlertPanel(
267 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
268 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
269 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
271 if (result == NSAlertDefaultReturn)
273 return NSTerminateNow;
276 return NSTerminateCancel;
279 // Warn if items still in the queue
280 else if ( fPendingCount > 0 )
282 int result = NSRunCriticalAlertPanel(
283 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
284 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
285 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
287 if ( result == NSAlertDefaultReturn )
288 return NSTerminateNow;
290 return NSTerminateCancel;
293 return NSTerminateNow;
296 - (void)applicationWillTerminate:(NSNotification *)aNotification
299 [browsedSourceDisplayName release];
300 [outputPanel release];
301 [fQueueController release];
302 [fPreviewController release];
303 [fPictureController release];
306 hb_close(&fQueueEncodeLibhb);
310 - (void) awakeFromNib
313 [fWindow setExcludedFromWindowsMenu:YES];
314 [fAdvancedOptions setView:fAdvancedView];
316 /* lets setup our presets drawer for drag and drop here */
317 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
318 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
319 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
321 /* Initialize currentScanCount so HB can use it to
322 evaluate successive scans */
323 currentScanCount = 0;
326 /* Init UserPresets .plist */
329 /* Init QueueFile .plist */
330 [self loadQueueFile];
332 fRipIndicatorShown = NO; // initially out of view in the nib
334 /* For 64 bit builds, the threaded animation in the progress
335 * indicators conflicts with the animation in the advanced tab
336 * for reasons not completely clear. jbrjake found a note in the
337 * 10.5 dev notes regarding this possiblility. It was also noted
338 * that unless specified, setUsesThreadedAnimation defaults to true.
339 * So, at least for now we set the indicator animation to NO for
340 * both the scan and regular progress indicators for both 32 and 64 bit
341 * as it test out fine on both and there is no reason our progress indicators
342 * should require their own thread.
345 [fScanIndicator setUsesThreadedAnimation:NO];
346 [fRipIndicator setUsesThreadedAnimation:NO];
350 /* Show/Dont Show Presets drawer upon launch based
351 on user preference DefaultPresetsDrawerShow*/
352 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
354 [fPresetDrawer setDelegate:self];
355 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
356 stringForKey:@"Drawer Size"] );
357 if( drawerSize.width )
358 [fPresetDrawer setContentSize: drawerSize];
359 [fPresetDrawer open];
363 NSMenuItem *menuItem;
364 [fDstFormatPopUp removeAllItems];
366 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
367 [menuItem setTag: HB_MUX_MP4];
369 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
370 [menuItem setTag: HB_MUX_MKV];
372 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"AVI file" action: NULL keyEquivalent: @""];
373 [menuItem setTag: HB_MUX_AVI];
375 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"OGM file" action: NULL keyEquivalent: @""];
376 [menuItem setTag: HB_MUX_OGM];
377 [fDstFormatPopUp selectItemAtIndex: 0];
379 [self formatPopUpChanged:nil];
381 /* We enable the create chapters checkbox here since we are .mp4 */
382 [fCreateChapterMarkers setEnabled: YES];
383 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
385 [fCreateChapterMarkers setState: NSOnState];
391 [fDstFile2Field setStringValue: [NSString stringWithFormat:
392 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
395 [fVidEncoderPopUp removeAllItems];
396 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
397 [fVidEncoderPopUp addItemWithTitle: @"XviD"];
402 [fVidTargetSizeField setIntValue: 700];
403 [fVidBitrateField setIntValue: 1000];
405 [fVidQualityMatrix selectCell: fVidBitrateCell];
406 [self videoMatrixChanged:nil];
408 /* Video framerate */
409 [fVidRatePopUp removeAllItems];
410 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
411 for( int i = 0; i < hb_video_rates_count; i++ )
413 if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
415 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
416 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
418 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
420 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
421 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
423 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
425 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
426 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
430 [fVidRatePopUp addItemWithTitle:
431 [NSString stringWithCString: hb_video_rates[i].string]];
434 [fVidRatePopUp selectItemAtIndex: 0];
436 /* Set Auto Crop to On at launch */
437 [fPictureController setAutoCrop:YES];
440 [fAudTrack1BitratePopUp removeAllItems];
441 for( int i = 0; i < hb_audio_bitrates_count; i++ )
443 [fAudTrack1BitratePopUp addItemWithTitle:
444 [NSString stringWithCString: hb_audio_bitrates[i].string]];
447 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
449 /* Audio samplerate */
450 [fAudTrack1RatePopUp removeAllItems];
451 for( int i = 0; i < hb_audio_rates_count; i++ )
453 [fAudTrack1RatePopUp addItemWithTitle:
454 [NSString stringWithCString: hb_audio_rates[i].string]];
456 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
459 [fStatusField setStringValue: @""];
464 /* We disable the Turbo 1st pass checkbox since we are not x264 */
465 [fVidTurboPassCheck setEnabled: NO];
466 [fVidTurboPassCheck setState: NSOffState];
469 /* lets get our default prefs here */
470 [self getDefaultPresets:nil];
471 /* lets initialize the current successful scancount here to 0 */
472 currentSuccessfulScanCount = 0;
477 - (void) enableUI: (bool) b
479 NSControl * controls[] =
480 { fSrcTitleField, fSrcTitlePopUp,
481 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
482 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
483 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
484 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
485 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
486 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
487 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
488 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
489 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
490 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
491 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
492 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
493 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
494 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
495 fQueueStatus,fPresetsAdd,fPresetsDelete,
496 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
497 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel};
500 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
502 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
504 NSTextField * tf = (NSTextField *) controls[i];
505 if( ![tf isBezeled] )
507 [tf setTextColor: b ? [NSColor controlTextColor] :
508 [NSColor disabledControlTextColor]];
512 [controls[i] setEnabled: b];
518 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
519 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
520 [self setEnabledStateOfAudioMixdownControls:nil];
521 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
522 [self calculatePictureSizing:nil];
526 [fPresetsOutlineView setEnabled: NO];
530 [self videoMatrixChanged:nil];
531 [fAdvancedOptions enableUI:b];
535 /***********************************************************************
537 ***********************************************************************
538 * Shows a progression bar on the dock icon, filled according to
539 * 'progress' (0.0 <= progress <= 1.0).
540 * Called with progress < 0.0 or progress > 1.0, restores the original
542 **********************************************************************/
543 - (void) UpdateDockIcon: (float) progress
547 NSBitmapImageRep * bmp;
549 uint32_t black = htonl( 0x000000FF );
550 uint32_t red = htonl( 0xFF0000FF );
551 uint32_t white = htonl( 0xFFFFFFFF );
552 int row_start, row_end;
555 /* Get application original icon */
556 icon = [NSImage imageNamed: @"NSApplicationIcon"];
558 if( progress < 0.0 || progress > 1.0 )
560 [NSApp setApplicationIconImage: icon];
564 /* Get it in a raw bitmap form */
565 tiff = [icon TIFFRepresentationUsingCompression:
566 NSTIFFCompressionNone factor: 1.0];
567 bmp = [NSBitmapImageRep imageRepWithData: tiff];
569 /* Draw the progression bar */
570 /* It's pretty simple (ugly?) now, but I'm no designer */
572 row_start = 3 * (int) [bmp size].height / 4;
573 row_end = 7 * (int) [bmp size].height / 8;
575 for( i = row_start; i < row_start + 2; i++ )
577 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
578 for( j = 0; j < (int) [bmp size].width; j++ )
583 for( i = row_start + 2; i < row_end - 2; i++ )
585 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
588 for( j = 2; j < (int) [bmp size].width - 2; j++ )
590 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
602 for( i = row_end - 2; i < row_end; i++ )
604 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
605 for( j = 0; j < (int) [bmp size].width; j++ )
611 /* Now update the dock icon */
612 tiff = [bmp TIFFRepresentationUsingCompression:
613 NSTIFFCompressionNone factor: 1.0];
614 icon = [[NSImage alloc] initWithData: tiff];
615 [NSApp setApplicationIconImage: icon];
619 - (void) updateUI: (NSTimer *) timer
622 /* Update UI for fHandle (user scanning instance of libhb ) */
625 list = hb_get_titles( fHandle );
626 /* check to see if there has been a new scan done
627 this bypasses the constraints of HB_STATE_WORKING
628 not allowing setting a newly scanned source */
629 int checkScanCount = hb_get_scancount( fHandle );
630 if( checkScanCount > currentScanCount )
632 currentScanCount = checkScanCount;
633 [fScanIndicator setIndeterminate: NO];
634 [fScanIndicator setDoubleValue: 0.0];
635 [fScanIndicator setHidden: YES];
636 [self showNewScan:nil];
640 hb_get_state( fHandle, &s );
646 #define p s.param.scanning
647 case HB_STATE_SCANNING:
649 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
650 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
651 p.title_cur, p.title_count]];
652 [fScanIndicator setHidden: NO];
653 double scanProgress = ( p.title_cur - 1 ) / p.title_count;
654 //[fScanIndicator setDoubleValue: 100.0 * scanProgress];
655 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
660 #define p s.param.scandone
661 case HB_STATE_SCANDONE:
663 [fScanIndicator setIndeterminate: NO];
664 [fScanIndicator setDoubleValue: 0.0];
665 [fScanIndicator setHidden: YES];
666 [self writeToActivityLog:"ScanDone state received from fHandle"];
667 [self showNewScan:nil];
668 [[fWindow toolbar] validateVisibleItems];
674 #define p s.param.working
675 case HB_STATE_WORKING:
682 #define p s.param.muxing
683 case HB_STATE_MUXING:
690 case HB_STATE_PAUSED:
693 case HB_STATE_WORKDONE:
700 /* Update UI for fQueueEncodeLibhb */
702 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
703 /* check to see if there has been a new scan done
704 this bypasses the constraints of HB_STATE_WORKING
705 not allowing setting a newly scanned source */
707 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
708 if( checkScanCount > currentScanCount )
710 currentScanCount = checkScanCount;
711 [self writeToActivityLog:"currentScanCount received from fQueueEncodeLibhb"];
715 hb_get_state( fQueueEncodeLibhb, &s );
721 #define p s.param.scanning
722 case HB_STATE_SCANNING:
724 [fStatusField setStringValue: [NSString stringWithFormat:
725 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
726 p.title_cur, p.title_count]];
728 /* Set the status string in fQueueController as well */
729 [fQueueController setQueueStatusString: [NSString stringWithFormat:
730 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
731 p.title_cur, p.title_count]];
736 #define p s.param.scandone
737 case HB_STATE_SCANDONE:
739 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
740 [self processNewQueueEncode];
741 [[fWindow toolbar] validateVisibleItems];
747 #define p s.param.working
748 case HB_STATE_WORKING:
750 NSMutableString * string;
751 /* Update text field */
752 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d of %d, %.2f %%", @"" ), p.job_cur, p.job_count, 100.0 * p.progress];
756 [string appendFormat:
757 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
758 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
761 [fStatusField setStringValue: string];
762 /* Set the status string in fQueueController as well */
763 [fQueueController setQueueStatusString: string];
765 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
766 [fRipIndicator setIndeterminate: NO];
767 [fRipIndicator setDoubleValue:100.0 * progress_total];
769 // If progress bar hasn't been revealed at the bottom of the window, do
770 // that now. This code used to be in doRip. I moved it to here to handle
771 // the case where hb_start is called by HBQueueController and not from
773 if( !fRipIndicatorShown )
775 NSRect frame = [fWindow frame];
776 if( frame.size.width <= 591 )
777 frame.size.width = 591;
778 frame.size.height += 36;
779 frame.origin.y -= 36;
780 [fWindow setFrame:frame display:YES animate:YES];
781 fRipIndicatorShown = YES;
785 /* Update dock icon */
786 if( dockIconProgress < 100.0 * progress_total )
788 [self UpdateDockIcon: progress_total];
789 dockIconProgress += 5;
796 #define p s.param.muxing
797 case HB_STATE_MUXING:
799 /* Update text field */
800 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
801 /* Set the status string in fQueueController as well */
802 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
804 [fRipIndicator setIndeterminate: YES];
805 [fRipIndicator startAnimation: nil];
807 /* Update dock icon */
808 [self UpdateDockIcon: 1.0];
814 case HB_STATE_PAUSED:
815 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
816 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
820 case HB_STATE_WORKDONE:
822 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
823 // or someone calling hb_stop. In the latter case, hb_stop does not clear
824 // out the remaining passes/jobs in the queue. We'll do that here.
826 // Delete all remaining jobs of this encode.
827 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
828 /* Set the status string in fQueueController as well */
829 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
830 [fRipIndicator setIndeterminate: NO];
831 [fRipIndicator stopAnimation: nil];
832 [fRipIndicator setDoubleValue: 0.0];
833 [[fWindow toolbar] validateVisibleItems];
835 /* Restore dock icon */
836 [self UpdateDockIcon: -1.0];
837 dockIconProgress = 0;
839 if( fRipIndicatorShown )
841 NSRect frame = [fWindow frame];
842 if( frame.size.width <= 591 )
843 frame.size.width = 591;
844 frame.size.height += -36;
845 frame.origin.y -= -36;
846 [fWindow setFrame:frame display:YES animate:YES];
847 fRipIndicatorShown = NO;
849 /* Since we are done with this encode, tell output to stop writing to the
850 * individual encode log
852 [outputPanel endEncodeLog];
853 /* Check to see if the encode state has not been cancelled
854 to determine if we should check for encode done notifications */
855 if( fEncodeState != 2 )
857 NSString *pathOfFinishedEncode;
858 /* Get the output file name for the finished encode */
859 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
861 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
863 [self showGrowlDoneNotification:pathOfFinishedEncode];
865 [self sendToMetaX:pathOfFinishedEncode];
867 /* since we have successfully completed an encode, we increment the queue counter */
868 [self incrementQueueItemDone:nil];
870 /* all end of queue actions below need to be done after all queue encodes have finished
871 * and there are no pending jobs left to process
873 if (fPendingCount == 0)
875 /* If Alert Window or Window and Growl has been selected */
876 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
877 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
879 /*On Screen Notification*/
882 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
883 [NSApp requestUserAttention:NSCriticalRequest];
886 /* If sleep has been selected */
887 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
890 NSDictionary* errorDict;
891 NSAppleEventDescriptor* returnDescriptor = nil;
892 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
893 @"tell application \"Finder\" to sleep"];
894 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
895 [scriptObject release];
897 /* If Shutdown has been selected */
898 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
901 NSDictionary* errorDict;
902 NSAppleEventDescriptor* returnDescriptor = nil;
903 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
904 @"tell application \"Finder\" to shut down"];
905 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
906 [scriptObject release];
920 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
921 - (void) writeToActivityLog:(const char *) format, ...
924 va_start(args, format);
928 vsnprintf( str, 1024, format, args );
930 time_t _now = time( NULL );
931 struct tm * now = localtime( &_now );
932 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
939 // ============================================================
940 // NSToolbar Related Methods
941 // ============================================================
943 - (void) setupToolbar {
944 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
946 [toolbar setAllowsUserCustomization: YES];
947 [toolbar setAutosavesConfiguration: YES];
948 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
950 [toolbar setDelegate: self];
952 [fWindow setToolbar: toolbar];
955 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
956 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
957 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
959 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
961 [item setLabel: @"Toggle Presets"];
962 [item setPaletteLabel: @"Toggler Presets"];
963 [item setToolTip: @"Open/Close Preset Drawer"];
964 [item setImage: [NSImage imageNamed: @"Drawer"]];
965 [item setTarget: self];
966 [item setAction: @selector(toggleDrawer:)];
967 [item setAutovalidates: NO];
969 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
971 [item setLabel: @"Start"];
972 [item setPaletteLabel: @"Start Encoding"];
973 [item setToolTip: @"Start Encoding"];
974 [item setImage: [NSImage imageNamed: @"Play"]];
975 [item setTarget: self];
976 [item setAction: @selector(Rip:)];
978 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
980 [item setLabel: @"Show Queue"];
981 [item setPaletteLabel: @"Show Queue"];
982 [item setToolTip: @"Show Queue"];
983 [item setImage: [NSImage imageNamed: @"Queue"]];
984 [item setTarget: self];
985 [item setAction: @selector(showQueueWindow:)];
986 [item setAutovalidates: NO];
988 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
990 [item setLabel: @"Add to Queue"];
991 [item setPaletteLabel: @"Add to Queue"];
992 [item setToolTip: @"Add to Queue"];
993 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
994 [item setTarget: self];
995 [item setAction: @selector(addToQueue:)];
997 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
999 [item setLabel: @"Pause"];
1000 [item setPaletteLabel: @"Pause Encoding"];
1001 [item setToolTip: @"Pause Encoding"];
1002 [item setImage: [NSImage imageNamed: @"Pause"]];
1003 [item setTarget: self];
1004 [item setAction: @selector(Pause:)];
1006 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1008 [item setLabel: @"Picture Settings"];
1009 [item setPaletteLabel: @"Show Picture Settings"];
1010 [item setToolTip: @"Show Picture Settings"];
1011 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1012 [item setTarget: self];
1013 [item setAction: @selector(showPicturePanel:)];
1015 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1017 [item setLabel: @"Activity Window"];
1018 [item setPaletteLabel: @"Show Activity Window"];
1019 [item setToolTip: @"Show Activity Window"];
1020 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1021 [item setTarget: self];
1022 [item setAction: @selector(showDebugOutputPanel:)];
1023 [item setAutovalidates: NO];
1025 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1027 [item setLabel: @"Source"];
1028 [item setPaletteLabel: @"Source"];
1029 [item setToolTip: @"Choose Video Source"];
1030 [item setImage: [NSImage imageNamed: @"Source"]];
1031 [item setTarget: self];
1032 [item setAction: @selector(browseSources:)];
1042 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1044 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1045 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1046 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1049 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1051 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1052 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1053 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1054 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1057 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1059 NSString * ident = [toolbarItem itemIdentifier];
1064 hb_get_state2( fQueueEncodeLibhb, &s );
1066 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
1068 if ([ident isEqualToString: StartEncodingIdentifier])
1070 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1071 [toolbarItem setLabel: @"Stop"];
1072 [toolbarItem setPaletteLabel: @"Stop"];
1073 [toolbarItem setToolTip: @"Stop Encoding"];
1076 if ([ident isEqualToString: PauseEncodingIdentifier])
1078 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1079 [toolbarItem setLabel: @"Pause"];
1080 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1081 [toolbarItem setToolTip: @"Pause Encoding"];
1086 if ([ident isEqualToString: AddToQueueIdentifier])
1088 if ([ident isEqualToString: ShowPictureIdentifier])
1092 else if (s.state == HB_STATE_PAUSED)
1094 if ([ident isEqualToString: PauseEncodingIdentifier])
1096 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1097 [toolbarItem setLabel: @"Resume"];
1098 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1099 [toolbarItem setToolTip: @"Resume Encoding"];
1102 if ([ident isEqualToString: StartEncodingIdentifier])
1104 if ([ident isEqualToString: AddToQueueIdentifier])
1106 if ([ident isEqualToString: ShowPictureIdentifier])
1109 else if (s.state == HB_STATE_SCANNING)
1111 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1113 if ([ident isEqualToString: StartEncodingIdentifier])
1115 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1116 if (hb_count(fHandle) > 0)
1117 [toolbarItem setLabel: @"Start Queue"];
1119 [toolbarItem setLabel: @"Start"];
1120 [toolbarItem setPaletteLabel: @"Start Encoding"];
1121 [toolbarItem setToolTip: @"Start Encoding"];
1124 if ([ident isEqualToString: AddToQueueIdentifier])
1126 if ([ident isEqualToString: ShowPictureIdentifier])
1131 /* If there are any pending queue items, make sure the start/stop button is active */
1132 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1134 if ([ident isEqualToString: ShowQueueIdentifier])
1136 if ([ident isEqualToString: ToggleDrawerIdentifier])
1138 if ([ident isEqualToString: ChooseSourceIdentifier])
1140 if ([ident isEqualToString: ShowActivityIdentifier])
1146 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1148 SEL action = [menuItem action];
1151 hb_get_state2( fHandle, &s );
1155 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1156 return SuccessfulScan && [fWindow attachedSheet] == nil;
1158 if (action == @selector(browseSources:))
1160 if (s.state == HB_STATE_SCANNING)
1163 return [fWindow attachedSheet] == nil;
1165 if (action == @selector(selectDefaultPreset:))
1166 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1167 if (action == @selector(Pause:))
1169 if (s.state == HB_STATE_WORKING)
1171 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1172 [menuItem setTitle:@"Pause Encoding"];
1175 else if (s.state == HB_STATE_PAUSED)
1177 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1178 [menuItem setTitle:@"Resume Encoding"];
1184 if (action == @selector(Rip:))
1186 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1188 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1189 [menuItem setTitle:@"Stop Encoding"];
1192 else if (SuccessfulScan)
1194 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1195 [menuItem setTitle:@"Start Encoding"];
1196 return [fWindow attachedSheet] == nil;
1202 if( action == @selector(setDefaultPreset:) )
1204 return [fPresetsOutlineView selectedRow] != -1;
1211 #pragma mark Encode Done Actions
1212 // register a test notification and make
1213 // it enabled by default
1214 #define SERVICE_NAME @"Encode Done"
1215 - (NSDictionary *)registrationDictionaryForGrowl
1217 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1218 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1219 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1222 return registrationDictionary;
1225 -(void)showGrowlDoneNotification:(NSString *) filePath
1227 /* This end of encode action is called as each encode rolls off of the queue */
1228 NSString * finishedEncode = filePath;
1229 /* strip off the path to just show the file name */
1230 finishedEncode = [finishedEncode lastPathComponent];
1231 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1232 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1234 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1235 [GrowlApplicationBridge
1236 notifyWithTitle:@"Put down that cocktail..."
1237 description:growlMssg
1238 notificationName:SERVICE_NAME
1246 -(void)sendToMetaX:(NSString *) filePath
1248 /* This end of encode action is called as each encode rolls off of the queue */
1249 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1251 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
1252 [myScript executeAndReturnError: nil];
1257 #pragma mark Get New Source
1259 /*Opens the source browse window, called from Open Source widgets */
1260 - (IBAction) browseSources: (id) sender
1262 NSOpenPanel * panel;
1264 panel = [NSOpenPanel openPanel];
1265 [panel setAllowsMultipleSelection: NO];
1266 [panel setCanChooseFiles: YES];
1267 [panel setCanChooseDirectories: YES ];
1268 NSString * sourceDirectory;
1269 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1271 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1275 sourceDirectory = @"~/Desktop";
1276 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1278 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1279 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1281 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1282 modalForWindow: fWindow modalDelegate: self
1283 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1284 contextInfo: sender];
1287 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1288 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1290 /* we convert the sender content of contextInfo back into a variable called sender
1291 * mostly just for consistency for evaluation later
1293 id sender = (id)contextInfo;
1294 /* User selected a file to open */
1295 if( returnCode == NSOKButton )
1297 /* Free display name allocated previously by this code */
1298 [browsedSourceDisplayName release];
1300 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1301 /* we set the last searched source directory in the prefs here */
1302 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1303 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1304 /* we order out sheet, which is the browse window as we need to open
1305 * the title selection sheet right away
1307 [sheet orderOut: self];
1309 if (sender == fOpenSourceTitleMMenu)
1311 /* We put the chosen source path in the source display text field for the
1312 * source title selection sheet in which the user specifies the specific title to be
1313 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1314 * purposes in the title panel
1317 [fScanSrcTitlePathField setStringValue:scanPath];
1318 NSString *displayTitlescanSourceName;
1320 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1322 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1323 we have to use the title->dvd value so we get the proper name of the volume if a physical dvd is the source*/
1324 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1328 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1329 displayTitlescanSourceName = [scanPath lastPathComponent];
1331 /* we set the source display name in the title selection dialogue */
1332 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1333 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1334 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1335 /* We show the actual sheet where the user specifies the title to be scanned
1336 * as we are going to do a title specific scan
1338 [self showSourceTitleScanPanel:nil];
1342 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1343 NSString *path = [[sheet filenames] objectAtIndex: 0];
1345 /* We check to see if the chosen file at path is a package */
1346 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1348 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1349 /* We check to see if this is an .eyetv package */
1350 if ([[path pathExtension] isEqualToString: @"eyetv"])
1352 [self writeToActivityLog:"trying to open eyetv package"];
1353 /* We're looking at an EyeTV package - try to open its enclosed
1355 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1357 int n = [[path stringByAppendingString: @"/"]
1358 completePathIntoString: &mpgname caseSensitive: NO
1359 matchesIntoArray: nil
1360 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1363 /* Found an mpeg inside the eyetv package, make it our scan path
1364 and call performScan on the enclosed mpeg */
1366 [self writeToActivityLog:"found mpeg in eyetv package"];
1367 [self performScan:path scanTitleNum:0];
1371 /* We did not find an mpeg file in our package, so we do not call performScan */
1372 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1375 /* We check to see if this is a .dvdmedia package */
1376 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1378 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1379 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1380 [self writeToActivityLog:"trying to open dvdmedia package"];
1381 [self performScan:path scanTitleNum:0];
1385 /* The package is not an eyetv package, so we do not call performScan */
1386 [self writeToActivityLog:"unable to open package"];
1389 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1391 /* path is not a package, so we call perform scan directly on our file */
1392 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1394 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1395 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1396 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1400 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1401 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1402 /* make sure we remove any path extension as this can also be an '.mpg' file */
1403 browsedSourceDisplayName = [[path lastPathComponent] retain];
1405 [self performScan:path scanTitleNum:0];
1413 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1414 - (IBAction) showSourceTitleScanPanel: (id) sender
1416 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1419 [fScanSrcTitleNumField setStringValue: @"0"];
1420 /* Show the panel */
1421 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1424 - (IBAction) closeSourceTitleScanPanel: (id) sender
1426 [NSApp endSheet: fScanSrcTitlePanel];
1427 [fScanSrcTitlePanel orderOut: self];
1429 if(sender == fScanSrcTitleOpenButton)
1431 /* We setup the scan status in the main window to indicate a source title scan */
1432 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1433 [fScanIndicator setHidden: NO];
1434 [fScanIndicator setIndeterminate: YES];
1435 [fScanIndicator startAnimation: nil];
1437 /* We use the performScan method to actually perform the specified scan passing the path and the title
1440 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1444 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1445 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1447 /* set the bool applyQueueToScan so that we dont apply a queue setting to the final scan */
1448 applyQueueToScan = NO;
1449 /* use a bool to determine whether or not we can decrypt using vlc */
1450 BOOL cancelScanDecrypt = 0;
1451 NSString *path = scanPath;
1452 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1454 // Notify ChapterTitles that there's no title
1455 [fChapterTitlesDelegate resetWithTitle:nil];
1456 [fChapterTable reloadData];
1458 [self enableUI: NO];
1460 if( [detector isVideoDVD] )
1462 // The chosen path was actually on a DVD, so use the raw block
1463 // device path instead.
1464 path = [detector devicePath];
1465 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1468 /* If we are 64 bit, we cannot read encrypted dvd's as vlc is 32 bit only */
1469 cancelScanDecrypt = 1;
1470 [self writeToActivityLog: "64 bit mode cannot read dvd's, scan cancelled"];
1471 /*On Screen Notification*/
1474 status = NSRunAlertPanel(@"64-bit HandBrake cannot read encrypted dvds!",@"This scan will be cancelled!", @"OK", nil, nil);
1475 [NSApp requestUserAttention:NSCriticalRequest];
1477 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1478 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1479 NSFileManager * fileManager = [NSFileManager defaultManager];
1480 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1482 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1483 cancelScanDecrypt = 1;
1484 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1486 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");
1487 [NSApp requestUserAttention:NSCriticalRequest];
1489 if (status == NSAlertDefaultReturn)
1491 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1492 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
1494 else if (status == NSAlertAlternateReturn)
1496 /* User chose to cancel the scan */
1497 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1501 /* 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 */
1502 cancelScanDecrypt = 0;
1503 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1509 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1510 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1515 if (cancelScanDecrypt == 0)
1517 /* we actually pass the scan off to libhb here */
1518 /* If there is no title number passed to scan, we use "0"
1519 * which causes the default behavior of a full source scan
1525 if (scanTitleNum > 0)
1527 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1529 /* We use our advance pref to determine how many previews to scan */
1530 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1531 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1532 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1536 - (IBAction) showNewScan:(id)sender
1540 int indxpri=0; // Used to search the longuest title (default in combobox)
1541 int longuestpri=0; // Used to search the longuest title (default in combobox)
1544 list = hb_get_titles( fHandle );
1546 if( !hb_list_count( list ) )
1548 /* We display a message if a valid dvd source was not chosen */
1549 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1550 SuccessfulScan = NO;
1552 // Notify ChapterTitles that there's no title
1553 [fChapterTitlesDelegate resetWithTitle:nil];
1554 [fChapterTable reloadData];
1558 /* We increment the successful scancount here by one,
1559 which we use at the end of this function to tell the gui
1560 if this is the first successful scan since launch and whether
1561 or not we should set all settings to the defaults */
1563 currentSuccessfulScanCount++;
1565 [[fWindow toolbar] validateVisibleItems];
1567 [fSrcTitlePopUp removeAllItems];
1568 for( int i = 0; i < hb_list_count( list ); i++ )
1570 title = (hb_title_t *) hb_list_item( list, i );
1572 currentSource = [NSString stringWithUTF8String: title->name];
1573 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1574 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1576 /* Use the dvd name in the default output field here
1577 May want to add code to remove blank spaces for some dvd names*/
1578 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1579 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1581 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1582 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1586 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1587 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1591 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1593 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1597 [fSrcTitlePopUp addItemWithTitle: [NSString
1598 stringWithFormat: @"%d - %02dh%02dm%02ds",
1599 title->index, title->hours, title->minutes,
1603 // Select the longuest title
1604 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1605 [self titlePopUpChanged:nil];
1607 SuccessfulScan = YES;
1608 [self enableUI: YES];
1610 /* if its the initial successful scan after awakeFromNib */
1611 if (currentSuccessfulScanCount == 1)
1613 [self selectDefaultPreset:nil];
1615 // Open preview window now if it was visible when HB was closed
1616 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1617 [self showPreviewWindow:nil];
1619 // Open picture sizing window now if it was visible when HB was closed
1620 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1621 [self showPicturePanel:nil];
1632 #pragma mark New Output Destination
1634 - (IBAction) browseFile: (id) sender
1636 /* Open a panel to let the user choose and update the text field */
1637 NSSavePanel * panel = [NSSavePanel savePanel];
1638 /* We get the current file name and path from the destination field here */
1639 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1640 modalForWindow: fWindow modalDelegate: self
1641 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1645 - (void) browseFileDone: (NSSavePanel *) sheet
1646 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1648 if( returnCode == NSOKButton )
1650 [fDstFile2Field setStringValue: [sheet filename]];
1651 /* Save this path to the prefs so that on next browse destination window it opens there */
1652 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1653 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1659 #pragma mark Main Window Control
1661 - (IBAction) openMainWindow: (id) sender
1663 [fWindow makeKeyAndOrderFront:nil];
1666 - (BOOL) windowShouldClose: (id) sender
1671 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1674 [fWindow makeKeyAndOrderFront:nil];
1682 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1683 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1688 #pragma mark Queue File
1690 - (void) loadQueueFile {
1691 /* We declare the default NSFileManager into fileManager */
1692 NSFileManager * fileManager = [NSFileManager defaultManager];
1693 /*We define the location of the user presets file */
1694 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1695 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1696 /* We check for the presets.plist */
1697 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1699 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1702 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1703 /* lets check to see if there is anything in the queue file .plist */
1704 if (nil == QueueFileArray)
1706 /* if not, then lets initialize an empty array */
1707 QueueFileArray = [[NSMutableArray alloc] init];
1709 /* Initialize our curQueueEncodeIndex to 0
1710 * so we can use it to track which queue
1711 * item is to be used to track our encodes */
1712 /* NOTE: this should be changed if and when we
1713 * are able to get the last unfinished encode
1714 * in the case of a crash or shutdown */
1719 [self clearQueueEncodedItems];
1721 currentQueueEncodeIndex = 0;
1724 - (void)addQueueFileItem
1726 [QueueFileArray addObject:[self createQueueFileItem]];
1727 [self saveQueueFileItem];
1731 - (void) removeQueueFileItem:(int) queueItemToRemove
1734 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
1735 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
1737 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
1738 * by one to keep in sync with the queue array
1740 currentQueueEncodeIndex--;
1741 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
1743 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1744 [self saveQueueFileItem];
1748 - (void)saveQueueFileItem
1750 [QueueFileArray writeToFile:QueueFile atomically:YES];
1751 [fQueueController setQueueArray: QueueFileArray];
1752 [self getQueueStats];
1755 - (void)getQueueStats
1757 /* lets get the stats on the status of the queue array */
1759 fEncodingQueueItem = 0;
1761 fCompletedCount = 0;
1765 /* We use a number system to set the encode status of the queue item
1767 * 0 == already encoded
1768 * 1 == is being encoded
1769 * 2 == is yet to be encoded
1774 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1776 while (tempObject = [enumerator nextObject])
1778 NSDictionary *thisQueueDict = tempObject;
1779 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1783 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1786 fEncodingQueueItem = i;
1788 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
1792 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
1799 /* Set the queue status field in the main window */
1800 NSMutableString * string;
1801 if (fPendingCount == 1)
1803 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
1807 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
1809 [fQueueStatus setStringValue:string];
1812 /* This method will set any item marked as encoding back to pending
1813 * currently used right after a queue reload
1815 - (void) setQueueEncodingItemsAsPending
1817 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1819 NSMutableArray *tempArray;
1820 tempArray = [NSMutableArray array];
1821 /* we look here to see if the preset is we move on to the next one */
1822 while ( tempObject = [enumerator nextObject] )
1824 /* If the queue item is marked as "encoding" (1)
1825 * then change its status back to pending (2) which effectively
1826 * puts it back into the queue to be encoded
1828 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
1830 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
1832 [tempArray addObject:tempObject];
1835 [QueueFileArray setArray:tempArray];
1836 [self saveQueueFileItem];
1840 /* This method will clear the queue of any encodes that are not still pending
1841 * this includes both successfully completed encodes as well as cancelled encodes */
1842 - (void) clearQueueEncodedItems
1844 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1846 NSMutableArray *tempArray;
1847 tempArray = [NSMutableArray array];
1848 /* we look here to see if the preset is we move on to the next one */
1849 while ( tempObject = [enumerator nextObject] )
1851 /* If the queue item is either completed (0) or cancelled (3) from the
1852 * last session, then we put it in tempArray to be deleted from QueueFileArray.
1853 * NOTE: this means we retain pending (2) and also an item that is marked as
1854 * still encoding (1). If the queue has an item that is still marked as encoding
1855 * from a previous session, we can conlude that HB was either shutdown, or crashed
1856 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
1858 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
1860 [tempArray addObject:tempObject];
1864 [QueueFileArray removeObjectsInArray:tempArray];
1865 [self saveQueueFileItem];
1868 /* This method will clear the queue of all encodes. effectively creating an empty queue */
1869 - (void) clearQueueAllItems
1871 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1873 NSMutableArray *tempArray;
1874 tempArray = [NSMutableArray array];
1875 /* we look here to see if the preset is we move on to the next one */
1876 while ( tempObject = [enumerator nextObject] )
1878 [tempArray addObject:tempObject];
1881 [QueueFileArray removeObjectsInArray:tempArray];
1882 [self saveQueueFileItem];
1885 /* This method will duplicate prepareJob however into the
1886 * queue .plist instead of into the job structure so it can
1887 * be recalled later */
1888 - (NSDictionary *)createQueueFileItem
1890 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
1892 hb_list_t * list = hb_get_titles( fHandle );
1893 hb_title_t * title = (hb_title_t *) hb_list_item( list,
1894 [fSrcTitlePopUp indexOfSelectedItem] );
1895 hb_job_t * job = title->job;
1899 /* We use a number system to set the encode status of the queue item
1900 * 0 == already encoded
1901 * 1 == is being encoded
1902 * 2 == is yet to be encoded
1905 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
1906 /* Source and Destination Information */
1908 [queueFileJob setObject:[NSString stringWithUTF8String: title->dvd] forKey:@"SourcePath"];
1909 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
1910 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
1911 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
1913 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
1915 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
1917 /* Lets get the preset info if there is any */
1918 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
1919 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
1921 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
1922 /* Chapter Markers fCreateChapterMarkers*/
1923 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
1925 /* We need to get the list of chapter names to put into an array and store
1926 * in our queue, so they can be reapplied in prepareJob when this queue
1927 * item comes up if Chapter Markers is set to on.
1930 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
1931 int chaptercount = hb_list_count( fTitle->list_chapter );
1932 for( i = 0; i < chaptercount; i++ )
1934 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
1935 if( chapter != NULL )
1937 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
1940 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
1941 [ChapterNamesArray autorelease];
1943 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
1944 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
1945 /* Mux mp4 with http optimization */
1946 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
1947 /* Add iPod uuid atom */
1948 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
1952 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
1953 /* x264 Option String */
1954 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
1956 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
1957 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
1958 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
1959 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
1961 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
1963 /* 2 Pass Encoding */
1964 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
1965 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
1966 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
1968 /* Picture Sizing */
1969 /* Use Max Picture settings for whatever the dvd is.*/
1970 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1971 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1972 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1973 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1974 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
1975 NSString * pictureSummary;
1976 pictureSummary = [fPictureSizeField stringValue];
1977 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
1978 /* Set crop settings here */
1979 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
1980 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
1981 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
1982 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
1983 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
1985 /* Picture Filters */
1986 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
1987 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
1989 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
1990 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
1991 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
1993 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
1994 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
1996 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
1997 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
1999 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2001 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2004 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2006 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2007 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2008 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2009 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2010 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2011 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2012 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2014 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2016 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2017 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2018 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2019 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2020 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2021 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2022 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2024 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2026 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2027 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2028 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2029 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2030 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2031 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2032 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2034 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2036 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2037 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2038 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2039 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2040 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2041 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2042 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2046 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
2047 [queueFileJob setObject:[NSNumber numberWithInt:[fSubPopUp indexOfSelectedItem]] forKey:@"JobSubtitlesIndex"];
2048 /* Forced Subtitles */
2049 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
2053 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2055 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2057 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2060 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2064 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2067 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2068 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2069 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2071 /* Picture Sizing */
2072 /* Use Max Picture settings for whatever the dvd is.*/
2073 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2074 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2075 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2076 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2077 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2079 /* Set crop settings here */
2080 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2081 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2082 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2083 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2084 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2086 /* Picture Filters */
2087 //[queueFileJob setObject:[fPicSettingDecomb stringValue] forKey:@"JobPictureDecomb"];
2090 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2092 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2093 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2094 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2095 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2096 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2098 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2100 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2101 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2102 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2103 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2104 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2106 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2108 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2109 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2110 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2111 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2112 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2114 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2116 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2117 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2118 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2119 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2120 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2123 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
2124 /* Forced Subtitles */
2125 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
2127 /* we need to auto relase the queueFileJob and return it */
2128 [queueFileJob autorelease];
2129 return queueFileJob;
2133 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2134 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2136 NSUInteger index = [indexSet lastIndex];
2137 NSUInteger aboveInsertIndexCount = 0;
2140 NSUInteger removeIndex;
2142 if (index >= insertIndex)
2144 removeIndex = index + aboveInsertIndexCount;
2145 aboveInsertIndexCount++;
2149 removeIndex = index;
2153 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2154 [QueueFileArray removeObjectAtIndex:removeIndex];
2155 [QueueFileArray insertObject:object atIndex:insertIndex];
2158 index = [indexSet indexLessThanIndex:index];
2160 /* We save all of the Queue data here
2161 * and it also gets sent back to the queue controller*/
2162 [self saveQueueFileItem];
2168 #pragma mark Queue Job Processing
2170 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2172 int i = currentQueueEncodeIndex;
2173 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2175 /* We save all of the Queue data here */
2176 [self saveQueueFileItem];
2177 /* We Reload the New Table data for presets */
2178 //[fPresetsOutlineView reloadData];
2180 /* Since we have now marked a queue item as done
2181 * we can go ahead and increment currentQueueEncodeIndex
2182 * so that if there is anything left in the queue we can
2183 * go ahead and move to the next item if we want to */
2184 currentQueueEncodeIndex++ ;
2185 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2186 int queueItems = [QueueFileArray count];
2187 /* If we still have more items in our queue, lets go to the next one */
2188 if (currentQueueEncodeIndex < queueItems)
2190 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2191 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2195 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2199 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2200 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2202 /* Tell HB to output a new activity log file for this encode */
2203 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2206 /* use a bool to determine whether or not we can decrypt using vlc */
2207 BOOL cancelScanDecrypt = 0;
2208 /* set the bool so that showNewScan knows to apply the appropriate queue
2209 * settings as this is a queue rescan
2211 applyQueueToScan = YES;
2212 NSString *path = scanPath;
2213 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2215 /*On Screen Notification*/
2217 //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2218 //[NSApp requestUserAttention:NSCriticalRequest];
2220 if( [detector isVideoDVD] )
2222 // The chosen path was actually on a DVD, so use the raw block
2223 // device path instead.
2224 path = [detector devicePath];
2225 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2227 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2228 NSString *vlcPath = @"/Applications/VLC.app";
2229 NSFileManager * fileManager = [NSFileManager defaultManager];
2230 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2232 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2233 cancelScanDecrypt = 1;
2234 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2236 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");
2237 [NSApp requestUserAttention:NSCriticalRequest];
2239 if (status == NSAlertDefaultReturn)
2241 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2242 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2244 else if (status == NSAlertAlternateReturn)
2246 /* User chose to cancel the scan */
2247 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2251 /* 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 */
2252 cancelScanDecrypt = 0;
2253 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2259 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2260 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2264 if (cancelScanDecrypt == 0)
2266 /* we actually pass the scan off to libhb here */
2267 /* If there is no title number passed to scan, we use "0"
2268 * which causes the default behavior of a full source scan
2274 if (scanTitleNum > 0)
2276 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2279 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2280 /* We use our advance pref to determine how many previews to scan */
2281 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2282 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2286 /* This method was originally used to load up a new queue item in the gui and
2287 * then start processing it. However we now have modified -prepareJob and use a second
2288 * instance of libhb to do our actual encoding, therefor right now it is not required.
2289 * Nonetheless I want to leave this in here
2290 * because basically its everything we need to be able to actually modify a pending queue
2291 * item in the gui and resave it. At least for now - dynaflash
2294 - (IBAction)applyQueueSettings:(id)sender
2296 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2297 hb_job_t * job = fTitle->job;
2299 /* Set title number and chapters */
2300 /* since the queue only scans a single title, we really don't need to pick a title */
2301 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2303 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2304 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2307 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2308 [self formatPopUpChanged:nil];
2310 /* Chapter Markers*/
2311 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2312 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2313 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2314 /* Mux mp4 with http optimization */
2315 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2318 /* We set the advanced opt string here if applicable*/
2319 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2320 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2322 /* Lets run through the following functions to get variables set there */
2323 [self videoEncoderPopUpChanged:nil];
2324 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2325 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2326 [self calculateBitrate:nil];
2329 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2331 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2332 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2333 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2335 [self videoMatrixChanged:nil];
2337 /* Video framerate */
2338 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2339 detected framerate in the fVidRatePopUp so we use index 0*/
2340 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2342 [fVidRatePopUp selectItemAtIndex: 0];
2346 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2349 /* 2 Pass Encoding */
2350 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2351 [self twoPassCheckboxChanged:nil];
2352 /* Turbo 1st pass for 2 Pass Encoding */
2353 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2356 if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2358 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2360 [fAudLang1PopUp selectItemAtIndex: 1];
2362 [self audioTrackPopUpChanged: fAudLang1PopUp];
2363 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2364 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2365 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2366 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2368 if ([fAudTrack1MixPopUp selectedItem] == nil)
2370 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2372 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2373 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2374 if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2376 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2378 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2379 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2381 if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2383 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2385 [fAudLang2PopUp selectItemAtIndex: 1];
2387 [self audioTrackPopUpChanged: fAudLang2PopUp];
2388 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2389 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2390 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2391 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2393 if ([fAudTrack2MixPopUp selectedItem] == nil)
2395 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2397 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2398 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2399 if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2401 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2403 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2404 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2406 if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2408 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2410 [fAudLang3PopUp selectItemAtIndex: 1];
2412 [self audioTrackPopUpChanged: fAudLang3PopUp];
2413 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2414 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2415 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2416 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2418 if ([fAudTrack3MixPopUp selectedItem] == nil)
2420 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2422 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2423 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2424 if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2426 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2428 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2429 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2431 if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2433 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2435 [fAudLang4PopUp selectItemAtIndex: 1];
2437 [self audioTrackPopUpChanged: fAudLang4PopUp];
2438 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2439 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2440 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2441 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2443 if ([fAudTrack4MixPopUp selectedItem] == nil)
2445 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2447 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2448 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2449 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2451 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2453 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2454 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2459 [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2460 /* Forced Subtitles */
2461 [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2463 /* Picture Settings */
2464 /* we check to make sure the presets width/height does not exceed the sources width/height */
2465 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2467 /* if so, then we use the sources height and width to avoid scaling up */
2468 job->width = fTitle->width;
2469 job->height = fTitle->height;
2471 else // source width/height is >= the preset height/width
2473 /* we can go ahead and use the presets values for height and width */
2474 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2475 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2477 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2478 if (job->keep_ratio == 1)
2480 hb_fix_aspect( job, HB_KEEP_WIDTH );
2481 if( job->height > fTitle->height )
2483 job->height = fTitle->height;
2484 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2487 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2490 /* If Cropping is set to custom, then recall all four crop values from
2491 when the preset was created and apply them */
2492 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2494 [fPictureController setAutoCrop:NO];
2496 /* Here we use the custom crop values saved at the time the preset was saved */
2497 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2498 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2499 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2500 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2503 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2505 [fPictureController setAutoCrop:YES];
2506 /* Here we use the auto crop values determined right after scan */
2507 job->crop[0] = AutoCropTop;
2508 job->crop[1] = AutoCropBottom;
2509 job->crop[2] = AutoCropLeft;
2510 job->crop[3] = AutoCropRight;
2516 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2519 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2521 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2523 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2525 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2527 [fPictureController setGrayscale:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2529 [self calculatePictureSizing:nil];
2532 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2533 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2534 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2535 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2537 /* Deselect the currently selected Preset if there is one*/
2538 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2539 //[self selectPreset:nil];
2541 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2542 /* Change UI to show "Custom" settings are being used */
2543 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2545 curUserPresetChosenNum = nil;
2549 /* Deselect the currently selected Preset if there is one*/
2550 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2551 /* Change UI to show "Custom" settings are being used */
2552 [fPresetSelectedDisplay setStringValue: @"Custom"];
2554 //curUserPresetChosenNum = nil;
2557 /* We need to set this bool back to NO, in case the user wants to do a scan */
2558 //applyQueueToScan = NO;
2560 /* so now we go ahead and process the new settings */
2561 [self processNewQueueEncode];
2566 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2567 - (void) processNewQueueEncode
2569 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2570 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2571 hb_job_t * job = title->job;
2573 if( !hb_list_count( list ) )
2575 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2579 [self writeToActivityLog: "processNewQueueEncode title list is: %d", hb_list_count( list )];
2582 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2583 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2584 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2585 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2586 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2588 if( [[queueToApply objectForKey:@"SubtitlesForced"] intValue] == 1 )
2589 job->subtitle_force = 1;
2591 job->subtitle_force = 0;
2594 * subtitle of -1 is a scan
2596 if( job->subtitle == -1 )
2601 * When subtitle scan is enabled do a fast pre-scan job
2602 * which will determine which subtitles to enable, if any.
2605 x264opts_tmp = job->x264opts;
2608 job->x264opts = NULL;
2610 job->indepth_scan = 1;
2612 job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
2613 *(job->select_subtitle) = NULL;
2616 * Add the pre-scan job
2618 hb_add( fQueueEncodeLibhb, job );
2619 job->x264opts = x264opts_tmp;
2622 job->select_subtitle = NULL;
2624 /* No subtitle were selected, so reset the subtitle to -1 (which before
2625 * this point meant we were scanning
2627 if( job->subtitle == -2 )
2630 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2632 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
2633 job->indepth_scan = 0;
2636 * Do not autoselect subtitles on the first pass of a two pass
2638 job->select_subtitle = NULL;
2642 hb_add( fQueueEncodeLibhb, job );
2646 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2647 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2649 job->select_subtitle = subtitle_tmp;
2651 hb_add( fQueueEncodeLibhb, job );
2656 job->indepth_scan = 0;
2659 hb_add( fQueueEncodeLibhb, job );
2662 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2663 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2664 /* Lets mark our new encode as 1 or "Encoding" */
2665 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2666 [self saveQueueFileItem];
2667 /* We should be all setup so let 'er rip */
2672 #pragma mark Live Preview
2673 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2674 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2677 - (void) prepareJobForPreview
2679 hb_list_t * list = hb_get_titles( fHandle );
2680 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2681 [fSrcTitlePopUp indexOfSelectedItem] );
2682 hb_job_t * job = title->job;
2683 hb_audio_config_t * audio;
2685 /* Chapter selection */
2686 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
2687 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
2689 /* Format (Muxer) and Video Encoder */
2690 job->mux = [[fDstFormatPopUp selectedItem] tag];
2691 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
2693 job->chapter_markers = 0;
2695 if( job->vcodec & HB_VCODEC_X264 )
2697 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2698 Currently only used with Constant Quality setting*/
2699 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
2704 /* Below Sends x264 options to the core library if x264 is selected*/
2705 /* Lets use this as per Nyx, Thanks Nyx!*/
2706 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2707 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
2708 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
2713 /* Video settings */
2714 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
2715 * and detelecine is on, so we handle that in the logic below
2718 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
2720 /* a specific framerate has been chosen */
2721 job->vrate = 27000000;
2722 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
2723 /* We are not same as source so we set job->cfr to 1
2724 * to enable constant frame rate since user has specified
2725 * a specific framerate*/
2730 /* We are same as source (variable) */
2731 job->vrate = title->rate;
2732 job->vrate_base = title->rate_base;
2733 /* We are same as source so we set job->cfr to 0
2734 * to enable true same as source framerate */
2736 /* If we are same as source and we have detelecine on, we need to turn on
2739 if ([fPictureController detelecine] == 1)
2745 switch( [fVidQualityMatrix selectedRow] )
2749 Bitrate should already have been calculated and displayed
2750 in fVidBitrateField, so let's just use it */
2752 job->vquality = -1.0;
2753 job->vbitrate = [fVidBitrateField intValue];
2756 job->vquality = [fVidQualityRFField floatValue];
2761 /* Subtitle settings */
2762 job->subtitle = [fSubPopUp indexOfSelectedItem] - 2;
2764 /* Audio tracks and mixdowns */
2765 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
2766 int audiotrack_count = hb_list_count(job->list_audio);
2767 for( int i = 0; i < audiotrack_count;i++)
2769 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
2770 hb_list_rem(job->list_audio, temp_audio);
2772 /* Now lets add our new tracks to the audio list here */
2773 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2775 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2776 hb_audio_config_init(audio);
2777 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2778 /* We go ahead and assign values to our audio->out.<properties> */
2779 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2780 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
2781 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
2782 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
2783 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
2784 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
2786 hb_audio_add( job, audio );
2789 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2791 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2792 hb_audio_config_init(audio);
2793 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2794 /* We go ahead and assign values to our audio->out.<properties> */
2795 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2796 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
2797 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
2798 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
2799 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
2800 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
2802 hb_audio_add( job, audio );
2807 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2809 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2810 hb_audio_config_init(audio);
2811 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2812 /* We go ahead and assign values to our audio->out.<properties> */
2813 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2814 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
2815 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
2816 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
2817 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
2818 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
2820 hb_audio_add( job, audio );
2825 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2827 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2828 hb_audio_config_init(audio);
2829 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2830 /* We go ahead and assign values to our audio->out.<properties> */
2831 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2832 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
2833 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
2834 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
2835 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
2836 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
2838 hb_audio_add( job, audio );
2847 /* Though Grayscale is not really a filter, per se
2848 * we put it here since its in the filters panel
2851 if ([fPictureController grayscale])
2860 /* Initialize the filters list */
2861 job->filters = hb_list_init();
2863 /* Now lets call the filters if applicable.
2864 * The order of the filters is critical
2868 if ([fPictureController detelecine] == 1)
2870 hb_list_add( job->filters, &hb_filter_detelecine );
2872 if ([fPictureController detelecine] == 2)
2874 /* use a custom detelecine string */
2875 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
2876 hb_list_add( job->filters, &hb_filter_detelecine );
2878 if ([fPictureController useDecomb] == 1)
2881 if ([fPictureController decomb] == 1)
2883 /* Run old deinterlacer fd by default */
2884 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
2885 hb_list_add( job->filters, &hb_filter_decomb );
2887 /* we add the custom string if present */
2888 if ([fPictureController decomb] == 2)
2890 /* use a custom decomb string */
2891 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
2892 hb_list_add( job->filters, &hb_filter_decomb );
2899 if ([fPictureController deinterlace] == 1)
2901 /* Run old deinterlacer fd by default */
2902 hb_filter_deinterlace.settings = "-1";
2903 hb_list_add( job->filters, &hb_filter_deinterlace );
2905 else if ([fPictureController deinterlace] == 2)
2907 /* Yadif mode 0 (without spatial deinterlacing.) */
2908 hb_filter_deinterlace.settings = "2";
2909 hb_list_add( job->filters, &hb_filter_deinterlace );
2911 else if ([fPictureController deinterlace] == 3)
2913 /* Yadif (with spatial deinterlacing) */
2914 hb_filter_deinterlace.settings = "0";
2915 hb_list_add( job->filters, &hb_filter_deinterlace );
2917 else if ([fPictureController deinterlace] == 4)
2919 /* we add the custom string if present */
2920 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
2921 hb_list_add( job->filters, &hb_filter_deinterlace );
2926 if ([fPictureController denoise] == 1) // Weak in popup
2928 hb_filter_denoise.settings = "2:1:2:3";
2929 hb_list_add( job->filters, &hb_filter_denoise );
2931 else if ([fPictureController denoise] == 2) // Medium in popup
2933 hb_filter_denoise.settings = "3:2:2:3";
2934 hb_list_add( job->filters, &hb_filter_denoise );
2936 else if ([fPictureController denoise] == 3) // Strong in popup
2938 hb_filter_denoise.settings = "7:7:5:5";
2939 hb_list_add( job->filters, &hb_filter_denoise );
2941 else if ([fPictureController denoise] == 4) // custom in popup
2943 /* we add the custom string if present */
2944 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
2945 hb_list_add( job->filters, &hb_filter_denoise );
2948 /* Deblock (uses pp7 default) */
2949 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
2950 * the macgui's purposes a value of 0 actually means to not even use the filter
2951 * current hb_filter_deblock.settings valid ranges are from 5 - 15
2953 if ([fPictureController deblock] != 0)
2955 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
2956 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
2957 hb_list_add( job->filters, &hb_filter_deblock );
2964 #pragma mark Job Handling
2970 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2971 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2972 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2973 hb_job_t * job = title->job;
2974 hb_audio_config_t * audio;
2975 /* Chapter selection */
2976 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
2977 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
2979 /* Format (Muxer) and Video Encoder */
2980 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
2981 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
2984 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
2985 //if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
2987 /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
2988 mpeg4 and the checkbox being checked
2989 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
2990 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
2992 job->largeFileSize = 1;
2996 job->largeFileSize = 0;
2998 /* We set http optimized mp4 here */
2999 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3001 job->mp4_optimize = 1;
3005 job->mp4_optimize = 0;
3010 /* We set the chapter marker extraction here based on the format being
3011 mpeg4 or mkv and the checkbox being checked */
3012 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3014 job->chapter_markers = 1;
3016 /* now lets get our saved chapter names out the array in the queue file
3017 * and insert them back into the title chapter list. We have it here,
3018 * because unless we are inserting chapter markers there is no need to
3019 * spend the overhead of iterating through the chapter names array imo
3020 * Also, note that if for some reason we don't apply chapter names, the
3021 * chapters just come out 001, 002, etc. etc.
3024 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3026 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3028 while (tempObject = [enumerator nextObject])
3030 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3031 if( chapter != NULL )
3033 strncpy( chapter->title, [tempObject UTF8String], 1023);
3034 chapter->title[1023] = '\0';
3041 job->chapter_markers = 0;
3044 if( job->vcodec & HB_VCODEC_X264 )
3046 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3055 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
3056 Currently only used with Constant Quality setting*/
3057 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2)
3061 /* Below Sends x264 options to the core library if x264 is selected*/
3062 /* Lets use this as per Nyx, Thanks Nyx!*/
3063 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3064 /* Turbo first pass if two pass and Turbo First pass is selected */
3065 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3067 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3068 NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3069 /* append the "Turbo" string variable to the existing opts string.
3070 Note: the "Turbo" string must be appended, not prepended to work properly*/
3071 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3072 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3076 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3082 /* Picture Size Settings */
3083 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3084 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3086 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3087 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3090 /* Here we use the crop values saved at the time the preset was saved */
3091 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3092 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3093 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3094 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3096 /* Video settings */
3099 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3100 * and detelecine is on, so we handle that in the logic below
3103 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3105 /* a specific framerate has been chosen */
3106 job->vrate = 27000000;
3107 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3108 /* We are not same as source so we set job->cfr to 1
3109 * to enable constant frame rate since user has specified
3110 * a specific framerate*/
3115 /* We are same as source (variable) */
3116 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3117 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3118 /* We are same as source so we set job->cfr to 0
3119 * to enable true same as source framerate */
3121 /* If we are same as source and we have detelecine on, we need to turn on
3124 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3130 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3133 Bitrate should already have been calculated and displayed
3134 in fVidBitrateField, so let's just use it same as abr*/
3135 job->vquality = -1.0;
3136 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3138 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3140 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3145 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3146 /* Subtitle settings */
3147 job->subtitle = [[queueToApply objectForKey:@"JobSubtitlesIndex"] intValue] - 2;
3149 /* Audio tracks and mixdowns */
3150 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3151 int audiotrack_count = hb_list_count(job->list_audio);
3152 for( int i = 0; i < audiotrack_count;i++)
3154 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3155 hb_list_rem(job->list_audio, temp_audio);
3157 /* Now lets add our new tracks to the audio list here */
3158 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3160 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3161 hb_audio_config_init(audio);
3162 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3163 /* We go ahead and assign values to our audio->out.<properties> */
3164 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3165 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3166 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3167 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3168 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3169 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3171 hb_audio_add( job, audio );
3174 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3177 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3178 hb_audio_config_init(audio);
3179 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3180 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3181 /* We go ahead and assign values to our audio->out.<properties> */
3182 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3183 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3184 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3185 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3186 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3187 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3189 hb_audio_add( job, audio );
3193 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3195 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3196 hb_audio_config_init(audio);
3197 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3198 /* We go ahead and assign values to our audio->out.<properties> */
3199 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3200 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3201 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3202 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3203 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3204 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3206 hb_audio_add( job, audio );
3210 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3212 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3213 hb_audio_config_init(audio);
3214 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3215 /* We go ahead and assign values to our audio->out.<properties> */
3216 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3217 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3218 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3219 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3220 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3221 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3223 hb_audio_add( job, audio );
3228 job->filters = hb_list_init();
3230 /* Now lets call the filters if applicable.
3231 * The order of the filters is critical
3234 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3236 //if ([queueToApply objectForKey:@"PictureDetelecineCustom"])
3237 hb_list_add( job->filters, &hb_filter_detelecine );
3239 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3241 /* use a custom detelecine string */
3242 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3243 hb_list_add( job->filters, &hb_filter_detelecine );
3246 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3249 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3251 /* Run old deinterlacer fd by default */
3252 hb_list_add( job->filters, &hb_filter_decomb );
3254 /* we add the custom string if present */
3255 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3257 /* use a custom decomb string */
3258 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3259 hb_list_add( job->filters, &hb_filter_decomb );
3267 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3269 /* Run old deinterlacer fd by default */
3270 hb_filter_deinterlace.settings = "-1";
3271 hb_list_add( job->filters, &hb_filter_deinterlace );
3273 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3275 /* Yadif mode 0 (without spatial deinterlacing.) */
3276 hb_filter_deinterlace.settings = "2";
3277 hb_list_add( job->filters, &hb_filter_deinterlace );
3279 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3281 /* Yadif (with spatial deinterlacing) */
3282 hb_filter_deinterlace.settings = "0";
3283 hb_list_add( job->filters, &hb_filter_deinterlace );
3285 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3287 /* we add the custom string if present */
3288 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3289 hb_list_add( job->filters, &hb_filter_deinterlace );
3295 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Weak in popup
3297 hb_filter_denoise.settings = "2:1:2:3";
3298 hb_list_add( job->filters, &hb_filter_denoise );
3300 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Medium in popup
3302 hb_filter_denoise.settings = "3:2:2:3";
3303 hb_list_add( job->filters, &hb_filter_denoise );
3305 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Strong in popup
3307 hb_filter_denoise.settings = "7:7:5:5";
3308 hb_list_add( job->filters, &hb_filter_denoise );
3310 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Custom in popup
3312 /* we add the custom string if present */
3313 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3314 hb_list_add( job->filters, &hb_filter_denoise );
3317 /* Deblock (uses pp7 default) */
3318 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3319 * the macgui's purposes a value of 0 actually means to not even use the filter
3320 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3322 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3324 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3325 hb_list_add( job->filters, &hb_filter_deblock );
3327 [self writeToActivityLog: "prepareJob exiting"];
3332 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3334 - (IBAction) addToQueue: (id) sender
3336 /* We get the destination directory from the destination field here */
3337 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3338 /* We check for a valid destination here */
3339 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3341 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3348 BOOL fileExistsInQueue;
3349 fileExistsInQueue = NO;
3351 /* We check for and existing file here */
3352 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3357 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3359 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3361 while (tempObject = [enumerator nextObject])
3363 NSDictionary *thisQueueDict = tempObject;
3364 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3366 fileExistsInQueue = YES;
3372 if(fileExists == YES)
3374 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
3375 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3376 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3377 NULL, NULL, [NSString stringWithFormat:
3378 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3379 [fDstFile2Field stringValue]] );
3381 else if (fileExistsInQueue == YES)
3383 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
3384 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3385 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3386 NULL, NULL, [NSString stringWithFormat:
3387 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3388 [fDstFile2Field stringValue]] );
3392 [self doAddToQueue];
3396 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
3397 the user if they want to overwrite an exiting movie file.
3399 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
3400 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3402 if( returnCode == NSAlertAlternateReturn )
3403 [self doAddToQueue];
3406 - (void) doAddToQueue
3408 [self addQueueFileItem ];
3413 /* Rip: puts up an alert before ultimately calling doRip
3415 - (IBAction) Rip: (id) sender
3417 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
3418 /* Rip or Cancel ? */
3420 hb_get_state2( fQueueEncodeLibhb, &s );
3422 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
3424 [self Cancel: sender];
3428 /* We check to see if we need to warn the user that the computer will go to sleep
3429 or shut down when encoding is finished */
3430 [self remindUserOfSleepOrShutdown];
3432 // If there are pending jobs in the queue, then this is a rip the queue
3433 if (fPendingCount > 0)
3435 /* here lets start the queue with the first pending item */
3436 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3441 // Before adding jobs to the queue, check for a valid destination.
3443 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3444 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3446 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3450 /* We check for duplicate name here */
3451 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
3453 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
3454 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3455 @selector( overWriteAlertDone:returnCode:contextInfo: ),
3456 NULL, NULL, [NSString stringWithFormat:
3457 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3458 [fDstFile2Field stringValue]] );
3460 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
3464 /* if there are no pending jobs in the queue, then add this one to the queue and rip
3465 otherwise, just rip the queue */
3466 if(fPendingCount == 0)
3468 [self writeToActivityLog: "Rip: No pending jobs, so sending this one to doAddToQueue"];
3469 [self doAddToQueue];
3472 /* go right to processing the new queue encode */
3473 [self writeToActivityLog: "Rip: Going right to performNewQueueScan"];
3474 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3479 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
3480 want to overwrite an exiting movie file.
3482 - (void) overWriteAlertDone: (NSWindow *) sheet
3483 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3485 if( returnCode == NSAlertAlternateReturn )
3487 /* if there are no jobs in the queue, then add this one to the queue and rip
3488 otherwise, just rip the queue */
3489 if( fPendingCount == 0 )
3491 [self doAddToQueue];
3494 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3495 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
3496 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3501 - (void) remindUserOfSleepOrShutdown
3503 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
3505 /*Warn that computer will sleep after encoding*/
3508 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);
3509 [NSApp requestUserAttention:NSCriticalRequest];
3510 if ( reminduser == NSAlertAlternateReturn )
3512 [self showPreferencesWindow:nil];
3515 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
3517 /*Warn that computer will shut down after encoding*/
3520 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);
3521 [NSApp requestUserAttention:NSCriticalRequest];
3522 if ( reminduser == NSAlertAlternateReturn )
3524 [self showPreferencesWindow:nil];
3533 /* Let libhb do the job */
3534 hb_start( fQueueEncodeLibhb );
3535 /*set the fEncodeState State */
3540 //------------------------------------------------------------------------------------
3541 // Displays an alert asking user if the want to cancel encoding of current job.
3542 // Cancel: returns immediately after posting the alert. Later, when the user
3543 // acknowledges the alert, doCancelCurrentJob is called.
3544 //------------------------------------------------------------------------------------
3545 - (IBAction)Cancel: (id)sender
3547 if (!fQueueController) return;
3549 hb_pause( fQueueEncodeLibhb );
3550 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
3552 // Which window to attach the sheet to?
3553 NSWindow * docWindow;
3554 if ([sender respondsToSelector: @selector(window)])
3555 docWindow = [sender window];
3557 docWindow = fWindow;
3559 NSBeginCriticalAlertSheet(
3561 NSLocalizedString(@"Continue Encoding", nil),
3562 NSLocalizedString(@"Cancel Current and Stop", nil),
3563 NSLocalizedString(@"Cancel Current and Continue", nil),
3565 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
3566 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
3568 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
3571 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
3573 hb_resume( fQueueEncodeLibhb );
3574 if (returnCode == NSAlertOtherReturn)
3576 [self doCancelCurrentJob]; // <- this also stops libhb
3578 if (returnCode == NSAlertAlternateReturn)
3580 [self doCancelCurrentJobAndStop];
3584 //------------------------------------------------------------------------------------
3585 // Cancels and deletes the current job and stops libhb from processing the remaining
3587 //------------------------------------------------------------------------------------
3588 - (void) doCancelCurrentJob
3590 // Stop the current job. hb_stop will only cancel the current pass and then set
3591 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
3592 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
3593 // remaining passes of the job and then start the queue back up if there are any
3597 hb_stop( fQueueEncodeLibhb );
3599 // Delete all remaining jobs since libhb doesn't do this on its own.
3601 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3602 hb_rem( fQueueEncodeLibhb, job );
3604 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3606 // now that we've stopped the currently encoding job, lets mark it as cancelled
3607 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3608 // and as always, save it in the queue .plist...
3609 /* We save all of the Queue data here */
3610 [self saveQueueFileItem];
3611 // so now lets move to
3612 currentQueueEncodeIndex++ ;
3613 // ... and see if there are more items left in our queue
3614 int queueItems = [QueueFileArray count];
3615 /* If we still have more items in our queue, lets go to the next one */
3616 if (currentQueueEncodeIndex < queueItems)
3618 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
3619 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
3621 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3625 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
3630 - (void) doCancelCurrentJobAndStop
3632 hb_stop( fQueueEncodeLibhb );
3634 // Delete all remaining jobs since libhb doesn't do this on its own.
3636 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3637 hb_rem( fQueueEncodeLibhb, job );
3640 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3642 // now that we've stopped the currently encoding job, lets mark it as cancelled
3643 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3644 // and as always, save it in the queue .plist...
3645 /* We save all of the Queue data here */
3646 [self saveQueueFileItem];
3647 // so now lets move to
3648 currentQueueEncodeIndex++ ;
3649 [self writeToActivityLog: "cancelling current job and stopping the queue"];
3651 - (IBAction) Pause: (id) sender
3654 hb_get_state2( fQueueEncodeLibhb, &s );
3656 if( s.state == HB_STATE_PAUSED )
3658 hb_resume( fQueueEncodeLibhb );
3662 hb_pause( fQueueEncodeLibhb );
3667 #pragma mark GUI Controls Changed Methods
3669 - (IBAction) titlePopUpChanged: (id) sender
3671 hb_list_t * list = hb_get_titles( fHandle );
3672 hb_title_t * title = (hb_title_t*)
3673 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3675 /* If Auto Naming is on. We create an output filename of dvd name - title number */
3676 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
3678 [fDstFile2Field setStringValue: [NSString stringWithFormat:
3679 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
3680 [browsedSourceDisplayName stringByDeletingPathExtension],
3682 [[fDstFile2Field stringValue] pathExtension]]];
3685 /* Update chapter popups */
3686 [fSrcChapterStartPopUp removeAllItems];
3687 [fSrcChapterEndPopUp removeAllItems];
3688 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
3690 [fSrcChapterStartPopUp addItemWithTitle: [NSString
3691 stringWithFormat: @"%d", i + 1]];
3692 [fSrcChapterEndPopUp addItemWithTitle: [NSString
3693 stringWithFormat: @"%d", i + 1]];
3696 [fSrcChapterStartPopUp selectItemAtIndex: 0];
3697 [fSrcChapterEndPopUp selectItemAtIndex:
3698 hb_list_count( title->list_chapter ) - 1];
3699 [self chapterPopUpChanged:nil];
3701 /* Start Get and set the initial pic size for display */
3702 hb_job_t * job = title->job;
3705 /* Set Auto Crop to on upon selecting a new title */
3706 [fPictureController setAutoCrop:YES];
3708 /* We get the originial output picture width and height and put them
3709 in variables for use with some presets later on */
3710 PicOrigOutputWidth = job->width;
3711 PicOrigOutputHeight = job->height;
3712 AutoCropTop = job->crop[0];
3713 AutoCropBottom = job->crop[1];
3714 AutoCropLeft = job->crop[2];
3715 AutoCropRight = job->crop[3];
3717 /* Reset the new title in fPictureController && fPreviewController*/
3718 [fPictureController SetTitle:title];
3719 //[fPictureController SetTitle:title];
3720 /* Update subtitle popups */
3721 hb_subtitle_t * subtitle;
3722 [fSubPopUp removeAllItems];
3723 [fSubPopUp addItemWithTitle: @"None"];
3724 [fSubPopUp addItemWithTitle: @"Autoselect"];
3725 for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
3727 subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
3729 /* We cannot use NSPopUpButton's addItemWithTitle because
3730 it checks for duplicate entries */
3731 [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
3732 subtitle->lang] action: NULL keyEquivalent: @""];
3734 [fSubPopUp selectItemAtIndex: 0];
3736 [self subtitleSelectionChanged:nil];
3738 /* Update chapter table */
3739 [fChapterTitlesDelegate resetWithTitle:title];
3740 [fChapterTable reloadData];
3742 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3743 int audiotrack_count = hb_list_count(job->list_audio);
3744 for( int i = 0; i < audiotrack_count;i++)
3746 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3747 hb_list_rem(job->list_audio, temp_audio);
3750 /* Update audio popups */
3751 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
3752 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
3753 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
3754 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
3755 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
3756 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
3757 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
3758 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3759 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3760 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3762 /* changing the title may have changed the audio channels on offer, */
3763 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3764 [self audioTrackPopUpChanged: fAudLang1PopUp];
3765 [self audioTrackPopUpChanged: fAudLang2PopUp];
3766 [self audioTrackPopUpChanged: fAudLang3PopUp];
3767 [self audioTrackPopUpChanged: fAudLang4PopUp];
3769 [fVidRatePopUp selectItemAtIndex: 0];
3771 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
3772 [self calculatePictureSizing:nil];
3774 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
3775 [self selectPreset:nil];
3778 - (IBAction) chapterPopUpChanged: (id) sender
3781 /* If start chapter popup is greater than end chapter popup,
3782 we set the end chapter popup to the same as start chapter popup */
3783 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
3785 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
3789 hb_list_t * list = hb_get_titles( fHandle );
3790 hb_title_t * title = (hb_title_t *)
3791 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3793 hb_chapter_t * chapter;
3794 int64_t duration = 0;
3795 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
3796 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
3798 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3799 duration += chapter->duration;
3802 duration /= 90000; /* pts -> seconds */
3803 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
3804 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
3807 [self calculateBitrate: sender];
3810 - (IBAction) formatPopUpChanged: (id) sender
3812 NSString * string = [fDstFile2Field stringValue];
3813 int format = [fDstFormatPopUp indexOfSelectedItem];
3815 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
3816 [fDstMp4LargeFileCheck setHidden: YES];
3817 [fDstMp4HttpOptFileCheck setHidden: YES];
3818 [fDstMp4iPodFileCheck setHidden: YES];
3820 /* Update the Video Codec PopUp */
3821 /* lets get the tag of the currently selected item first so we might reset it later */
3822 int selectedVidEncoderTag;
3823 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
3825 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
3826 [fVidEncoderPopUp removeAllItems];
3827 NSMenuItem *menuItem;
3828 /* These video encoders are available to all of our current muxers, so lets list them once here */
3829 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
3830 [menuItem setTag: HB_VCODEC_FFMPEG];
3832 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (XviD)" action: NULL keyEquivalent: @""];
3833 [menuItem setTag: HB_VCODEC_XVID];
3837 /*Get Default MP4 File Extension*/
3838 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
3846 /* Add additional video encoders here */
3847 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3848 [menuItem setTag: HB_VCODEC_X264];
3849 /* We show the mp4 option checkboxes here since we are mp4 */
3850 [fCreateChapterMarkers setEnabled: YES];
3851 [fDstMp4LargeFileCheck setHidden: NO];
3852 [fDstMp4HttpOptFileCheck setHidden: NO];
3853 [fDstMp4iPodFileCheck setHidden: NO];
3858 /* Add additional video encoders here */
3859 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3860 [menuItem setTag: HB_VCODEC_X264];
3861 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3862 [menuItem setTag: HB_VCODEC_THEORA];
3863 /* We enable the create chapters checkbox here */
3864 [fCreateChapterMarkers setEnabled: YES];
3869 /* Add additional video encoders here */
3870 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3871 [menuItem setTag: HB_VCODEC_X264];
3872 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3873 [fCreateChapterMarkers setEnabled: NO];
3874 [fCreateChapterMarkers setState: NSOffState];
3879 /* Add additional video encoders here */
3880 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3881 [menuItem setTag: HB_VCODEC_THEORA];
3882 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3883 [fCreateChapterMarkers setEnabled: NO];
3884 [fCreateChapterMarkers setState: NSOffState];
3887 /* if we have a previously selected vid encoder tag, then try to select it */
3888 if (selectedVidEncoderTag)
3890 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
3894 [fVidEncoderPopUp selectItemAtIndex: 0];
3897 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
3898 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
3899 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
3900 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
3903 [self autoSetM4vExtension: sender];
3905 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
3907 if( SuccessfulScan )
3909 /* Add/replace to the correct extension */
3910 [self audioTrackPopUpChanged: fAudLang1PopUp];
3911 [self audioTrackPopUpChanged: fAudLang2PopUp];
3912 [self audioTrackPopUpChanged: fAudLang3PopUp];
3913 [self audioTrackPopUpChanged: fAudLang4PopUp];
3915 if( [fVidEncoderPopUp selectedItem] == nil )
3918 [fVidEncoderPopUp selectItemAtIndex:0];
3919 [self videoEncoderPopUpChanged:nil];
3921 /* changing the format may mean that we can / can't offer mono or 6ch, */
3922 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3924 /* We call the method to properly enable/disable turbo 2 pass */
3925 [self twoPassCheckboxChanged: sender];
3926 /* We call method method to change UI to reflect whether a preset is used or not*/
3929 [self customSettingUsed: sender];
3932 - (IBAction) autoSetM4vExtension: (id) sender
3934 if ( [fDstFormatPopUp indexOfSelectedItem] )
3937 NSString * extension = @"mp4";
3939 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3940 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3941 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3942 [fCreateChapterMarkers state] == NSOnState ||
3943 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
3948 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
3951 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
3952 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
3955 /* Method to determine if we should change the UI
3956 To reflect whether or not a Preset is being used or if
3957 the user is using "Custom" settings by determining the sender*/
3958 - (IBAction) customSettingUsed: (id) sender
3960 if ([sender stringValue])
3962 /* Deselect the currently selected Preset if there is one*/
3963 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3964 /* Change UI to show "Custom" settings are being used */
3965 [fPresetSelectedDisplay setStringValue: @"Custom"];
3967 curUserPresetChosenNum = nil;
3969 [self calculateBitrate:nil];
3974 #pragma mark - Video
3976 - (IBAction) videoEncoderPopUpChanged: (id) sender
3978 hb_job_t * job = fTitle->job;
3979 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
3981 [fAdvancedOptions setHidden:YES];
3982 /* If we are using x264 then show the x264 advanced panel*/
3983 if (videoEncoder == HB_VCODEC_X264)
3985 [fAdvancedOptions setHidden:NO];
3986 [self autoSetM4vExtension: sender];
3989 /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
3990 is being used as it borks up loose anamorphic .
3991 For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
3992 to use the index itself but this is easier */
3993 if (videoEncoder == HB_VCODEC_FFMPEG)
3995 if (job->anamorphic.mode == 2)
3997 job->anamorphic.mode = 0;
3999 [fPictureController setAllowLooseAnamorphic:NO];
4000 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4001 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4002 anything other than MP4.
4004 [fDstMp4iPodFileCheck setEnabled: NO];
4005 [fDstMp4iPodFileCheck setState: NSOffState];
4009 [fPictureController setAllowLooseAnamorphic:YES];
4010 [fDstMp4iPodFileCheck setEnabled: YES];
4012 [self setupQualitySlider];
4013 [self calculatePictureSizing: sender];
4014 [self twoPassCheckboxChanged: sender];
4018 - (IBAction) twoPassCheckboxChanged: (id) sender
4020 /* check to see if x264 is chosen */
4021 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4023 if( [fVidTwoPassCheck state] == NSOnState)
4025 [fVidTurboPassCheck setHidden: NO];
4029 [fVidTurboPassCheck setHidden: YES];
4030 [fVidTurboPassCheck setState: NSOffState];
4032 /* Make sure Two Pass is checked if Turbo is checked */
4033 if( [fVidTurboPassCheck state] == NSOnState)
4035 [fVidTwoPassCheck setState: NSOnState];
4040 [fVidTurboPassCheck setHidden: YES];
4041 [fVidTurboPassCheck setState: NSOffState];
4044 /* We call method method to change UI to reflect whether a preset is used or not*/
4045 [self customSettingUsed: sender];
4048 - (IBAction ) videoFrameRateChanged: (id) sender
4050 /* We call method method to calculatePictureSizing to error check detelecine*/
4051 [self calculatePictureSizing: sender];
4053 /* We call method method to change UI to reflect whether a preset is used or not*/
4054 [self customSettingUsed: sender];
4056 - (IBAction) videoMatrixChanged: (id) sender;
4058 bool target, bitrate, quality;
4060 target = bitrate = quality = false;
4061 if( [fVidQualityMatrix isEnabled] )
4063 switch( [fVidQualityMatrix selectedRow] )
4076 [fVidTargetSizeField setEnabled: target];
4077 [fVidBitrateField setEnabled: bitrate];
4078 [fVidQualitySlider setEnabled: quality];
4079 [fVidQualityRFField setEnabled: quality];
4080 [fVidQualityRFLabel setEnabled: quality];
4081 [fVidTwoPassCheck setEnabled: !quality &&
4082 [fVidQualityMatrix isEnabled]];
4085 [fVidTwoPassCheck setState: NSOffState];
4086 [fVidTurboPassCheck setHidden: YES];
4087 [fVidTurboPassCheck setState: NSOffState];
4090 [self qualitySliderChanged: sender];
4091 [self calculateBitrate: sender];
4092 [self customSettingUsed: sender];
4095 /* Use this method to setup the quality slider for cq/rf values depending on
4096 * the video encoder selected.
4098 - (void) setupQualitySlider
4100 /* Get the current slider maxValue to check for a change in slider scale later
4101 * so that we can choose a new similar value on the new slider scale */
4102 float previousMaxValue = [fVidQualitySlider maxValue];
4103 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4104 NSString * qpRFLabelString = @"QP:";
4106 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4108 [fVidQualitySlider setMinValue:0.0];
4109 [fVidQualitySlider setMaxValue:51.0];
4110 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4111 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4112 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4113 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0)
4115 qpRFLabelString = @"RF:";
4118 /* ffmpeg and xvid 1-31 */
4119 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG || [[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_XVID)
4121 [fVidQualitySlider setMinValue:1.0];
4122 [fVidQualitySlider setMaxValue:31.0];
4123 [fVidQualitySlider setNumberOfTickMarks:31];
4126 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4128 [fVidQualitySlider setMinValue:0.0];
4129 [fVidQualitySlider setMaxValue:63.0];
4130 [fVidQualitySlider setNumberOfTickMarks:64];
4132 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4134 /* check to see if we have changed slider scales */
4135 if (previousMaxValue != [fVidQualitySlider maxValue])
4137 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4138 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4139 [fVidQualitySlider setFloatValue:rf];
4142 [self qualitySliderChanged:nil];
4145 - (IBAction) qualitySliderChanged: (id) sender
4147 /* Our constant quality slider is in a range based
4148 * on each encoders qp/rf values. The range depends
4149 * on the encoder. Also, the range is inverse of quality
4150 * for all of the encoders *except* for theora
4151 * (ie. as the "quality" goes up, the cq or rf value
4152 * actually goes down). Since the IB sliders always set
4153 * their max value at the right end of the slider, we
4154 * will calculate the inverse, so as the slider floatValue
4155 * goes up, we will show the inverse in the rf field
4156 * so, the floatValue at the right for x264 would be 51
4157 * and our rf field needs to show 0 and vice versa.
4160 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4161 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4162 float sliderRfToPercent;
4163 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4165 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4166 sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4170 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4171 sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4173 [fVidConstantCell setTitle: [NSString stringWithFormat:
4174 NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
4176 [self customSettingUsed: sender];
4179 - (void) controlTextDidChange: (NSNotification *) notification
4181 [self calculateBitrate:nil];
4184 - (IBAction) calculateBitrate: (id) sender
4186 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4191 hb_list_t * list = hb_get_titles( fHandle );
4192 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4193 [fSrcTitlePopUp indexOfSelectedItem] );
4194 hb_job_t * job = title->job;
4195 hb_audio_config_t * audio;
4196 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4197 * Target Size Field, we also need the job info for the Muxer, the Chapters
4198 * as well as all of the audio track info.
4199 * This used to be accomplished by simply calling prepareJob here, however
4200 * since the resilient queue sets the queue array values instead of the job
4201 * values directly, we duplicate the old prepareJob code here for the variables
4204 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4205 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4206 job->mux = [[fDstFormatPopUp selectedItem] tag];
4208 /* Audio goes here */
4209 int audiotrack_count = hb_list_count(job->list_audio);
4210 for( int i = 0; i < audiotrack_count;i++)
4212 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4213 hb_list_rem(job->list_audio, temp_audio);
4215 /* Now we need our audio info here for each track if applicable */
4216 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4218 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4219 hb_audio_config_init(audio);
4220 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4221 /* We go ahead and assign values to our audio->out.<properties> */
4222 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4223 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4224 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4225 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4226 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4227 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4229 hb_audio_add( job, audio );
4232 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4234 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4235 hb_audio_config_init(audio);
4236 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4237 /* We go ahead and assign values to our audio->out.<properties> */
4238 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4239 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4240 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4241 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4242 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4243 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4245 hb_audio_add( job, audio );
4250 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4252 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4253 hb_audio_config_init(audio);
4254 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4255 /* We go ahead and assign values to our audio->out.<properties> */
4256 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4257 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
4258 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
4259 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
4260 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
4261 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
4263 hb_audio_add( job, audio );
4268 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4270 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4271 hb_audio_config_init(audio);
4272 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4273 /* We go ahead and assign values to our audio->out.<properties> */
4274 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4275 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
4276 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
4277 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
4278 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
4279 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
4281 hb_audio_add( job, audio );
4286 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
4290 #pragma mark - Picture
4292 /* lets set the picture size back to the max from right after title scan
4293 Lets use an IBAction here as down the road we could always use a checkbox
4294 in the gui to easily take the user back to max. Remember, the compiler
4295 resolves IBActions down to -(void) during compile anyway */
4296 - (IBAction) revertPictureSizeToMax: (id) sender
4298 hb_job_t * job = fTitle->job;
4299 /* Here we apply the title source and height */
4300 job->width = fTitle->width;
4301 job->height = fTitle->height;
4303 [self calculatePictureSizing: sender];
4304 /* We call method to change UI to reflect whether a preset is used or not*/
4305 [self customSettingUsed: sender];
4309 * Registers changes made in the Picture Settings Window.
4312 - (void)pictureSettingsDidChange
4314 [self calculatePictureSizing:nil];
4317 /* Get and Display Current Pic Settings in main window */
4318 - (IBAction) calculatePictureSizing: (id) sender
4320 if (fTitle->job->anamorphic.mode > 0)
4322 fTitle->job->keep_ratio = 0;
4325 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
4327 NSString *picCropping;
4328 /* Set the display field for crop as per boolean */
4329 if (![fPictureController autoCrop])
4331 picCropping = @"Custom";
4335 picCropping = @"Auto";
4337 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]]];
4339 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
4341 NSString *videoFilters;
4344 if ([fPictureController detelecine] == 1)
4346 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
4348 else if ([fPictureController detelecine] == 2)
4350 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
4354 if ([fPictureController useDecomb] == 1)
4357 if ([fPictureController decomb] == 1)
4359 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
4361 else if ([fPictureController decomb] == 2)
4363 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
4369 if ([fPictureController deinterlace] > 0)
4371 fTitle->job->deinterlace = 1;
4375 fTitle->job->deinterlace = 0;
4378 if ([fPictureController deinterlace] == 1)
4380 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
4382 else if ([fPictureController deinterlace] == 2)
4384 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
4386 else if ([fPictureController deinterlace] == 3)
4388 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
4390 else if ([fPictureController deinterlace] == 4)
4392 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
4398 if ([fPictureController denoise] == 1)
4400 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
4402 else if ([fPictureController denoise] == 2)
4404 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
4406 else if ([fPictureController denoise] == 3)
4408 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
4410 else if ([fPictureController denoise] == 4)
4412 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
4416 if ([fPictureController deblock] > 0)
4418 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
4422 if ([fPictureController grayscale])
4424 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
4426 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
4428 [fPictureController reloadStillPreview];
4433 #pragma mark - Audio and Subtitles
4434 - (IBAction) audioCodecsPopUpChanged: (id) sender
4437 NSPopUpButton * audiotrackPopUp;
4438 NSPopUpButton * sampleratePopUp;
4439 NSPopUpButton * bitratePopUp;
4440 NSPopUpButton * audiocodecPopUp;
4441 if (sender == fAudTrack1CodecPopUp)
4443 audiotrackPopUp = fAudLang1PopUp;
4444 audiocodecPopUp = fAudTrack1CodecPopUp;
4445 sampleratePopUp = fAudTrack1RatePopUp;
4446 bitratePopUp = fAudTrack1BitratePopUp;
4448 else if (sender == fAudTrack2CodecPopUp)
4450 audiotrackPopUp = fAudLang2PopUp;
4451 audiocodecPopUp = fAudTrack2CodecPopUp;
4452 sampleratePopUp = fAudTrack2RatePopUp;
4453 bitratePopUp = fAudTrack2BitratePopUp;
4455 else if (sender == fAudTrack3CodecPopUp)
4457 audiotrackPopUp = fAudLang3PopUp;
4458 audiocodecPopUp = fAudTrack3CodecPopUp;
4459 sampleratePopUp = fAudTrack3RatePopUp;
4460 bitratePopUp = fAudTrack3BitratePopUp;
4464 audiotrackPopUp = fAudLang4PopUp;
4465 audiocodecPopUp = fAudTrack4CodecPopUp;
4466 sampleratePopUp = fAudTrack4RatePopUp;
4467 bitratePopUp = fAudTrack4BitratePopUp;
4470 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
4471 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4472 [self audioTrackPopUpChanged: audiotrackPopUp];
4476 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
4478 /* We will be setting the enabled/disabled state of each tracks audio controls based on
4479 * the settings of the source audio for that track. We leave the samplerate and bitrate
4480 * to audiotrackMixdownChanged
4483 /* We will first verify that a lower track number has been selected before enabling each track
4484 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
4486 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4488 [fAudLang2PopUp setEnabled: NO];
4489 [fAudLang2PopUp selectItemAtIndex: 0];
4493 [fAudLang2PopUp setEnabled: YES];
4496 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4498 [fAudLang3PopUp setEnabled: NO];
4499 [fAudLang3PopUp selectItemAtIndex: 0];
4503 [fAudLang3PopUp setEnabled: YES];
4505 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4507 [fAudLang4PopUp setEnabled: NO];
4508 [fAudLang4PopUp selectItemAtIndex: 0];
4512 [fAudLang4PopUp setEnabled: YES];
4514 /* enable/disable the mixdown text and popupbutton for audio track 1 */
4515 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4516 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4517 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4518 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4519 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4520 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4521 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4523 [fAudTrack1CodecPopUp removeAllItems];
4524 [fAudTrack1MixPopUp removeAllItems];
4525 [fAudTrack1RatePopUp removeAllItems];
4526 [fAudTrack1BitratePopUp removeAllItems];
4527 [fAudTrack1DrcSlider setFloatValue: 1.00];
4528 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4530 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4532 [fAudTrack1RatePopUp setEnabled: NO];
4533 [fAudTrack1BitratePopUp setEnabled: NO];
4534 [fAudTrack1DrcSlider setEnabled: NO];
4535 [fAudTrack1DrcField setEnabled: NO];
4538 /* enable/disable the mixdown text and popupbutton for audio track 2 */
4539 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4540 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4541 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4542 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4543 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4544 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4545 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4547 [fAudTrack2CodecPopUp removeAllItems];
4548 [fAudTrack2MixPopUp removeAllItems];
4549 [fAudTrack2RatePopUp removeAllItems];
4550 [fAudTrack2BitratePopUp removeAllItems];
4551 [fAudTrack2DrcSlider setFloatValue: 1.00];
4552 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
4554 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4556 [fAudTrack2RatePopUp setEnabled: NO];
4557 [fAudTrack2BitratePopUp setEnabled: NO];
4558 [fAudTrack2DrcSlider setEnabled: NO];
4559 [fAudTrack2DrcField setEnabled: NO];
4562 /* enable/disable the mixdown text and popupbutton for audio track 3 */
4563 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4564 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4565 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4566 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4567 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4568 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4569 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4571 [fAudTrack3CodecPopUp removeAllItems];
4572 [fAudTrack3MixPopUp removeAllItems];
4573 [fAudTrack3RatePopUp removeAllItems];
4574 [fAudTrack3BitratePopUp removeAllItems];
4575 [fAudTrack3DrcSlider setFloatValue: 1.00];
4576 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
4578 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4580 [fAudTrack3RatePopUp setEnabled: NO];
4581 [fAudTrack3BitratePopUp setEnabled: NO];
4582 [fAudTrack3DrcSlider setEnabled: NO];
4583 [fAudTrack3DrcField setEnabled: NO];
4586 /* enable/disable the mixdown text and popupbutton for audio track 4 */
4587 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4588 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4589 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4590 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4591 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4592 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4593 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
4595 [fAudTrack4CodecPopUp removeAllItems];
4596 [fAudTrack4MixPopUp removeAllItems];
4597 [fAudTrack4RatePopUp removeAllItems];
4598 [fAudTrack4BitratePopUp removeAllItems];
4599 [fAudTrack4DrcSlider setFloatValue: 1.00];
4600 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
4602 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4604 [fAudTrack4RatePopUp setEnabled: NO];
4605 [fAudTrack4BitratePopUp setEnabled: NO];
4606 [fAudTrack4DrcSlider setEnabled: NO];
4607 [fAudTrack4DrcField setEnabled: NO];
4612 - (IBAction) addAllAudioTracksToPopUp: (id) sender
4615 hb_list_t * list = hb_get_titles( fHandle );
4616 hb_title_t * title = (hb_title_t*)
4617 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4619 hb_audio_config_t * audio;
4621 [sender removeAllItems];
4622 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
4623 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
4625 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
4626 [[sender menu] addItemWithTitle:
4627 [NSString stringWithCString: audio->lang.description]
4628 action: NULL keyEquivalent: @""];
4630 [sender selectItemAtIndex: 0];
4634 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
4637 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
4638 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
4639 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
4640 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
4642 if (searchPrefixString)
4645 for( int i = 0; i < [sender numberOfItems]; i++ )
4647 /* Try to find the desired search string */
4648 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
4650 [sender selectItemAtIndex: i];
4654 /* couldn't find the string, so select the requested "search string not found" item */
4655 /* index of 0 means select the "none" item */
4656 /* index of 1 means select the first audio track */
4657 [sender selectItemAtIndex: selectIndexIfNotFound];
4661 /* if no search string is provided, then select the selectIndexIfNotFound item */
4662 [sender selectItemAtIndex: selectIndexIfNotFound];
4666 - (IBAction) audioAddAudioTrackCodecs: (id)sender
4668 int format = [fDstFormatPopUp indexOfSelectedItem];
4670 /* setup pointers to the appropriate popups for the correct track */
4671 NSPopUpButton * audiocodecPopUp;
4672 NSPopUpButton * audiotrackPopUp;
4673 if (sender == fAudTrack1CodecPopUp)
4675 audiotrackPopUp = fAudLang1PopUp;
4676 audiocodecPopUp = fAudTrack1CodecPopUp;
4678 else if (sender == fAudTrack2CodecPopUp)
4680 audiotrackPopUp = fAudLang2PopUp;
4681 audiocodecPopUp = fAudTrack2CodecPopUp;
4683 else if (sender == fAudTrack3CodecPopUp)
4685 audiotrackPopUp = fAudLang3PopUp;
4686 audiocodecPopUp = fAudTrack3CodecPopUp;
4690 audiotrackPopUp = fAudLang4PopUp;
4691 audiocodecPopUp = fAudTrack4CodecPopUp;
4694 [audiocodecPopUp removeAllItems];
4695 /* Make sure "None" isnt selected in the source track */
4696 if ([audiotrackPopUp indexOfSelectedItem] > 0)
4698 [audiocodecPopUp setEnabled:YES];
4699 NSMenuItem *menuItem;
4700 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
4706 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4707 [menuItem setTag: HB_ACODEC_FAAC];
4710 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4711 [menuItem setTag: HB_ACODEC_AC3];
4717 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4718 [menuItem setTag: HB_ACODEC_FAAC];
4720 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4721 [menuItem setTag: HB_ACODEC_AC3];
4723 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4724 [menuItem setTag: HB_ACODEC_LAME];
4726 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4727 [menuItem setTag: HB_ACODEC_VORBIS];
4733 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4734 [menuItem setTag: HB_ACODEC_LAME];
4736 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4737 [menuItem setTag: HB_ACODEC_AC3];
4743 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4744 [menuItem setTag: HB_ACODEC_VORBIS];
4746 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4747 [menuItem setTag: HB_ACODEC_LAME];
4750 [audiocodecPopUp selectItemAtIndex:0];
4754 [audiocodecPopUp setEnabled:NO];
4758 - (IBAction) audioTrackPopUpChanged: (id) sender
4760 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
4761 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
4764 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
4767 /* make sure we have a selected title before continuing */
4768 if (fTitle == NULL) return;
4769 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
4770 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
4772 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
4774 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4776 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
4778 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4780 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
4782 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4784 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
4786 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4789 /* Now lets make the sender the appropriate Audio Track popup from this point on */
4790 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
4792 sender = fAudLang1PopUp;
4794 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
4796 sender = fAudLang2PopUp;
4798 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
4800 sender = fAudLang3PopUp;
4802 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
4804 sender = fAudLang4PopUp;
4807 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
4808 NSPopUpButton * mixdownPopUp;
4809 NSPopUpButton * audiocodecPopUp;
4810 NSPopUpButton * sampleratePopUp;
4811 NSPopUpButton * bitratePopUp;
4812 if (sender == fAudLang1PopUp)
4814 mixdownPopUp = fAudTrack1MixPopUp;
4815 audiocodecPopUp = fAudTrack1CodecPopUp;
4816 sampleratePopUp = fAudTrack1RatePopUp;
4817 bitratePopUp = fAudTrack1BitratePopUp;
4819 else if (sender == fAudLang2PopUp)
4821 mixdownPopUp = fAudTrack2MixPopUp;
4822 audiocodecPopUp = fAudTrack2CodecPopUp;
4823 sampleratePopUp = fAudTrack2RatePopUp;
4824 bitratePopUp = fAudTrack2BitratePopUp;
4826 else if (sender == fAudLang3PopUp)
4828 mixdownPopUp = fAudTrack3MixPopUp;
4829 audiocodecPopUp = fAudTrack3CodecPopUp;
4830 sampleratePopUp = fAudTrack3RatePopUp;
4831 bitratePopUp = fAudTrack3BitratePopUp;
4835 mixdownPopUp = fAudTrack4MixPopUp;
4836 audiocodecPopUp = fAudTrack4CodecPopUp;
4837 sampleratePopUp = fAudTrack4RatePopUp;
4838 bitratePopUp = fAudTrack4BitratePopUp;
4841 /* get the index of the selected audio Track*/
4842 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
4844 /* pointer for the hb_audio_s struct we will use later on */
4845 hb_audio_config_t * audio;
4848 /* check if the audio mixdown controls need their enabled state changing */
4849 [self setEnabledStateOfAudioMixdownControls:nil];
4851 if (thisAudioIndex != -1)
4855 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
4857 /* actually manipulate the proper mixdowns here */
4858 /* delete the previous audio mixdown options */
4859 [mixdownPopUp removeAllItems];
4861 acodec = [[audiocodecPopUp selectedItem] tag];
4866 /* find out if our selected output audio codec supports mono and / or 6ch */
4867 /* we also check for an input codec of AC3 or DCA,
4868 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
4869 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
4870 but this may change in the future, so they are separated for flexibility */
4871 int audioCodecsSupportMono =
4872 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4873 (acodec != HB_ACODEC_LAME);
4874 int audioCodecsSupport6Ch =
4875 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4876 (acodec != HB_ACODEC_LAME);
4878 /* check for AC-3 passthru */
4879 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4882 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4883 [NSString stringWithCString: "AC3 Passthru"]
4884 action: NULL keyEquivalent: @""];
4885 [menuItem setTag: HB_ACODEC_AC3];
4890 /* add the appropriate audio mixdown menuitems to the popupbutton */
4891 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
4892 so that we can reference the mixdown later */
4894 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
4895 int minMixdownUsed = 0;
4896 int maxMixdownUsed = 0;
4898 /* get the input channel layout without any lfe channels */
4899 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4901 /* do we want to add a mono option? */
4902 if (audioCodecsSupportMono == 1)
4904 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4905 [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
4906 action: NULL keyEquivalent: @""];
4907 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
4908 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
4909 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
4912 /* do we want to add a stereo option? */
4913 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
4914 /* also offer stereo if we have a stereo-or-better source */
4915 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
4917 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4918 [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
4919 action: NULL keyEquivalent: @""];
4920 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
4921 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
4922 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
4925 /* do we want to add a dolby surround (DPL1) option? */
4926 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
4928 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4929 [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
4930 action: NULL keyEquivalent: @""];
4931 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
4932 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
4933 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
4936 /* do we want to add a dolby pro logic 2 (DPL2) option? */
4937 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
4939 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4940 [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
4941 action: NULL keyEquivalent: @""];
4942 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
4943 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
4944 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
4947 /* do we want to add a 6-channel discrete option? */
4948 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
4950 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4951 [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
4952 action: NULL keyEquivalent: @""];
4953 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
4954 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
4955 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
4958 /* do we want to add an AC-3 passthrough option? */
4959 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4961 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4962 [NSString stringWithCString: hb_audio_mixdowns[5].human_readable_name]
4963 action: NULL keyEquivalent: @""];
4964 [menuItem setTag: HB_ACODEC_AC3];
4965 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
4966 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
4969 /* auto-select the best mixdown based on our saved mixdown preference */
4971 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
4972 /* ultimately this should be a prefs option */
4975 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
4976 if (mixdownToUse > 0)
4978 useMixdown = mixdownToUse;
4982 useMixdown = HB_AMIXDOWN_DOLBYPLII;
4985 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
4986 if (useMixdown > maxMixdownUsed)
4988 useMixdown = maxMixdownUsed;
4991 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
4992 if (useMixdown < minMixdownUsed)
4994 useMixdown = minMixdownUsed;
4997 /* select the (possibly-amended) preferred mixdown */
4998 [mixdownPopUp selectItemWithTag: useMixdown];
5001 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5002 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5005 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5007 /* If we are using the avi container, we select MP3 as there is no aac available*/
5008 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5010 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5014 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5017 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5018 [self audioTrackMixdownChanged: mixdownPopUp];
5022 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5024 [self autoSetM4vExtension: sender];
5028 - (IBAction) audioTrackMixdownChanged: (id) sender
5032 /* setup pointers to all of the other audio track controls
5033 * we will need later
5035 NSPopUpButton * mixdownPopUp;
5036 NSPopUpButton * sampleratePopUp;
5037 NSPopUpButton * bitratePopUp;
5038 NSPopUpButton * audiocodecPopUp;
5039 NSPopUpButton * audiotrackPopUp;
5040 NSSlider * drcSlider;
5041 NSTextField * drcField;
5042 if (sender == fAudTrack1MixPopUp)
5044 audiotrackPopUp = fAudLang1PopUp;
5045 audiocodecPopUp = fAudTrack1CodecPopUp;
5046 mixdownPopUp = fAudTrack1MixPopUp;
5047 sampleratePopUp = fAudTrack1RatePopUp;
5048 bitratePopUp = fAudTrack1BitratePopUp;
5049 drcSlider = fAudTrack1DrcSlider;
5050 drcField = fAudTrack1DrcField;
5052 else if (sender == fAudTrack2MixPopUp)
5054 audiotrackPopUp = fAudLang2PopUp;
5055 audiocodecPopUp = fAudTrack2CodecPopUp;
5056 mixdownPopUp = fAudTrack2MixPopUp;
5057 sampleratePopUp = fAudTrack2RatePopUp;
5058 bitratePopUp = fAudTrack2BitratePopUp;
5059 drcSlider = fAudTrack2DrcSlider;
5060 drcField = fAudTrack2DrcField;
5062 else if (sender == fAudTrack3MixPopUp)
5064 audiotrackPopUp = fAudLang3PopUp;
5065 audiocodecPopUp = fAudTrack3CodecPopUp;
5066 mixdownPopUp = fAudTrack3MixPopUp;
5067 sampleratePopUp = fAudTrack3RatePopUp;
5068 bitratePopUp = fAudTrack3BitratePopUp;
5069 drcSlider = fAudTrack3DrcSlider;
5070 drcField = fAudTrack3DrcField;
5074 audiotrackPopUp = fAudLang4PopUp;
5075 audiocodecPopUp = fAudTrack4CodecPopUp;
5076 mixdownPopUp = fAudTrack4MixPopUp;
5077 sampleratePopUp = fAudTrack4RatePopUp;
5078 bitratePopUp = fAudTrack4BitratePopUp;
5079 drcSlider = fAudTrack4DrcSlider;
5080 drcField = fAudTrack4DrcField;
5082 acodec = [[audiocodecPopUp selectedItem] tag];
5083 /* storage variable for the min and max bitrate allowed for this codec */
5089 case HB_ACODEC_FAAC:
5090 /* check if we have a 6ch discrete conversion in either audio track */
5091 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5093 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
5095 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5101 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5103 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5104 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5109 case HB_ACODEC_LAME:
5110 /* Lame is happy using our min bitrate of 32 kbps */
5112 /* Lame won't encode if the bitrate is higher than 320 kbps */
5116 case HB_ACODEC_VORBIS:
5117 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5119 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5121 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5127 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5129 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5135 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5141 /* make sure we have a selected title before continuing */
5142 if (fTitle == NULL) return;
5143 /* get the audio so we can find out what input rates are*/
5144 hb_audio_config_t * audio;
5145 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5146 int inputbitrate = audio->in.bitrate / 1000;
5147 int inputsamplerate = audio->in.samplerate;
5149 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3)
5151 [bitratePopUp removeAllItems];
5153 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5155 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5157 /* add a new menuitem for this bitrate */
5158 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5159 [NSString stringWithCString: hb_audio_bitrates[i].string]
5160 action: NULL keyEquivalent: @""];
5161 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5162 [menuItem setTag: hb_audio_bitrates[i].rate];
5166 /* select the default bitrate (but use 384 for 6-ch AAC) */
5167 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5169 [bitratePopUp selectItemWithTag: 384];
5173 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5176 /* populate and set the sample rate popup */
5177 /* Audio samplerate */
5178 [sampleratePopUp removeAllItems];
5179 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5180 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5181 [menuItem setTag: inputsamplerate];
5183 for( int i = 0; i < hb_audio_rates_count; i++ )
5185 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5186 [NSString stringWithCString: hb_audio_rates[i].string]
5187 action: NULL keyEquivalent: @""];
5188 [menuItem setTag: hb_audio_rates[i].rate];
5190 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5191 * and there is no compelling reason to use anything else as default, though the users default
5192 * preset will likely override any setting chosen here.
5194 [sampleratePopUp selectItemWithTag: inputsamplerate];
5197 /* Since AC3 Pass Thru uses the input ac3 bitrate and sample rate, we get the input tracks
5198 * bitrate and dispay it in the bitrate popup even though libhb happily ignores any bitrate input from
5199 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
5201 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3)
5204 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
5205 [bitratePopUp removeAllItems];
5206 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5207 [NSString stringWithFormat:@"%d", inputbitrate]
5208 action: NULL keyEquivalent: @""];
5209 [menuItem setTag: inputbitrate];
5210 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
5211 [bitratePopUp setEnabled: NO];
5212 [sampleratePopUp setEnabled: NO];
5214 [drcSlider setFloatValue: 1.00];
5215 [self audioDRCSliderChanged: drcSlider];
5216 [drcSlider setEnabled: NO];
5217 [drcField setEnabled: NO];
5221 [sampleratePopUp setEnabled: YES];
5222 [bitratePopUp setEnabled: YES];
5223 [drcSlider setEnabled: YES];
5224 [drcField setEnabled: YES];
5226 [self calculateBitrate:nil];
5229 - (IBAction) audioDRCSliderChanged: (id) sender
5231 NSSlider * drcSlider;
5232 NSTextField * drcField;
5233 if (sender == fAudTrack1DrcSlider)
5235 drcSlider = fAudTrack1DrcSlider;
5236 drcField = fAudTrack1DrcField;
5238 else if (sender == fAudTrack2DrcSlider)
5240 drcSlider = fAudTrack2DrcSlider;
5241 drcField = fAudTrack2DrcField;
5243 else if (sender == fAudTrack3DrcSlider)
5245 drcSlider = fAudTrack3DrcSlider;
5246 drcField = fAudTrack3DrcField;
5250 drcSlider = fAudTrack4DrcSlider;
5251 drcField = fAudTrack4DrcField;
5254 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
5255 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
5257 [drcSlider setFloatValue:1.0];
5261 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
5262 /* For now, do not call this until we have an intelligent way to determine audio track selections
5263 * compared to presets
5265 //[self customSettingUsed: sender];
5268 - (IBAction) subtitleSelectionChanged: (id) sender
5270 if ([fSubPopUp indexOfSelectedItem] == 0)
5272 [fSubForcedCheck setState: NSOffState];
5273 [fSubForcedCheck setEnabled: NO];
5277 [fSubForcedCheck setEnabled: YES];
5286 #pragma mark Open New Windows
5288 - (IBAction) openHomepage: (id) sender
5290 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5291 URLWithString:@"http://handbrake.fr/"]];
5294 - (IBAction) openForums: (id) sender
5296 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5297 URLWithString:@"http://handbrake.fr/forum/"]];
5299 - (IBAction) openUserGuide: (id) sender
5301 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5302 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
5306 * Shows debug output window.
5308 - (IBAction)showDebugOutputPanel:(id)sender
5310 [outputPanel showOutputPanel:sender];
5314 * Shows preferences window.
5316 - (IBAction) showPreferencesWindow: (id) sender
5318 NSWindow * window = [fPreferencesController window];
5319 if (![window isVisible])
5322 [window makeKeyAndOrderFront: nil];
5326 * Shows queue window.
5328 - (IBAction) showQueueWindow:(id)sender
5330 [fQueueController showQueueWindow:sender];
5334 - (IBAction) toggleDrawer:(id)sender {
5335 [fPresetDrawer toggle:self];
5339 * Shows Picture Settings Window.
5342 - (IBAction) showPicturePanel: (id) sender
5344 [fPictureController showPictureWindow:sender];
5347 - (void) picturePanelFullScreen
5349 [fPictureController setToFullScreenMode];
5352 - (void) picturePanelWindowed
5354 [fPictureController setToWindowedMode];
5357 - (IBAction) showPreviewWindow: (id) sender
5359 [fPictureController showPreviewWindow:sender];
5363 #pragma mark Preset Outline View Methods
5364 #pragma mark - Required
5365 /* These are required by the NSOutlineView Datasource Delegate */
5368 /* used to specify the number of levels to show for each item */
5369 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
5371 /* currently use no levels to test outline view viability */
5372 if (item == nil) // for an outline view the root level of the hierarchy is always nil
5374 return [UserPresets count];
5378 /* we need to return the count of the array in ChildrenArray for this folder */
5379 NSArray *children = nil;
5380 children = [item objectForKey:@"ChildrenArray"];
5381 if ([children count] > 0)
5383 return [children count];
5392 /* We use this to deterimine children of an item */
5393 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
5396 /* we need to return the count of the array in ChildrenArray for this folder */
5397 NSArray *children = nil;
5400 children = UserPresets;
5404 if ([item objectForKey:@"ChildrenArray"])
5406 children = [item objectForKey:@"ChildrenArray"];
5409 if ((children == nil) || ( [children count] <= (NSUInteger) index))
5415 return [children objectAtIndex:index];
5419 // We are only one level deep, so we can't be asked about children
5420 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
5424 /* We use this to determine if an item should be expandable */
5425 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
5428 /* we need to return the count of the array in ChildrenArray for this folder */
5429 NSArray *children= nil;
5432 children = UserPresets;
5436 if ([item objectForKey:@"ChildrenArray"])
5438 children = [item objectForKey:@"ChildrenArray"];
5442 /* To deterimine if an item should show a disclosure triangle
5443 * we could do it by the children count as so:
5444 * if ([children count] < 1)
5445 * However, lets leave the triangle show even if there are no
5446 * children to help indicate a folder, just like folder in the
5447 * finder can show a disclosure triangle even when empty
5450 /* We need to determine if the item is a folder */
5451 if ([[item objectForKey:@"Folder"] intValue] == 1)
5462 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
5464 // Our outline view has no levels, but we can still expand every item. Doing so
5465 // just makes the row taller. See heightOfRowByItem below.
5466 //return ![(HBQueueOutlineView*)outlineView isDragging];
5472 /* Used to tell the outline view which information is to be displayed per item */
5473 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5475 /* We have two columns right now, icon and PresetName */
5477 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5479 return [item objectForKey:@"PresetName"];
5488 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
5490 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
5492 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
5494 return [NSKeyedArchiver archivedDataWithRootObject:item];
5497 #pragma mark - Added Functionality (optional)
5498 /* Use to customize the font and display characteristics of the title cell */
5499 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
5501 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5505 NSColor *shadowColor;
5506 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
5507 /*check to see if its a selected row */
5508 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
5511 fontColor = [NSColor blackColor];
5512 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
5516 if ([[item objectForKey:@"Type"] intValue] == 0)
5518 fontColor = [NSColor blueColor];
5520 else // User created preset, use a black font
5522 fontColor = [NSColor blackColor];
5524 /* check to see if its a folder */
5525 //if ([[item objectForKey:@"Folder"] intValue] == 1)
5527 //fontColor = [NSColor greenColor];
5532 /* We use Bold Text for the HB Default */
5533 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
5535 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5537 /* We use Bold Text for the User Specified Default */
5538 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
5540 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5544 [cell setTextColor:fontColor];
5545 [cell setFont:txtFont];
5550 /* We use this to edit the name field in the outline view */
5551 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5553 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5558 [theRecord setObject:object forKey:@"PresetName"];
5562 [fPresetsOutlineView reloadData];
5563 /* We save all of the preset data here */
5567 /* We use this to provide tooltips for the items in the presets outline view */
5568 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
5570 //if ([[tc identifier] isEqualToString:@"PresetName"])
5572 /* initialize the tooltip contents variable */
5574 /* if there is a description for the preset, we show it in the tooltip */
5575 if ([item objectForKey:@"PresetDescription"])
5577 loc_tip = [item objectForKey:@"PresetDescription"];
5582 loc_tip = @"No description available";
5589 #pragma mark Preset Outline View Methods (dragging related)
5592 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
5594 // Dragging is only allowed for custom presets.
5595 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
5596 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
5600 // Don't retain since this is just holding temporaral drag information, and it is
5601 //only used during a drag! We could put this in the pboard actually.
5602 fDraggedNodes = items;
5603 // Provide data for our custom type, and simple NSStrings.
5604 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
5606 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
5607 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
5612 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
5615 // Don't allow dropping ONTO an item since they can't really contain any children.
5617 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
5618 if (isOnDropTypeProposal)
5619 return NSDragOperationNone;
5621 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
5624 index = [fPresetsOutlineView rowForItem: item] + 1;
5628 // Don't allow dropping into the Built In Presets.
5629 if (index < presetCurrentBuiltInCount)
5631 return NSDragOperationNone;
5632 index = MAX (index, presetCurrentBuiltInCount);
5635 [outlineView setDropItem:item dropChildIndex:index];
5636 return NSDragOperationGeneric;
5641 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
5643 /* first, lets see if we are dropping into a folder */
5644 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
5646 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
5647 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
5648 [childrenArray addObject:item];
5649 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
5650 [childrenArray autorelease];
5652 else // We are not, so we just move the preset into the existing array
5654 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
5656 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
5657 while (obj = [enumerator nextObject])
5659 [moveItems addIndex:[UserPresets indexOfObject:obj]];
5661 // Successful drop, lets rearrange the view and save it all
5662 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
5664 [fPresetsOutlineView reloadData];
5669 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
5671 NSUInteger index = [indexSet lastIndex];
5672 NSUInteger aboveInsertIndexCount = 0;
5674 NSUInteger removeIndex;
5676 if (index >= insertIndex)
5678 removeIndex = index + aboveInsertIndexCount;
5679 aboveInsertIndexCount++;
5683 removeIndex = index;
5687 id object = [[array objectAtIndex:removeIndex] retain];
5688 [array removeObjectAtIndex:removeIndex];
5689 [array insertObject:object atIndex:insertIndex];
5692 index = [indexSet indexLessThanIndex:index];
5697 #pragma mark - Functional Preset NSOutlineView Methods
5699 - (IBAction)selectPreset:(id)sender
5702 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
5704 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
5705 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5707 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
5709 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
5713 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5717 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
5718 [self formatPopUpChanged:nil];
5720 /* Chapter Markers*/
5721 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
5722 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
5723 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
5724 /* Mux mp4 with http optimization */
5725 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
5728 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
5729 /* We set the advanced opt string here if applicable*/
5730 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
5732 /* Lets run through the following functions to get variables set there */
5733 [self videoEncoderPopUpChanged:nil];
5734 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
5735 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
5736 [self calculateBitrate:nil];
5739 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
5741 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
5742 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
5744 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
5745 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
5746 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
5747 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
5748 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
5749 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
5751 /* For the quality slider we need to convert the old percent's to the new rf scales */
5752 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
5753 [fVidQualitySlider setFloatValue:rf];
5758 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
5761 [self videoMatrixChanged:nil];
5763 /* Video framerate */
5764 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
5765 detected framerate in the fVidRatePopUp so we use index 0*/
5766 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
5768 [fVidRatePopUp selectItemAtIndex: 0];
5772 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
5776 /* 2 Pass Encoding */
5777 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
5778 [self twoPassCheckboxChanged:nil];
5780 /* Turbo 1st pass for 2 Pass Encoding */
5781 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
5785 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
5787 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5789 [fAudLang1PopUp selectItemAtIndex: 1];
5791 [self audioTrackPopUpChanged: fAudLang1PopUp];
5792 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
5793 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5794 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
5795 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5797 if ([fAudTrack1MixPopUp selectedItem] == nil)
5799 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5801 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
5802 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5803 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
5805 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
5807 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
5808 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5810 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
5812 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5814 [fAudLang2PopUp selectItemAtIndex: 1];
5816 [self audioTrackPopUpChanged: fAudLang2PopUp];
5817 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
5818 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5819 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
5820 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5822 if ([fAudTrack2MixPopUp selectedItem] == nil)
5824 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5826 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
5827 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5828 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
5830 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
5832 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
5833 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5835 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
5837 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5839 [fAudLang3PopUp selectItemAtIndex: 1];
5841 [self audioTrackPopUpChanged: fAudLang3PopUp];
5842 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
5843 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5844 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
5845 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5847 if ([fAudTrack3MixPopUp selectedItem] == nil)
5849 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5851 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
5852 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5853 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
5855 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
5857 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
5858 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5860 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
5862 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5864 [fAudLang4PopUp selectItemAtIndex: 1];
5866 [self audioTrackPopUpChanged: fAudLang4PopUp];
5867 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
5868 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5869 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
5870 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5872 if ([fAudTrack4MixPopUp selectedItem] == nil)
5874 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5876 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
5877 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5878 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
5880 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
5882 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
5883 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5886 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
5888 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
5890 [fAudLang2PopUp selectItemAtIndex: 0];
5891 [self audioTrackPopUpChanged: fAudLang2PopUp];
5893 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
5895 [fAudLang3PopUp selectItemAtIndex: 0];
5896 [self audioTrackPopUpChanged: fAudLang3PopUp];
5898 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
5900 [fAudLang4PopUp selectItemAtIndex: 0];
5901 [self audioTrackPopUpChanged: fAudLang4PopUp];
5905 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
5906 /* Forced Subtitles */
5907 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
5909 /* Picture Settings */
5910 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
5911 * height, width, keep ar, anamorphic and crop settings.
5912 * picture filters are handled separately below.
5914 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
5915 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
5916 * preset completely ignores any picture sizing values in the preset.
5918 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
5920 hb_job_t * job = fTitle->job;
5922 /* If Cropping is set to custom, then recall all four crop values from
5923 when the preset was created and apply them */
5924 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
5926 [fPictureController setAutoCrop:NO];
5928 /* Here we use the custom crop values saved at the time the preset was saved */
5929 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
5930 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
5931 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
5932 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
5935 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
5937 [fPictureController setAutoCrop:YES];
5938 /* Here we use the auto crop values determined right after scan */
5939 job->crop[0] = AutoCropTop;
5940 job->crop[1] = AutoCropBottom;
5941 job->crop[2] = AutoCropLeft;
5942 job->crop[3] = AutoCropRight;
5947 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
5948 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
5950 /* Use Max Picture settings for whatever the dvd is.*/
5951 [self revertPictureSizeToMax:nil];
5952 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5953 if (job->keep_ratio == 1)
5955 hb_fix_aspect( job, HB_KEEP_WIDTH );
5956 if( job->height > fTitle->height )
5958 job->height = fTitle->height;
5959 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5962 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5964 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
5966 /* we check to make sure the presets width/height does not exceed the sources width/height */
5967 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
5969 /* if so, then we use the sources height and width to avoid scaling up */
5970 //job->width = fTitle->width;
5971 //job->height = fTitle->height;
5972 [self revertPictureSizeToMax:nil];
5974 else // source width/height is >= the preset height/width
5976 /* we can go ahead and use the presets values for height and width */
5977 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
5978 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
5980 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5981 if (job->keep_ratio == 1)
5983 hb_fix_aspect( job, HB_KEEP_WIDTH );
5984 if( job->height > fTitle->height )
5986 job->height = fTitle->height;
5987 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5990 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5996 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
5997 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
6001 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
6002 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
6003 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
6006 [fPictureController setUseDecomb:1];
6007 [fPictureController setDecomb:0];
6008 [fPictureController setDeinterlace:0];
6009 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
6011 /* we are using decomb */
6013 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
6015 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
6017 /* if we are using "Custom" in the decomb setting, also set the custom string*/
6018 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 2)
6020 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
6026 /* We are using Deinterlace */
6028 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
6030 [fPictureController setUseDecomb:0];
6031 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
6032 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
6033 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
6035 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
6042 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
6044 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
6045 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
6046 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 2)
6048 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
6053 [fPictureController setDetelecine:0];
6057 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
6059 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
6060 /* if we are using "Custom" in the denoise setting, also set the custom string*/
6061 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 4)
6063 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
6068 [fPictureController setDenoise:0];
6072 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
6074 /* if its a one, then its the old on/off deblock, set on to 5*/
6075 [fPictureController setDeblock:5];
6079 /* use the settings intValue */
6080 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
6083 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
6085 [fPictureController setGrayscale:1];
6089 [fPictureController setGrayscale:0];
6092 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
6093 [fPictureController SetTitle:fTitle];
6094 [fPictureController SetTitle:fTitle];
6095 [self calculatePictureSizing:nil];
6101 #pragma mark Manage Presets
6103 - (void) loadPresets {
6104 /* We declare the default NSFileManager into fileManager */
6105 NSFileManager * fileManager = [NSFileManager defaultManager];
6106 /*We define the location of the user presets file */
6107 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
6108 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
6109 /* We check for the presets.plist */
6110 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
6112 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
6115 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
6116 if (nil == UserPresets)
6118 UserPresets = [[NSMutableArray alloc] init];
6119 [self addFactoryPresets:nil];
6121 [fPresetsOutlineView reloadData];
6125 - (IBAction) showAddPresetPanel: (id) sender
6127 /* Deselect the currently selected Preset if there is one*/
6128 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
6130 /* Populate the preset picture settings popup here */
6131 [fPresetNewPicSettingsPopUp removeAllItems];
6132 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
6133 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
6134 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
6135 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
6136 /* Uncheck the preset use filters checkbox */
6137 [fPresetNewPicFiltersCheck setState:NSOffState];
6138 // fPresetNewFolderCheck
6139 [fPresetNewFolderCheck setState:NSOffState];
6140 /* Erase info from the input fields*/
6141 [fPresetNewName setStringValue: @""];
6142 [fPresetNewDesc setStringValue: @""];
6143 /* Show the panel */
6144 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
6147 - (IBAction) closeAddPresetPanel: (id) sender
6149 [NSApp endSheet: fAddPresetPanel];
6150 [fAddPresetPanel orderOut: self];
6153 - (IBAction)addUserPreset:(id)sender
6155 if (![[fPresetNewName stringValue] length])
6156 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
6159 /* Here we create a custom user preset */
6160 [UserPresets addObject:[self createPreset]];
6163 [self closeAddPresetPanel:nil];
6170 /* We Reload the New Table data for presets */
6171 [fPresetsOutlineView reloadData];
6172 /* We save all of the preset data here */
6180 /* We Sort the Presets By Factory or Custom */
6181 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
6182 ascending:YES] autorelease];
6183 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
6185 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
6186 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
6187 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
6190 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
6191 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
6192 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
6193 [UserPresets setArray:sortedArray];
6198 - (IBAction)insertPreset:(id)sender
6200 int index = [fPresetsOutlineView selectedRow];
6201 [UserPresets insertObject:[self createPreset] atIndex:index];
6202 [fPresetsOutlineView reloadData];
6206 - (NSDictionary *)createPreset
6208 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
6209 /* Get the New Preset Name from the field in the AddPresetPanel */
6210 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
6211 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
6212 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
6213 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
6214 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
6215 /*Set whether or not this is default, at creation set to 0*/
6216 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6217 if ([fPresetNewFolderCheck state] == YES)
6219 /* initialize and set an empty array for children here since we are a new folder */
6220 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6221 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6222 [childrenArray autorelease];
6224 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
6226 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
6227 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
6228 /* Get whether or not to use the current Picture Filter settings for the preset */
6229 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
6231 /* Get New Preset Description from the field in the AddPresetPanel*/
6232 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
6234 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
6235 /* Chapter Markers fCreateChapterMarkers*/
6236 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
6237 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6238 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
6239 /* Mux mp4 with http optimization */
6240 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
6241 /* Add iPod uuid atom */
6242 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
6246 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
6247 /* x264 Option String */
6248 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
6250 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
6251 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
6252 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
6253 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
6255 /* Video framerate */
6256 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
6258 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
6260 else // we can record the actual titleOfSelectedItem
6262 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
6265 /* 2 Pass Encoding */
6266 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
6267 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
6268 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
6269 /*Picture Settings*/
6270 hb_job_t * job = fTitle->job;
6271 /* Picture Sizing */
6272 /* Use Max Picture settings for whatever the dvd is.*/
6273 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
6274 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
6275 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
6276 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
6277 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
6279 /* Set crop settings here */
6280 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
6281 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
6282 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
6283 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
6284 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
6286 /* Picture Filters */
6287 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
6288 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
6289 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
6290 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
6291 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
6292 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
6293 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
6294 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
6295 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
6296 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
6297 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
6301 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
6303 [preset setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
6304 [preset setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
6305 [preset setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
6306 [preset setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
6307 [preset setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
6308 [preset setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
6309 [preset setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
6311 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
6313 [preset setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
6314 [preset setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
6315 [preset setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
6316 [preset setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
6317 [preset setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
6318 [preset setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
6319 [preset setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
6321 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
6323 [preset setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
6324 [preset setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
6325 [preset setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
6326 [preset setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
6327 [preset setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
6328 [preset setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
6329 [preset setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
6331 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
6333 [preset setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
6334 [preset setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
6335 [preset setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
6336 [preset setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
6337 [preset setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
6338 [preset setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
6339 [preset setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
6343 [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
6344 /* Forced Subtitles */
6345 [preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
6347 [preset autorelease];
6354 [UserPresets writeToFile:UserPresetsFile atomically:YES];
6355 /* We get the default preset in case it changed */
6356 [self getDefaultPresets:nil];
6360 - (IBAction)deletePreset:(id)sender
6364 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
6368 /* Alert user before deleting preset */
6370 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
6372 if ( status == NSAlertDefaultReturn )
6374 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6375 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6376 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6378 NSEnumerator *enumerator;
6379 NSMutableArray *presetsArrayToMod;
6380 NSMutableArray *tempArray;
6382 /* If we are a root level preset, we are modding the UserPresets array */
6383 if (presetToModLevel == 0)
6385 presetsArrayToMod = UserPresets;
6387 else // We have a parent preset, so we modify the chidren array object for key
6389 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6392 enumerator = [presetsArrayToMod objectEnumerator];
6393 tempArray = [NSMutableArray array];
6395 while (tempObject = [enumerator nextObject])
6397 NSDictionary *thisPresetDict = tempObject;
6398 if (thisPresetDict == presetToMod)
6400 [tempArray addObject:tempObject];
6404 [presetsArrayToMod removeObjectsInArray:tempArray];
6405 [fPresetsOutlineView reloadData];
6411 #pragma mark Manage Default Preset
6413 - (IBAction)getDefaultPresets:(id)sender
6415 presetHbDefault = nil;
6416 presetUserDefault = nil;
6417 presetUserDefaultParent = nil;
6418 presetUserDefaultParentParent = nil;
6419 NSMutableDictionary *presetHbDefaultParent = nil;
6420 NSMutableDictionary *presetHbDefaultParentParent = nil;
6423 BOOL userDefaultFound = NO;
6424 presetCurrentBuiltInCount = 0;
6425 /* First we iterate through the root UserPresets array to check for defaults */
6426 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6428 while (tempObject = [enumerator nextObject])
6430 NSMutableDictionary *thisPresetDict = tempObject;
6431 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6433 presetHbDefault = thisPresetDict;
6435 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6437 presetUserDefault = thisPresetDict;
6438 userDefaultFound = YES;
6440 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
6442 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
6446 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6447 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6449 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
6450 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6452 while (tempObject = [enumerator nextObject])
6454 NSMutableDictionary *thisPresetDict = tempObject;
6455 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6457 presetHbDefault = thisPresetDict;
6458 presetHbDefaultParent = thisPresetDictParent;
6460 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6462 presetUserDefault = thisPresetDict;
6463 presetUserDefaultParent = thisPresetDictParent;
6464 userDefaultFound = YES;
6467 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6468 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6470 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
6471 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6473 while (tempObject = [enumerator nextObject])
6475 NSMutableDictionary *thisPresetDict = tempObject;
6476 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6478 presetHbDefault = thisPresetDict;
6479 presetHbDefaultParent = thisPresetDictParent;
6480 presetHbDefaultParentParent = thisPresetDictParentParent;
6482 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6484 presetUserDefault = thisPresetDict;
6485 presetUserDefaultParent = thisPresetDictParent;
6486 presetUserDefaultParentParent = thisPresetDictParentParent;
6487 userDefaultFound = YES;
6496 /* check to see if a user specified preset was found, if not then assign the parents for
6497 * the presetHbDefault so that we can open the parents for the nested presets
6499 if (userDefaultFound == NO)
6501 presetUserDefaultParent = presetHbDefaultParent;
6502 presetUserDefaultParentParent = presetHbDefaultParentParent;
6506 - (IBAction)setDefaultPreset:(id)sender
6508 /* We need to determine if the item is a folder */
6509 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
6515 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6517 /* First make sure the old user specified default preset is removed */
6518 while (tempObject = [enumerator nextObject])
6520 NSMutableDictionary *thisPresetDict = tempObject;
6521 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6523 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6526 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6527 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6529 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6532 while (tempObject = [enumerator nextObject])
6534 NSMutableDictionary *thisPresetDict1 = tempObject;
6535 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6537 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6539 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6540 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
6542 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
6545 while (tempObject = [enumerator nextObject])
6547 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6549 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6562 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6563 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6564 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6567 NSMutableArray *presetsArrayToMod;
6568 NSMutableArray *tempArray;
6570 /* If we are a root level preset, we are modding the UserPresets array */
6571 if (presetToModLevel == 0)
6573 presetsArrayToMod = UserPresets;
6575 else // We have a parent preset, so we modify the chidren array object for key
6577 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6580 enumerator = [presetsArrayToMod objectEnumerator];
6581 tempArray = [NSMutableArray array];
6583 while (tempObject = [enumerator nextObject])
6585 NSDictionary *thisPresetDict = tempObject;
6586 if (thisPresetDict == presetToMod)
6588 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
6590 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
6597 /* We save all of the preset data here */
6599 /* We Reload the New Table data for presets */
6600 [fPresetsOutlineView reloadData];
6603 - (IBAction)selectDefaultPreset:(id)sender
6605 NSMutableDictionary *presetToMod;
6606 /* if there is a user specified default, we use it */
6607 if (presetUserDefault)
6609 presetToMod = presetUserDefault;
6611 else if (presetHbDefault) //else we use the built in default presetHbDefault
6613 presetToMod = presetHbDefault;
6620 if (presetUserDefaultParent != nil)
6622 [fPresetsOutlineView expandItem:presetUserDefaultParent];
6625 if (presetUserDefaultParentParent != nil)
6627 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
6631 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
6632 [self selectPreset:nil];
6637 #pragma mark Manage Built In Presets
6640 - (IBAction)deleteFactoryPresets:(id)sender
6643 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6647 NSMutableArray *tempArray;
6650 tempArray = [NSMutableArray array];
6651 /* we look here to see if the preset is we move on to the next one */
6652 while ( tempObject = [enumerator nextObject] )
6654 /* if the preset is "Factory" then we put it in the array of
6655 presets to delete */
6656 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
6658 [tempArray addObject:tempObject];
6662 [UserPresets removeObjectsInArray:tempArray];
6663 [fPresetsOutlineView reloadData];
6668 /* We use this method to recreate new, updated factory
6670 - (IBAction)addFactoryPresets:(id)sender
6673 /* First, we delete any existing built in presets */
6674 [self deleteFactoryPresets: sender];
6675 /* Then we generate new built in presets programmatically with fPresetsBuiltin
6676 * which is all setup in HBPresets.h and HBPresets.m*/
6677 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
6689 /*******************************
6690 * Subclass of the HBPresetsOutlineView *
6691 *******************************/
6693 @implementation HBPresetsOutlineView
6694 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
6698 // By default, NSTableView only drags an image of the first column. Change this to
6699 // drag an image of the queue's icon and PresetName columns.
6700 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
6701 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
6706 - (void) mouseDown:(NSEvent *)theEvent
6708 [super mouseDown:theEvent];
6714 - (BOOL) isDragging;