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"
13 #import "HBFilterController.h"
15 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
17 /* We setup the toolbar values here */
18 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
19 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
20 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
21 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
22 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
23 static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
24 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
25 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
28 /*******************************
29 * HBController implementation *
30 *******************************/
31 @implementation HBController
41 [HBPreferencesController registerUserDefaults];
43 fQueueEncodeLibhb = NULL;
44 /* Check for check for the app support directory here as
45 * outputPanel needs it right away, as may other future methods
47 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
49 YES ) objectAtIndex:0];
50 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
51 stringByAppendingPathComponent:@"HandBrake"];
52 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
54 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
57 /* Check for and create the App Support Preview directory if necessary */
58 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
59 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
61 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
64 outputPanel = [[HBOutputPanelController alloc] init];
65 fPictureController = [[PictureController alloc] init];
66 fPictureFilterController = [[PictureFilterController alloc] init];
67 fQueueController = [[HBQueueController alloc] init];
68 fAdvancedOptions = [[HBAdvancedController alloc] init];
69 /* we init the HBPresets class which currently is only used
70 * for updating built in presets, may move more functionality
73 fPresetsBuiltin = [[HBPresets alloc] init];
74 fPreferencesController = [[HBPreferencesController alloc] init];
75 /* Lets report the HandBrake version number here to the activity log and text log file */
76 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleGetInfoString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
77 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
83 - (void) applicationDidFinishLaunching: (NSNotification *) notification
85 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
86 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
87 fHandle = hb_init(loggingLevel, 0);
88 /* Init a separate instance of libhb for user scanning and setting up jobs */
89 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
91 // Set the Growl Delegate
92 [GrowlApplicationBridge setGrowlDelegate: self];
93 /* Init others controllers */
94 [fPictureController SetHandle: fHandle];
95 [fPictureController setHBController: self];
96 /* fPictureController */
97 [fPictureFilterController SetHandle: fHandle];
98 [fPictureFilterController setHBController: self];
100 [fQueueController setHandle: fQueueEncodeLibhb];
101 [fQueueController setHBController: self];
103 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
104 [fChapterTable setDataSource:fChapterTitlesDelegate];
105 [fChapterTable setDelegate:fChapterTitlesDelegate];
107 [fPresetsOutlineView setAutosaveName:@"Presets View"];
108 [fPresetsOutlineView setAutosaveExpandedItems:YES];
110 /* Call UpdateUI every 1/2 sec */
111 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
112 scheduledTimerWithTimeInterval:0.5 target:self
113 selector:@selector(updateUI:) userInfo:nil repeats:YES]
114 forMode:NSEventTrackingRunLoopMode];
116 // Open debug output window now if it was visible when HB was closed
117 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
118 [self showDebugOutputPanel:nil];
120 // Open queue window now if it was visible when HB was closed
121 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
122 [self showQueueWindow:nil];
124 [self openMainWindow:nil];
126 /* We have to set the bool to tell hb what to do after a scan
127 * Initially we set it to NO until we start processing the queue
129 applyQueueToScan = NO;
131 /* Now we re-check the queue array to see if there are
132 * any remaining encodes to be done in it and ask the
133 * user if they want to reload the queue */
134 if ([QueueFileArray count] > 0)
136 /* run getQueueStats to see whats in the queue file */
137 [self getQueueStats];
138 /* this results in these values
139 * fEncodingQueueItem = 0;
141 * fCompletedCount = 0;
142 * fCanceledCount = 0;
146 /*On Screen Notification*/
147 NSString * alertTitle;
148 if (fWorkingCount > 0)
150 alertTitle = [NSString stringWithFormat:
151 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
152 fWorkingCount,fPendingCount];
156 alertTitle = [NSString stringWithFormat:
157 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
160 NSBeginCriticalAlertSheet(
162 NSLocalizedString(@"Reload Queue", nil),
164 NSLocalizedString(@"Empty Queue", nil),
166 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
167 NSLocalizedString(@" Do you want to reload them ?", nil));
168 // call didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
169 // right below to either clear the old queue or keep it loaded up.
173 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
174 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
176 [self browseSources:nil];
179 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
181 [self browseSources:(id)fOpenSourceTitleMMenu];
186 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
188 if (returnCode == NSAlertOtherReturn)
190 [self clearQueueAllItems];
191 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
192 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
194 [self browseSources:nil];
197 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
199 [self browseSources:(id)fOpenSourceTitleMMenu];
204 [self setQueueEncodingItemsAsPending];
205 [self showQueueWindow:NULL];
209 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
211 if ([fPreviewController fullScreen] == YES)
213 [fPreviewController goWindowedScreen:nil];
217 hb_get_state( fQueueEncodeLibhb, &s );
219 if ( s.state != HB_STATE_IDLE )
221 int result = NSRunCriticalAlertPanel(
222 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
223 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
224 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
226 if (result == NSAlertDefaultReturn)
228 return NSTerminateNow;
231 return NSTerminateCancel;
234 // Warn if items still in the queue
235 else if ( fPendingCount > 0 )
237 int result = NSRunCriticalAlertPanel(
238 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
239 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
240 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
242 if ( result == NSAlertDefaultReturn )
243 return NSTerminateNow;
245 return NSTerminateCancel;
248 return NSTerminateNow;
251 - (void)applicationWillTerminate:(NSNotification *)aNotification
253 [browsedSourceDisplayName release];
254 [outputPanel release];
255 [fQueueController release];
256 [fPictureController release];
257 [fPictureFilterController release];
259 [fPreviewController release];
261 hb_close(&fQueueEncodeLibhb);
265 - (void) awakeFromNib
268 [fWindow setExcludedFromWindowsMenu:YES];
269 [fAdvancedOptions setView:fAdvancedView];
271 /* lets setup our presets drawer for drag and drop here */
272 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
273 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
274 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
276 /* Initialize currentScanCount so HB can use it to
277 evaluate successive scans */
278 currentScanCount = 0;
281 /* Init UserPresets .plist */
284 /* Init QueueFile .plist */
285 [self loadQueueFile];
287 fRipIndicatorShown = NO; // initially out of view in the nib
289 /* Show/Dont Show Presets drawer upon launch based
290 on user preference DefaultPresetsDrawerShow*/
291 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
293 [fPresetDrawer setDelegate:self];
294 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
295 stringForKey:@"Drawer Size"] );
296 if( drawerSize.width )
297 [fPresetDrawer setContentSize: drawerSize];
298 [fPresetDrawer open];
302 NSMenuItem *menuItem;
303 [fDstFormatPopUp removeAllItems];
305 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
306 [menuItem setTag: HB_MUX_MP4];
308 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
309 [menuItem setTag: HB_MUX_MKV];
311 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"AVI file" action: NULL keyEquivalent: @""];
312 [menuItem setTag: HB_MUX_AVI];
314 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"OGM file" action: NULL keyEquivalent: @""];
315 [menuItem setTag: HB_MUX_OGM];
316 [fDstFormatPopUp selectItemAtIndex: 0];
318 [self formatPopUpChanged:nil];
320 /* We enable the create chapters checkbox here since we are .mp4 */
321 [fCreateChapterMarkers setEnabled: YES];
322 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
324 [fCreateChapterMarkers setState: NSOnState];
330 [fDstFile2Field setStringValue: [NSString stringWithFormat:
331 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
334 [fVidEncoderPopUp removeAllItems];
335 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
336 [fVidEncoderPopUp addItemWithTitle: @"XviD"];
341 [fVidTargetSizeField setIntValue: 700];
342 [fVidBitrateField setIntValue: 1000];
344 [fVidQualityMatrix selectCell: fVidBitrateCell];
345 [self videoMatrixChanged:nil];
347 /* Video framerate */
348 [fVidRatePopUp removeAllItems];
349 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
350 for( int i = 0; i < hb_video_rates_count; i++ )
352 if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
354 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
355 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
357 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
359 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
360 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
362 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
364 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
365 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
369 [fVidRatePopUp addItemWithTitle:
370 [NSString stringWithCString: hb_video_rates[i].string]];
373 [fVidRatePopUp selectItemAtIndex: 0];
375 /* Set Auto Crop to On at launch */
376 [fPictureController setAutoCrop:YES];
379 [fAudTrack1BitratePopUp removeAllItems];
380 for( int i = 0; i < hb_audio_bitrates_count; i++ )
382 [fAudTrack1BitratePopUp addItemWithTitle:
383 [NSString stringWithCString: hb_audio_bitrates[i].string]];
386 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
388 /* Audio samplerate */
389 [fAudTrack1RatePopUp removeAllItems];
390 for( int i = 0; i < hb_audio_rates_count; i++ )
392 [fAudTrack1RatePopUp addItemWithTitle:
393 [NSString stringWithCString: hb_audio_rates[i].string]];
395 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
398 [fStatusField setStringValue: @""];
403 /* We disable the Turbo 1st pass checkbox since we are not x264 */
404 [fVidTurboPassCheck setEnabled: NO];
405 [fVidTurboPassCheck setState: NSOffState];
408 /* lets get our default prefs here */
409 [self getDefaultPresets:nil];
410 /* lets initialize the current successful scancount here to 0 */
411 currentSuccessfulScanCount = 0;
416 - (void) enableUI: (bool) b
418 NSControl * controls[] =
419 { fSrcTitleField, fSrcTitlePopUp,
420 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
421 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
422 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
423 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
424 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
425 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
426 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
427 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
428 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
429 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
430 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
431 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
432 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
433 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
434 fQueueStatus,fPresetsAdd,fPresetsDelete,
435 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
436 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel};
439 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
441 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
443 NSTextField * tf = (NSTextField *) controls[i];
444 if( ![tf isBezeled] )
446 [tf setTextColor: b ? [NSColor controlTextColor] :
447 [NSColor disabledControlTextColor]];
451 [controls[i] setEnabled: b];
457 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
458 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
459 [self setEnabledStateOfAudioMixdownControls:nil];
460 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
461 [self calculatePictureSizing:nil];
465 [fPresetsOutlineView setEnabled: NO];
469 [self videoMatrixChanged:nil];
470 [fAdvancedOptions enableUI:b];
474 /***********************************************************************
476 ***********************************************************************
477 * Shows a progression bar on the dock icon, filled according to
478 * 'progress' (0.0 <= progress <= 1.0).
479 * Called with progress < 0.0 or progress > 1.0, restores the original
481 **********************************************************************/
482 - (void) UpdateDockIcon: (float) progress
486 NSBitmapImageRep * bmp;
488 uint32_t black = htonl( 0x000000FF );
489 uint32_t red = htonl( 0xFF0000FF );
490 uint32_t white = htonl( 0xFFFFFFFF );
491 int row_start, row_end;
494 /* Get application original icon */
495 icon = [NSImage imageNamed: @"NSApplicationIcon"];
497 if( progress < 0.0 || progress > 1.0 )
499 [NSApp setApplicationIconImage: icon];
503 /* Get it in a raw bitmap form */
504 tiff = [icon TIFFRepresentationUsingCompression:
505 NSTIFFCompressionNone factor: 1.0];
506 bmp = [NSBitmapImageRep imageRepWithData: tiff];
508 /* Draw the progression bar */
509 /* It's pretty simple (ugly?) now, but I'm no designer */
511 row_start = 3 * (int) [bmp size].height / 4;
512 row_end = 7 * (int) [bmp size].height / 8;
514 for( i = row_start; i < row_start + 2; i++ )
516 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
517 for( j = 0; j < (int) [bmp size].width; j++ )
522 for( i = row_start + 2; i < row_end - 2; i++ )
524 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
527 for( j = 2; j < (int) [bmp size].width - 2; j++ )
529 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
541 for( i = row_end - 2; i < row_end; i++ )
543 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
544 for( j = 0; j < (int) [bmp size].width; j++ )
550 /* Now update the dock icon */
551 tiff = [bmp TIFFRepresentationUsingCompression:
552 NSTIFFCompressionNone factor: 1.0];
553 icon = [[NSImage alloc] initWithData: tiff];
554 [NSApp setApplicationIconImage: icon];
558 - (void) updateUI: (NSTimer *) timer
561 /* Update UI for fHandle (user scanning instance of libhb ) */
564 list = hb_get_titles( fHandle );
565 /* check to see if there has been a new scan done
566 this bypasses the constraints of HB_STATE_WORKING
567 not allowing setting a newly scanned source */
568 int checkScanCount = hb_get_scancount( fHandle );
569 if( checkScanCount > currentScanCount )
571 currentScanCount = checkScanCount;
572 [fScanIndicator setIndeterminate: NO];
573 [fScanIndicator setDoubleValue: 0.0];
574 [fScanIndicator setHidden: YES];
575 [self showNewScan:nil];
579 hb_get_state( fHandle, &s );
585 #define p s.param.scanning
586 case HB_STATE_SCANNING:
588 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
589 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
590 p.title_cur, p.title_count]];
591 [fScanIndicator setHidden: NO];
592 [fScanIndicator setDoubleValue: 100.0 * ( p.title_cur - 1 ) / p.title_count];
597 #define p s.param.scandone
598 case HB_STATE_SCANDONE:
600 [fScanIndicator setIndeterminate: NO];
601 [fScanIndicator setDoubleValue: 0.0];
602 [fScanIndicator setHidden: YES];
603 [self writeToActivityLog:"ScanDone state received from fHandle"];
604 [self showNewScan:nil];
605 [[fWindow toolbar] validateVisibleItems];
611 #define p s.param.working
612 case HB_STATE_WORKING:
619 #define p s.param.muxing
620 case HB_STATE_MUXING:
627 case HB_STATE_PAUSED:
630 case HB_STATE_WORKDONE:
637 /* Update UI for fQueueEncodeLibhb */
639 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
640 /* check to see if there has been a new scan done
641 this bypasses the constraints of HB_STATE_WORKING
642 not allowing setting a newly scanned source */
644 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
645 if( checkScanCount > currentScanCount )
647 currentScanCount = checkScanCount;
648 [self writeToActivityLog:"currentScanCount received from fQueueEncodeLibhb"];
652 hb_get_state( fQueueEncodeLibhb, &s );
658 #define p s.param.scanning
659 case HB_STATE_SCANNING:
661 [fStatusField setStringValue: [NSString stringWithFormat:
662 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
663 p.title_cur, p.title_count]];
665 /* Set the status string in fQueueController as well */
666 [fQueueController setQueueStatusString: [NSString stringWithFormat:
667 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
668 p.title_cur, p.title_count]];
670 [fRipIndicator setHidden: NO];
671 [fRipIndicator setDoubleValue: 100.0 * ( p.title_cur - 1 ) / p.title_count];
676 #define p s.param.scandone
677 case HB_STATE_SCANDONE:
679 [fRipIndicator setIndeterminate: NO];
680 [fRipIndicator setDoubleValue: 0.0];
682 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
683 [self processNewQueueEncode];
684 [[fWindow toolbar] validateVisibleItems];
690 #define p s.param.working
691 case HB_STATE_WORKING:
693 float progress_total;
694 NSMutableString * string;
695 /* Update text field */
696 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d of %d, %.2f %%", @"" ), p.job_cur, p.job_count, 100.0 * p.progress];
700 [string appendFormat:
701 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
702 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
705 [fStatusField setStringValue: string];
706 /* Set the status string in fQueueController as well */
707 [fQueueController setQueueStatusString: string];
709 progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
710 [fRipIndicator setIndeterminate: NO];
711 [fRipIndicator setDoubleValue: 100.0 * progress_total];
713 // If progress bar hasn't been revealed at the bottom of the window, do
714 // that now. This code used to be in doRip. I moved it to here to handle
715 // the case where hb_start is called by HBQueueController and not from
717 if( !fRipIndicatorShown )
719 NSRect frame = [fWindow frame];
720 if( frame.size.width <= 591 )
721 frame.size.width = 591;
722 frame.size.height += 36;
723 frame.origin.y -= 36;
724 [fWindow setFrame:frame display:YES animate:YES];
725 fRipIndicatorShown = YES;
729 /* Update dock icon */
730 [self UpdateDockIcon: progress_total];
736 #define p s.param.muxing
737 case HB_STATE_MUXING:
739 /* Update text field */
740 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
741 /* Set the status string in fQueueController as well */
742 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
744 [fRipIndicator setIndeterminate: YES];
745 [fRipIndicator startAnimation: nil];
747 /* Update dock icon */
748 [self UpdateDockIcon: 1.0];
754 case HB_STATE_PAUSED:
755 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
756 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
760 case HB_STATE_WORKDONE:
762 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
763 // or someone calling hb_stop. In the latter case, hb_stop does not clear
764 // out the remaining passes/jobs in the queue. We'll do that here.
766 // Delete all remaining jobs of this encode.
767 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
768 /* Set the status string in fQueueController as well */
769 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
770 [fRipIndicator setIndeterminate: NO];
771 [fRipIndicator setDoubleValue: 0.0];
772 [[fWindow toolbar] validateVisibleItems];
774 /* Restore dock icon */
775 [self UpdateDockIcon: -1.0];
777 if( fRipIndicatorShown )
779 NSRect frame = [fWindow frame];
780 if( frame.size.width <= 591 )
781 frame.size.width = 591;
782 frame.size.height += -36;
783 frame.origin.y -= -36;
784 [fWindow setFrame:frame display:YES animate:YES];
785 fRipIndicatorShown = NO;
787 /* Since we are done with this encode, tell output to stop writing to the
788 * individual encode log
790 [outputPanel endEncodeLog];
791 /* Check to see if the encode state has not been cancelled
792 to determine if we should check for encode done notifications */
793 if( fEncodeState != 2 )
795 NSString *pathOfFinishedEncode;
796 /* Get the output file name for the finished encode */
797 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
799 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
801 [self showGrowlDoneNotification:pathOfFinishedEncode];
803 [self sendToMetaX:pathOfFinishedEncode];
805 /* since we have successfully completed an encode, we increment the queue counter */
806 [self incrementQueueItemDone:nil];
808 /* all end of queue actions below need to be done after all queue encodes have finished
809 * and there are no pending jobs left to process
811 if (fPendingCount == 0)
813 /* If Alert Window or Window and Growl has been selected */
814 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
815 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
817 /*On Screen Notification*/
820 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
821 [NSApp requestUserAttention:NSCriticalRequest];
824 /* If sleep has been selected */
825 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
828 NSDictionary* errorDict;
829 NSAppleEventDescriptor* returnDescriptor = nil;
830 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
831 @"tell application \"Finder\" to sleep"];
832 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
833 [scriptObject release];
835 /* If Shutdown has been selected */
836 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
839 NSDictionary* errorDict;
840 NSAppleEventDescriptor* returnDescriptor = nil;
841 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
842 @"tell application \"Finder\" to shut down"];
843 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
844 [scriptObject release];
858 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
859 - (void) writeToActivityLog:(char *) format, ...
862 va_start(args, format);
866 vsnprintf( str, 1024, format, args );
868 time_t _now = time( NULL );
869 struct tm * now = localtime( &_now );
870 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
877 // ============================================================
878 // NSToolbar Related Methods
879 // ============================================================
881 - (void) setupToolbar {
882 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
884 [toolbar setAllowsUserCustomization: YES];
885 [toolbar setAutosavesConfiguration: YES];
886 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
888 [toolbar setDelegate: self];
890 [fWindow setToolbar: toolbar];
893 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
894 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
895 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
897 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
899 [item setLabel: @"Toggle Presets"];
900 [item setPaletteLabel: @"Toggler Presets"];
901 [item setToolTip: @"Open/Close Preset Drawer"];
902 [item setImage: [NSImage imageNamed: @"Drawer"]];
903 [item setTarget: self];
904 [item setAction: @selector(toggleDrawer:)];
905 [item setAutovalidates: NO];
907 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
909 [item setLabel: @"Start"];
910 [item setPaletteLabel: @"Start Encoding"];
911 [item setToolTip: @"Start Encoding"];
912 [item setImage: [NSImage imageNamed: @"Play"]];
913 [item setTarget: self];
914 [item setAction: @selector(Rip:)];
916 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
918 [item setLabel: @"Show Queue"];
919 [item setPaletteLabel: @"Show Queue"];
920 [item setToolTip: @"Show Queue"];
921 [item setImage: [NSImage imageNamed: @"Queue"]];
922 [item setTarget: self];
923 [item setAction: @selector(showQueueWindow:)];
924 [item setAutovalidates: NO];
926 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
928 [item setLabel: @"Add to Queue"];
929 [item setPaletteLabel: @"Add to Queue"];
930 [item setToolTip: @"Add to Queue"];
931 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
932 [item setTarget: self];
933 [item setAction: @selector(addToQueue:)];
935 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
937 [item setLabel: @"Pause"];
938 [item setPaletteLabel: @"Pause Encoding"];
939 [item setToolTip: @"Pause Encoding"];
940 [item setImage: [NSImage imageNamed: @"Pause"]];
941 [item setTarget: self];
942 [item setAction: @selector(Pause:)];
944 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
946 [item setLabel: @"Picture Settings"];
947 [item setPaletteLabel: @"Show Picture Settings"];
948 [item setToolTip: @"Show Picture Settings"];
949 [item setImage: [NSImage imageNamed: @"pref-picture"]];
950 [item setTarget: self];
951 [item setAction: @selector(showPicturePanel:)];
953 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
955 [item setLabel: @"Activity Window"];
956 [item setPaletteLabel: @"Show Activity Window"];
957 [item setToolTip: @"Show Activity Window"];
958 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
959 [item setTarget: self];
960 [item setAction: @selector(showDebugOutputPanel:)];
961 [item setAutovalidates: NO];
963 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
965 [item setLabel: @"Source"];
966 [item setPaletteLabel: @"Source"];
967 [item setToolTip: @"Choose Video Source"];
968 [item setImage: [NSImage imageNamed: @"Source"]];
969 [item setTarget: self];
970 [item setAction: @selector(browseSources:)];
980 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
982 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
983 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
984 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
987 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
989 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
990 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
991 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
992 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
995 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
997 NSString * ident = [toolbarItem itemIdentifier];
1002 hb_get_state2( fQueueEncodeLibhb, &s );
1004 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
1006 if ([ident isEqualToString: StartEncodingIdentifier])
1008 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1009 [toolbarItem setLabel: @"Stop"];
1010 [toolbarItem setPaletteLabel: @"Stop"];
1011 [toolbarItem setToolTip: @"Stop Encoding"];
1014 if ([ident isEqualToString: PauseEncodingIdentifier])
1016 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1017 [toolbarItem setLabel: @"Pause"];
1018 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1019 [toolbarItem setToolTip: @"Pause Encoding"];
1024 if ([ident isEqualToString: AddToQueueIdentifier])
1026 if ([ident isEqualToString: ShowPictureIdentifier])
1030 else if (s.state == HB_STATE_PAUSED)
1032 if ([ident isEqualToString: PauseEncodingIdentifier])
1034 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1035 [toolbarItem setLabel: @"Resume"];
1036 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1037 [toolbarItem setToolTip: @"Resume Encoding"];
1040 if ([ident isEqualToString: StartEncodingIdentifier])
1042 if ([ident isEqualToString: AddToQueueIdentifier])
1044 if ([ident isEqualToString: ShowPictureIdentifier])
1047 else if (s.state == HB_STATE_SCANNING)
1049 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1051 if ([ident isEqualToString: StartEncodingIdentifier])
1053 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1054 if (hb_count(fHandle) > 0)
1055 [toolbarItem setLabel: @"Start Queue"];
1057 [toolbarItem setLabel: @"Start"];
1058 [toolbarItem setPaletteLabel: @"Start Encoding"];
1059 [toolbarItem setToolTip: @"Start Encoding"];
1062 if ([ident isEqualToString: AddToQueueIdentifier])
1064 if ([ident isEqualToString: ShowPictureIdentifier])
1069 /* If there are any pending queue items, make sure the start/stop button is active */
1070 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1072 if ([ident isEqualToString: ShowQueueIdentifier])
1074 if ([ident isEqualToString: ToggleDrawerIdentifier])
1076 if ([ident isEqualToString: ChooseSourceIdentifier])
1078 if ([ident isEqualToString: ShowActivityIdentifier])
1084 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1086 SEL action = [menuItem action];
1089 hb_get_state2( fHandle, &s );
1093 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1094 return SuccessfulScan && [fWindow attachedSheet] == nil;
1096 if (action == @selector(browseSources:))
1098 if (s.state == HB_STATE_SCANNING)
1101 return [fWindow attachedSheet] == nil;
1103 if (action == @selector(selectDefaultPreset:))
1104 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1105 if (action == @selector(Pause:))
1107 if (s.state == HB_STATE_WORKING)
1109 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1110 [menuItem setTitle:@"Pause Encoding"];
1113 else if (s.state == HB_STATE_PAUSED)
1115 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1116 [menuItem setTitle:@"Resume Encoding"];
1122 if (action == @selector(Rip:))
1124 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1126 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1127 [menuItem setTitle:@"Stop Encoding"];
1130 else if (SuccessfulScan)
1132 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1133 [menuItem setTitle:@"Start Encoding"];
1134 return [fWindow attachedSheet] == nil;
1140 if( action == @selector(setDefaultPreset:) )
1142 return [fPresetsOutlineView selectedRow] != -1;
1149 #pragma mark Encode Done Actions
1150 // register a test notification and make
1151 // it enabled by default
1152 #define SERVICE_NAME @"Encode Done"
1153 - (NSDictionary *)registrationDictionaryForGrowl
1155 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1156 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1157 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1160 return registrationDictionary;
1163 -(void)showGrowlDoneNotification:(NSString *) filePath
1165 /* This end of encode action is called as each encode rolls off of the queue */
1166 NSString * finishedEncode = filePath;
1167 /* strip off the path to just show the file name */
1168 finishedEncode = [finishedEncode lastPathComponent];
1169 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1170 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1172 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1173 [GrowlApplicationBridge
1174 notifyWithTitle:@"Put down that cocktail..."
1175 description:growlMssg
1176 notificationName:SERVICE_NAME
1184 -(void)sendToMetaX:(NSString *) filePath
1186 /* This end of encode action is called as each encode rolls off of the queue */
1187 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1189 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
1190 [myScript executeAndReturnError: nil];
1195 #pragma mark Get New Source
1197 /*Opens the source browse window, called from Open Source widgets */
1198 - (IBAction) browseSources: (id) sender
1200 NSOpenPanel * panel;
1202 panel = [NSOpenPanel openPanel];
1203 [panel setAllowsMultipleSelection: NO];
1204 [panel setCanChooseFiles: YES];
1205 [panel setCanChooseDirectories: YES ];
1206 NSString * sourceDirectory;
1207 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1209 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1213 sourceDirectory = @"~/Desktop";
1214 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1216 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1217 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1219 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1220 modalForWindow: fWindow modalDelegate: self
1221 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1222 contextInfo: sender];
1225 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1226 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1228 /* we convert the sender content of contextInfo back into a variable called sender
1229 * mostly just for consistency for evaluation later
1231 id sender = (id)contextInfo;
1232 /* User selected a file to open */
1233 if( returnCode == NSOKButton )
1235 /* Free display name allocated previously by this code */
1236 [browsedSourceDisplayName release];
1238 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1239 /* we set the last searched source directory in the prefs here */
1240 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1241 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1242 /* we order out sheet, which is the browse window as we need to open
1243 * the title selection sheet right away
1245 [sheet orderOut: self];
1247 if (sender == fOpenSourceTitleMMenu)
1249 /* We put the chosen source path in the source display text field for the
1250 * source title selection sheet in which the user specifies the specific title to be
1251 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1252 * purposes in the title panel
1255 [fScanSrcTitlePathField setStringValue:scanPath];
1256 NSString *displayTitlescanSourceName;
1258 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1260 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1261 we have to use the title->dvd value so we get the proper name of the volume if a physical dvd is the source*/
1262 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1266 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1267 displayTitlescanSourceName = [scanPath lastPathComponent];
1269 /* we set the source display name in the title selection dialogue */
1270 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1271 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1272 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1273 /* We show the actual sheet where the user specifies the title to be scanned
1274 * as we are going to do a title specific scan
1276 [self showSourceTitleScanPanel:nil];
1280 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1281 NSString *path = [[sheet filenames] objectAtIndex: 0];
1283 /* We check to see if the chosen file at path is a package */
1284 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1286 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1287 /* We check to see if this is an .eyetv package */
1288 if ([[path pathExtension] isEqualToString: @"eyetv"])
1290 [self writeToActivityLog:"trying to open eyetv package"];
1291 /* We're looking at an EyeTV package - try to open its enclosed
1293 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1295 int n = [[path stringByAppendingString: @"/"]
1296 completePathIntoString: &mpgname caseSensitive: NO
1297 matchesIntoArray: nil
1298 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1301 /* Found an mpeg inside the eyetv package, make it our scan path
1302 and call performScan on the enclosed mpeg */
1304 [self writeToActivityLog:"found mpeg in eyetv package"];
1305 [self performScan:path scanTitleNum:0];
1309 /* We did not find an mpeg file in our package, so we do not call performScan */
1310 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1313 /* We check to see if this is a .dvdmedia package */
1314 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1316 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1317 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1318 [self writeToActivityLog:"trying to open dvdmedia package"];
1319 [self performScan:path scanTitleNum:0];
1323 /* The package is not an eyetv package, so we do not call performScan */
1324 [self writeToActivityLog:"unable to open package"];
1327 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1329 /* path is not a package, so we call perform scan directly on our file */
1330 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1332 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1333 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1334 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1338 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1339 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1340 /* make sure we remove any path extension as this can also be an '.mpg' file */
1341 browsedSourceDisplayName = [[path lastPathComponent] retain];
1343 [self performScan:path scanTitleNum:0];
1351 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1352 - (IBAction) showSourceTitleScanPanel: (id) sender
1354 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1357 [fScanSrcTitleNumField setStringValue: @"0"];
1358 /* Show the panel */
1359 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1362 - (IBAction) closeSourceTitleScanPanel: (id) sender
1364 [NSApp endSheet: fScanSrcTitlePanel];
1365 [fScanSrcTitlePanel orderOut: self];
1367 if(sender == fScanSrcTitleOpenButton)
1369 /* We setup the scan status in the main window to indicate a source title scan */
1370 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1371 [fScanIndicator setHidden: NO];
1372 [fScanIndicator setIndeterminate: YES];
1373 [fScanIndicator startAnimation: nil];
1375 /* We use the performScan method to actually perform the specified scan passing the path and the title
1378 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1382 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1383 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1385 /* set the bool applyQueueToScan so that we dont apply a queue setting to the final scan */
1386 applyQueueToScan = NO;
1387 /* use a bool to determine whether or not we can decrypt using vlc */
1388 BOOL cancelScanDecrypt = 0;
1389 NSString *path = scanPath;
1390 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1392 // Notify ChapterTitles that there's no title
1393 [fChapterTitlesDelegate resetWithTitle:nil];
1394 [fChapterTable reloadData];
1396 [self enableUI: NO];
1398 if( [detector isVideoDVD] )
1400 // The chosen path was actually on a DVD, so use the raw block
1401 // device path instead.
1402 path = [detector devicePath];
1403 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1405 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1406 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1407 NSFileManager * fileManager = [NSFileManager defaultManager];
1408 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1410 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1411 cancelScanDecrypt = 1;
1412 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1414 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");
1415 [NSApp requestUserAttention:NSCriticalRequest];
1417 if (status == NSAlertDefaultReturn)
1419 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1420 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
1422 else if (status == NSAlertAlternateReturn)
1424 /* User chose to cancel the scan */
1425 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1429 /* 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 */
1430 cancelScanDecrypt = 0;
1431 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1437 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1438 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1442 if (cancelScanDecrypt == 0)
1444 /* we actually pass the scan off to libhb here */
1445 /* If there is no title number passed to scan, we use "0"
1446 * which causes the default behavior of a full source scan
1452 if (scanTitleNum > 0)
1454 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1456 /* We use our advance pref to determine how many previews to scan */
1457 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1458 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1459 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1463 - (IBAction) showNewScan:(id)sender
1467 int indxpri=0; // Used to search the longuest title (default in combobox)
1468 int longuestpri=0; // Used to search the longuest title (default in combobox)
1471 list = hb_get_titles( fHandle );
1473 if( !hb_list_count( list ) )
1475 /* We display a message if a valid dvd source was not chosen */
1476 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1477 SuccessfulScan = NO;
1479 // Notify ChapterTitles that there's no title
1480 [fChapterTitlesDelegate resetWithTitle:nil];
1481 [fChapterTable reloadData];
1485 /* We increment the successful scancount here by one,
1486 which we use at the end of this function to tell the gui
1487 if this is the first successful scan since launch and whether
1488 or not we should set all settings to the defaults */
1490 currentSuccessfulScanCount++;
1492 [[fWindow toolbar] validateVisibleItems];
1494 [fSrcTitlePopUp removeAllItems];
1495 for( int i = 0; i < hb_list_count( list ); i++ )
1497 title = (hb_title_t *) hb_list_item( list, i );
1499 currentSource = [NSString stringWithUTF8String: title->name];
1500 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1501 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1503 /* Use the dvd name in the default output field here
1504 May want to add code to remove blank spaces for some dvd names*/
1505 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1506 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1508 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1509 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1513 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1514 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1518 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1520 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1524 [fSrcTitlePopUp addItemWithTitle: [NSString
1525 stringWithFormat: @"%d - %02dh%02dm%02ds",
1526 title->index, title->hours, title->minutes,
1530 // Select the longuest title
1531 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1532 [self titlePopUpChanged:nil];
1534 SuccessfulScan = YES;
1535 [self enableUI: YES];
1537 /* if its the initial successful scan after awakeFromNib */
1538 if (currentSuccessfulScanCount == 1)
1540 [self selectDefaultPreset:nil];
1542 [fPictureFilterController setInitialPictureFilters];
1544 // Open preview window now if it was visible when HB was closed
1545 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1546 [self showPreviewWindow:nil];
1548 // Open picture sizing window now if it was visible when HB was closed
1549 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1550 [self showPicturePanel:nil];
1552 // Open filters window now if it was visible when HB was closed
1553 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureFiltersWindowIsOpen"])
1554 [self showFiltersPanel:nil];
1564 #pragma mark New Output Destination
1566 - (IBAction) browseFile: (id) sender
1568 /* Open a panel to let the user choose and update the text field */
1569 NSSavePanel * panel = [NSSavePanel savePanel];
1570 /* We get the current file name and path from the destination field here */
1571 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1572 modalForWindow: fWindow modalDelegate: self
1573 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1577 - (void) browseFileDone: (NSSavePanel *) sheet
1578 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1580 if( returnCode == NSOKButton )
1582 [fDstFile2Field setStringValue: [sheet filename]];
1583 /* Save this path to the prefs so that on next browse destination window it opens there */
1584 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1585 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1591 #pragma mark Main Window Control
1593 - (IBAction) openMainWindow: (id) sender
1595 [fWindow makeKeyAndOrderFront:nil];
1598 - (BOOL) windowShouldClose: (id) sender
1603 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1606 [fWindow makeKeyAndOrderFront:nil];
1614 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1615 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1620 #pragma mark Queue File
1622 - (void) loadQueueFile {
1623 /* We declare the default NSFileManager into fileManager */
1624 NSFileManager * fileManager = [NSFileManager defaultManager];
1625 /*We define the location of the user presets file */
1626 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1627 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1628 /* We check for the presets.plist */
1629 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1631 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1634 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1635 /* lets check to see if there is anything in the queue file .plist */
1636 if (nil == QueueFileArray)
1638 /* if not, then lets initialize an empty array */
1639 QueueFileArray = [[NSMutableArray alloc] init];
1641 /* Initialize our curQueueEncodeIndex to 0
1642 * so we can use it to track which queue
1643 * item is to be used to track our encodes */
1644 /* NOTE: this should be changed if and when we
1645 * are able to get the last unfinished encode
1646 * in the case of a crash or shutdown */
1651 [self clearQueueEncodedItems];
1653 currentQueueEncodeIndex = 0;
1656 - (void)addQueueFileItem
1658 [QueueFileArray addObject:[self createQueueFileItem]];
1659 [self saveQueueFileItem];
1663 - (void) removeQueueFileItem:(int) queueItemToRemove
1666 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
1667 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
1669 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
1670 * by one to keep in sync with the queue array
1672 currentQueueEncodeIndex--;
1673 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
1675 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1676 [self saveQueueFileItem];
1680 - (void)saveQueueFileItem
1682 [QueueFileArray writeToFile:QueueFile atomically:YES];
1683 [fQueueController setQueueArray: QueueFileArray];
1684 [self getQueueStats];
1687 - (void)getQueueStats
1689 /* lets get the stats on the status of the queue array */
1691 fEncodingQueueItem = 0;
1693 fCompletedCount = 0;
1697 /* We use a number system to set the encode status of the queue item
1699 * 0 == already encoded
1700 * 1 == is being encoded
1701 * 2 == is yet to be encoded
1706 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1708 while (tempObject = [enumerator nextObject])
1710 NSDictionary *thisQueueDict = tempObject;
1711 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1715 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1718 fEncodingQueueItem = i;
1720 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
1724 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
1731 /* Set the queue status field in the main window */
1732 NSMutableString * string;
1733 if (fPendingCount == 1)
1735 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
1739 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
1741 [fQueueStatus setStringValue:string];
1744 /* This method will set any item marked as encoding back to pending
1745 * currently used right after a queue reload
1747 - (void) setQueueEncodingItemsAsPending
1749 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1751 NSMutableArray *tempArray;
1752 tempArray = [NSMutableArray array];
1753 /* we look here to see if the preset is we move on to the next one */
1754 while ( tempObject = [enumerator nextObject] )
1756 /* If the queue item is marked as "encoding" (1)
1757 * then change its status back to pending (2) which effectively
1758 * puts it back into the queue to be encoded
1760 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
1762 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
1764 [tempArray addObject:tempObject];
1767 [QueueFileArray setArray:tempArray];
1768 [self saveQueueFileItem];
1772 /* This method will clear the queue of any encodes that are not still pending
1773 * this includes both successfully completed encodes as well as cancelled encodes */
1774 - (void) clearQueueEncodedItems
1776 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1778 NSMutableArray *tempArray;
1779 tempArray = [NSMutableArray array];
1780 /* we look here to see if the preset is we move on to the next one */
1781 while ( tempObject = [enumerator nextObject] )
1783 /* If the queue item is either completed (0) or cancelled (3) from the
1784 * last session, then we put it in tempArray to be deleted from QueueFileArray.
1785 * NOTE: this means we retain pending (2) and also an item that is marked as
1786 * still encoding (1). If the queue has an item that is still marked as encoding
1787 * from a previous session, we can conlude that HB was either shutdown, or crashed
1788 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
1790 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
1792 [tempArray addObject:tempObject];
1796 [QueueFileArray removeObjectsInArray:tempArray];
1797 [self saveQueueFileItem];
1800 /* This method will clear the queue of all encodes. effectively creating an empty queue */
1801 - (void) clearQueueAllItems
1803 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1805 NSMutableArray *tempArray;
1806 tempArray = [NSMutableArray array];
1807 /* we look here to see if the preset is we move on to the next one */
1808 while ( tempObject = [enumerator nextObject] )
1810 [tempArray addObject:tempObject];
1813 [QueueFileArray removeObjectsInArray:tempArray];
1814 [self saveQueueFileItem];
1817 /* This method will duplicate prepareJob however into the
1818 * queue .plist instead of into the job structure so it can
1819 * be recalled later */
1820 - (NSDictionary *)createQueueFileItem
1822 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
1824 hb_list_t * list = hb_get_titles( fHandle );
1825 hb_title_t * title = (hb_title_t *) hb_list_item( list,
1826 [fSrcTitlePopUp indexOfSelectedItem] );
1827 hb_job_t * job = title->job;
1831 /* We use a number system to set the encode status of the queue item
1832 * 0 == already encoded
1833 * 1 == is being encoded
1834 * 2 == is yet to be encoded
1837 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
1838 /* Source and Destination Information */
1840 [queueFileJob setObject:[NSString stringWithUTF8String: title->dvd] forKey:@"SourcePath"];
1841 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
1842 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
1843 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
1845 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
1847 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
1849 /* Lets get the preset info if there is any */
1850 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
1851 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
1853 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
1854 /* Chapter Markers fCreateChapterMarkers*/
1855 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
1857 /* We need to get the list of chapter names to put into an array and store
1858 * in our queue, so they can be reapplied in prepareJob when this queue
1859 * item comes up if Chapter Markers is set to on.
1862 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
1863 int chaptercount = hb_list_count( fTitle->list_chapter );
1864 for( i = 0; i < chaptercount; i++ )
1866 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
1867 if( chapter != NULL )
1869 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
1872 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
1873 [ChapterNamesArray autorelease];
1875 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
1876 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
1877 /* Mux mp4 with http optimization */
1878 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
1879 /* Add iPod uuid atom */
1880 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
1884 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
1885 /* x264 Option String */
1886 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
1888 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
1889 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
1890 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
1891 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
1893 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
1895 /* 2 Pass Encoding */
1896 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
1897 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
1898 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
1900 /* Picture Sizing */
1901 /* Use Max Picture settings for whatever the dvd is.*/
1902 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1903 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1904 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1905 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1906 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
1907 NSString * pictureSummary;
1908 pictureSummary = [fPictureSizeField stringValue];
1909 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
1910 /* Set crop settings here */
1911 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
1912 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
1913 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
1914 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
1915 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
1917 /* Picture Filters */
1918 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController detelecine]] forKey:@"PictureDetelecine"];
1919 [queueFileJob setObject:[fPictureFilterController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
1921 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController useDecomb]] forKey:@"PictureDecombDeinterlace"];
1922 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController decomb]] forKey:@"PictureDecomb"];
1923 [queueFileJob setObject:[fPictureFilterController decombCustomString] forKey:@"PictureDecombCustom"];
1925 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController deinterlace]] forKey:@"PictureDeinterlace"];
1926 [queueFileJob setObject:[fPictureFilterController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
1928 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController denoise]] forKey:@"PictureDenoise"];
1929 [queueFileJob setObject:[fPictureFilterController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
1931 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureFilterController deblock]] forKey:@"PictureDeblock"];
1933 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController grayscale]] forKey:@"VideoGrayScale"];
1936 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
1938 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
1939 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
1940 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
1941 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
1942 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
1943 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
1944 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
1946 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
1948 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
1949 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
1950 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
1951 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
1952 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
1953 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
1954 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
1956 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
1958 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
1959 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
1960 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
1961 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
1962 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
1963 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
1964 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
1966 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
1968 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
1969 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
1970 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
1971 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
1972 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
1973 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
1974 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
1978 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
1979 [queueFileJob setObject:[NSNumber numberWithInt:[fSubPopUp indexOfSelectedItem]] forKey:@"JobSubtitlesIndex"];
1980 /* Forced Subtitles */
1981 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
1985 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
1987 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
1989 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
1992 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
1996 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
1999 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2000 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2001 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2003 /* Picture Sizing */
2004 /* Use Max Picture settings for whatever the dvd is.*/
2005 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2006 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2007 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2008 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2009 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2011 /* Set crop settings here */
2012 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2013 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2014 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2015 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2016 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2018 /* Picture Filters */
2019 //[queueFileJob setObject:[fPicSettingDecomb stringValue] forKey:@"JobPictureDecomb"];
2022 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2024 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2025 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2026 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2027 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2028 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2030 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2032 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2033 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2034 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2035 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2036 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2038 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2040 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2041 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2042 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2043 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2044 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2046 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2048 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2049 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2050 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2051 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2052 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2055 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
2056 /* Forced Subtitles */
2057 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
2059 /* we need to auto relase the queueFileJob and return it */
2060 [queueFileJob autorelease];
2061 return queueFileJob;
2065 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2066 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
2068 unsigned index = [indexSet lastIndex];
2069 unsigned aboveInsertIndexCount = 0;
2071 while (index != NSNotFound)
2073 unsigned removeIndex;
2075 if (index >= insertIndex)
2077 removeIndex = index + aboveInsertIndexCount;
2078 aboveInsertIndexCount++;
2082 removeIndex = index;
2086 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2087 [QueueFileArray removeObjectAtIndex:removeIndex];
2088 [QueueFileArray insertObject:object atIndex:insertIndex];
2091 index = [indexSet indexLessThanIndex:index];
2093 /* We save all of the Queue data here
2094 * and it also gets sent back to the queue controller*/
2095 [self saveQueueFileItem];
2101 #pragma mark Queue Job Processing
2103 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2105 int i = currentQueueEncodeIndex;
2106 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2108 /* We save all of the Queue data here */
2109 [self saveQueueFileItem];
2110 /* We Reload the New Table data for presets */
2111 //[fPresetsOutlineView reloadData];
2113 /* Since we have now marked a queue item as done
2114 * we can go ahead and increment currentQueueEncodeIndex
2115 * so that if there is anything left in the queue we can
2116 * go ahead and move to the next item if we want to */
2117 currentQueueEncodeIndex++ ;
2118 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2119 int queueItems = [QueueFileArray count];
2120 /* If we still have more items in our queue, lets go to the next one */
2121 if (currentQueueEncodeIndex < queueItems)
2123 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2124 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2128 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2132 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2133 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2135 /* Tell HB to output a new activity log file for this encode */
2136 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2139 /* use a bool to determine whether or not we can decrypt using vlc */
2140 BOOL cancelScanDecrypt = 0;
2141 /* set the bool so that showNewScan knows to apply the appropriate queue
2142 * settings as this is a queue rescan
2144 applyQueueToScan = YES;
2145 NSString *path = scanPath;
2146 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2148 /*On Screen Notification*/
2150 //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2151 //[NSApp requestUserAttention:NSCriticalRequest];
2153 if( [detector isVideoDVD] )
2155 // The chosen path was actually on a DVD, so use the raw block
2156 // device path instead.
2157 path = [detector devicePath];
2158 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2160 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2161 NSString *vlcPath = @"/Applications/VLC.app";
2162 NSFileManager * fileManager = [NSFileManager defaultManager];
2163 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2165 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2166 cancelScanDecrypt = 1;
2167 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2169 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");
2170 [NSApp requestUserAttention:NSCriticalRequest];
2172 if (status == NSAlertDefaultReturn)
2174 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2175 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2177 else if (status == NSAlertAlternateReturn)
2179 /* User chose to cancel the scan */
2180 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2184 /* 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 */
2185 cancelScanDecrypt = 0;
2186 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2192 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2193 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2197 if (cancelScanDecrypt == 0)
2199 /* we actually pass the scan off to libhb here */
2200 /* If there is no title number passed to scan, we use "0"
2201 * which causes the default behavior of a full source scan
2207 if (scanTitleNum > 0)
2209 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2212 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2213 /* We use our advance pref to determine how many previews to scan */
2214 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2215 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2219 /* This method was originally used to load up a new queue item in the gui and
2220 * then start processing it. However we now have modified -prepareJob and use a second
2221 * instance of libhb to do our actual encoding, therefor right now it is not required.
2222 * Nonetheless I want to leave this in here
2223 * because basically its everything we need to be able to actually modify a pending queue
2224 * item in the gui and resave it. At least for now - dynaflash
2227 - (IBAction)applyQueueSettings:(id)sender
2229 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2230 hb_job_t * job = fTitle->job;
2232 /* Set title number and chapters */
2233 /* since the queue only scans a single title, we really don't need to pick a title */
2234 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2236 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2237 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2240 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2241 [self formatPopUpChanged:nil];
2243 /* Chapter Markers*/
2244 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2245 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2246 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2247 /* Mux mp4 with http optimization */
2248 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2251 /* We set the advanced opt string here if applicable*/
2252 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2253 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2255 /* Lets run through the following functions to get variables set there */
2256 [self videoEncoderPopUpChanged:nil];
2257 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2258 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2259 [self calculateBitrate:nil];
2262 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2264 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2265 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2266 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2268 [self videoMatrixChanged:nil];
2270 /* Video framerate */
2271 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2272 detected framerate in the fVidRatePopUp so we use index 0*/
2273 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2275 [fVidRatePopUp selectItemAtIndex: 0];
2279 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2282 /* 2 Pass Encoding */
2283 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2284 [self twoPassCheckboxChanged:nil];
2285 /* Turbo 1st pass for 2 Pass Encoding */
2286 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2289 if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2291 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2293 [fAudLang1PopUp selectItemAtIndex: 1];
2295 [self audioTrackPopUpChanged: fAudLang1PopUp];
2296 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2297 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2298 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2299 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2301 if ([fAudTrack1MixPopUp selectedItem] == nil)
2303 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2305 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2306 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2307 if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2309 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2311 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2312 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2314 if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2316 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2318 [fAudLang2PopUp selectItemAtIndex: 1];
2320 [self audioTrackPopUpChanged: fAudLang2PopUp];
2321 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2322 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2323 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2324 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2326 if ([fAudTrack2MixPopUp selectedItem] == nil)
2328 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2330 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2331 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2332 if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2334 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2336 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2337 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2339 if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2341 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2343 [fAudLang3PopUp selectItemAtIndex: 1];
2345 [self audioTrackPopUpChanged: fAudLang3PopUp];
2346 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2347 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2348 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2349 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2351 if ([fAudTrack3MixPopUp selectedItem] == nil)
2353 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2355 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2356 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2357 if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2359 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2361 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2362 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2364 if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2366 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2368 [fAudLang4PopUp selectItemAtIndex: 1];
2370 [self audioTrackPopUpChanged: fAudLang4PopUp];
2371 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2372 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2373 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2374 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2376 if ([fAudTrack4MixPopUp selectedItem] == nil)
2378 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2380 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2381 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2382 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2384 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2386 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2387 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2392 [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2393 /* Forced Subtitles */
2394 [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2396 /* Picture Settings */
2397 /* we check to make sure the presets width/height does not exceed the sources width/height */
2398 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2400 /* if so, then we use the sources height and width to avoid scaling up */
2401 job->width = fTitle->width;
2402 job->height = fTitle->height;
2404 else // source width/height is >= the preset height/width
2406 /* we can go ahead and use the presets values for height and width */
2407 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2408 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2410 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2411 if (job->keep_ratio == 1)
2413 hb_fix_aspect( job, HB_KEEP_WIDTH );
2414 if( job->height > fTitle->height )
2416 job->height = fTitle->height;
2417 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2420 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2423 /* If Cropping is set to custom, then recall all four crop values from
2424 when the preset was created and apply them */
2425 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2427 [fPictureController setAutoCrop:NO];
2429 /* Here we use the custom crop values saved at the time the preset was saved */
2430 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2431 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2432 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2433 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2436 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2438 [fPictureController setAutoCrop:YES];
2439 /* Here we use the auto crop values determined right after scan */
2440 job->crop[0] = AutoCropTop;
2441 job->crop[1] = AutoCropBottom;
2442 job->crop[2] = AutoCropLeft;
2443 job->crop[3] = AutoCropRight;
2449 [fPictureFilterController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2452 [fPictureFilterController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2454 [fPictureFilterController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2456 [fPictureFilterController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2458 [fPictureFilterController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2460 [fPictureFilterController setGrayscale:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2462 [self calculatePictureSizing:nil];
2465 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2466 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2467 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2468 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2470 /* Deselect the currently selected Preset if there is one*/
2471 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2472 //[self selectPreset:nil];
2474 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2475 /* Change UI to show "Custom" settings are being used */
2476 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2478 curUserPresetChosenNum = nil;
2482 /* Deselect the currently selected Preset if there is one*/
2483 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2484 /* Change UI to show "Custom" settings are being used */
2485 [fPresetSelectedDisplay setStringValue: @"Custom"];
2487 //curUserPresetChosenNum = nil;
2490 /* We need to set this bool back to NO, in case the user wants to do a scan */
2491 //applyQueueToScan = NO;
2493 /* so now we go ahead and process the new settings */
2494 [self processNewQueueEncode];
2499 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2500 - (void) processNewQueueEncode
2502 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2503 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2504 hb_job_t * job = title->job;
2506 if( !hb_list_count( list ) )
2508 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2512 [self writeToActivityLog: "processNewQueueEncode title list is: %d", hb_list_count( list )];
2515 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2516 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2517 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2518 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2519 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2521 if( [[queueToApply objectForKey:@"SubtitlesForced"] intValue] == 1 )
2522 job->subtitle_force = 1;
2524 job->subtitle_force = 0;
2527 * subtitle of -1 is a scan
2529 if( job->subtitle == -1 )
2534 * When subtitle scan is enabled do a fast pre-scan job
2535 * which will determine which subtitles to enable, if any.
2538 x264opts_tmp = job->x264opts;
2541 job->x264opts = NULL;
2543 job->indepth_scan = 1;
2545 job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
2546 *(job->select_subtitle) = NULL;
2549 * Add the pre-scan job
2551 hb_add( fQueueEncodeLibhb, job );
2552 job->x264opts = x264opts_tmp;
2555 job->select_subtitle = NULL;
2557 /* No subtitle were selected, so reset the subtitle to -1 (which before
2558 * this point meant we were scanning
2560 if( job->subtitle == -2 )
2563 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2565 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
2566 job->indepth_scan = 0;
2569 * Do not autoselect subtitles on the first pass of a two pass
2571 job->select_subtitle = NULL;
2575 hb_add( fQueueEncodeLibhb, job );
2579 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2580 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2582 job->select_subtitle = subtitle_tmp;
2584 hb_add( fQueueEncodeLibhb, job );
2589 job->indepth_scan = 0;
2592 hb_add( fQueueEncodeLibhb, job );
2595 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2596 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2597 /* Lets mark our new encode as 1 or "Encoding" */
2598 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2599 [self saveQueueFileItem];
2600 /* We should be all setup so let 'er rip */
2605 #pragma mark Live Preview
2606 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2607 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2610 - (void) prepareJobForPreview
2612 hb_list_t * list = hb_get_titles( fHandle );
2613 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2614 [fSrcTitlePopUp indexOfSelectedItem] );
2615 hb_job_t * job = title->job;
2616 hb_audio_config_t * audio;
2618 /* Chapter selection */
2619 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
2620 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
2622 /* Format (Muxer) and Video Encoder */
2623 job->mux = [[fDstFormatPopUp selectedItem] tag];
2624 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
2626 job->chapter_markers = 0;
2628 if( job->vcodec & HB_VCODEC_X264 )
2630 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2631 Currently only used with Constant Quality setting*/
2632 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
2637 /* Below Sends x264 options to the core library if x264 is selected*/
2638 /* Lets use this as per Nyx, Thanks Nyx!*/
2639 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2640 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
2641 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
2646 /* Video settings */
2647 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
2648 * and detelecine is on, so we handle that in the logic below
2651 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
2653 /* a specific framerate has been chosen */
2654 job->vrate = 27000000;
2655 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
2656 /* We are not same as source so we set job->cfr to 1
2657 * to enable constant frame rate since user has specified
2658 * a specific framerate*/
2663 /* We are same as source (variable) */
2664 job->vrate = title->rate;
2665 job->vrate_base = title->rate_base;
2666 /* We are same as source so we set job->cfr to 0
2667 * to enable true same as source framerate */
2669 /* If we are same as source and we have detelecine on, we need to turn on
2672 if ([fPictureFilterController detelecine] == 1)
2678 switch( [fVidQualityMatrix selectedRow] )
2682 Bitrate should already have been calculated and displayed
2683 in fVidBitrateField, so let's just use it */
2685 job->vquality = -1.0;
2686 job->vbitrate = [fVidBitrateField intValue];
2689 job->vquality = [fVidQualityRFField floatValue];
2694 /* Subtitle settings */
2695 job->subtitle = [fSubPopUp indexOfSelectedItem] - 2;
2697 /* Audio tracks and mixdowns */
2698 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
2699 int audiotrack_count = hb_list_count(job->list_audio);
2700 for( int i = 0; i < audiotrack_count;i++)
2702 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
2703 hb_list_rem(job->list_audio, temp_audio);
2705 /* Now lets add our new tracks to the audio list here */
2706 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2708 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2709 hb_audio_config_init(audio);
2710 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2711 /* We go ahead and assign values to our audio->out.<properties> */
2712 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2713 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
2714 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
2715 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
2716 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
2717 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
2719 hb_audio_add( job, audio );
2722 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2724 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2725 hb_audio_config_init(audio);
2726 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2727 /* We go ahead and assign values to our audio->out.<properties> */
2728 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2729 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
2730 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
2731 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
2732 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
2733 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
2735 hb_audio_add( job, audio );
2740 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2742 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2743 hb_audio_config_init(audio);
2744 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2745 /* We go ahead and assign values to our audio->out.<properties> */
2746 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2747 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
2748 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
2749 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
2750 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
2751 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
2753 hb_audio_add( job, audio );
2758 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2760 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2761 hb_audio_config_init(audio);
2762 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2763 /* We go ahead and assign values to our audio->out.<properties> */
2764 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2765 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
2766 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
2767 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
2768 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
2769 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
2771 hb_audio_add( job, audio );
2780 /* Though Grayscale is not really a filter, per se
2781 * we put it here since its in the filters panel
2784 if ([fPictureFilterController grayscale])
2793 /* Initialize the filters list */
2794 job->filters = hb_list_init();
2796 /* Now lets call the filters if applicable.
2797 * The order of the filters is critical
2801 if ([fPictureFilterController detelecine] == 1)
2803 hb_list_add( job->filters, &hb_filter_detelecine );
2805 if ([fPictureFilterController detelecine] == 2)
2807 /* use a custom detelecine string */
2808 hb_filter_detelecine.settings = (char *) [[fPictureFilterController detelecineCustomString] UTF8String];
2809 hb_list_add( job->filters, &hb_filter_detelecine );
2811 if ([fPictureFilterController useDecomb] == 1)
2814 if ([fPictureFilterController decomb] == 1)
2816 /* Run old deinterlacer fd by default */
2817 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
2818 hb_list_add( job->filters, &hb_filter_decomb );
2820 /* we add the custom string if present */
2821 if ([fPictureFilterController decomb] == 2)
2823 /* use a custom decomb string */
2824 hb_filter_decomb.settings = (char *) [[fPictureFilterController decombCustomString] UTF8String];
2825 hb_list_add( job->filters, &hb_filter_decomb );
2832 if ([fPictureFilterController deinterlace] == 1)
2834 /* Run old deinterlacer fd by default */
2835 hb_filter_deinterlace.settings = "-1";
2836 hb_list_add( job->filters, &hb_filter_deinterlace );
2838 else if ([fPictureFilterController deinterlace] == 2)
2840 /* Yadif mode 0 (without spatial deinterlacing.) */
2841 hb_filter_deinterlace.settings = "2";
2842 hb_list_add( job->filters, &hb_filter_deinterlace );
2844 else if ([fPictureFilterController deinterlace] == 3)
2846 /* Yadif (with spatial deinterlacing) */
2847 hb_filter_deinterlace.settings = "0";
2848 hb_list_add( job->filters, &hb_filter_deinterlace );
2850 else if ([fPictureFilterController deinterlace] == 4)
2852 /* we add the custom string if present */
2853 hb_filter_deinterlace.settings = (char *) [[fPictureFilterController deinterlaceCustomString] UTF8String];
2854 hb_list_add( job->filters, &hb_filter_deinterlace );
2859 if ([fPictureFilterController denoise] == 1) // Weak in popup
2861 hb_filter_denoise.settings = "2:1:2:3";
2862 hb_list_add( job->filters, &hb_filter_denoise );
2864 else if ([fPictureFilterController denoise] == 2) // Medium in popup
2866 hb_filter_denoise.settings = "3:2:2:3";
2867 hb_list_add( job->filters, &hb_filter_denoise );
2869 else if ([fPictureFilterController denoise] == 3) // Strong in popup
2871 hb_filter_denoise.settings = "7:7:5:5";
2872 hb_list_add( job->filters, &hb_filter_denoise );
2874 else if ([fPictureFilterController denoise] == 4) // custom in popup
2876 /* we add the custom string if present */
2877 hb_filter_denoise.settings = (char *) [[fPictureFilterController denoiseCustomString] UTF8String];
2878 hb_list_add( job->filters, &hb_filter_denoise );
2881 /* Deblock (uses pp7 default) */
2882 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
2883 * the macgui's purposes a value of 0 actually means to not even use the filter
2884 * current hb_filter_deblock.settings valid ranges are from 5 - 15
2886 if ([fPictureFilterController deblock] != 0)
2888 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureFilterController deblock]];
2889 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
2890 hb_list_add( job->filters, &hb_filter_deblock );
2897 #pragma mark Job Handling
2903 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2904 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2905 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2906 hb_job_t * job = title->job;
2907 hb_audio_config_t * audio;
2908 /* Chapter selection */
2909 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
2910 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
2912 /* Format (Muxer) and Video Encoder */
2913 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
2914 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
2917 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
2918 //if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
2920 /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
2921 mpeg4 and the checkbox being checked
2922 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
2923 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
2925 job->largeFileSize = 1;
2929 job->largeFileSize = 0;
2931 /* We set http optimized mp4 here */
2932 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
2934 job->mp4_optimize = 1;
2938 job->mp4_optimize = 0;
2943 /* We set the chapter marker extraction here based on the format being
2944 mpeg4 or mkv and the checkbox being checked */
2945 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
2947 job->chapter_markers = 1;
2949 /* now lets get our saved chapter names out the array in the queue file
2950 * and insert them back into the title chapter list. We have it here,
2951 * because unless we are inserting chapter markers there is no need to
2952 * spend the overhead of iterating through the chapter names array imo
2953 * Also, note that if for some reason we don't apply chapter names, the
2954 * chapters just come out 001, 002, etc. etc.
2957 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
2959 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
2961 while (tempObject = [enumerator nextObject])
2963 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
2964 if( chapter != NULL )
2966 strncpy( chapter->title, [tempObject UTF8String], 1023);
2967 chapter->title[1023] = '\0';
2974 job->chapter_markers = 0;
2977 if( job->vcodec & HB_VCODEC_X264 )
2979 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
2988 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2989 Currently only used with Constant Quality setting*/
2990 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2)
2994 /* Below Sends x264 options to the core library if x264 is selected*/
2995 /* Lets use this as per Nyx, Thanks Nyx!*/
2996 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2997 /* Turbo first pass if two pass and Turbo First pass is selected */
2998 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3000 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3001 NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3002 /* append the "Turbo" string variable to the existing opts string.
3003 Note: the "Turbo" string must be appended, not prepended to work properly*/
3004 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3005 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3009 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3015 /* Picture Size Settings */
3016 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3017 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3019 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3020 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3023 /* Here we use the crop values saved at the time the preset was saved */
3024 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3025 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3026 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3027 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3029 /* Video settings */
3032 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3033 * and detelecine is on, so we handle that in the logic below
3036 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3038 /* a specific framerate has been chosen */
3039 job->vrate = 27000000;
3040 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3041 /* We are not same as source so we set job->cfr to 1
3042 * to enable constant frame rate since user has specified
3043 * a specific framerate*/
3048 /* We are same as source (variable) */
3049 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3050 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3051 /* We are same as source so we set job->cfr to 0
3052 * to enable true same as source framerate */
3054 /* If we are same as source and we have detelecine on, we need to turn on
3057 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3063 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3066 Bitrate should already have been calculated and displayed
3067 in fVidBitrateField, so let's just use it same as abr*/
3068 job->vquality = -1.0;
3069 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3071 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3073 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3078 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3079 /* Subtitle settings */
3080 job->subtitle = [[queueToApply objectForKey:@"JobSubtitlesIndex"] intValue] - 2;
3082 /* Audio tracks and mixdowns */
3083 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3084 int audiotrack_count = hb_list_count(job->list_audio);
3085 for( int i = 0; i < audiotrack_count;i++)
3087 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3088 hb_list_rem(job->list_audio, temp_audio);
3090 /* Now lets add our new tracks to the audio list here */
3091 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3093 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3094 hb_audio_config_init(audio);
3095 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3096 /* We go ahead and assign values to our audio->out.<properties> */
3097 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3098 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3099 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3100 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3101 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3102 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3104 hb_audio_add( job, audio );
3107 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3110 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3111 hb_audio_config_init(audio);
3112 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3113 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3114 /* We go ahead and assign values to our audio->out.<properties> */
3115 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3116 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3117 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3118 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3119 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3120 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3122 hb_audio_add( job, audio );
3126 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3128 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3129 hb_audio_config_init(audio);
3130 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3131 /* We go ahead and assign values to our audio->out.<properties> */
3132 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3133 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3134 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3135 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3136 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3137 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3139 hb_audio_add( job, audio );
3143 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3145 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3146 hb_audio_config_init(audio);
3147 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3148 /* We go ahead and assign values to our audio->out.<properties> */
3149 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3150 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3151 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3152 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3153 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3154 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3156 hb_audio_add( job, audio );
3161 job->filters = hb_list_init();
3163 /* Now lets call the filters if applicable.
3164 * The order of the filters is critical
3167 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3169 //if ([queueToApply objectForKey:@"PictureDetelecineCustom"])
3170 hb_list_add( job->filters, &hb_filter_detelecine );
3172 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3174 /* use a custom detelecine string */
3175 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3176 hb_list_add( job->filters, &hb_filter_detelecine );
3179 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3182 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3184 /* Run old deinterlacer fd by default */
3185 hb_list_add( job->filters, &hb_filter_decomb );
3187 /* we add the custom string if present */
3188 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3190 /* use a custom decomb string */
3191 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3192 hb_list_add( job->filters, &hb_filter_decomb );
3200 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3202 /* Run old deinterlacer fd by default */
3203 hb_filter_deinterlace.settings = "-1";
3204 hb_list_add( job->filters, &hb_filter_deinterlace );
3206 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3208 /* Yadif mode 0 (without spatial deinterlacing.) */
3209 hb_filter_deinterlace.settings = "2";
3210 hb_list_add( job->filters, &hb_filter_deinterlace );
3212 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3214 /* Yadif (with spatial deinterlacing) */
3215 hb_filter_deinterlace.settings = "0";
3216 hb_list_add( job->filters, &hb_filter_deinterlace );
3218 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3220 /* we add the custom string if present */
3221 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3222 hb_list_add( job->filters, &hb_filter_deinterlace );
3228 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Weak in popup
3230 hb_filter_denoise.settings = "2:1:2:3";
3231 hb_list_add( job->filters, &hb_filter_denoise );
3233 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Medium in popup
3235 hb_filter_denoise.settings = "3:2:2:3";
3236 hb_list_add( job->filters, &hb_filter_denoise );
3238 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Strong in popup
3240 hb_filter_denoise.settings = "7:7:5:5";
3241 hb_list_add( job->filters, &hb_filter_denoise );
3243 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Custom in popup
3245 /* we add the custom string if present */
3246 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3247 hb_list_add( job->filters, &hb_filter_denoise );
3250 /* Deblock (uses pp7 default) */
3251 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3252 * the macgui's purposes a value of 0 actually means to not even use the filter
3253 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3255 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3257 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3258 hb_list_add( job->filters, &hb_filter_deblock );
3260 [self writeToActivityLog: "prepareJob exiting"];
3265 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3267 - (IBAction) addToQueue: (id) sender
3269 /* We get the destination directory from the destination field here */
3270 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3271 /* We check for a valid destination here */
3272 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3274 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3281 BOOL fileExistsInQueue;
3282 fileExistsInQueue = NO;
3284 /* We check for and existing file here */
3285 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3290 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3292 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3294 while (tempObject = [enumerator nextObject])
3296 NSDictionary *thisQueueDict = tempObject;
3297 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3299 fileExistsInQueue = YES;
3305 if(fileExists == YES)
3307 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
3308 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3309 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3310 NULL, NULL, [NSString stringWithFormat:
3311 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3312 [fDstFile2Field stringValue]] );
3314 else if (fileExistsInQueue == YES)
3316 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
3317 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3318 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3319 NULL, NULL, [NSString stringWithFormat:
3320 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3321 [fDstFile2Field stringValue]] );
3325 [self doAddToQueue];
3329 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
3330 the user if they want to overwrite an exiting movie file.
3332 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
3333 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3335 if( returnCode == NSAlertAlternateReturn )
3336 [self doAddToQueue];
3339 - (void) doAddToQueue
3341 [self addQueueFileItem ];
3346 /* Rip: puts up an alert before ultimately calling doRip
3348 - (IBAction) Rip: (id) sender
3350 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
3351 /* Rip or Cancel ? */
3353 hb_get_state2( fQueueEncodeLibhb, &s );
3355 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
3357 [self Cancel: sender];
3361 /* We check to see if we need to warn the user that the computer will go to sleep
3362 or shut down when encoding is finished */
3363 [self remindUserOfSleepOrShutdown];
3365 // If there are pending jobs in the queue, then this is a rip the queue
3366 if (fPendingCount > 0)
3368 /* here lets start the queue with the first pending item */
3369 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3374 // Before adding jobs to the queue, check for a valid destination.
3376 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3377 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3379 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3383 /* We check for duplicate name here */
3384 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
3386 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
3387 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3388 @selector( overWriteAlertDone:returnCode:contextInfo: ),
3389 NULL, NULL, [NSString stringWithFormat:
3390 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3391 [fDstFile2Field stringValue]] );
3393 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
3397 /* if there are no pending jobs in the queue, then add this one to the queue and rip
3398 otherwise, just rip the queue */
3399 if(fPendingCount == 0)
3401 [self writeToActivityLog: "Rip: No pending jobs, so sending this one to doAddToQueue"];
3402 [self doAddToQueue];
3405 /* go right to processing the new queue encode */
3406 [self writeToActivityLog: "Rip: Going right to performNewQueueScan"];
3407 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3412 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
3413 want to overwrite an exiting movie file.
3415 - (void) overWriteAlertDone: (NSWindow *) sheet
3416 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3418 if( returnCode == NSAlertAlternateReturn )
3420 /* if there are no jobs in the queue, then add this one to the queue and rip
3421 otherwise, just rip the queue */
3422 if( fPendingCount == 0 )
3424 [self doAddToQueue];
3427 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3428 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
3429 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3434 - (void) remindUserOfSleepOrShutdown
3436 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
3438 /*Warn that computer will sleep after encoding*/
3441 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);
3442 [NSApp requestUserAttention:NSCriticalRequest];
3443 if ( reminduser == NSAlertAlternateReturn )
3445 [self showPreferencesWindow:nil];
3448 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
3450 /*Warn that computer will shut down after encoding*/
3453 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);
3454 [NSApp requestUserAttention:NSCriticalRequest];
3455 if ( reminduser == NSAlertAlternateReturn )
3457 [self showPreferencesWindow:nil];
3466 /* Let libhb do the job */
3467 hb_start( fQueueEncodeLibhb );
3468 /*set the fEncodeState State */
3473 //------------------------------------------------------------------------------------
3474 // Displays an alert asking user if the want to cancel encoding of current job.
3475 // Cancel: returns immediately after posting the alert. Later, when the user
3476 // acknowledges the alert, doCancelCurrentJob is called.
3477 //------------------------------------------------------------------------------------
3478 - (IBAction)Cancel: (id)sender
3480 if (!fQueueController) return;
3482 hb_pause( fQueueEncodeLibhb );
3483 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
3485 // Which window to attach the sheet to?
3486 NSWindow * docWindow;
3487 if ([sender respondsToSelector: @selector(window)])
3488 docWindow = [sender window];
3490 docWindow = fWindow;
3492 NSBeginCriticalAlertSheet(
3494 NSLocalizedString(@"Continue Encoding", nil),
3495 NSLocalizedString(@"Cancel Current and Stop", nil),
3496 NSLocalizedString(@"Cancel Current and Continue", nil),
3498 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
3499 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
3501 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
3504 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
3506 hb_resume( fQueueEncodeLibhb );
3507 if (returnCode == NSAlertOtherReturn)
3509 [self doCancelCurrentJob]; // <- this also stops libhb
3511 if (returnCode == NSAlertAlternateReturn)
3513 [self doCancelCurrentJobAndStop];
3517 //------------------------------------------------------------------------------------
3518 // Cancels and deletes the current job and stops libhb from processing the remaining
3520 //------------------------------------------------------------------------------------
3521 - (void) doCancelCurrentJob
3523 // Stop the current job. hb_stop will only cancel the current pass and then set
3524 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
3525 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
3526 // remaining passes of the job and then start the queue back up if there are any
3530 hb_stop( fQueueEncodeLibhb );
3532 // Delete all remaining jobs since libhb doesn't do this on its own.
3534 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3535 hb_rem( fQueueEncodeLibhb, job );
3537 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3539 // now that we've stopped the currently encoding job, lets mark it as cancelled
3540 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3541 // and as always, save it in the queue .plist...
3542 /* We save all of the Queue data here */
3543 [self saveQueueFileItem];
3544 // so now lets move to
3545 currentQueueEncodeIndex++ ;
3546 // ... and see if there are more items left in our queue
3547 int queueItems = [QueueFileArray count];
3548 /* If we still have more items in our queue, lets go to the next one */
3549 if (currentQueueEncodeIndex < queueItems)
3551 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
3552 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
3554 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3558 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
3563 - (void) doCancelCurrentJobAndStop
3565 hb_stop( fQueueEncodeLibhb );
3567 // Delete all remaining jobs since libhb doesn't do this on its own.
3569 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3570 hb_rem( fQueueEncodeLibhb, job );
3573 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3575 // now that we've stopped the currently encoding job, lets mark it as cancelled
3576 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3577 // and as always, save it in the queue .plist...
3578 /* We save all of the Queue data here */
3579 [self saveQueueFileItem];
3580 // so now lets move to
3581 currentQueueEncodeIndex++ ;
3582 [self writeToActivityLog: "cancelling current job and stopping the queue"];
3584 - (IBAction) Pause: (id) sender
3587 hb_get_state2( fQueueEncodeLibhb, &s );
3589 if( s.state == HB_STATE_PAUSED )
3591 hb_resume( fQueueEncodeLibhb );
3595 hb_pause( fQueueEncodeLibhb );
3600 #pragma mark GUI Controls Changed Methods
3602 - (IBAction) titlePopUpChanged: (id) sender
3604 hb_list_t * list = hb_get_titles( fHandle );
3605 hb_title_t * title = (hb_title_t*)
3606 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3608 /* If Auto Naming is on. We create an output filename of dvd name - title number */
3609 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
3611 [fDstFile2Field setStringValue: [NSString stringWithFormat:
3612 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
3613 [browsedSourceDisplayName stringByDeletingPathExtension],
3615 [[fDstFile2Field stringValue] pathExtension]]];
3618 /* Update chapter popups */
3619 [fSrcChapterStartPopUp removeAllItems];
3620 [fSrcChapterEndPopUp removeAllItems];
3621 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
3623 [fSrcChapterStartPopUp addItemWithTitle: [NSString
3624 stringWithFormat: @"%d", i + 1]];
3625 [fSrcChapterEndPopUp addItemWithTitle: [NSString
3626 stringWithFormat: @"%d", i + 1]];
3629 [fSrcChapterStartPopUp selectItemAtIndex: 0];
3630 [fSrcChapterEndPopUp selectItemAtIndex:
3631 hb_list_count( title->list_chapter ) - 1];
3632 [self chapterPopUpChanged:nil];
3634 /* Start Get and set the initial pic size for display */
3635 hb_job_t * job = title->job;
3638 /* Set Auto Crop to on upon selecting a new title */
3639 [fPictureController setAutoCrop:YES];
3641 /* We get the originial output picture width and height and put them
3642 in variables for use with some presets later on */
3643 PicOrigOutputWidth = job->width;
3644 PicOrigOutputHeight = job->height;
3645 AutoCropTop = job->crop[0];
3646 AutoCropBottom = job->crop[1];
3647 AutoCropLeft = job->crop[2];
3648 AutoCropRight = job->crop[3];
3650 /* Reset the new title in fPictureController && fPreviewController*/
3651 [fPictureController SetTitle:title];
3652 //[fPictureFilterController SetTitle:title];
3653 /* Update subtitle popups */
3654 hb_subtitle_t * subtitle;
3655 [fSubPopUp removeAllItems];
3656 [fSubPopUp addItemWithTitle: @"None"];
3657 [fSubPopUp addItemWithTitle: @"Autoselect"];
3658 for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
3660 subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
3662 /* We cannot use NSPopUpButton's addItemWithTitle because
3663 it checks for duplicate entries */
3664 [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
3665 subtitle->lang] action: NULL keyEquivalent: @""];
3667 [fSubPopUp selectItemAtIndex: 0];
3669 [self subtitleSelectionChanged:nil];
3671 /* Update chapter table */
3672 [fChapterTitlesDelegate resetWithTitle:title];
3673 [fChapterTable reloadData];
3675 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3676 int audiotrack_count = hb_list_count(job->list_audio);
3677 for( int i = 0; i < audiotrack_count;i++)
3679 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3680 hb_list_rem(job->list_audio, temp_audio);
3683 /* Update audio popups */
3684 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
3685 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
3686 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
3687 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
3688 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
3689 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
3690 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
3691 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3692 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3693 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3695 /* changing the title may have changed the audio channels on offer, */
3696 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3697 [self audioTrackPopUpChanged: fAudLang1PopUp];
3698 [self audioTrackPopUpChanged: fAudLang2PopUp];
3699 [self audioTrackPopUpChanged: fAudLang3PopUp];
3700 [self audioTrackPopUpChanged: fAudLang4PopUp];
3702 [fVidRatePopUp selectItemAtIndex: 0];
3704 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
3705 [self calculatePictureSizing:nil];
3707 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
3708 [self selectPreset:nil];
3711 - (IBAction) chapterPopUpChanged: (id) sender
3714 /* If start chapter popup is greater than end chapter popup,
3715 we set the end chapter popup to the same as start chapter popup */
3716 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
3718 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
3722 hb_list_t * list = hb_get_titles( fHandle );
3723 hb_title_t * title = (hb_title_t *)
3724 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3726 hb_chapter_t * chapter;
3727 int64_t duration = 0;
3728 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
3729 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
3731 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3732 duration += chapter->duration;
3735 duration /= 90000; /* pts -> seconds */
3736 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
3737 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
3740 [self calculateBitrate: sender];
3743 - (IBAction) formatPopUpChanged: (id) sender
3745 NSString * string = [fDstFile2Field stringValue];
3746 int format = [fDstFormatPopUp indexOfSelectedItem];
3748 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
3749 [fDstMp4LargeFileCheck setHidden: YES];
3750 [fDstMp4HttpOptFileCheck setHidden: YES];
3751 [fDstMp4iPodFileCheck setHidden: YES];
3753 /* Update the Video Codec PopUp */
3754 /* lets get the tag of the currently selected item first so we might reset it later */
3755 int selectedVidEncoderTag;
3756 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
3758 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
3759 [fVidEncoderPopUp removeAllItems];
3760 NSMenuItem *menuItem;
3761 /* These video encoders are available to all of our current muxers, so lets list them once here */
3762 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
3763 [menuItem setTag: HB_VCODEC_FFMPEG];
3765 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (XviD)" action: NULL keyEquivalent: @""];
3766 [menuItem setTag: HB_VCODEC_XVID];
3770 /*Get Default MP4 File Extension*/
3771 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
3779 /* Add additional video encoders here */
3780 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3781 [menuItem setTag: HB_VCODEC_X264];
3782 /* We show the mp4 option checkboxes here since we are mp4 */
3783 [fCreateChapterMarkers setEnabled: YES];
3784 [fDstMp4LargeFileCheck setHidden: NO];
3785 [fDstMp4HttpOptFileCheck setHidden: NO];
3786 [fDstMp4iPodFileCheck setHidden: NO];
3791 /* Add additional video encoders here */
3792 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3793 [menuItem setTag: HB_VCODEC_X264];
3794 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3795 [menuItem setTag: HB_VCODEC_THEORA];
3796 /* We enable the create chapters checkbox here */
3797 [fCreateChapterMarkers setEnabled: YES];
3802 /* Add additional video encoders here */
3803 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3804 [menuItem setTag: HB_VCODEC_X264];
3805 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3806 [fCreateChapterMarkers setEnabled: NO];
3807 [fCreateChapterMarkers setState: NSOffState];
3812 /* Add additional video encoders here */
3813 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3814 [menuItem setTag: HB_VCODEC_THEORA];
3815 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3816 [fCreateChapterMarkers setEnabled: NO];
3817 [fCreateChapterMarkers setState: NSOffState];
3820 /* if we have a previously selected vid encoder tag, then try to select it */
3821 if (selectedVidEncoderTag)
3823 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
3827 [fVidEncoderPopUp selectItemAtIndex: 0];
3830 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
3831 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
3832 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
3833 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
3836 [self autoSetM4vExtension: sender];
3838 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
3840 if( SuccessfulScan )
3842 /* Add/replace to the correct extension */
3843 [self audioTrackPopUpChanged: fAudLang1PopUp];
3844 [self audioTrackPopUpChanged: fAudLang2PopUp];
3845 [self audioTrackPopUpChanged: fAudLang3PopUp];
3846 [self audioTrackPopUpChanged: fAudLang4PopUp];
3848 if( [fVidEncoderPopUp selectedItem] == nil )
3851 [fVidEncoderPopUp selectItemAtIndex:0];
3852 [self videoEncoderPopUpChanged:nil];
3854 /* changing the format may mean that we can / can't offer mono or 6ch, */
3855 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3857 /* We call the method to properly enable/disable turbo 2 pass */
3858 [self twoPassCheckboxChanged: sender];
3859 /* We call method method to change UI to reflect whether a preset is used or not*/
3862 [self customSettingUsed: sender];
3865 - (IBAction) autoSetM4vExtension: (id) sender
3867 if ( [fDstFormatPopUp indexOfSelectedItem] )
3870 NSString * extension = @"mp4";
3872 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3873 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3874 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3875 [fCreateChapterMarkers state] == NSOnState ||
3876 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
3881 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
3884 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
3885 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
3888 /* Method to determine if we should change the UI
3889 To reflect whether or not a Preset is being used or if
3890 the user is using "Custom" settings by determining the sender*/
3891 - (IBAction) customSettingUsed: (id) sender
3893 if ([sender stringValue])
3895 /* Deselect the currently selected Preset if there is one*/
3896 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3897 /* Change UI to show "Custom" settings are being used */
3898 [fPresetSelectedDisplay setStringValue: @"Custom"];
3900 curUserPresetChosenNum = nil;
3902 [self calculateBitrate:nil];
3907 #pragma mark - Video
3909 - (IBAction) videoEncoderPopUpChanged: (id) sender
3911 hb_job_t * job = fTitle->job;
3912 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
3914 [fAdvancedOptions setHidden:YES];
3915 /* If we are using x264 then show the x264 advanced panel*/
3916 if (videoEncoder == HB_VCODEC_X264)
3918 [fAdvancedOptions setHidden:NO];
3919 [self autoSetM4vExtension: sender];
3922 /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
3923 is being used as it borks up loose anamorphic .
3924 For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
3925 to use the index itself but this is easier */
3926 if (videoEncoder == HB_VCODEC_FFMPEG)
3928 if (job->anamorphic.mode == 2)
3930 job->anamorphic.mode = 0;
3932 [fPictureController setAllowLooseAnamorphic:NO];
3933 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
3934 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
3935 anything other than MP4.
3937 [fDstMp4iPodFileCheck setEnabled: NO];
3938 [fDstMp4iPodFileCheck setState: NSOffState];
3942 [fPictureController setAllowLooseAnamorphic:YES];
3943 [fDstMp4iPodFileCheck setEnabled: YES];
3945 [self setupQualitySlider];
3946 [self calculatePictureSizing: sender];
3947 [self twoPassCheckboxChanged: sender];
3951 - (IBAction) twoPassCheckboxChanged: (id) sender
3953 /* check to see if x264 is chosen */
3954 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
3956 if( [fVidTwoPassCheck state] == NSOnState)
3958 [fVidTurboPassCheck setHidden: NO];
3962 [fVidTurboPassCheck setHidden: YES];
3963 [fVidTurboPassCheck setState: NSOffState];
3965 /* Make sure Two Pass is checked if Turbo is checked */
3966 if( [fVidTurboPassCheck state] == NSOnState)
3968 [fVidTwoPassCheck setState: NSOnState];
3973 [fVidTurboPassCheck setHidden: YES];
3974 [fVidTurboPassCheck setState: NSOffState];
3977 /* We call method method to change UI to reflect whether a preset is used or not*/
3978 [self customSettingUsed: sender];
3981 - (IBAction ) videoFrameRateChanged: (id) sender
3983 /* We call method method to calculatePictureSizing to error check detelecine*/
3984 [self calculatePictureSizing: sender];
3986 /* We call method method to change UI to reflect whether a preset is used or not*/
3987 [self customSettingUsed: sender];
3989 - (IBAction) videoMatrixChanged: (id) sender;
3991 bool target, bitrate, quality;
3993 target = bitrate = quality = false;
3994 if( [fVidQualityMatrix isEnabled] )
3996 switch( [fVidQualityMatrix selectedRow] )
4009 [fVidTargetSizeField setEnabled: target];
4010 [fVidBitrateField setEnabled: bitrate];
4011 [fVidQualitySlider setEnabled: quality];
4012 [fVidQualityRFField setEnabled: quality];
4013 [fVidQualityRFLabel setEnabled: quality];
4014 [fVidTwoPassCheck setEnabled: !quality &&
4015 [fVidQualityMatrix isEnabled]];
4018 [fVidTwoPassCheck setState: NSOffState];
4019 [fVidTurboPassCheck setHidden: YES];
4020 [fVidTurboPassCheck setState: NSOffState];
4023 [self qualitySliderChanged: sender];
4024 [self calculateBitrate: sender];
4025 [self customSettingUsed: sender];
4028 /* Use this method to setup the quality slider for cq/rf values depending on
4029 * the video encoder selected.
4031 - (void) setupQualitySlider
4033 /* Get the current slider maxValue to check for a change in slider scale later
4034 * so that we can choose a new similar value on the new slider scale */
4035 float previousMaxValue = [fVidQualitySlider maxValue];
4036 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4037 NSString * qpRFLabelString = @"QP:";
4039 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4041 [fVidQualitySlider setMinValue:0.0];
4042 [fVidQualitySlider setMaxValue:51.0];
4043 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4044 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4045 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4046 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0)
4048 qpRFLabelString = @"RF:";
4051 /* ffmpeg and xvid 1-31 */
4052 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG || [[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_XVID)
4054 [fVidQualitySlider setMinValue:1.0];
4055 [fVidQualitySlider setMaxValue:31.0];
4056 [fVidQualitySlider setNumberOfTickMarks:31];
4059 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4061 [fVidQualitySlider setMinValue:0.0];
4062 [fVidQualitySlider setMaxValue:63.0];
4063 [fVidQualitySlider setNumberOfTickMarks:64];
4065 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4067 /* check to see if we have changed slider scales */
4068 if (previousMaxValue != [fVidQualitySlider maxValue])
4070 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4071 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4072 [fVidQualitySlider setFloatValue:rf];
4075 [self qualitySliderChanged:nil];
4078 - (IBAction) qualitySliderChanged: (id) sender
4080 /* Our constant quality slider is in a range based
4081 * on each encoders qp/rf values. The range depends
4082 * on the encoder. Also, the range is inverse of quality
4083 * for all of the encoders *except* for theora
4084 * (ie. as the "quality" goes up, the cq or rf value
4085 * actually goes down). Since the IB sliders always set
4086 * their max value at the right end of the slider, we
4087 * will calculate the inverse, so as the slider floatValue
4088 * goes up, we will show the inverse in the rf field
4089 * so, the floatValue at the right for x264 would be 51
4090 * and our rf field needs to show 0 and vice versa.
4093 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4094 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4095 float sliderRfToPercent;
4096 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4098 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4099 sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4103 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4104 sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4106 [fVidConstantCell setTitle: [NSString stringWithFormat:
4107 NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
4109 [self customSettingUsed: sender];
4112 - (void) controlTextDidChange: (NSNotification *) notification
4114 [self calculateBitrate:nil];
4117 - (IBAction) calculateBitrate: (id) sender
4119 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4124 hb_list_t * list = hb_get_titles( fHandle );
4125 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4126 [fSrcTitlePopUp indexOfSelectedItem] );
4127 hb_job_t * job = title->job;
4128 hb_audio_config_t * audio;
4129 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4130 * Target Size Field, we also need the job info for the Muxer, the Chapters
4131 * as well as all of the audio track info.
4132 * This used to be accomplished by simply calling prepareJob here, however
4133 * since the resilient queue sets the queue array values instead of the job
4134 * values directly, we duplicate the old prepareJob code here for the variables
4137 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4138 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4139 job->mux = [[fDstFormatPopUp selectedItem] tag];
4141 /* Audio goes here */
4142 int audiotrack_count = hb_list_count(job->list_audio);
4143 for( int i = 0; i < audiotrack_count;i++)
4145 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4146 hb_list_rem(job->list_audio, temp_audio);
4148 /* Now we need our audio info here for each track if applicable */
4149 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4151 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4152 hb_audio_config_init(audio);
4153 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4154 /* We go ahead and assign values to our audio->out.<properties> */
4155 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4156 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4157 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4158 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4159 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4160 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4162 hb_audio_add( job, audio );
4165 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4167 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4168 hb_audio_config_init(audio);
4169 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4170 /* We go ahead and assign values to our audio->out.<properties> */
4171 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4172 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4173 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4174 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4175 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4176 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4178 hb_audio_add( job, audio );
4183 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4185 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4186 hb_audio_config_init(audio);
4187 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4188 /* We go ahead and assign values to our audio->out.<properties> */
4189 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4190 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
4191 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
4192 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
4193 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
4194 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
4196 hb_audio_add( job, audio );
4201 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4203 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4204 hb_audio_config_init(audio);
4205 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4206 /* We go ahead and assign values to our audio->out.<properties> */
4207 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4208 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
4209 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
4210 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
4211 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
4212 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
4214 hb_audio_add( job, audio );
4219 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
4223 #pragma mark - Picture
4225 /* lets set the picture size back to the max from right after title scan
4226 Lets use an IBAction here as down the road we could always use a checkbox
4227 in the gui to easily take the user back to max. Remember, the compiler
4228 resolves IBActions down to -(void) during compile anyway */
4229 - (IBAction) revertPictureSizeToMax: (id) sender
4231 hb_job_t * job = fTitle->job;
4232 /* Here we apply the title source and height */
4233 job->width = fTitle->width;
4234 job->height = fTitle->height;
4236 [self calculatePictureSizing: sender];
4237 /* We call method to change UI to reflect whether a preset is used or not*/
4238 [self customSettingUsed: sender];
4242 * Registers changes made in the Picture Settings Window.
4245 - (void)pictureSettingsDidChange
4247 [self calculatePictureSizing:nil];
4250 /* Get and Display Current Pic Settings in main window */
4251 - (IBAction) calculatePictureSizing: (id) sender
4253 if (fTitle->job->anamorphic.mode > 0)
4255 fTitle->job->keep_ratio = 0;
4258 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
4260 NSString *picCropping;
4261 /* Set the display field for crop as per boolean */
4262 if (![fPictureController autoCrop])
4264 picCropping = @"Custom";
4268 picCropping = @"Auto";
4270 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]]];
4272 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
4274 NSString *videoFilters;
4277 if ([fPictureFilterController detelecine] == 1)
4279 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
4281 else if ([fPictureFilterController detelecine] == 2)
4283 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureFilterController detelecineCustomString]]];
4287 if ([fPictureFilterController useDecomb] == 1)
4290 if ([fPictureFilterController decomb] == 1)
4292 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
4294 else if ([fPictureFilterController decomb] == 2)
4296 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureFilterController decombCustomString]]];
4302 if ([fPictureFilterController deinterlace] > 0)
4304 fTitle->job->deinterlace = 1;
4308 fTitle->job->deinterlace = 0;
4311 if ([fPictureFilterController deinterlace] == 1)
4313 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
4315 else if ([fPictureFilterController deinterlace] == 2)
4317 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
4319 else if ([fPictureFilterController deinterlace] == 3)
4321 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
4323 else if ([fPictureFilterController deinterlace] == 4)
4325 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureFilterController deinterlaceCustomString]]];
4331 if ([fPictureFilterController denoise] == 1)
4333 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
4335 else if ([fPictureFilterController denoise] == 2)
4337 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
4339 else if ([fPictureFilterController denoise] == 3)
4341 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
4343 else if ([fPictureFilterController denoise] == 4)
4345 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureFilterController denoiseCustomString]]];
4349 if ([fPictureFilterController deblock] > 0)
4351 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureFilterController deblock]]];
4355 if ([fPictureFilterController grayscale])
4357 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
4359 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
4361 [fPictureController reloadStillPreview];
4366 #pragma mark - Audio and Subtitles
4367 - (IBAction) audioCodecsPopUpChanged: (id) sender
4370 NSPopUpButton * audiotrackPopUp;
4371 NSPopUpButton * sampleratePopUp;
4372 NSPopUpButton * bitratePopUp;
4373 NSPopUpButton * audiocodecPopUp;
4374 if (sender == fAudTrack1CodecPopUp)
4376 audiotrackPopUp = fAudLang1PopUp;
4377 audiocodecPopUp = fAudTrack1CodecPopUp;
4378 sampleratePopUp = fAudTrack1RatePopUp;
4379 bitratePopUp = fAudTrack1BitratePopUp;
4381 else if (sender == fAudTrack2CodecPopUp)
4383 audiotrackPopUp = fAudLang2PopUp;
4384 audiocodecPopUp = fAudTrack2CodecPopUp;
4385 sampleratePopUp = fAudTrack2RatePopUp;
4386 bitratePopUp = fAudTrack2BitratePopUp;
4388 else if (sender == fAudTrack3CodecPopUp)
4390 audiotrackPopUp = fAudLang3PopUp;
4391 audiocodecPopUp = fAudTrack3CodecPopUp;
4392 sampleratePopUp = fAudTrack3RatePopUp;
4393 bitratePopUp = fAudTrack3BitratePopUp;
4397 audiotrackPopUp = fAudLang4PopUp;
4398 audiocodecPopUp = fAudTrack4CodecPopUp;
4399 sampleratePopUp = fAudTrack4RatePopUp;
4400 bitratePopUp = fAudTrack4BitratePopUp;
4403 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
4404 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4405 [self audioTrackPopUpChanged: audiotrackPopUp];
4409 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
4411 /* We will be setting the enabled/disabled state of each tracks audio controls based on
4412 * the settings of the source audio for that track. We leave the samplerate and bitrate
4413 * to audiotrackMixdownChanged
4416 /* We will first verify that a lower track number has been selected before enabling each track
4417 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
4419 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4421 [fAudLang2PopUp setEnabled: NO];
4422 [fAudLang2PopUp selectItemAtIndex: 0];
4426 [fAudLang2PopUp setEnabled: YES];
4429 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4431 [fAudLang3PopUp setEnabled: NO];
4432 [fAudLang3PopUp selectItemAtIndex: 0];
4436 [fAudLang3PopUp setEnabled: YES];
4438 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4440 [fAudLang4PopUp setEnabled: NO];
4441 [fAudLang4PopUp selectItemAtIndex: 0];
4445 [fAudLang4PopUp setEnabled: YES];
4447 /* enable/disable the mixdown text and popupbutton for audio track 1 */
4448 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4449 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4450 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4451 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4452 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4453 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4454 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4456 [fAudTrack1CodecPopUp removeAllItems];
4457 [fAudTrack1MixPopUp removeAllItems];
4458 [fAudTrack1RatePopUp removeAllItems];
4459 [fAudTrack1BitratePopUp removeAllItems];
4460 [fAudTrack1DrcSlider setFloatValue: 1.00];
4461 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4463 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4465 [fAudTrack1RatePopUp setEnabled: NO];
4466 [fAudTrack1BitratePopUp setEnabled: NO];
4467 [fAudTrack1DrcSlider setEnabled: NO];
4468 [fAudTrack1DrcField setEnabled: NO];
4471 /* enable/disable the mixdown text and popupbutton for audio track 2 */
4472 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4473 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4474 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4475 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4476 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4477 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4478 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4480 [fAudTrack2CodecPopUp removeAllItems];
4481 [fAudTrack2MixPopUp removeAllItems];
4482 [fAudTrack2RatePopUp removeAllItems];
4483 [fAudTrack2BitratePopUp removeAllItems];
4484 [fAudTrack2DrcSlider setFloatValue: 1.00];
4485 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
4487 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4489 [fAudTrack2RatePopUp setEnabled: NO];
4490 [fAudTrack2BitratePopUp setEnabled: NO];
4491 [fAudTrack2DrcSlider setEnabled: NO];
4492 [fAudTrack2DrcField setEnabled: NO];
4495 /* enable/disable the mixdown text and popupbutton for audio track 3 */
4496 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4497 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4498 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4499 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4500 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4501 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4502 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4504 [fAudTrack3CodecPopUp removeAllItems];
4505 [fAudTrack3MixPopUp removeAllItems];
4506 [fAudTrack3RatePopUp removeAllItems];
4507 [fAudTrack3BitratePopUp removeAllItems];
4508 [fAudTrack3DrcSlider setFloatValue: 1.00];
4509 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
4511 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4513 [fAudTrack3RatePopUp setEnabled: NO];
4514 [fAudTrack3BitratePopUp setEnabled: NO];
4515 [fAudTrack3DrcSlider setEnabled: NO];
4516 [fAudTrack3DrcField setEnabled: NO];
4519 /* enable/disable the mixdown text and popupbutton for audio track 4 */
4520 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4521 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4522 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4523 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4524 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4525 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4526 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
4528 [fAudTrack4CodecPopUp removeAllItems];
4529 [fAudTrack4MixPopUp removeAllItems];
4530 [fAudTrack4RatePopUp removeAllItems];
4531 [fAudTrack4BitratePopUp removeAllItems];
4532 [fAudTrack4DrcSlider setFloatValue: 1.00];
4533 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
4535 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4537 [fAudTrack4RatePopUp setEnabled: NO];
4538 [fAudTrack4BitratePopUp setEnabled: NO];
4539 [fAudTrack4DrcSlider setEnabled: NO];
4540 [fAudTrack4DrcField setEnabled: NO];
4545 - (IBAction) addAllAudioTracksToPopUp: (id) sender
4548 hb_list_t * list = hb_get_titles( fHandle );
4549 hb_title_t * title = (hb_title_t*)
4550 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4552 hb_audio_config_t * audio;
4554 [sender removeAllItems];
4555 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
4556 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
4558 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
4559 [[sender menu] addItemWithTitle:
4560 [NSString stringWithCString: audio->lang.description]
4561 action: NULL keyEquivalent: @""];
4563 [sender selectItemAtIndex: 0];
4567 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
4570 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
4571 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
4572 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
4573 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
4575 if (searchPrefixString)
4578 for( int i = 0; i < [sender numberOfItems]; i++ )
4580 /* Try to find the desired search string */
4581 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
4583 [sender selectItemAtIndex: i];
4587 /* couldn't find the string, so select the requested "search string not found" item */
4588 /* index of 0 means select the "none" item */
4589 /* index of 1 means select the first audio track */
4590 [sender selectItemAtIndex: selectIndexIfNotFound];
4594 /* if no search string is provided, then select the selectIndexIfNotFound item */
4595 [sender selectItemAtIndex: selectIndexIfNotFound];
4599 - (IBAction) audioAddAudioTrackCodecs: (id)sender
4601 int format = [fDstFormatPopUp indexOfSelectedItem];
4603 /* setup pointers to the appropriate popups for the correct track */
4604 NSPopUpButton * audiocodecPopUp;
4605 NSPopUpButton * audiotrackPopUp;
4606 if (sender == fAudTrack1CodecPopUp)
4608 audiotrackPopUp = fAudLang1PopUp;
4609 audiocodecPopUp = fAudTrack1CodecPopUp;
4611 else if (sender == fAudTrack2CodecPopUp)
4613 audiotrackPopUp = fAudLang2PopUp;
4614 audiocodecPopUp = fAudTrack2CodecPopUp;
4616 else if (sender == fAudTrack3CodecPopUp)
4618 audiotrackPopUp = fAudLang3PopUp;
4619 audiocodecPopUp = fAudTrack3CodecPopUp;
4623 audiotrackPopUp = fAudLang4PopUp;
4624 audiocodecPopUp = fAudTrack4CodecPopUp;
4627 [audiocodecPopUp removeAllItems];
4628 /* Make sure "None" isnt selected in the source track */
4629 if ([audiotrackPopUp indexOfSelectedItem] > 0)
4631 [audiocodecPopUp setEnabled:YES];
4632 NSMenuItem *menuItem;
4633 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
4639 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4640 [menuItem setTag: HB_ACODEC_FAAC];
4643 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4644 [menuItem setTag: HB_ACODEC_AC3];
4650 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4651 [menuItem setTag: HB_ACODEC_FAAC];
4653 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4654 [menuItem setTag: HB_ACODEC_AC3];
4656 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4657 [menuItem setTag: HB_ACODEC_LAME];
4659 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4660 [menuItem setTag: HB_ACODEC_VORBIS];
4666 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4667 [menuItem setTag: HB_ACODEC_LAME];
4669 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4670 [menuItem setTag: HB_ACODEC_AC3];
4676 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4677 [menuItem setTag: HB_ACODEC_VORBIS];
4679 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4680 [menuItem setTag: HB_ACODEC_LAME];
4683 [audiocodecPopUp selectItemAtIndex:0];
4687 [audiocodecPopUp setEnabled:NO];
4691 - (IBAction) audioTrackPopUpChanged: (id) sender
4693 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
4694 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
4697 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
4700 /* make sure we have a selected title before continuing */
4701 if (fTitle == NULL) return;
4702 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
4703 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
4705 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
4707 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4709 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
4711 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4713 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
4715 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4717 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
4719 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4722 /* Now lets make the sender the appropriate Audio Track popup from this point on */
4723 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
4725 sender = fAudLang1PopUp;
4727 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
4729 sender = fAudLang2PopUp;
4731 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
4733 sender = fAudLang3PopUp;
4735 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
4737 sender = fAudLang4PopUp;
4740 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
4741 NSPopUpButton * mixdownPopUp;
4742 NSPopUpButton * audiocodecPopUp;
4743 NSPopUpButton * sampleratePopUp;
4744 NSPopUpButton * bitratePopUp;
4745 if (sender == fAudLang1PopUp)
4747 mixdownPopUp = fAudTrack1MixPopUp;
4748 audiocodecPopUp = fAudTrack1CodecPopUp;
4749 sampleratePopUp = fAudTrack1RatePopUp;
4750 bitratePopUp = fAudTrack1BitratePopUp;
4752 else if (sender == fAudLang2PopUp)
4754 mixdownPopUp = fAudTrack2MixPopUp;
4755 audiocodecPopUp = fAudTrack2CodecPopUp;
4756 sampleratePopUp = fAudTrack2RatePopUp;
4757 bitratePopUp = fAudTrack2BitratePopUp;
4759 else if (sender == fAudLang3PopUp)
4761 mixdownPopUp = fAudTrack3MixPopUp;
4762 audiocodecPopUp = fAudTrack3CodecPopUp;
4763 sampleratePopUp = fAudTrack3RatePopUp;
4764 bitratePopUp = fAudTrack3BitratePopUp;
4768 mixdownPopUp = fAudTrack4MixPopUp;
4769 audiocodecPopUp = fAudTrack4CodecPopUp;
4770 sampleratePopUp = fAudTrack4RatePopUp;
4771 bitratePopUp = fAudTrack4BitratePopUp;
4774 /* get the index of the selected audio Track*/
4775 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
4777 /* pointer for the hb_audio_s struct we will use later on */
4778 hb_audio_config_t * audio;
4781 /* check if the audio mixdown controls need their enabled state changing */
4782 [self setEnabledStateOfAudioMixdownControls:nil];
4784 if (thisAudioIndex != -1)
4788 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
4790 /* actually manipulate the proper mixdowns here */
4791 /* delete the previous audio mixdown options */
4792 [mixdownPopUp removeAllItems];
4794 acodec = [[audiocodecPopUp selectedItem] tag];
4799 /* find out if our selected output audio codec supports mono and / or 6ch */
4800 /* we also check for an input codec of AC3 or DCA,
4801 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
4802 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
4803 but this may change in the future, so they are separated for flexibility */
4804 int audioCodecsSupportMono =
4805 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4806 (acodec != HB_ACODEC_LAME);
4807 int audioCodecsSupport6Ch =
4808 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4809 (acodec != HB_ACODEC_LAME);
4811 /* check for AC-3 passthru */
4812 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4815 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4816 [NSString stringWithCString: "AC3 Passthru"]
4817 action: NULL keyEquivalent: @""];
4818 [menuItem setTag: HB_ACODEC_AC3];
4823 /* add the appropriate audio mixdown menuitems to the popupbutton */
4824 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
4825 so that we can reference the mixdown later */
4827 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
4828 int minMixdownUsed = 0;
4829 int maxMixdownUsed = 0;
4831 /* get the input channel layout without any lfe channels */
4832 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4834 /* do we want to add a mono option? */
4835 if (audioCodecsSupportMono == 1)
4837 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4838 [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
4839 action: NULL keyEquivalent: @""];
4840 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
4841 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
4842 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
4845 /* do we want to add a stereo option? */
4846 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
4847 /* also offer stereo if we have a stereo-or-better source */
4848 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
4850 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4851 [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
4852 action: NULL keyEquivalent: @""];
4853 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
4854 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
4855 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
4858 /* do we want to add a dolby surround (DPL1) option? */
4859 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
4861 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4862 [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
4863 action: NULL keyEquivalent: @""];
4864 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
4865 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
4866 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
4869 /* do we want to add a dolby pro logic 2 (DPL2) option? */
4870 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
4872 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4873 [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
4874 action: NULL keyEquivalent: @""];
4875 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
4876 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
4877 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
4880 /* do we want to add a 6-channel discrete option? */
4881 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
4883 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4884 [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
4885 action: NULL keyEquivalent: @""];
4886 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
4887 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
4888 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
4891 /* do we want to add an AC-3 passthrough option? */
4892 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4894 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4895 [NSString stringWithCString: hb_audio_mixdowns[5].human_readable_name]
4896 action: NULL keyEquivalent: @""];
4897 [menuItem setTag: HB_ACODEC_AC3];
4898 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
4899 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
4902 /* auto-select the best mixdown based on our saved mixdown preference */
4904 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
4905 /* ultimately this should be a prefs option */
4908 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
4909 if (mixdownToUse > 0)
4911 useMixdown = mixdownToUse;
4915 useMixdown = HB_AMIXDOWN_DOLBYPLII;
4918 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
4919 if (useMixdown > maxMixdownUsed)
4921 useMixdown = maxMixdownUsed;
4924 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
4925 if (useMixdown < minMixdownUsed)
4927 useMixdown = minMixdownUsed;
4930 /* select the (possibly-amended) preferred mixdown */
4931 [mixdownPopUp selectItemWithTag: useMixdown];
4934 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
4935 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
4938 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
4940 /* If we are using the avi container, we select MP3 as there is no aac available*/
4941 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
4943 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
4947 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
4950 /* Setup our samplerate and bitrate popups we will need based on mixdown */
4951 [self audioTrackMixdownChanged: mixdownPopUp];
4955 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
4957 [self autoSetM4vExtension: sender];
4961 - (IBAction) audioTrackMixdownChanged: (id) sender
4965 /* setup pointers to all of the other audio track controls
4966 * we will need later
4968 NSPopUpButton * mixdownPopUp;
4969 NSPopUpButton * sampleratePopUp;
4970 NSPopUpButton * bitratePopUp;
4971 NSPopUpButton * audiocodecPopUp;
4972 NSPopUpButton * audiotrackPopUp;
4973 NSSlider * drcSlider;
4974 NSTextField * drcField;
4975 if (sender == fAudTrack1MixPopUp)
4977 audiotrackPopUp = fAudLang1PopUp;
4978 audiocodecPopUp = fAudTrack1CodecPopUp;
4979 mixdownPopUp = fAudTrack1MixPopUp;
4980 sampleratePopUp = fAudTrack1RatePopUp;
4981 bitratePopUp = fAudTrack1BitratePopUp;
4982 drcSlider = fAudTrack1DrcSlider;
4983 drcField = fAudTrack1DrcField;
4985 else if (sender == fAudTrack2MixPopUp)
4987 audiotrackPopUp = fAudLang2PopUp;
4988 audiocodecPopUp = fAudTrack2CodecPopUp;
4989 mixdownPopUp = fAudTrack2MixPopUp;
4990 sampleratePopUp = fAudTrack2RatePopUp;
4991 bitratePopUp = fAudTrack2BitratePopUp;
4992 drcSlider = fAudTrack2DrcSlider;
4993 drcField = fAudTrack2DrcField;
4995 else if (sender == fAudTrack3MixPopUp)
4997 audiotrackPopUp = fAudLang3PopUp;
4998 audiocodecPopUp = fAudTrack3CodecPopUp;
4999 mixdownPopUp = fAudTrack3MixPopUp;
5000 sampleratePopUp = fAudTrack3RatePopUp;
5001 bitratePopUp = fAudTrack3BitratePopUp;
5002 drcSlider = fAudTrack3DrcSlider;
5003 drcField = fAudTrack3DrcField;
5007 audiotrackPopUp = fAudLang4PopUp;
5008 audiocodecPopUp = fAudTrack4CodecPopUp;
5009 mixdownPopUp = fAudTrack4MixPopUp;
5010 sampleratePopUp = fAudTrack4RatePopUp;
5011 bitratePopUp = fAudTrack4BitratePopUp;
5012 drcSlider = fAudTrack4DrcSlider;
5013 drcField = fAudTrack4DrcField;
5015 acodec = [[audiocodecPopUp selectedItem] tag];
5016 /* storage variable for the min and max bitrate allowed for this codec */
5022 case HB_ACODEC_FAAC:
5023 /* check if we have a 6ch discrete conversion in either audio track */
5024 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5026 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
5028 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5034 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5036 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5037 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5042 case HB_ACODEC_LAME:
5043 /* Lame is happy using our min bitrate of 32 kbps */
5045 /* Lame won't encode if the bitrate is higher than 320 kbps */
5049 case HB_ACODEC_VORBIS:
5050 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5052 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5054 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5060 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5062 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5068 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5074 /* make sure we have a selected title before continuing */
5075 if (fTitle == NULL) return;
5076 /* get the audio so we can find out what input rates are*/
5077 hb_audio_config_t * audio;
5078 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5079 int inputbitrate = audio->in.bitrate / 1000;
5080 int inputsamplerate = audio->in.samplerate;
5082 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3)
5084 [bitratePopUp removeAllItems];
5086 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5088 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5090 /* add a new menuitem for this bitrate */
5091 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5092 [NSString stringWithCString: hb_audio_bitrates[i].string]
5093 action: NULL keyEquivalent: @""];
5094 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5095 [menuItem setTag: hb_audio_bitrates[i].rate];
5099 /* select the default bitrate (but use 384 for 6-ch AAC) */
5100 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5102 [bitratePopUp selectItemWithTag: 384];
5106 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5109 /* populate and set the sample rate popup */
5110 /* Audio samplerate */
5111 [sampleratePopUp removeAllItems];
5112 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5113 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5114 [menuItem setTag: inputsamplerate];
5116 for( int i = 0; i < hb_audio_rates_count; i++ )
5118 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5119 [NSString stringWithCString: hb_audio_rates[i].string]
5120 action: NULL keyEquivalent: @""];
5121 [menuItem setTag: hb_audio_rates[i].rate];
5123 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5124 * and there is no compelling reason to use anything else as default, though the users default
5125 * preset will likely override any setting chosen here.
5127 [sampleratePopUp selectItemWithTag: inputsamplerate];
5130 /* Since AC3 Pass Thru uses the input ac3 bitrate and sample rate, we get the input tracks
5131 * bitrate and dispay it in the bitrate popup even though libhb happily ignores any bitrate input from
5132 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
5134 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3)
5137 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
5138 [bitratePopUp removeAllItems];
5139 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5140 [NSString stringWithFormat:@"%d", inputbitrate]
5141 action: NULL keyEquivalent: @""];
5142 [menuItem setTag: inputbitrate];
5143 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
5144 [bitratePopUp setEnabled: NO];
5145 [sampleratePopUp setEnabled: NO];
5147 [drcSlider setFloatValue: 1.00];
5148 [self audioDRCSliderChanged: drcSlider];
5149 [drcSlider setEnabled: NO];
5150 [drcField setEnabled: NO];
5154 [sampleratePopUp setEnabled: YES];
5155 [bitratePopUp setEnabled: YES];
5156 [drcSlider setEnabled: YES];
5157 [drcField setEnabled: YES];
5159 [self calculateBitrate:nil];
5162 - (IBAction) audioDRCSliderChanged: (id) sender
5164 NSSlider * drcSlider;
5165 NSTextField * drcField;
5166 if (sender == fAudTrack1DrcSlider)
5168 drcSlider = fAudTrack1DrcSlider;
5169 drcField = fAudTrack1DrcField;
5171 else if (sender == fAudTrack2DrcSlider)
5173 drcSlider = fAudTrack2DrcSlider;
5174 drcField = fAudTrack2DrcField;
5176 else if (sender == fAudTrack3DrcSlider)
5178 drcSlider = fAudTrack3DrcSlider;
5179 drcField = fAudTrack3DrcField;
5183 drcSlider = fAudTrack4DrcSlider;
5184 drcField = fAudTrack4DrcField;
5187 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
5188 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
5190 [drcSlider setFloatValue:1.0];
5194 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
5195 /* For now, do not call this until we have an intelligent way to determine audio track selections
5196 * compared to presets
5198 //[self customSettingUsed: sender];
5201 - (IBAction) subtitleSelectionChanged: (id) sender
5203 if ([fSubPopUp indexOfSelectedItem] == 0)
5205 [fSubForcedCheck setState: NSOffState];
5206 [fSubForcedCheck setEnabled: NO];
5210 [fSubForcedCheck setEnabled: YES];
5219 #pragma mark Open New Windows
5221 - (IBAction) openHomepage: (id) sender
5223 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5224 URLWithString:@"http://handbrake.fr/"]];
5227 - (IBAction) openForums: (id) sender
5229 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5230 URLWithString:@"http://handbrake.fr/forum/"]];
5232 - (IBAction) openUserGuide: (id) sender
5234 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5235 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
5239 * Shows debug output window.
5241 - (IBAction)showDebugOutputPanel:(id)sender
5243 [outputPanel showOutputPanel:sender];
5247 * Shows preferences window.
5249 - (IBAction) showPreferencesWindow: (id) sender
5251 NSWindow * window = [fPreferencesController window];
5252 if (![window isVisible])
5255 [window makeKeyAndOrderFront: nil];
5259 * Shows queue window.
5261 - (IBAction) showQueueWindow:(id)sender
5263 [fQueueController showQueueWindow:sender];
5267 - (IBAction) toggleDrawer:(id)sender {
5268 [fPresetDrawer toggle:self];
5272 * Shows Picture Settings Window.
5275 - (IBAction) showPicturePanel: (id) sender
5277 [fPictureController showPictureWindow:sender];
5280 - (void) picturePanelFullScreen
5282 [fPictureController setToFullScreenMode];
5285 - (void) picturePanelWindowed
5287 [fPictureController setToWindowedMode];
5290 - (IBAction) showFiltersPanel: (id) sender
5292 [fPictureFilterController showFilterWindow:sender];
5295 - (IBAction) showPreviewWindow: (id) sender
5297 [fPictureController showPreviewWindow:sender];
5301 #pragma mark Preset Outline View Methods
5302 #pragma mark - Required
5303 /* These are required by the NSOutlineView Datasource Delegate */
5306 /* used to specify the number of levels to show for each item */
5307 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
5309 /* currently use no levels to test outline view viability */
5310 if (item == nil) // for an outline view the root level of the hierarchy is always nil
5312 return [UserPresets count];
5316 /* we need to return the count of the array in ChildrenArray for this folder */
5317 NSArray *children = nil;
5318 children = [item objectForKey:@"ChildrenArray"];
5319 if ([children count] > 0)
5321 return [children count];
5330 /* We use this to deterimine children of an item */
5331 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(int)index ofItem:(id)item
5334 /* we need to return the count of the array in ChildrenArray for this folder */
5335 NSArray *children = nil;
5338 children = UserPresets;
5342 if ([item objectForKey:@"ChildrenArray"])
5344 children = [item objectForKey:@"ChildrenArray"];
5347 if ((children == nil) || ([children count] <= index))
5353 return [children objectAtIndex:index];
5357 // We are only one level deep, so we can't be asked about children
5358 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
5362 /* We use this to determine if an item should be expandable */
5363 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
5366 /* we need to return the count of the array in ChildrenArray for this folder */
5367 NSArray *children= nil;
5370 children = UserPresets;
5374 if ([item objectForKey:@"ChildrenArray"])
5376 children = [item objectForKey:@"ChildrenArray"];
5380 /* To deterimine if an item should show a disclosure triangle
5381 * we could do it by the children count as so:
5382 * if ([children count] < 1)
5383 * However, lets leave the triangle show even if there are no
5384 * children to help indicate a folder, just like folder in the
5385 * finder can show a disclosure triangle even when empty
5388 /* We need to determine if the item is a folder */
5389 if ([[item objectForKey:@"Folder"] intValue] == 1)
5400 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
5402 // Our outline view has no levels, but we can still expand every item. Doing so
5403 // just makes the row taller. See heightOfRowByItem below.
5404 //return ![(HBQueueOutlineView*)outlineView isDragging];
5410 /* Used to tell the outline view which information is to be displayed per item */
5411 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5413 /* We have two columns right now, icon and PresetName */
5415 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5417 return [item objectForKey:@"PresetName"];
5426 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
5428 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
5430 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
5432 return [NSKeyedArchiver archivedDataWithRootObject:item];
5435 #pragma mark - Added Functionality (optional)
5436 /* Use to customize the font and display characteristics of the title cell */
5437 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
5439 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5443 NSColor *shadowColor;
5444 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
5445 /*check to see if its a selected row */
5446 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
5449 fontColor = [NSColor blackColor];
5450 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
5454 if ([[item objectForKey:@"Type"] intValue] == 0)
5456 fontColor = [NSColor blueColor];
5458 else // User created preset, use a black font
5460 fontColor = [NSColor blackColor];
5462 /* check to see if its a folder */
5463 //if ([[item objectForKey:@"Folder"] intValue] == 1)
5465 //fontColor = [NSColor greenColor];
5470 /* We use Bold Text for the HB Default */
5471 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
5473 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5475 /* We use Bold Text for the User Specified Default */
5476 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
5478 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5482 [cell setTextColor:fontColor];
5483 [cell setFont:txtFont];
5488 /* We use this to edit the name field in the outline view */
5489 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5491 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5496 [theRecord setObject:object forKey:@"PresetName"];
5500 [fPresetsOutlineView reloadData];
5501 /* We save all of the preset data here */
5505 /* We use this to provide tooltips for the items in the presets outline view */
5506 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
5508 //if ([[tc identifier] isEqualToString:@"PresetName"])
5510 /* initialize the tooltip contents variable */
5512 /* if there is a description for the preset, we show it in the tooltip */
5513 if ([item objectForKey:@"PresetDescription"])
5515 loc_tip = [item objectForKey:@"PresetDescription"];
5520 loc_tip = @"No description available";
5527 #pragma mark Preset Outline View Methods (dragging related)
5530 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
5532 // Dragging is only allowed for custom presets.
5533 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
5534 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
5538 // Don't retain since this is just holding temporaral drag information, and it is
5539 //only used during a drag! We could put this in the pboard actually.
5540 fDraggedNodes = items;
5541 // Provide data for our custom type, and simple NSStrings.
5542 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
5544 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
5545 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
5550 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
5553 // Don't allow dropping ONTO an item since they can't really contain any children.
5555 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
5556 if (isOnDropTypeProposal)
5557 return NSDragOperationNone;
5559 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
5562 index = [fPresetsOutlineView rowForItem: item] + 1;
5566 // Don't allow dropping into the Built In Presets.
5567 if (index < presetCurrentBuiltInCount)
5569 return NSDragOperationNone;
5570 index = MAX (index, presetCurrentBuiltInCount);
5573 [outlineView setDropItem:item dropChildIndex:index];
5574 return NSDragOperationGeneric;
5579 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
5581 /* first, lets see if we are dropping into a folder */
5582 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
5584 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
5585 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
5586 [childrenArray addObject:item];
5587 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
5588 [childrenArray autorelease];
5590 else // We are not, so we just move the preset into the existing array
5592 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
5594 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
5595 while (obj = [enumerator nextObject])
5597 [moveItems addIndex:[UserPresets indexOfObject:obj]];
5599 // Successful drop, lets rearrange the view and save it all
5600 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
5602 [fPresetsOutlineView reloadData];
5607 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
5609 unsigned index = [indexSet lastIndex];
5610 unsigned aboveInsertIndexCount = 0;
5612 while (index != NSNotFound)
5614 unsigned removeIndex;
5616 if (index >= insertIndex)
5618 removeIndex = index + aboveInsertIndexCount;
5619 aboveInsertIndexCount++;
5623 removeIndex = index;
5627 id object = [[array objectAtIndex:removeIndex] retain];
5628 [array removeObjectAtIndex:removeIndex];
5629 [array insertObject:object atIndex:insertIndex];
5632 index = [indexSet indexLessThanIndex:index];
5638 #pragma mark - Functional Preset NSOutlineView Methods
5640 - (IBAction)selectPreset:(id)sender
5643 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
5645 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
5646 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5648 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
5650 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
5654 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5658 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
5659 [self formatPopUpChanged:nil];
5661 /* Chapter Markers*/
5662 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
5663 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
5664 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
5665 /* Mux mp4 with http optimization */
5666 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
5669 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
5670 /* We set the advanced opt string here if applicable*/
5671 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
5673 /* Lets run through the following functions to get variables set there */
5674 [self videoEncoderPopUpChanged:nil];
5675 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
5676 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
5677 [self calculateBitrate:nil];
5680 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
5682 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
5683 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
5685 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
5686 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
5687 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
5688 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
5689 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
5690 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
5692 /* For the quality slider we need to convert the old percent's to the new rf scales */
5693 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
5694 [fVidQualitySlider setFloatValue:rf];
5699 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
5702 [self videoMatrixChanged:nil];
5704 /* Video framerate */
5705 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
5706 detected framerate in the fVidRatePopUp so we use index 0*/
5707 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
5709 [fVidRatePopUp selectItemAtIndex: 0];
5713 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
5717 /* 2 Pass Encoding */
5718 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
5719 [self twoPassCheckboxChanged:nil];
5721 /* Turbo 1st pass for 2 Pass Encoding */
5722 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
5726 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
5728 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5730 [fAudLang1PopUp selectItemAtIndex: 1];
5732 [self audioTrackPopUpChanged: fAudLang1PopUp];
5733 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
5734 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5735 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
5736 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5738 if ([fAudTrack1MixPopUp selectedItem] == nil)
5740 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5742 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
5743 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5744 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
5746 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
5748 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
5749 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5751 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
5753 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5755 [fAudLang2PopUp selectItemAtIndex: 1];
5757 [self audioTrackPopUpChanged: fAudLang2PopUp];
5758 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
5759 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5760 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
5761 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5763 if ([fAudTrack2MixPopUp selectedItem] == nil)
5765 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5767 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
5768 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5769 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
5771 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
5773 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
5774 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5776 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
5778 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5780 [fAudLang3PopUp selectItemAtIndex: 1];
5782 [self audioTrackPopUpChanged: fAudLang3PopUp];
5783 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
5784 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5785 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
5786 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5788 if ([fAudTrack3MixPopUp selectedItem] == nil)
5790 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5792 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
5793 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5794 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
5796 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
5798 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
5799 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5801 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
5803 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5805 [fAudLang4PopUp selectItemAtIndex: 1];
5807 [self audioTrackPopUpChanged: fAudLang4PopUp];
5808 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
5809 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5810 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
5811 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5813 if ([fAudTrack4MixPopUp selectedItem] == nil)
5815 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5817 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
5818 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5819 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
5821 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
5823 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
5824 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5827 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
5829 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
5831 [fAudLang2PopUp selectItemAtIndex: 0];
5832 [self audioTrackPopUpChanged: fAudLang2PopUp];
5834 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
5836 [fAudLang3PopUp selectItemAtIndex: 0];
5837 [self audioTrackPopUpChanged: fAudLang3PopUp];
5839 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
5841 [fAudLang4PopUp selectItemAtIndex: 0];
5842 [self audioTrackPopUpChanged: fAudLang4PopUp];
5846 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
5847 /* Forced Subtitles */
5848 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
5850 /* Picture Settings */
5851 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
5852 * height, width, keep ar, anamorphic and crop settings.
5853 * picture filters are handled separately below.
5855 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
5856 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
5857 * preset completely ignores any picture sizing values in the preset.
5859 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
5861 hb_job_t * job = fTitle->job;
5863 /* If Cropping is set to custom, then recall all four crop values from
5864 when the preset was created and apply them */
5865 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
5867 [fPictureController setAutoCrop:NO];
5869 /* Here we use the custom crop values saved at the time the preset was saved */
5870 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
5871 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
5872 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
5873 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
5876 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
5878 [fPictureController setAutoCrop:YES];
5879 /* Here we use the auto crop values determined right after scan */
5880 job->crop[0] = AutoCropTop;
5881 job->crop[1] = AutoCropBottom;
5882 job->crop[2] = AutoCropLeft;
5883 job->crop[3] = AutoCropRight;
5888 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
5889 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
5891 /* Use Max Picture settings for whatever the dvd is.*/
5892 [self revertPictureSizeToMax:nil];
5893 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5894 if (job->keep_ratio == 1)
5896 hb_fix_aspect( job, HB_KEEP_WIDTH );
5897 if( job->height > fTitle->height )
5899 job->height = fTitle->height;
5900 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5903 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5905 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
5907 /* we check to make sure the presets width/height does not exceed the sources width/height */
5908 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
5910 /* if so, then we use the sources height and width to avoid scaling up */
5911 //job->width = fTitle->width;
5912 //job->height = fTitle->height;
5913 [self revertPictureSizeToMax:nil];
5915 else // source width/height is >= the preset height/width
5917 /* we can go ahead and use the presets values for height and width */
5918 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
5919 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
5921 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5922 if (job->keep_ratio == 1)
5924 hb_fix_aspect( job, HB_KEEP_WIDTH );
5925 if( job->height > fTitle->height )
5927 job->height = fTitle->height;
5928 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5931 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5937 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
5938 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
5942 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
5943 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
5944 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
5947 [fPictureFilterController setUseDecomb:1];
5948 [fPictureFilterController setDecomb:0];
5949 [fPictureFilterController setDeinterlace:0];
5950 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
5952 /* we are using decomb */
5954 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
5956 [fPictureFilterController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
5958 /* if we are using "Custom" in the decomb setting, also set the custom string*/
5959 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 2)
5961 [fPictureFilterController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
5967 /* We are using Deinterlace */
5969 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
5971 [fPictureFilterController setUseDecomb:0];
5972 [fPictureFilterController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
5973 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
5974 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
5976 [fPictureFilterController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
5983 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
5985 [fPictureFilterController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
5986 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
5987 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 2)
5989 [fPictureFilterController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
5994 [fPictureFilterController setDetelecine:0];
5998 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
6000 [fPictureFilterController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
6001 /* if we are using "Custom" in the denoise setting, also set the custom string*/
6002 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 4)
6004 [fPictureFilterController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
6009 [fPictureFilterController setDenoise:0];
6013 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
6015 /* if its a one, then its the old on/off deblock, set on to 5*/
6016 [fPictureFilterController setDeblock:5];
6020 /* use the settings intValue */
6021 [fPictureFilterController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
6024 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
6026 [fPictureFilterController setGrayscale:1];
6030 [fPictureFilterController setGrayscale:0];
6033 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
6034 [fPictureController SetTitle:fTitle];
6035 [fPictureFilterController SetTitle:fTitle];
6036 [self calculatePictureSizing:nil];
6042 #pragma mark Manage Presets
6044 - (void) loadPresets {
6045 /* We declare the default NSFileManager into fileManager */
6046 NSFileManager * fileManager = [NSFileManager defaultManager];
6047 /*We define the location of the user presets file */
6048 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
6049 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
6050 /* We check for the presets.plist */
6051 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
6053 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
6056 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
6057 if (nil == UserPresets)
6059 UserPresets = [[NSMutableArray alloc] init];
6060 [self addFactoryPresets:nil];
6062 [fPresetsOutlineView reloadData];
6066 - (IBAction) showAddPresetPanel: (id) sender
6068 /* Deselect the currently selected Preset if there is one*/
6069 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
6071 /* Populate the preset picture settings popup here */
6072 [fPresetNewPicSettingsPopUp removeAllItems];
6073 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
6074 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
6075 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
6076 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
6077 /* Uncheck the preset use filters checkbox */
6078 [fPresetNewPicFiltersCheck setState:NSOffState];
6079 // fPresetNewFolderCheck
6080 [fPresetNewFolderCheck setState:NSOffState];
6081 /* Erase info from the input fields*/
6082 [fPresetNewName setStringValue: @""];
6083 [fPresetNewDesc setStringValue: @""];
6084 /* Show the panel */
6085 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
6088 - (IBAction) closeAddPresetPanel: (id) sender
6090 [NSApp endSheet: fAddPresetPanel];
6091 [fAddPresetPanel orderOut: self];
6094 - (IBAction)addUserPreset:(id)sender
6096 if (![[fPresetNewName stringValue] length])
6097 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
6100 /* Here we create a custom user preset */
6101 [UserPresets addObject:[self createPreset]];
6104 [self closeAddPresetPanel:nil];
6111 /* We Reload the New Table data for presets */
6112 [fPresetsOutlineView reloadData];
6113 /* We save all of the preset data here */
6121 /* We Sort the Presets By Factory or Custom */
6122 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
6123 ascending:YES] autorelease];
6124 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
6126 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
6127 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
6128 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
6131 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
6132 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
6133 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
6134 [UserPresets setArray:sortedArray];
6139 - (IBAction)insertPreset:(id)sender
6141 int index = [fPresetsOutlineView selectedRow];
6142 [UserPresets insertObject:[self createPreset] atIndex:index];
6143 [fPresetsOutlineView reloadData];
6147 - (NSDictionary *)createPreset
6149 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
6150 /* Get the New Preset Name from the field in the AddPresetPanel */
6151 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
6152 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
6153 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
6154 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
6155 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
6156 /*Set whether or not this is default, at creation set to 0*/
6157 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6158 if ([fPresetNewFolderCheck state] == YES)
6160 /* initialize and set an empty array for children here since we are a new folder */
6161 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6162 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6163 [childrenArray autorelease];
6165 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
6167 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
6168 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
6169 /* Get whether or not to use the current Picture Filter settings for the preset */
6170 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
6172 /* Get New Preset Description from the field in the AddPresetPanel*/
6173 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
6175 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
6176 /* Chapter Markers fCreateChapterMarkers*/
6177 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
6178 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6179 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
6180 /* Mux mp4 with http optimization */
6181 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
6182 /* Add iPod uuid atom */
6183 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
6187 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
6188 /* x264 Option String */
6189 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
6191 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
6192 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
6193 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
6194 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
6196 /* Video framerate */
6197 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
6199 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
6201 else // we can record the actual titleOfSelectedItem
6203 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
6206 /* 2 Pass Encoding */
6207 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
6208 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
6209 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
6210 /*Picture Settings*/
6211 hb_job_t * job = fTitle->job;
6212 /* Picture Sizing */
6213 /* Use Max Picture settings for whatever the dvd is.*/
6214 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
6215 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
6216 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
6217 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
6218 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
6220 /* Set crop settings here */
6221 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
6222 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
6223 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
6224 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
6225 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
6227 /* Picture Filters */
6228 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController useDecomb]] forKey:@"PictureDecombDeinterlace"];
6229 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController deinterlace]] forKey:@"PictureDeinterlace"];
6230 [preset setObject:[fPictureFilterController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
6231 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController detelecine]] forKey:@"PictureDetelecine"];
6232 [preset setObject:[fPictureFilterController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
6233 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController denoise]] forKey:@"PictureDenoise"];
6234 [preset setObject:[fPictureFilterController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
6235 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController deblock]] forKey:@"PictureDeblock"];
6236 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController decomb]] forKey:@"PictureDecomb"];
6237 [preset setObject:[fPictureFilterController decombCustomString] forKey:@"PictureDecombCustom"];
6238 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController grayscale]] forKey:@"VideoGrayScale"];
6242 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
6244 [preset setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
6245 [preset setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
6246 [preset setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
6247 [preset setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
6248 [preset setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
6249 [preset setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
6250 [preset setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
6252 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
6254 [preset setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
6255 [preset setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
6256 [preset setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
6257 [preset setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
6258 [preset setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
6259 [preset setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
6260 [preset setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
6262 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
6264 [preset setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
6265 [preset setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
6266 [preset setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
6267 [preset setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
6268 [preset setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
6269 [preset setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
6270 [preset setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
6272 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
6274 [preset setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
6275 [preset setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
6276 [preset setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
6277 [preset setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
6278 [preset setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
6279 [preset setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
6280 [preset setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
6284 [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
6285 /* Forced Subtitles */
6286 [preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
6288 [preset autorelease];
6295 [UserPresets writeToFile:UserPresetsFile atomically:YES];
6296 /* We get the default preset in case it changed */
6297 [self getDefaultPresets:nil];
6301 - (IBAction)deletePreset:(id)sender
6305 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
6309 /* Alert user before deleting preset */
6311 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
6313 if ( status == NSAlertDefaultReturn )
6315 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6316 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6317 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6319 NSEnumerator *enumerator;
6320 NSMutableArray *presetsArrayToMod;
6321 NSMutableArray *tempArray;
6323 /* If we are a root level preset, we are modding the UserPresets array */
6324 if (presetToModLevel == 0)
6326 presetsArrayToMod = UserPresets;
6328 else // We have a parent preset, so we modify the chidren array object for key
6330 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6333 enumerator = [presetsArrayToMod objectEnumerator];
6334 tempArray = [NSMutableArray array];
6336 while (tempObject = [enumerator nextObject])
6338 NSDictionary *thisPresetDict = tempObject;
6339 if (thisPresetDict == presetToMod)
6341 [tempArray addObject:tempObject];
6345 [presetsArrayToMod removeObjectsInArray:tempArray];
6346 [fPresetsOutlineView reloadData];
6352 #pragma mark Manage Default Preset
6354 - (IBAction)getDefaultPresets:(id)sender
6356 presetHbDefault = nil;
6357 presetUserDefault = nil;
6358 presetUserDefaultParent = nil;
6359 presetUserDefaultParentParent = nil;
6360 NSMutableDictionary *presetHbDefaultParent = nil;
6361 NSMutableDictionary *presetHbDefaultParentParent = nil;
6364 BOOL userDefaultFound = NO;
6365 presetCurrentBuiltInCount = 0;
6366 /* First we iterate through the root UserPresets array to check for defaults */
6367 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6369 while (tempObject = [enumerator nextObject])
6371 NSMutableDictionary *thisPresetDict = tempObject;
6372 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6374 presetHbDefault = thisPresetDict;
6376 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6378 presetUserDefault = thisPresetDict;
6379 userDefaultFound = YES;
6381 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
6383 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
6387 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6388 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6390 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
6391 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6393 while (tempObject = [enumerator nextObject])
6395 NSMutableDictionary *thisPresetDict = tempObject;
6396 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6398 presetHbDefault = thisPresetDict;
6399 presetHbDefaultParent = thisPresetDictParent;
6401 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6403 presetUserDefault = thisPresetDict;
6404 presetUserDefaultParent = thisPresetDictParent;
6405 userDefaultFound = YES;
6408 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6409 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6411 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
6412 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6414 while (tempObject = [enumerator nextObject])
6416 NSMutableDictionary *thisPresetDict = tempObject;
6417 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6419 presetHbDefault = thisPresetDict;
6420 presetHbDefaultParent = thisPresetDictParent;
6421 presetHbDefaultParentParent = thisPresetDictParentParent;
6423 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6425 presetUserDefault = thisPresetDict;
6426 presetUserDefaultParent = thisPresetDictParent;
6427 presetUserDefaultParentParent = thisPresetDictParentParent;
6428 userDefaultFound = YES;
6437 /* check to see if a user specified preset was found, if not then assign the parents for
6438 * the presetHbDefault so that we can open the parents for the nested presets
6440 if (userDefaultFound == NO)
6442 presetUserDefaultParent = presetHbDefaultParent;
6443 presetUserDefaultParentParent = presetHbDefaultParentParent;
6447 - (IBAction)setDefaultPreset:(id)sender
6449 /* We need to determine if the item is a folder */
6450 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
6456 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6458 /* First make sure the old user specified default preset is removed */
6459 while (tempObject = [enumerator nextObject])
6461 NSMutableDictionary *thisPresetDict = tempObject;
6462 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6464 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6467 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6468 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6470 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6473 while (tempObject = [enumerator nextObject])
6475 NSMutableDictionary *thisPresetDict1 = tempObject;
6476 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6478 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6480 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6481 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
6483 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
6486 while (tempObject = [enumerator nextObject])
6488 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6490 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6503 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6504 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6505 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6508 NSMutableArray *presetsArrayToMod;
6509 NSMutableArray *tempArray;
6511 /* If we are a root level preset, we are modding the UserPresets array */
6512 if (presetToModLevel == 0)
6514 presetsArrayToMod = UserPresets;
6516 else // We have a parent preset, so we modify the chidren array object for key
6518 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6521 enumerator = [presetsArrayToMod objectEnumerator];
6522 tempArray = [NSMutableArray array];
6524 while (tempObject = [enumerator nextObject])
6526 NSDictionary *thisPresetDict = tempObject;
6527 if (thisPresetDict == presetToMod)
6529 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
6531 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
6538 /* We save all of the preset data here */
6540 /* We Reload the New Table data for presets */
6541 [fPresetsOutlineView reloadData];
6544 - (IBAction)selectDefaultPreset:(id)sender
6546 NSMutableDictionary *presetToMod;
6547 /* if there is a user specified default, we use it */
6548 if (presetUserDefault)
6550 presetToMod = presetUserDefault;
6552 else if (presetHbDefault) //else we use the built in default presetHbDefault
6554 presetToMod = presetHbDefault;
6561 if (presetUserDefaultParent != nil)
6563 [fPresetsOutlineView expandItem:presetUserDefaultParent];
6566 if (presetUserDefaultParentParent != nil)
6568 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
6572 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
6573 [self selectPreset:nil];
6578 #pragma mark Manage Built In Presets
6581 - (IBAction)deleteFactoryPresets:(id)sender
6584 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6588 NSMutableArray *tempArray;
6591 tempArray = [NSMutableArray array];
6592 /* we look here to see if the preset is we move on to the next one */
6593 while ( tempObject = [enumerator nextObject] )
6595 /* if the preset is "Factory" then we put it in the array of
6596 presets to delete */
6597 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
6599 [tempArray addObject:tempObject];
6603 [UserPresets removeObjectsInArray:tempArray];
6604 [fPresetsOutlineView reloadData];
6609 /* We use this method to recreate new, updated factory
6611 - (IBAction)addFactoryPresets:(id)sender
6614 /* First, we delete any existing built in presets */
6615 [self deleteFactoryPresets: sender];
6616 /* Then we generate new built in presets programmatically with fPresetsBuiltin
6617 * which is all setup in HBPresets.h and HBPresets.m*/
6618 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
6630 /*******************************
6631 * Subclass of the HBPresetsOutlineView *
6632 *******************************/
6634 @implementation HBPresetsOutlineView
6635 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
6639 // By default, NSTableView only drags an image of the first column. Change this to
6640 // drag an image of the queue's icon and PresetName columns.
6641 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
6642 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
6647 - (void) mouseDown:(NSEvent *)theEvent
6649 [super mouseDown:theEvent];
6655 - (BOOL) isDragging;