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 we are in preview full screen mode, we need to go to
212 * windowed mode and release the display before we terminate.
213 * We do it here (instead of applicationWillTerminate) so we
214 * release the displays and can then see the alerts below.
216 if ([fPictureController previewFullScreenMode] == YES)
218 [fPictureController previewGoWindowed:nil];
222 hb_get_state( fQueueEncodeLibhb, &s );
224 if ( s.state != HB_STATE_IDLE )
226 int result = NSRunCriticalAlertPanel(
227 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
228 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
229 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
231 if (result == NSAlertDefaultReturn)
233 return NSTerminateNow;
236 return NSTerminateCancel;
239 // Warn if items still in the queue
240 else if ( fPendingCount > 0 )
242 int result = NSRunCriticalAlertPanel(
243 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
244 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
245 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
247 if ( result == NSAlertDefaultReturn )
248 return NSTerminateNow;
250 return NSTerminateCancel;
253 return NSTerminateNow;
256 - (void)applicationWillTerminate:(NSNotification *)aNotification
259 [browsedSourceDisplayName release];
260 [outputPanel release];
261 [fQueueController release];
262 [fPreviewController release];
263 [fPictureController release];
264 [fPictureFilterController release];
267 hb_close(&fQueueEncodeLibhb);
271 - (void) awakeFromNib
274 [fWindow setExcludedFromWindowsMenu:YES];
275 [fAdvancedOptions setView:fAdvancedView];
277 /* lets setup our presets drawer for drag and drop here */
278 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
279 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
280 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
282 /* Initialize currentScanCount so HB can use it to
283 evaluate successive scans */
284 currentScanCount = 0;
287 /* Init UserPresets .plist */
290 /* Init QueueFile .plist */
291 [self loadQueueFile];
293 fRipIndicatorShown = NO; // initially out of view in the nib
295 /* Show/Dont Show Presets drawer upon launch based
296 on user preference DefaultPresetsDrawerShow*/
297 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
299 [fPresetDrawer setDelegate:self];
300 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
301 stringForKey:@"Drawer Size"] );
302 if( drawerSize.width )
303 [fPresetDrawer setContentSize: drawerSize];
304 [fPresetDrawer open];
308 NSMenuItem *menuItem;
309 [fDstFormatPopUp removeAllItems];
311 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
312 [menuItem setTag: HB_MUX_MP4];
314 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
315 [menuItem setTag: HB_MUX_MKV];
317 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"AVI file" action: NULL keyEquivalent: @""];
318 [menuItem setTag: HB_MUX_AVI];
320 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"OGM file" action: NULL keyEquivalent: @""];
321 [menuItem setTag: HB_MUX_OGM];
322 [fDstFormatPopUp selectItemAtIndex: 0];
324 [self formatPopUpChanged:nil];
326 /* We enable the create chapters checkbox here since we are .mp4 */
327 [fCreateChapterMarkers setEnabled: YES];
328 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
330 [fCreateChapterMarkers setState: NSOnState];
336 [fDstFile2Field setStringValue: [NSString stringWithFormat:
337 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
340 [fVidEncoderPopUp removeAllItems];
341 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
342 [fVidEncoderPopUp addItemWithTitle: @"XviD"];
347 [fVidTargetSizeField setIntValue: 700];
348 [fVidBitrateField setIntValue: 1000];
350 [fVidQualityMatrix selectCell: fVidBitrateCell];
351 [self videoMatrixChanged:nil];
353 /* Video framerate */
354 [fVidRatePopUp removeAllItems];
355 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
356 for( int i = 0; i < hb_video_rates_count; i++ )
358 if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
360 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
361 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
363 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
365 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
366 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
368 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
370 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
371 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
375 [fVidRatePopUp addItemWithTitle:
376 [NSString stringWithCString: hb_video_rates[i].string]];
379 [fVidRatePopUp selectItemAtIndex: 0];
381 /* Set Auto Crop to On at launch */
382 [fPictureController setAutoCrop:YES];
385 [fAudTrack1BitratePopUp removeAllItems];
386 for( int i = 0; i < hb_audio_bitrates_count; i++ )
388 [fAudTrack1BitratePopUp addItemWithTitle:
389 [NSString stringWithCString: hb_audio_bitrates[i].string]];
392 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
394 /* Audio samplerate */
395 [fAudTrack1RatePopUp removeAllItems];
396 for( int i = 0; i < hb_audio_rates_count; i++ )
398 [fAudTrack1RatePopUp addItemWithTitle:
399 [NSString stringWithCString: hb_audio_rates[i].string]];
401 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
404 [fStatusField setStringValue: @""];
409 /* We disable the Turbo 1st pass checkbox since we are not x264 */
410 [fVidTurboPassCheck setEnabled: NO];
411 [fVidTurboPassCheck setState: NSOffState];
414 /* lets get our default prefs here */
415 [self getDefaultPresets:nil];
416 /* lets initialize the current successful scancount here to 0 */
417 currentSuccessfulScanCount = 0;
422 - (void) enableUI: (bool) b
424 NSControl * controls[] =
425 { fSrcTitleField, fSrcTitlePopUp,
426 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
427 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
428 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
429 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
430 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
431 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
432 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
433 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
434 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
435 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
436 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
437 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
438 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
439 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
440 fQueueStatus,fPresetsAdd,fPresetsDelete,
441 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
442 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel};
445 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
447 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
449 NSTextField * tf = (NSTextField *) controls[i];
450 if( ![tf isBezeled] )
452 [tf setTextColor: b ? [NSColor controlTextColor] :
453 [NSColor disabledControlTextColor]];
457 [controls[i] setEnabled: b];
463 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
464 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
465 [self setEnabledStateOfAudioMixdownControls:nil];
466 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
467 [self calculatePictureSizing:nil];
471 [fPresetsOutlineView setEnabled: NO];
475 [self videoMatrixChanged:nil];
476 [fAdvancedOptions enableUI:b];
480 /***********************************************************************
482 ***********************************************************************
483 * Shows a progression bar on the dock icon, filled according to
484 * 'progress' (0.0 <= progress <= 1.0).
485 * Called with progress < 0.0 or progress > 1.0, restores the original
487 **********************************************************************/
488 - (void) UpdateDockIcon: (float) progress
492 NSBitmapImageRep * bmp;
494 uint32_t black = htonl( 0x000000FF );
495 uint32_t red = htonl( 0xFF0000FF );
496 uint32_t white = htonl( 0xFFFFFFFF );
497 int row_start, row_end;
500 /* Get application original icon */
501 icon = [NSImage imageNamed: @"NSApplicationIcon"];
503 if( progress < 0.0 || progress > 1.0 )
505 [NSApp setApplicationIconImage: icon];
509 /* Get it in a raw bitmap form */
510 tiff = [icon TIFFRepresentationUsingCompression:
511 NSTIFFCompressionNone factor: 1.0];
512 bmp = [NSBitmapImageRep imageRepWithData: tiff];
514 /* Draw the progression bar */
515 /* It's pretty simple (ugly?) now, but I'm no designer */
517 row_start = 3 * (int) [bmp size].height / 4;
518 row_end = 7 * (int) [bmp size].height / 8;
520 for( i = row_start; i < row_start + 2; i++ )
522 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
523 for( j = 0; j < (int) [bmp size].width; j++ )
528 for( i = row_start + 2; i < row_end - 2; i++ )
530 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
533 for( j = 2; j < (int) [bmp size].width - 2; j++ )
535 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
547 for( i = row_end - 2; i < row_end; i++ )
549 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
550 for( j = 0; j < (int) [bmp size].width; j++ )
556 /* Now update the dock icon */
557 tiff = [bmp TIFFRepresentationUsingCompression:
558 NSTIFFCompressionNone factor: 1.0];
559 icon = [[NSImage alloc] initWithData: tiff];
560 [NSApp setApplicationIconImage: icon];
564 - (void) updateUI: (NSTimer *) timer
567 /* Update UI for fHandle (user scanning instance of libhb ) */
570 list = hb_get_titles( fHandle );
571 /* check to see if there has been a new scan done
572 this bypasses the constraints of HB_STATE_WORKING
573 not allowing setting a newly scanned source */
574 int checkScanCount = hb_get_scancount( fHandle );
575 if( checkScanCount > currentScanCount )
577 currentScanCount = checkScanCount;
578 [fScanIndicator setIndeterminate: NO];
579 [fScanIndicator setDoubleValue: 0.0];
580 [fScanIndicator setHidden: YES];
581 [self showNewScan:nil];
585 hb_get_state( fHandle, &s );
591 #define p s.param.scanning
592 case HB_STATE_SCANNING:
594 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
595 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
596 p.title_cur, p.title_count]];
597 [fScanIndicator setHidden: NO];
598 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
603 #define p s.param.scandone
604 case HB_STATE_SCANDONE:
606 [fScanIndicator setIndeterminate: NO];
607 [fScanIndicator setDoubleValue: 0.0];
608 [fScanIndicator setHidden: YES];
609 [self writeToActivityLog:"ScanDone state received from fHandle"];
610 [self showNewScan:nil];
611 [[fWindow toolbar] validateVisibleItems];
617 #define p s.param.working
618 case HB_STATE_WORKING:
625 #define p s.param.muxing
626 case HB_STATE_MUXING:
633 case HB_STATE_PAUSED:
636 case HB_STATE_WORKDONE:
643 /* Update UI for fQueueEncodeLibhb */
645 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
646 /* check to see if there has been a new scan done
647 this bypasses the constraints of HB_STATE_WORKING
648 not allowing setting a newly scanned source */
650 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
651 if( checkScanCount > currentScanCount )
653 currentScanCount = checkScanCount;
654 [self writeToActivityLog:"currentScanCount received from fQueueEncodeLibhb"];
658 hb_get_state( fQueueEncodeLibhb, &s );
664 #define p s.param.scanning
665 case HB_STATE_SCANNING:
667 [fStatusField setStringValue: [NSString stringWithFormat:
668 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
669 p.title_cur, p.title_count]];
671 /* Set the status string in fQueueController as well */
672 [fQueueController setQueueStatusString: [NSString stringWithFormat:
673 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
674 p.title_cur, p.title_count]];
676 [fRipIndicator setHidden: NO];
677 [fRipIndicator setDoubleValue: 100.0 * ( p.title_cur - 1 ) / p.title_count];
682 #define p s.param.scandone
683 case HB_STATE_SCANDONE:
685 [fRipIndicator setIndeterminate: NO];
686 [fRipIndicator setDoubleValue: 0.0];
688 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
689 [self processNewQueueEncode];
690 [[fWindow toolbar] validateVisibleItems];
696 #define p s.param.working
697 case HB_STATE_WORKING:
699 NSMutableString * string;
700 /* Update text field */
701 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d of %d, %.2f %%", @"" ), p.job_cur, p.job_count, 100.0 * p.progress];
705 [string appendFormat:
706 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
707 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
710 [fStatusField setStringValue: string];
711 /* Set the status string in fQueueController as well */
712 [fQueueController setQueueStatusString: string];
714 double progress_total;
715 progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
716 [fRipIndicator setIndeterminate: NO];
717 [fRipIndicator setDoubleValue: 100.0 * progress_total];
718 //[fRipIndicator setDoubleValue: 100.0 * p.progress];
720 // If progress bar hasn't been revealed at the bottom of the window, do
721 // that now. This code used to be in doRip. I moved it to here to handle
722 // the case where hb_start is called by HBQueueController and not from
724 if( !fRipIndicatorShown )
726 NSRect frame = [fWindow frame];
727 if( frame.size.width <= 591 )
728 frame.size.width = 591;
729 frame.size.height += 36;
730 frame.origin.y -= 36;
731 [fWindow setFrame:frame display:YES animate:YES];
732 fRipIndicatorShown = YES;
736 /* Update dock icon */
737 [self UpdateDockIcon: progress_total];
743 #define p s.param.muxing
744 case HB_STATE_MUXING:
746 /* Update text field */
747 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
748 /* Set the status string in fQueueController as well */
749 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
751 [fRipIndicator setIndeterminate: YES];
752 [fRipIndicator startAnimation: nil];
754 /* Update dock icon */
755 [self UpdateDockIcon: 1.0];
761 case HB_STATE_PAUSED:
762 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
763 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
767 case HB_STATE_WORKDONE:
769 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
770 // or someone calling hb_stop. In the latter case, hb_stop does not clear
771 // out the remaining passes/jobs in the queue. We'll do that here.
773 // Delete all remaining jobs of this encode.
774 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
775 /* Set the status string in fQueueController as well */
776 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
777 [fRipIndicator setIndeterminate: NO];
778 [fRipIndicator setDoubleValue: 0.0];
779 [[fWindow toolbar] validateVisibleItems];
781 /* Restore dock icon */
782 [self UpdateDockIcon: -1.0];
784 if( fRipIndicatorShown )
786 NSRect frame = [fWindow frame];
787 if( frame.size.width <= 591 )
788 frame.size.width = 591;
789 frame.size.height += -36;
790 frame.origin.y -= -36;
791 [fWindow setFrame:frame display:YES animate:YES];
792 fRipIndicatorShown = NO;
794 /* Since we are done with this encode, tell output to stop writing to the
795 * individual encode log
797 [outputPanel endEncodeLog];
798 /* Check to see if the encode state has not been cancelled
799 to determine if we should check for encode done notifications */
800 if( fEncodeState != 2 )
802 NSString *pathOfFinishedEncode;
803 /* Get the output file name for the finished encode */
804 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
806 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
808 [self showGrowlDoneNotification:pathOfFinishedEncode];
810 [self sendToMetaX:pathOfFinishedEncode];
812 /* since we have successfully completed an encode, we increment the queue counter */
813 [self incrementQueueItemDone:nil];
815 /* all end of queue actions below need to be done after all queue encodes have finished
816 * and there are no pending jobs left to process
818 if (fPendingCount == 0)
820 /* If Alert Window or Window and Growl has been selected */
821 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
822 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
824 /*On Screen Notification*/
827 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
828 [NSApp requestUserAttention:NSCriticalRequest];
831 /* If sleep has been selected */
832 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
835 NSDictionary* errorDict;
836 NSAppleEventDescriptor* returnDescriptor = nil;
837 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
838 @"tell application \"Finder\" to sleep"];
839 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
840 [scriptObject release];
842 /* If Shutdown has been selected */
843 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
846 NSDictionary* errorDict;
847 NSAppleEventDescriptor* returnDescriptor = nil;
848 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
849 @"tell application \"Finder\" to shut down"];
850 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
851 [scriptObject release];
865 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
866 - (void) writeToActivityLog:(char *) format, ...
869 va_start(args, format);
873 vsnprintf( str, 1024, format, args );
875 time_t _now = time( NULL );
876 struct tm * now = localtime( &_now );
877 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
884 // ============================================================
885 // NSToolbar Related Methods
886 // ============================================================
888 - (void) setupToolbar {
889 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
891 [toolbar setAllowsUserCustomization: YES];
892 [toolbar setAutosavesConfiguration: YES];
893 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
895 [toolbar setDelegate: self];
897 [fWindow setToolbar: toolbar];
900 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
901 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
902 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
904 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
906 [item setLabel: @"Toggle Presets"];
907 [item setPaletteLabel: @"Toggler Presets"];
908 [item setToolTip: @"Open/Close Preset Drawer"];
909 [item setImage: [NSImage imageNamed: @"Drawer"]];
910 [item setTarget: self];
911 [item setAction: @selector(toggleDrawer:)];
912 [item setAutovalidates: NO];
914 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
916 [item setLabel: @"Start"];
917 [item setPaletteLabel: @"Start Encoding"];
918 [item setToolTip: @"Start Encoding"];
919 [item setImage: [NSImage imageNamed: @"Play"]];
920 [item setTarget: self];
921 [item setAction: @selector(Rip:)];
923 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
925 [item setLabel: @"Show Queue"];
926 [item setPaletteLabel: @"Show Queue"];
927 [item setToolTip: @"Show Queue"];
928 [item setImage: [NSImage imageNamed: @"Queue"]];
929 [item setTarget: self];
930 [item setAction: @selector(showQueueWindow:)];
931 [item setAutovalidates: NO];
933 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
935 [item setLabel: @"Add to Queue"];
936 [item setPaletteLabel: @"Add to Queue"];
937 [item setToolTip: @"Add to Queue"];
938 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
939 [item setTarget: self];
940 [item setAction: @selector(addToQueue:)];
942 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
944 [item setLabel: @"Pause"];
945 [item setPaletteLabel: @"Pause Encoding"];
946 [item setToolTip: @"Pause Encoding"];
947 [item setImage: [NSImage imageNamed: @"Pause"]];
948 [item setTarget: self];
949 [item setAction: @selector(Pause:)];
951 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
953 [item setLabel: @"Picture Settings"];
954 [item setPaletteLabel: @"Show Picture Settings"];
955 [item setToolTip: @"Show Picture Settings"];
956 [item setImage: [NSImage imageNamed: @"pref-picture"]];
957 [item setTarget: self];
958 [item setAction: @selector(showPicturePanel:)];
960 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
962 [item setLabel: @"Activity Window"];
963 [item setPaletteLabel: @"Show Activity Window"];
964 [item setToolTip: @"Show Activity Window"];
965 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
966 [item setTarget: self];
967 [item setAction: @selector(showDebugOutputPanel:)];
968 [item setAutovalidates: NO];
970 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
972 [item setLabel: @"Source"];
973 [item setPaletteLabel: @"Source"];
974 [item setToolTip: @"Choose Video Source"];
975 [item setImage: [NSImage imageNamed: @"Source"]];
976 [item setTarget: self];
977 [item setAction: @selector(browseSources:)];
987 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
989 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
990 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
991 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
994 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
996 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
997 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
998 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
999 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1002 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1004 NSString * ident = [toolbarItem itemIdentifier];
1009 hb_get_state2( fQueueEncodeLibhb, &s );
1011 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
1013 if ([ident isEqualToString: StartEncodingIdentifier])
1015 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1016 [toolbarItem setLabel: @"Stop"];
1017 [toolbarItem setPaletteLabel: @"Stop"];
1018 [toolbarItem setToolTip: @"Stop Encoding"];
1021 if ([ident isEqualToString: PauseEncodingIdentifier])
1023 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1024 [toolbarItem setLabel: @"Pause"];
1025 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1026 [toolbarItem setToolTip: @"Pause Encoding"];
1031 if ([ident isEqualToString: AddToQueueIdentifier])
1033 if ([ident isEqualToString: ShowPictureIdentifier])
1037 else if (s.state == HB_STATE_PAUSED)
1039 if ([ident isEqualToString: PauseEncodingIdentifier])
1041 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1042 [toolbarItem setLabel: @"Resume"];
1043 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1044 [toolbarItem setToolTip: @"Resume Encoding"];
1047 if ([ident isEqualToString: StartEncodingIdentifier])
1049 if ([ident isEqualToString: AddToQueueIdentifier])
1051 if ([ident isEqualToString: ShowPictureIdentifier])
1054 else if (s.state == HB_STATE_SCANNING)
1056 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1058 if ([ident isEqualToString: StartEncodingIdentifier])
1060 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1061 if (hb_count(fHandle) > 0)
1062 [toolbarItem setLabel: @"Start Queue"];
1064 [toolbarItem setLabel: @"Start"];
1065 [toolbarItem setPaletteLabel: @"Start Encoding"];
1066 [toolbarItem setToolTip: @"Start Encoding"];
1069 if ([ident isEqualToString: AddToQueueIdentifier])
1071 if ([ident isEqualToString: ShowPictureIdentifier])
1076 /* If there are any pending queue items, make sure the start/stop button is active */
1077 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1079 if ([ident isEqualToString: ShowQueueIdentifier])
1081 if ([ident isEqualToString: ToggleDrawerIdentifier])
1083 if ([ident isEqualToString: ChooseSourceIdentifier])
1085 if ([ident isEqualToString: ShowActivityIdentifier])
1091 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1093 SEL action = [menuItem action];
1096 hb_get_state2( fHandle, &s );
1100 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1101 return SuccessfulScan && [fWindow attachedSheet] == nil;
1103 if (action == @selector(browseSources:))
1105 if (s.state == HB_STATE_SCANNING)
1108 return [fWindow attachedSheet] == nil;
1110 if (action == @selector(selectDefaultPreset:))
1111 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1112 if (action == @selector(Pause:))
1114 if (s.state == HB_STATE_WORKING)
1116 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1117 [menuItem setTitle:@"Pause Encoding"];
1120 else if (s.state == HB_STATE_PAUSED)
1122 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1123 [menuItem setTitle:@"Resume Encoding"];
1129 if (action == @selector(Rip:))
1131 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1133 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1134 [menuItem setTitle:@"Stop Encoding"];
1137 else if (SuccessfulScan)
1139 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1140 [menuItem setTitle:@"Start Encoding"];
1141 return [fWindow attachedSheet] == nil;
1147 if( action == @selector(setDefaultPreset:) )
1149 return [fPresetsOutlineView selectedRow] != -1;
1156 #pragma mark Encode Done Actions
1157 // register a test notification and make
1158 // it enabled by default
1159 #define SERVICE_NAME @"Encode Done"
1160 - (NSDictionary *)registrationDictionaryForGrowl
1162 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1163 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1164 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1167 return registrationDictionary;
1170 -(void)showGrowlDoneNotification:(NSString *) filePath
1172 /* This end of encode action is called as each encode rolls off of the queue */
1173 NSString * finishedEncode = filePath;
1174 /* strip off the path to just show the file name */
1175 finishedEncode = [finishedEncode lastPathComponent];
1176 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1177 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1179 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1180 [GrowlApplicationBridge
1181 notifyWithTitle:@"Put down that cocktail..."
1182 description:growlMssg
1183 notificationName:SERVICE_NAME
1191 -(void)sendToMetaX:(NSString *) filePath
1193 /* This end of encode action is called as each encode rolls off of the queue */
1194 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1196 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
1197 [myScript executeAndReturnError: nil];
1202 #pragma mark Get New Source
1204 /*Opens the source browse window, called from Open Source widgets */
1205 - (IBAction) browseSources: (id) sender
1207 NSOpenPanel * panel;
1209 panel = [NSOpenPanel openPanel];
1210 [panel setAllowsMultipleSelection: NO];
1211 [panel setCanChooseFiles: YES];
1212 [panel setCanChooseDirectories: YES ];
1213 NSString * sourceDirectory;
1214 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1216 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1220 sourceDirectory = @"~/Desktop";
1221 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1223 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1224 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1226 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1227 modalForWindow: fWindow modalDelegate: self
1228 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1229 contextInfo: sender];
1232 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1233 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1235 /* we convert the sender content of contextInfo back into a variable called sender
1236 * mostly just for consistency for evaluation later
1238 id sender = (id)contextInfo;
1239 /* User selected a file to open */
1240 if( returnCode == NSOKButton )
1242 /* Free display name allocated previously by this code */
1243 [browsedSourceDisplayName release];
1245 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1246 /* we set the last searched source directory in the prefs here */
1247 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1248 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1249 /* we order out sheet, which is the browse window as we need to open
1250 * the title selection sheet right away
1252 [sheet orderOut: self];
1254 if (sender == fOpenSourceTitleMMenu)
1256 /* We put the chosen source path in the source display text field for the
1257 * source title selection sheet in which the user specifies the specific title to be
1258 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1259 * purposes in the title panel
1262 [fScanSrcTitlePathField setStringValue:scanPath];
1263 NSString *displayTitlescanSourceName;
1265 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1267 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1268 we have to use the title->dvd value so we get the proper name of the volume if a physical dvd is the source*/
1269 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1273 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1274 displayTitlescanSourceName = [scanPath lastPathComponent];
1276 /* we set the source display name in the title selection dialogue */
1277 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1278 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1279 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1280 /* We show the actual sheet where the user specifies the title to be scanned
1281 * as we are going to do a title specific scan
1283 [self showSourceTitleScanPanel:nil];
1287 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1288 NSString *path = [[sheet filenames] objectAtIndex: 0];
1290 /* We check to see if the chosen file at path is a package */
1291 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1293 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1294 /* We check to see if this is an .eyetv package */
1295 if ([[path pathExtension] isEqualToString: @"eyetv"])
1297 [self writeToActivityLog:"trying to open eyetv package"];
1298 /* We're looking at an EyeTV package - try to open its enclosed
1300 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1302 int n = [[path stringByAppendingString: @"/"]
1303 completePathIntoString: &mpgname caseSensitive: NO
1304 matchesIntoArray: nil
1305 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1308 /* Found an mpeg inside the eyetv package, make it our scan path
1309 and call performScan on the enclosed mpeg */
1311 [self writeToActivityLog:"found mpeg in eyetv package"];
1312 [self performScan:path scanTitleNum:0];
1316 /* We did not find an mpeg file in our package, so we do not call performScan */
1317 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1320 /* We check to see if this is a .dvdmedia package */
1321 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1323 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1324 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1325 [self writeToActivityLog:"trying to open dvdmedia package"];
1326 [self performScan:path scanTitleNum:0];
1330 /* The package is not an eyetv package, so we do not call performScan */
1331 [self writeToActivityLog:"unable to open package"];
1334 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1336 /* path is not a package, so we call perform scan directly on our file */
1337 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1339 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1340 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1341 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1345 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1346 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1347 /* make sure we remove any path extension as this can also be an '.mpg' file */
1348 browsedSourceDisplayName = [[path lastPathComponent] retain];
1350 [self performScan:path scanTitleNum:0];
1358 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1359 - (IBAction) showSourceTitleScanPanel: (id) sender
1361 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1364 [fScanSrcTitleNumField setStringValue: @"0"];
1365 /* Show the panel */
1366 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1369 - (IBAction) closeSourceTitleScanPanel: (id) sender
1371 [NSApp endSheet: fScanSrcTitlePanel];
1372 [fScanSrcTitlePanel orderOut: self];
1374 if(sender == fScanSrcTitleOpenButton)
1376 /* We setup the scan status in the main window to indicate a source title scan */
1377 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1378 [fScanIndicator setHidden: NO];
1379 [fScanIndicator setIndeterminate: YES];
1380 [fScanIndicator startAnimation: nil];
1382 /* We use the performScan method to actually perform the specified scan passing the path and the title
1385 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1389 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1390 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1392 /* set the bool applyQueueToScan so that we dont apply a queue setting to the final scan */
1393 applyQueueToScan = NO;
1394 /* use a bool to determine whether or not we can decrypt using vlc */
1395 BOOL cancelScanDecrypt = 0;
1396 NSString *path = scanPath;
1397 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1399 // Notify ChapterTitles that there's no title
1400 [fChapterTitlesDelegate resetWithTitle:nil];
1401 [fChapterTable reloadData];
1403 [self enableUI: NO];
1405 if( [detector isVideoDVD] )
1407 // The chosen path was actually on a DVD, so use the raw block
1408 // device path instead.
1409 path = [detector devicePath];
1410 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1412 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1413 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1414 NSFileManager * fileManager = [NSFileManager defaultManager];
1415 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1417 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1418 cancelScanDecrypt = 1;
1419 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1421 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");
1422 [NSApp requestUserAttention:NSCriticalRequest];
1424 if (status == NSAlertDefaultReturn)
1426 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1427 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
1429 else if (status == NSAlertAlternateReturn)
1431 /* User chose to cancel the scan */
1432 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1436 /* 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 */
1437 cancelScanDecrypt = 0;
1438 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1444 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1445 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1449 if (cancelScanDecrypt == 0)
1451 /* we actually pass the scan off to libhb here */
1452 /* If there is no title number passed to scan, we use "0"
1453 * which causes the default behavior of a full source scan
1459 if (scanTitleNum > 0)
1461 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1463 /* We use our advance pref to determine how many previews to scan */
1464 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1465 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1466 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1470 - (IBAction) showNewScan:(id)sender
1474 int indxpri=0; // Used to search the longuest title (default in combobox)
1475 int longuestpri=0; // Used to search the longuest title (default in combobox)
1478 list = hb_get_titles( fHandle );
1480 if( !hb_list_count( list ) )
1482 /* We display a message if a valid dvd source was not chosen */
1483 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1484 SuccessfulScan = NO;
1486 // Notify ChapterTitles that there's no title
1487 [fChapterTitlesDelegate resetWithTitle:nil];
1488 [fChapterTable reloadData];
1492 /* We increment the successful scancount here by one,
1493 which we use at the end of this function to tell the gui
1494 if this is the first successful scan since launch and whether
1495 or not we should set all settings to the defaults */
1497 currentSuccessfulScanCount++;
1499 [[fWindow toolbar] validateVisibleItems];
1501 [fSrcTitlePopUp removeAllItems];
1502 for( int i = 0; i < hb_list_count( list ); i++ )
1504 title = (hb_title_t *) hb_list_item( list, i );
1506 currentSource = [NSString stringWithUTF8String: title->name];
1507 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1508 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1510 /* Use the dvd name in the default output field here
1511 May want to add code to remove blank spaces for some dvd names*/
1512 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1513 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1515 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1516 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1520 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1521 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1525 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1527 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1531 [fSrcTitlePopUp addItemWithTitle: [NSString
1532 stringWithFormat: @"%d - %02dh%02dm%02ds",
1533 title->index, title->hours, title->minutes,
1537 // Select the longuest title
1538 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1539 [self titlePopUpChanged:nil];
1541 SuccessfulScan = YES;
1542 [self enableUI: YES];
1544 /* if its the initial successful scan after awakeFromNib */
1545 if (currentSuccessfulScanCount == 1)
1547 [self selectDefaultPreset:nil];
1549 [fPictureFilterController setInitialPictureFilters];
1551 // Open preview window now if it was visible when HB was closed
1552 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1553 [self showPreviewWindow:nil];
1555 // Open picture sizing window now if it was visible when HB was closed
1556 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1557 [self showPicturePanel:nil];
1559 // Open filters window now if it was visible when HB was closed
1560 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureFiltersWindowIsOpen"])
1561 [self showFiltersPanel:nil];
1571 #pragma mark New Output Destination
1573 - (IBAction) browseFile: (id) sender
1575 /* Open a panel to let the user choose and update the text field */
1576 NSSavePanel * panel = [NSSavePanel savePanel];
1577 /* We get the current file name and path from the destination field here */
1578 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1579 modalForWindow: fWindow modalDelegate: self
1580 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1584 - (void) browseFileDone: (NSSavePanel *) sheet
1585 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1587 if( returnCode == NSOKButton )
1589 [fDstFile2Field setStringValue: [sheet filename]];
1590 /* Save this path to the prefs so that on next browse destination window it opens there */
1591 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1592 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1598 #pragma mark Main Window Control
1600 - (IBAction) openMainWindow: (id) sender
1602 [fWindow makeKeyAndOrderFront:nil];
1605 - (BOOL) windowShouldClose: (id) sender
1610 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1613 [fWindow makeKeyAndOrderFront:nil];
1621 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1622 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1627 #pragma mark Queue File
1629 - (void) loadQueueFile {
1630 /* We declare the default NSFileManager into fileManager */
1631 NSFileManager * fileManager = [NSFileManager defaultManager];
1632 /*We define the location of the user presets file */
1633 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1634 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1635 /* We check for the presets.plist */
1636 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1638 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1641 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1642 /* lets check to see if there is anything in the queue file .plist */
1643 if (nil == QueueFileArray)
1645 /* if not, then lets initialize an empty array */
1646 QueueFileArray = [[NSMutableArray alloc] init];
1648 /* Initialize our curQueueEncodeIndex to 0
1649 * so we can use it to track which queue
1650 * item is to be used to track our encodes */
1651 /* NOTE: this should be changed if and when we
1652 * are able to get the last unfinished encode
1653 * in the case of a crash or shutdown */
1658 [self clearQueueEncodedItems];
1660 currentQueueEncodeIndex = 0;
1663 - (void)addQueueFileItem
1665 [QueueFileArray addObject:[self createQueueFileItem]];
1666 [self saveQueueFileItem];
1670 - (void) removeQueueFileItem:(int) queueItemToRemove
1673 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
1674 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
1676 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
1677 * by one to keep in sync with the queue array
1679 currentQueueEncodeIndex--;
1680 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
1682 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1683 [self saveQueueFileItem];
1687 - (void)saveQueueFileItem
1689 [QueueFileArray writeToFile:QueueFile atomically:YES];
1690 [fQueueController setQueueArray: QueueFileArray];
1691 [self getQueueStats];
1694 - (void)getQueueStats
1696 /* lets get the stats on the status of the queue array */
1698 fEncodingQueueItem = 0;
1700 fCompletedCount = 0;
1704 /* We use a number system to set the encode status of the queue item
1706 * 0 == already encoded
1707 * 1 == is being encoded
1708 * 2 == is yet to be encoded
1713 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1715 while (tempObject = [enumerator nextObject])
1717 NSDictionary *thisQueueDict = tempObject;
1718 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1722 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1725 fEncodingQueueItem = i;
1727 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
1731 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
1738 /* Set the queue status field in the main window */
1739 NSMutableString * string;
1740 if (fPendingCount == 1)
1742 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
1746 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
1748 [fQueueStatus setStringValue:string];
1751 /* This method will set any item marked as encoding back to pending
1752 * currently used right after a queue reload
1754 - (void) setQueueEncodingItemsAsPending
1756 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1758 NSMutableArray *tempArray;
1759 tempArray = [NSMutableArray array];
1760 /* we look here to see if the preset is we move on to the next one */
1761 while ( tempObject = [enumerator nextObject] )
1763 /* If the queue item is marked as "encoding" (1)
1764 * then change its status back to pending (2) which effectively
1765 * puts it back into the queue to be encoded
1767 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
1769 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
1771 [tempArray addObject:tempObject];
1774 [QueueFileArray setArray:tempArray];
1775 [self saveQueueFileItem];
1779 /* This method will clear the queue of any encodes that are not still pending
1780 * this includes both successfully completed encodes as well as cancelled encodes */
1781 - (void) clearQueueEncodedItems
1783 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1785 NSMutableArray *tempArray;
1786 tempArray = [NSMutableArray array];
1787 /* we look here to see if the preset is we move on to the next one */
1788 while ( tempObject = [enumerator nextObject] )
1790 /* If the queue item is either completed (0) or cancelled (3) from the
1791 * last session, then we put it in tempArray to be deleted from QueueFileArray.
1792 * NOTE: this means we retain pending (2) and also an item that is marked as
1793 * still encoding (1). If the queue has an item that is still marked as encoding
1794 * from a previous session, we can conlude that HB was either shutdown, or crashed
1795 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
1797 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
1799 [tempArray addObject:tempObject];
1803 [QueueFileArray removeObjectsInArray:tempArray];
1804 [self saveQueueFileItem];
1807 /* This method will clear the queue of all encodes. effectively creating an empty queue */
1808 - (void) clearQueueAllItems
1810 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1812 NSMutableArray *tempArray;
1813 tempArray = [NSMutableArray array];
1814 /* we look here to see if the preset is we move on to the next one */
1815 while ( tempObject = [enumerator nextObject] )
1817 [tempArray addObject:tempObject];
1820 [QueueFileArray removeObjectsInArray:tempArray];
1821 [self saveQueueFileItem];
1824 /* This method will duplicate prepareJob however into the
1825 * queue .plist instead of into the job structure so it can
1826 * be recalled later */
1827 - (NSDictionary *)createQueueFileItem
1829 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
1831 hb_list_t * list = hb_get_titles( fHandle );
1832 hb_title_t * title = (hb_title_t *) hb_list_item( list,
1833 [fSrcTitlePopUp indexOfSelectedItem] );
1834 hb_job_t * job = title->job;
1838 /* We use a number system to set the encode status of the queue item
1839 * 0 == already encoded
1840 * 1 == is being encoded
1841 * 2 == is yet to be encoded
1844 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
1845 /* Source and Destination Information */
1847 [queueFileJob setObject:[NSString stringWithUTF8String: title->dvd] forKey:@"SourcePath"];
1848 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
1849 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
1850 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
1852 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
1854 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
1856 /* Lets get the preset info if there is any */
1857 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
1858 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
1860 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
1861 /* Chapter Markers fCreateChapterMarkers*/
1862 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
1864 /* We need to get the list of chapter names to put into an array and store
1865 * in our queue, so they can be reapplied in prepareJob when this queue
1866 * item comes up if Chapter Markers is set to on.
1869 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
1870 int chaptercount = hb_list_count( fTitle->list_chapter );
1871 for( i = 0; i < chaptercount; i++ )
1873 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
1874 if( chapter != NULL )
1876 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
1879 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
1880 [ChapterNamesArray autorelease];
1882 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
1883 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
1884 /* Mux mp4 with http optimization */
1885 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
1886 /* Add iPod uuid atom */
1887 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
1891 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
1892 /* x264 Option String */
1893 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
1895 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
1896 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
1897 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
1898 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
1900 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
1902 /* 2 Pass Encoding */
1903 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
1904 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
1905 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
1907 /* Picture Sizing */
1908 /* Use Max Picture settings for whatever the dvd is.*/
1909 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1910 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1911 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1912 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1913 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
1914 NSString * pictureSummary;
1915 pictureSummary = [fPictureSizeField stringValue];
1916 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
1917 /* Set crop settings here */
1918 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
1919 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
1920 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
1921 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
1922 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
1924 /* Picture Filters */
1925 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController detelecine]] forKey:@"PictureDetelecine"];
1926 [queueFileJob setObject:[fPictureFilterController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
1928 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController useDecomb]] forKey:@"PictureDecombDeinterlace"];
1929 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController decomb]] forKey:@"PictureDecomb"];
1930 [queueFileJob setObject:[fPictureFilterController decombCustomString] forKey:@"PictureDecombCustom"];
1932 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController deinterlace]] forKey:@"PictureDeinterlace"];
1933 [queueFileJob setObject:[fPictureFilterController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
1935 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController denoise]] forKey:@"PictureDenoise"];
1936 [queueFileJob setObject:[fPictureFilterController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
1938 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureFilterController deblock]] forKey:@"PictureDeblock"];
1940 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureFilterController grayscale]] forKey:@"VideoGrayScale"];
1943 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
1945 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
1946 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
1947 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
1948 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
1949 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
1950 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
1951 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
1953 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
1955 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
1956 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
1957 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
1958 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
1959 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
1960 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
1961 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
1963 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
1965 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
1966 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
1967 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
1968 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
1969 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
1970 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
1971 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
1973 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
1975 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
1976 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
1977 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
1978 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
1979 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
1980 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
1981 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
1985 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
1986 [queueFileJob setObject:[NSNumber numberWithInt:[fSubPopUp indexOfSelectedItem]] forKey:@"JobSubtitlesIndex"];
1987 /* Forced Subtitles */
1988 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
1992 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
1994 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
1996 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
1999 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2003 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2006 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2007 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2008 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2010 /* Picture Sizing */
2011 /* Use Max Picture settings for whatever the dvd is.*/
2012 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2013 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2014 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2015 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2016 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2018 /* Set crop settings here */
2019 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2020 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2021 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2022 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2023 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2025 /* Picture Filters */
2026 //[queueFileJob setObject:[fPicSettingDecomb stringValue] forKey:@"JobPictureDecomb"];
2029 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2031 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2032 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2033 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2034 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2035 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2037 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2039 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2040 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2041 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2042 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2043 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2045 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2047 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2048 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2049 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2050 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2051 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2053 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2055 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2056 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2057 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2058 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2059 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2062 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
2063 /* Forced Subtitles */
2064 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
2066 /* we need to auto relase the queueFileJob and return it */
2067 [queueFileJob autorelease];
2068 return queueFileJob;
2072 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2073 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2075 NSUInteger index = [indexSet lastIndex];
2076 NSUInteger aboveInsertIndexCount = 0;
2079 NSUInteger removeIndex;
2081 if (index >= insertIndex)
2083 removeIndex = index + aboveInsertIndexCount;
2084 aboveInsertIndexCount++;
2088 removeIndex = index;
2092 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2093 [QueueFileArray removeObjectAtIndex:removeIndex];
2094 [QueueFileArray insertObject:object atIndex:insertIndex];
2097 index = [indexSet indexLessThanIndex:index];
2099 /* We save all of the Queue data here
2100 * and it also gets sent back to the queue controller*/
2101 [self saveQueueFileItem];
2107 #pragma mark Queue Job Processing
2109 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2111 int i = currentQueueEncodeIndex;
2112 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2114 /* We save all of the Queue data here */
2115 [self saveQueueFileItem];
2116 /* We Reload the New Table data for presets */
2117 //[fPresetsOutlineView reloadData];
2119 /* Since we have now marked a queue item as done
2120 * we can go ahead and increment currentQueueEncodeIndex
2121 * so that if there is anything left in the queue we can
2122 * go ahead and move to the next item if we want to */
2123 currentQueueEncodeIndex++ ;
2124 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2125 int queueItems = [QueueFileArray count];
2126 /* If we still have more items in our queue, lets go to the next one */
2127 if (currentQueueEncodeIndex < queueItems)
2129 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2130 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2134 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2138 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2139 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2141 /* Tell HB to output a new activity log file for this encode */
2142 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2145 /* use a bool to determine whether or not we can decrypt using vlc */
2146 BOOL cancelScanDecrypt = 0;
2147 /* set the bool so that showNewScan knows to apply the appropriate queue
2148 * settings as this is a queue rescan
2150 applyQueueToScan = YES;
2151 NSString *path = scanPath;
2152 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2154 /*On Screen Notification*/
2156 //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2157 //[NSApp requestUserAttention:NSCriticalRequest];
2159 if( [detector isVideoDVD] )
2161 // The chosen path was actually on a DVD, so use the raw block
2162 // device path instead.
2163 path = [detector devicePath];
2164 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2166 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2167 NSString *vlcPath = @"/Applications/VLC.app";
2168 NSFileManager * fileManager = [NSFileManager defaultManager];
2169 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2171 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2172 cancelScanDecrypt = 1;
2173 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2175 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");
2176 [NSApp requestUserAttention:NSCriticalRequest];
2178 if (status == NSAlertDefaultReturn)
2180 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2181 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2183 else if (status == NSAlertAlternateReturn)
2185 /* User chose to cancel the scan */
2186 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2190 /* 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 */
2191 cancelScanDecrypt = 0;
2192 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2198 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2199 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2203 if (cancelScanDecrypt == 0)
2205 /* we actually pass the scan off to libhb here */
2206 /* If there is no title number passed to scan, we use "0"
2207 * which causes the default behavior of a full source scan
2213 if (scanTitleNum > 0)
2215 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2218 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2219 /* We use our advance pref to determine how many previews to scan */
2220 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2221 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2225 /* This method was originally used to load up a new queue item in the gui and
2226 * then start processing it. However we now have modified -prepareJob and use a second
2227 * instance of libhb to do our actual encoding, therefor right now it is not required.
2228 * Nonetheless I want to leave this in here
2229 * because basically its everything we need to be able to actually modify a pending queue
2230 * item in the gui and resave it. At least for now - dynaflash
2233 - (IBAction)applyQueueSettings:(id)sender
2235 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2236 hb_job_t * job = fTitle->job;
2238 /* Set title number and chapters */
2239 /* since the queue only scans a single title, we really don't need to pick a title */
2240 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2242 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2243 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2246 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2247 [self formatPopUpChanged:nil];
2249 /* Chapter Markers*/
2250 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2251 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2252 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2253 /* Mux mp4 with http optimization */
2254 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2257 /* We set the advanced opt string here if applicable*/
2258 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2259 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2261 /* Lets run through the following functions to get variables set there */
2262 [self videoEncoderPopUpChanged:nil];
2263 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2264 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2265 [self calculateBitrate:nil];
2268 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2270 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2271 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2272 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2274 [self videoMatrixChanged:nil];
2276 /* Video framerate */
2277 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2278 detected framerate in the fVidRatePopUp so we use index 0*/
2279 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2281 [fVidRatePopUp selectItemAtIndex: 0];
2285 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2288 /* 2 Pass Encoding */
2289 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2290 [self twoPassCheckboxChanged:nil];
2291 /* Turbo 1st pass for 2 Pass Encoding */
2292 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2295 if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2297 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2299 [fAudLang1PopUp selectItemAtIndex: 1];
2301 [self audioTrackPopUpChanged: fAudLang1PopUp];
2302 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2303 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2304 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2305 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2307 if ([fAudTrack1MixPopUp selectedItem] == nil)
2309 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2311 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2312 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2313 if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2315 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2317 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2318 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2320 if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2322 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2324 [fAudLang2PopUp selectItemAtIndex: 1];
2326 [self audioTrackPopUpChanged: fAudLang2PopUp];
2327 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2328 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2329 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2330 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2332 if ([fAudTrack2MixPopUp selectedItem] == nil)
2334 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2336 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2337 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2338 if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2340 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2342 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2343 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2345 if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2347 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2349 [fAudLang3PopUp selectItemAtIndex: 1];
2351 [self audioTrackPopUpChanged: fAudLang3PopUp];
2352 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2353 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2354 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2355 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2357 if ([fAudTrack3MixPopUp selectedItem] == nil)
2359 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2361 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2362 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2363 if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2365 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2367 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2368 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2370 if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2372 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2374 [fAudLang4PopUp selectItemAtIndex: 1];
2376 [self audioTrackPopUpChanged: fAudLang4PopUp];
2377 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2378 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2379 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2380 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2382 if ([fAudTrack4MixPopUp selectedItem] == nil)
2384 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2386 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2387 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2388 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2390 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2392 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2393 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2398 [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2399 /* Forced Subtitles */
2400 [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2402 /* Picture Settings */
2403 /* we check to make sure the presets width/height does not exceed the sources width/height */
2404 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2406 /* if so, then we use the sources height and width to avoid scaling up */
2407 job->width = fTitle->width;
2408 job->height = fTitle->height;
2410 else // source width/height is >= the preset height/width
2412 /* we can go ahead and use the presets values for height and width */
2413 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2414 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2416 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2417 if (job->keep_ratio == 1)
2419 hb_fix_aspect( job, HB_KEEP_WIDTH );
2420 if( job->height > fTitle->height )
2422 job->height = fTitle->height;
2423 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2426 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2429 /* If Cropping is set to custom, then recall all four crop values from
2430 when the preset was created and apply them */
2431 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2433 [fPictureController setAutoCrop:NO];
2435 /* Here we use the custom crop values saved at the time the preset was saved */
2436 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2437 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2438 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2439 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2442 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2444 [fPictureController setAutoCrop:YES];
2445 /* Here we use the auto crop values determined right after scan */
2446 job->crop[0] = AutoCropTop;
2447 job->crop[1] = AutoCropBottom;
2448 job->crop[2] = AutoCropLeft;
2449 job->crop[3] = AutoCropRight;
2455 [fPictureFilterController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2458 [fPictureFilterController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2460 [fPictureFilterController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2462 [fPictureFilterController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2464 [fPictureFilterController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2466 [fPictureFilterController setGrayscale:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2468 [self calculatePictureSizing:nil];
2471 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2472 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2473 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2474 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2476 /* Deselect the currently selected Preset if there is one*/
2477 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2478 //[self selectPreset:nil];
2480 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2481 /* Change UI to show "Custom" settings are being used */
2482 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2484 curUserPresetChosenNum = nil;
2488 /* Deselect the currently selected Preset if there is one*/
2489 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2490 /* Change UI to show "Custom" settings are being used */
2491 [fPresetSelectedDisplay setStringValue: @"Custom"];
2493 //curUserPresetChosenNum = nil;
2496 /* We need to set this bool back to NO, in case the user wants to do a scan */
2497 //applyQueueToScan = NO;
2499 /* so now we go ahead and process the new settings */
2500 [self processNewQueueEncode];
2505 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2506 - (void) processNewQueueEncode
2508 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2509 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2510 hb_job_t * job = title->job;
2512 if( !hb_list_count( list ) )
2514 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2518 [self writeToActivityLog: "processNewQueueEncode title list is: %d", hb_list_count( list )];
2521 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2522 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2523 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2524 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2525 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2527 if( [[queueToApply objectForKey:@"SubtitlesForced"] intValue] == 1 )
2528 job->subtitle_force = 1;
2530 job->subtitle_force = 0;
2533 * subtitle of -1 is a scan
2535 if( job->subtitle == -1 )
2540 * When subtitle scan is enabled do a fast pre-scan job
2541 * which will determine which subtitles to enable, if any.
2544 x264opts_tmp = job->x264opts;
2547 job->x264opts = NULL;
2549 job->indepth_scan = 1;
2551 job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
2552 *(job->select_subtitle) = NULL;
2555 * Add the pre-scan job
2557 hb_add( fQueueEncodeLibhb, job );
2558 job->x264opts = x264opts_tmp;
2561 job->select_subtitle = NULL;
2563 /* No subtitle were selected, so reset the subtitle to -1 (which before
2564 * this point meant we were scanning
2566 if( job->subtitle == -2 )
2569 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2571 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
2572 job->indepth_scan = 0;
2575 * Do not autoselect subtitles on the first pass of a two pass
2577 job->select_subtitle = NULL;
2581 hb_add( fQueueEncodeLibhb, job );
2585 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2586 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2588 job->select_subtitle = subtitle_tmp;
2590 hb_add( fQueueEncodeLibhb, job );
2595 job->indepth_scan = 0;
2598 hb_add( fQueueEncodeLibhb, job );
2601 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2602 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2603 /* Lets mark our new encode as 1 or "Encoding" */
2604 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2605 [self saveQueueFileItem];
2606 /* We should be all setup so let 'er rip */
2611 #pragma mark Live Preview
2612 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2613 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2616 - (void) prepareJobForPreview
2618 hb_list_t * list = hb_get_titles( fHandle );
2619 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2620 [fSrcTitlePopUp indexOfSelectedItem] );
2621 hb_job_t * job = title->job;
2622 hb_audio_config_t * audio;
2624 /* Chapter selection */
2625 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
2626 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
2628 /* Format (Muxer) and Video Encoder */
2629 job->mux = [[fDstFormatPopUp selectedItem] tag];
2630 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
2632 job->chapter_markers = 0;
2634 if( job->vcodec & HB_VCODEC_X264 )
2636 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2637 Currently only used with Constant Quality setting*/
2638 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
2643 /* Below Sends x264 options to the core library if x264 is selected*/
2644 /* Lets use this as per Nyx, Thanks Nyx!*/
2645 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2646 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
2647 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
2652 /* Video settings */
2653 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
2654 * and detelecine is on, so we handle that in the logic below
2657 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
2659 /* a specific framerate has been chosen */
2660 job->vrate = 27000000;
2661 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
2662 /* We are not same as source so we set job->cfr to 1
2663 * to enable constant frame rate since user has specified
2664 * a specific framerate*/
2669 /* We are same as source (variable) */
2670 job->vrate = title->rate;
2671 job->vrate_base = title->rate_base;
2672 /* We are same as source so we set job->cfr to 0
2673 * to enable true same as source framerate */
2675 /* If we are same as source and we have detelecine on, we need to turn on
2678 if ([fPictureFilterController detelecine] == 1)
2684 switch( [fVidQualityMatrix selectedRow] )
2688 Bitrate should already have been calculated and displayed
2689 in fVidBitrateField, so let's just use it */
2691 job->vquality = -1.0;
2692 job->vbitrate = [fVidBitrateField intValue];
2695 job->vquality = [fVidQualityRFField floatValue];
2700 /* Subtitle settings */
2701 job->subtitle = [fSubPopUp indexOfSelectedItem] - 2;
2703 /* Audio tracks and mixdowns */
2704 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
2705 int audiotrack_count = hb_list_count(job->list_audio);
2706 for( int i = 0; i < audiotrack_count;i++)
2708 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
2709 hb_list_rem(job->list_audio, temp_audio);
2711 /* Now lets add our new tracks to the audio list here */
2712 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2714 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2715 hb_audio_config_init(audio);
2716 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2717 /* We go ahead and assign values to our audio->out.<properties> */
2718 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2719 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
2720 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
2721 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
2722 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
2723 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
2725 hb_audio_add( job, audio );
2728 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2730 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2731 hb_audio_config_init(audio);
2732 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2733 /* We go ahead and assign values to our audio->out.<properties> */
2734 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2735 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
2736 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
2737 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
2738 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
2739 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
2741 hb_audio_add( job, audio );
2746 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2748 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2749 hb_audio_config_init(audio);
2750 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2751 /* We go ahead and assign values to our audio->out.<properties> */
2752 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2753 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
2754 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
2755 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
2756 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
2757 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
2759 hb_audio_add( job, audio );
2764 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2766 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2767 hb_audio_config_init(audio);
2768 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2769 /* We go ahead and assign values to our audio->out.<properties> */
2770 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2771 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
2772 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
2773 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
2774 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
2775 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
2777 hb_audio_add( job, audio );
2786 /* Though Grayscale is not really a filter, per se
2787 * we put it here since its in the filters panel
2790 if ([fPictureFilterController grayscale])
2799 /* Initialize the filters list */
2800 job->filters = hb_list_init();
2802 /* Now lets call the filters if applicable.
2803 * The order of the filters is critical
2807 if ([fPictureFilterController detelecine] == 1)
2809 hb_list_add( job->filters, &hb_filter_detelecine );
2811 if ([fPictureFilterController detelecine] == 2)
2813 /* use a custom detelecine string */
2814 hb_filter_detelecine.settings = (char *) [[fPictureFilterController detelecineCustomString] UTF8String];
2815 hb_list_add( job->filters, &hb_filter_detelecine );
2817 if ([fPictureFilterController useDecomb] == 1)
2820 if ([fPictureFilterController decomb] == 1)
2822 /* Run old deinterlacer fd by default */
2823 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
2824 hb_list_add( job->filters, &hb_filter_decomb );
2826 /* we add the custom string if present */
2827 if ([fPictureFilterController decomb] == 2)
2829 /* use a custom decomb string */
2830 hb_filter_decomb.settings = (char *) [[fPictureFilterController decombCustomString] UTF8String];
2831 hb_list_add( job->filters, &hb_filter_decomb );
2838 if ([fPictureFilterController deinterlace] == 1)
2840 /* Run old deinterlacer fd by default */
2841 hb_filter_deinterlace.settings = "-1";
2842 hb_list_add( job->filters, &hb_filter_deinterlace );
2844 else if ([fPictureFilterController deinterlace] == 2)
2846 /* Yadif mode 0 (without spatial deinterlacing.) */
2847 hb_filter_deinterlace.settings = "2";
2848 hb_list_add( job->filters, &hb_filter_deinterlace );
2850 else if ([fPictureFilterController deinterlace] == 3)
2852 /* Yadif (with spatial deinterlacing) */
2853 hb_filter_deinterlace.settings = "0";
2854 hb_list_add( job->filters, &hb_filter_deinterlace );
2856 else if ([fPictureFilterController deinterlace] == 4)
2858 /* we add the custom string if present */
2859 hb_filter_deinterlace.settings = (char *) [[fPictureFilterController deinterlaceCustomString] UTF8String];
2860 hb_list_add( job->filters, &hb_filter_deinterlace );
2865 if ([fPictureFilterController denoise] == 1) // Weak in popup
2867 hb_filter_denoise.settings = "2:1:2:3";
2868 hb_list_add( job->filters, &hb_filter_denoise );
2870 else if ([fPictureFilterController denoise] == 2) // Medium in popup
2872 hb_filter_denoise.settings = "3:2:2:3";
2873 hb_list_add( job->filters, &hb_filter_denoise );
2875 else if ([fPictureFilterController denoise] == 3) // Strong in popup
2877 hb_filter_denoise.settings = "7:7:5:5";
2878 hb_list_add( job->filters, &hb_filter_denoise );
2880 else if ([fPictureFilterController denoise] == 4) // custom in popup
2882 /* we add the custom string if present */
2883 hb_filter_denoise.settings = (char *) [[fPictureFilterController denoiseCustomString] UTF8String];
2884 hb_list_add( job->filters, &hb_filter_denoise );
2887 /* Deblock (uses pp7 default) */
2888 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
2889 * the macgui's purposes a value of 0 actually means to not even use the filter
2890 * current hb_filter_deblock.settings valid ranges are from 5 - 15
2892 if ([fPictureFilterController deblock] != 0)
2894 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureFilterController deblock]];
2895 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
2896 hb_list_add( job->filters, &hb_filter_deblock );
2903 #pragma mark Job Handling
2909 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2910 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2911 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2912 hb_job_t * job = title->job;
2913 hb_audio_config_t * audio;
2914 /* Chapter selection */
2915 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
2916 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
2918 /* Format (Muxer) and Video Encoder */
2919 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
2920 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
2923 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
2924 //if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
2926 /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
2927 mpeg4 and the checkbox being checked
2928 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
2929 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
2931 job->largeFileSize = 1;
2935 job->largeFileSize = 0;
2937 /* We set http optimized mp4 here */
2938 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
2940 job->mp4_optimize = 1;
2944 job->mp4_optimize = 0;
2949 /* We set the chapter marker extraction here based on the format being
2950 mpeg4 or mkv and the checkbox being checked */
2951 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
2953 job->chapter_markers = 1;
2955 /* now lets get our saved chapter names out the array in the queue file
2956 * and insert them back into the title chapter list. We have it here,
2957 * because unless we are inserting chapter markers there is no need to
2958 * spend the overhead of iterating through the chapter names array imo
2959 * Also, note that if for some reason we don't apply chapter names, the
2960 * chapters just come out 001, 002, etc. etc.
2963 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
2965 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
2967 while (tempObject = [enumerator nextObject])
2969 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
2970 if( chapter != NULL )
2972 strncpy( chapter->title, [tempObject UTF8String], 1023);
2973 chapter->title[1023] = '\0';
2980 job->chapter_markers = 0;
2983 if( job->vcodec & HB_VCODEC_X264 )
2985 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
2994 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2995 Currently only used with Constant Quality setting*/
2996 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2)
3000 /* Below Sends x264 options to the core library if x264 is selected*/
3001 /* Lets use this as per Nyx, Thanks Nyx!*/
3002 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3003 /* Turbo first pass if two pass and Turbo First pass is selected */
3004 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3006 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3007 NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3008 /* append the "Turbo" string variable to the existing opts string.
3009 Note: the "Turbo" string must be appended, not prepended to work properly*/
3010 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3011 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3015 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3021 /* Picture Size Settings */
3022 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3023 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3025 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3026 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3029 /* Here we use the crop values saved at the time the preset was saved */
3030 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3031 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3032 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3033 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3035 /* Video settings */
3038 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3039 * and detelecine is on, so we handle that in the logic below
3042 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3044 /* a specific framerate has been chosen */
3045 job->vrate = 27000000;
3046 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3047 /* We are not same as source so we set job->cfr to 1
3048 * to enable constant frame rate since user has specified
3049 * a specific framerate*/
3054 /* We are same as source (variable) */
3055 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3056 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3057 /* We are same as source so we set job->cfr to 0
3058 * to enable true same as source framerate */
3060 /* If we are same as source and we have detelecine on, we need to turn on
3063 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3069 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3072 Bitrate should already have been calculated and displayed
3073 in fVidBitrateField, so let's just use it same as abr*/
3074 job->vquality = -1.0;
3075 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3077 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3079 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3084 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3085 /* Subtitle settings */
3086 job->subtitle = [[queueToApply objectForKey:@"JobSubtitlesIndex"] intValue] - 2;
3088 /* Audio tracks and mixdowns */
3089 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3090 int audiotrack_count = hb_list_count(job->list_audio);
3091 for( int i = 0; i < audiotrack_count;i++)
3093 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3094 hb_list_rem(job->list_audio, temp_audio);
3096 /* Now lets add our new tracks to the audio list here */
3097 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3099 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3100 hb_audio_config_init(audio);
3101 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3102 /* We go ahead and assign values to our audio->out.<properties> */
3103 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3104 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3105 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3106 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3107 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3108 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3110 hb_audio_add( job, audio );
3113 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3116 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3117 hb_audio_config_init(audio);
3118 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3119 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3120 /* We go ahead and assign values to our audio->out.<properties> */
3121 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3122 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3123 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3124 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3125 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3126 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3128 hb_audio_add( job, audio );
3132 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3134 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3135 hb_audio_config_init(audio);
3136 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3137 /* We go ahead and assign values to our audio->out.<properties> */
3138 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3139 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3140 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3141 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3142 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3143 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3145 hb_audio_add( job, audio );
3149 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3151 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3152 hb_audio_config_init(audio);
3153 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3154 /* We go ahead and assign values to our audio->out.<properties> */
3155 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3156 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3157 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3158 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3159 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3160 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3162 hb_audio_add( job, audio );
3167 job->filters = hb_list_init();
3169 /* Now lets call the filters if applicable.
3170 * The order of the filters is critical
3173 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3175 //if ([queueToApply objectForKey:@"PictureDetelecineCustom"])
3176 hb_list_add( job->filters, &hb_filter_detelecine );
3178 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3180 /* use a custom detelecine string */
3181 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3182 hb_list_add( job->filters, &hb_filter_detelecine );
3185 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3188 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3190 /* Run old deinterlacer fd by default */
3191 hb_list_add( job->filters, &hb_filter_decomb );
3193 /* we add the custom string if present */
3194 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3196 /* use a custom decomb string */
3197 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3198 hb_list_add( job->filters, &hb_filter_decomb );
3206 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3208 /* Run old deinterlacer fd by default */
3209 hb_filter_deinterlace.settings = "-1";
3210 hb_list_add( job->filters, &hb_filter_deinterlace );
3212 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3214 /* Yadif mode 0 (without spatial deinterlacing.) */
3215 hb_filter_deinterlace.settings = "2";
3216 hb_list_add( job->filters, &hb_filter_deinterlace );
3218 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3220 /* Yadif (with spatial deinterlacing) */
3221 hb_filter_deinterlace.settings = "0";
3222 hb_list_add( job->filters, &hb_filter_deinterlace );
3224 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3226 /* we add the custom string if present */
3227 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3228 hb_list_add( job->filters, &hb_filter_deinterlace );
3234 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Weak in popup
3236 hb_filter_denoise.settings = "2:1:2:3";
3237 hb_list_add( job->filters, &hb_filter_denoise );
3239 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Medium in popup
3241 hb_filter_denoise.settings = "3:2:2:3";
3242 hb_list_add( job->filters, &hb_filter_denoise );
3244 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Strong in popup
3246 hb_filter_denoise.settings = "7:7:5:5";
3247 hb_list_add( job->filters, &hb_filter_denoise );
3249 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Custom in popup
3251 /* we add the custom string if present */
3252 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3253 hb_list_add( job->filters, &hb_filter_denoise );
3256 /* Deblock (uses pp7 default) */
3257 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3258 * the macgui's purposes a value of 0 actually means to not even use the filter
3259 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3261 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3263 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3264 hb_list_add( job->filters, &hb_filter_deblock );
3266 [self writeToActivityLog: "prepareJob exiting"];
3271 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3273 - (IBAction) addToQueue: (id) sender
3275 /* We get the destination directory from the destination field here */
3276 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3277 /* We check for a valid destination here */
3278 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3280 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3287 BOOL fileExistsInQueue;
3288 fileExistsInQueue = NO;
3290 /* We check for and existing file here */
3291 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3296 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3298 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3300 while (tempObject = [enumerator nextObject])
3302 NSDictionary *thisQueueDict = tempObject;
3303 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3305 fileExistsInQueue = YES;
3311 if(fileExists == YES)
3313 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
3314 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3315 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3316 NULL, NULL, [NSString stringWithFormat:
3317 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3318 [fDstFile2Field stringValue]] );
3320 else if (fileExistsInQueue == YES)
3322 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
3323 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3324 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3325 NULL, NULL, [NSString stringWithFormat:
3326 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3327 [fDstFile2Field stringValue]] );
3331 [self doAddToQueue];
3335 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
3336 the user if they want to overwrite an exiting movie file.
3338 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
3339 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3341 if( returnCode == NSAlertAlternateReturn )
3342 [self doAddToQueue];
3345 - (void) doAddToQueue
3347 [self addQueueFileItem ];
3352 /* Rip: puts up an alert before ultimately calling doRip
3354 - (IBAction) Rip: (id) sender
3356 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
3357 /* Rip or Cancel ? */
3359 hb_get_state2( fQueueEncodeLibhb, &s );
3361 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
3363 [self Cancel: sender];
3367 /* We check to see if we need to warn the user that the computer will go to sleep
3368 or shut down when encoding is finished */
3369 [self remindUserOfSleepOrShutdown];
3371 // If there are pending jobs in the queue, then this is a rip the queue
3372 if (fPendingCount > 0)
3374 /* here lets start the queue with the first pending item */
3375 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3380 // Before adding jobs to the queue, check for a valid destination.
3382 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3383 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3385 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3389 /* We check for duplicate name here */
3390 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
3392 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
3393 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3394 @selector( overWriteAlertDone:returnCode:contextInfo: ),
3395 NULL, NULL, [NSString stringWithFormat:
3396 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3397 [fDstFile2Field stringValue]] );
3399 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
3403 /* if there are no pending jobs in the queue, then add this one to the queue and rip
3404 otherwise, just rip the queue */
3405 if(fPendingCount == 0)
3407 [self writeToActivityLog: "Rip: No pending jobs, so sending this one to doAddToQueue"];
3408 [self doAddToQueue];
3411 /* go right to processing the new queue encode */
3412 [self writeToActivityLog: "Rip: Going right to performNewQueueScan"];
3413 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3418 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
3419 want to overwrite an exiting movie file.
3421 - (void) overWriteAlertDone: (NSWindow *) sheet
3422 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3424 if( returnCode == NSAlertAlternateReturn )
3426 /* if there are no jobs in the queue, then add this one to the queue and rip
3427 otherwise, just rip the queue */
3428 if( fPendingCount == 0 )
3430 [self doAddToQueue];
3433 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3434 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
3435 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3440 - (void) remindUserOfSleepOrShutdown
3442 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
3444 /*Warn that computer will sleep after encoding*/
3447 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);
3448 [NSApp requestUserAttention:NSCriticalRequest];
3449 if ( reminduser == NSAlertAlternateReturn )
3451 [self showPreferencesWindow:nil];
3454 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
3456 /*Warn that computer will shut down after encoding*/
3459 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);
3460 [NSApp requestUserAttention:NSCriticalRequest];
3461 if ( reminduser == NSAlertAlternateReturn )
3463 [self showPreferencesWindow:nil];
3472 /* Let libhb do the job */
3473 hb_start( fQueueEncodeLibhb );
3474 /*set the fEncodeState State */
3479 //------------------------------------------------------------------------------------
3480 // Displays an alert asking user if the want to cancel encoding of current job.
3481 // Cancel: returns immediately after posting the alert. Later, when the user
3482 // acknowledges the alert, doCancelCurrentJob is called.
3483 //------------------------------------------------------------------------------------
3484 - (IBAction)Cancel: (id)sender
3486 if (!fQueueController) return;
3488 hb_pause( fQueueEncodeLibhb );
3489 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
3491 // Which window to attach the sheet to?
3492 NSWindow * docWindow;
3493 if ([sender respondsToSelector: @selector(window)])
3494 docWindow = [sender window];
3496 docWindow = fWindow;
3498 NSBeginCriticalAlertSheet(
3500 NSLocalizedString(@"Continue Encoding", nil),
3501 NSLocalizedString(@"Cancel Current and Stop", nil),
3502 NSLocalizedString(@"Cancel Current and Continue", nil),
3504 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
3505 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
3507 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
3510 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
3512 hb_resume( fQueueEncodeLibhb );
3513 if (returnCode == NSAlertOtherReturn)
3515 [self doCancelCurrentJob]; // <- this also stops libhb
3517 if (returnCode == NSAlertAlternateReturn)
3519 [self doCancelCurrentJobAndStop];
3523 //------------------------------------------------------------------------------------
3524 // Cancels and deletes the current job and stops libhb from processing the remaining
3526 //------------------------------------------------------------------------------------
3527 - (void) doCancelCurrentJob
3529 // Stop the current job. hb_stop will only cancel the current pass and then set
3530 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
3531 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
3532 // remaining passes of the job and then start the queue back up if there are any
3536 hb_stop( fQueueEncodeLibhb );
3538 // Delete all remaining jobs since libhb doesn't do this on its own.
3540 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3541 hb_rem( fQueueEncodeLibhb, job );
3543 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3545 // now that we've stopped the currently encoding job, lets mark it as cancelled
3546 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3547 // and as always, save it in the queue .plist...
3548 /* We save all of the Queue data here */
3549 [self saveQueueFileItem];
3550 // so now lets move to
3551 currentQueueEncodeIndex++ ;
3552 // ... and see if there are more items left in our queue
3553 int queueItems = [QueueFileArray count];
3554 /* If we still have more items in our queue, lets go to the next one */
3555 if (currentQueueEncodeIndex < queueItems)
3557 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
3558 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
3560 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3564 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
3569 - (void) doCancelCurrentJobAndStop
3571 hb_stop( fQueueEncodeLibhb );
3573 // Delete all remaining jobs since libhb doesn't do this on its own.
3575 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3576 hb_rem( fQueueEncodeLibhb, job );
3579 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3581 // now that we've stopped the currently encoding job, lets mark it as cancelled
3582 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3583 // and as always, save it in the queue .plist...
3584 /* We save all of the Queue data here */
3585 [self saveQueueFileItem];
3586 // so now lets move to
3587 currentQueueEncodeIndex++ ;
3588 [self writeToActivityLog: "cancelling current job and stopping the queue"];
3590 - (IBAction) Pause: (id) sender
3593 hb_get_state2( fQueueEncodeLibhb, &s );
3595 if( s.state == HB_STATE_PAUSED )
3597 hb_resume( fQueueEncodeLibhb );
3601 hb_pause( fQueueEncodeLibhb );
3606 #pragma mark GUI Controls Changed Methods
3608 - (IBAction) titlePopUpChanged: (id) sender
3610 hb_list_t * list = hb_get_titles( fHandle );
3611 hb_title_t * title = (hb_title_t*)
3612 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3614 /* If Auto Naming is on. We create an output filename of dvd name - title number */
3615 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
3617 [fDstFile2Field setStringValue: [NSString stringWithFormat:
3618 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
3619 [browsedSourceDisplayName stringByDeletingPathExtension],
3621 [[fDstFile2Field stringValue] pathExtension]]];
3624 /* Update chapter popups */
3625 [fSrcChapterStartPopUp removeAllItems];
3626 [fSrcChapterEndPopUp removeAllItems];
3627 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
3629 [fSrcChapterStartPopUp addItemWithTitle: [NSString
3630 stringWithFormat: @"%d", i + 1]];
3631 [fSrcChapterEndPopUp addItemWithTitle: [NSString
3632 stringWithFormat: @"%d", i + 1]];
3635 [fSrcChapterStartPopUp selectItemAtIndex: 0];
3636 [fSrcChapterEndPopUp selectItemAtIndex:
3637 hb_list_count( title->list_chapter ) - 1];
3638 [self chapterPopUpChanged:nil];
3640 /* Start Get and set the initial pic size for display */
3641 hb_job_t * job = title->job;
3644 /* Set Auto Crop to on upon selecting a new title */
3645 [fPictureController setAutoCrop:YES];
3647 /* We get the originial output picture width and height and put them
3648 in variables for use with some presets later on */
3649 PicOrigOutputWidth = job->width;
3650 PicOrigOutputHeight = job->height;
3651 AutoCropTop = job->crop[0];
3652 AutoCropBottom = job->crop[1];
3653 AutoCropLeft = job->crop[2];
3654 AutoCropRight = job->crop[3];
3656 /* Reset the new title in fPictureController && fPreviewController*/
3657 [fPictureController SetTitle:title];
3658 //[fPictureFilterController SetTitle:title];
3659 /* Update subtitle popups */
3660 hb_subtitle_t * subtitle;
3661 [fSubPopUp removeAllItems];
3662 [fSubPopUp addItemWithTitle: @"None"];
3663 [fSubPopUp addItemWithTitle: @"Autoselect"];
3664 for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
3666 subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
3668 /* We cannot use NSPopUpButton's addItemWithTitle because
3669 it checks for duplicate entries */
3670 [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
3671 subtitle->lang] action: NULL keyEquivalent: @""];
3673 [fSubPopUp selectItemAtIndex: 0];
3675 [self subtitleSelectionChanged:nil];
3677 /* Update chapter table */
3678 [fChapterTitlesDelegate resetWithTitle:title];
3679 [fChapterTable reloadData];
3681 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3682 int audiotrack_count = hb_list_count(job->list_audio);
3683 for( int i = 0; i < audiotrack_count;i++)
3685 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3686 hb_list_rem(job->list_audio, temp_audio);
3689 /* Update audio popups */
3690 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
3691 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
3692 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
3693 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
3694 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
3695 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
3696 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
3697 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3698 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3699 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3701 /* changing the title may have changed the audio channels on offer, */
3702 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3703 [self audioTrackPopUpChanged: fAudLang1PopUp];
3704 [self audioTrackPopUpChanged: fAudLang2PopUp];
3705 [self audioTrackPopUpChanged: fAudLang3PopUp];
3706 [self audioTrackPopUpChanged: fAudLang4PopUp];
3708 [fVidRatePopUp selectItemAtIndex: 0];
3710 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
3711 [self calculatePictureSizing:nil];
3713 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
3714 [self selectPreset:nil];
3717 - (IBAction) chapterPopUpChanged: (id) sender
3720 /* If start chapter popup is greater than end chapter popup,
3721 we set the end chapter popup to the same as start chapter popup */
3722 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
3724 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
3728 hb_list_t * list = hb_get_titles( fHandle );
3729 hb_title_t * title = (hb_title_t *)
3730 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3732 hb_chapter_t * chapter;
3733 int64_t duration = 0;
3734 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
3735 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
3737 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3738 duration += chapter->duration;
3741 duration /= 90000; /* pts -> seconds */
3742 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
3743 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
3746 [self calculateBitrate: sender];
3749 - (IBAction) formatPopUpChanged: (id) sender
3751 NSString * string = [fDstFile2Field stringValue];
3752 int format = [fDstFormatPopUp indexOfSelectedItem];
3754 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
3755 [fDstMp4LargeFileCheck setHidden: YES];
3756 [fDstMp4HttpOptFileCheck setHidden: YES];
3757 [fDstMp4iPodFileCheck setHidden: YES];
3759 /* Update the Video Codec PopUp */
3760 /* lets get the tag of the currently selected item first so we might reset it later */
3761 int selectedVidEncoderTag;
3762 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
3764 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
3765 [fVidEncoderPopUp removeAllItems];
3766 NSMenuItem *menuItem;
3767 /* These video encoders are available to all of our current muxers, so lets list them once here */
3768 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
3769 [menuItem setTag: HB_VCODEC_FFMPEG];
3771 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (XviD)" action: NULL keyEquivalent: @""];
3772 [menuItem setTag: HB_VCODEC_XVID];
3776 /*Get Default MP4 File Extension*/
3777 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
3785 /* Add additional video encoders here */
3786 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3787 [menuItem setTag: HB_VCODEC_X264];
3788 /* We show the mp4 option checkboxes here since we are mp4 */
3789 [fCreateChapterMarkers setEnabled: YES];
3790 [fDstMp4LargeFileCheck setHidden: NO];
3791 [fDstMp4HttpOptFileCheck setHidden: NO];
3792 [fDstMp4iPodFileCheck setHidden: NO];
3797 /* Add additional video encoders here */
3798 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3799 [menuItem setTag: HB_VCODEC_X264];
3800 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3801 [menuItem setTag: HB_VCODEC_THEORA];
3802 /* We enable the create chapters checkbox here */
3803 [fCreateChapterMarkers setEnabled: YES];
3808 /* Add additional video encoders here */
3809 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3810 [menuItem setTag: HB_VCODEC_X264];
3811 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3812 [fCreateChapterMarkers setEnabled: NO];
3813 [fCreateChapterMarkers setState: NSOffState];
3818 /* Add additional video encoders here */
3819 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3820 [menuItem setTag: HB_VCODEC_THEORA];
3821 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3822 [fCreateChapterMarkers setEnabled: NO];
3823 [fCreateChapterMarkers setState: NSOffState];
3826 /* if we have a previously selected vid encoder tag, then try to select it */
3827 if (selectedVidEncoderTag)
3829 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
3833 [fVidEncoderPopUp selectItemAtIndex: 0];
3836 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
3837 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
3838 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
3839 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
3842 [self autoSetM4vExtension: sender];
3844 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
3846 if( SuccessfulScan )
3848 /* Add/replace to the correct extension */
3849 [self audioTrackPopUpChanged: fAudLang1PopUp];
3850 [self audioTrackPopUpChanged: fAudLang2PopUp];
3851 [self audioTrackPopUpChanged: fAudLang3PopUp];
3852 [self audioTrackPopUpChanged: fAudLang4PopUp];
3854 if( [fVidEncoderPopUp selectedItem] == nil )
3857 [fVidEncoderPopUp selectItemAtIndex:0];
3858 [self videoEncoderPopUpChanged:nil];
3860 /* changing the format may mean that we can / can't offer mono or 6ch, */
3861 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3863 /* We call the method to properly enable/disable turbo 2 pass */
3864 [self twoPassCheckboxChanged: sender];
3865 /* We call method method to change UI to reflect whether a preset is used or not*/
3868 [self customSettingUsed: sender];
3871 - (IBAction) autoSetM4vExtension: (id) sender
3873 if ( [fDstFormatPopUp indexOfSelectedItem] )
3876 NSString * extension = @"mp4";
3878 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3879 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3880 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3881 [fCreateChapterMarkers state] == NSOnState ||
3882 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
3887 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
3890 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
3891 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
3894 /* Method to determine if we should change the UI
3895 To reflect whether or not a Preset is being used or if
3896 the user is using "Custom" settings by determining the sender*/
3897 - (IBAction) customSettingUsed: (id) sender
3899 if ([sender stringValue])
3901 /* Deselect the currently selected Preset if there is one*/
3902 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3903 /* Change UI to show "Custom" settings are being used */
3904 [fPresetSelectedDisplay setStringValue: @"Custom"];
3906 curUserPresetChosenNum = nil;
3908 [self calculateBitrate:nil];
3913 #pragma mark - Video
3915 - (IBAction) videoEncoderPopUpChanged: (id) sender
3917 hb_job_t * job = fTitle->job;
3918 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
3920 [fAdvancedOptions setHidden:YES];
3921 /* If we are using x264 then show the x264 advanced panel*/
3922 if (videoEncoder == HB_VCODEC_X264)
3924 [fAdvancedOptions setHidden:NO];
3925 [self autoSetM4vExtension: sender];
3928 /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
3929 is being used as it borks up loose anamorphic .
3930 For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
3931 to use the index itself but this is easier */
3932 if (videoEncoder == HB_VCODEC_FFMPEG)
3934 if (job->anamorphic.mode == 2)
3936 job->anamorphic.mode = 0;
3938 [fPictureController setAllowLooseAnamorphic:NO];
3939 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
3940 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
3941 anything other than MP4.
3943 [fDstMp4iPodFileCheck setEnabled: NO];
3944 [fDstMp4iPodFileCheck setState: NSOffState];
3948 [fPictureController setAllowLooseAnamorphic:YES];
3949 [fDstMp4iPodFileCheck setEnabled: YES];
3951 [self setupQualitySlider];
3952 [self calculatePictureSizing: sender];
3953 [self twoPassCheckboxChanged: sender];
3957 - (IBAction) twoPassCheckboxChanged: (id) sender
3959 /* check to see if x264 is chosen */
3960 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
3962 if( [fVidTwoPassCheck state] == NSOnState)
3964 [fVidTurboPassCheck setHidden: NO];
3968 [fVidTurboPassCheck setHidden: YES];
3969 [fVidTurboPassCheck setState: NSOffState];
3971 /* Make sure Two Pass is checked if Turbo is checked */
3972 if( [fVidTurboPassCheck state] == NSOnState)
3974 [fVidTwoPassCheck setState: NSOnState];
3979 [fVidTurboPassCheck setHidden: YES];
3980 [fVidTurboPassCheck setState: NSOffState];
3983 /* We call method method to change UI to reflect whether a preset is used or not*/
3984 [self customSettingUsed: sender];
3987 - (IBAction ) videoFrameRateChanged: (id) sender
3989 /* We call method method to calculatePictureSizing to error check detelecine*/
3990 [self calculatePictureSizing: sender];
3992 /* We call method method to change UI to reflect whether a preset is used or not*/
3993 [self customSettingUsed: sender];
3995 - (IBAction) videoMatrixChanged: (id) sender;
3997 bool target, bitrate, quality;
3999 target = bitrate = quality = false;
4000 if( [fVidQualityMatrix isEnabled] )
4002 switch( [fVidQualityMatrix selectedRow] )
4015 [fVidTargetSizeField setEnabled: target];
4016 [fVidBitrateField setEnabled: bitrate];
4017 [fVidQualitySlider setEnabled: quality];
4018 [fVidQualityRFField setEnabled: quality];
4019 [fVidQualityRFLabel setEnabled: quality];
4020 [fVidTwoPassCheck setEnabled: !quality &&
4021 [fVidQualityMatrix isEnabled]];
4024 [fVidTwoPassCheck setState: NSOffState];
4025 [fVidTurboPassCheck setHidden: YES];
4026 [fVidTurboPassCheck setState: NSOffState];
4029 [self qualitySliderChanged: sender];
4030 [self calculateBitrate: sender];
4031 [self customSettingUsed: sender];
4034 /* Use this method to setup the quality slider for cq/rf values depending on
4035 * the video encoder selected.
4037 - (void) setupQualitySlider
4039 /* Get the current slider maxValue to check for a change in slider scale later
4040 * so that we can choose a new similar value on the new slider scale */
4041 float previousMaxValue = [fVidQualitySlider maxValue];
4042 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4043 NSString * qpRFLabelString = @"QP:";
4045 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4047 [fVidQualitySlider setMinValue:0.0];
4048 [fVidQualitySlider setMaxValue:51.0];
4049 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4050 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4051 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4052 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0)
4054 qpRFLabelString = @"RF:";
4057 /* ffmpeg and xvid 1-31 */
4058 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG || [[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_XVID)
4060 [fVidQualitySlider setMinValue:1.0];
4061 [fVidQualitySlider setMaxValue:31.0];
4062 [fVidQualitySlider setNumberOfTickMarks:31];
4065 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4067 [fVidQualitySlider setMinValue:0.0];
4068 [fVidQualitySlider setMaxValue:63.0];
4069 [fVidQualitySlider setNumberOfTickMarks:64];
4071 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4073 /* check to see if we have changed slider scales */
4074 if (previousMaxValue != [fVidQualitySlider maxValue])
4076 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4077 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4078 [fVidQualitySlider setFloatValue:rf];
4081 [self qualitySliderChanged:nil];
4084 - (IBAction) qualitySliderChanged: (id) sender
4086 /* Our constant quality slider is in a range based
4087 * on each encoders qp/rf values. The range depends
4088 * on the encoder. Also, the range is inverse of quality
4089 * for all of the encoders *except* for theora
4090 * (ie. as the "quality" goes up, the cq or rf value
4091 * actually goes down). Since the IB sliders always set
4092 * their max value at the right end of the slider, we
4093 * will calculate the inverse, so as the slider floatValue
4094 * goes up, we will show the inverse in the rf field
4095 * so, the floatValue at the right for x264 would be 51
4096 * and our rf field needs to show 0 and vice versa.
4099 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4100 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4101 float sliderRfToPercent;
4102 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4104 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4105 sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4109 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4110 sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4112 [fVidConstantCell setTitle: [NSString stringWithFormat:
4113 NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
4115 [self customSettingUsed: sender];
4118 - (void) controlTextDidChange: (NSNotification *) notification
4120 [self calculateBitrate:nil];
4123 - (IBAction) calculateBitrate: (id) sender
4125 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4130 hb_list_t * list = hb_get_titles( fHandle );
4131 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4132 [fSrcTitlePopUp indexOfSelectedItem] );
4133 hb_job_t * job = title->job;
4134 hb_audio_config_t * audio;
4135 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4136 * Target Size Field, we also need the job info for the Muxer, the Chapters
4137 * as well as all of the audio track info.
4138 * This used to be accomplished by simply calling prepareJob here, however
4139 * since the resilient queue sets the queue array values instead of the job
4140 * values directly, we duplicate the old prepareJob code here for the variables
4143 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4144 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4145 job->mux = [[fDstFormatPopUp selectedItem] tag];
4147 /* Audio goes here */
4148 int audiotrack_count = hb_list_count(job->list_audio);
4149 for( int i = 0; i < audiotrack_count;i++)
4151 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4152 hb_list_rem(job->list_audio, temp_audio);
4154 /* Now we need our audio info here for each track if applicable */
4155 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4157 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4158 hb_audio_config_init(audio);
4159 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4160 /* We go ahead and assign values to our audio->out.<properties> */
4161 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4162 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4163 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4164 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4165 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4166 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4168 hb_audio_add( job, audio );
4171 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4173 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4174 hb_audio_config_init(audio);
4175 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4176 /* We go ahead and assign values to our audio->out.<properties> */
4177 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4178 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4179 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4180 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4181 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4182 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4184 hb_audio_add( job, audio );
4189 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4191 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4192 hb_audio_config_init(audio);
4193 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4194 /* We go ahead and assign values to our audio->out.<properties> */
4195 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4196 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
4197 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
4198 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
4199 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
4200 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
4202 hb_audio_add( job, audio );
4207 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4209 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4210 hb_audio_config_init(audio);
4211 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4212 /* We go ahead and assign values to our audio->out.<properties> */
4213 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4214 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
4215 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
4216 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
4217 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
4218 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
4220 hb_audio_add( job, audio );
4225 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
4229 #pragma mark - Picture
4231 /* lets set the picture size back to the max from right after title scan
4232 Lets use an IBAction here as down the road we could always use a checkbox
4233 in the gui to easily take the user back to max. Remember, the compiler
4234 resolves IBActions down to -(void) during compile anyway */
4235 - (IBAction) revertPictureSizeToMax: (id) sender
4237 hb_job_t * job = fTitle->job;
4238 /* Here we apply the title source and height */
4239 job->width = fTitle->width;
4240 job->height = fTitle->height;
4242 [self calculatePictureSizing: sender];
4243 /* We call method to change UI to reflect whether a preset is used or not*/
4244 [self customSettingUsed: sender];
4248 * Registers changes made in the Picture Settings Window.
4251 - (void)pictureSettingsDidChange
4253 [self calculatePictureSizing:nil];
4256 /* Get and Display Current Pic Settings in main window */
4257 - (IBAction) calculatePictureSizing: (id) sender
4259 if (fTitle->job->anamorphic.mode > 0)
4261 fTitle->job->keep_ratio = 0;
4264 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
4266 NSString *picCropping;
4267 /* Set the display field for crop as per boolean */
4268 if (![fPictureController autoCrop])
4270 picCropping = @"Custom";
4274 picCropping = @"Auto";
4276 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]]];
4278 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
4280 NSString *videoFilters;
4283 if ([fPictureFilterController detelecine] == 1)
4285 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
4287 else if ([fPictureFilterController detelecine] == 2)
4289 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureFilterController detelecineCustomString]]];
4293 if ([fPictureFilterController useDecomb] == 1)
4296 if ([fPictureFilterController decomb] == 1)
4298 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
4300 else if ([fPictureFilterController decomb] == 2)
4302 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureFilterController decombCustomString]]];
4308 if ([fPictureFilterController deinterlace] > 0)
4310 fTitle->job->deinterlace = 1;
4314 fTitle->job->deinterlace = 0;
4317 if ([fPictureFilterController deinterlace] == 1)
4319 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
4321 else if ([fPictureFilterController deinterlace] == 2)
4323 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
4325 else if ([fPictureFilterController deinterlace] == 3)
4327 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
4329 else if ([fPictureFilterController deinterlace] == 4)
4331 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureFilterController deinterlaceCustomString]]];
4337 if ([fPictureFilterController denoise] == 1)
4339 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
4341 else if ([fPictureFilterController denoise] == 2)
4343 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
4345 else if ([fPictureFilterController denoise] == 3)
4347 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
4349 else if ([fPictureFilterController denoise] == 4)
4351 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureFilterController denoiseCustomString]]];
4355 if ([fPictureFilterController deblock] > 0)
4357 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureFilterController deblock]]];
4361 if ([fPictureFilterController grayscale])
4363 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
4365 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
4367 [fPictureController reloadStillPreview];
4372 #pragma mark - Audio and Subtitles
4373 - (IBAction) audioCodecsPopUpChanged: (id) sender
4376 NSPopUpButton * audiotrackPopUp;
4377 NSPopUpButton * sampleratePopUp;
4378 NSPopUpButton * bitratePopUp;
4379 NSPopUpButton * audiocodecPopUp;
4380 if (sender == fAudTrack1CodecPopUp)
4382 audiotrackPopUp = fAudLang1PopUp;
4383 audiocodecPopUp = fAudTrack1CodecPopUp;
4384 sampleratePopUp = fAudTrack1RatePopUp;
4385 bitratePopUp = fAudTrack1BitratePopUp;
4387 else if (sender == fAudTrack2CodecPopUp)
4389 audiotrackPopUp = fAudLang2PopUp;
4390 audiocodecPopUp = fAudTrack2CodecPopUp;
4391 sampleratePopUp = fAudTrack2RatePopUp;
4392 bitratePopUp = fAudTrack2BitratePopUp;
4394 else if (sender == fAudTrack3CodecPopUp)
4396 audiotrackPopUp = fAudLang3PopUp;
4397 audiocodecPopUp = fAudTrack3CodecPopUp;
4398 sampleratePopUp = fAudTrack3RatePopUp;
4399 bitratePopUp = fAudTrack3BitratePopUp;
4403 audiotrackPopUp = fAudLang4PopUp;
4404 audiocodecPopUp = fAudTrack4CodecPopUp;
4405 sampleratePopUp = fAudTrack4RatePopUp;
4406 bitratePopUp = fAudTrack4BitratePopUp;
4409 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
4410 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4411 [self audioTrackPopUpChanged: audiotrackPopUp];
4415 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
4417 /* We will be setting the enabled/disabled state of each tracks audio controls based on
4418 * the settings of the source audio for that track. We leave the samplerate and bitrate
4419 * to audiotrackMixdownChanged
4422 /* We will first verify that a lower track number has been selected before enabling each track
4423 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
4425 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4427 [fAudLang2PopUp setEnabled: NO];
4428 [fAudLang2PopUp selectItemAtIndex: 0];
4432 [fAudLang2PopUp setEnabled: YES];
4435 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4437 [fAudLang3PopUp setEnabled: NO];
4438 [fAudLang3PopUp selectItemAtIndex: 0];
4442 [fAudLang3PopUp setEnabled: YES];
4444 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4446 [fAudLang4PopUp setEnabled: NO];
4447 [fAudLang4PopUp selectItemAtIndex: 0];
4451 [fAudLang4PopUp setEnabled: YES];
4453 /* enable/disable the mixdown text and popupbutton for audio track 1 */
4454 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4455 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4456 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4457 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4458 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4459 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4460 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4462 [fAudTrack1CodecPopUp removeAllItems];
4463 [fAudTrack1MixPopUp removeAllItems];
4464 [fAudTrack1RatePopUp removeAllItems];
4465 [fAudTrack1BitratePopUp removeAllItems];
4466 [fAudTrack1DrcSlider setFloatValue: 1.00];
4467 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4469 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4471 [fAudTrack1RatePopUp setEnabled: NO];
4472 [fAudTrack1BitratePopUp setEnabled: NO];
4473 [fAudTrack1DrcSlider setEnabled: NO];
4474 [fAudTrack1DrcField setEnabled: NO];
4477 /* enable/disable the mixdown text and popupbutton for audio track 2 */
4478 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4479 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4480 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4481 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4482 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4483 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4484 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4486 [fAudTrack2CodecPopUp removeAllItems];
4487 [fAudTrack2MixPopUp removeAllItems];
4488 [fAudTrack2RatePopUp removeAllItems];
4489 [fAudTrack2BitratePopUp removeAllItems];
4490 [fAudTrack2DrcSlider setFloatValue: 1.00];
4491 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
4493 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4495 [fAudTrack2RatePopUp setEnabled: NO];
4496 [fAudTrack2BitratePopUp setEnabled: NO];
4497 [fAudTrack2DrcSlider setEnabled: NO];
4498 [fAudTrack2DrcField setEnabled: NO];
4501 /* enable/disable the mixdown text and popupbutton for audio track 3 */
4502 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4503 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4504 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4505 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4506 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4507 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4508 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4510 [fAudTrack3CodecPopUp removeAllItems];
4511 [fAudTrack3MixPopUp removeAllItems];
4512 [fAudTrack3RatePopUp removeAllItems];
4513 [fAudTrack3BitratePopUp removeAllItems];
4514 [fAudTrack3DrcSlider setFloatValue: 1.00];
4515 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
4517 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4519 [fAudTrack3RatePopUp setEnabled: NO];
4520 [fAudTrack3BitratePopUp setEnabled: NO];
4521 [fAudTrack3DrcSlider setEnabled: NO];
4522 [fAudTrack3DrcField setEnabled: NO];
4525 /* enable/disable the mixdown text and popupbutton for audio track 4 */
4526 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4527 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4528 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4529 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4530 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4531 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4532 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
4534 [fAudTrack4CodecPopUp removeAllItems];
4535 [fAudTrack4MixPopUp removeAllItems];
4536 [fAudTrack4RatePopUp removeAllItems];
4537 [fAudTrack4BitratePopUp removeAllItems];
4538 [fAudTrack4DrcSlider setFloatValue: 1.00];
4539 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
4541 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4543 [fAudTrack4RatePopUp setEnabled: NO];
4544 [fAudTrack4BitratePopUp setEnabled: NO];
4545 [fAudTrack4DrcSlider setEnabled: NO];
4546 [fAudTrack4DrcField setEnabled: NO];
4551 - (IBAction) addAllAudioTracksToPopUp: (id) sender
4554 hb_list_t * list = hb_get_titles( fHandle );
4555 hb_title_t * title = (hb_title_t*)
4556 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4558 hb_audio_config_t * audio;
4560 [sender removeAllItems];
4561 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
4562 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
4564 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
4565 [[sender menu] addItemWithTitle:
4566 [NSString stringWithCString: audio->lang.description]
4567 action: NULL keyEquivalent: @""];
4569 [sender selectItemAtIndex: 0];
4573 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
4576 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
4577 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
4578 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
4579 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
4581 if (searchPrefixString)
4584 for( int i = 0; i < [sender numberOfItems]; i++ )
4586 /* Try to find the desired search string */
4587 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
4589 [sender selectItemAtIndex: i];
4593 /* couldn't find the string, so select the requested "search string not found" item */
4594 /* index of 0 means select the "none" item */
4595 /* index of 1 means select the first audio track */
4596 [sender selectItemAtIndex: selectIndexIfNotFound];
4600 /* if no search string is provided, then select the selectIndexIfNotFound item */
4601 [sender selectItemAtIndex: selectIndexIfNotFound];
4605 - (IBAction) audioAddAudioTrackCodecs: (id)sender
4607 int format = [fDstFormatPopUp indexOfSelectedItem];
4609 /* setup pointers to the appropriate popups for the correct track */
4610 NSPopUpButton * audiocodecPopUp;
4611 NSPopUpButton * audiotrackPopUp;
4612 if (sender == fAudTrack1CodecPopUp)
4614 audiotrackPopUp = fAudLang1PopUp;
4615 audiocodecPopUp = fAudTrack1CodecPopUp;
4617 else if (sender == fAudTrack2CodecPopUp)
4619 audiotrackPopUp = fAudLang2PopUp;
4620 audiocodecPopUp = fAudTrack2CodecPopUp;
4622 else if (sender == fAudTrack3CodecPopUp)
4624 audiotrackPopUp = fAudLang3PopUp;
4625 audiocodecPopUp = fAudTrack3CodecPopUp;
4629 audiotrackPopUp = fAudLang4PopUp;
4630 audiocodecPopUp = fAudTrack4CodecPopUp;
4633 [audiocodecPopUp removeAllItems];
4634 /* Make sure "None" isnt selected in the source track */
4635 if ([audiotrackPopUp indexOfSelectedItem] > 0)
4637 [audiocodecPopUp setEnabled:YES];
4638 NSMenuItem *menuItem;
4639 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
4645 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4646 [menuItem setTag: HB_ACODEC_FAAC];
4649 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4650 [menuItem setTag: HB_ACODEC_AC3];
4656 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4657 [menuItem setTag: HB_ACODEC_FAAC];
4659 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4660 [menuItem setTag: HB_ACODEC_AC3];
4662 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4663 [menuItem setTag: HB_ACODEC_LAME];
4665 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4666 [menuItem setTag: HB_ACODEC_VORBIS];
4672 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4673 [menuItem setTag: HB_ACODEC_LAME];
4675 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4676 [menuItem setTag: HB_ACODEC_AC3];
4682 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4683 [menuItem setTag: HB_ACODEC_VORBIS];
4685 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4686 [menuItem setTag: HB_ACODEC_LAME];
4689 [audiocodecPopUp selectItemAtIndex:0];
4693 [audiocodecPopUp setEnabled:NO];
4697 - (IBAction) audioTrackPopUpChanged: (id) sender
4699 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
4700 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
4703 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
4706 /* make sure we have a selected title before continuing */
4707 if (fTitle == NULL) return;
4708 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
4709 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
4711 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
4713 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4715 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
4717 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4719 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
4721 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4723 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
4725 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4728 /* Now lets make the sender the appropriate Audio Track popup from this point on */
4729 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
4731 sender = fAudLang1PopUp;
4733 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
4735 sender = fAudLang2PopUp;
4737 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
4739 sender = fAudLang3PopUp;
4741 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
4743 sender = fAudLang4PopUp;
4746 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
4747 NSPopUpButton * mixdownPopUp;
4748 NSPopUpButton * audiocodecPopUp;
4749 NSPopUpButton * sampleratePopUp;
4750 NSPopUpButton * bitratePopUp;
4751 if (sender == fAudLang1PopUp)
4753 mixdownPopUp = fAudTrack1MixPopUp;
4754 audiocodecPopUp = fAudTrack1CodecPopUp;
4755 sampleratePopUp = fAudTrack1RatePopUp;
4756 bitratePopUp = fAudTrack1BitratePopUp;
4758 else if (sender == fAudLang2PopUp)
4760 mixdownPopUp = fAudTrack2MixPopUp;
4761 audiocodecPopUp = fAudTrack2CodecPopUp;
4762 sampleratePopUp = fAudTrack2RatePopUp;
4763 bitratePopUp = fAudTrack2BitratePopUp;
4765 else if (sender == fAudLang3PopUp)
4767 mixdownPopUp = fAudTrack3MixPopUp;
4768 audiocodecPopUp = fAudTrack3CodecPopUp;
4769 sampleratePopUp = fAudTrack3RatePopUp;
4770 bitratePopUp = fAudTrack3BitratePopUp;
4774 mixdownPopUp = fAudTrack4MixPopUp;
4775 audiocodecPopUp = fAudTrack4CodecPopUp;
4776 sampleratePopUp = fAudTrack4RatePopUp;
4777 bitratePopUp = fAudTrack4BitratePopUp;
4780 /* get the index of the selected audio Track*/
4781 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
4783 /* pointer for the hb_audio_s struct we will use later on */
4784 hb_audio_config_t * audio;
4787 /* check if the audio mixdown controls need their enabled state changing */
4788 [self setEnabledStateOfAudioMixdownControls:nil];
4790 if (thisAudioIndex != -1)
4794 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
4796 /* actually manipulate the proper mixdowns here */
4797 /* delete the previous audio mixdown options */
4798 [mixdownPopUp removeAllItems];
4800 acodec = [[audiocodecPopUp selectedItem] tag];
4805 /* find out if our selected output audio codec supports mono and / or 6ch */
4806 /* we also check for an input codec of AC3 or DCA,
4807 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
4808 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
4809 but this may change in the future, so they are separated for flexibility */
4810 int audioCodecsSupportMono =
4811 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4812 (acodec != HB_ACODEC_LAME);
4813 int audioCodecsSupport6Ch =
4814 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4815 (acodec != HB_ACODEC_LAME);
4817 /* check for AC-3 passthru */
4818 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4821 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4822 [NSString stringWithCString: "AC3 Passthru"]
4823 action: NULL keyEquivalent: @""];
4824 [menuItem setTag: HB_ACODEC_AC3];
4829 /* add the appropriate audio mixdown menuitems to the popupbutton */
4830 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
4831 so that we can reference the mixdown later */
4833 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
4834 int minMixdownUsed = 0;
4835 int maxMixdownUsed = 0;
4837 /* get the input channel layout without any lfe channels */
4838 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4840 /* do we want to add a mono option? */
4841 if (audioCodecsSupportMono == 1)
4843 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4844 [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
4845 action: NULL keyEquivalent: @""];
4846 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
4847 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
4848 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
4851 /* do we want to add a stereo option? */
4852 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
4853 /* also offer stereo if we have a stereo-or-better source */
4854 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
4856 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4857 [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
4858 action: NULL keyEquivalent: @""];
4859 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
4860 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
4861 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
4864 /* do we want to add a dolby surround (DPL1) option? */
4865 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
4867 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4868 [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
4869 action: NULL keyEquivalent: @""];
4870 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
4871 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
4872 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
4875 /* do we want to add a dolby pro logic 2 (DPL2) option? */
4876 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
4878 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4879 [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
4880 action: NULL keyEquivalent: @""];
4881 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
4882 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
4883 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
4886 /* do we want to add a 6-channel discrete option? */
4887 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
4889 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4890 [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
4891 action: NULL keyEquivalent: @""];
4892 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
4893 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
4894 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
4897 /* do we want to add an AC-3 passthrough option? */
4898 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4900 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4901 [NSString stringWithCString: hb_audio_mixdowns[5].human_readable_name]
4902 action: NULL keyEquivalent: @""];
4903 [menuItem setTag: HB_ACODEC_AC3];
4904 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
4905 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
4908 /* auto-select the best mixdown based on our saved mixdown preference */
4910 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
4911 /* ultimately this should be a prefs option */
4914 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
4915 if (mixdownToUse > 0)
4917 useMixdown = mixdownToUse;
4921 useMixdown = HB_AMIXDOWN_DOLBYPLII;
4924 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
4925 if (useMixdown > maxMixdownUsed)
4927 useMixdown = maxMixdownUsed;
4930 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
4931 if (useMixdown < minMixdownUsed)
4933 useMixdown = minMixdownUsed;
4936 /* select the (possibly-amended) preferred mixdown */
4937 [mixdownPopUp selectItemWithTag: useMixdown];
4940 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
4941 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
4944 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
4946 /* If we are using the avi container, we select MP3 as there is no aac available*/
4947 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
4949 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
4953 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
4956 /* Setup our samplerate and bitrate popups we will need based on mixdown */
4957 [self audioTrackMixdownChanged: mixdownPopUp];
4961 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
4963 [self autoSetM4vExtension: sender];
4967 - (IBAction) audioTrackMixdownChanged: (id) sender
4971 /* setup pointers to all of the other audio track controls
4972 * we will need later
4974 NSPopUpButton * mixdownPopUp;
4975 NSPopUpButton * sampleratePopUp;
4976 NSPopUpButton * bitratePopUp;
4977 NSPopUpButton * audiocodecPopUp;
4978 NSPopUpButton * audiotrackPopUp;
4979 NSSlider * drcSlider;
4980 NSTextField * drcField;
4981 if (sender == fAudTrack1MixPopUp)
4983 audiotrackPopUp = fAudLang1PopUp;
4984 audiocodecPopUp = fAudTrack1CodecPopUp;
4985 mixdownPopUp = fAudTrack1MixPopUp;
4986 sampleratePopUp = fAudTrack1RatePopUp;
4987 bitratePopUp = fAudTrack1BitratePopUp;
4988 drcSlider = fAudTrack1DrcSlider;
4989 drcField = fAudTrack1DrcField;
4991 else if (sender == fAudTrack2MixPopUp)
4993 audiotrackPopUp = fAudLang2PopUp;
4994 audiocodecPopUp = fAudTrack2CodecPopUp;
4995 mixdownPopUp = fAudTrack2MixPopUp;
4996 sampleratePopUp = fAudTrack2RatePopUp;
4997 bitratePopUp = fAudTrack2BitratePopUp;
4998 drcSlider = fAudTrack2DrcSlider;
4999 drcField = fAudTrack2DrcField;
5001 else if (sender == fAudTrack3MixPopUp)
5003 audiotrackPopUp = fAudLang3PopUp;
5004 audiocodecPopUp = fAudTrack3CodecPopUp;
5005 mixdownPopUp = fAudTrack3MixPopUp;
5006 sampleratePopUp = fAudTrack3RatePopUp;
5007 bitratePopUp = fAudTrack3BitratePopUp;
5008 drcSlider = fAudTrack3DrcSlider;
5009 drcField = fAudTrack3DrcField;
5013 audiotrackPopUp = fAudLang4PopUp;
5014 audiocodecPopUp = fAudTrack4CodecPopUp;
5015 mixdownPopUp = fAudTrack4MixPopUp;
5016 sampleratePopUp = fAudTrack4RatePopUp;
5017 bitratePopUp = fAudTrack4BitratePopUp;
5018 drcSlider = fAudTrack4DrcSlider;
5019 drcField = fAudTrack4DrcField;
5021 acodec = [[audiocodecPopUp selectedItem] tag];
5022 /* storage variable for the min and max bitrate allowed for this codec */
5028 case HB_ACODEC_FAAC:
5029 /* check if we have a 6ch discrete conversion in either audio track */
5030 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5032 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
5034 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5040 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5042 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5043 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5048 case HB_ACODEC_LAME:
5049 /* Lame is happy using our min bitrate of 32 kbps */
5051 /* Lame won't encode if the bitrate is higher than 320 kbps */
5055 case HB_ACODEC_VORBIS:
5056 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5058 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5060 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5066 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5068 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5074 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5080 /* make sure we have a selected title before continuing */
5081 if (fTitle == NULL) return;
5082 /* get the audio so we can find out what input rates are*/
5083 hb_audio_config_t * audio;
5084 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5085 int inputbitrate = audio->in.bitrate / 1000;
5086 int inputsamplerate = audio->in.samplerate;
5088 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3)
5090 [bitratePopUp removeAllItems];
5092 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5094 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5096 /* add a new menuitem for this bitrate */
5097 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5098 [NSString stringWithCString: hb_audio_bitrates[i].string]
5099 action: NULL keyEquivalent: @""];
5100 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5101 [menuItem setTag: hb_audio_bitrates[i].rate];
5105 /* select the default bitrate (but use 384 for 6-ch AAC) */
5106 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5108 [bitratePopUp selectItemWithTag: 384];
5112 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5115 /* populate and set the sample rate popup */
5116 /* Audio samplerate */
5117 [sampleratePopUp removeAllItems];
5118 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5119 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5120 [menuItem setTag: inputsamplerate];
5122 for( int i = 0; i < hb_audio_rates_count; i++ )
5124 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5125 [NSString stringWithCString: hb_audio_rates[i].string]
5126 action: NULL keyEquivalent: @""];
5127 [menuItem setTag: hb_audio_rates[i].rate];
5129 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5130 * and there is no compelling reason to use anything else as default, though the users default
5131 * preset will likely override any setting chosen here.
5133 [sampleratePopUp selectItemWithTag: inputsamplerate];
5136 /* Since AC3 Pass Thru uses the input ac3 bitrate and sample rate, we get the input tracks
5137 * bitrate and dispay it in the bitrate popup even though libhb happily ignores any bitrate input from
5138 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
5140 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3)
5143 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
5144 [bitratePopUp removeAllItems];
5145 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5146 [NSString stringWithFormat:@"%d", inputbitrate]
5147 action: NULL keyEquivalent: @""];
5148 [menuItem setTag: inputbitrate];
5149 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
5150 [bitratePopUp setEnabled: NO];
5151 [sampleratePopUp setEnabled: NO];
5153 [drcSlider setFloatValue: 1.00];
5154 [self audioDRCSliderChanged: drcSlider];
5155 [drcSlider setEnabled: NO];
5156 [drcField setEnabled: NO];
5160 [sampleratePopUp setEnabled: YES];
5161 [bitratePopUp setEnabled: YES];
5162 [drcSlider setEnabled: YES];
5163 [drcField setEnabled: YES];
5165 [self calculateBitrate:nil];
5168 - (IBAction) audioDRCSliderChanged: (id) sender
5170 NSSlider * drcSlider;
5171 NSTextField * drcField;
5172 if (sender == fAudTrack1DrcSlider)
5174 drcSlider = fAudTrack1DrcSlider;
5175 drcField = fAudTrack1DrcField;
5177 else if (sender == fAudTrack2DrcSlider)
5179 drcSlider = fAudTrack2DrcSlider;
5180 drcField = fAudTrack2DrcField;
5182 else if (sender == fAudTrack3DrcSlider)
5184 drcSlider = fAudTrack3DrcSlider;
5185 drcField = fAudTrack3DrcField;
5189 drcSlider = fAudTrack4DrcSlider;
5190 drcField = fAudTrack4DrcField;
5193 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
5194 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
5196 [drcSlider setFloatValue:1.0];
5200 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
5201 /* For now, do not call this until we have an intelligent way to determine audio track selections
5202 * compared to presets
5204 //[self customSettingUsed: sender];
5207 - (IBAction) subtitleSelectionChanged: (id) sender
5209 if ([fSubPopUp indexOfSelectedItem] == 0)
5211 [fSubForcedCheck setState: NSOffState];
5212 [fSubForcedCheck setEnabled: NO];
5216 [fSubForcedCheck setEnabled: YES];
5225 #pragma mark Open New Windows
5227 - (IBAction) openHomepage: (id) sender
5229 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5230 URLWithString:@"http://handbrake.fr/"]];
5233 - (IBAction) openForums: (id) sender
5235 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5236 URLWithString:@"http://handbrake.fr/forum/"]];
5238 - (IBAction) openUserGuide: (id) sender
5240 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5241 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
5245 * Shows debug output window.
5247 - (IBAction)showDebugOutputPanel:(id)sender
5249 [outputPanel showOutputPanel:sender];
5253 * Shows preferences window.
5255 - (IBAction) showPreferencesWindow: (id) sender
5257 NSWindow * window = [fPreferencesController window];
5258 if (![window isVisible])
5261 [window makeKeyAndOrderFront: nil];
5265 * Shows queue window.
5267 - (IBAction) showQueueWindow:(id)sender
5269 [fQueueController showQueueWindow:sender];
5273 - (IBAction) toggleDrawer:(id)sender {
5274 [fPresetDrawer toggle:self];
5278 * Shows Picture Settings Window.
5281 - (IBAction) showPicturePanel: (id) sender
5283 [fPictureController showPictureWindow:sender];
5286 - (void) picturePanelFullScreen
5288 [fPictureController setToFullScreenMode];
5291 - (void) picturePanelWindowed
5293 [fPictureController setToWindowedMode];
5296 - (IBAction) showFiltersPanel: (id) sender
5298 [fPictureFilterController showFilterWindow:sender];
5301 - (IBAction) showPreviewWindow: (id) sender
5303 [fPictureController showPreviewWindow:sender];
5307 #pragma mark Preset Outline View Methods
5308 #pragma mark - Required
5309 /* These are required by the NSOutlineView Datasource Delegate */
5312 /* used to specify the number of levels to show for each item */
5313 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
5315 /* currently use no levels to test outline view viability */
5316 if (item == nil) // for an outline view the root level of the hierarchy is always nil
5318 return [UserPresets count];
5322 /* we need to return the count of the array in ChildrenArray for this folder */
5323 NSArray *children = nil;
5324 children = [item objectForKey:@"ChildrenArray"];
5325 if ([children count] > 0)
5327 return [children count];
5336 /* We use this to deterimine children of an item */
5337 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
5340 /* we need to return the count of the array in ChildrenArray for this folder */
5341 NSArray *children = nil;
5344 children = UserPresets;
5348 if ([item objectForKey:@"ChildrenArray"])
5350 children = [item objectForKey:@"ChildrenArray"];
5353 if ((children == nil) || ( [children count] <= (NSUInteger) index))
5359 return [children objectAtIndex:index];
5363 // We are only one level deep, so we can't be asked about children
5364 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
5368 /* We use this to determine if an item should be expandable */
5369 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
5372 /* we need to return the count of the array in ChildrenArray for this folder */
5373 NSArray *children= nil;
5376 children = UserPresets;
5380 if ([item objectForKey:@"ChildrenArray"])
5382 children = [item objectForKey:@"ChildrenArray"];
5386 /* To deterimine if an item should show a disclosure triangle
5387 * we could do it by the children count as so:
5388 * if ([children count] < 1)
5389 * However, lets leave the triangle show even if there are no
5390 * children to help indicate a folder, just like folder in the
5391 * finder can show a disclosure triangle even when empty
5394 /* We need to determine if the item is a folder */
5395 if ([[item objectForKey:@"Folder"] intValue] == 1)
5406 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
5408 // Our outline view has no levels, but we can still expand every item. Doing so
5409 // just makes the row taller. See heightOfRowByItem below.
5410 //return ![(HBQueueOutlineView*)outlineView isDragging];
5416 /* Used to tell the outline view which information is to be displayed per item */
5417 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5419 /* We have two columns right now, icon and PresetName */
5421 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5423 return [item objectForKey:@"PresetName"];
5432 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
5434 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
5436 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
5438 return [NSKeyedArchiver archivedDataWithRootObject:item];
5441 #pragma mark - Added Functionality (optional)
5442 /* Use to customize the font and display characteristics of the title cell */
5443 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
5445 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5449 NSColor *shadowColor;
5450 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
5451 /*check to see if its a selected row */
5452 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
5455 fontColor = [NSColor blackColor];
5456 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
5460 if ([[item objectForKey:@"Type"] intValue] == 0)
5462 fontColor = [NSColor blueColor];
5464 else // User created preset, use a black font
5466 fontColor = [NSColor blackColor];
5468 /* check to see if its a folder */
5469 //if ([[item objectForKey:@"Folder"] intValue] == 1)
5471 //fontColor = [NSColor greenColor];
5476 /* We use Bold Text for the HB Default */
5477 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
5479 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5481 /* We use Bold Text for the User Specified Default */
5482 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
5484 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5488 [cell setTextColor:fontColor];
5489 [cell setFont:txtFont];
5494 /* We use this to edit the name field in the outline view */
5495 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5497 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5502 [theRecord setObject:object forKey:@"PresetName"];
5506 [fPresetsOutlineView reloadData];
5507 /* We save all of the preset data here */
5511 /* We use this to provide tooltips for the items in the presets outline view */
5512 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
5514 //if ([[tc identifier] isEqualToString:@"PresetName"])
5516 /* initialize the tooltip contents variable */
5518 /* if there is a description for the preset, we show it in the tooltip */
5519 if ([item objectForKey:@"PresetDescription"])
5521 loc_tip = [item objectForKey:@"PresetDescription"];
5526 loc_tip = @"No description available";
5533 #pragma mark Preset Outline View Methods (dragging related)
5536 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
5538 // Dragging is only allowed for custom presets.
5539 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
5540 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
5544 // Don't retain since this is just holding temporaral drag information, and it is
5545 //only used during a drag! We could put this in the pboard actually.
5546 fDraggedNodes = items;
5547 // Provide data for our custom type, and simple NSStrings.
5548 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
5550 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
5551 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
5556 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
5559 // Don't allow dropping ONTO an item since they can't really contain any children.
5561 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
5562 if (isOnDropTypeProposal)
5563 return NSDragOperationNone;
5565 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
5568 index = [fPresetsOutlineView rowForItem: item] + 1;
5572 // Don't allow dropping into the Built In Presets.
5573 if (index < presetCurrentBuiltInCount)
5575 return NSDragOperationNone;
5576 index = MAX (index, presetCurrentBuiltInCount);
5579 [outlineView setDropItem:item dropChildIndex:index];
5580 return NSDragOperationGeneric;
5585 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
5587 /* first, lets see if we are dropping into a folder */
5588 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
5590 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
5591 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
5592 [childrenArray addObject:item];
5593 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
5594 [childrenArray autorelease];
5596 else // We are not, so we just move the preset into the existing array
5598 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
5600 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
5601 while (obj = [enumerator nextObject])
5603 [moveItems addIndex:[UserPresets indexOfObject:obj]];
5605 // Successful drop, lets rearrange the view and save it all
5606 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
5608 [fPresetsOutlineView reloadData];
5613 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
5615 NSUInteger index = [indexSet lastIndex];
5616 NSUInteger aboveInsertIndexCount = 0;
5618 NSUInteger removeIndex;
5620 if (index >= insertIndex)
5622 removeIndex = index + aboveInsertIndexCount;
5623 aboveInsertIndexCount++;
5627 removeIndex = index;
5631 id object = [[array objectAtIndex:removeIndex] retain];
5632 [array removeObjectAtIndex:removeIndex];
5633 [array insertObject:object atIndex:insertIndex];
5636 index = [indexSet indexLessThanIndex:index];
5641 #pragma mark - Functional Preset NSOutlineView Methods
5643 - (IBAction)selectPreset:(id)sender
5646 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
5648 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
5649 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5651 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
5653 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
5657 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5661 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
5662 [self formatPopUpChanged:nil];
5664 /* Chapter Markers*/
5665 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
5666 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
5667 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
5668 /* Mux mp4 with http optimization */
5669 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
5672 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
5673 /* We set the advanced opt string here if applicable*/
5674 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
5676 /* Lets run through the following functions to get variables set there */
5677 [self videoEncoderPopUpChanged:nil];
5678 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
5679 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
5680 [self calculateBitrate:nil];
5683 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
5685 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
5686 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
5688 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
5689 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
5690 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
5691 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
5692 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
5693 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
5695 /* For the quality slider we need to convert the old percent's to the new rf scales */
5696 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
5697 [fVidQualitySlider setFloatValue:rf];
5702 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
5705 [self videoMatrixChanged:nil];
5707 /* Video framerate */
5708 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
5709 detected framerate in the fVidRatePopUp so we use index 0*/
5710 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
5712 [fVidRatePopUp selectItemAtIndex: 0];
5716 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
5720 /* 2 Pass Encoding */
5721 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
5722 [self twoPassCheckboxChanged:nil];
5724 /* Turbo 1st pass for 2 Pass Encoding */
5725 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
5729 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
5731 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5733 [fAudLang1PopUp selectItemAtIndex: 1];
5735 [self audioTrackPopUpChanged: fAudLang1PopUp];
5736 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
5737 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5738 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
5739 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5741 if ([fAudTrack1MixPopUp selectedItem] == nil)
5743 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5745 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
5746 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5747 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
5749 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
5751 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
5752 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5754 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
5756 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5758 [fAudLang2PopUp selectItemAtIndex: 1];
5760 [self audioTrackPopUpChanged: fAudLang2PopUp];
5761 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
5762 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5763 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
5764 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5766 if ([fAudTrack2MixPopUp selectedItem] == nil)
5768 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5770 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
5771 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5772 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
5774 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
5776 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
5777 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5779 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
5781 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5783 [fAudLang3PopUp selectItemAtIndex: 1];
5785 [self audioTrackPopUpChanged: fAudLang3PopUp];
5786 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
5787 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5788 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
5789 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5791 if ([fAudTrack3MixPopUp selectedItem] == nil)
5793 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5795 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
5796 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5797 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
5799 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
5801 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
5802 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5804 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
5806 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5808 [fAudLang4PopUp selectItemAtIndex: 1];
5810 [self audioTrackPopUpChanged: fAudLang4PopUp];
5811 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
5812 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5813 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
5814 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5816 if ([fAudTrack4MixPopUp selectedItem] == nil)
5818 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5820 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
5821 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5822 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
5824 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
5826 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
5827 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5830 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
5832 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
5834 [fAudLang2PopUp selectItemAtIndex: 0];
5835 [self audioTrackPopUpChanged: fAudLang2PopUp];
5837 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
5839 [fAudLang3PopUp selectItemAtIndex: 0];
5840 [self audioTrackPopUpChanged: fAudLang3PopUp];
5842 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
5844 [fAudLang4PopUp selectItemAtIndex: 0];
5845 [self audioTrackPopUpChanged: fAudLang4PopUp];
5849 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
5850 /* Forced Subtitles */
5851 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
5853 /* Picture Settings */
5854 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
5855 * height, width, keep ar, anamorphic and crop settings.
5856 * picture filters are handled separately below.
5858 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
5859 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
5860 * preset completely ignores any picture sizing values in the preset.
5862 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
5864 hb_job_t * job = fTitle->job;
5866 /* If Cropping is set to custom, then recall all four crop values from
5867 when the preset was created and apply them */
5868 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
5870 [fPictureController setAutoCrop:NO];
5872 /* Here we use the custom crop values saved at the time the preset was saved */
5873 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
5874 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
5875 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
5876 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
5879 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
5881 [fPictureController setAutoCrop:YES];
5882 /* Here we use the auto crop values determined right after scan */
5883 job->crop[0] = AutoCropTop;
5884 job->crop[1] = AutoCropBottom;
5885 job->crop[2] = AutoCropLeft;
5886 job->crop[3] = AutoCropRight;
5891 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
5892 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
5894 /* Use Max Picture settings for whatever the dvd is.*/
5895 [self revertPictureSizeToMax:nil];
5896 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5897 if (job->keep_ratio == 1)
5899 hb_fix_aspect( job, HB_KEEP_WIDTH );
5900 if( job->height > fTitle->height )
5902 job->height = fTitle->height;
5903 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5906 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5908 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
5910 /* we check to make sure the presets width/height does not exceed the sources width/height */
5911 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
5913 /* if so, then we use the sources height and width to avoid scaling up */
5914 //job->width = fTitle->width;
5915 //job->height = fTitle->height;
5916 [self revertPictureSizeToMax:nil];
5918 else // source width/height is >= the preset height/width
5920 /* we can go ahead and use the presets values for height and width */
5921 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
5922 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
5924 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5925 if (job->keep_ratio == 1)
5927 hb_fix_aspect( job, HB_KEEP_WIDTH );
5928 if( job->height > fTitle->height )
5930 job->height = fTitle->height;
5931 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5934 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5940 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
5941 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
5945 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
5946 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
5947 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
5950 [fPictureFilterController setUseDecomb:1];
5951 [fPictureFilterController setDecomb:0];
5952 [fPictureFilterController setDeinterlace:0];
5953 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
5955 /* we are using decomb */
5957 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
5959 [fPictureFilterController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
5961 /* if we are using "Custom" in the decomb setting, also set the custom string*/
5962 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 2)
5964 [fPictureFilterController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
5970 /* We are using Deinterlace */
5972 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
5974 [fPictureFilterController setUseDecomb:0];
5975 [fPictureFilterController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
5976 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
5977 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
5979 [fPictureFilterController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
5986 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
5988 [fPictureFilterController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
5989 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
5990 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 2)
5992 [fPictureFilterController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
5997 [fPictureFilterController setDetelecine:0];
6001 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
6003 [fPictureFilterController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
6004 /* if we are using "Custom" in the denoise setting, also set the custom string*/
6005 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 4)
6007 [fPictureFilterController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
6012 [fPictureFilterController setDenoise:0];
6016 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
6018 /* if its a one, then its the old on/off deblock, set on to 5*/
6019 [fPictureFilterController setDeblock:5];
6023 /* use the settings intValue */
6024 [fPictureFilterController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
6027 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
6029 [fPictureFilterController setGrayscale:1];
6033 [fPictureFilterController setGrayscale:0];
6036 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
6037 [fPictureController SetTitle:fTitle];
6038 [fPictureFilterController SetTitle:fTitle];
6039 [self calculatePictureSizing:nil];
6045 #pragma mark Manage Presets
6047 - (void) loadPresets {
6048 /* We declare the default NSFileManager into fileManager */
6049 NSFileManager * fileManager = [NSFileManager defaultManager];
6050 /*We define the location of the user presets file */
6051 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
6052 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
6053 /* We check for the presets.plist */
6054 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
6056 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
6059 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
6060 if (nil == UserPresets)
6062 UserPresets = [[NSMutableArray alloc] init];
6063 [self addFactoryPresets:nil];
6065 [fPresetsOutlineView reloadData];
6069 - (IBAction) showAddPresetPanel: (id) sender
6071 /* Deselect the currently selected Preset if there is one*/
6072 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
6074 /* Populate the preset picture settings popup here */
6075 [fPresetNewPicSettingsPopUp removeAllItems];
6076 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
6077 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
6078 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
6079 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
6080 /* Uncheck the preset use filters checkbox */
6081 [fPresetNewPicFiltersCheck setState:NSOffState];
6082 // fPresetNewFolderCheck
6083 [fPresetNewFolderCheck setState:NSOffState];
6084 /* Erase info from the input fields*/
6085 [fPresetNewName setStringValue: @""];
6086 [fPresetNewDesc setStringValue: @""];
6087 /* Show the panel */
6088 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
6091 - (IBAction) closeAddPresetPanel: (id) sender
6093 [NSApp endSheet: fAddPresetPanel];
6094 [fAddPresetPanel orderOut: self];
6097 - (IBAction)addUserPreset:(id)sender
6099 if (![[fPresetNewName stringValue] length])
6100 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
6103 /* Here we create a custom user preset */
6104 [UserPresets addObject:[self createPreset]];
6107 [self closeAddPresetPanel:nil];
6114 /* We Reload the New Table data for presets */
6115 [fPresetsOutlineView reloadData];
6116 /* We save all of the preset data here */
6124 /* We Sort the Presets By Factory or Custom */
6125 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
6126 ascending:YES] autorelease];
6127 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
6129 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
6130 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
6131 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
6134 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
6135 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
6136 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
6137 [UserPresets setArray:sortedArray];
6142 - (IBAction)insertPreset:(id)sender
6144 int index = [fPresetsOutlineView selectedRow];
6145 [UserPresets insertObject:[self createPreset] atIndex:index];
6146 [fPresetsOutlineView reloadData];
6150 - (NSDictionary *)createPreset
6152 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
6153 /* Get the New Preset Name from the field in the AddPresetPanel */
6154 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
6155 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
6156 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
6157 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
6158 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
6159 /*Set whether or not this is default, at creation set to 0*/
6160 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6161 if ([fPresetNewFolderCheck state] == YES)
6163 /* initialize and set an empty array for children here since we are a new folder */
6164 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6165 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6166 [childrenArray autorelease];
6168 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
6170 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
6171 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
6172 /* Get whether or not to use the current Picture Filter settings for the preset */
6173 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
6175 /* Get New Preset Description from the field in the AddPresetPanel*/
6176 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
6178 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
6179 /* Chapter Markers fCreateChapterMarkers*/
6180 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
6181 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6182 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
6183 /* Mux mp4 with http optimization */
6184 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
6185 /* Add iPod uuid atom */
6186 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
6190 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
6191 /* x264 Option String */
6192 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
6194 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
6195 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
6196 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
6197 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
6199 /* Video framerate */
6200 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
6202 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
6204 else // we can record the actual titleOfSelectedItem
6206 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
6209 /* 2 Pass Encoding */
6210 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
6211 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
6212 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
6213 /*Picture Settings*/
6214 hb_job_t * job = fTitle->job;
6215 /* Picture Sizing */
6216 /* Use Max Picture settings for whatever the dvd is.*/
6217 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
6218 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
6219 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
6220 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
6221 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
6223 /* Set crop settings here */
6224 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
6225 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
6226 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
6227 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
6228 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
6230 /* Picture Filters */
6231 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController useDecomb]] forKey:@"PictureDecombDeinterlace"];
6232 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController deinterlace]] forKey:@"PictureDeinterlace"];
6233 [preset setObject:[fPictureFilterController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
6234 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController detelecine]] forKey:@"PictureDetelecine"];
6235 [preset setObject:[fPictureFilterController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
6236 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController denoise]] forKey:@"PictureDenoise"];
6237 [preset setObject:[fPictureFilterController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
6238 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController deblock]] forKey:@"PictureDeblock"];
6239 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController decomb]] forKey:@"PictureDecomb"];
6240 [preset setObject:[fPictureFilterController decombCustomString] forKey:@"PictureDecombCustom"];
6241 [preset setObject:[NSNumber numberWithInt:[fPictureFilterController grayscale]] forKey:@"VideoGrayScale"];
6245 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
6247 [preset setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
6248 [preset setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
6249 [preset setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
6250 [preset setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
6251 [preset setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
6252 [preset setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
6253 [preset setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
6255 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
6257 [preset setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
6258 [preset setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
6259 [preset setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
6260 [preset setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
6261 [preset setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
6262 [preset setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
6263 [preset setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
6265 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
6267 [preset setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
6268 [preset setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
6269 [preset setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
6270 [preset setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
6271 [preset setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
6272 [preset setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
6273 [preset setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
6275 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
6277 [preset setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
6278 [preset setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
6279 [preset setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
6280 [preset setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
6281 [preset setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
6282 [preset setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
6283 [preset setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
6287 [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
6288 /* Forced Subtitles */
6289 [preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
6291 [preset autorelease];
6298 [UserPresets writeToFile:UserPresetsFile atomically:YES];
6299 /* We get the default preset in case it changed */
6300 [self getDefaultPresets:nil];
6304 - (IBAction)deletePreset:(id)sender
6308 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
6312 /* Alert user before deleting preset */
6314 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
6316 if ( status == NSAlertDefaultReturn )
6318 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6319 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6320 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6322 NSEnumerator *enumerator;
6323 NSMutableArray *presetsArrayToMod;
6324 NSMutableArray *tempArray;
6326 /* If we are a root level preset, we are modding the UserPresets array */
6327 if (presetToModLevel == 0)
6329 presetsArrayToMod = UserPresets;
6331 else // We have a parent preset, so we modify the chidren array object for key
6333 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6336 enumerator = [presetsArrayToMod objectEnumerator];
6337 tempArray = [NSMutableArray array];
6339 while (tempObject = [enumerator nextObject])
6341 NSDictionary *thisPresetDict = tempObject;
6342 if (thisPresetDict == presetToMod)
6344 [tempArray addObject:tempObject];
6348 [presetsArrayToMod removeObjectsInArray:tempArray];
6349 [fPresetsOutlineView reloadData];
6355 #pragma mark Manage Default Preset
6357 - (IBAction)getDefaultPresets:(id)sender
6359 presetHbDefault = nil;
6360 presetUserDefault = nil;
6361 presetUserDefaultParent = nil;
6362 presetUserDefaultParentParent = nil;
6363 NSMutableDictionary *presetHbDefaultParent = nil;
6364 NSMutableDictionary *presetHbDefaultParentParent = nil;
6367 BOOL userDefaultFound = NO;
6368 presetCurrentBuiltInCount = 0;
6369 /* First we iterate through the root UserPresets array to check for defaults */
6370 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6372 while (tempObject = [enumerator nextObject])
6374 NSMutableDictionary *thisPresetDict = tempObject;
6375 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6377 presetHbDefault = thisPresetDict;
6379 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6381 presetUserDefault = thisPresetDict;
6382 userDefaultFound = YES;
6384 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
6386 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
6390 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6391 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6393 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
6394 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6396 while (tempObject = [enumerator nextObject])
6398 NSMutableDictionary *thisPresetDict = tempObject;
6399 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6401 presetHbDefault = thisPresetDict;
6402 presetHbDefaultParent = thisPresetDictParent;
6404 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6406 presetUserDefault = thisPresetDict;
6407 presetUserDefaultParent = thisPresetDictParent;
6408 userDefaultFound = YES;
6411 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6412 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6414 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
6415 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6417 while (tempObject = [enumerator nextObject])
6419 NSMutableDictionary *thisPresetDict = tempObject;
6420 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6422 presetHbDefault = thisPresetDict;
6423 presetHbDefaultParent = thisPresetDictParent;
6424 presetHbDefaultParentParent = thisPresetDictParentParent;
6426 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6428 presetUserDefault = thisPresetDict;
6429 presetUserDefaultParent = thisPresetDictParent;
6430 presetUserDefaultParentParent = thisPresetDictParentParent;
6431 userDefaultFound = YES;
6440 /* check to see if a user specified preset was found, if not then assign the parents for
6441 * the presetHbDefault so that we can open the parents for the nested presets
6443 if (userDefaultFound == NO)
6445 presetUserDefaultParent = presetHbDefaultParent;
6446 presetUserDefaultParentParent = presetHbDefaultParentParent;
6450 - (IBAction)setDefaultPreset:(id)sender
6452 /* We need to determine if the item is a folder */
6453 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
6459 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6461 /* First make sure the old user specified default preset is removed */
6462 while (tempObject = [enumerator nextObject])
6464 NSMutableDictionary *thisPresetDict = tempObject;
6465 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6467 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6470 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6471 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6473 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6476 while (tempObject = [enumerator nextObject])
6478 NSMutableDictionary *thisPresetDict1 = tempObject;
6479 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6481 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6483 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6484 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
6486 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
6489 while (tempObject = [enumerator nextObject])
6491 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6493 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6506 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6507 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6508 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6511 NSMutableArray *presetsArrayToMod;
6512 NSMutableArray *tempArray;
6514 /* If we are a root level preset, we are modding the UserPresets array */
6515 if (presetToModLevel == 0)
6517 presetsArrayToMod = UserPresets;
6519 else // We have a parent preset, so we modify the chidren array object for key
6521 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6524 enumerator = [presetsArrayToMod objectEnumerator];
6525 tempArray = [NSMutableArray array];
6527 while (tempObject = [enumerator nextObject])
6529 NSDictionary *thisPresetDict = tempObject;
6530 if (thisPresetDict == presetToMod)
6532 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
6534 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
6541 /* We save all of the preset data here */
6543 /* We Reload the New Table data for presets */
6544 [fPresetsOutlineView reloadData];
6547 - (IBAction)selectDefaultPreset:(id)sender
6549 NSMutableDictionary *presetToMod;
6550 /* if there is a user specified default, we use it */
6551 if (presetUserDefault)
6553 presetToMod = presetUserDefault;
6555 else if (presetHbDefault) //else we use the built in default presetHbDefault
6557 presetToMod = presetHbDefault;
6564 if (presetUserDefaultParent != nil)
6566 [fPresetsOutlineView expandItem:presetUserDefaultParent];
6569 if (presetUserDefaultParentParent != nil)
6571 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
6575 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
6576 [self selectPreset:nil];
6581 #pragma mark Manage Built In Presets
6584 - (IBAction)deleteFactoryPresets:(id)sender
6587 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6591 NSMutableArray *tempArray;
6594 tempArray = [NSMutableArray array];
6595 /* we look here to see if the preset is we move on to the next one */
6596 while ( tempObject = [enumerator nextObject] )
6598 /* if the preset is "Factory" then we put it in the array of
6599 presets to delete */
6600 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
6602 [tempArray addObject:tempObject];
6606 [UserPresets removeObjectsInArray:tempArray];
6607 [fPresetsOutlineView reloadData];
6612 /* We use this method to recreate new, updated factory
6614 - (IBAction)addFactoryPresets:(id)sender
6617 /* First, we delete any existing built in presets */
6618 [self deleteFactoryPresets: sender];
6619 /* Then we generate new built in presets programmatically with fPresetsBuiltin
6620 * which is all setup in HBPresets.h and HBPresets.m*/
6621 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
6633 /*******************************
6634 * Subclass of the HBPresetsOutlineView *
6635 *******************************/
6637 @implementation HBPresetsOutlineView
6638 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
6642 // By default, NSTableView only drags an image of the first column. Change this to
6643 // drag an image of the queue's icon and PresetName columns.
6644 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
6645 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
6650 - (void) mouseDown:(NSEvent *)theEvent
6652 [super mouseDown:theEvent];
6658 - (BOOL) isDragging;