1 /* $Id: Controller.mm,v 1.79 2005/11/04 19:41:32 titer Exp $
3 This file is part of the HandBrake source code.
4 Homepage: <http://handbrake.fr/>.
5 It may be used under the terms of the GNU General Public License. */
8 #import "HBOutputPanelController.h"
9 #import "HBPreferencesController.h"
10 #import "HBDVDDetector.h"
12 #import "HBPreviewController.h"
14 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
16 /* We setup the toolbar values here */
17 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
18 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
19 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
20 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
21 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
22 static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
23 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
24 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
27 /*******************************
28 * HBController implementation *
29 *******************************/
30 @implementation HBController
40 [HBPreferencesController registerUserDefaults];
42 fQueueEncodeLibhb = NULL;
43 /* Check for check for the app support directory here as
44 * outputPanel needs it right away, as may other future methods
46 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
48 YES ) objectAtIndex:0];
49 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
50 stringByAppendingPathComponent:@"HandBrake"];
51 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
53 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
56 /* Check for and create the App Support Preview directory if necessary */
57 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
58 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
60 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
63 outputPanel = [[HBOutputPanelController alloc] init];
64 fPictureController = [[PictureController alloc] init];
65 //fPreviewController = [[PreviewController alloc] init];
66 fQueueController = [[HBQueueController alloc] init];
67 fAdvancedOptions = [[HBAdvancedController alloc] init];
68 /* we init the HBPresets class which currently is only used
69 * for updating built in presets, may move more functionality
72 fPresetsBuiltin = [[HBPresets alloc] init];
73 fPreferencesController = [[HBPreferencesController alloc] init];
74 /* Lets report the HandBrake version number here to the activity log and text log file */
75 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleGetInfoString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
76 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
82 - (void) applicationDidFinishLaunching: (NSNotification *) notification
84 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
85 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
86 fHandle = hb_init(loggingLevel, 0);
87 /* Init a separate instance of libhb for user scanning and setting up jobs */
88 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
90 // Set the Growl Delegate
91 [GrowlApplicationBridge setGrowlDelegate: self];
92 /* Init others controllers */
93 [fPictureController SetHandle: fHandle];
94 [fPictureController setHBController: self];
95 /* fPreviewController */
96 //[fPreviewController SetHandle: fHandle];
97 //[fPreviewController setHBController: self];
99 [fQueueController setHandle: fQueueEncodeLibhb];
100 [fQueueController setHBController: self];
102 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
103 [fChapterTable setDataSource:fChapterTitlesDelegate];
104 [fChapterTable setDelegate:fChapterTitlesDelegate];
106 [fPresetsOutlineView setAutosaveName:@"Presets View"];
107 [fPresetsOutlineView setAutosaveExpandedItems:YES];
109 /* Call UpdateUI every 1/2 sec */
110 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
111 scheduledTimerWithTimeInterval:0.5 target:self
112 selector:@selector(updateUI:) userInfo:nil repeats:YES]
113 forMode:NSEventTrackingRunLoopMode];
115 // Open debug output window now if it was visible when HB was closed
116 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
117 [self showDebugOutputPanel:nil];
119 // Open queue window now if it was visible when HB was closed
120 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
121 [self showQueueWindow:nil];
123 [self openMainWindow:nil];
125 /* We have to set the bool to tell hb what to do after a scan
126 * Initially we set it to NO until we start processing the queue
128 applyQueueToScan = NO;
130 /* Now we re-check the queue array to see if there are
131 * any remaining encodes to be done in it and ask the
132 * user if they want to reload the queue */
133 if ([QueueFileArray count] > 0)
135 /* run getQueueStats to see whats in the queue file */
136 [self getQueueStats];
137 /* this results in these values
138 * fEncodingQueueItem = 0;
140 * fCompletedCount = 0;
141 * fCanceledCount = 0;
145 /*On Screen Notification*/
146 NSString * alertTitle;
147 if (fWorkingCount > 0)
149 alertTitle = [NSString stringWithFormat:
150 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
151 fWorkingCount,fPendingCount];
155 alertTitle = [NSString stringWithFormat:
156 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
159 NSBeginCriticalAlertSheet(
161 NSLocalizedString(@"Reload Queue", nil),
163 NSLocalizedString(@"Empty Queue", nil),
165 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
166 NSLocalizedString(@" Do you want to reload them ?", nil));
167 // call didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
168 // right below to either clear the old queue or keep it loaded up.
172 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
173 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
175 [self browseSources:nil];
178 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
180 [self browseSources:(id)fOpenSourceTitleMMenu];
185 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
187 if (returnCode == NSAlertOtherReturn)
189 [self clearQueueAllItems];
190 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
191 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
193 [self browseSources:nil];
196 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
198 [self browseSources:(id)fOpenSourceTitleMMenu];
203 [self setQueueEncodingItemsAsPending];
204 [self showQueueWindow:NULL];
208 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
210 [fPreviewController goWindowedScreen:nil];
211 // Warn if encoding a movie
213 hb_get_state( fQueueEncodeLibhb, &s );
215 if ( s.state != HB_STATE_IDLE )
217 int result = NSRunCriticalAlertPanel(
218 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
219 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
220 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
222 if (result == NSAlertDefaultReturn)
224 return NSTerminateNow;
227 return NSTerminateCancel;
230 // Warn if items still in the queue
231 else if ( fPendingCount > 0 )
233 int result = NSRunCriticalAlertPanel(
234 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
235 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
236 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
238 if ( result == NSAlertDefaultReturn )
239 return NSTerminateNow;
241 return NSTerminateCancel;
244 return NSTerminateNow;
247 - (void)applicationWillTerminate:(NSNotification *)aNotification
249 [browsedSourceDisplayName release];
250 [outputPanel release];
251 [fQueueController release];
252 [fPictureController release];
254 [fPreviewController release];
256 hb_close(&fQueueEncodeLibhb);
260 - (void) awakeFromNib
263 [fWindow setExcludedFromWindowsMenu:YES];
264 [fAdvancedOptions setView:fAdvancedView];
266 /* lets setup our presets drawer for drag and drop here */
267 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
268 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
269 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
271 /* Initialize currentScanCount so HB can use it to
272 evaluate successive scans */
273 currentScanCount = 0;
276 /* Init UserPresets .plist */
279 /* Init QueueFile .plist */
280 [self loadQueueFile];
282 fRipIndicatorShown = NO; // initially out of view in the nib
284 /* Show/Dont Show Presets drawer upon launch based
285 on user preference DefaultPresetsDrawerShow*/
286 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
288 [fPresetDrawer setDelegate:self];
289 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
290 stringForKey:@"Drawer Size"] );
291 if( drawerSize.width )
292 [fPresetDrawer setContentSize: drawerSize];
293 [fPresetDrawer open];
297 NSMenuItem *menuItem;
298 [fDstFormatPopUp removeAllItems];
300 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
301 [menuItem setTag: HB_MUX_MP4];
303 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
304 [menuItem setTag: HB_MUX_MKV];
306 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"AVI file" action: NULL keyEquivalent: @""];
307 [menuItem setTag: HB_MUX_AVI];
309 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"OGM file" action: NULL keyEquivalent: @""];
310 [menuItem setTag: HB_MUX_OGM];
311 [fDstFormatPopUp selectItemAtIndex: 0];
313 [self formatPopUpChanged:nil];
315 /* We enable the create chapters checkbox here since we are .mp4 */
316 [fCreateChapterMarkers setEnabled: YES];
317 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
319 [fCreateChapterMarkers setState: NSOnState];
325 [fDstFile2Field setStringValue: [NSString stringWithFormat:
326 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
329 [fVidEncoderPopUp removeAllItems];
330 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
331 [fVidEncoderPopUp addItemWithTitle: @"XviD"];
336 [fVidTargetSizeField setIntValue: 700];
337 [fVidBitrateField setIntValue: 1000];
339 [fVidQualityMatrix selectCell: fVidBitrateCell];
340 [self videoMatrixChanged:nil];
342 /* Video framerate */
343 [fVidRatePopUp removeAllItems];
344 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
345 for( int i = 0; i < hb_video_rates_count; i++ )
347 if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
349 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
350 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
352 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
354 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
355 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
357 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
359 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
360 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
364 [fVidRatePopUp addItemWithTitle:
365 [NSString stringWithCString: hb_video_rates[i].string]];
368 [fVidRatePopUp selectItemAtIndex: 0];
370 /* Set Auto Crop to On at launch */
371 [fPictureController setAutoCrop:YES];
374 [fAudTrack1BitratePopUp removeAllItems];
375 for( int i = 0; i < hb_audio_bitrates_count; i++ )
377 [fAudTrack1BitratePopUp addItemWithTitle:
378 [NSString stringWithCString: hb_audio_bitrates[i].string]];
381 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
383 /* Audio samplerate */
384 [fAudTrack1RatePopUp removeAllItems];
385 for( int i = 0; i < hb_audio_rates_count; i++ )
387 [fAudTrack1RatePopUp addItemWithTitle:
388 [NSString stringWithCString: hb_audio_rates[i].string]];
390 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
393 [fStatusField setStringValue: @""];
398 /* We disable the Turbo 1st pass checkbox since we are not x264 */
399 [fVidTurboPassCheck setEnabled: NO];
400 [fVidTurboPassCheck setState: NSOffState];
403 /* lets get our default prefs here */
404 [self getDefaultPresets:nil];
405 /* lets initialize the current successful scancount here to 0 */
406 currentSuccessfulScanCount = 0;
411 - (void) enableUI: (bool) b
413 NSControl * controls[] =
414 { fSrcTitleField, fSrcTitlePopUp,
415 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
416 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
417 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
418 fDstBrowseButton, fVidRateField, fVidRatePopUp,
419 fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
420 fVidQualityMatrix, fVidGrayscaleCheck, fSubField, fSubPopUp,
421 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
422 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
423 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
424 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
425 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
426 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
427 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
428 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
429 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
430 fQueueStatus,fPicSettingARkeep, fPicSettingDeinterlace,fPicLabelSettings,fPicLabelSrc,
431 fPicLabelOutp,fPicSettingsSrc,fPicSettingsOutp,fPicSettingsAnamorphic,
432 fPicLabelAr,fPicLabelDeinterlace,fPicSettingPAR,fPicLabelAnamorphic,fPresetsAdd,fPresetsDelete,
433 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fPicLabelAutoCrop,
434 fPicSettingAutoCrop,fPicSettingDetelecine,fPicLabelDetelecine,fPicLabelDenoise,fPicSettingDenoise,
435 fSubForcedCheck,fPicSettingDeblock,fPicLabelDeblock,fPicLabelDecomb,fPicSettingDecomb,fPresetsOutlineView,
436 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck};
439 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
441 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
443 NSTextField * tf = (NSTextField *) controls[i];
444 if( ![tf isBezeled] )
446 [tf setTextColor: b ? [NSColor controlTextColor] :
447 [NSColor disabledControlTextColor]];
451 [controls[i] setEnabled: b];
457 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
458 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
459 [self setEnabledStateOfAudioMixdownControls:nil];
460 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
461 [self calculatePictureSizing:nil];
465 [fPresetsOutlineView setEnabled: NO];
469 [self videoMatrixChanged:nil];
470 [fAdvancedOptions enableUI:b];
474 /***********************************************************************
476 ***********************************************************************
477 * Shows a progression bar on the dock icon, filled according to
478 * 'progress' (0.0 <= progress <= 1.0).
479 * Called with progress < 0.0 or progress > 1.0, restores the original
481 **********************************************************************/
482 - (void) UpdateDockIcon: (float) progress
486 NSBitmapImageRep * bmp;
488 uint32_t black = htonl( 0x000000FF );
489 uint32_t red = htonl( 0xFF0000FF );
490 uint32_t white = htonl( 0xFFFFFFFF );
491 int row_start, row_end;
494 /* Get application original icon */
495 icon = [NSImage imageNamed: @"NSApplicationIcon"];
497 if( progress < 0.0 || progress > 1.0 )
499 [NSApp setApplicationIconImage: icon];
503 /* Get it in a raw bitmap form */
504 tiff = [icon TIFFRepresentationUsingCompression:
505 NSTIFFCompressionNone factor: 1.0];
506 bmp = [NSBitmapImageRep imageRepWithData: tiff];
508 /* Draw the progression bar */
509 /* It's pretty simple (ugly?) now, but I'm no designer */
511 row_start = 3 * (int) [bmp size].height / 4;
512 row_end = 7 * (int) [bmp size].height / 8;
514 for( i = row_start; i < row_start + 2; i++ )
516 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
517 for( j = 0; j < (int) [bmp size].width; j++ )
522 for( i = row_start + 2; i < row_end - 2; i++ )
524 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
527 for( j = 2; j < (int) [bmp size].width - 2; j++ )
529 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
541 for( i = row_end - 2; i < row_end; i++ )
543 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
544 for( j = 0; j < (int) [bmp size].width; j++ )
550 /* Now update the dock icon */
551 tiff = [bmp TIFFRepresentationUsingCompression:
552 NSTIFFCompressionNone factor: 1.0];
553 icon = [[NSImage alloc] initWithData: tiff];
554 [NSApp setApplicationIconImage: icon];
558 - (void) updateUI: (NSTimer *) timer
561 /* Update UI for fHandle (user scanning instance of libhb ) */
564 list = hb_get_titles( fHandle );
565 /* check to see if there has been a new scan done
566 this bypasses the constraints of HB_STATE_WORKING
567 not allowing setting a newly scanned source */
568 int checkScanCount = hb_get_scancount( fHandle );
569 if( checkScanCount > currentScanCount )
571 currentScanCount = checkScanCount;
572 [fScanIndicator setIndeterminate: NO];
573 [fScanIndicator setDoubleValue: 0.0];
574 [fScanIndicator setHidden: YES];
575 [self showNewScan:nil];
579 hb_get_state( fHandle, &s );
585 #define p s.param.scanning
586 case HB_STATE_SCANNING:
588 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
589 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
590 p.title_cur, p.title_count]];
591 [fScanIndicator setHidden: NO];
592 [fScanIndicator setDoubleValue: 100.0 * ( p.title_cur - 1 ) / p.title_count];
597 #define p s.param.scandone
598 case HB_STATE_SCANDONE:
600 [fScanIndicator setIndeterminate: NO];
601 [fScanIndicator setDoubleValue: 0.0];
602 [fScanIndicator setHidden: YES];
603 [self writeToActivityLog:"ScanDone state received from fHandle"];
604 [self showNewScan:nil];
605 [[fWindow toolbar] validateVisibleItems];
611 #define p s.param.working
612 case HB_STATE_WORKING:
619 #define p s.param.muxing
620 case HB_STATE_MUXING:
627 case HB_STATE_PAUSED:
630 case HB_STATE_WORKDONE:
637 /* Update UI for fQueueEncodeLibhb */
639 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
640 /* check to see if there has been a new scan done
641 this bypasses the constraints of HB_STATE_WORKING
642 not allowing setting a newly scanned source */
644 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
645 if( checkScanCount > currentScanCount )
647 currentScanCount = checkScanCount;
648 [self writeToActivityLog:"currentScanCount received from fQueueEncodeLibhb"];
652 hb_get_state( fQueueEncodeLibhb, &s );
658 #define p s.param.scanning
659 case HB_STATE_SCANNING:
661 [fStatusField setStringValue: [NSString stringWithFormat:
662 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
663 p.title_cur, p.title_count]];
665 /* Set the status string in fQueueController as well */
666 [fQueueController setQueueStatusString: [NSString stringWithFormat:
667 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
668 p.title_cur, p.title_count]];
670 [fRipIndicator setHidden: NO];
671 [fRipIndicator setDoubleValue: 100.0 * ( p.title_cur - 1 ) / p.title_count];
676 #define p s.param.scandone
677 case HB_STATE_SCANDONE:
679 [fRipIndicator setIndeterminate: NO];
680 [fRipIndicator setDoubleValue: 0.0];
682 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
683 [self processNewQueueEncode];
684 [[fWindow toolbar] validateVisibleItems];
690 #define p s.param.working
691 case HB_STATE_WORKING:
693 float progress_total;
694 NSMutableString * string;
695 /* Update text field */
696 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d of %d, %.2f %%", @"" ), p.job_cur, p.job_count, 100.0 * p.progress];
700 [string appendFormat:
701 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
702 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
705 [fStatusField setStringValue: string];
706 /* Set the status string in fQueueController as well */
707 [fQueueController setQueueStatusString: string];
709 progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
710 [fRipIndicator setIndeterminate: NO];
711 [fRipIndicator setDoubleValue: 100.0 * progress_total];
713 // If progress bar hasn't been revealed at the bottom of the window, do
714 // that now. This code used to be in doRip. I moved it to here to handle
715 // the case where hb_start is called by HBQueueController and not from
717 if( !fRipIndicatorShown )
719 NSRect frame = [fWindow frame];
720 if( frame.size.width <= 591 )
721 frame.size.width = 591;
722 frame.size.height += 36;
723 frame.origin.y -= 36;
724 [fWindow setFrame:frame display:YES animate:YES];
725 fRipIndicatorShown = YES;
729 /* Update dock icon */
730 [self UpdateDockIcon: progress_total];
736 #define p s.param.muxing
737 case HB_STATE_MUXING:
739 /* Update text field */
740 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
741 /* Set the status string in fQueueController as well */
742 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
744 [fRipIndicator setIndeterminate: YES];
745 [fRipIndicator startAnimation: nil];
747 /* Update dock icon */
748 [self UpdateDockIcon: 1.0];
754 case HB_STATE_PAUSED:
755 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
756 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
760 case HB_STATE_WORKDONE:
762 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
763 // or someone calling hb_stop. In the latter case, hb_stop does not clear
764 // out the remaining passes/jobs in the queue. We'll do that here.
766 // Delete all remaining jobs of this encode.
767 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
768 /* Set the status string in fQueueController as well */
769 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
770 [fRipIndicator setIndeterminate: NO];
771 [fRipIndicator setDoubleValue: 0.0];
772 [[fWindow toolbar] validateVisibleItems];
774 /* Restore dock icon */
775 [self UpdateDockIcon: -1.0];
777 if( fRipIndicatorShown )
779 NSRect frame = [fWindow frame];
780 if( frame.size.width <= 591 )
781 frame.size.width = 591;
782 frame.size.height += -36;
783 frame.origin.y -= -36;
784 [fWindow setFrame:frame display:YES animate:YES];
785 fRipIndicatorShown = NO;
787 /* Since we are done with this encode, tell output to stop writing to the
788 * individual encode log
790 [outputPanel endEncodeLog];
791 /* Check to see if the encode state has not been cancelled
792 to determine if we should check for encode done notifications */
793 if( fEncodeState != 2 )
795 NSString *pathOfFinishedEncode;
796 /* Get the output file name for the finished encode */
797 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
799 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
801 [self showGrowlDoneNotification:pathOfFinishedEncode];
803 [self sendToMetaX:pathOfFinishedEncode];
805 /* since we have successfully completed an encode, we increment the queue counter */
806 [self incrementQueueItemDone:nil];
808 /* all end of queue actions below need to be done after all queue encodes have finished
809 * and there are no pending jobs left to process
811 if (fPendingCount == 0)
813 /* If Alert Window or Window and Growl has been selected */
814 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
815 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
817 /*On Screen Notification*/
820 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
821 [NSApp requestUserAttention:NSCriticalRequest];
824 /* If sleep has been selected */
825 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
828 NSDictionary* errorDict;
829 NSAppleEventDescriptor* returnDescriptor = nil;
830 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
831 @"tell application \"Finder\" to sleep"];
832 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
833 [scriptObject release];
835 /* If Shutdown has been selected */
836 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
839 NSDictionary* errorDict;
840 NSAppleEventDescriptor* returnDescriptor = nil;
841 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
842 @"tell application \"Finder\" to shut down"];
843 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
844 [scriptObject release];
858 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
859 - (void) writeToActivityLog:(char *) format, ...
862 va_start(args, format);
866 vsnprintf( str, 1024, format, args );
868 time_t _now = time( NULL );
869 struct tm * now = localtime( &_now );
870 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
877 // ============================================================
878 // NSToolbar Related Methods
879 // ============================================================
881 - (void) setupToolbar {
882 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
884 [toolbar setAllowsUserCustomization: YES];
885 [toolbar setAutosavesConfiguration: YES];
886 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
888 [toolbar setDelegate: self];
890 [fWindow setToolbar: toolbar];
893 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
894 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
895 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
897 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
899 [item setLabel: @"Toggle Presets"];
900 [item setPaletteLabel: @"Toggler Presets"];
901 [item setToolTip: @"Open/Close Preset Drawer"];
902 [item setImage: [NSImage imageNamed: @"Drawer"]];
903 [item setTarget: self];
904 [item setAction: @selector(toggleDrawer:)];
905 [item setAutovalidates: NO];
907 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
909 [item setLabel: @"Start"];
910 [item setPaletteLabel: @"Start Encoding"];
911 [item setToolTip: @"Start Encoding"];
912 [item setImage: [NSImage imageNamed: @"Play"]];
913 [item setTarget: self];
914 [item setAction: @selector(Rip:)];
916 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
918 [item setLabel: @"Show Queue"];
919 [item setPaletteLabel: @"Show Queue"];
920 [item setToolTip: @"Show Queue"];
921 [item setImage: [NSImage imageNamed: @"Queue"]];
922 [item setTarget: self];
923 [item setAction: @selector(showQueueWindow:)];
924 [item setAutovalidates: NO];
926 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
928 [item setLabel: @"Add to Queue"];
929 [item setPaletteLabel: @"Add to Queue"];
930 [item setToolTip: @"Add to Queue"];
931 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
932 [item setTarget: self];
933 [item setAction: @selector(addToQueue:)];
935 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
937 [item setLabel: @"Pause"];
938 [item setPaletteLabel: @"Pause Encoding"];
939 [item setToolTip: @"Pause Encoding"];
940 [item setImage: [NSImage imageNamed: @"Pause"]];
941 [item setTarget: self];
942 [item setAction: @selector(Pause:)];
944 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
946 [item setLabel: @"Picture Settings"];
947 [item setPaletteLabel: @"Show Picture Settings"];
948 [item setToolTip: @"Show Picture Settings"];
949 [item setImage: [NSImage imageNamed: @"pref-picture"]];
950 [item setTarget: self];
951 [item setAction: @selector(showPicturePanel:)];
953 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
955 [item setLabel: @"Activity Window"];
956 [item setPaletteLabel: @"Show Activity Window"];
957 [item setToolTip: @"Show Activity Window"];
958 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
959 [item setTarget: self];
960 [item setAction: @selector(showDebugOutputPanel:)];
961 [item setAutovalidates: NO];
963 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
965 [item setLabel: @"Source"];
966 [item setPaletteLabel: @"Source"];
967 [item setToolTip: @"Choose Video Source"];
968 [item setImage: [NSImage imageNamed: @"Source"]];
969 [item setTarget: self];
970 [item setAction: @selector(browseSources:)];
980 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
982 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
983 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
984 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
987 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
989 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
990 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
991 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
992 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
995 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
997 NSString * ident = [toolbarItem itemIdentifier];
1002 hb_get_state2( fQueueEncodeLibhb, &s );
1004 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
1006 if ([ident isEqualToString: StartEncodingIdentifier])
1008 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1009 [toolbarItem setLabel: @"Stop"];
1010 [toolbarItem setPaletteLabel: @"Stop"];
1011 [toolbarItem setToolTip: @"Stop Encoding"];
1014 if ([ident isEqualToString: PauseEncodingIdentifier])
1016 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1017 [toolbarItem setLabel: @"Pause"];
1018 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1019 [toolbarItem setToolTip: @"Pause Encoding"];
1024 if ([ident isEqualToString: AddToQueueIdentifier])
1026 if ([ident isEqualToString: ShowPictureIdentifier])
1030 else if (s.state == HB_STATE_PAUSED)
1032 if ([ident isEqualToString: PauseEncodingIdentifier])
1034 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1035 [toolbarItem setLabel: @"Resume"];
1036 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1037 [toolbarItem setToolTip: @"Resume Encoding"];
1040 if ([ident isEqualToString: StartEncodingIdentifier])
1042 if ([ident isEqualToString: AddToQueueIdentifier])
1044 if ([ident isEqualToString: ShowPictureIdentifier])
1047 else if (s.state == HB_STATE_SCANNING)
1049 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1051 if ([ident isEqualToString: StartEncodingIdentifier])
1053 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1054 if (hb_count(fHandle) > 0)
1055 [toolbarItem setLabel: @"Start Queue"];
1057 [toolbarItem setLabel: @"Start"];
1058 [toolbarItem setPaletteLabel: @"Start Encoding"];
1059 [toolbarItem setToolTip: @"Start Encoding"];
1062 if ([ident isEqualToString: AddToQueueIdentifier])
1064 if ([ident isEqualToString: ShowPictureIdentifier])
1069 /* If there are any pending queue items, make sure the start/stop button is active */
1070 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1072 if ([ident isEqualToString: ShowQueueIdentifier])
1074 if ([ident isEqualToString: ToggleDrawerIdentifier])
1076 if ([ident isEqualToString: ChooseSourceIdentifier])
1078 if ([ident isEqualToString: ShowActivityIdentifier])
1084 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1086 SEL action = [menuItem action];
1089 hb_get_state2( fHandle, &s );
1093 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1094 return SuccessfulScan && [fWindow attachedSheet] == nil;
1096 if (action == @selector(browseSources:))
1098 if (s.state == HB_STATE_SCANNING)
1101 return [fWindow attachedSheet] == nil;
1103 if (action == @selector(selectDefaultPreset:))
1104 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1105 if (action == @selector(Pause:))
1107 if (s.state == HB_STATE_WORKING)
1109 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1110 [menuItem setTitle:@"Pause Encoding"];
1113 else if (s.state == HB_STATE_PAUSED)
1115 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1116 [menuItem setTitle:@"Resume Encoding"];
1122 if (action == @selector(Rip:))
1124 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1126 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1127 [menuItem setTitle:@"Stop Encoding"];
1130 else if (SuccessfulScan)
1132 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1133 [menuItem setTitle:@"Start Encoding"];
1134 return [fWindow attachedSheet] == nil;
1140 if( action == @selector(setDefaultPreset:) )
1142 return [fPresetsOutlineView selectedRow] != -1;
1149 #pragma mark Encode Done Actions
1150 // register a test notification and make
1151 // it enabled by default
1152 #define SERVICE_NAME @"Encode Done"
1153 - (NSDictionary *)registrationDictionaryForGrowl
1155 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1156 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1157 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1160 return registrationDictionary;
1163 -(void)showGrowlDoneNotification:(NSString *) filePath
1165 /* This end of encode action is called as each encode rolls off of the queue */
1166 NSString * finishedEncode = filePath;
1167 /* strip off the path to just show the file name */
1168 finishedEncode = [finishedEncode lastPathComponent];
1169 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1170 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1172 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1173 [GrowlApplicationBridge
1174 notifyWithTitle:@"Put down that cocktail..."
1175 description:growlMssg
1176 notificationName:SERVICE_NAME
1184 -(void)sendToMetaX:(NSString *) filePath
1186 /* This end of encode action is called as each encode rolls off of the queue */
1187 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1189 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
1190 [myScript executeAndReturnError: nil];
1195 #pragma mark Get New Source
1197 /*Opens the source browse window, called from Open Source widgets */
1198 - (IBAction) browseSources: (id) sender
1200 NSOpenPanel * panel;
1202 panel = [NSOpenPanel openPanel];
1203 [panel setAllowsMultipleSelection: NO];
1204 [panel setCanChooseFiles: YES];
1205 [panel setCanChooseDirectories: YES ];
1206 NSString * sourceDirectory;
1207 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1209 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1213 sourceDirectory = @"~/Desktop";
1214 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1216 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1217 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1219 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1220 modalForWindow: fWindow modalDelegate: self
1221 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1222 contextInfo: sender];
1225 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1226 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1228 /* we convert the sender content of contextInfo back into a variable called sender
1229 * mostly just for consistency for evaluation later
1231 id sender = (id)contextInfo;
1232 /* User selected a file to open */
1233 if( returnCode == NSOKButton )
1235 /* Free display name allocated previously by this code */
1236 [browsedSourceDisplayName release];
1238 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1239 /* we set the last searched source directory in the prefs here */
1240 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1241 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1242 /* we order out sheet, which is the browse window as we need to open
1243 * the title selection sheet right away
1245 [sheet orderOut: self];
1247 if (sender == fOpenSourceTitleMMenu)
1249 /* We put the chosen source path in the source display text field for the
1250 * source title selection sheet in which the user specifies the specific title to be
1251 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1252 * purposes in the title panel
1255 [fScanSrcTitlePathField setStringValue:scanPath];
1256 NSString *displayTitlescanSourceName;
1258 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1260 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1261 we have to use the title->dvd value so we get the proper name of the volume if a physical dvd is the source*/
1262 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1266 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1267 displayTitlescanSourceName = [scanPath lastPathComponent];
1269 /* we set the source display name in the title selection dialogue */
1270 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1271 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1272 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1273 /* We show the actual sheet where the user specifies the title to be scanned
1274 * as we are going to do a title specific scan
1276 [self showSourceTitleScanPanel:nil];
1280 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1281 NSString *path = [[sheet filenames] objectAtIndex: 0];
1283 /* We check to see if the chosen file at path is a package */
1284 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1286 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1287 /* We check to see if this is an .eyetv package */
1288 if ([[path pathExtension] isEqualToString: @"eyetv"])
1290 [self writeToActivityLog:"trying to open eyetv package"];
1291 /* We're looking at an EyeTV package - try to open its enclosed
1293 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1295 int n = [[path stringByAppendingString: @"/"]
1296 completePathIntoString: &mpgname caseSensitive: NO
1297 matchesIntoArray: nil
1298 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1301 /* Found an mpeg inside the eyetv package, make it our scan path
1302 and call performScan on the enclosed mpeg */
1304 [self writeToActivityLog:"found mpeg in eyetv package"];
1305 [self performScan:path scanTitleNum:0];
1309 /* We did not find an mpeg file in our package, so we do not call performScan */
1310 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1313 /* We check to see if this is a .dvdmedia package */
1314 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1316 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1317 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1318 [self writeToActivityLog:"trying to open dvdmedia package"];
1319 [self performScan:path scanTitleNum:0];
1323 /* The package is not an eyetv package, so we do not call performScan */
1324 [self writeToActivityLog:"unable to open package"];
1327 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1329 /* path is not a package, so we call perform scan directly on our file */
1330 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1332 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1333 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1334 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1338 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1339 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1340 /* make sure we remove any path extension as this can also be an '.mpg' file */
1341 browsedSourceDisplayName = [[path lastPathComponent] retain];
1343 [self performScan:path scanTitleNum:0];
1351 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1352 - (IBAction) showSourceTitleScanPanel: (id) sender
1354 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1357 [fScanSrcTitleNumField setStringValue: @"0"];
1358 /* Show the panel */
1359 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1362 - (IBAction) closeSourceTitleScanPanel: (id) sender
1364 [NSApp endSheet: fScanSrcTitlePanel];
1365 [fScanSrcTitlePanel orderOut: self];
1367 if(sender == fScanSrcTitleOpenButton)
1369 /* We setup the scan status in the main window to indicate a source title scan */
1370 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1371 [fScanIndicator setHidden: NO];
1372 [fScanIndicator setIndeterminate: YES];
1373 [fScanIndicator startAnimation: nil];
1375 /* We use the performScan method to actually perform the specified scan passing the path and the title
1378 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1382 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1383 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1385 /* set the bool applyQueueToScan so that we dont apply a queue setting to the final scan */
1386 applyQueueToScan = NO;
1387 /* use a bool to determine whether or not we can decrypt using vlc */
1388 BOOL cancelScanDecrypt = 0;
1389 NSString *path = scanPath;
1390 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1392 // Notify ChapterTitles that there's no title
1393 [fChapterTitlesDelegate resetWithTitle:nil];
1394 [fChapterTable reloadData];
1396 [self enableUI: NO];
1398 if( [detector isVideoDVD] )
1400 // The chosen path was actually on a DVD, so use the raw block
1401 // device path instead.
1402 path = [detector devicePath];
1403 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1405 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1406 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1407 NSFileManager * fileManager = [NSFileManager defaultManager];
1408 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1410 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1411 cancelScanDecrypt = 1;
1412 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1414 status = NSRunAlertPanel(@"HandBrake could not find VLC or your VLC is out of date.",@"Please download and install VLC media player in your /Applications folder if you wish to read encrypted DVDs.", @"Get VLC", @"Cancel Scan", @"Attempt Scan Anyway");
1415 [NSApp requestUserAttention:NSCriticalRequest];
1417 if (status == NSAlertDefaultReturn)
1419 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1420 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
1422 else if (status == NSAlertAlternateReturn)
1424 /* User chose to cancel the scan */
1425 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1429 /* User chose to override our warning and scan the physical dvd anyway, at their own peril. on an encrypted dvd this produces massive log files and fails */
1430 cancelScanDecrypt = 0;
1431 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1437 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1438 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1442 if (cancelScanDecrypt == 0)
1444 /* we actually pass the scan off to libhb here */
1445 /* If there is no title number passed to scan, we use "0"
1446 * which causes the default behavior of a full source scan
1452 if (scanTitleNum > 0)
1454 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1456 /* We use our advance pref to determine how many previews to scan */
1457 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1458 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1459 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1463 - (IBAction) showNewScan:(id)sender
1467 int indxpri=0; // Used to search the longuest title (default in combobox)
1468 int longuestpri=0; // Used to search the longuest title (default in combobox)
1471 list = hb_get_titles( fHandle );
1473 if( !hb_list_count( list ) )
1475 /* We display a message if a valid dvd source was not chosen */
1476 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1477 SuccessfulScan = NO;
1479 // Notify ChapterTitles that there's no title
1480 [fChapterTitlesDelegate resetWithTitle:nil];
1481 [fChapterTable reloadData];
1485 /* We increment the successful scancount here by one,
1486 which we use at the end of this function to tell the gui
1487 if this is the first successful scan since launch and whether
1488 or not we should set all settings to the defaults */
1490 currentSuccessfulScanCount++;
1492 [[fWindow toolbar] validateVisibleItems];
1494 [fSrcTitlePopUp removeAllItems];
1495 for( int i = 0; i < hb_list_count( list ); i++ )
1497 title = (hb_title_t *) hb_list_item( list, i );
1499 currentSource = [NSString stringWithUTF8String: title->name];
1500 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1501 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1503 /* Use the dvd name in the default output field here
1504 May want to add code to remove blank spaces for some dvd names*/
1505 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1506 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1508 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1509 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1513 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1514 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1518 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1520 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1524 [fSrcTitlePopUp addItemWithTitle: [NSString
1525 stringWithFormat: @"%d - %02dh%02dm%02ds",
1526 title->index, title->hours, title->minutes,
1530 // Select the longuest title
1531 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1532 [self titlePopUpChanged:nil];
1534 SuccessfulScan = YES;
1535 [self enableUI: YES];
1537 /* if its the initial successful scan after awakeFromNib */
1538 if (currentSuccessfulScanCount == 1)
1540 [self selectDefaultPreset:nil];
1541 /* initially set deinterlace to 0, will be overridden reset by the default preset anyway */
1542 //[fPictureController setDeinterlace:0];
1544 /* lets set Denoise to index 0 or "None" since this is the first scan */
1545 //[fPictureController setDenoise:0];
1547 [fPictureController setInitialPictureFilters];
1557 #pragma mark New Output Destination
1559 - (IBAction) browseFile: (id) sender
1561 /* Open a panel to let the user choose and update the text field */
1562 NSSavePanel * panel = [NSSavePanel savePanel];
1563 /* We get the current file name and path from the destination field here */
1564 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1565 modalForWindow: fWindow modalDelegate: self
1566 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1570 - (void) browseFileDone: (NSSavePanel *) sheet
1571 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1573 if( returnCode == NSOKButton )
1575 [fDstFile2Field setStringValue: [sheet filename]];
1576 /* Save this path to the prefs so that on next browse destination window it opens there */
1577 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1578 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1584 #pragma mark Main Window Control
1586 - (IBAction) openMainWindow: (id) sender
1588 [fWindow makeKeyAndOrderFront:nil];
1591 - (BOOL) windowShouldClose: (id) sender
1596 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1599 [fWindow makeKeyAndOrderFront:nil];
1607 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1608 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1613 #pragma mark Queue File
1615 - (void) loadQueueFile {
1616 /* We declare the default NSFileManager into fileManager */
1617 NSFileManager * fileManager = [NSFileManager defaultManager];
1618 /*We define the location of the user presets file */
1619 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1620 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1621 /* We check for the presets.plist */
1622 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1624 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1627 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1628 /* lets check to see if there is anything in the queue file .plist */
1629 if (nil == QueueFileArray)
1631 /* if not, then lets initialize an empty array */
1632 QueueFileArray = [[NSMutableArray alloc] init];
1634 /* Initialize our curQueueEncodeIndex to 0
1635 * so we can use it to track which queue
1636 * item is to be used to track our encodes */
1637 /* NOTE: this should be changed if and when we
1638 * are able to get the last unfinished encode
1639 * in the case of a crash or shutdown */
1644 [self clearQueueEncodedItems];
1646 currentQueueEncodeIndex = 0;
1649 - (void)addQueueFileItem
1651 [QueueFileArray addObject:[self createQueueFileItem]];
1652 [self saveQueueFileItem];
1656 - (void) removeQueueFileItem:(int) queueItemToRemove
1659 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
1660 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
1662 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
1663 * by one to keep in sync with the queue array
1665 currentQueueEncodeIndex--;
1666 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
1668 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1669 [self saveQueueFileItem];
1673 - (void)saveQueueFileItem
1675 [QueueFileArray writeToFile:QueueFile atomically:YES];
1676 [fQueueController setQueueArray: QueueFileArray];
1677 [self getQueueStats];
1680 - (void)getQueueStats
1682 /* lets get the stats on the status of the queue array */
1684 fEncodingQueueItem = 0;
1686 fCompletedCount = 0;
1690 /* We use a number system to set the encode status of the queue item
1692 * 0 == already encoded
1693 * 1 == is being encoded
1694 * 2 == is yet to be encoded
1699 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1701 while (tempObject = [enumerator nextObject])
1703 NSDictionary *thisQueueDict = tempObject;
1704 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1708 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1711 fEncodingQueueItem = i;
1713 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
1717 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
1724 /* Set the queue status field in the main window */
1725 NSMutableString * string;
1726 if (fPendingCount == 1)
1728 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
1732 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
1734 [fQueueStatus setStringValue:string];
1737 /* This method will set any item marked as encoding back to pending
1738 * currently used right after a queue reload
1740 - (void) setQueueEncodingItemsAsPending
1742 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1744 NSMutableArray *tempArray;
1745 tempArray = [NSMutableArray array];
1746 /* we look here to see if the preset is we move on to the next one */
1747 while ( tempObject = [enumerator nextObject] )
1749 /* If the queue item is marked as "encoding" (1)
1750 * then change its status back to pending (2) which effectively
1751 * puts it back into the queue to be encoded
1753 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
1755 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
1757 [tempArray addObject:tempObject];
1760 [QueueFileArray setArray:tempArray];
1761 [self saveQueueFileItem];
1765 /* This method will clear the queue of any encodes that are not still pending
1766 * this includes both successfully completed encodes as well as cancelled encodes */
1767 - (void) clearQueueEncodedItems
1769 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1771 NSMutableArray *tempArray;
1772 tempArray = [NSMutableArray array];
1773 /* we look here to see if the preset is we move on to the next one */
1774 while ( tempObject = [enumerator nextObject] )
1776 /* If the queue item is either completed (0) or cancelled (3) from the
1777 * last session, then we put it in tempArray to be deleted from QueueFileArray.
1778 * NOTE: this means we retain pending (2) and also an item that is marked as
1779 * still encoding (1). If the queue has an item that is still marked as encoding
1780 * from a previous session, we can conlude that HB was either shutdown, or crashed
1781 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
1783 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
1785 [tempArray addObject:tempObject];
1789 [QueueFileArray removeObjectsInArray:tempArray];
1790 [self saveQueueFileItem];
1793 /* This method will clear the queue of all encodes. effectively creating an empty queue */
1794 - (void) clearQueueAllItems
1796 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1798 NSMutableArray *tempArray;
1799 tempArray = [NSMutableArray array];
1800 /* we look here to see if the preset is we move on to the next one */
1801 while ( tempObject = [enumerator nextObject] )
1803 [tempArray addObject:tempObject];
1806 [QueueFileArray removeObjectsInArray:tempArray];
1807 [self saveQueueFileItem];
1810 /* This method will duplicate prepareJob however into the
1811 * queue .plist instead of into the job structure so it can
1812 * be recalled later */
1813 - (NSDictionary *)createQueueFileItem
1815 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
1817 hb_list_t * list = hb_get_titles( fHandle );
1818 hb_title_t * title = (hb_title_t *) hb_list_item( list,
1819 [fSrcTitlePopUp indexOfSelectedItem] );
1820 hb_job_t * job = title->job;
1824 /* We use a number system to set the encode status of the queue item
1825 * 0 == already encoded
1826 * 1 == is being encoded
1827 * 2 == is yet to be encoded
1830 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
1831 /* Source and Destination Information */
1833 [queueFileJob setObject:[NSString stringWithUTF8String: title->dvd] forKey:@"SourcePath"];
1834 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
1835 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
1836 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
1838 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
1840 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
1842 /* Lets get the preset info if there is any */
1843 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
1844 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
1846 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
1847 /* Chapter Markers fCreateChapterMarkers*/
1848 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
1850 /* We need to get the list of chapter names to put into an array and store
1851 * in our queue, so they can be reapplied in prepareJob when this queue
1852 * item comes up if Chapter Markers is set to on.
1855 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
1856 int chaptercount = hb_list_count( fTitle->list_chapter );
1857 for( i = 0; i < chaptercount; i++ )
1859 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
1860 if( chapter != NULL )
1862 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
1865 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
1866 [ChapterNamesArray autorelease];
1868 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
1869 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
1870 /* Mux mp4 with http optimization */
1871 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
1872 /* Add iPod uuid atom */
1873 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
1877 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
1878 /* x264 Option String */
1879 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
1881 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
1882 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
1883 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
1884 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
1886 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
1889 [queueFileJob setObject:[NSNumber numberWithInt:[fVidGrayscaleCheck state]] forKey:@"VideoGrayScale"];
1890 /* 2 Pass Encoding */
1891 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
1892 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
1893 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
1895 /* Picture Sizing */
1896 /* Use Max Picture settings for whatever the dvd is.*/
1897 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1898 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1899 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1900 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1901 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
1902 NSString * pictureSummary;
1903 pictureSummary = [NSString stringWithFormat:@"Source: %@ Output: %@ Anamorphic: %@",
1904 [fPicSettingsSrc stringValue],
1905 [fPicSettingsOutp stringValue],
1906 [fPicSettingsAnamorphic stringValue]];
1907 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
1908 /* Set crop settings here */
1909 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
1910 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
1911 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
1912 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
1913 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
1915 /* Picture Filters */
1916 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
1917 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
1918 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
1919 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
1920 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
1923 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
1925 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
1926 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
1927 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
1928 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
1929 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
1930 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
1931 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
1933 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
1935 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
1936 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
1937 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
1938 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
1939 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
1940 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
1941 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
1943 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
1945 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
1946 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
1947 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
1948 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
1949 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
1950 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
1951 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
1953 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
1955 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
1956 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
1957 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
1958 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
1959 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
1960 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
1961 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
1965 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
1966 [queueFileJob setObject:[NSNumber numberWithInt:[fSubPopUp indexOfSelectedItem]] forKey:@"JobSubtitlesIndex"];
1967 /* Forced Subtitles */
1968 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
1972 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
1974 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
1976 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
1979 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
1983 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
1986 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
1987 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
1988 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
1990 /* Picture Sizing */
1991 /* Use Max Picture settings for whatever the dvd is.*/
1992 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
1993 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
1994 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
1995 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
1996 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
1998 /* Set crop settings here */
1999 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2000 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2001 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2002 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2003 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2005 /* Picture Filters */
2006 [queueFileJob setObject:[fPicSettingDecomb stringValue] forKey:@"JobPictureDecomb"];
2009 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2011 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2012 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2013 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2014 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2015 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2017 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2019 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2020 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2021 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2022 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2023 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2025 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2027 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2028 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2029 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2030 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2031 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2033 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2035 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2036 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2037 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2038 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2039 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2042 [queueFileJob setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
2043 /* Forced Subtitles */
2044 [queueFileJob setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
2046 /* we need to auto relase the queueFileJob and return it */
2047 [queueFileJob autorelease];
2048 return queueFileJob;
2052 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2053 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
2055 unsigned index = [indexSet lastIndex];
2056 unsigned aboveInsertIndexCount = 0;
2058 while (index != NSNotFound)
2060 unsigned removeIndex;
2062 if (index >= insertIndex)
2064 removeIndex = index + aboveInsertIndexCount;
2065 aboveInsertIndexCount++;
2069 removeIndex = index;
2073 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2074 [QueueFileArray removeObjectAtIndex:removeIndex];
2075 [QueueFileArray insertObject:object atIndex:insertIndex];
2078 index = [indexSet indexLessThanIndex:index];
2080 /* We save all of the Queue data here
2081 * and it also gets sent back to the queue controller*/
2082 [self saveQueueFileItem];
2088 #pragma mark Queue Job Processing
2090 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2092 int i = currentQueueEncodeIndex;
2093 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2095 /* We save all of the Queue data here */
2096 [self saveQueueFileItem];
2097 /* We Reload the New Table data for presets */
2098 //[fPresetsOutlineView reloadData];
2100 /* Since we have now marked a queue item as done
2101 * we can go ahead and increment currentQueueEncodeIndex
2102 * so that if there is anything left in the queue we can
2103 * go ahead and move to the next item if we want to */
2104 currentQueueEncodeIndex++ ;
2105 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2106 int queueItems = [QueueFileArray count];
2107 /* If we still have more items in our queue, lets go to the next one */
2108 if (currentQueueEncodeIndex < queueItems)
2110 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2111 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2115 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2119 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2120 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2122 /* Tell HB to output a new activity log file for this encode */
2123 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2126 /* use a bool to determine whether or not we can decrypt using vlc */
2127 BOOL cancelScanDecrypt = 0;
2128 /* set the bool so that showNewScan knows to apply the appropriate queue
2129 * settings as this is a queue rescan
2131 applyQueueToScan = YES;
2132 NSString *path = scanPath;
2133 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2135 /*On Screen Notification*/
2137 //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2138 //[NSApp requestUserAttention:NSCriticalRequest];
2140 if( [detector isVideoDVD] )
2142 // The chosen path was actually on a DVD, so use the raw block
2143 // device path instead.
2144 path = [detector devicePath];
2145 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2147 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2148 NSString *vlcPath = @"/Applications/VLC.app";
2149 NSFileManager * fileManager = [NSFileManager defaultManager];
2150 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2152 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2153 cancelScanDecrypt = 1;
2154 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2156 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");
2157 [NSApp requestUserAttention:NSCriticalRequest];
2159 if (status == NSAlertDefaultReturn)
2161 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2162 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2164 else if (status == NSAlertAlternateReturn)
2166 /* User chose to cancel the scan */
2167 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2171 /* 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 */
2172 cancelScanDecrypt = 0;
2173 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2179 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2180 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2184 if (cancelScanDecrypt == 0)
2186 /* we actually pass the scan off to libhb here */
2187 /* If there is no title number passed to scan, we use "0"
2188 * which causes the default behavior of a full source scan
2194 if (scanTitleNum > 0)
2196 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2199 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2200 /* We use our advance pref to determine how many previews to scan */
2201 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2202 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2206 /* This method was originally used to load up a new queue item in the gui and
2207 * then start processing it. However we now have modified -prepareJob and use a second
2208 * instance of libhb to do our actual encoding, therefor right now it is not required.
2209 * Nonetheless I want to leave this in here
2210 * because basically its everything we need to be able to actually modify a pending queue
2211 * item in the gui and resave it. At least for now - dynaflash
2214 - (IBAction)applyQueueSettings:(id)sender
2216 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2217 hb_job_t * job = fTitle->job;
2219 /* Set title number and chapters */
2220 /* since the queue only scans a single title, we really don't need to pick a title */
2221 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2223 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2224 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2227 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2228 [self formatPopUpChanged:nil];
2230 /* Chapter Markers*/
2231 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2232 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2233 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2234 /* Mux mp4 with http optimization */
2235 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2238 /* We set the advanced opt string here if applicable*/
2239 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2240 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2242 /* Lets run through the following functions to get variables set there */
2243 [self videoEncoderPopUpChanged:nil];
2244 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2245 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2246 [self calculateBitrate:nil];
2249 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2251 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2252 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2253 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2255 [self videoMatrixChanged:nil];
2257 /* Video framerate */
2258 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2259 detected framerate in the fVidRatePopUp so we use index 0*/
2260 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2262 [fVidRatePopUp selectItemAtIndex: 0];
2266 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2270 [fVidGrayscaleCheck setState:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2272 /* 2 Pass Encoding */
2273 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2274 [self twoPassCheckboxChanged:nil];
2275 /* Turbo 1st pass for 2 Pass Encoding */
2276 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2279 if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2281 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2283 [fAudLang1PopUp selectItemAtIndex: 1];
2285 [self audioTrackPopUpChanged: fAudLang1PopUp];
2286 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2287 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2288 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2289 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2291 if ([fAudTrack1MixPopUp selectedItem] == nil)
2293 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2295 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2296 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2297 if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2299 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2301 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2302 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2304 if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2306 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2308 [fAudLang2PopUp selectItemAtIndex: 1];
2310 [self audioTrackPopUpChanged: fAudLang2PopUp];
2311 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2312 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2313 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2314 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2316 if ([fAudTrack2MixPopUp selectedItem] == nil)
2318 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2320 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2321 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2322 if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2324 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2326 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2327 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2329 if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2331 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2333 [fAudLang3PopUp selectItemAtIndex: 1];
2335 [self audioTrackPopUpChanged: fAudLang3PopUp];
2336 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2337 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2338 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2339 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2341 if ([fAudTrack3MixPopUp selectedItem] == nil)
2343 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2345 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2346 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2347 if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2349 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2351 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2352 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2354 if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2356 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2358 [fAudLang4PopUp selectItemAtIndex: 1];
2360 [self audioTrackPopUpChanged: fAudLang4PopUp];
2361 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2362 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2363 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2364 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2366 if ([fAudTrack4MixPopUp selectedItem] == nil)
2368 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2370 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2371 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2372 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2374 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2376 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2377 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2382 [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2383 /* Forced Subtitles */
2384 [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2386 /* Picture Settings */
2387 /* we check to make sure the presets width/height does not exceed the sources width/height */
2388 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2390 /* if so, then we use the sources height and width to avoid scaling up */
2391 job->width = fTitle->width;
2392 job->height = fTitle->height;
2394 else // source width/height is >= the preset height/width
2396 /* we can go ahead and use the presets values for height and width */
2397 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2398 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2400 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2401 if (job->keep_ratio == 1)
2403 hb_fix_aspect( job, HB_KEEP_WIDTH );
2404 if( job->height > fTitle->height )
2406 job->height = fTitle->height;
2407 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2410 job->pixel_ratio = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2413 /* If Cropping is set to custom, then recall all four crop values from
2414 when the preset was created and apply them */
2415 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2417 [fPictureController setAutoCrop:NO];
2419 /* Here we use the custom crop values saved at the time the preset was saved */
2420 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2421 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2422 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2423 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2426 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2428 [fPictureController setAutoCrop:YES];
2429 /* Here we use the auto crop values determined right after scan */
2430 job->crop[0] = AutoCropTop;
2431 job->crop[1] = AutoCropBottom;
2432 job->crop[2] = AutoCropLeft;
2433 job->crop[3] = AutoCropRight;
2439 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2442 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2444 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2446 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2448 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2450 [self calculatePictureSizing:nil];
2453 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2454 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2455 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2456 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2458 /* Deselect the currently selected Preset if there is one*/
2459 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2460 //[self selectPreset:nil];
2462 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2463 /* Change UI to show "Custom" settings are being used */
2464 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2466 curUserPresetChosenNum = nil;
2470 /* Deselect the currently selected Preset if there is one*/
2471 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2472 /* Change UI to show "Custom" settings are being used */
2473 [fPresetSelectedDisplay setStringValue: @"Custom"];
2475 //curUserPresetChosenNum = nil;
2478 /* We need to set this bool back to NO, in case the user wants to do a scan */
2479 //applyQueueToScan = NO;
2481 /* so now we go ahead and process the new settings */
2482 [self processNewQueueEncode];
2487 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2488 - (void) processNewQueueEncode
2490 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2491 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2492 hb_job_t * job = title->job;
2494 if( !hb_list_count( list ) )
2496 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2500 [self writeToActivityLog: "processNewQueueEncode title list is: %d", hb_list_count( list )];
2503 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2504 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2505 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2506 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2507 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2509 if( [[queueToApply objectForKey:@"SubtitlesForced"] intValue] == 1 )
2510 job->subtitle_force = 1;
2512 job->subtitle_force = 0;
2515 * subtitle of -1 is a scan
2517 if( job->subtitle == -1 )
2522 * When subtitle scan is enabled do a fast pre-scan job
2523 * which will determine which subtitles to enable, if any.
2526 x264opts_tmp = job->x264opts;
2529 job->x264opts = NULL;
2531 job->indepth_scan = 1;
2533 job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
2534 *(job->select_subtitle) = NULL;
2537 * Add the pre-scan job
2539 hb_add( fQueueEncodeLibhb, job );
2540 job->x264opts = x264opts_tmp;
2543 job->select_subtitle = NULL;
2545 /* No subtitle were selected, so reset the subtitle to -1 (which before
2546 * this point meant we were scanning
2548 if( job->subtitle == -2 )
2551 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2553 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
2554 job->indepth_scan = 0;
2557 * Do not autoselect subtitles on the first pass of a two pass
2559 job->select_subtitle = NULL;
2563 hb_add( fQueueEncodeLibhb, job );
2567 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2568 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2570 job->select_subtitle = subtitle_tmp;
2572 hb_add( fQueueEncodeLibhb, job );
2577 job->indepth_scan = 0;
2580 hb_add( fQueueEncodeLibhb, job );
2583 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2584 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2585 /* Lets mark our new encode as 1 or "Encoding" */
2586 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2587 [self saveQueueFileItem];
2588 /* We should be all setup so let 'er rip */
2593 #pragma mark Live Preview
2594 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2595 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2598 - (void) prepareJobForPreview
2600 hb_list_t * list = hb_get_titles( fHandle );
2601 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2602 [fSrcTitlePopUp indexOfSelectedItem] );
2603 hb_job_t * job = title->job;
2604 hb_audio_config_t * audio;
2606 /* Chapter selection */
2607 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
2608 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
2610 /* Format (Muxer) and Video Encoder */
2611 job->mux = [[fDstFormatPopUp selectedItem] tag];
2612 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
2615 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
2616 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
2618 /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
2619 mpeg4 and the checkbox being checked
2620 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
2621 if( [fDstMp4LargeFileCheck state] == NSOnState )
2623 job->largeFileSize = 1;
2627 job->largeFileSize = 0;
2629 /* We set http optimized mp4 here */
2630 if( [fDstMp4HttpOptFileCheck state] == NSOnState && [fDstMp4HttpOptFileCheck isEnabled] )
2632 job->mp4_optimize = 1;
2636 job->mp4_optimize = 0;
2639 if( [fDstFormatPopUp indexOfSelectedItem] == 0 || [fDstFormatPopUp indexOfSelectedItem] == 1 )
2641 /* We set the chapter marker extraction here based on the format being
2642 mpeg4 or mkv and the checkbox being checked */
2643 if ([fCreateChapterMarkers state] == NSOnState)
2645 job->chapter_markers = 1;
2649 job->chapter_markers = 0;
2653 if( job->vcodec & HB_VCODEC_X264 )
2655 if ([fDstMp4iPodFileCheck state] == NSOnState)
2664 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2665 Currently only used with Constant Quality setting*/
2666 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
2671 /* Below Sends x264 options to the core library if x264 is selected*/
2672 /* Lets use this as per Nyx, Thanks Nyx!*/
2673 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2674 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
2675 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
2680 /* Video settings */
2681 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
2682 * and detelecine is on, so we handle that in the logic below
2685 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
2687 /* a specific framerate has been chosen */
2688 job->vrate = 27000000;
2689 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
2690 /* We are not same as source so we set job->cfr to 1
2691 * to enable constant frame rate since user has specified
2692 * a specific framerate*/
2697 /* We are same as source (variable) */
2698 job->vrate = title->rate;
2699 job->vrate_base = title->rate_base;
2700 /* We are same as source so we set job->cfr to 0
2701 * to enable true same as source framerate */
2703 /* If we are same as source and we have detelecine on, we need to turn on
2706 if ([fPictureController detelecine] == 1)
2712 switch( [fVidQualityMatrix selectedRow] )
2716 Bitrate should already have been calculated and displayed
2717 in fVidBitrateField, so let's just use it */
2719 job->vquality = -1.0;
2720 job->vbitrate = [fVidBitrateField intValue];
2723 job->vquality = [fVidQualitySlider floatValue];
2728 job->grayscale = ( [fVidGrayscaleCheck state] == NSOnState );
2730 /* Subtitle settings */
2731 job->subtitle = [fSubPopUp indexOfSelectedItem] - 2;
2733 /* Audio tracks and mixdowns */
2734 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
2735 int audiotrack_count = hb_list_count(job->list_audio);
2736 for( int i = 0; i < audiotrack_count;i++)
2738 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
2739 hb_list_rem(job->list_audio, temp_audio);
2741 /* Now lets add our new tracks to the audio list here */
2742 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2744 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2745 hb_audio_config_init(audio);
2746 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2747 /* We go ahead and assign values to our audio->out.<properties> */
2748 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
2749 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
2750 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
2751 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
2752 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
2753 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
2755 hb_audio_add( job, audio );
2758 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2760 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2761 hb_audio_config_init(audio);
2762 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2763 /* We go ahead and assign values to our audio->out.<properties> */
2764 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
2765 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
2766 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
2767 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
2768 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
2769 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
2771 hb_audio_add( job, audio );
2776 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2778 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2779 hb_audio_config_init(audio);
2780 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2781 /* We go ahead and assign values to our audio->out.<properties> */
2782 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
2783 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
2784 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
2785 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
2786 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
2787 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
2789 hb_audio_add( job, audio );
2794 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2796 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
2797 hb_audio_config_init(audio);
2798 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2799 /* We go ahead and assign values to our audio->out.<properties> */
2800 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
2801 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
2802 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
2803 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
2804 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
2805 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
2807 hb_audio_add( job, audio );
2815 job->filters = hb_list_init();
2817 /* Now lets call the filters if applicable.
2818 * The order of the filters is critical
2822 if ([fPictureController detelecine])
2824 hb_list_add( job->filters, &hb_filter_detelecine );
2828 if ([fPictureController decomb] > 0)
2830 /* Run old deinterlacer fd by default */
2832 hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
2833 //hb_filter_decomb.settings = "4:10:15:9:10:35:9"; // <-- jbrjakes recommended parameters as of 5/23/08
2834 hb_list_add( job->filters, &hb_filter_decomb );
2839 if ([fPictureController deinterlace] == 1)
2841 /* Run old deinterlacer fd by default */
2842 hb_filter_deinterlace.settings = "-1";
2843 hb_list_add( job->filters, &hb_filter_deinterlace );
2845 else if ([fPictureController deinterlace] == 2)
2847 /* Yadif mode 0 (without spatial deinterlacing.) */
2848 hb_filter_deinterlace.settings = "2";
2849 hb_list_add( job->filters, &hb_filter_deinterlace );
2851 else if ([fPictureController deinterlace] == 3)
2853 /* Yadif (with spatial deinterlacing) */
2854 hb_filter_deinterlace.settings = "0";
2855 hb_list_add( job->filters, &hb_filter_deinterlace );
2859 if ([fPictureController denoise] == 1) // Weak in popup
2861 hb_filter_denoise.settings = "2:1:2:3";
2862 hb_list_add( job->filters, &hb_filter_denoise );
2864 else if ([fPictureController denoise] == 2) // Medium in popup
2866 hb_filter_denoise.settings = "3:2:2:3";
2867 hb_list_add( job->filters, &hb_filter_denoise );
2869 else if ([fPictureController denoise] == 3) // Strong in popup
2871 hb_filter_denoise.settings = "7:7:5:5";
2872 hb_list_add( job->filters, &hb_filter_denoise );
2875 /* Deblock (uses pp7 default) */
2876 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
2877 * the macgui's purposes a value of 0 actually means to not even use the filter
2878 * current hb_filter_deblock.settings valid ranges are from 5 - 15
2880 if ([fPictureController deblock] != 0)
2882 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
2883 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
2884 hb_list_add( job->filters, &hb_filter_deblock );
2891 #pragma mark Job Handling
2897 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2898 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2899 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2900 hb_job_t * job = title->job;
2901 hb_audio_config_t * audio;
2902 /* Chapter selection */
2903 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
2904 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
2906 /* Format (Muxer) and Video Encoder */
2907 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
2908 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
2911 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
2912 //if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
2914 /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
2915 mpeg4 and the checkbox being checked
2916 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
2917 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
2919 job->largeFileSize = 1;
2923 job->largeFileSize = 0;
2925 /* We set http optimized mp4 here */
2926 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
2928 job->mp4_optimize = 1;
2932 job->mp4_optimize = 0;
2937 /* We set the chapter marker extraction here based on the format being
2938 mpeg4 or mkv and the checkbox being checked */
2939 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
2941 job->chapter_markers = 1;
2943 /* now lets get our saved chapter names out the array in the queue file
2944 * and insert them back into the title chapter list. We have it here,
2945 * because unless we are inserting chapter markers there is no need to
2946 * spend the overhead of iterating through the chapter names array imo
2947 * Also, note that if for some reason we don't apply chapter names, the
2948 * chapters just come out 001, 002, etc. etc.
2951 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
2953 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
2955 while (tempObject = [enumerator nextObject])
2957 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
2958 if( chapter != NULL )
2960 strncpy( chapter->title, [tempObject UTF8String], 1023);
2961 chapter->title[1023] = '\0';
2968 job->chapter_markers = 0;
2971 if( job->vcodec & HB_VCODEC_X264 )
2973 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
2982 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
2983 Currently only used with Constant Quality setting*/
2984 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2)
2988 /* Below Sends x264 options to the core library if x264 is selected*/
2989 /* Lets use this as per Nyx, Thanks Nyx!*/
2990 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2991 /* Turbo first pass if two pass and Turbo First pass is selected */
2992 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
2994 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
2995 NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
2996 /* append the "Turbo" string variable to the existing opts string.
2997 Note: the "Turbo" string must be appended, not prepended to work properly*/
2998 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
2999 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3003 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3009 /* Picture Size Settings */
3010 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3011 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3013 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3014 job->pixel_ratio = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3017 /* Here we use the crop values saved at the time the preset was saved */
3018 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3019 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3020 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3021 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3023 /* Video settings */
3026 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3027 * and detelecine is on, so we handle that in the logic below
3030 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3032 /* a specific framerate has been chosen */
3033 job->vrate = 27000000;
3034 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3035 /* We are not same as source so we set job->cfr to 1
3036 * to enable constant frame rate since user has specified
3037 * a specific framerate*/
3042 /* We are same as source (variable) */
3043 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3044 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3045 /* We are same as source so we set job->cfr to 0
3046 * to enable true same as source framerate */
3048 /* If we are same as source and we have detelecine on, we need to turn on
3051 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3057 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3060 Bitrate should already have been calculated and displayed
3061 in fVidBitrateField, so let's just use it same as abr*/
3062 job->vquality = -1.0;
3063 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3065 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3067 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3072 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3073 /* Subtitle settings */
3074 job->subtitle = [[queueToApply objectForKey:@"JobSubtitlesIndex"] intValue] - 2;
3076 /* Audio tracks and mixdowns */
3077 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3078 int audiotrack_count = hb_list_count(job->list_audio);
3079 for( int i = 0; i < audiotrack_count;i++)
3081 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3082 hb_list_rem(job->list_audio, temp_audio);
3084 /* Now lets add our new tracks to the audio list here */
3085 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3087 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3088 hb_audio_config_init(audio);
3089 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3090 /* We go ahead and assign values to our audio->out.<properties> */
3091 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3092 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3093 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3094 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3095 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3096 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3098 hb_audio_add( job, audio );
3101 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3104 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3105 hb_audio_config_init(audio);
3106 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3107 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3108 /* We go ahead and assign values to our audio->out.<properties> */
3109 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3110 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3111 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3112 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3113 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3114 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3116 hb_audio_add( job, audio );
3120 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3122 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3123 hb_audio_config_init(audio);
3124 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3125 /* We go ahead and assign values to our audio->out.<properties> */
3126 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3127 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3128 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3129 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3130 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3131 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3133 hb_audio_add( job, audio );
3137 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3139 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3140 hb_audio_config_init(audio);
3141 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3142 /* We go ahead and assign values to our audio->out.<properties> */
3143 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3144 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3145 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3146 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3147 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3148 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3150 hb_audio_add( job, audio );
3155 job->filters = hb_list_init();
3157 /* Now lets call the filters if applicable.
3158 * The order of the filters is critical
3161 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3163 hb_list_add( job->filters, &hb_filter_detelecine );
3167 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3169 /* Run old deinterlacer fd by default */
3170 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"JobPictureDecomb"] UTF8String];
3171 hb_list_add( job->filters, &hb_filter_decomb );
3175 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3177 /* Run old deinterlacer fd by default */
3178 hb_filter_deinterlace.settings = "-1";
3179 hb_list_add( job->filters, &hb_filter_deinterlace );
3181 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3183 /* Yadif mode 0 (without spatial deinterlacing.) */
3184 hb_filter_deinterlace.settings = "2";
3185 hb_list_add( job->filters, &hb_filter_deinterlace );
3187 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3189 /* Yadif (with spatial deinterlacing) */
3190 hb_filter_deinterlace.settings = "0";
3191 hb_list_add( job->filters, &hb_filter_deinterlace );
3195 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Weak in popup
3197 hb_filter_denoise.settings = "2:1:2:3";
3198 hb_list_add( job->filters, &hb_filter_denoise );
3200 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Medium in popup
3202 hb_filter_denoise.settings = "3:2:2:3";
3203 hb_list_add( job->filters, &hb_filter_denoise );
3205 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Strong in popup
3207 hb_filter_denoise.settings = "7:7:5:5";
3208 hb_list_add( job->filters, &hb_filter_denoise );
3211 /* Deblock (uses pp7 default) */
3212 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3213 * the macgui's purposes a value of 0 actually means to not even use the filter
3214 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3216 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3218 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3219 hb_list_add( job->filters, &hb_filter_deblock );
3221 [self writeToActivityLog: "prepareJob exiting"];
3226 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3228 - (IBAction) addToQueue: (id) sender
3230 /* We get the destination directory from the destination field here */
3231 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3232 /* We check for a valid destination here */
3233 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3235 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3242 BOOL fileExistsInQueue;
3243 fileExistsInQueue = NO;
3245 /* We check for and existing file here */
3246 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3251 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3253 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3255 while (tempObject = [enumerator nextObject])
3257 NSDictionary *thisQueueDict = tempObject;
3258 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3260 fileExistsInQueue = YES;
3266 if(fileExists == YES)
3268 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
3269 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3270 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3271 NULL, NULL, [NSString stringWithFormat:
3272 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3273 [fDstFile2Field stringValue]] );
3275 else if (fileExistsInQueue == YES)
3277 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
3278 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3279 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3280 NULL, NULL, [NSString stringWithFormat:
3281 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3282 [fDstFile2Field stringValue]] );
3286 [self doAddToQueue];
3290 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
3291 the user if they want to overwrite an exiting movie file.
3293 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
3294 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3296 if( returnCode == NSAlertAlternateReturn )
3297 [self doAddToQueue];
3300 - (void) doAddToQueue
3302 [self addQueueFileItem ];
3307 /* Rip: puts up an alert before ultimately calling doRip
3309 - (IBAction) Rip: (id) sender
3311 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
3312 /* Rip or Cancel ? */
3314 hb_get_state2( fQueueEncodeLibhb, &s );
3316 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
3318 [self Cancel: sender];
3322 /* We check to see if we need to warn the user that the computer will go to sleep
3323 or shut down when encoding is finished */
3324 [self remindUserOfSleepOrShutdown];
3326 // If there are pending jobs in the queue, then this is a rip the queue
3327 if (fPendingCount > 0)
3329 /* here lets start the queue with the first pending item */
3330 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3335 // Before adding jobs to the queue, check for a valid destination.
3337 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3338 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3340 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3344 /* We check for duplicate name here */
3345 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
3347 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
3348 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3349 @selector( overWriteAlertDone:returnCode:contextInfo: ),
3350 NULL, NULL, [NSString stringWithFormat:
3351 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3352 [fDstFile2Field stringValue]] );
3354 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
3358 /* if there are no pending jobs in the queue, then add this one to the queue and rip
3359 otherwise, just rip the queue */
3360 if(fPendingCount == 0)
3362 [self writeToActivityLog: "Rip: No pending jobs, so sending this one to doAddToQueue"];
3363 [self doAddToQueue];
3366 /* go right to processing the new queue encode */
3367 [self writeToActivityLog: "Rip: Going right to performNewQueueScan"];
3368 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3373 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
3374 want to overwrite an exiting movie file.
3376 - (void) overWriteAlertDone: (NSWindow *) sheet
3377 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3379 if( returnCode == NSAlertAlternateReturn )
3381 /* if there are no jobs in the queue, then add this one to the queue and rip
3382 otherwise, just rip the queue */
3383 if( fPendingCount == 0 )
3385 [self doAddToQueue];
3388 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3389 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
3390 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3395 - (void) remindUserOfSleepOrShutdown
3397 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
3399 /*Warn that computer will sleep after encoding*/
3402 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);
3403 [NSApp requestUserAttention:NSCriticalRequest];
3404 if ( reminduser == NSAlertAlternateReturn )
3406 [self showPreferencesWindow:nil];
3409 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
3411 /*Warn that computer will shut down after encoding*/
3414 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);
3415 [NSApp requestUserAttention:NSCriticalRequest];
3416 if ( reminduser == NSAlertAlternateReturn )
3418 [self showPreferencesWindow:nil];
3427 /* Let libhb do the job */
3428 hb_start( fQueueEncodeLibhb );
3429 /*set the fEncodeState State */
3434 //------------------------------------------------------------------------------------
3435 // Displays an alert asking user if the want to cancel encoding of current job.
3436 // Cancel: returns immediately after posting the alert. Later, when the user
3437 // acknowledges the alert, doCancelCurrentJob is called.
3438 //------------------------------------------------------------------------------------
3439 - (IBAction)Cancel: (id)sender
3441 if (!fQueueController) return;
3443 hb_pause( fQueueEncodeLibhb );
3444 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
3446 // Which window to attach the sheet to?
3447 NSWindow * docWindow;
3448 if ([sender respondsToSelector: @selector(window)])
3449 docWindow = [sender window];
3451 docWindow = fWindow;
3453 NSBeginCriticalAlertSheet(
3455 NSLocalizedString(@"Continue Encoding", nil),
3456 NSLocalizedString(@"Cancel Current and Stop", nil),
3457 NSLocalizedString(@"Cancel Current and Continue", nil),
3459 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
3460 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
3462 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
3465 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
3467 hb_resume( fQueueEncodeLibhb );
3468 if (returnCode == NSAlertOtherReturn)
3470 [self doCancelCurrentJob]; // <- this also stops libhb
3472 if (returnCode == NSAlertAlternateReturn)
3474 [self doCancelCurrentJobAndStop];
3478 //------------------------------------------------------------------------------------
3479 // Cancels and deletes the current job and stops libhb from processing the remaining
3481 //------------------------------------------------------------------------------------
3482 - (void) doCancelCurrentJob
3484 // Stop the current job. hb_stop will only cancel the current pass and then set
3485 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
3486 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
3487 // remaining passes of the job and then start the queue back up if there are any
3491 hb_stop( fQueueEncodeLibhb );
3493 // Delete all remaining jobs since libhb doesn't do this on its own.
3495 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3496 hb_rem( fQueueEncodeLibhb, job );
3498 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3500 // now that we've stopped the currently encoding job, lets mark it as cancelled
3501 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3502 // and as always, save it in the queue .plist...
3503 /* We save all of the Queue data here */
3504 [self saveQueueFileItem];
3505 // so now lets move to
3506 currentQueueEncodeIndex++ ;
3507 // ... and see if there are more items left in our queue
3508 int queueItems = [QueueFileArray count];
3509 /* If we still have more items in our queue, lets go to the next one */
3510 if (currentQueueEncodeIndex < queueItems)
3512 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
3513 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
3515 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3519 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
3524 - (void) doCancelCurrentJobAndStop
3526 hb_stop( fQueueEncodeLibhb );
3528 // Delete all remaining jobs since libhb doesn't do this on its own.
3530 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
3531 hb_rem( fQueueEncodeLibhb, job );
3534 fEncodeState = 2; // don't alert at end of processing since this was a cancel
3536 // now that we've stopped the currently encoding job, lets mark it as cancelled
3537 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
3538 // and as always, save it in the queue .plist...
3539 /* We save all of the Queue data here */
3540 [self saveQueueFileItem];
3541 // so now lets move to
3542 currentQueueEncodeIndex++ ;
3543 [self writeToActivityLog: "cancelling current job and stopping the queue"];
3545 - (IBAction) Pause: (id) sender
3548 hb_get_state2( fQueueEncodeLibhb, &s );
3550 if( s.state == HB_STATE_PAUSED )
3552 hb_resume( fQueueEncodeLibhb );
3556 hb_pause( fQueueEncodeLibhb );
3561 #pragma mark GUI Controls Changed Methods
3563 - (IBAction) titlePopUpChanged: (id) sender
3565 hb_list_t * list = hb_get_titles( fHandle );
3566 hb_title_t * title = (hb_title_t*)
3567 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3569 /* If Auto Naming is on. We create an output filename of dvd name - title number */
3570 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
3572 [fDstFile2Field setStringValue: [NSString stringWithFormat:
3573 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
3574 [browsedSourceDisplayName stringByDeletingPathExtension],
3576 [[fDstFile2Field stringValue] pathExtension]]];
3579 /* Update chapter popups */
3580 [fSrcChapterStartPopUp removeAllItems];
3581 [fSrcChapterEndPopUp removeAllItems];
3582 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
3584 [fSrcChapterStartPopUp addItemWithTitle: [NSString
3585 stringWithFormat: @"%d", i + 1]];
3586 [fSrcChapterEndPopUp addItemWithTitle: [NSString
3587 stringWithFormat: @"%d", i + 1]];
3590 [fSrcChapterStartPopUp selectItemAtIndex: 0];
3591 [fSrcChapterEndPopUp selectItemAtIndex:
3592 hb_list_count( title->list_chapter ) - 1];
3593 [self chapterPopUpChanged:nil];
3595 /* Start Get and set the initial pic size for display */
3596 hb_job_t * job = title->job;
3599 /*Set Source Size Field Here */
3600 [fPicSettingsSrc setStringValue: [NSString stringWithFormat: @"%d x %d", fTitle->width, fTitle->height]];
3602 /* Set Auto Crop to on upon selecting a new title */
3603 [fPictureController setAutoCrop:YES];
3605 /* We get the originial output picture width and height and put them
3606 in variables for use with some presets later on */
3607 PicOrigOutputWidth = job->width;
3608 PicOrigOutputHeight = job->height;
3609 AutoCropTop = job->crop[0];
3610 AutoCropBottom = job->crop[1];
3611 AutoCropLeft = job->crop[2];
3612 AutoCropRight = job->crop[3];
3614 /* Reset the new title in fPictureController && fPreviewController*/
3615 [fPictureController SetTitle:title];
3616 //[fPreviewController SetTitle:title];
3617 /* Update subtitle popups */
3618 hb_subtitle_t * subtitle;
3619 [fSubPopUp removeAllItems];
3620 [fSubPopUp addItemWithTitle: @"None"];
3621 [fSubPopUp addItemWithTitle: @"Autoselect"];
3622 for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
3624 subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
3626 /* We cannot use NSPopUpButton's addItemWithTitle because
3627 it checks for duplicate entries */
3628 [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
3629 subtitle->lang] action: NULL keyEquivalent: @""];
3631 [fSubPopUp selectItemAtIndex: 0];
3633 [self subtitleSelectionChanged:nil];
3635 /* Update chapter table */
3636 [fChapterTitlesDelegate resetWithTitle:title];
3637 [fChapterTable reloadData];
3639 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3640 int audiotrack_count = hb_list_count(job->list_audio);
3641 for( int i = 0; i < audiotrack_count;i++)
3643 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3644 hb_list_rem(job->list_audio, temp_audio);
3647 /* Update audio popups */
3648 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
3649 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
3650 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
3651 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
3652 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
3653 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
3654 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
3655 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3656 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3657 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
3659 /* changing the title may have changed the audio channels on offer, */
3660 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3661 [self audioTrackPopUpChanged: fAudLang1PopUp];
3662 [self audioTrackPopUpChanged: fAudLang2PopUp];
3663 [self audioTrackPopUpChanged: fAudLang3PopUp];
3664 [self audioTrackPopUpChanged: fAudLang4PopUp];
3666 [fVidRatePopUp selectItemAtIndex: 0];
3668 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
3669 [self calculatePictureSizing:nil];
3671 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
3672 [self selectPreset:nil];
3675 - (IBAction) chapterPopUpChanged: (id) sender
3678 /* If start chapter popup is greater than end chapter popup,
3679 we set the end chapter popup to the same as start chapter popup */
3680 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
3682 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
3686 hb_list_t * list = hb_get_titles( fHandle );
3687 hb_title_t * title = (hb_title_t *)
3688 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
3690 hb_chapter_t * chapter;
3691 int64_t duration = 0;
3692 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
3693 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
3695 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3696 duration += chapter->duration;
3699 duration /= 90000; /* pts -> seconds */
3700 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
3701 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
3704 [self calculateBitrate: sender];
3707 - (IBAction) formatPopUpChanged: (id) sender
3709 NSString * string = [fDstFile2Field stringValue];
3710 int format = [fDstFormatPopUp indexOfSelectedItem];
3712 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
3713 [fDstMp4LargeFileCheck setHidden: YES];
3714 [fDstMp4HttpOptFileCheck setHidden: YES];
3715 [fDstMp4iPodFileCheck setHidden: YES];
3717 /* Update the Video Codec PopUp */
3718 /* lets get the tag of the currently selected item first so we might reset it later */
3719 int selectedVidEncoderTag;
3720 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
3722 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
3723 [fVidEncoderPopUp removeAllItems];
3724 NSMenuItem *menuItem;
3725 /* These video encoders are available to all of our current muxers, so lets list them once here */
3726 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
3727 [menuItem setTag: HB_VCODEC_FFMPEG];
3729 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (XviD)" action: NULL keyEquivalent: @""];
3730 [menuItem setTag: HB_VCODEC_XVID];
3734 /*Get Default MP4 File Extension*/
3735 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
3743 /* Add additional video encoders here */
3744 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3745 [menuItem setTag: HB_VCODEC_X264];
3746 /* We show the mp4 option checkboxes here since we are mp4 */
3747 [fCreateChapterMarkers setEnabled: YES];
3748 [fDstMp4LargeFileCheck setHidden: NO];
3749 [fDstMp4HttpOptFileCheck setHidden: NO];
3750 [fDstMp4iPodFileCheck setHidden: NO];
3755 /* Add additional video encoders here */
3756 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3757 [menuItem setTag: HB_VCODEC_X264];
3758 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3759 [menuItem setTag: HB_VCODEC_THEORA];
3760 /* We enable the create chapters checkbox here */
3761 [fCreateChapterMarkers setEnabled: YES];
3766 /* Add additional video encoders here */
3767 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
3768 [menuItem setTag: HB_VCODEC_X264];
3769 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3770 [fCreateChapterMarkers setEnabled: NO];
3771 [fCreateChapterMarkers setState: NSOffState];
3776 /* Add additional video encoders here */
3777 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
3778 [menuItem setTag: HB_VCODEC_THEORA];
3779 /* We disable the create chapters checkbox here and make sure it is unchecked*/
3780 [fCreateChapterMarkers setEnabled: NO];
3781 [fCreateChapterMarkers setState: NSOffState];
3784 /* if we have a previously selected vid encoder tag, then try to select it */
3785 if (selectedVidEncoderTag)
3787 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
3791 [fVidEncoderPopUp selectItemAtIndex: 0];
3794 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
3795 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
3796 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
3797 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
3800 [self autoSetM4vExtension: sender];
3802 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
3804 if( SuccessfulScan )
3806 /* Add/replace to the correct extension */
3807 [self audioTrackPopUpChanged: fAudLang1PopUp];
3808 [self audioTrackPopUpChanged: fAudLang2PopUp];
3809 [self audioTrackPopUpChanged: fAudLang3PopUp];
3810 [self audioTrackPopUpChanged: fAudLang4PopUp];
3812 if( [fVidEncoderPopUp selectedItem] == nil )
3815 [fVidEncoderPopUp selectItemAtIndex:0];
3816 [self videoEncoderPopUpChanged:nil];
3818 /* changing the format may mean that we can / can't offer mono or 6ch, */
3819 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
3821 /* We call the method to properly enable/disable turbo 2 pass */
3822 [self twoPassCheckboxChanged: sender];
3823 /* We call method method to change UI to reflect whether a preset is used or not*/
3826 [self customSettingUsed: sender];
3829 - (IBAction) autoSetM4vExtension: (id) sender
3831 if ( [fDstFormatPopUp indexOfSelectedItem] )
3834 NSString * extension = @"mp4";
3836 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3837 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3838 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
3839 [fCreateChapterMarkers state] == NSOnState ||
3840 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
3845 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
3848 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
3849 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
3852 /* Method to determine if we should change the UI
3853 To reflect whether or not a Preset is being used or if
3854 the user is using "Custom" settings by determining the sender*/
3855 - (IBAction) customSettingUsed: (id) sender
3857 if ([sender stringValue])
3859 /* Deselect the currently selected Preset if there is one*/
3860 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3861 /* Change UI to show "Custom" settings are being used */
3862 [fPresetSelectedDisplay setStringValue: @"Custom"];
3864 curUserPresetChosenNum = nil;
3866 [self calculateBitrate:nil];
3871 #pragma mark - Video
3873 - (IBAction) videoEncoderPopUpChanged: (id) sender
3875 hb_job_t * job = fTitle->job;
3876 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
3878 [fAdvancedOptions setHidden:YES];
3879 /* If we are using x264 then show the x264 advanced panel*/
3880 if (videoEncoder == HB_VCODEC_X264)
3882 [fAdvancedOptions setHidden:NO];
3883 [self autoSetM4vExtension: sender];
3886 /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
3887 is being used as it borks up loose anamorphic .
3888 For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
3889 to use the index itself but this is easier */
3890 if (videoEncoder == HB_VCODEC_FFMPEG)
3892 if (job->pixel_ratio == 2)
3894 job->pixel_ratio = 0;
3896 [fPictureController setAllowLooseAnamorphic:NO];
3897 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
3898 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
3899 anything other than MP4.
3901 [fDstMp4iPodFileCheck setEnabled: NO];
3902 [fDstMp4iPodFileCheck setState: NSOffState];
3906 [fPictureController setAllowLooseAnamorphic:YES];
3907 [fDstMp4iPodFileCheck setEnabled: YES];
3910 [self calculatePictureSizing: sender];
3911 [self twoPassCheckboxChanged: sender];
3915 - (IBAction) twoPassCheckboxChanged: (id) sender
3917 /* check to see if x264 is chosen */
3918 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
3920 if( [fVidTwoPassCheck state] == NSOnState)
3922 [fVidTurboPassCheck setHidden: NO];
3926 [fVidTurboPassCheck setHidden: YES];
3927 [fVidTurboPassCheck setState: NSOffState];
3929 /* Make sure Two Pass is checked if Turbo is checked */
3930 if( [fVidTurboPassCheck state] == NSOnState)
3932 [fVidTwoPassCheck setState: NSOnState];
3937 [fVidTurboPassCheck setHidden: YES];
3938 [fVidTurboPassCheck setState: NSOffState];
3941 /* We call method method to change UI to reflect whether a preset is used or not*/
3942 [self customSettingUsed: sender];
3945 - (IBAction ) videoFrameRateChanged: (id) sender
3947 /* We call method method to calculatePictureSizing to error check detelecine*/
3948 [self calculatePictureSizing: sender];
3950 /* We call method method to change UI to reflect whether a preset is used or not*/
3951 [self customSettingUsed: sender];
3953 - (IBAction) videoMatrixChanged: (id) sender;
3955 bool target, bitrate, quality;
3957 target = bitrate = quality = false;
3958 if( [fVidQualityMatrix isEnabled] )
3960 switch( [fVidQualityMatrix selectedRow] )
3973 [fVidTargetSizeField setEnabled: target];
3974 [fVidBitrateField setEnabled: bitrate];
3975 [fVidQualitySlider setEnabled: quality];
3976 [fVidTwoPassCheck setEnabled: !quality &&
3977 [fVidQualityMatrix isEnabled]];
3980 [fVidTwoPassCheck setState: NSOffState];
3981 [fVidTurboPassCheck setHidden: YES];
3982 [fVidTurboPassCheck setState: NSOffState];
3985 [self qualitySliderChanged: sender];
3986 [self calculateBitrate: sender];
3987 [self customSettingUsed: sender];
3990 - (IBAction) qualitySliderChanged: (id) sender
3992 [fVidConstantCell setTitle: [NSString stringWithFormat:
3993 NSLocalizedString( @"Constant quality: %.0f %%", @"" ), 100.0 *
3994 [fVidQualitySlider floatValue]]];
3995 [self customSettingUsed: sender];
3998 - (void) controlTextDidChange: (NSNotification *) notification
4000 [self calculateBitrate:nil];
4003 - (IBAction) calculateBitrate: (id) sender
4005 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4010 hb_list_t * list = hb_get_titles( fHandle );
4011 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4012 [fSrcTitlePopUp indexOfSelectedItem] );
4013 hb_job_t * job = title->job;
4014 hb_audio_config_t * audio;
4015 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4016 * Target Size Field, we also need the job info for the Muxer, the Chapters
4017 * as well as all of the audio track info.
4018 * This used to be accomplished by simply calling prepareJob here, however
4019 * since the resilient queue sets the queue array values instead of the job
4020 * values directly, we duplicate the old prepareJob code here for the variables
4023 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4024 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4025 job->mux = [[fDstFormatPopUp selectedItem] tag];
4027 /* Audio goes here */
4028 int audiotrack_count = hb_list_count(job->list_audio);
4029 for( int i = 0; i < audiotrack_count;i++)
4031 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4032 hb_list_rem(job->list_audio, temp_audio);
4034 /* Now we need our audio info here for each track if applicable */
4035 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4037 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4038 hb_audio_config_init(audio);
4039 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4040 /* We go ahead and assign values to our audio->out.<properties> */
4041 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4042 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4043 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4044 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4045 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4046 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4048 hb_audio_add( job, audio );
4051 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4053 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4054 hb_audio_config_init(audio);
4055 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4056 /* We go ahead and assign values to our audio->out.<properties> */
4057 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4058 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4059 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4060 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4061 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4062 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4064 hb_audio_add( job, audio );
4069 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4071 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4072 hb_audio_config_init(audio);
4073 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4074 /* We go ahead and assign values to our audio->out.<properties> */
4075 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4076 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
4077 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
4078 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
4079 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
4080 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
4082 hb_audio_add( job, audio );
4087 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4089 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4090 hb_audio_config_init(audio);
4091 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4092 /* We go ahead and assign values to our audio->out.<properties> */
4093 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4094 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
4095 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
4096 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
4097 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
4098 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
4100 hb_audio_add( job, audio );
4105 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
4109 #pragma mark - Picture
4111 /* lets set the picture size back to the max from right after title scan
4112 Lets use an IBAction here as down the road we could always use a checkbox
4113 in the gui to easily take the user back to max. Remember, the compiler
4114 resolves IBActions down to -(void) during compile anyway */
4115 - (IBAction) revertPictureSizeToMax: (id) sender
4117 hb_job_t * job = fTitle->job;
4118 /* Here we apply the title source and height */
4119 job->width = fTitle->width;
4120 job->height = fTitle->height;
4122 [self calculatePictureSizing: sender];
4123 /* We call method to change UI to reflect whether a preset is used or not*/
4124 [self customSettingUsed: sender];
4128 * Registers changes made in the Picture Settings Window.
4131 - (void)pictureSettingsDidChange
4133 [self calculatePictureSizing:nil];
4136 /* Get and Display Current Pic Settings in main window */
4137 - (IBAction) calculatePictureSizing: (id) sender
4139 [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", fTitle->job->width, fTitle->job->height]];
4141 if (fTitle->job->pixel_ratio == 1)
4143 int titlewidth = fTitle->width-fTitle->job->crop[2]-fTitle->job->crop[3];
4144 int arpwidth = fTitle->job->pixel_aspect_width;
4145 int arpheight = fTitle->job->pixel_aspect_height;
4146 int displayparwidth = titlewidth * arpwidth / arpheight;
4147 int displayparheight = fTitle->height-fTitle->job->crop[0]-fTitle->job->crop[1];
4148 [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", titlewidth, displayparheight]];
4149 [fPicSettingsAnamorphic setStringValue: [NSString stringWithFormat:@"%d x %d Strict", displayparwidth, displayparheight]];
4150 fTitle->job->keep_ratio = 0;
4152 else if (fTitle->job->pixel_ratio == 2)
4154 hb_job_t * job = fTitle->job;
4155 int output_width, output_height, output_par_width, output_par_height;
4156 hb_set_anamorphic_size(job, &output_width, &output_height, &output_par_width, &output_par_height);
4158 display_width = output_width * output_par_width / output_par_height;
4160 [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", output_width, output_height]];
4161 [fPicSettingsAnamorphic setStringValue: [NSString stringWithFormat:@"%d x %d Loose", display_width, output_height]];
4163 fTitle->job->keep_ratio = 0;
4167 [fPicSettingsAnamorphic setStringValue:@"Off"];
4170 /* Set ON/Off values for the deinterlace/keep aspect ratio according to boolean */
4171 if (fTitle->job->keep_ratio > 0)
4173 [fPicSettingARkeep setStringValue: @"On"];
4177 [fPicSettingARkeep setStringValue: @"Off"];
4181 if ([fPictureController detelecine])
4183 [fPicSettingDetelecine setStringValue: @"Yes"];
4187 [fPicSettingDetelecine setStringValue: @"Off"];
4191 if ([fPictureController decomb])
4193 [fPicSettingDecomb setStringValue: @"1:2:6:9:80:16:16"];
4197 [fPicSettingDecomb setStringValue: @"Off"];
4201 /* VFR (Variable Frame Rate) */
4205 if ([fPictureController deinterlace] == 0)
4207 [fPicSettingDeinterlace setStringValue: @"Off"];
4209 else if ([fPictureController deinterlace] == 1)
4211 [fPicSettingDeinterlace setStringValue: @"Fast"];
4213 else if ([fPictureController deinterlace] == 2)
4215 [fPicSettingDeinterlace setStringValue: @"Slow"];
4217 else if ([fPictureController deinterlace] == 3)
4219 [fPicSettingDeinterlace setStringValue: @"Slower"];
4223 if ([fPictureController denoise] == 0)
4225 [fPicSettingDenoise setStringValue: @"Off"];
4227 else if ([fPictureController denoise] == 1)
4229 [fPicSettingDenoise setStringValue: @"Weak"];
4231 else if ([fPictureController denoise] == 2)
4233 [fPicSettingDenoise setStringValue: @"Medium"];
4235 else if ([fPictureController denoise] == 3)
4237 [fPicSettingDenoise setStringValue: @"Strong"];
4241 if ([fPictureController deblock] == 0)
4243 [fPicSettingDeblock setStringValue: @"Off"];
4247 [fPicSettingDeblock setStringValue: [NSString stringWithFormat:@"%d",[fPictureController deblock]]];
4250 if (fTitle->job->pixel_ratio > 0)
4252 [fPicSettingPAR setStringValue: @""];
4256 [fPicSettingPAR setStringValue: @"Off"];
4259 /* Set the display field for crop as per boolean */
4260 if (![fPictureController autoCrop])
4262 [fPicSettingAutoCrop setStringValue: @"Custom"];
4266 [fPicSettingAutoCrop setStringValue: @"Auto"];
4273 #pragma mark - Audio and Subtitles
4274 - (IBAction) audioCodecsPopUpChanged: (id) sender
4277 NSPopUpButton * audiotrackPopUp;
4278 NSPopUpButton * sampleratePopUp;
4279 NSPopUpButton * bitratePopUp;
4280 NSPopUpButton * audiocodecPopUp;
4281 if (sender == fAudTrack1CodecPopUp)
4283 audiotrackPopUp = fAudLang1PopUp;
4284 audiocodecPopUp = fAudTrack1CodecPopUp;
4285 sampleratePopUp = fAudTrack1RatePopUp;
4286 bitratePopUp = fAudTrack1BitratePopUp;
4288 else if (sender == fAudTrack2CodecPopUp)
4290 audiotrackPopUp = fAudLang2PopUp;
4291 audiocodecPopUp = fAudTrack2CodecPopUp;
4292 sampleratePopUp = fAudTrack2RatePopUp;
4293 bitratePopUp = fAudTrack2BitratePopUp;
4295 else if (sender == fAudTrack3CodecPopUp)
4297 audiotrackPopUp = fAudLang3PopUp;
4298 audiocodecPopUp = fAudTrack3CodecPopUp;
4299 sampleratePopUp = fAudTrack3RatePopUp;
4300 bitratePopUp = fAudTrack3BitratePopUp;
4304 audiotrackPopUp = fAudLang4PopUp;
4305 audiocodecPopUp = fAudTrack4CodecPopUp;
4306 sampleratePopUp = fAudTrack4RatePopUp;
4307 bitratePopUp = fAudTrack4BitratePopUp;
4310 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
4311 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4312 [self audioTrackPopUpChanged: audiotrackPopUp];
4316 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
4318 /* We will be setting the enabled/disabled state of each tracks audio controls based on
4319 * the settings of the source audio for that track. We leave the samplerate and bitrate
4320 * to audiotrackMixdownChanged
4323 /* We will first verify that a lower track number has been selected before enabling each track
4324 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
4326 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4328 [fAudLang2PopUp setEnabled: NO];
4329 [fAudLang2PopUp selectItemAtIndex: 0];
4333 [fAudLang2PopUp setEnabled: YES];
4336 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4338 [fAudLang3PopUp setEnabled: NO];
4339 [fAudLang3PopUp selectItemAtIndex: 0];
4343 [fAudLang3PopUp setEnabled: YES];
4345 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4347 [fAudLang4PopUp setEnabled: NO];
4348 [fAudLang4PopUp selectItemAtIndex: 0];
4352 [fAudLang4PopUp setEnabled: YES];
4354 /* enable/disable the mixdown text and popupbutton for audio track 1 */
4355 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4356 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4357 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4358 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4359 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4360 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
4361 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4363 [fAudTrack1CodecPopUp removeAllItems];
4364 [fAudTrack1MixPopUp removeAllItems];
4365 [fAudTrack1RatePopUp removeAllItems];
4366 [fAudTrack1BitratePopUp removeAllItems];
4367 [fAudTrack1DrcSlider setFloatValue: 1.00];
4368 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4370 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4372 [fAudTrack1RatePopUp setEnabled: NO];
4373 [fAudTrack1BitratePopUp setEnabled: NO];
4374 [fAudTrack1DrcSlider setEnabled: NO];
4375 [fAudTrack1DrcField setEnabled: NO];
4378 /* enable/disable the mixdown text and popupbutton for audio track 2 */
4379 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4380 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4381 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4382 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4383 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4384 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
4385 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4387 [fAudTrack2CodecPopUp removeAllItems];
4388 [fAudTrack2MixPopUp removeAllItems];
4389 [fAudTrack2RatePopUp removeAllItems];
4390 [fAudTrack2BitratePopUp removeAllItems];
4391 [fAudTrack2DrcSlider setFloatValue: 1.00];
4392 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
4394 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4396 [fAudTrack2RatePopUp setEnabled: NO];
4397 [fAudTrack2BitratePopUp setEnabled: NO];
4398 [fAudTrack2DrcSlider setEnabled: NO];
4399 [fAudTrack2DrcField setEnabled: NO];
4402 /* enable/disable the mixdown text and popupbutton for audio track 3 */
4403 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4404 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4405 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4406 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4407 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4408 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
4409 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4411 [fAudTrack3CodecPopUp removeAllItems];
4412 [fAudTrack3MixPopUp removeAllItems];
4413 [fAudTrack3RatePopUp removeAllItems];
4414 [fAudTrack3BitratePopUp removeAllItems];
4415 [fAudTrack3DrcSlider setFloatValue: 1.00];
4416 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
4418 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4420 [fAudTrack3RatePopUp setEnabled: NO];
4421 [fAudTrack3BitratePopUp setEnabled: NO];
4422 [fAudTrack3DrcSlider setEnabled: NO];
4423 [fAudTrack3DrcField setEnabled: NO];
4426 /* enable/disable the mixdown text and popupbutton for audio track 4 */
4427 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4428 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4429 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4430 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4431 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4432 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
4433 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
4435 [fAudTrack4CodecPopUp removeAllItems];
4436 [fAudTrack4MixPopUp removeAllItems];
4437 [fAudTrack4RatePopUp removeAllItems];
4438 [fAudTrack4BitratePopUp removeAllItems];
4439 [fAudTrack4DrcSlider setFloatValue: 1.00];
4440 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
4442 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
4444 [fAudTrack4RatePopUp setEnabled: NO];
4445 [fAudTrack4BitratePopUp setEnabled: NO];
4446 [fAudTrack4DrcSlider setEnabled: NO];
4447 [fAudTrack4DrcField setEnabled: NO];
4452 - (IBAction) addAllAudioTracksToPopUp: (id) sender
4455 hb_list_t * list = hb_get_titles( fHandle );
4456 hb_title_t * title = (hb_title_t*)
4457 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4459 hb_audio_config_t * audio;
4461 [sender removeAllItems];
4462 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
4463 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
4465 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
4466 [[sender menu] addItemWithTitle:
4467 [NSString stringWithCString: audio->lang.description]
4468 action: NULL keyEquivalent: @""];
4470 [sender selectItemAtIndex: 0];
4474 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
4477 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
4478 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
4479 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
4480 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
4482 if (searchPrefixString)
4485 for( int i = 0; i < [sender numberOfItems]; i++ )
4487 /* Try to find the desired search string */
4488 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
4490 [sender selectItemAtIndex: i];
4494 /* couldn't find the string, so select the requested "search string not found" item */
4495 /* index of 0 means select the "none" item */
4496 /* index of 1 means select the first audio track */
4497 [sender selectItemAtIndex: selectIndexIfNotFound];
4501 /* if no search string is provided, then select the selectIndexIfNotFound item */
4502 [sender selectItemAtIndex: selectIndexIfNotFound];
4506 - (IBAction) audioAddAudioTrackCodecs: (id)sender
4508 int format = [fDstFormatPopUp indexOfSelectedItem];
4510 /* setup pointers to the appropriate popups for the correct track */
4511 NSPopUpButton * audiocodecPopUp;
4512 NSPopUpButton * audiotrackPopUp;
4513 if (sender == fAudTrack1CodecPopUp)
4515 audiotrackPopUp = fAudLang1PopUp;
4516 audiocodecPopUp = fAudTrack1CodecPopUp;
4518 else if (sender == fAudTrack2CodecPopUp)
4520 audiotrackPopUp = fAudLang2PopUp;
4521 audiocodecPopUp = fAudTrack2CodecPopUp;
4523 else if (sender == fAudTrack3CodecPopUp)
4525 audiotrackPopUp = fAudLang3PopUp;
4526 audiocodecPopUp = fAudTrack3CodecPopUp;
4530 audiotrackPopUp = fAudLang4PopUp;
4531 audiocodecPopUp = fAudTrack4CodecPopUp;
4534 [audiocodecPopUp removeAllItems];
4535 /* Make sure "None" isnt selected in the source track */
4536 if ([audiotrackPopUp indexOfSelectedItem] > 0)
4538 [audiocodecPopUp setEnabled:YES];
4539 NSMenuItem *menuItem;
4540 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
4546 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4547 [menuItem setTag: HB_ACODEC_FAAC];
4550 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4551 [menuItem setTag: HB_ACODEC_AC3];
4557 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
4558 [menuItem setTag: HB_ACODEC_FAAC];
4560 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4561 [menuItem setTag: HB_ACODEC_AC3];
4563 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4564 [menuItem setTag: HB_ACODEC_LAME];
4566 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4567 [menuItem setTag: HB_ACODEC_VORBIS];
4573 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4574 [menuItem setTag: HB_ACODEC_LAME];
4576 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
4577 [menuItem setTag: HB_ACODEC_AC3];
4583 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
4584 [menuItem setTag: HB_ACODEC_VORBIS];
4586 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
4587 [menuItem setTag: HB_ACODEC_LAME];
4590 [audiocodecPopUp selectItemAtIndex:0];
4594 [audiocodecPopUp setEnabled:NO];
4598 - (IBAction) audioTrackPopUpChanged: (id) sender
4600 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
4601 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
4604 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
4607 /* make sure we have a selected title before continuing */
4608 if (fTitle == NULL) return;
4609 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
4610 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
4612 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
4614 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4616 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
4618 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4620 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
4622 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4624 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
4626 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4629 /* Now lets make the sender the appropriate Audio Track popup from this point on */
4630 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
4632 sender = fAudLang1PopUp;
4634 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
4636 sender = fAudLang2PopUp;
4638 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
4640 sender = fAudLang3PopUp;
4642 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
4644 sender = fAudLang4PopUp;
4647 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
4648 NSPopUpButton * mixdownPopUp;
4649 NSPopUpButton * audiocodecPopUp;
4650 NSPopUpButton * sampleratePopUp;
4651 NSPopUpButton * bitratePopUp;
4652 if (sender == fAudLang1PopUp)
4654 mixdownPopUp = fAudTrack1MixPopUp;
4655 audiocodecPopUp = fAudTrack1CodecPopUp;
4656 sampleratePopUp = fAudTrack1RatePopUp;
4657 bitratePopUp = fAudTrack1BitratePopUp;
4659 else if (sender == fAudLang2PopUp)
4661 mixdownPopUp = fAudTrack2MixPopUp;
4662 audiocodecPopUp = fAudTrack2CodecPopUp;
4663 sampleratePopUp = fAudTrack2RatePopUp;
4664 bitratePopUp = fAudTrack2BitratePopUp;
4666 else if (sender == fAudLang3PopUp)
4668 mixdownPopUp = fAudTrack3MixPopUp;
4669 audiocodecPopUp = fAudTrack3CodecPopUp;
4670 sampleratePopUp = fAudTrack3RatePopUp;
4671 bitratePopUp = fAudTrack3BitratePopUp;
4675 mixdownPopUp = fAudTrack4MixPopUp;
4676 audiocodecPopUp = fAudTrack4CodecPopUp;
4677 sampleratePopUp = fAudTrack4RatePopUp;
4678 bitratePopUp = fAudTrack4BitratePopUp;
4681 /* get the index of the selected audio Track*/
4682 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
4684 /* pointer for the hb_audio_s struct we will use later on */
4685 hb_audio_config_t * audio;
4688 /* check if the audio mixdown controls need their enabled state changing */
4689 [self setEnabledStateOfAudioMixdownControls:nil];
4691 if (thisAudioIndex != -1)
4695 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
4697 /* actually manipulate the proper mixdowns here */
4698 /* delete the previous audio mixdown options */
4699 [mixdownPopUp removeAllItems];
4701 acodec = [[audiocodecPopUp selectedItem] tag];
4706 /* find out if our selected output audio codec supports mono and / or 6ch */
4707 /* we also check for an input codec of AC3 or DCA,
4708 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
4709 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
4710 but this may change in the future, so they are separated for flexibility */
4711 int audioCodecsSupportMono =
4712 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4713 (acodec != HB_ACODEC_LAME);
4714 int audioCodecsSupport6Ch =
4715 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
4716 (acodec != HB_ACODEC_LAME);
4718 /* check for AC-3 passthru */
4719 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4722 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4723 [NSString stringWithCString: "AC3 Passthru"]
4724 action: NULL keyEquivalent: @""];
4725 [menuItem setTag: HB_ACODEC_AC3];
4730 /* add the appropriate audio mixdown menuitems to the popupbutton */
4731 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
4732 so that we can reference the mixdown later */
4734 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
4735 int minMixdownUsed = 0;
4736 int maxMixdownUsed = 0;
4738 /* get the input channel layout without any lfe channels */
4739 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
4741 /* do we want to add a mono option? */
4742 if (audioCodecsSupportMono == 1)
4744 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4745 [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
4746 action: NULL keyEquivalent: @""];
4747 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
4748 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
4749 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
4752 /* do we want to add a stereo option? */
4753 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
4754 /* also offer stereo if we have a stereo-or-better source */
4755 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
4757 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4758 [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
4759 action: NULL keyEquivalent: @""];
4760 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
4761 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
4762 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
4765 /* do we want to add a dolby surround (DPL1) option? */
4766 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
4768 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4769 [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
4770 action: NULL keyEquivalent: @""];
4771 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
4772 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
4773 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
4776 /* do we want to add a dolby pro logic 2 (DPL2) option? */
4777 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
4779 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4780 [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
4781 action: NULL keyEquivalent: @""];
4782 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
4783 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
4784 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
4787 /* do we want to add a 6-channel discrete option? */
4788 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
4790 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4791 [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
4792 action: NULL keyEquivalent: @""];
4793 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
4794 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
4795 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
4798 /* do we want to add an AC-3 passthrough option? */
4799 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
4801 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
4802 [NSString stringWithCString: hb_audio_mixdowns[5].human_readable_name]
4803 action: NULL keyEquivalent: @""];
4804 [menuItem setTag: HB_ACODEC_AC3];
4805 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
4806 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
4809 /* auto-select the best mixdown based on our saved mixdown preference */
4811 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
4812 /* ultimately this should be a prefs option */
4815 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
4816 if (mixdownToUse > 0)
4818 useMixdown = mixdownToUse;
4822 useMixdown = HB_AMIXDOWN_DOLBYPLII;
4825 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
4826 if (useMixdown > maxMixdownUsed)
4828 useMixdown = maxMixdownUsed;
4831 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
4832 if (useMixdown < minMixdownUsed)
4834 useMixdown = minMixdownUsed;
4837 /* select the (possibly-amended) preferred mixdown */
4838 [mixdownPopUp selectItemWithTag: useMixdown];
4841 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
4842 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
4845 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
4847 /* If we are using the avi container, we select MP3 as there is no aac available*/
4848 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
4850 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
4854 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
4857 /* Setup our samplerate and bitrate popups we will need based on mixdown */
4858 [self audioTrackMixdownChanged: mixdownPopUp];
4862 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
4864 [self autoSetM4vExtension: sender];
4868 - (IBAction) audioTrackMixdownChanged: (id) sender
4872 /* setup pointers to all of the other audio track controls
4873 * we will need later
4875 NSPopUpButton * mixdownPopUp;
4876 NSPopUpButton * sampleratePopUp;
4877 NSPopUpButton * bitratePopUp;
4878 NSPopUpButton * audiocodecPopUp;
4879 NSPopUpButton * audiotrackPopUp;
4880 NSSlider * drcSlider;
4881 NSTextField * drcField;
4882 if (sender == fAudTrack1MixPopUp)
4884 audiotrackPopUp = fAudLang1PopUp;
4885 audiocodecPopUp = fAudTrack1CodecPopUp;
4886 mixdownPopUp = fAudTrack1MixPopUp;
4887 sampleratePopUp = fAudTrack1RatePopUp;
4888 bitratePopUp = fAudTrack1BitratePopUp;
4889 drcSlider = fAudTrack1DrcSlider;
4890 drcField = fAudTrack1DrcField;
4892 else if (sender == fAudTrack2MixPopUp)
4894 audiotrackPopUp = fAudLang2PopUp;
4895 audiocodecPopUp = fAudTrack2CodecPopUp;
4896 mixdownPopUp = fAudTrack2MixPopUp;
4897 sampleratePopUp = fAudTrack2RatePopUp;
4898 bitratePopUp = fAudTrack2BitratePopUp;
4899 drcSlider = fAudTrack2DrcSlider;
4900 drcField = fAudTrack2DrcField;
4902 else if (sender == fAudTrack3MixPopUp)
4904 audiotrackPopUp = fAudLang3PopUp;
4905 audiocodecPopUp = fAudTrack3CodecPopUp;
4906 mixdownPopUp = fAudTrack3MixPopUp;
4907 sampleratePopUp = fAudTrack3RatePopUp;
4908 bitratePopUp = fAudTrack3BitratePopUp;
4909 drcSlider = fAudTrack3DrcSlider;
4910 drcField = fAudTrack3DrcField;
4914 audiotrackPopUp = fAudLang4PopUp;
4915 audiocodecPopUp = fAudTrack4CodecPopUp;
4916 mixdownPopUp = fAudTrack4MixPopUp;
4917 sampleratePopUp = fAudTrack4RatePopUp;
4918 bitratePopUp = fAudTrack4BitratePopUp;
4919 drcSlider = fAudTrack4DrcSlider;
4920 drcField = fAudTrack4DrcField;
4922 acodec = [[audiocodecPopUp selectedItem] tag];
4923 /* storage variable for the min and max bitrate allowed for this codec */
4929 case HB_ACODEC_FAAC:
4930 /* check if we have a 6ch discrete conversion in either audio track */
4931 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
4933 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
4935 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
4941 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
4943 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
4944 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
4949 case HB_ACODEC_LAME:
4950 /* Lame is happy using our min bitrate of 32 kbps */
4952 /* Lame won't encode if the bitrate is higher than 320 kbps */
4956 case HB_ACODEC_VORBIS:
4957 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
4959 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
4961 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
4967 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
4969 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
4975 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
4981 /* make sure we have a selected title before continuing */
4982 if (fTitle == NULL) return;
4983 /* get the audio so we can find out what input rates are*/
4984 hb_audio_config_t * audio;
4985 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
4986 int inputbitrate = audio->in.bitrate / 1000;
4987 int inputsamplerate = audio->in.samplerate;
4989 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3)
4991 [bitratePopUp removeAllItems];
4993 for( int i = 0; i < hb_audio_bitrates_count; i++ )
4995 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
4997 /* add a new menuitem for this bitrate */
4998 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
4999 [NSString stringWithCString: hb_audio_bitrates[i].string]
5000 action: NULL keyEquivalent: @""];
5001 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5002 [menuItem setTag: hb_audio_bitrates[i].rate];
5006 /* select the default bitrate (but use 384 for 6-ch AAC) */
5007 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5009 [bitratePopUp selectItemWithTag: 384];
5013 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5016 /* populate and set the sample rate popup */
5017 /* Audio samplerate */
5018 [sampleratePopUp removeAllItems];
5019 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5020 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5021 [menuItem setTag: inputsamplerate];
5023 for( int i = 0; i < hb_audio_rates_count; i++ )
5025 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5026 [NSString stringWithCString: hb_audio_rates[i].string]
5027 action: NULL keyEquivalent: @""];
5028 [menuItem setTag: hb_audio_rates[i].rate];
5030 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5031 * and there is no compelling reason to use anything else as default, though the users default
5032 * preset will likely override any setting chosen here.
5034 [sampleratePopUp selectItemWithTag: inputsamplerate];
5037 /* Since AC3 Pass Thru uses the input ac3 bitrate and sample rate, we get the input tracks
5038 * bitrate and dispay it in the bitrate popup even though libhb happily ignores any bitrate input from
5039 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
5041 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3)
5044 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
5045 [bitratePopUp removeAllItems];
5046 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5047 [NSString stringWithFormat:@"%d", inputbitrate]
5048 action: NULL keyEquivalent: @""];
5049 [menuItem setTag: inputbitrate];
5050 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
5051 [bitratePopUp setEnabled: NO];
5052 [sampleratePopUp setEnabled: NO];
5054 [drcSlider setFloatValue: 1.00];
5055 [self audioDRCSliderChanged: drcSlider];
5056 [drcSlider setEnabled: NO];
5057 [drcField setEnabled: NO];
5061 [sampleratePopUp setEnabled: YES];
5062 [bitratePopUp setEnabled: YES];
5063 [drcSlider setEnabled: YES];
5064 [drcField setEnabled: YES];
5066 [self calculateBitrate:nil];
5069 - (IBAction) audioDRCSliderChanged: (id) sender
5071 NSSlider * drcSlider;
5072 NSTextField * drcField;
5073 if (sender == fAudTrack1DrcSlider)
5075 drcSlider = fAudTrack1DrcSlider;
5076 drcField = fAudTrack1DrcField;
5078 else if (sender == fAudTrack2DrcSlider)
5080 drcSlider = fAudTrack2DrcSlider;
5081 drcField = fAudTrack2DrcField;
5083 else if (sender == fAudTrack3DrcSlider)
5085 drcSlider = fAudTrack3DrcSlider;
5086 drcField = fAudTrack3DrcField;
5090 drcSlider = fAudTrack4DrcSlider;
5091 drcField = fAudTrack4DrcField;
5093 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
5094 /* For now, do not call this until we have an intelligent way to determine audio track selections
5095 * compared to presets
5097 //[self customSettingUsed: sender];
5100 - (IBAction) subtitleSelectionChanged: (id) sender
5102 if ([fSubPopUp indexOfSelectedItem] == 0)
5104 [fSubForcedCheck setState: NSOffState];
5105 [fSubForcedCheck setEnabled: NO];
5109 [fSubForcedCheck setEnabled: YES];
5118 #pragma mark Open New Windows
5120 - (IBAction) openHomepage: (id) sender
5122 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5123 URLWithString:@"http://handbrake.fr/"]];
5126 - (IBAction) openForums: (id) sender
5128 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5129 URLWithString:@"http://handbrake.fr/forum/"]];
5131 - (IBAction) openUserGuide: (id) sender
5133 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5134 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
5138 * Shows debug output window.
5140 - (IBAction)showDebugOutputPanel:(id)sender
5142 [outputPanel showOutputPanel:sender];
5146 * Shows preferences window.
5148 - (IBAction) showPreferencesWindow: (id) sender
5150 NSWindow * window = [fPreferencesController window];
5151 if (![window isVisible])
5154 [window makeKeyAndOrderFront: nil];
5158 * Shows queue window.
5160 - (IBAction) showQueueWindow:(id)sender
5162 [fQueueController showQueueWindow:sender];
5166 - (IBAction) toggleDrawer:(id)sender {
5167 [fPresetDrawer toggle:self];
5171 * Shows Picture Settings Window.
5174 - (IBAction) showPicturePanel: (id) sender
5176 [fPictureController showPictureWindow:sender];
5179 - (void) picturePanelFullScreen
5181 [fPictureController setToFullScreenMode];
5184 - (void) picturePanelWindowed
5186 [fPictureController setToWindowedMode];
5189 - (IBAction) showPreviewWindow: (id) sender
5191 [fPictureController showPreviewWindow:sender];
5195 #pragma mark Preset Outline View Methods
5196 #pragma mark - Required
5197 /* These are required by the NSOutlineView Datasource Delegate */
5200 /* used to specify the number of levels to show for each item */
5201 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
5203 /* currently use no levels to test outline view viability */
5204 if (item == nil) // for an outline view the root level of the hierarchy is always nil
5206 return [UserPresets count];
5210 /* we need to return the count of the array in ChildrenArray for this folder */
5211 NSArray *children = nil;
5212 children = [item objectForKey:@"ChildrenArray"];
5213 if ([children count] > 0)
5215 return [children count];
5224 /* We use this to deterimine children of an item */
5225 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(int)index ofItem:(id)item
5228 /* we need to return the count of the array in ChildrenArray for this folder */
5229 NSArray *children = nil;
5232 children = UserPresets;
5236 if ([item objectForKey:@"ChildrenArray"])
5238 children = [item objectForKey:@"ChildrenArray"];
5241 if ((children == nil) || ([children count] <= index))
5247 return [children objectAtIndex:index];
5251 // We are only one level deep, so we can't be asked about children
5252 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
5256 /* We use this to determine if an item should be expandable */
5257 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
5260 /* we need to return the count of the array in ChildrenArray for this folder */
5261 NSArray *children= nil;
5264 children = UserPresets;
5268 if ([item objectForKey:@"ChildrenArray"])
5270 children = [item objectForKey:@"ChildrenArray"];
5274 /* To deterimine if an item should show a disclosure triangle
5275 * we could do it by the children count as so:
5276 * if ([children count] < 1)
5277 * However, lets leave the triangle show even if there are no
5278 * children to help indicate a folder, just like folder in the
5279 * finder can show a disclosure triangle even when empty
5282 /* We need to determine if the item is a folder */
5283 if ([[item objectForKey:@"Folder"] intValue] == 1)
5294 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
5296 // Our outline view has no levels, but we can still expand every item. Doing so
5297 // just makes the row taller. See heightOfRowByItem below.
5298 //return ![(HBQueueOutlineView*)outlineView isDragging];
5304 /* Used to tell the outline view which information is to be displayed per item */
5305 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5307 /* We have two columns right now, icon and PresetName */
5309 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5311 return [item objectForKey:@"PresetName"];
5320 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
5322 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
5324 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
5326 return [NSKeyedArchiver archivedDataWithRootObject:item];
5329 #pragma mark - Added Functionality (optional)
5330 /* Use to customize the font and display characteristics of the title cell */
5331 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
5333 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5337 NSColor *shadowColor;
5338 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
5339 /*check to see if its a selected row */
5340 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
5343 fontColor = [NSColor blackColor];
5344 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
5348 if ([[item objectForKey:@"Type"] intValue] == 0)
5350 fontColor = [NSColor blueColor];
5352 else // User created preset, use a black font
5354 fontColor = [NSColor blackColor];
5356 /* check to see if its a folder */
5357 //if ([[item objectForKey:@"Folder"] intValue] == 1)
5359 //fontColor = [NSColor greenColor];
5364 /* We use Bold Text for the HB Default */
5365 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
5367 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5369 /* We use Bold Text for the User Specified Default */
5370 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
5372 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5376 [cell setTextColor:fontColor];
5377 [cell setFont:txtFont];
5382 /* We use this to edit the name field in the outline view */
5383 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5385 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5390 [theRecord setObject:object forKey:@"PresetName"];
5394 [fPresetsOutlineView reloadData];
5395 /* We save all of the preset data here */
5399 /* We use this to provide tooltips for the items in the presets outline view */
5400 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
5402 //if ([[tc identifier] isEqualToString:@"PresetName"])
5404 /* initialize the tooltip contents variable */
5406 /* if there is a description for the preset, we show it in the tooltip */
5407 if ([item objectForKey:@"PresetDescription"])
5409 loc_tip = [item objectForKey:@"PresetDescription"];
5414 loc_tip = @"No description available";
5421 #pragma mark Preset Outline View Methods (dragging related)
5424 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
5426 // Dragging is only allowed for custom presets.
5427 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
5428 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
5432 // Don't retain since this is just holding temporaral drag information, and it is
5433 //only used during a drag! We could put this in the pboard actually.
5434 fDraggedNodes = items;
5435 // Provide data for our custom type, and simple NSStrings.
5436 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
5438 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
5439 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
5444 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
5447 // Don't allow dropping ONTO an item since they can't really contain any children.
5449 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
5450 if (isOnDropTypeProposal)
5451 return NSDragOperationNone;
5453 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
5456 index = [fPresetsOutlineView rowForItem: item] + 1;
5460 // Don't allow dropping into the Built In Presets.
5461 if (index < presetCurrentBuiltInCount)
5463 return NSDragOperationNone;
5464 index = MAX (index, presetCurrentBuiltInCount);
5467 [outlineView setDropItem:item dropChildIndex:index];
5468 return NSDragOperationGeneric;
5473 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
5475 /* first, lets see if we are dropping into a folder */
5476 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
5478 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
5479 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
5480 [childrenArray addObject:item];
5481 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
5482 [childrenArray autorelease];
5484 else // We are not, so we just move the preset into the existing array
5486 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
5488 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
5489 while (obj = [enumerator nextObject])
5491 [moveItems addIndex:[UserPresets indexOfObject:obj]];
5493 // Successful drop, lets rearrange the view and save it all
5494 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
5496 [fPresetsOutlineView reloadData];
5501 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
5503 unsigned index = [indexSet lastIndex];
5504 unsigned aboveInsertIndexCount = 0;
5506 while (index != NSNotFound)
5508 unsigned removeIndex;
5510 if (index >= insertIndex)
5512 removeIndex = index + aboveInsertIndexCount;
5513 aboveInsertIndexCount++;
5517 removeIndex = index;
5521 id object = [[array objectAtIndex:removeIndex] retain];
5522 [array removeObjectAtIndex:removeIndex];
5523 [array insertObject:object atIndex:insertIndex];
5526 index = [indexSet indexLessThanIndex:index];
5532 #pragma mark - Functional Preset NSOutlineView Methods
5534 - (IBAction)selectPreset:(id)sender
5537 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
5539 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
5540 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5542 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
5544 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
5548 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5552 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
5553 [self formatPopUpChanged:nil];
5555 /* Chapter Markers*/
5556 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
5557 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
5558 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
5559 /* Mux mp4 with http optimization */
5560 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
5563 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
5564 /* We set the advanced opt string here if applicable*/
5565 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
5567 /* Lets run through the following functions to get variables set there */
5568 [self videoEncoderPopUpChanged:nil];
5569 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
5570 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
5571 [self calculateBitrate:nil];
5574 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
5576 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
5577 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
5578 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
5580 [self videoMatrixChanged:nil];
5582 /* Video framerate */
5583 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
5584 detected framerate in the fVidRatePopUp so we use index 0*/
5585 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
5587 [fVidRatePopUp selectItemAtIndex: 0];
5591 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
5595 [fVidGrayscaleCheck setState:[[chosenPreset objectForKey:@"VideoGrayScale"] intValue]];
5597 /* 2 Pass Encoding */
5598 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
5599 [self twoPassCheckboxChanged:nil];
5601 /* Turbo 1st pass for 2 Pass Encoding */
5602 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
5606 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
5608 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5610 [fAudLang1PopUp selectItemAtIndex: 1];
5612 [self audioTrackPopUpChanged: fAudLang1PopUp];
5613 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
5614 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5615 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
5616 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5618 if ([fAudTrack1MixPopUp selectedItem] == nil)
5620 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
5622 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
5623 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5624 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
5626 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
5628 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
5629 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5631 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
5633 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5635 [fAudLang2PopUp selectItemAtIndex: 1];
5637 [self audioTrackPopUpChanged: fAudLang2PopUp];
5638 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
5639 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5640 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
5641 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5643 if ([fAudTrack2MixPopUp selectedItem] == nil)
5645 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
5647 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
5648 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5649 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
5651 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
5653 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
5654 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5656 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
5658 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5660 [fAudLang3PopUp selectItemAtIndex: 1];
5662 [self audioTrackPopUpChanged: fAudLang3PopUp];
5663 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
5664 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5665 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
5666 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5668 if ([fAudTrack3MixPopUp selectedItem] == nil)
5670 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
5672 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
5673 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5674 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
5676 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
5678 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
5679 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5681 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
5683 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5685 [fAudLang4PopUp selectItemAtIndex: 1];
5687 [self audioTrackPopUpChanged: fAudLang4PopUp];
5688 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
5689 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5690 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
5691 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
5693 if ([fAudTrack4MixPopUp selectedItem] == nil)
5695 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
5697 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
5698 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
5699 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
5701 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
5703 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
5704 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5707 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
5709 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
5711 [fAudLang2PopUp selectItemAtIndex: 0];
5712 [self audioTrackPopUpChanged: fAudLang2PopUp];
5714 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
5716 [fAudLang3PopUp selectItemAtIndex: 0];
5717 [self audioTrackPopUpChanged: fAudLang3PopUp];
5719 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
5721 [fAudLang4PopUp selectItemAtIndex: 0];
5722 [self audioTrackPopUpChanged: fAudLang4PopUp];
5726 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
5727 /* Forced Subtitles */
5728 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
5730 /* Picture Settings */
5731 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
5732 * height, width, keep ar, anamorphic and crop settings.
5733 * picture filters are handled separately below.
5735 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
5736 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
5737 * preset completely ignores any picture sizing values in the preset.
5739 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
5741 hb_job_t * job = fTitle->job;
5743 /* If Cropping is set to custom, then recall all four crop values from
5744 when the preset was created and apply them */
5745 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
5747 [fPictureController setAutoCrop:NO];
5749 /* Here we use the custom crop values saved at the time the preset was saved */
5750 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
5751 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
5752 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
5753 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
5756 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
5758 [fPictureController setAutoCrop:YES];
5759 /* Here we use the auto crop values determined right after scan */
5760 job->crop[0] = AutoCropTop;
5761 job->crop[1] = AutoCropBottom;
5762 job->crop[2] = AutoCropLeft;
5763 job->crop[3] = AutoCropRight;
5768 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
5769 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
5771 /* Use Max Picture settings for whatever the dvd is.*/
5772 [self revertPictureSizeToMax:nil];
5773 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5774 if (job->keep_ratio == 1)
5776 hb_fix_aspect( job, HB_KEEP_WIDTH );
5777 if( job->height > fTitle->height )
5779 job->height = fTitle->height;
5780 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5783 job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5785 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
5787 /* we check to make sure the presets width/height does not exceed the sources width/height */
5788 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
5790 /* if so, then we use the sources height and width to avoid scaling up */
5791 //job->width = fTitle->width;
5792 //job->height = fTitle->height;
5793 [self revertPictureSizeToMax:nil];
5795 else // source width/height is >= the preset height/width
5797 /* we can go ahead and use the presets values for height and width */
5798 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
5799 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
5801 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5802 if (job->keep_ratio == 1)
5804 hb_fix_aspect( job, HB_KEEP_WIDTH );
5805 if( job->height > fTitle->height )
5807 job->height = fTitle->height;
5808 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5811 job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5817 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
5818 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
5822 if ([chosenPreset objectForKey:@"PictureDeinterlace"])
5824 /* We check to see if the preset used the past fourth "Slowest" deinterlaceing and set that to "Slower
5825 * since we no longer have a fourth "Slowest" deinterlacing due to the mcdeint bug */
5826 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
5828 [fPictureController setDeinterlace:3];
5832 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
5837 [fPictureController setDeinterlace:0];
5841 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
5843 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
5847 [fPictureController setDetelecine:0];
5850 if ([chosenPreset objectForKey:@"PictureDenoise"])
5852 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
5856 [fPictureController setDenoise:0];
5859 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
5861 /* if its a one, then its the old on/off deblock, set on to 5*/
5862 [fPictureController setDeblock:5];
5866 /* use the settings intValue */
5867 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
5870 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
5872 [fPictureController setDecomb:1];
5876 [fPictureController setDecomb:0];
5879 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
5880 [fPictureController SetTitle:fTitle];
5881 [self calculatePictureSizing:nil];
5887 #pragma mark Manage Presets
5889 - (void) loadPresets {
5890 /* We declare the default NSFileManager into fileManager */
5891 NSFileManager * fileManager = [NSFileManager defaultManager];
5892 /*We define the location of the user presets file */
5893 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
5894 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
5895 /* We check for the presets.plist */
5896 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
5898 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
5901 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
5902 if (nil == UserPresets)
5904 UserPresets = [[NSMutableArray alloc] init];
5905 [self addFactoryPresets:nil];
5907 [fPresetsOutlineView reloadData];
5911 - (IBAction) showAddPresetPanel: (id) sender
5913 /* Deselect the currently selected Preset if there is one*/
5914 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
5916 /* Populate the preset picture settings popup here */
5917 [fPresetNewPicSettingsPopUp removeAllItems];
5918 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
5919 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
5920 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
5921 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
5922 /* Uncheck the preset use filters checkbox */
5923 [fPresetNewPicFiltersCheck setState:NSOffState];
5924 // fPresetNewFolderCheck
5925 [fPresetNewFolderCheck setState:NSOffState];
5926 /* Erase info from the input fields*/
5927 [fPresetNewName setStringValue: @""];
5928 [fPresetNewDesc setStringValue: @""];
5929 /* Show the panel */
5930 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
5933 - (IBAction) closeAddPresetPanel: (id) sender
5935 [NSApp endSheet: fAddPresetPanel];
5936 [fAddPresetPanel orderOut: self];
5939 - (IBAction)addUserPreset:(id)sender
5941 if (![[fPresetNewName stringValue] length])
5942 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
5945 /* Here we create a custom user preset */
5946 [UserPresets addObject:[self createPreset]];
5949 [self closeAddPresetPanel:nil];
5956 /* We Reload the New Table data for presets */
5957 [fPresetsOutlineView reloadData];
5958 /* We save all of the preset data here */
5966 /* We Sort the Presets By Factory or Custom */
5967 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
5968 ascending:YES] autorelease];
5969 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
5971 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
5972 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
5973 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
5976 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
5977 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
5978 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
5979 [UserPresets setArray:sortedArray];
5984 - (IBAction)insertPreset:(id)sender
5986 int index = [fPresetsOutlineView selectedRow];
5987 [UserPresets insertObject:[self createPreset] atIndex:index];
5988 [fPresetsOutlineView reloadData];
5992 - (NSDictionary *)createPreset
5994 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
5995 /* Get the New Preset Name from the field in the AddPresetPanel */
5996 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
5997 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
5998 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
5999 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
6000 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
6001 /*Set whether or not this is default, at creation set to 0*/
6002 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6003 if ([fPresetNewFolderCheck state] == YES)
6005 /* initialize and set an empty array for children here since we are a new folder */
6006 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6007 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6008 [childrenArray autorelease];
6010 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
6012 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
6013 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
6014 /* Get whether or not to use the current Picture Filter settings for the preset */
6015 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
6017 /* Get New Preset Description from the field in the AddPresetPanel*/
6018 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
6020 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
6021 /* Chapter Markers fCreateChapterMarkers*/
6022 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
6023 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6024 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
6025 /* Mux mp4 with http optimization */
6026 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
6027 /* Add iPod uuid atom */
6028 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
6032 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
6033 /* x264 Option String */
6034 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
6036 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
6037 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
6038 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
6039 [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
6041 /* Video framerate */
6042 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
6044 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
6046 else // we can record the actual titleOfSelectedItem
6048 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
6051 [preset setObject:[NSNumber numberWithInt:[fVidGrayscaleCheck state]] forKey:@"VideoGrayScale"];
6052 /* 2 Pass Encoding */
6053 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
6054 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
6055 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
6056 /*Picture Settings*/
6057 hb_job_t * job = fTitle->job;
6058 /* Picture Sizing */
6059 /* Use Max Picture settings for whatever the dvd is.*/
6060 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
6061 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
6062 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
6063 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
6064 [preset setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
6066 /* Set crop settings here */
6067 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
6068 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
6069 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
6070 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
6071 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
6073 /* Picture Filters */
6074 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
6075 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
6076 //[preset setObject:[NSNumber numberWithInt:[fPictureController vfr]] forKey:@"VFR"];
6077 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
6078 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
6079 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
6083 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
6085 [preset setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
6086 [preset setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
6087 [preset setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
6088 [preset setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
6089 [preset setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
6090 [preset setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
6091 [preset setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
6093 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
6095 [preset setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
6096 [preset setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
6097 [preset setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
6098 [preset setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
6099 [preset setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
6100 [preset setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
6101 [preset setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
6103 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
6105 [preset setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
6106 [preset setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
6107 [preset setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
6108 [preset setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
6109 [preset setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
6110 [preset setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
6111 [preset setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
6113 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
6115 [preset setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
6116 [preset setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
6117 [preset setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
6118 [preset setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
6119 [preset setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
6120 [preset setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
6121 [preset setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
6125 [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
6126 /* Forced Subtitles */
6127 [preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
6129 [preset autorelease];
6136 [UserPresets writeToFile:UserPresetsFile atomically:YES];
6137 /* We get the default preset in case it changed */
6138 [self getDefaultPresets:nil];
6142 - (IBAction)deletePreset:(id)sender
6146 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
6150 /* Alert user before deleting preset */
6152 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
6154 if ( status == NSAlertDefaultReturn )
6156 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6157 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6158 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6160 NSEnumerator *enumerator;
6161 NSMutableArray *presetsArrayToMod;
6162 NSMutableArray *tempArray;
6164 /* If we are a root level preset, we are modding the UserPresets array */
6165 if (presetToModLevel == 0)
6167 presetsArrayToMod = UserPresets;
6169 else // We have a parent preset, so we modify the chidren array object for key
6171 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6174 enumerator = [presetsArrayToMod objectEnumerator];
6175 tempArray = [NSMutableArray array];
6177 while (tempObject = [enumerator nextObject])
6179 NSDictionary *thisPresetDict = tempObject;
6180 if (thisPresetDict == presetToMod)
6182 [tempArray addObject:tempObject];
6186 [presetsArrayToMod removeObjectsInArray:tempArray];
6187 [fPresetsOutlineView reloadData];
6193 #pragma mark Manage Default Preset
6195 - (IBAction)getDefaultPresets:(id)sender
6197 presetHbDefault = nil;
6198 presetUserDefault = nil;
6199 presetUserDefaultParent = nil;
6200 presetUserDefaultParentParent = nil;
6201 NSMutableDictionary *presetHbDefaultParent = nil;
6202 NSMutableDictionary *presetHbDefaultParentParent = nil;
6205 BOOL userDefaultFound = NO;
6206 presetCurrentBuiltInCount = 0;
6207 /* First we iterate through the root UserPresets array to check for defaults */
6208 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6210 while (tempObject = [enumerator nextObject])
6212 NSMutableDictionary *thisPresetDict = tempObject;
6213 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6215 presetHbDefault = thisPresetDict;
6217 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6219 presetUserDefault = thisPresetDict;
6220 userDefaultFound = YES;
6222 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
6224 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
6228 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6229 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6231 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
6232 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6234 while (tempObject = [enumerator nextObject])
6236 NSMutableDictionary *thisPresetDict = tempObject;
6237 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6239 presetHbDefault = thisPresetDict;
6240 presetHbDefaultParent = thisPresetDictParent;
6242 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6244 presetUserDefault = thisPresetDict;
6245 presetUserDefaultParent = thisPresetDictParent;
6246 userDefaultFound = YES;
6249 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6250 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6252 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
6253 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6255 while (tempObject = [enumerator nextObject])
6257 NSMutableDictionary *thisPresetDict = tempObject;
6258 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6260 presetHbDefault = thisPresetDict;
6261 presetHbDefaultParent = thisPresetDictParent;
6262 presetHbDefaultParentParent = thisPresetDictParentParent;
6264 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6266 presetUserDefault = thisPresetDict;
6267 presetUserDefaultParent = thisPresetDictParent;
6268 presetUserDefaultParentParent = thisPresetDictParentParent;
6269 userDefaultFound = YES;
6278 /* check to see if a user specified preset was found, if not then assign the parents for
6279 * the presetHbDefault so that we can open the parents for the nested presets
6281 if (userDefaultFound == NO)
6283 presetUserDefaultParent = presetHbDefaultParent;
6284 presetUserDefaultParentParent = presetHbDefaultParentParent;
6288 - (IBAction)setDefaultPreset:(id)sender
6290 /* We need to determine if the item is a folder */
6291 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
6297 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6299 /* First make sure the old user specified default preset is removed */
6300 while (tempObject = [enumerator nextObject])
6302 NSMutableDictionary *thisPresetDict = tempObject;
6303 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6305 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6308 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6309 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6311 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6314 while (tempObject = [enumerator nextObject])
6316 NSMutableDictionary *thisPresetDict1 = tempObject;
6317 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6319 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6321 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6322 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
6324 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
6327 while (tempObject = [enumerator nextObject])
6329 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6331 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6344 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6345 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6346 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6349 NSMutableArray *presetsArrayToMod;
6350 NSMutableArray *tempArray;
6352 /* If we are a root level preset, we are modding the UserPresets array */
6353 if (presetToModLevel == 0)
6355 presetsArrayToMod = UserPresets;
6357 else // We have a parent preset, so we modify the chidren array object for key
6359 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6362 enumerator = [presetsArrayToMod objectEnumerator];
6363 tempArray = [NSMutableArray array];
6365 while (tempObject = [enumerator nextObject])
6367 NSDictionary *thisPresetDict = tempObject;
6368 if (thisPresetDict == presetToMod)
6370 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
6372 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
6379 /* We save all of the preset data here */
6381 /* We Reload the New Table data for presets */
6382 [fPresetsOutlineView reloadData];
6385 - (IBAction)selectDefaultPreset:(id)sender
6387 NSMutableDictionary *presetToMod;
6388 /* if there is a user specified default, we use it */
6389 if (presetUserDefault)
6391 presetToMod = presetUserDefault;
6393 else if (presetHbDefault) //else we use the built in default presetHbDefault
6395 presetToMod = presetHbDefault;
6402 if (presetUserDefaultParent != nil)
6404 [fPresetsOutlineView expandItem:presetUserDefaultParent];
6407 if (presetUserDefaultParentParent != nil)
6409 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
6413 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
6414 [self selectPreset:nil];
6419 #pragma mark Manage Built In Presets
6422 - (IBAction)deleteFactoryPresets:(id)sender
6425 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6429 NSMutableArray *tempArray;
6432 tempArray = [NSMutableArray array];
6433 /* we look here to see if the preset is we move on to the next one */
6434 while ( tempObject = [enumerator nextObject] )
6436 /* if the preset is "Factory" then we put it in the array of
6437 presets to delete */
6438 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
6440 [tempArray addObject:tempObject];
6444 [UserPresets removeObjectsInArray:tempArray];
6445 [fPresetsOutlineView reloadData];
6450 /* We use this method to recreate new, updated factory
6452 - (IBAction)addFactoryPresets:(id)sender
6455 /* First, we delete any existing built in presets */
6456 [self deleteFactoryPresets: sender];
6457 /* Then we generate new built in presets programmatically with fPresetsBuiltin
6458 * which is all setup in HBPresets.h and HBPresets.m*/
6459 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
6471 /*******************************
6472 * Subclass of the HBPresetsOutlineView *
6473 *******************************/
6475 @implementation HBPresetsOutlineView
6476 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
6480 // By default, NSTableView only drags an image of the first column. Change this to
6481 // drag an image of the queue's icon and PresetName columns.
6482 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
6483 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
6488 - (void) mouseDown:(NSEvent *)theEvent
6490 [super mouseDown:theEvent];
6496 - (BOOL) isDragging;