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 ShowPreviewIdentifier */
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 * ShowPreviewIdentifier = @"Show Preview Window Item Identifier";
24 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
25 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
28 /*******************************
29 * HBController implementation *
30 *******************************/
31 @implementation HBController
41 /* replace bundled app icon with one which is 32/64-bit savvy */
42 #if defined( __LP64__ )
43 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
45 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
47 if( fApplicationIcon != nil )
48 [NSApp setApplicationIconImage:fApplicationIcon];
50 [HBPreferencesController registerUserDefaults];
52 fQueueEncodeLibhb = NULL;
53 /* Check for check for the app support directory here as
54 * outputPanel needs it right away, as may other future methods
56 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
58 YES ) objectAtIndex:0];
59 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
60 stringByAppendingPathComponent:@"HandBrake"];
61 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
63 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
66 /* Check for and create the App Support Preview directory if necessary */
67 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
68 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
70 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
73 outputPanel = [[HBOutputPanelController alloc] init];
74 fPictureController = [[PictureController alloc] init];
75 fQueueController = [[HBQueueController alloc] init];
76 fAdvancedOptions = [[HBAdvancedController alloc] init];
77 /* we init the HBPresets class which currently is only used
78 * for updating built in presets, may move more functionality
81 fPresetsBuiltin = [[HBPresets alloc] init];
82 fPreferencesController = [[HBPreferencesController alloc] init];
83 /* Lets report the HandBrake version number here to the activity log and text log file */
84 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
85 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
91 - (void) applicationDidFinishLaunching: (NSNotification *) notification
93 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
94 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
95 fHandle = hb_init(loggingLevel, 0);
96 /* Optional dvd nav UseDvdNav*/
97 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
98 /* Init a separate instance of libhb for user scanning and setting up jobs */
99 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
101 // Set the Growl Delegate
102 [GrowlApplicationBridge setGrowlDelegate: self];
103 /* Init others controllers */
104 [fPictureController SetHandle: fHandle];
105 [fPictureController setHBController: self];
107 [fQueueController setHandle: fQueueEncodeLibhb];
108 [fQueueController setHBController: self];
110 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
111 [fChapterTable setDataSource:fChapterTitlesDelegate];
112 [fChapterTable setDelegate:fChapterTitlesDelegate];
114 /* setup the subtitles delegate and connections to table */
115 fSubtitlesDelegate = [[HBSubtitles alloc] init];
116 [fSubtitlesTable setDataSource:fSubtitlesDelegate];
117 [fSubtitlesTable setDelegate:fSubtitlesDelegate];
118 [fSubtitlesTable setRowHeight:25.0];
120 [fPresetsOutlineView setAutosaveName:@"Presets View"];
121 [fPresetsOutlineView setAutosaveExpandedItems:YES];
123 dockIconProgress = 0;
125 /* Call UpdateUI every 1/2 sec */
126 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
127 scheduledTimerWithTimeInterval:0.5 target:self
128 selector:@selector(updateUI:) userInfo:nil repeats:YES]
129 forMode:NSDefaultRunLoopMode];
131 // Open debug output window now if it was visible when HB was closed
132 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
133 [self showDebugOutputPanel:nil];
135 // Open queue window now if it was visible when HB was closed
136 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
137 [self showQueueWindow:nil];
139 [self openMainWindow:nil];
141 /* We have to set the bool to tell hb what to do after a scan
142 * Initially we set it to NO until we start processing the queue
144 applyQueueToScan = NO;
146 /* Now we re-check the queue array to see if there are
147 * any remaining encodes to be done in it and ask the
148 * user if they want to reload the queue */
149 if ([QueueFileArray count] > 0)
151 /* run getQueueStats to see whats in the queue file */
152 [self getQueueStats];
153 /* this results in these values
154 * fEncodingQueueItem = 0;
156 * fCompletedCount = 0;
157 * fCanceledCount = 0;
161 /*On Screen Notification*/
162 NSString * alertTitle;
164 /* We check to see if there is already another instance of hb running.
165 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
167 if ([self hbInstances] > 1)
169 alertTitle = [NSString stringWithFormat:
170 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
171 NSBeginCriticalAlertSheet(
173 NSLocalizedString(@"Reload Queue", nil),
177 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
178 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
182 if (fWorkingCount > 0)
184 alertTitle = [NSString stringWithFormat:
185 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
186 fWorkingCount,fPendingCount];
190 alertTitle = [NSString stringWithFormat:
191 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
195 NSBeginCriticalAlertSheet(
197 NSLocalizedString(@"Reload Queue", nil),
199 NSLocalizedString(@"Empty Queue", nil),
201 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
202 NSLocalizedString(@" Do you want to reload them ?", nil));
205 // call didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
206 // right below to either clear the old queue or keep it loaded up.
210 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
211 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
213 [self browseSources:nil];
216 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
218 [self browseSources:(id)fOpenSourceTitleMMenu];
225 /* check to see if another instance of HandBrake.app is running */
226 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
227 NSDictionary *aDictionary;
229 for (aDictionary in runningAppDictionaries)
231 // NSLog(@"Open App: %@", [aDictionary valueForKey:@"NSApplicationName"]);
233 if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
241 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
243 if (returnCode == NSAlertOtherReturn)
245 [self clearQueueAllItems];
246 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
247 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
249 [self browseSources:nil];
252 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
254 [self browseSources:(id)fOpenSourceTitleMMenu];
259 if ([self hbInstances] == 1)
261 [self setQueueEncodingItemsAsPending];
263 [self showQueueWindow:NULL];
267 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
269 /* if we are in preview full screen mode, we need to go to
270 * windowed mode and release the display before we terminate.
271 * We do it here (instead of applicationWillTerminate) so we
272 * release the displays and can then see the alerts below.
274 if ([fPictureController previewFullScreenMode] == YES)
276 [fPictureController previewGoWindowed:nil];
280 hb_get_state( fQueueEncodeLibhb, &s );
282 if ( s.state != HB_STATE_IDLE )
284 int result = NSRunCriticalAlertPanel(
285 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
286 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
287 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
289 if (result == NSAlertDefaultReturn)
291 return NSTerminateNow;
294 return NSTerminateCancel;
297 // Warn if items still in the queue
298 else if ( fPendingCount > 0 )
300 int result = NSRunCriticalAlertPanel(
301 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
302 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
303 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
305 if ( result == NSAlertDefaultReturn )
306 return NSTerminateNow;
308 return NSTerminateCancel;
311 return NSTerminateNow;
314 - (void)applicationWillTerminate:(NSNotification *)aNotification
317 [browsedSourceDisplayName release];
318 [outputPanel release];
319 [fQueueController release];
320 [fPreviewController release];
321 [fPictureController release];
322 [fApplicationIcon release];
325 hb_close(&fQueueEncodeLibhb);
329 - (void) awakeFromNib
332 [fWindow setExcludedFromWindowsMenu:YES];
333 [fAdvancedOptions setView:fAdvancedView];
335 /* lets setup our presets drawer for drag and drop here */
336 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
337 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
338 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
340 /* Initialize currentScanCount so HB can use it to
341 evaluate successive scans */
342 currentScanCount = 0;
345 /* Init UserPresets .plist */
348 /* Init QueueFile .plist */
349 [self loadQueueFile];
351 fRipIndicatorShown = NO; // initially out of view in the nib
353 /* For 64 bit builds, the threaded animation in the progress
354 * indicators conflicts with the animation in the advanced tab
355 * for reasons not completely clear. jbrjake found a note in the
356 * 10.5 dev notes regarding this possiblility. It was also noted
357 * that unless specified, setUsesThreadedAnimation defaults to true.
358 * So, at least for now we set the indicator animation to NO for
359 * both the scan and regular progress indicators for both 32 and 64 bit
360 * as it test out fine on both and there is no reason our progress indicators
361 * should require their own thread.
364 [fScanIndicator setUsesThreadedAnimation:NO];
365 [fRipIndicator setUsesThreadedAnimation:NO];
369 /* Show/Dont Show Presets drawer upon launch based
370 on user preference DefaultPresetsDrawerShow*/
371 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
373 [fPresetDrawer setDelegate:self];
374 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
375 stringForKey:@"Drawer Size"] );
376 if( drawerSize.width )
377 [fPresetDrawer setContentSize: drawerSize];
378 [fPresetDrawer open];
381 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
382 [fSrcAngleLabel setHidden:YES];
383 [fSrcAnglePopUp setHidden:YES];
385 /* Setup the start / stop popup */
386 [fEncodeStartStopPopUp removeAllItems];
387 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
388 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
389 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
390 /* Align the start / stop widgets with the chapter popups */
391 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
392 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
394 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
395 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
398 NSMenuItem *menuItem;
399 [fDstFormatPopUp removeAllItems];
401 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
402 [menuItem setTag: HB_MUX_MP4];
404 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
405 [menuItem setTag: HB_MUX_MKV];
407 [fDstFormatPopUp selectItemAtIndex: 0];
409 [self formatPopUpChanged:nil];
411 /* We enable the create chapters checkbox here since we are .mp4 */
412 [fCreateChapterMarkers setEnabled: YES];
413 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
415 [fCreateChapterMarkers setState: NSOnState];
421 [fDstFile2Field setStringValue: [NSString stringWithFormat:
422 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
425 [fVidEncoderPopUp removeAllItems];
426 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
430 [fVidTargetSizeField setIntValue: 700];
431 [fVidBitrateField setIntValue: 1000];
433 [fVidQualityMatrix selectCell: fVidBitrateCell];
434 [self videoMatrixChanged:nil];
436 /* Video framerate */
437 [fVidRatePopUp removeAllItems];
438 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
439 for( int i = 0; i < hb_video_rates_count; i++ )
441 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
443 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
444 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
446 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
448 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
449 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
451 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
453 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
454 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
458 [fVidRatePopUp addItemWithTitle:
459 [NSString stringWithUTF8String: hb_video_rates[i].string]];
462 [fVidRatePopUp selectItemAtIndex: 0];
464 /* Set Auto Crop to On at launch */
465 [fPictureController setAutoCrop:YES];
468 [fAudTrack1BitratePopUp removeAllItems];
469 for( int i = 0; i < hb_audio_bitrates_count; i++ )
471 [fAudTrack1BitratePopUp addItemWithTitle:
472 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
475 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
477 /* Audio samplerate */
478 [fAudTrack1RatePopUp removeAllItems];
479 for( int i = 0; i < hb_audio_rates_count; i++ )
481 [fAudTrack1RatePopUp addItemWithTitle:
482 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
484 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
487 [fStatusField setStringValue: @""];
492 /* We disable the Turbo 1st pass checkbox since we are not x264 */
493 [fVidTurboPassCheck setEnabled: NO];
494 [fVidTurboPassCheck setState: NSOffState];
497 /* lets get our default prefs here */
498 [self getDefaultPresets:nil];
499 /* lets initialize the current successful scancount here to 0 */
500 currentSuccessfulScanCount = 0;
505 - (void) enableUI: (bool) b
507 NSControl * controls[] =
508 { fSrcTitleField, fSrcTitlePopUp,
509 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
510 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
511 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
512 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
513 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
514 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
515 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
516 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
517 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
518 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
519 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
520 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
521 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
522 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
523 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
524 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
525 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
526 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,fSrcFrameEndEncodingField};
529 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
531 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
533 NSTextField * tf = (NSTextField *) controls[i];
534 if( ![tf isBezeled] )
536 [tf setTextColor: b ? [NSColor controlTextColor] :
537 [NSColor disabledControlTextColor]];
541 [controls[i] setEnabled: b];
547 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
548 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
549 [self setEnabledStateOfAudioMixdownControls:nil];
550 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
551 [self calculatePictureSizing:nil];
555 [fPresetsOutlineView setEnabled: NO];
559 [self videoMatrixChanged:nil];
560 [fAdvancedOptions enableUI:b];
564 /***********************************************************************
566 ***********************************************************************
567 * Shows a progression bar on the dock icon, filled according to
568 * 'progress' (0.0 <= progress <= 1.0).
569 * Called with progress < 0.0 or progress > 1.0, restores the original
571 **********************************************************************/
572 - (void) UpdateDockIcon: (float) progress
575 NSBitmapImageRep * bmp;
577 uint32_t black = htonl( 0x000000FF );
578 uint32_t red = htonl( 0xFF0000FF );
579 uint32_t white = htonl( 0xFFFFFFFF );
580 int row_start, row_end;
583 if( progress < 0.0 || progress > 1.0 )
585 [NSApp setApplicationIconImage: fApplicationIcon];
589 /* Get it in a raw bitmap form */
590 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
591 NSTIFFCompressionNone factor: 1.0];
592 bmp = [NSBitmapImageRep imageRepWithData: tiff];
594 /* Draw the progression bar */
595 /* It's pretty simple (ugly?) now, but I'm no designer */
597 row_start = 3 * (int) [bmp size].height / 4;
598 row_end = 7 * (int) [bmp size].height / 8;
600 for( i = row_start; i < row_start + 2; i++ )
602 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
603 for( j = 0; j < (int) [bmp size].width; j++ )
608 for( i = row_start + 2; i < row_end - 2; i++ )
610 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
613 for( j = 2; j < (int) [bmp size].width - 2; j++ )
615 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
627 for( i = row_end - 2; i < row_end; i++ )
629 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
630 for( j = 0; j < (int) [bmp size].width; j++ )
636 /* Now update the dock icon */
637 tiff = [bmp TIFFRepresentationUsingCompression:
638 NSTIFFCompressionNone factor: 1.0];
639 NSImage* icon = [[NSImage alloc] initWithData: tiff];
640 [NSApp setApplicationIconImage: icon];
644 - (void) updateUI: (NSTimer *) timer
647 /* Update UI for fHandle (user scanning instance of libhb ) */
650 list = hb_get_titles( fHandle );
651 /* check to see if there has been a new scan done
652 this bypasses the constraints of HB_STATE_WORKING
653 not allowing setting a newly scanned source */
654 int checkScanCount = hb_get_scancount( fHandle );
655 if( checkScanCount > currentScanCount )
657 currentScanCount = checkScanCount;
658 [fScanIndicator setIndeterminate: NO];
659 [fScanIndicator setDoubleValue: 0.0];
660 [fScanIndicator setHidden: YES];
661 [self showNewScan:nil];
665 hb_get_state( fHandle, &s );
671 #define p s.param.scanning
672 case HB_STATE_SCANNING:
674 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
675 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
676 p.title_cur, p.title_count]];
677 [fScanIndicator setHidden: NO];
678 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
683 #define p s.param.scandone
684 case HB_STATE_SCANDONE:
686 [fScanIndicator setIndeterminate: NO];
687 [fScanIndicator setDoubleValue: 0.0];
688 [fScanIndicator setHidden: YES];
689 [self writeToActivityLog:"ScanDone state received from fHandle"];
690 [self showNewScan:nil];
691 [[fWindow toolbar] validateVisibleItems];
697 #define p s.param.working
698 case HB_STATE_WORKING:
705 #define p s.param.muxing
706 case HB_STATE_MUXING:
713 case HB_STATE_PAUSED:
716 case HB_STATE_WORKDONE:
723 /* Update UI for fQueueEncodeLibhb */
725 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
726 /* check to see if there has been a new scan done
727 this bypasses the constraints of HB_STATE_WORKING
728 not allowing setting a newly scanned source */
730 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
731 if( checkScanCount > currentScanCount )
733 currentScanCount = checkScanCount;
737 hb_get_state( fQueueEncodeLibhb, &s );
743 #define p s.param.scanning
744 case HB_STATE_SCANNING:
746 [fStatusField setStringValue: [NSString stringWithFormat:
747 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
748 p.title_cur, p.title_count]];
750 /* Set the status string in fQueueController as well */
751 [fQueueController setQueueStatusString: [NSString stringWithFormat:
752 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
753 p.title_cur, p.title_count]];
758 #define p s.param.scandone
759 case HB_STATE_SCANDONE:
761 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
762 [self processNewQueueEncode];
763 [[fWindow toolbar] validateVisibleItems];
770 #define p s.param.working
772 case HB_STATE_SEARCHING:
774 NSMutableString * string;
775 NSString * pass_desc;
777 /* Update text field */
779 //string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
780 /* For now, do not announce "pass x of x for the search phase ... */
781 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
785 [string appendFormat:
786 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
789 [fStatusField setStringValue: string];
790 /* Set the status string in fQueueController as well */
791 [fQueueController setQueueStatusString: string];
793 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
794 [fRipIndicator setIndeterminate: NO];
795 [fRipIndicator setDoubleValue:100.0 * progress_total];
797 // If progress bar hasn't been revealed at the bottom of the window, do
798 // that now. This code used to be in doRip. I moved it to here to handle
799 // the case where hb_start is called by HBQueueController and not from
801 if( !fRipIndicatorShown )
803 NSRect frame = [fWindow frame];
804 if( frame.size.width <= 591 )
805 frame.size.width = 591;
806 frame.size.height += 36;
807 frame.origin.y -= 36;
808 [fWindow setFrame:frame display:YES animate:YES];
809 fRipIndicatorShown = YES;
813 /* Update dock icon */
814 /* Note not done yet */
819 case HB_STATE_WORKING:
821 NSMutableString * string;
822 NSString * pass_desc;
823 /* Update text field */
824 if (p.job_cur == 1 && p.job_count > 1)
826 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
828 pass_desc = @"(subtitle scan)";
840 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
844 [string appendFormat:
845 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
846 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
849 [fStatusField setStringValue: string];
850 /* Set the status string in fQueueController as well */
851 [fQueueController setQueueStatusString: string];
853 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
854 [fRipIndicator setIndeterminate: NO];
855 [fRipIndicator setDoubleValue:100.0 * progress_total];
857 // If progress bar hasn't been revealed at the bottom of the window, do
858 // that now. This code used to be in doRip. I moved it to here to handle
859 // the case where hb_start is called by HBQueueController and not from
861 if( !fRipIndicatorShown )
863 NSRect frame = [fWindow frame];
864 if( frame.size.width <= 591 )
865 frame.size.width = 591;
866 frame.size.height += 36;
867 frame.origin.y -= 36;
868 [fWindow setFrame:frame display:YES animate:YES];
869 fRipIndicatorShown = YES;
873 /* Update dock icon */
874 if( dockIconProgress < 100.0 * progress_total )
876 [self UpdateDockIcon: progress_total];
877 dockIconProgress += 5;
884 #define p s.param.muxing
885 case HB_STATE_MUXING:
887 /* Update text field */
888 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
889 /* Set the status string in fQueueController as well */
890 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
892 [fRipIndicator setIndeterminate: YES];
893 [fRipIndicator startAnimation: nil];
895 /* Update dock icon */
896 [self UpdateDockIcon: 1.0];
902 case HB_STATE_PAUSED:
903 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
904 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
908 case HB_STATE_WORKDONE:
910 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
911 // or someone calling hb_stop. In the latter case, hb_stop does not clear
912 // out the remaining passes/jobs in the queue. We'll do that here.
914 // Delete all remaining jobs of this encode.
915 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
916 /* Set the status string in fQueueController as well */
917 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
918 [fRipIndicator setIndeterminate: NO];
919 [fRipIndicator stopAnimation: nil];
920 [fRipIndicator setDoubleValue: 0.0];
921 [[fWindow toolbar] validateVisibleItems];
923 /* Restore dock icon */
924 [self UpdateDockIcon: -1.0];
925 dockIconProgress = 0;
927 if( fRipIndicatorShown )
929 NSRect frame = [fWindow frame];
930 if( frame.size.width <= 591 )
931 frame.size.width = 591;
932 frame.size.height += -36;
933 frame.origin.y -= -36;
934 [fWindow setFrame:frame display:YES animate:YES];
935 fRipIndicatorShown = NO;
937 /* Since we are done with this encode, tell output to stop writing to the
938 * individual encode log
940 [outputPanel endEncodeLog];
941 /* Check to see if the encode state has not been cancelled
942 to determine if we should check for encode done notifications */
943 if( fEncodeState != 2 )
945 NSString *pathOfFinishedEncode;
946 /* Get the output file name for the finished encode */
947 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
949 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
951 [self showGrowlDoneNotification:pathOfFinishedEncode];
953 [self sendToMetaX:pathOfFinishedEncode];
955 /* since we have successfully completed an encode, we increment the queue counter */
956 [self incrementQueueItemDone:nil];
958 /* all end of queue actions below need to be done after all queue encodes have finished
959 * and there are no pending jobs left to process
961 if (fPendingCount == 0)
963 /* If Alert Window or Window and Growl has been selected */
964 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
965 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
967 /*On Screen Notification*/
970 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
971 [NSApp requestUserAttention:NSCriticalRequest];
974 /* If sleep has been selected */
975 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
978 NSDictionary* errorDict;
979 NSAppleEventDescriptor* returnDescriptor = nil;
980 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
981 @"tell application \"Finder\" to sleep"];
982 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
983 [scriptObject release];
985 /* If Shutdown has been selected */
986 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
989 NSDictionary* errorDict;
990 NSAppleEventDescriptor* returnDescriptor = nil;
991 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
992 @"tell application \"Finder\" to shut down"];
993 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
994 [scriptObject release];
1008 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1009 - (void) writeToActivityLog:(const char *) format, ...
1012 va_start(args, format);
1016 vsnprintf( str, 1024, format, args );
1018 time_t _now = time( NULL );
1019 struct tm * now = localtime( &_now );
1020 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1026 #pragma mark Toolbar
1027 // ============================================================
1028 // NSToolbar Related Methods
1029 // ============================================================
1031 - (void) setupToolbar {
1032 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1034 [toolbar setAllowsUserCustomization: YES];
1035 [toolbar setAutosavesConfiguration: YES];
1036 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1038 [toolbar setDelegate: self];
1040 [fWindow setToolbar: toolbar];
1043 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1044 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1045 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1047 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1049 [item setLabel: @"Toggle Presets"];
1050 [item setPaletteLabel: @"Toggler Presets"];
1051 [item setToolTip: @"Open/Close Preset Drawer"];
1052 [item setImage: [NSImage imageNamed: @"Drawer"]];
1053 [item setTarget: self];
1054 [item setAction: @selector(toggleDrawer:)];
1055 [item setAutovalidates: NO];
1057 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1059 [item setLabel: @"Start"];
1060 [item setPaletteLabel: @"Start Encoding"];
1061 [item setToolTip: @"Start Encoding"];
1062 [item setImage: [NSImage imageNamed: @"Play"]];
1063 [item setTarget: self];
1064 [item setAction: @selector(Rip:)];
1066 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1068 [item setLabel: @"Show Queue"];
1069 [item setPaletteLabel: @"Show Queue"];
1070 [item setToolTip: @"Show Queue"];
1071 [item setImage: [NSImage imageNamed: @"Queue"]];
1072 [item setTarget: self];
1073 [item setAction: @selector(showQueueWindow:)];
1074 [item setAutovalidates: NO];
1076 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1078 [item setLabel: @"Add to Queue"];
1079 [item setPaletteLabel: @"Add to Queue"];
1080 [item setToolTip: @"Add to Queue"];
1081 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1082 [item setTarget: self];
1083 [item setAction: @selector(addToQueue:)];
1085 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1087 [item setLabel: @"Pause"];
1088 [item setPaletteLabel: @"Pause Encoding"];
1089 [item setToolTip: @"Pause Encoding"];
1090 [item setImage: [NSImage imageNamed: @"Pause"]];
1091 [item setTarget: self];
1092 [item setAction: @selector(Pause:)];
1094 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1096 [item setLabel: @"Picture Settings"];
1097 [item setPaletteLabel: @"Show Picture Settings"];
1098 [item setToolTip: @"Show Picture Settings"];
1099 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1100 [item setTarget: self];
1101 [item setAction: @selector(showPicturePanel:)];
1103 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1105 [item setLabel: @"Preview Window"];
1106 [item setPaletteLabel: @"Show Preview"];
1107 [item setToolTip: @"Show Preview"];
1108 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1109 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1110 [item setTarget: self];
1111 [item setAction: @selector(showPreviewWindow:)];
1113 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1115 [item setLabel: @"Activity Window"];
1116 [item setPaletteLabel: @"Show Activity Window"];
1117 [item setToolTip: @"Show Activity Window"];
1118 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1119 [item setTarget: self];
1120 [item setAction: @selector(showDebugOutputPanel:)];
1121 [item setAutovalidates: NO];
1123 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1125 [item setLabel: @"Source"];
1126 [item setPaletteLabel: @"Source"];
1127 [item setToolTip: @"Choose Video Source"];
1128 [item setImage: [NSImage imageNamed: @"Source"]];
1129 [item setTarget: self];
1130 [item setAction: @selector(browseSources:)];
1140 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1142 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1143 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1144 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1147 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1149 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1150 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1151 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1152 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1155 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1157 NSString * ident = [toolbarItem itemIdentifier];
1163 hb_get_state( fHandle, &s );
1164 if (s.state == HB_STATE_SCANNING)
1167 if ([ident isEqualToString: ChooseSourceIdentifier])
1169 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1170 [toolbarItem setLabel: @"Cancel Scan"];
1171 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1172 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1176 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1181 if ([ident isEqualToString: ChooseSourceIdentifier])
1183 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1184 [toolbarItem setLabel: @"Source"];
1185 [toolbarItem setPaletteLabel: @"Source"];
1186 [toolbarItem setToolTip: @"Choose Video Source"];
1191 hb_get_state2( fQueueEncodeLibhb, &s );
1193 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1195 if ([ident isEqualToString: StartEncodingIdentifier])
1197 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1198 [toolbarItem setLabel: @"Stop"];
1199 [toolbarItem setPaletteLabel: @"Stop"];
1200 [toolbarItem setToolTip: @"Stop Encoding"];
1203 if ([ident isEqualToString: PauseEncodingIdentifier])
1205 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1206 [toolbarItem setLabel: @"Pause"];
1207 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1208 [toolbarItem setToolTip: @"Pause Encoding"];
1213 if ([ident isEqualToString: AddToQueueIdentifier])
1215 if ([ident isEqualToString: ShowPictureIdentifier])
1217 if ([ident isEqualToString: ShowPreviewIdentifier])
1221 else if (s.state == HB_STATE_PAUSED)
1223 if ([ident isEqualToString: PauseEncodingIdentifier])
1225 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1226 [toolbarItem setLabel: @"Resume"];
1227 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1228 [toolbarItem setToolTip: @"Resume Encoding"];
1231 if ([ident isEqualToString: StartEncodingIdentifier])
1233 if ([ident isEqualToString: AddToQueueIdentifier])
1235 if ([ident isEqualToString: ShowPictureIdentifier])
1237 if ([ident isEqualToString: ShowPreviewIdentifier])
1240 else if (s.state == HB_STATE_SCANNING)
1242 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1244 if ([ident isEqualToString: StartEncodingIdentifier])
1246 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1247 if (hb_count(fHandle) > 0)
1248 [toolbarItem setLabel: @"Start Queue"];
1250 [toolbarItem setLabel: @"Start"];
1251 [toolbarItem setPaletteLabel: @"Start Encoding"];
1252 [toolbarItem setToolTip: @"Start Encoding"];
1255 if ([ident isEqualToString: AddToQueueIdentifier])
1257 if ([ident isEqualToString: ShowPictureIdentifier])
1259 if ([ident isEqualToString: ShowPreviewIdentifier])
1264 /* If there are any pending queue items, make sure the start/stop button is active */
1265 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1267 if ([ident isEqualToString: ShowQueueIdentifier])
1269 if ([ident isEqualToString: ToggleDrawerIdentifier])
1271 if ([ident isEqualToString: ChooseSourceIdentifier])
1273 if ([ident isEqualToString: ShowActivityIdentifier])
1279 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1281 SEL action = [menuItem action];
1284 hb_get_state2( fHandle, &s );
1288 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1289 return SuccessfulScan && [fWindow attachedSheet] == nil;
1291 if (action == @selector(browseSources:))
1293 if (s.state == HB_STATE_SCANNING)
1296 return [fWindow attachedSheet] == nil;
1298 if (action == @selector(selectDefaultPreset:))
1299 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1300 if (action == @selector(Pause:))
1302 if (s.state == HB_STATE_WORKING)
1304 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1305 [menuItem setTitle:@"Pause Encoding"];
1308 else if (s.state == HB_STATE_PAUSED)
1310 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1311 [menuItem setTitle:@"Resume Encoding"];
1317 if (action == @selector(Rip:))
1319 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1321 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1322 [menuItem setTitle:@"Stop Encoding"];
1325 else if (SuccessfulScan)
1327 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1328 [menuItem setTitle:@"Start Encoding"];
1329 return [fWindow attachedSheet] == nil;
1335 if( action == @selector(setDefaultPreset:) )
1337 return [fPresetsOutlineView selectedRow] != -1;
1344 #pragma mark Encode Done Actions
1345 // register a test notification and make
1346 // it enabled by default
1347 #define SERVICE_NAME @"Encode Done"
1348 - (NSDictionary *)registrationDictionaryForGrowl
1350 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1351 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1352 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1355 return registrationDictionary;
1358 -(void)showGrowlDoneNotification:(NSString *) filePath
1360 /* This end of encode action is called as each encode rolls off of the queue */
1361 NSString * finishedEncode = filePath;
1362 /* strip off the path to just show the file name */
1363 finishedEncode = [finishedEncode lastPathComponent];
1364 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1365 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1367 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1368 [GrowlApplicationBridge
1369 notifyWithTitle:@"Put down that cocktail..."
1370 description:growlMssg
1371 notificationName:SERVICE_NAME
1379 -(void)sendToMetaX:(NSString *) filePath
1381 /* This end of encode action is called as each encode rolls off of the queue */
1382 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1384 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
1385 [myScript executeAndReturnError: nil];
1390 #pragma mark Get New Source
1392 /*Opens the source browse window, called from Open Source widgets */
1393 - (IBAction) browseSources: (id) sender
1397 hb_get_state( fHandle, &s );
1398 if (s.state == HB_STATE_SCANNING)
1400 [self cancelScanning:nil];
1405 NSOpenPanel * panel;
1407 panel = [NSOpenPanel openPanel];
1408 [panel setAllowsMultipleSelection: NO];
1409 [panel setCanChooseFiles: YES];
1410 [panel setCanChooseDirectories: YES ];
1411 NSString * sourceDirectory;
1412 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1414 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1418 sourceDirectory = @"~/Desktop";
1419 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1421 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1422 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1424 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1425 modalForWindow: fWindow modalDelegate: self
1426 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1427 contextInfo: sender];
1430 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1431 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1433 /* we convert the sender content of contextInfo back into a variable called sender
1434 * mostly just for consistency for evaluation later
1436 id sender = (id)contextInfo;
1437 /* User selected a file to open */
1438 if( returnCode == NSOKButton )
1440 /* Free display name allocated previously by this code */
1441 [browsedSourceDisplayName release];
1443 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1444 /* we set the last searched source directory in the prefs here */
1445 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1446 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1447 /* we order out sheet, which is the browse window as we need to open
1448 * the title selection sheet right away
1450 [sheet orderOut: self];
1452 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1454 /* We put the chosen source path in the source display text field for the
1455 * source title selection sheet in which the user specifies the specific title to be
1456 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1457 * purposes in the title panel
1460 [fScanSrcTitlePathField setStringValue:scanPath];
1461 NSString *displayTitlescanSourceName;
1463 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1465 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1466 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1467 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1471 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1472 displayTitlescanSourceName = [scanPath lastPathComponent];
1474 /* we set the source display name in the title selection dialogue */
1475 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1476 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1477 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1478 /* We show the actual sheet where the user specifies the title to be scanned
1479 * as we are going to do a title specific scan
1481 [self showSourceTitleScanPanel:nil];
1485 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1486 NSString *path = [[sheet filenames] objectAtIndex: 0];
1488 /* We check to see if the chosen file at path is a package */
1489 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1491 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1492 /* We check to see if this is an .eyetv package */
1493 if ([[path pathExtension] isEqualToString: @"eyetv"])
1495 [self writeToActivityLog:"trying to open eyetv package"];
1496 /* We're looking at an EyeTV package - try to open its enclosed
1498 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1500 int n = [[path stringByAppendingString: @"/"]
1501 completePathIntoString: &mpgname caseSensitive: YES
1502 matchesIntoArray: nil
1503 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1506 /* Found an mpeg inside the eyetv package, make it our scan path
1507 and call performScan on the enclosed mpeg */
1509 [self writeToActivityLog:"found mpeg in eyetv package"];
1510 [self performScan:path scanTitleNum:0];
1514 /* We did not find an mpeg file in our package, so we do not call performScan */
1515 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1518 /* We check to see if this is a .dvdmedia package */
1519 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1521 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1522 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1523 [self writeToActivityLog:"trying to open dvdmedia package"];
1524 [self performScan:path scanTitleNum:0];
1528 /* The package is not an eyetv package, so we do not call performScan */
1529 [self writeToActivityLog:"unable to open package"];
1532 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1534 /* path is not a package, so we call perform scan directly on our file */
1535 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1537 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1538 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1539 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1543 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1544 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1545 /* make sure we remove any path extension as this can also be an '.mpg' file */
1546 browsedSourceDisplayName = [[path lastPathComponent] retain];
1548 [self performScan:path scanTitleNum:0];
1556 - (IBAction)showAboutPanel:(id)sender
1558 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1559 fApplicationIcon, @"ApplicationIcon",
1561 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1565 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1566 - (IBAction) showSourceTitleScanPanel: (id) sender
1568 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1571 [fScanSrcTitleNumField setStringValue: @"0"];
1572 /* Show the panel */
1573 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1576 - (IBAction) closeSourceTitleScanPanel: (id) sender
1578 [NSApp endSheet: fScanSrcTitlePanel];
1579 [fScanSrcTitlePanel orderOut: self];
1581 if(sender == fScanSrcTitleOpenButton)
1583 /* We setup the scan status in the main window to indicate a source title scan */
1584 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1585 [fScanIndicator setHidden: NO];
1586 [fScanIndicator setIndeterminate: YES];
1587 [fScanIndicator startAnimation: nil];
1589 /* We use the performScan method to actually perform the specified scan passing the path and the title
1592 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1596 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1597 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1599 /* set the bool applyQueueToScan so that we dont apply a queue setting to the final scan */
1600 applyQueueToScan = NO;
1601 /* use a bool to determine whether or not we can decrypt using vlc */
1602 BOOL cancelScanDecrypt = 0;
1604 NSString *path = scanPath;
1605 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1607 // Notify ChapterTitles that there's no title
1608 [fChapterTitlesDelegate resetWithTitle:nil];
1609 [fChapterTable reloadData];
1611 // Notify Subtitles that there's no title
1612 [fSubtitlesDelegate resetWithTitle:nil];
1613 [fSubtitlesTable reloadData];
1615 [self enableUI: NO];
1617 if( [detector isVideoDVD] )
1620 #if defined( __LP64__ )
1629 // The chosen path was actually on a DVD, so use the raw block
1630 // device path instead.
1631 path = [detector devicePath];
1632 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1634 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1635 NSString *vlcPath = @"/Applications/VLC.app/Contents/MacOS/lib/libdvdcss.2.dylib";
1636 NSFileManager * fileManager = [NSFileManager defaultManager];
1637 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1639 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1640 cancelScanDecrypt = 1;
1641 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1643 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");
1644 [NSApp requestUserAttention:NSCriticalRequest];
1646 if (status == NSAlertDefaultReturn)
1648 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1649 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1651 else if (status == NSAlertAlternateReturn)
1653 /* User chose to cancel the scan */
1654 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1658 /* 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 */
1659 cancelScanDecrypt = 0;
1660 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1666 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1667 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1670 /* test for architecture of the vlc app */
1671 NSArray *vlc_architecturesArray = [[NSBundle bundleWithPath:@"/Applications/VLC.app"] executableArchitectures];
1672 BOOL vlcIntel32bit = NO;
1673 BOOL vlcIntel64bit = NO;
1674 BOOL vlcPPC32bit = NO;
1675 BOOL vlcPPC64bit = NO;
1676 /* check the available architectures for vlc and note accordingly */
1677 NSEnumerator *enumerator = [vlc_architecturesArray objectEnumerator];
1679 while (tempObject = [enumerator nextObject])
1682 if ([tempObject intValue] == NSBundleExecutableArchitectureI386)
1684 vlcIntel32bit = YES;
1686 if ([tempObject intValue] == NSBundleExecutableArchitectureX86_64)
1688 vlcIntel64bit = YES;
1690 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC)
1694 if ([tempObject intValue] == NSBundleExecutableArchitecturePPC64)
1700 /* Write vlc architecture findings to activity window */
1703 [self writeToActivityLog: " 32-Bit VLC app found for decrypting physical dvd"];
1707 [self writeToActivityLog: " 64-Bit VLC app found for decrypting physical dvd"];
1712 if (vlcFound && hb_arch == 64 && !vlcIntel64bit && cancelScanDecrypt != 1)
1717 /* Appropriate VLC not found, so cancel */
1718 cancelScanDecrypt = 1;
1719 [self writeToActivityLog: "This version of HandBrake is 64 bit, 64 bit version of vlc not found, scan cancelled"];
1720 /*On Screen Notification*/
1723 status = NSRunAlertPanel(@"This version of HandBrake is 64 bit, VLC found but not 64 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 64 bit VLC", nil);
1724 [NSApp requestUserAttention:NSCriticalRequest];
1726 if (status == NSAlertDefaultReturn)
1728 /* User chose to cancel the scan */
1729 [self writeToActivityLog: "cannot open physical dvd VLC found but not 64 bit, scan cancelled"];
1730 cancelScanDecrypt = 1;
1732 else if (status == NSAlertAlternateReturn)
1734 [self writeToActivityLog: "user overrode 64-bit warning trying to open physical dvd without proper decryption"];
1735 cancelScanDecrypt = 0;
1739 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1740 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1744 else if (vlcFound && hb_arch == 32 && !vlcIntel32bit && cancelScanDecrypt != 1)
1747 /* Appropriate VLC not found, so cancel */
1748 cancelScanDecrypt = 1;
1749 [self writeToActivityLog: "This version of HandBrake is 32 bit, 32 bit version of vlc not found, scan cancelled"];
1750 /*On Screen Notification*/
1753 status = NSRunAlertPanel(@"This version of HandBrake is 32 bit, VLC found but not 32 bit!",@"", @"Cancel Scan", @"Attempt Scan Anyway", @"Get 32 bit VLC", nil);
1754 [NSApp requestUserAttention:NSCriticalRequest];
1756 if (status == NSAlertDefaultReturn)
1758 /* User chose to cancel the scan */
1759 [self writeToActivityLog: "cannot open physical dvd VLC found but not 32 bit, scan cancelled"];
1760 cancelScanDecrypt = 1;
1762 else if (status == NSAlertAlternateReturn)
1764 [self writeToActivityLog: "user overrode 32-bit warning trying to open physical dvd without proper decryption"];
1765 cancelScanDecrypt = 0;
1769 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1770 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1776 if (cancelScanDecrypt == 0)
1778 /* we actually pass the scan off to libhb here */
1779 /* If there is no title number passed to scan, we use "0"
1780 * which causes the default behavior of a full source scan
1786 if (scanTitleNum > 0)
1788 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1790 /* We use our advance pref to determine how many previews to scan */
1791 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1792 /* set title to NULL */
1794 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1795 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1799 - (IBAction) cancelScanning:(id)sender
1801 hb_scan_stop(fHandle);
1804 - (IBAction) showNewScan:(id)sender
1808 int indxpri=0; // Used to search the longuest title (default in combobox)
1809 int longuestpri=0; // Used to search the longuest title (default in combobox)
1812 list = hb_get_titles( fHandle );
1814 if( !hb_list_count( list ) )
1816 /* We display a message if a valid dvd source was not chosen */
1817 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1818 SuccessfulScan = NO;
1820 // Notify ChapterTitles that there's no title
1821 [fSubtitlesDelegate resetWithTitle:nil];
1822 [fSubtitlesTable reloadData];
1824 // Notify Subtitles that there's no title
1825 [fChapterTitlesDelegate resetWithTitle:nil];
1826 [fChapterTable reloadData];
1830 /* We increment the successful scancount here by one,
1831 which we use at the end of this function to tell the gui
1832 if this is the first successful scan since launch and whether
1833 or not we should set all settings to the defaults */
1835 currentSuccessfulScanCount++;
1837 [[fWindow toolbar] validateVisibleItems];
1839 [fSrcTitlePopUp removeAllItems];
1840 for( int i = 0; i < hb_list_count( list ); i++ )
1842 title = (hb_title_t *) hb_list_item( list, i );
1844 currentSource = [NSString stringWithUTF8String: title->name];
1845 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1846 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1848 /* Use the dvd name in the default output field here
1849 May want to add code to remove blank spaces for some dvd names*/
1850 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1851 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1853 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1854 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1858 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1859 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1863 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1865 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1869 [fSrcTitlePopUp addItemWithTitle: [NSString
1870 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1871 title->name,title->index, title->hours, title->minutes,
1875 /* if we are a stream, select the first title */
1876 if (title->type == HB_STREAM_TYPE)
1878 [fSrcTitlePopUp selectItemAtIndex: 0];
1882 /* if not then select the longest title (dvd) */
1883 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1885 [self titlePopUpChanged:nil];
1887 SuccessfulScan = YES;
1888 [self enableUI: YES];
1890 /* if its the initial successful scan after awakeFromNib */
1891 if (currentSuccessfulScanCount == 1)
1893 [self encodeStartStopPopUpChanged:nil];
1895 [self selectDefaultPreset:nil];
1897 // Open preview window now if it was visible when HB was closed
1898 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1899 [self showPreviewWindow:nil];
1901 // Open picture sizing window now if it was visible when HB was closed
1902 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1903 [self showPicturePanel:nil];
1914 #pragma mark New Output Destination
1916 - (IBAction) browseFile: (id) sender
1918 /* Open a panel to let the user choose and update the text field */
1919 NSSavePanel * panel = [NSSavePanel savePanel];
1920 /* We get the current file name and path from the destination field here */
1921 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1922 modalForWindow: fWindow modalDelegate: self
1923 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1927 - (void) browseFileDone: (NSSavePanel *) sheet
1928 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1930 if( returnCode == NSOKButton )
1932 [fDstFile2Field setStringValue: [sheet filename]];
1933 /* Save this path to the prefs so that on next browse destination window it opens there */
1934 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1935 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1941 #pragma mark Main Window Control
1943 - (IBAction) openMainWindow: (id) sender
1945 [fWindow makeKeyAndOrderFront:nil];
1948 - (BOOL) windowShouldClose: (id) sender
1953 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1956 [fWindow makeKeyAndOrderFront:nil];
1964 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1965 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1970 #pragma mark Queue File
1972 - (void) loadQueueFile {
1973 /* We declare the default NSFileManager into fileManager */
1974 NSFileManager * fileManager = [NSFileManager defaultManager];
1975 /*We define the location of the user presets file */
1976 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1977 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1978 /* We check for the presets.plist */
1979 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1981 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1984 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1985 /* lets check to see if there is anything in the queue file .plist */
1986 if (nil == QueueFileArray)
1988 /* if not, then lets initialize an empty array */
1989 QueueFileArray = [[NSMutableArray alloc] init];
1991 /* Initialize our curQueueEncodeIndex to 0
1992 * so we can use it to track which queue
1993 * item is to be used to track our encodes */
1994 /* NOTE: this should be changed if and when we
1995 * are able to get the last unfinished encode
1996 * in the case of a crash or shutdown */
2001 [self clearQueueEncodedItems];
2003 currentQueueEncodeIndex = 0;
2006 - (void)addQueueFileItem
2008 [QueueFileArray addObject:[self createQueueFileItem]];
2009 [self saveQueueFileItem];
2013 - (void) removeQueueFileItem:(int) queueItemToRemove
2016 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
2017 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
2019 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
2020 * by one to keep in sync with the queue array
2022 currentQueueEncodeIndex--;
2023 [self writeToActivityLog: "removeQueueFileItem: Removing a cancelled/finished encode, decrement currentQueueEncodeIndex to %d", currentQueueEncodeIndex];
2025 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2026 [self saveQueueFileItem];
2030 - (void)saveQueueFileItem
2032 [QueueFileArray writeToFile:QueueFile atomically:YES];
2033 [fQueueController setQueueArray: QueueFileArray];
2034 [self getQueueStats];
2037 - (void)getQueueStats
2039 /* lets get the stats on the status of the queue array */
2041 fEncodingQueueItem = 0;
2043 fCompletedCount = 0;
2047 /* We use a number system to set the encode status of the queue item
2049 * 0 == already encoded
2050 * 1 == is being encoded
2051 * 2 == is yet to be encoded
2056 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2058 while (tempObject = [enumerator nextObject])
2060 NSDictionary *thisQueueDict = tempObject;
2061 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2065 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2068 fEncodingQueueItem = i;
2070 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2074 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2081 /* Set the queue status field in the main window */
2082 NSMutableString * string;
2083 if (fPendingCount == 1)
2085 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2089 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2091 [fQueueStatus setStringValue:string];
2094 /* This method will set any item marked as encoding back to pending
2095 * currently used right after a queue reload
2097 - (void) setQueueEncodingItemsAsPending
2099 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2101 NSMutableArray *tempArray;
2102 tempArray = [NSMutableArray array];
2103 /* we look here to see if the preset is we move on to the next one */
2104 while ( tempObject = [enumerator nextObject] )
2106 /* If the queue item is marked as "encoding" (1)
2107 * then change its status back to pending (2) which effectively
2108 * puts it back into the queue to be encoded
2110 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2112 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2114 [tempArray addObject:tempObject];
2117 [QueueFileArray setArray:tempArray];
2118 [self saveQueueFileItem];
2122 /* This method will clear the queue of any encodes that are not still pending
2123 * this includes both successfully completed encodes as well as cancelled encodes */
2124 - (void) clearQueueEncodedItems
2126 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2128 NSMutableArray *tempArray;
2129 tempArray = [NSMutableArray array];
2130 /* we look here to see if the preset is we move on to the next one */
2131 while ( tempObject = [enumerator nextObject] )
2133 /* If the queue item is either completed (0) or cancelled (3) from the
2134 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2135 * NOTE: this means we retain pending (2) and also an item that is marked as
2136 * still encoding (1). If the queue has an item that is still marked as encoding
2137 * from a previous session, we can conlude that HB was either shutdown, or crashed
2138 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2140 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2142 [tempArray addObject:tempObject];
2146 [QueueFileArray removeObjectsInArray:tempArray];
2147 [self saveQueueFileItem];
2150 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2151 - (void) clearQueueAllItems
2153 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2155 NSMutableArray *tempArray;
2156 tempArray = [NSMutableArray array];
2157 /* we look here to see if the preset is we move on to the next one */
2158 while ( tempObject = [enumerator nextObject] )
2160 [tempArray addObject:tempObject];
2163 [QueueFileArray removeObjectsInArray:tempArray];
2164 [self saveQueueFileItem];
2167 /* This method will duplicate prepareJob however into the
2168 * queue .plist instead of into the job structure so it can
2169 * be recalled later */
2170 - (NSDictionary *)createQueueFileItem
2172 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2174 hb_list_t * list = hb_get_titles( fHandle );
2175 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2176 [fSrcTitlePopUp indexOfSelectedItem] );
2177 hb_job_t * job = title->job;
2181 /* We use a number system to set the encode status of the queue item
2182 * 0 == already encoded
2183 * 1 == is being encoded
2184 * 2 == is yet to be encoded
2187 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2188 /* Source and Destination Information */
2190 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2191 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2192 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2193 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2195 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2196 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2198 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2200 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2202 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2204 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2206 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2208 /* Chapter encode info */
2209 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2210 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2211 /* Time (pts) encode info */
2212 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2213 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2214 /* Frame number encode info */
2215 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2216 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2219 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2220 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2221 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2223 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2225 /* Lets get the preset info if there is any */
2226 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2227 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2229 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2230 /* Chapter Markers*/
2231 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2232 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2234 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2238 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2241 /* We need to get the list of chapter names to put into an array and store
2242 * in our queue, so they can be reapplied in prepareJob when this queue
2243 * item comes up if Chapter Markers is set to on.
2246 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2247 int chaptercount = hb_list_count( fTitle->list_chapter );
2248 for( i = 0; i < chaptercount; i++ )
2250 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2251 if( chapter != NULL )
2253 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2256 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2257 [ChapterNamesArray autorelease];
2259 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2260 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2261 /* Mux mp4 with http optimization */
2262 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2263 /* Add iPod uuid atom */
2264 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2268 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2269 /* x264 Option String */
2270 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2272 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2273 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2274 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2275 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2277 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2279 /* 2 Pass Encoding */
2280 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2281 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2282 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2284 /* Picture Sizing */
2285 /* Use Max Picture settings for whatever the dvd is.*/
2286 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2287 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2288 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2289 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2290 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2291 /* if we are custom anamorphic, store the exact storage, par and display dims */
2292 if (fTitle->job->anamorphic.mode == 3)
2294 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.modulus] forKey:@"PicturePARModulus"];
2296 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2297 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2299 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2300 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2302 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2303 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2306 NSString * pictureSummary;
2307 pictureSummary = [fPictureSizeField stringValue];
2308 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2309 /* Set crop settings here */
2310 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2311 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2312 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2313 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2314 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2316 /* Picture Filters */
2317 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2318 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2320 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2321 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2322 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2324 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2325 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2327 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2328 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2330 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2332 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2335 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2337 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2338 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2339 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2340 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2341 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2342 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2343 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2345 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2347 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2348 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2349 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2350 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2351 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2352 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2353 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2355 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2357 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2358 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2359 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2360 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2361 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2362 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2363 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2365 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2367 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2368 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2369 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2370 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2371 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2372 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2373 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2377 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2378 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2379 [subtitlesArray autorelease];
2381 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2383 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2385 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2388 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2392 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2395 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2396 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2397 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2399 /* Picture Sizing */
2400 /* Use Max Picture settings for whatever the dvd is.*/
2401 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2402 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2403 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2404 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2405 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2407 /* Set crop settings here */
2408 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2409 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2410 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2411 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2412 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2416 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2418 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio1Encoder"];
2419 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2420 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2421 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2422 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2424 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2426 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio2Encoder"];
2427 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2428 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2429 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2430 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2432 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2434 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio3Encoder"];
2435 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2436 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2437 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2438 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2440 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2442 //[queueFileJob setObject:[fAudTrack1CodecPopUp indexOfSelectedItem] forKey:@"JobAudio4Encoder"];
2443 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2444 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2445 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2446 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2450 /* we need to auto relase the queueFileJob and return it */
2451 [queueFileJob autorelease];
2452 return queueFileJob;
2456 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2457 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2459 NSUInteger index = [indexSet lastIndex];
2460 NSUInteger aboveInsertIndexCount = 0;
2463 NSUInteger removeIndex;
2465 if (index >= insertIndex)
2467 removeIndex = index + aboveInsertIndexCount;
2468 aboveInsertIndexCount++;
2472 removeIndex = index;
2476 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2477 [QueueFileArray removeObjectAtIndex:removeIndex];
2478 [QueueFileArray insertObject:object atIndex:insertIndex];
2481 index = [indexSet indexLessThanIndex:index];
2483 /* We save all of the Queue data here
2484 * and it also gets sent back to the queue controller*/
2485 [self saveQueueFileItem];
2491 #pragma mark Queue Job Processing
2493 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2495 int i = currentQueueEncodeIndex;
2496 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2498 /* We save all of the Queue data here */
2499 [self saveQueueFileItem];
2500 /* We Reload the New Table data for presets */
2501 //[fPresetsOutlineView reloadData];
2503 /* Since we have now marked a queue item as done
2504 * we can go ahead and increment currentQueueEncodeIndex
2505 * so that if there is anything left in the queue we can
2506 * go ahead and move to the next item if we want to */
2507 currentQueueEncodeIndex++ ;
2508 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2509 int queueItems = [QueueFileArray count];
2510 /* If we still have more items in our queue, lets go to the next one */
2511 if (currentQueueEncodeIndex < queueItems)
2513 [self writeToActivityLog: "incrementQueueItemDone currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
2514 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2518 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2522 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2523 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2525 /* Tell HB to output a new activity log file for this encode */
2526 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2529 /* use a bool to determine whether or not we can decrypt using vlc */
2530 BOOL cancelScanDecrypt = 0;
2531 /* set the bool so that showNewScan knows to apply the appropriate queue
2532 * settings as this is a queue rescan
2534 applyQueueToScan = YES;
2535 NSString *path = scanPath;
2536 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2538 /*On Screen Notification*/
2540 //status = NSRunAlertPanel(@"HandBrake is now loading up a new queue item...",@"Would You Like to wait until you add another encode?", @"Cancel", @"Okay", nil);
2541 //[NSApp requestUserAttention:NSCriticalRequest];
2543 if( [detector isVideoDVD] )
2545 // The chosen path was actually on a DVD, so use the raw block
2546 // device path instead.
2547 path = [detector devicePath];
2548 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2550 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2551 NSString *vlcPath = @"/Applications/VLC.app";
2552 NSFileManager * fileManager = [NSFileManager defaultManager];
2553 if ([fileManager fileExistsAtPath:vlcPath] == 0)
2555 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2556 cancelScanDecrypt = 1;
2557 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2559 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");
2560 [NSApp requestUserAttention:NSCriticalRequest];
2562 if (status == NSAlertDefaultReturn)
2564 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2565 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2567 else if (status == NSAlertAlternateReturn)
2569 /* User chose to cancel the scan */
2570 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2574 /* 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 */
2575 cancelScanDecrypt = 0;
2576 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2582 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2583 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2587 if (cancelScanDecrypt == 0)
2589 /* we actually pass the scan off to libhb here */
2590 /* If there is no title number passed to scan, we use "0"
2591 * which causes the default behavior of a full source scan
2597 if (scanTitleNum > 0)
2599 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2602 [self writeToActivityLog: "performNewQueueScan currentQueueEncodeIndex is: %d", currentQueueEncodeIndex];
2603 /* We use our advance pref to determine how many previews to scan */
2604 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2605 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2609 /* This method was originally used to load up a new queue item in the gui and
2610 * then start processing it. However we now have modified -prepareJob and use a second
2611 * instance of libhb to do our actual encoding, therefor right now it is not required.
2612 * Nonetheless I want to leave this in here
2613 * because basically its everything we need to be able to actually modify a pending queue
2614 * item in the gui and resave it. At least for now - dynaflash
2617 - (IBAction)applyQueueSettings:(id)sender
2619 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2620 hb_job_t * job = fTitle->job;
2622 /* Set title number and chapters */
2623 /* since the queue only scans a single title, we really don't need to pick a title */
2624 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2626 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2627 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2630 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2631 [self formatPopUpChanged:nil];
2633 /* Chapter Markers*/
2634 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2635 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2636 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2637 /* Mux mp4 with http optimization */
2638 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2641 /* We set the advanced opt string here if applicable*/
2642 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2643 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2645 /* Lets run through the following functions to get variables set there */
2646 [self videoEncoderPopUpChanged:nil];
2647 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2648 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2649 [self calculateBitrate:nil];
2652 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2654 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2655 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2656 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2658 [self videoMatrixChanged:nil];
2660 /* Video framerate */
2661 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2662 detected framerate in the fVidRatePopUp so we use index 0*/
2663 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2665 [fVidRatePopUp selectItemAtIndex: 0];
2669 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2672 /* 2 Pass Encoding */
2673 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2674 [self twoPassCheckboxChanged:nil];
2675 /* Turbo 1st pass for 2 Pass Encoding */
2676 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2679 if ([queueToApply objectForKey:@"Audio1Track"] > 0)
2681 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2683 [fAudLang1PopUp selectItemAtIndex: 1];
2685 [self audioTrackPopUpChanged: fAudLang1PopUp];
2686 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2687 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2688 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2689 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2691 if ([fAudTrack1MixPopUp selectedItem] == nil)
2693 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2695 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
2696 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2697 if (![[queueToApply objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
2699 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2701 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2702 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2704 if ([queueToApply objectForKey:@"Audio2Track"] > 0)
2706 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2708 [fAudLang2PopUp selectItemAtIndex: 1];
2710 [self audioTrackPopUpChanged: fAudLang2PopUp];
2711 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2712 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2713 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2714 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2716 if ([fAudTrack2MixPopUp selectedItem] == nil)
2718 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2720 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2721 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2722 if (![[queueToApply objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
2724 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2726 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2727 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2729 if ([queueToApply objectForKey:@"Audio3Track"] > 0)
2731 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2733 [fAudLang3PopUp selectItemAtIndex: 1];
2735 [self audioTrackPopUpChanged: fAudLang3PopUp];
2736 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2737 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2738 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2739 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2741 if ([fAudTrack3MixPopUp selectedItem] == nil)
2743 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2745 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2746 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2747 if (![[queueToApply objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
2749 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2751 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2752 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2754 if ([queueToApply objectForKey:@"Audio4Track"] > 0)
2756 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2758 [fAudLang4PopUp selectItemAtIndex: 1];
2760 [self audioTrackPopUpChanged: fAudLang4PopUp];
2761 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2762 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2763 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2764 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
2766 if ([fAudTrack4MixPopUp selectedItem] == nil)
2768 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2770 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2771 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
2772 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
2774 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2776 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2777 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2782 [fSubPopUp selectItemWithTitle:[queueToApply objectForKey:@"Subtitles"]];
2783 /* Forced Subtitles */
2784 [fSubForcedCheck setState:[[queueToApply objectForKey:@"SubtitlesForced"] intValue]];
2786 /* Picture Settings */
2787 /* we check to make sure the presets width/height does not exceed the sources width/height */
2788 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2790 /* if so, then we use the sources height and width to avoid scaling up */
2791 job->width = fTitle->width;
2792 job->height = fTitle->height;
2794 else // source width/height is >= the preset height/width
2796 /* we can go ahead and use the presets values for height and width */
2797 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2798 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2800 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2801 if (job->keep_ratio == 1)
2803 hb_fix_aspect( job, HB_KEEP_WIDTH );
2804 if( job->height > fTitle->height )
2806 job->height = fTitle->height;
2807 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2810 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2813 /* If Cropping is set to custom, then recall all four crop values from
2814 when the preset was created and apply them */
2815 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2817 [fPictureController setAutoCrop:NO];
2819 /* Here we use the custom crop values saved at the time the preset was saved */
2820 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2821 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2822 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2823 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2826 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2828 [fPictureController setAutoCrop:YES];
2829 /* Here we use the auto crop values determined right after scan */
2830 job->crop[0] = AutoCropTop;
2831 job->crop[1] = AutoCropBottom;
2832 job->crop[2] = AutoCropLeft;
2833 job->crop[3] = AutoCropRight;
2839 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2842 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2844 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2846 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2848 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2850 [fPictureController setGrayscale:[[queueToApply objectForKey:@"VideoGrayScale"] intValue]];
2852 [self calculatePictureSizing:nil];
2855 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2856 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2857 // [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2858 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2860 /* Deselect the currently selected Preset if there is one*/
2861 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2862 //[self selectPreset:nil];
2864 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2865 /* Change UI to show "Custom" settings are being used */
2866 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2868 curUserPresetChosenNum = nil;
2872 /* Deselect the currently selected Preset if there is one*/
2873 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2874 /* Change UI to show "Custom" settings are being used */
2875 [fPresetSelectedDisplay setStringValue: @"Custom"];
2877 //curUserPresetChosenNum = nil;
2880 /* We need to set this bool back to NO, in case the user wants to do a scan */
2881 //applyQueueToScan = NO;
2883 /* so now we go ahead and process the new settings */
2884 [self processNewQueueEncode];
2889 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2890 - (void) processNewQueueEncode
2892 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2893 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2894 hb_job_t * job = title->job;
2896 if( !hb_list_count( list ) )
2898 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2901 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2902 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2903 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2904 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2905 //[self writeToActivityLog: "processNewQueueEncode sending to prepareJob"];
2909 * If scanning we need to do some extra setup of the job.
2911 if( job->indepth_scan == 1 )
2916 * When subtitle scan is enabled do a fast pre-scan job
2917 * which will determine which subtitles to enable, if any.
2920 x264opts_tmp = job->x264opts;
2922 job->x264opts = NULL;
2924 job->indepth_scan = 1;
2928 * Add the pre-scan job
2930 hb_add( fQueueEncodeLibhb, job );
2931 job->x264opts = x264opts_tmp;
2935 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2937 job->indepth_scan = 0;
2943 hb_add( fQueueEncodeLibhb, job );
2947 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2948 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2950 hb_add( fQueueEncodeLibhb, job );
2955 job->indepth_scan = 0;
2958 hb_add( fQueueEncodeLibhb, job );
2961 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2962 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2963 /* Lets mark our new encode as 1 or "Encoding" */
2964 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2965 [self saveQueueFileItem];
2967 /* we need to clean up the subtitle tracks after the job(s) have been set */
2968 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2970 for(ii = 0; ii < num_subtitle_tracks; ii++)
2972 hb_subtitle_t * subtitle;
2973 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2976 hb_list_rem(job->list_subtitle, subtitle);
2981 /* We should be all setup so let 'er rip */
2986 #pragma mark Live Preview
2987 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2988 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2991 - (void) prepareJobForPreview
2993 hb_list_t * list = hb_get_titles( fHandle );
2994 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2995 [fSrcTitlePopUp indexOfSelectedItem] );
2996 hb_job_t * job = title->job;
2997 hb_audio_config_t * audio;
2998 /* set job->angle for libdvdnav */
2999 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3000 /* Chapter selection */
3001 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3002 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3004 /* Format (Muxer) and Video Encoder */
3005 job->mux = [[fDstFormatPopUp selectedItem] tag];
3006 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3008 job->chapter_markers = 0;
3010 if( job->vcodec & HB_VCODEC_X264 )
3013 /* Below Sends x264 options to the core library if x264 is selected*/
3014 /* Lets use this as per Nyx, Thanks Nyx!*/
3015 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3016 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3017 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3022 /* Video settings */
3023 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3024 * and detelecine is on, so we handle that in the logic below
3027 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3029 /* a specific framerate has been chosen */
3030 job->vrate = 27000000;
3031 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3032 /* We are not same as source so we set job->cfr to 1
3033 * to enable constant frame rate since user has specified
3034 * a specific framerate*/
3039 /* We are same as source (variable) */
3040 job->vrate = title->rate;
3041 job->vrate_base = title->rate_base;
3042 /* We are same as source so we set job->cfr to 0
3043 * to enable true same as source framerate */
3045 /* If we are same as source and we have detelecine on, we need to turn on
3048 if ([fPictureController detelecine] == 1)
3054 switch( [fVidQualityMatrix selectedRow] )
3058 Bitrate should already have been calculated and displayed
3059 in fVidBitrateField, so let's just use it */
3061 job->vquality = -1.0;
3062 job->vbitrate = [fVidBitrateField intValue];
3065 job->vquality = [fVidQualityRFField floatValue];
3070 /* Subtitle settings */
3071 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3078 bool one_burned = FALSE;
3081 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3083 while (tempObject = [enumerator nextObject])
3086 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3087 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3088 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3089 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3091 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3092 * we want to ignore it for display as well as encoding.
3096 /* if i is 0, then we are in the first item of the subtitles which we need to
3097 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3098 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3101 /* if we are on the first track and using "Foreign Audio Search" */
3102 if (i == 0 && subtitle == 1)
3104 /* NOTE: Currently foreign language search is borked for preview.
3105 * Commented out but left in for initial commit. */
3108 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3110 job->indepth_scan = 1;
3111 if (burned == 1 || job->mux != HB_MUX_MP4)
3113 if (burned != 1 && job->mux == HB_MUX_MKV)
3115 job->select_subtitle_config.dest = PASSTHRUSUB;
3119 job->select_subtitle_config.dest = RENDERSUB;
3122 job->select_subtitle_config.force = force;
3123 job->select_subtitle_config.default_track = def;
3132 /* for the actual source tracks, we must subtract the non source entries so
3133 * that the menu index matches the source subtitle_list index for convenience */
3136 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3137 * Foreign Language Search is 1) so subtract 2 */
3138 subtitle = subtitle - 2;
3142 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3145 subtitle = subtitle - 1;
3148 /* We are setting a source subtitle so access the source subtitle info */
3149 hb_subtitle_t * subt;
3151 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3153 /* if we are getting the subtitles from an external srt file */
3154 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3156 hb_subtitle_config_t sub_config;
3158 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3160 /* we need to srncpy file path and char code */
3161 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3162 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3164 sub_config.force = 0;
3165 sub_config.dest = PASSTHRUSUB;
3166 sub_config.default_track = def;
3168 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3173 hb_subtitle_config_t sub_config = subt->config;
3175 if (!burned && job->mux == HB_MUX_MKV &&
3176 subt->format == PICTURESUB)
3178 sub_config.dest = PASSTHRUSUB;
3180 else if (!burned && job->mux == HB_MUX_MP4 &&
3181 subt->format == PICTURESUB)
3183 // Skip any non-burned vobsubs when output is mp4
3186 else if ( burned && subt->format == PICTURESUB )
3188 // Only allow one subtitle to be burned into the video
3193 sub_config.force = force;
3194 sub_config.default_track = def;
3195 hb_subtitle_add( job, &sub_config, subtitle );
3205 [subtitlesArray autorelease];
3208 /* Audio tracks and mixdowns */
3209 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3210 int audiotrack_count = hb_list_count(job->list_audio);
3211 for( int i = 0; i < audiotrack_count;i++)
3213 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3214 hb_list_rem(job->list_audio, temp_audio);
3216 /* Now lets add our new tracks to the audio list here */
3217 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3219 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3220 hb_audio_config_init(audio);
3221 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3222 /* We go ahead and assign values to our audio->out.<properties> */
3223 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3224 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3225 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3226 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3227 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3228 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3230 hb_audio_add( job, audio );
3233 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3235 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3236 hb_audio_config_init(audio);
3237 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3238 /* We go ahead and assign values to our audio->out.<properties> */
3239 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3240 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3241 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3242 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3243 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3244 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3246 hb_audio_add( job, audio );
3251 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3253 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3254 hb_audio_config_init(audio);
3255 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3256 /* We go ahead and assign values to our audio->out.<properties> */
3257 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3258 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3259 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3260 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3261 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3262 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3264 hb_audio_add( job, audio );
3269 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3271 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3272 hb_audio_config_init(audio);
3273 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3274 /* We go ahead and assign values to our audio->out.<properties> */
3275 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3276 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3277 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3278 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3279 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3280 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3282 hb_audio_add( job, audio );
3291 /* Though Grayscale is not really a filter, per se
3292 * we put it here since its in the filters panel
3295 if ([fPictureController grayscale])
3304 /* Initialize the filters list */
3305 job->filters = hb_list_init();
3307 /* Now lets call the filters if applicable.
3308 * The order of the filters is critical
3312 if ([fPictureController detelecine] == 1)
3314 /* use a custom detelecine string */
3315 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3316 hb_list_add( job->filters, &hb_filter_detelecine );
3318 if ([fPictureController detelecine] == 2)
3321 hb_list_add( job->filters, &hb_filter_detelecine );
3326 if ([fPictureController useDecomb] == 1)
3329 /* we add the custom string if present */
3330 if ([fPictureController decomb] == 1)
3332 /* use a custom decomb string */
3333 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3334 hb_list_add( job->filters, &hb_filter_decomb );
3336 if ([fPictureController decomb] == 2)
3338 /* Run old deinterlacer fd by default */
3339 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3340 hb_list_add( job->filters, &hb_filter_decomb );
3347 if ([fPictureController deinterlace] == 1)
3349 /* we add the custom string if present */
3350 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3351 hb_list_add( job->filters, &hb_filter_deinterlace );
3353 else if ([fPictureController deinterlace] == 2)
3355 /* Run old deinterlacer fd by default */
3356 hb_filter_deinterlace.settings = "-1";
3357 hb_list_add( job->filters, &hb_filter_deinterlace );
3359 else if ([fPictureController deinterlace] == 3)
3361 /* Yadif mode 0 (without spatial deinterlacing.) */
3362 hb_filter_deinterlace.settings = "2";
3363 hb_list_add( job->filters, &hb_filter_deinterlace );
3365 else if ([fPictureController deinterlace] == 4)
3367 /* Yadif (with spatial deinterlacing) */
3368 hb_filter_deinterlace.settings = "0";
3369 hb_list_add( job->filters, &hb_filter_deinterlace );
3375 if ([fPictureController denoise] == 1) // custom in popup
3377 /* we add the custom string if present */
3378 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3379 hb_list_add( job->filters, &hb_filter_denoise );
3381 else if ([fPictureController denoise] == 2) // Weak in popup
3383 hb_filter_denoise.settings = "2:1:2:3";
3384 hb_list_add( job->filters, &hb_filter_denoise );
3386 else if ([fPictureController denoise] == 3) // Medium in popup
3388 hb_filter_denoise.settings = "3:2:2:3";
3389 hb_list_add( job->filters, &hb_filter_denoise );
3391 else if ([fPictureController denoise] == 4) // Strong in popup
3393 hb_filter_denoise.settings = "7:7:5:5";
3394 hb_list_add( job->filters, &hb_filter_denoise );
3398 /* Deblock (uses pp7 default) */
3399 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3400 * the macgui's purposes a value of 0 actually means to not even use the filter
3401 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3403 if ([fPictureController deblock] != 0)
3405 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3406 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3407 hb_list_add( job->filters, &hb_filter_deblock );
3414 #pragma mark Job Handling
3420 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3421 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3422 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3423 hb_job_t * job = title->job;
3424 hb_audio_config_t * audio;
3425 /* Title Angle for dvdnav */
3426 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3428 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3430 /* Chapter selection */
3431 [self writeToActivityLog: "Start / Stop set to chapters"];
3432 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3433 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3435 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3437 /* we are pts based start / stop */
3438 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3440 /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3441 * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3443 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3444 /* get the start seconds from the start seconds field */
3445 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3446 //job->start_at_preview = start_seconds;
3447 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3448 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3449 job->pts_to_start = start_seconds * 90000LL;
3450 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3451 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3452 job->pts_to_stop = stop_seconds * 90000LL;
3454 /* A bunch of verbose activity log messages to check on what should be expected */
3455 [self writeToActivityLog: "point a to b should start at: %d seconds", start_seconds];
3456 [self writeToActivityLog: "point a to b should start at (hh:mm:ss): %d:%d:%d", start_seconds / 3600, ( start_seconds / 60 ) % 60,start_seconds % 60];
3457 [self writeToActivityLog: "point a to b duration: %d seconds", stop_seconds];
3458 [self writeToActivityLog: "point a to b duration (hh:mm:ss): %d:%d:%d", stop_seconds / 3600, ( stop_seconds / 60 ) % 60,stop_seconds % 60];
3459 [self writeToActivityLog: "point a to b should end at: %d seconds", start_seconds + stop_seconds];
3460 [self writeToActivityLog: "point a to b should end at (hh:mm:ss): %d:%d:%d", (start_seconds + stop_seconds) / 3600, ( (start_seconds + stop_seconds) / 60 ) % 60,(start_seconds + stop_seconds) % 60];
3462 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3464 /* we are frame based start / stop */
3465 [self writeToActivityLog: "Start / Stop set to frames ..."];
3467 /* Point A to Point B. Since we cannot get frame accurate start times, attempt to glean a semi-accurate start time based on a percentage of the
3468 * scanned title time as per live preview, while in some cases inaccurate its the best I can do with what I have barring a pre-scan index afaik.
3470 /* Attempt to bastardize the live preview code to get a roughly 1 second accurate point a to point b encode ... */
3471 /* get the start seconds from the start seconds field */
3472 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3473 //job->start_at_preview = start_seconds;
3474 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
3475 //job->seek_points = [[queueToApply objectForKey:@"SourceTotalSeconds"] intValue];
3476 job->frame_to_start = start_frame;
3477 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3478 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3479 job->frame_to_stop = stop_frame;
3481 /* A bunch of verbose activity log messages to check on what should be expected */
3482 [self writeToActivityLog: "point a to b should start at frame %d", start_frame];
3483 [self writeToActivityLog: "point a to b duration: %d frames", stop_frame];
3484 [self writeToActivityLog: "point a to b should end at frame %d", start_frame + stop_frame];
3490 /* Format (Muxer) and Video Encoder */
3491 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3492 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3495 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3496 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3498 job->largeFileSize = 1;
3502 job->largeFileSize = 0;
3504 /* We set http optimized mp4 here */
3505 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3507 job->mp4_optimize = 1;
3511 job->mp4_optimize = 0;
3515 /* We set the chapter marker extraction here based on the format being
3516 mpeg4 or mkv and the checkbox being checked */
3517 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3519 job->chapter_markers = 1;
3521 /* now lets get our saved chapter names out the array in the queue file
3522 * and insert them back into the title chapter list. We have it here,
3523 * because unless we are inserting chapter markers there is no need to
3524 * spend the overhead of iterating through the chapter names array imo
3525 * Also, note that if for some reason we don't apply chapter names, the
3526 * chapters just come out 001, 002, etc. etc.
3529 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3531 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3533 while (tempObject = [enumerator nextObject])
3535 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3536 if( chapter != NULL )
3538 strncpy( chapter->title, [tempObject UTF8String], 1023);
3539 chapter->title[1023] = '\0';
3546 job->chapter_markers = 0;
3549 if( job->vcodec & HB_VCODEC_X264 )
3551 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3561 /* Below Sends x264 options to the core library if x264 is selected*/
3562 /* Lets use this as per Nyx, Thanks Nyx!*/
3563 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3564 /* Turbo first pass if two pass and Turbo First pass is selected */
3565 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3567 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3568 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3569 /* append the "Turbo" string variable to the existing opts string.
3570 Note: the "Turbo" string must be appended, not prepended to work properly*/
3571 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3572 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3576 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3582 /* Picture Size Settings */
3583 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3584 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3586 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3587 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3588 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3590 /* insert our custom values here for capuj */
3591 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3592 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3594 job->anamorphic.modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3596 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3597 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3599 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3600 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3603 /* Here we use the crop values saved at the time the preset was saved */
3604 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3605 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3606 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3607 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3609 /* Video settings */
3612 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3613 * and detelecine is on, so we handle that in the logic below
3616 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3618 /* a specific framerate has been chosen */
3619 job->vrate = 27000000;
3620 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3621 /* We are not same as source so we set job->cfr to 1
3622 * to enable constant frame rate since user has specified
3623 * a specific framerate*/
3628 /* We are same as source (variable) */
3629 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3630 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3631 /* We are same as source so we set job->cfr to 0
3632 * to enable true same as source framerate */
3634 /* If we are same as source and we have detelecine on, we need to turn on
3637 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3643 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3646 Bitrate should already have been calculated and displayed
3647 in fVidBitrateField, so let's just use it same as abr*/
3648 job->vquality = -1.0;
3649 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3651 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3653 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3658 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3663 #pragma mark Process Subtitles to libhb
3665 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3666 * which means that we need to account for the offset of non source language settings in from
3667 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3668 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3669 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3670 * to the source tracks position in title->list_subtitle.
3677 bool one_burned = FALSE;
3680 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3682 while (tempObject = [enumerator nextObject])
3685 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3686 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3687 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3688 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3690 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3691 * we want to ignore it for display as well as encoding.
3695 /* if i is 0, then we are in the first item of the subtitles which we need to
3696 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3697 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3700 /* if we are on the first track and using "Foreign Audio Search" */
3701 if (i == 0 && subtitle == 1)
3703 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3705 job->indepth_scan = 1;
3706 if (burned == 1 || job->mux != HB_MUX_MP4)
3708 if (burned != 1 && job->mux == HB_MUX_MKV)
3710 job->select_subtitle_config.dest = PASSTHRUSUB;
3714 job->select_subtitle_config.dest = RENDERSUB;
3717 job->select_subtitle_config.force = force;
3718 job->select_subtitle_config.default_track = def;
3726 /* for the actual source tracks, we must subtract the non source entries so
3727 * that the menu index matches the source subtitle_list index for convenience */
3730 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3731 * Foreign Language Search is 1) so subtract 2 */
3732 subtitle = subtitle - 2;
3736 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3739 subtitle = subtitle - 1;
3742 /* We are setting a source subtitle so access the source subtitle info */
3743 hb_subtitle_t * subt;
3745 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3747 /* if we are getting the subtitles from an external srt file */
3748 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3750 hb_subtitle_config_t sub_config;
3752 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3754 /* we need to srncpy file name and codeset */
3755 //sub_config.src_filename = [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String];
3756 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3757 //sub_config.src_codeset = [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String];
3758 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3760 sub_config.force = 0;
3761 sub_config.dest = PASSTHRUSUB;
3762 sub_config.default_track = def;
3764 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3770 hb_subtitle_config_t sub_config = subt->config;
3772 if (!burned && job->mux == HB_MUX_MKV &&
3773 subt->format == PICTURESUB)
3775 sub_config.dest = PASSTHRUSUB;
3777 else if (!burned && job->mux == HB_MUX_MP4 &&
3778 subt->format == PICTURESUB)
3780 // Skip any non-burned vobsubs when output is mp4
3783 else if ( burned && subt->format == PICTURESUB )
3785 // Only allow one subtitle to be burned into the video
3790 sub_config.force = force;
3791 sub_config.default_track = def;
3792 hb_subtitle_add( job, &sub_config, subtitle );
3803 /* Audio tracks and mixdowns */
3804 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3805 int audiotrack_count = hb_list_count(job->list_audio);
3806 for( int i = 0; i < audiotrack_count;i++)
3808 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3809 hb_list_rem(job->list_audio, temp_audio);
3811 /* Now lets add our new tracks to the audio list here */
3812 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3814 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3815 hb_audio_config_init(audio);
3816 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3817 /* We go ahead and assign values to our audio->out.<properties> */
3818 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3819 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3820 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3821 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3822 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3823 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3825 hb_audio_add( job, audio );
3828 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3831 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3832 hb_audio_config_init(audio);
3833 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3834 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3835 /* We go ahead and assign values to our audio->out.<properties> */
3836 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3837 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3838 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3839 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3840 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3841 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3843 hb_audio_add( job, audio );
3847 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3849 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3850 hb_audio_config_init(audio);
3851 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3852 /* We go ahead and assign values to our audio->out.<properties> */
3853 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3854 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3855 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3856 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3857 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3858 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3860 hb_audio_add( job, audio );
3864 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3866 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3867 hb_audio_config_init(audio);
3868 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3869 /* We go ahead and assign values to our audio->out.<properties> */
3870 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3871 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3872 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3873 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3874 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3875 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3877 hb_audio_add( job, audio );
3883 job->filters = hb_list_init();
3885 /* Now lets call the filters if applicable.
3886 * The order of the filters is critical
3889 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3891 /* use a custom detelecine string */
3892 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3893 hb_list_add( job->filters, &hb_filter_detelecine );
3895 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3897 /* Use libhb's default values */
3898 hb_list_add( job->filters, &hb_filter_detelecine );
3901 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3904 /* we add the custom string if present */
3905 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3907 /* use a custom decomb string */
3908 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3909 hb_list_add( job->filters, &hb_filter_decomb );
3911 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3913 /* Use libhb default */
3914 hb_list_add( job->filters, &hb_filter_decomb );
3922 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3924 /* we add the custom string if present */
3925 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3926 hb_list_add( job->filters, &hb_filter_deinterlace );
3928 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3930 /* Run old deinterlacer fd by default */
3931 hb_filter_deinterlace.settings = "-1";
3932 hb_list_add( job->filters, &hb_filter_deinterlace );
3934 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3936 /* Yadif mode 0 (without spatial deinterlacing.) */
3937 hb_filter_deinterlace.settings = "2";
3938 hb_list_add( job->filters, &hb_filter_deinterlace );
3940 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3942 /* Yadif (with spatial deinterlacing) */
3943 hb_filter_deinterlace.settings = "0";
3944 hb_list_add( job->filters, &hb_filter_deinterlace );
3950 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
3952 /* we add the custom string if present */
3953 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3954 hb_list_add( job->filters, &hb_filter_denoise );
3956 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
3958 hb_filter_denoise.settings = "2:1:2:3";
3959 hb_list_add( job->filters, &hb_filter_denoise );
3961 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
3963 hb_filter_denoise.settings = "3:2:2:3";
3964 hb_list_add( job->filters, &hb_filter_denoise );
3966 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
3968 hb_filter_denoise.settings = "7:7:5:5";
3969 hb_list_add( job->filters, &hb_filter_denoise );
3973 /* Deblock (uses pp7 default) */
3974 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3975 * the macgui's purposes a value of 0 actually means to not even use the filter
3976 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3978 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3980 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3981 hb_list_add( job->filters, &hb_filter_deblock );
3983 [self writeToActivityLog: "prepareJob exiting"];
3988 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3990 - (IBAction) addToQueue: (id) sender
3992 /* We get the destination directory from the destination field here */
3993 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3994 /* We check for a valid destination here */
3995 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3997 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4004 BOOL fileExistsInQueue;
4005 fileExistsInQueue = NO;
4007 /* We check for and existing file here */
4008 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4013 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4015 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4017 while (tempObject = [enumerator nextObject])
4019 NSDictionary *thisQueueDict = tempObject;
4020 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4022 fileExistsInQueue = YES;
4028 if(fileExists == YES)
4030 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4031 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4032 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4033 NULL, NULL, [NSString stringWithFormat:
4034 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4035 [fDstFile2Field stringValue]] );
4037 else if (fileExistsInQueue == YES)
4039 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4040 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4041 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4042 NULL, NULL, [NSString stringWithFormat:
4043 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4044 [fDstFile2Field stringValue]] );
4048 [self doAddToQueue];
4052 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4053 the user if they want to overwrite an exiting movie file.
4055 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4056 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4058 if( returnCode == NSAlertAlternateReturn )
4059 [self doAddToQueue];
4062 - (void) doAddToQueue
4064 [self addQueueFileItem ];
4069 /* Rip: puts up an alert before ultimately calling doRip
4071 - (IBAction) Rip: (id) sender
4073 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4074 /* Rip or Cancel ? */
4076 hb_get_state2( fQueueEncodeLibhb, &s );
4078 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4080 [self Cancel: sender];
4084 /* We check to see if we need to warn the user that the computer will go to sleep
4085 or shut down when encoding is finished */
4086 [self remindUserOfSleepOrShutdown];
4088 // If there are pending jobs in the queue, then this is a rip the queue
4089 if (fPendingCount > 0)
4091 /* here lets start the queue with the first pending item */
4092 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4097 // Before adding jobs to the queue, check for a valid destination.
4099 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4100 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4102 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4106 /* We check for duplicate name here */
4107 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4109 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4110 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4111 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4112 NULL, NULL, [NSString stringWithFormat:
4113 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4114 [fDstFile2Field stringValue]] );
4116 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4120 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4121 otherwise, just rip the queue */
4122 if(fPendingCount == 0)
4124 [self doAddToQueue];
4127 /* go right to processing the new queue encode */
4128 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4133 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4134 want to overwrite an exiting movie file.
4136 - (void) overWriteAlertDone: (NSWindow *) sheet
4137 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4139 if( returnCode == NSAlertAlternateReturn )
4141 /* if there are no jobs in the queue, then add this one to the queue and rip
4142 otherwise, just rip the queue */
4143 if( fPendingCount == 0 )
4145 [self doAddToQueue];
4148 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4149 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4150 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4155 - (void) remindUserOfSleepOrShutdown
4157 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4159 /*Warn that computer will sleep after encoding*/
4162 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);
4163 [NSApp requestUserAttention:NSCriticalRequest];
4164 if ( reminduser == NSAlertAlternateReturn )
4166 [self showPreferencesWindow:nil];
4169 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4171 /*Warn that computer will shut down after encoding*/
4174 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);
4175 [NSApp requestUserAttention:NSCriticalRequest];
4176 if ( reminduser == NSAlertAlternateReturn )
4178 [self showPreferencesWindow:nil];
4187 /* Let libhb do the job */
4188 hb_start( fQueueEncodeLibhb );
4189 /*set the fEncodeState State */
4194 //------------------------------------------------------------------------------------
4195 // Displays an alert asking user if the want to cancel encoding of current job.
4196 // Cancel: returns immediately after posting the alert. Later, when the user
4197 // acknowledges the alert, doCancelCurrentJob is called.
4198 //------------------------------------------------------------------------------------
4199 - (IBAction)Cancel: (id)sender
4201 if (!fQueueController) return;
4203 hb_pause( fQueueEncodeLibhb );
4204 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4206 // Which window to attach the sheet to?
4207 NSWindow * docWindow;
4208 if ([sender respondsToSelector: @selector(window)])
4209 docWindow = [sender window];
4211 docWindow = fWindow;
4213 NSBeginCriticalAlertSheet(
4215 NSLocalizedString(@"Continue Encoding", nil),
4216 NSLocalizedString(@"Cancel Current and Stop", nil),
4217 NSLocalizedString(@"Cancel Current and Continue", nil),
4219 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4220 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4222 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4225 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4227 hb_resume( fQueueEncodeLibhb );
4228 if (returnCode == NSAlertOtherReturn)
4230 [self doCancelCurrentJob]; // <- this also stops libhb
4232 if (returnCode == NSAlertAlternateReturn)
4234 [self doCancelCurrentJobAndStop];
4238 //------------------------------------------------------------------------------------
4239 // Cancels and deletes the current job and stops libhb from processing the remaining
4241 //------------------------------------------------------------------------------------
4242 - (void) doCancelCurrentJob
4244 // Stop the current job. hb_stop will only cancel the current pass and then set
4245 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4246 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4247 // remaining passes of the job and then start the queue back up if there are any
4251 hb_stop( fQueueEncodeLibhb );
4253 // Delete all remaining jobs since libhb doesn't do this on its own.
4255 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4256 hb_rem( fQueueEncodeLibhb, job );
4258 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4260 // now that we've stopped the currently encoding job, lets mark it as cancelled
4261 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4262 // and as always, save it in the queue .plist...
4263 /* We save all of the Queue data here */
4264 [self saveQueueFileItem];
4265 // so now lets move to
4266 currentQueueEncodeIndex++ ;
4267 // ... and see if there are more items left in our queue
4268 int queueItems = [QueueFileArray count];
4269 /* If we still have more items in our queue, lets go to the next one */
4270 if (currentQueueEncodeIndex < queueItems)
4272 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4273 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4275 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4279 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4284 - (void) doCancelCurrentJobAndStop
4286 hb_stop( fQueueEncodeLibhb );
4288 // Delete all remaining jobs since libhb doesn't do this on its own.
4290 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4291 hb_rem( fQueueEncodeLibhb, job );
4294 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4296 // now that we've stopped the currently encoding job, lets mark it as cancelled
4297 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4298 // and as always, save it in the queue .plist...
4299 /* We save all of the Queue data here */
4300 [self saveQueueFileItem];
4301 // so now lets move to
4302 currentQueueEncodeIndex++ ;
4303 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4305 - (IBAction) Pause: (id) sender
4308 hb_get_state2( fQueueEncodeLibhb, &s );
4310 if( s.state == HB_STATE_PAUSED )
4312 hb_resume( fQueueEncodeLibhb );
4316 hb_pause( fQueueEncodeLibhb );
4321 #pragma mark GUI Controls Changed Methods
4323 - (IBAction) titlePopUpChanged: (id) sender
4325 hb_list_t * list = hb_get_titles( fHandle );
4326 hb_title_t * title = (hb_title_t*)
4327 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4329 /* If we are a stream type, grok the output file name from title->name upon title change */
4330 if (title->type == HB_STREAM_TYPE)
4332 /* we set the default name according to the new title->name */
4333 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4334 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4335 [NSString stringWithUTF8String: title->name],
4336 [[fDstFile2Field stringValue] pathExtension]]];
4337 /* If we have more than one title and are stream then we have a batch, change the source to read out the parent folder also */
4338 if ( hb_list_count( list ) > 1 )
4340 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4344 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4345 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4346 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4347 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4348 /* For point a to point b frame encoding, set the start and end fields to 0 and the title duration * announced fps in seconds respectively */
4349 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4350 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4351 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4353 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4354 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4356 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4357 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4358 [browsedSourceDisplayName stringByDeletingPathExtension],
4360 [[fDstFile2Field stringValue] pathExtension]]];
4362 /* Update encode start / stop variables */
4366 /* Update chapter popups */
4367 [fSrcChapterStartPopUp removeAllItems];
4368 [fSrcChapterEndPopUp removeAllItems];
4369 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4371 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4372 stringWithFormat: @"%d", i + 1]];
4373 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4374 stringWithFormat: @"%d", i + 1]];
4377 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4378 [fSrcChapterEndPopUp selectItemAtIndex:
4379 hb_list_count( title->list_chapter ) - 1];
4380 [self chapterPopUpChanged:nil];
4382 /* if using dvd nav, show the angle widget */
4383 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4385 [fSrcAngleLabel setHidden:NO];
4386 [fSrcAnglePopUp setHidden:NO];
4388 [fSrcAnglePopUp removeAllItems];
4389 for( int i = 0; i < title->angle_count; i++ )
4391 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4393 [fSrcAnglePopUp selectItemAtIndex: 0];
4397 [fSrcAngleLabel setHidden:YES];
4398 [fSrcAnglePopUp setHidden:YES];
4401 /* Start Get and set the initial pic size for display */
4402 hb_job_t * job = title->job;
4405 /* Set Auto Crop to on upon selecting a new title */
4406 [fPictureController setAutoCrop:YES];
4408 /* We get the originial output picture width and height and put them
4409 in variables for use with some presets later on */
4410 PicOrigOutputWidth = job->width;
4411 PicOrigOutputHeight = job->height;
4412 AutoCropTop = job->crop[0];
4413 AutoCropBottom = job->crop[1];
4414 AutoCropLeft = job->crop[2];
4415 AutoCropRight = job->crop[3];
4417 /* Reset the new title in fPictureController && fPreviewController*/
4418 [fPictureController SetTitle:title];
4421 /* Update Subtitle Table */
4422 [fSubtitlesDelegate resetWithTitle:title];
4423 [fSubtitlesTable reloadData];
4426 /* Update chapter table */
4427 [fChapterTitlesDelegate resetWithTitle:title];
4428 [fChapterTable reloadData];
4430 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4431 int audiotrack_count = hb_list_count(job->list_audio);
4432 for( int i = 0; i < audiotrack_count;i++)
4434 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4435 hb_list_rem(job->list_audio, temp_audio);
4438 /* Update audio popups */
4439 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4440 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4441 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4442 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4443 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4444 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4445 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4446 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4447 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4448 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4450 /* changing the title may have changed the audio channels on offer, */
4451 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4452 [self audioTrackPopUpChanged: fAudLang1PopUp];
4453 [self audioTrackPopUpChanged: fAudLang2PopUp];
4454 [self audioTrackPopUpChanged: fAudLang3PopUp];
4455 [self audioTrackPopUpChanged: fAudLang4PopUp];
4457 [fVidRatePopUp selectItemAtIndex: 0];
4459 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4460 [self calculatePictureSizing:nil];
4462 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4463 [self selectPreset:nil];
4466 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4468 if( [fEncodeStartStopPopUp isEnabled] )
4470 /* We are chapters */
4471 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4473 [fSrcChapterStartPopUp setHidden: NO];
4474 [fSrcChapterEndPopUp setHidden: NO];
4476 [fSrcTimeStartEncodingField setHidden: YES];
4477 [fSrcTimeEndEncodingField setHidden: YES];
4479 [fSrcFrameStartEncodingField setHidden: YES];
4480 [fSrcFrameEndEncodingField setHidden: YES];
4482 [self chapterPopUpChanged:nil];
4484 /* We are time based (seconds) */
4485 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4487 [fSrcChapterStartPopUp setHidden: YES];
4488 [fSrcChapterEndPopUp setHidden: YES];
4490 [fSrcTimeStartEncodingField setHidden: NO];
4491 [fSrcTimeEndEncodingField setHidden: NO];
4493 [fSrcFrameStartEncodingField setHidden: YES];
4494 [fSrcFrameEndEncodingField setHidden: YES];
4496 [self startEndSecValueChanged:nil];
4498 /* We are frame based */
4499 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4501 [fSrcChapterStartPopUp setHidden: YES];
4502 [fSrcChapterEndPopUp setHidden: YES];
4504 [fSrcTimeStartEncodingField setHidden: YES];
4505 [fSrcTimeEndEncodingField setHidden: YES];
4507 [fSrcFrameStartEncodingField setHidden: NO];
4508 [fSrcFrameEndEncodingField setHidden: NO];
4510 [self startEndFrameValueChanged:nil];
4515 - (IBAction) chapterPopUpChanged: (id) sender
4518 /* If start chapter popup is greater than end chapter popup,
4519 we set the end chapter popup to the same as start chapter popup */
4520 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4522 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4526 hb_list_t * list = hb_get_titles( fHandle );
4527 hb_title_t * title = (hb_title_t *)
4528 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4530 hb_chapter_t * chapter;
4531 int64_t duration = 0;
4532 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4533 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4535 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4536 duration += chapter->duration;
4539 duration /= 90000; /* pts -> seconds */
4540 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4541 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4544 [self calculateBitrate: sender];
4546 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4548 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4549 [fCreateChapterMarkers setEnabled: NO];
4550 [fCreateChapterMarkers setState: NSOffState];
4554 [fCreateChapterMarkers setEnabled: YES];
4558 - (IBAction) startEndSecValueChanged: (id) sender
4561 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4562 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4563 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4566 //[self calculateBitrate: sender];
4570 - (IBAction) startEndFrameValueChanged: (id) sender
4572 hb_list_t * list = hb_get_titles( fHandle );
4573 hb_title_t * title = (hb_title_t*)
4574 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4576 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4577 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4578 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4581 //[self calculateBitrate: sender];
4585 - (IBAction) formatPopUpChanged: (id) sender
4587 NSString * string = [fDstFile2Field stringValue];
4588 int format = [fDstFormatPopUp indexOfSelectedItem];
4590 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4591 [fDstMp4LargeFileCheck setHidden: YES];
4592 [fDstMp4HttpOptFileCheck setHidden: YES];
4593 [fDstMp4iPodFileCheck setHidden: YES];
4595 /* Update the Video Codec PopUp */
4596 /* lets get the tag of the currently selected item first so we might reset it later */
4597 int selectedVidEncoderTag;
4598 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4600 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4601 [fVidEncoderPopUp removeAllItems];
4602 NSMenuItem *menuItem;
4603 /* These video encoders are available to all of our current muxers, so lets list them once here */
4604 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4605 [menuItem setTag: HB_VCODEC_FFMPEG];
4610 /*Get Default MP4 File Extension*/
4611 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4619 /* Add additional video encoders here */
4620 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4621 [menuItem setTag: HB_VCODEC_X264];
4622 /* We show the mp4 option checkboxes here since we are mp4 */
4623 [fCreateChapterMarkers setEnabled: YES];
4624 [fDstMp4LargeFileCheck setHidden: NO];
4625 [fDstMp4HttpOptFileCheck setHidden: NO];
4626 [fDstMp4iPodFileCheck setHidden: NO];
4631 /* Add additional video encoders here */
4632 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4633 [menuItem setTag: HB_VCODEC_X264];
4634 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4635 [menuItem setTag: HB_VCODEC_THEORA];
4636 /* We enable the create chapters checkbox here */
4637 [fCreateChapterMarkers setEnabled: YES];
4642 /* tell fSubtitlesDelegate we have a new video container */
4644 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4645 [fSubtitlesTable reloadData];
4646 /* if we have a previously selected vid encoder tag, then try to select it */
4647 if (selectedVidEncoderTag)
4649 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4653 [fVidEncoderPopUp selectItemAtIndex: 0];
4656 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4657 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4658 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4659 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4662 [self autoSetM4vExtension: sender];
4664 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4666 if( SuccessfulScan )
4668 /* Add/replace to the correct extension */
4669 [self audioTrackPopUpChanged: fAudLang1PopUp];
4670 [self audioTrackPopUpChanged: fAudLang2PopUp];
4671 [self audioTrackPopUpChanged: fAudLang3PopUp];
4672 [self audioTrackPopUpChanged: fAudLang4PopUp];
4674 if( [fVidEncoderPopUp selectedItem] == nil )
4677 [fVidEncoderPopUp selectItemAtIndex:0];
4678 [self videoEncoderPopUpChanged:nil];
4680 /* changing the format may mean that we can / can't offer mono or 6ch, */
4681 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4683 /* We call the method to properly enable/disable turbo 2 pass */
4684 [self twoPassCheckboxChanged: sender];
4685 /* We call method method to change UI to reflect whether a preset is used or not*/
4688 [self customSettingUsed: sender];
4691 - (IBAction) autoSetM4vExtension: (id) sender
4693 if ( [fDstFormatPopUp indexOfSelectedItem] )
4696 NSString * extension = @"mp4";
4698 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4699 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4700 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4701 [fCreateChapterMarkers state] == NSOnState ||
4702 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4707 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4710 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4711 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4714 /* Method to determine if we should change the UI
4715 To reflect whether or not a Preset is being used or if
4716 the user is using "Custom" settings by determining the sender*/
4717 - (IBAction) customSettingUsed: (id) sender
4719 if ([sender stringValue])
4721 /* Deselect the currently selected Preset if there is one*/
4722 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4723 /* Change UI to show "Custom" settings are being used */
4724 [fPresetSelectedDisplay setStringValue: @"Custom"];
4726 curUserPresetChosenNum = nil;
4728 [self calculateBitrate:nil];
4733 #pragma mark - Video
4735 - (IBAction) videoEncoderPopUpChanged: (id) sender
4737 hb_job_t * job = fTitle->job;
4738 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4740 [fAdvancedOptions setHidden:YES];
4741 /* If we are using x264 then show the x264 advanced panel*/
4742 if (videoEncoder == HB_VCODEC_X264)
4744 [fAdvancedOptions setHidden:NO];
4745 [self autoSetM4vExtension: sender];
4748 if (videoEncoder == HB_VCODEC_FFMPEG)
4750 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4751 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4752 anything other than MP4.
4754 [fDstMp4iPodFileCheck setEnabled: NO];
4755 [fDstMp4iPodFileCheck setState: NSOffState];
4759 [fDstMp4iPodFileCheck setEnabled: YES];
4761 [self setupQualitySlider];
4762 [self calculatePictureSizing: sender];
4763 [self twoPassCheckboxChanged: sender];
4767 - (IBAction) twoPassCheckboxChanged: (id) sender
4769 /* check to see if x264 is chosen */
4770 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4772 if( [fVidTwoPassCheck state] == NSOnState)
4774 [fVidTurboPassCheck setHidden: NO];
4778 [fVidTurboPassCheck setHidden: YES];
4779 [fVidTurboPassCheck setState: NSOffState];
4781 /* Make sure Two Pass is checked if Turbo is checked */
4782 if( [fVidTurboPassCheck state] == NSOnState)
4784 [fVidTwoPassCheck setState: NSOnState];
4789 [fVidTurboPassCheck setHidden: YES];
4790 [fVidTurboPassCheck setState: NSOffState];
4793 /* We call method method to change UI to reflect whether a preset is used or not*/
4794 [self customSettingUsed: sender];
4797 - (IBAction ) videoFrameRateChanged: (id) sender
4799 /* We call method method to calculatePictureSizing to error check detelecine*/
4800 [self calculatePictureSizing: sender];
4802 /* We call method method to change UI to reflect whether a preset is used or not*/
4803 [self customSettingUsed: sender];
4805 - (IBAction) videoMatrixChanged: (id) sender;
4807 bool target, bitrate, quality;
4809 target = bitrate = quality = false;
4810 if( [fVidQualityMatrix isEnabled] )
4812 switch( [fVidQualityMatrix selectedRow] )
4825 [fVidTargetSizeField setEnabled: target];
4826 [fVidBitrateField setEnabled: bitrate];
4827 [fVidQualitySlider setEnabled: quality];
4828 [fVidQualityRFField setEnabled: quality];
4829 [fVidQualityRFLabel setEnabled: quality];
4830 [fVidTwoPassCheck setEnabled: !quality &&
4831 [fVidQualityMatrix isEnabled]];
4834 [fVidTwoPassCheck setState: NSOffState];
4835 [fVidTurboPassCheck setHidden: YES];
4836 [fVidTurboPassCheck setState: NSOffState];
4839 [self qualitySliderChanged: sender];
4840 [self calculateBitrate: sender];
4841 [self customSettingUsed: sender];
4844 /* Use this method to setup the quality slider for cq/rf values depending on
4845 * the video encoder selected.
4847 - (void) setupQualitySlider
4849 /* Get the current slider maxValue to check for a change in slider scale later
4850 * so that we can choose a new similar value on the new slider scale */
4851 float previousMaxValue = [fVidQualitySlider maxValue];
4852 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4853 NSString * qpRFLabelString = @"QP:";
4855 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4857 [fVidQualitySlider setMinValue:0.0];
4858 [fVidQualitySlider setMaxValue:51.0];
4859 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4860 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4861 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4862 qpRFLabelString = @"RF:";
4865 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
4867 [fVidQualitySlider setMinValue:1.0];
4868 [fVidQualitySlider setMaxValue:31.0];
4869 [fVidQualitySlider setNumberOfTickMarks:31];
4872 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4874 [fVidQualitySlider setMinValue:0.0];
4875 [fVidQualitySlider setMaxValue:63.0];
4876 [fVidQualitySlider setNumberOfTickMarks:64];
4878 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4880 /* check to see if we have changed slider scales */
4881 if (previousMaxValue != [fVidQualitySlider maxValue])
4883 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4884 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4885 [fVidQualitySlider setFloatValue:rf];
4888 [self qualitySliderChanged:nil];
4891 - (IBAction) qualitySliderChanged: (id) sender
4893 /* Our constant quality slider is in a range based
4894 * on each encoders qp/rf values. The range depends
4895 * on the encoder. Also, the range is inverse of quality
4896 * for all of the encoders *except* for theora
4897 * (ie. as the "quality" goes up, the cq or rf value
4898 * actually goes down). Since the IB sliders always set
4899 * their max value at the right end of the slider, we
4900 * will calculate the inverse, so as the slider floatValue
4901 * goes up, we will show the inverse in the rf field
4902 * so, the floatValue at the right for x264 would be 51
4903 * and our rf field needs to show 0 and vice versa.
4906 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4907 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4908 float sliderRfToPercent;
4909 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4911 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4912 sliderRfToPercent = [fVidQualityRFField floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4916 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4917 sliderRfToPercent = ( ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) - ([fVidQualityRFField floatValue] - [fVidQualitySlider minValue])) / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]);
4919 [fVidConstantCell setTitle: [NSString stringWithFormat:
4920 NSLocalizedString( @"Constant quality: %.2f %%", @"" ), 100 * sliderRfToPercent]];
4922 [self customSettingUsed: sender];
4925 - (void) controlTextDidChange: (NSNotification *) notification
4927 [self calculateBitrate:nil];
4930 - (IBAction) calculateBitrate: (id) sender
4932 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4937 hb_list_t * list = hb_get_titles( fHandle );
4938 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4939 [fSrcTitlePopUp indexOfSelectedItem] );
4940 hb_job_t * job = title->job;
4941 hb_audio_config_t * audio;
4942 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4943 * Target Size Field, we also need the job info for the Muxer, the Chapters
4944 * as well as all of the audio track info.
4945 * This used to be accomplished by simply calling prepareJob here, however
4946 * since the resilient queue sets the queue array values instead of the job
4947 * values directly, we duplicate the old prepareJob code here for the variables
4950 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4951 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4952 job->mux = [[fDstFormatPopUp selectedItem] tag];
4954 /* Audio goes here */
4955 int audiotrack_count = hb_list_count(job->list_audio);
4956 for( int i = 0; i < audiotrack_count;i++)
4958 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4959 hb_list_rem(job->list_audio, temp_audio);
4961 /* Now we need our audio info here for each track if applicable */
4962 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4964 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4965 hb_audio_config_init(audio);
4966 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4967 /* We go ahead and assign values to our audio->out.<properties> */
4968 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4969 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4970 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4971 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4972 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4973 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4975 hb_audio_add( job, audio );
4978 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4980 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4981 hb_audio_config_init(audio);
4982 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4983 /* We go ahead and assign values to our audio->out.<properties> */
4984 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4985 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4986 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4987 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4988 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4989 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4991 hb_audio_add( job, audio );
4996 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4998 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4999 hb_audio_config_init(audio);
5000 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5001 /* We go ahead and assign values to our audio->out.<properties> */
5002 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5003 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5004 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5005 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5006 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5007 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5009 hb_audio_add( job, audio );
5014 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5016 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5017 hb_audio_config_init(audio);
5018 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5019 /* We go ahead and assign values to our audio->out.<properties> */
5020 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5021 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5022 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5023 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5024 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5025 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5027 hb_audio_add( job, audio );
5032 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5036 #pragma mark - Picture
5038 /* lets set the picture size back to the max from right after title scan
5039 Lets use an IBAction here as down the road we could always use a checkbox
5040 in the gui to easily take the user back to max. Remember, the compiler
5041 resolves IBActions down to -(void) during compile anyway */
5042 - (IBAction) revertPictureSizeToMax: (id) sender
5044 hb_job_t * job = fTitle->job;
5045 /* Here we apply the title source and height */
5046 job->width = fTitle->width;
5047 job->height = fTitle->height;
5049 [self calculatePictureSizing: sender];
5050 /* We call method to change UI to reflect whether a preset is used or not*/
5051 [self customSettingUsed: sender];
5055 * Registers changes made in the Picture Settings Window.
5058 - (void)pictureSettingsDidChange
5060 [self calculatePictureSizing:nil];
5063 /* Get and Display Current Pic Settings in main window */
5064 - (IBAction) calculatePictureSizing: (id) sender
5066 if (fTitle->job->anamorphic.mode > 0)
5068 fTitle->job->keep_ratio = 0;
5071 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5073 NSString *picCropping;
5074 /* Set the display field for crop as per boolean */
5075 if (![fPictureController autoCrop])
5077 picCropping = @"Custom";
5081 picCropping = @"Auto";
5083 picCropping = [picCropping stringByAppendingString:[NSString stringWithFormat:@" %d/%d/%d/%d",fTitle->job->crop[0],fTitle->job->crop[1],fTitle->job->crop[2],fTitle->job->crop[3]]];
5085 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5087 NSString *videoFilters;
5090 if ([fPictureController detelecine] == 2)
5092 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5094 else if ([fPictureController detelecine] == 1)
5096 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5100 if ([fPictureController useDecomb] == 1)
5103 if ([fPictureController decomb] == 2)
5105 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5107 else if ([fPictureController decomb] == 1)
5109 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5115 if ([fPictureController deinterlace] > 0)
5117 fTitle->job->deinterlace = 1;
5121 fTitle->job->deinterlace = 0;
5124 if ([fPictureController deinterlace] == 2)
5126 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5128 else if ([fPictureController deinterlace] == 3)
5130 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5132 else if ([fPictureController deinterlace] == 4)
5134 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5136 else if ([fPictureController deinterlace] == 1)
5138 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5144 if ([fPictureController denoise] == 2)
5146 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5148 else if ([fPictureController denoise] == 3)
5150 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5152 else if ([fPictureController denoise] == 4)
5154 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5156 else if ([fPictureController denoise] == 1)
5158 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5162 if ([fPictureController deblock] > 0)
5164 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5168 if ([fPictureController grayscale])
5170 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5172 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5174 //[fPictureController reloadStillPreview];
5179 #pragma mark - Audio and Subtitles
5180 - (IBAction) audioCodecsPopUpChanged: (id) sender
5183 NSPopUpButton * audiotrackPopUp;
5184 NSPopUpButton * sampleratePopUp;
5185 NSPopUpButton * bitratePopUp;
5186 NSPopUpButton * audiocodecPopUp;
5187 if (sender == fAudTrack1CodecPopUp)
5189 audiotrackPopUp = fAudLang1PopUp;
5190 audiocodecPopUp = fAudTrack1CodecPopUp;
5191 sampleratePopUp = fAudTrack1RatePopUp;
5192 bitratePopUp = fAudTrack1BitratePopUp;
5194 else if (sender == fAudTrack2CodecPopUp)
5196 audiotrackPopUp = fAudLang2PopUp;
5197 audiocodecPopUp = fAudTrack2CodecPopUp;
5198 sampleratePopUp = fAudTrack2RatePopUp;
5199 bitratePopUp = fAudTrack2BitratePopUp;
5201 else if (sender == fAudTrack3CodecPopUp)
5203 audiotrackPopUp = fAudLang3PopUp;
5204 audiocodecPopUp = fAudTrack3CodecPopUp;
5205 sampleratePopUp = fAudTrack3RatePopUp;
5206 bitratePopUp = fAudTrack3BitratePopUp;
5210 audiotrackPopUp = fAudLang4PopUp;
5211 audiocodecPopUp = fAudTrack4CodecPopUp;
5212 sampleratePopUp = fAudTrack4RatePopUp;
5213 bitratePopUp = fAudTrack4BitratePopUp;
5216 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5217 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5218 [self audioTrackPopUpChanged: audiotrackPopUp];
5222 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5224 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5225 * the settings of the source audio for that track. We leave the samplerate and bitrate
5226 * to audiotrackMixdownChanged
5229 /* We will first verify that a lower track number has been selected before enabling each track
5230 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5232 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5234 [fAudLang2PopUp setEnabled: NO];
5235 [fAudLang2PopUp selectItemAtIndex: 0];
5239 [fAudLang2PopUp setEnabled: YES];
5242 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5244 [fAudLang3PopUp setEnabled: NO];
5245 [fAudLang3PopUp selectItemAtIndex: 0];
5249 [fAudLang3PopUp setEnabled: YES];
5251 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5253 [fAudLang4PopUp setEnabled: NO];
5254 [fAudLang4PopUp selectItemAtIndex: 0];
5258 [fAudLang4PopUp setEnabled: YES];
5260 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5261 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5262 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5263 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5264 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5265 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5266 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5267 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5269 [fAudTrack1CodecPopUp removeAllItems];
5270 [fAudTrack1MixPopUp removeAllItems];
5271 [fAudTrack1RatePopUp removeAllItems];
5272 [fAudTrack1BitratePopUp removeAllItems];
5273 [fAudTrack1DrcSlider setFloatValue: 0.00];
5274 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5276 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5278 [fAudTrack1RatePopUp setEnabled: NO];
5279 [fAudTrack1BitratePopUp setEnabled: NO];
5280 [fAudTrack1DrcSlider setEnabled: NO];
5281 [fAudTrack1DrcField setEnabled: NO];
5284 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5285 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5286 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5287 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5288 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5289 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5290 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5291 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5293 [fAudTrack2CodecPopUp removeAllItems];
5294 [fAudTrack2MixPopUp removeAllItems];
5295 [fAudTrack2RatePopUp removeAllItems];
5296 [fAudTrack2BitratePopUp removeAllItems];
5297 [fAudTrack2DrcSlider setFloatValue: 0.00];
5298 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5300 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5302 [fAudTrack2RatePopUp setEnabled: NO];
5303 [fAudTrack2BitratePopUp setEnabled: NO];
5304 [fAudTrack2DrcSlider setEnabled: NO];
5305 [fAudTrack2DrcField setEnabled: NO];
5308 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5309 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5310 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5311 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5312 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5313 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5314 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5315 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5317 [fAudTrack3CodecPopUp removeAllItems];
5318 [fAudTrack3MixPopUp removeAllItems];
5319 [fAudTrack3RatePopUp removeAllItems];
5320 [fAudTrack3BitratePopUp removeAllItems];
5321 [fAudTrack3DrcSlider setFloatValue: 0.00];
5322 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5324 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5326 [fAudTrack3RatePopUp setEnabled: NO];
5327 [fAudTrack3BitratePopUp setEnabled: NO];
5328 [fAudTrack3DrcSlider setEnabled: NO];
5329 [fAudTrack3DrcField setEnabled: NO];
5332 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5333 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5334 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5335 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5336 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5337 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5338 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5339 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5341 [fAudTrack4CodecPopUp removeAllItems];
5342 [fAudTrack4MixPopUp removeAllItems];
5343 [fAudTrack4RatePopUp removeAllItems];
5344 [fAudTrack4BitratePopUp removeAllItems];
5345 [fAudTrack4DrcSlider setFloatValue: 0.00];
5346 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5348 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5350 [fAudTrack4RatePopUp setEnabled: NO];
5351 [fAudTrack4BitratePopUp setEnabled: NO];
5352 [fAudTrack4DrcSlider setEnabled: NO];
5353 [fAudTrack4DrcField setEnabled: NO];
5358 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5361 hb_list_t * list = hb_get_titles( fHandle );
5362 hb_title_t * title = (hb_title_t*)
5363 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5365 hb_audio_config_t * audio;
5367 [sender removeAllItems];
5368 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5369 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5371 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5372 [[sender menu] addItemWithTitle:
5373 [NSString stringWithUTF8String: audio->lang.description]
5374 action: NULL keyEquivalent: @""];
5376 [sender selectItemAtIndex: 0];
5380 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5383 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5384 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5385 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5386 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5388 if (searchPrefixString)
5391 for( int i = 0; i < [sender numberOfItems]; i++ )
5393 /* Try to find the desired search string */
5394 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5396 [sender selectItemAtIndex: i];
5400 /* couldn't find the string, so select the requested "search string not found" item */
5401 /* index of 0 means select the "none" item */
5402 /* index of 1 means select the first audio track */
5403 [sender selectItemAtIndex: selectIndexIfNotFound];
5407 /* if no search string is provided, then select the selectIndexIfNotFound item */
5408 [sender selectItemAtIndex: selectIndexIfNotFound];
5412 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5414 int format = [fDstFormatPopUp indexOfSelectedItem];
5416 /* setup pointers to the appropriate popups for the correct track */
5417 NSPopUpButton * audiocodecPopUp;
5418 NSPopUpButton * audiotrackPopUp;
5419 if (sender == fAudTrack1CodecPopUp)
5421 audiotrackPopUp = fAudLang1PopUp;
5422 audiocodecPopUp = fAudTrack1CodecPopUp;
5424 else if (sender == fAudTrack2CodecPopUp)
5426 audiotrackPopUp = fAudLang2PopUp;
5427 audiocodecPopUp = fAudTrack2CodecPopUp;
5429 else if (sender == fAudTrack3CodecPopUp)
5431 audiotrackPopUp = fAudLang3PopUp;
5432 audiocodecPopUp = fAudTrack3CodecPopUp;
5436 audiotrackPopUp = fAudLang4PopUp;
5437 audiocodecPopUp = fAudTrack4CodecPopUp;
5440 [audiocodecPopUp removeAllItems];
5441 /* Make sure "None" isnt selected in the source track */
5442 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5444 [audiocodecPopUp setEnabled:YES];
5445 NSMenuItem *menuItem;
5446 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5452 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5453 [menuItem setTag: HB_ACODEC_FAAC];
5456 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5457 [menuItem setTag: HB_ACODEC_CA_AAC];
5460 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5461 [menuItem setTag: HB_ACODEC_AC3];
5467 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5468 [menuItem setTag: HB_ACODEC_FAAC];
5470 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5471 [menuItem setTag: HB_ACODEC_CA_AAC];
5473 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5474 [menuItem setTag: HB_ACODEC_AC3];
5476 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5477 [menuItem setTag: HB_ACODEC_DCA];
5479 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5480 [menuItem setTag: HB_ACODEC_LAME];
5482 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5483 [menuItem setTag: HB_ACODEC_VORBIS];
5489 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5490 [menuItem setTag: HB_ACODEC_LAME];
5492 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5493 [menuItem setTag: HB_ACODEC_AC3];
5499 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5500 [menuItem setTag: HB_ACODEC_VORBIS];
5502 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5503 [menuItem setTag: HB_ACODEC_LAME];
5506 [audiocodecPopUp selectItemAtIndex:0];
5510 [audiocodecPopUp setEnabled:NO];
5514 - (IBAction) audioTrackPopUpChanged: (id) sender
5516 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5517 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5520 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5523 /* make sure we have a selected title before continuing */
5524 if (fTitle == NULL) return;
5525 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5526 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5528 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5530 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5532 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5534 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5536 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5538 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5540 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5542 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5545 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5546 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5548 sender = fAudLang1PopUp;
5550 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5552 sender = fAudLang2PopUp;
5554 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5556 sender = fAudLang3PopUp;
5558 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5560 sender = fAudLang4PopUp;
5563 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5564 NSPopUpButton * mixdownPopUp;
5565 NSPopUpButton * audiocodecPopUp;
5566 NSPopUpButton * sampleratePopUp;
5567 NSPopUpButton * bitratePopUp;
5568 if (sender == fAudLang1PopUp)
5570 mixdownPopUp = fAudTrack1MixPopUp;
5571 audiocodecPopUp = fAudTrack1CodecPopUp;
5572 sampleratePopUp = fAudTrack1RatePopUp;
5573 bitratePopUp = fAudTrack1BitratePopUp;
5575 else if (sender == fAudLang2PopUp)
5577 mixdownPopUp = fAudTrack2MixPopUp;
5578 audiocodecPopUp = fAudTrack2CodecPopUp;
5579 sampleratePopUp = fAudTrack2RatePopUp;
5580 bitratePopUp = fAudTrack2BitratePopUp;
5582 else if (sender == fAudLang3PopUp)
5584 mixdownPopUp = fAudTrack3MixPopUp;
5585 audiocodecPopUp = fAudTrack3CodecPopUp;
5586 sampleratePopUp = fAudTrack3RatePopUp;
5587 bitratePopUp = fAudTrack3BitratePopUp;
5591 mixdownPopUp = fAudTrack4MixPopUp;
5592 audiocodecPopUp = fAudTrack4CodecPopUp;
5593 sampleratePopUp = fAudTrack4RatePopUp;
5594 bitratePopUp = fAudTrack4BitratePopUp;
5597 /* get the index of the selected audio Track*/
5598 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5600 /* pointer for the hb_audio_s struct we will use later on */
5601 hb_audio_config_t * audio;
5604 /* check if the audio mixdown controls need their enabled state changing */
5605 [self setEnabledStateOfAudioMixdownControls:nil];
5607 if (thisAudioIndex != -1)
5611 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5613 /* actually manipulate the proper mixdowns here */
5614 /* delete the previous audio mixdown options */
5615 [mixdownPopUp removeAllItems];
5617 acodec = [[audiocodecPopUp selectedItem] tag];
5622 /* find out if our selected output audio codec supports mono and / or 6ch */
5623 /* we also check for an input codec of AC3 or DCA,
5624 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
5625 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5626 but this may change in the future, so they are separated for flexibility */
5627 int audioCodecsSupportMono =
5628 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5629 (acodec != HB_ACODEC_LAME);
5630 int audioCodecsSupport6Ch =
5631 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
5632 (acodec != HB_ACODEC_LAME);
5634 /* check for AC-3 passthru */
5635 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5638 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5639 [NSString stringWithUTF8String: "AC3 Passthru"]
5640 action: NULL keyEquivalent: @""];
5641 [menuItem setTag: HB_ACODEC_AC3];
5643 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5645 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5646 [NSString stringWithUTF8String: "DTS Passthru"]
5647 action: NULL keyEquivalent: @""];
5648 [menuItem setTag: HB_ACODEC_DCA];
5653 /* add the appropriate audio mixdown menuitems to the popupbutton */
5654 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5655 so that we can reference the mixdown later */
5657 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5658 int minMixdownUsed = 0;
5659 int maxMixdownUsed = 0;
5661 /* get the input channel layout without any lfe channels */
5662 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5664 /* do we want to add a mono option? */
5665 if (audioCodecsSupportMono == 1)
5667 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5668 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5669 action: NULL keyEquivalent: @""];
5670 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5671 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5672 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5675 /* do we want to add a stereo option? */
5676 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5677 /* also offer stereo if we have a stereo-or-better source */
5678 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5680 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5681 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5682 action: NULL keyEquivalent: @""];
5683 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5684 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5685 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5688 /* do we want to add a dolby surround (DPL1) option? */
5689 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5691 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5692 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5693 action: NULL keyEquivalent: @""];
5694 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5695 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5696 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5699 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5700 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5702 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5703 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5704 action: NULL keyEquivalent: @""];
5705 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5706 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5707 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5710 /* do we want to add a 6-channel discrete option? */
5711 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5713 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5714 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5715 action: NULL keyEquivalent: @""];
5716 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5717 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5718 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5721 /* do we want to add an AC-3 passthrough option? */
5722 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5724 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5725 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5726 action: NULL keyEquivalent: @""];
5727 [menuItem setTag: HB_ACODEC_AC3];
5728 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5729 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5732 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5733 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5735 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5736 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5737 action: NULL keyEquivalent: @""];
5738 [menuItem setTag: HB_ACODEC_DCA];
5739 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5740 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5743 /* auto-select the best mixdown based on our saved mixdown preference */
5745 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5746 /* ultimately this should be a prefs option */
5749 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5750 if (mixdownToUse > 0)
5752 useMixdown = mixdownToUse;
5756 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5759 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5760 if (useMixdown > maxMixdownUsed)
5762 useMixdown = maxMixdownUsed;
5765 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5766 if (useMixdown < minMixdownUsed)
5768 useMixdown = minMixdownUsed;
5771 /* select the (possibly-amended) preferred mixdown */
5772 [mixdownPopUp selectItemWithTag: useMixdown];
5775 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5776 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5779 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5781 /* If we are using the avi container, we select MP3 as there is no aac available*/
5782 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5784 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5788 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5792 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5793 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
5796 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5798 /* If we are using the avi container, we select MP3 as there is no aac available*/
5799 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
5801 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
5805 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
5809 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5810 [self audioTrackMixdownChanged: mixdownPopUp];
5814 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5816 [self autoSetM4vExtension: sender];
5820 - (IBAction) audioTrackMixdownChanged: (id) sender
5824 /* setup pointers to all of the other audio track controls
5825 * we will need later
5827 NSPopUpButton * mixdownPopUp;
5828 NSPopUpButton * sampleratePopUp;
5829 NSPopUpButton * bitratePopUp;
5830 NSPopUpButton * audiocodecPopUp;
5831 NSPopUpButton * audiotrackPopUp;
5832 NSSlider * drcSlider;
5833 NSTextField * drcField;
5834 if (sender == fAudTrack1MixPopUp)
5836 audiotrackPopUp = fAudLang1PopUp;
5837 audiocodecPopUp = fAudTrack1CodecPopUp;
5838 mixdownPopUp = fAudTrack1MixPopUp;
5839 sampleratePopUp = fAudTrack1RatePopUp;
5840 bitratePopUp = fAudTrack1BitratePopUp;
5841 drcSlider = fAudTrack1DrcSlider;
5842 drcField = fAudTrack1DrcField;
5844 else if (sender == fAudTrack2MixPopUp)
5846 audiotrackPopUp = fAudLang2PopUp;
5847 audiocodecPopUp = fAudTrack2CodecPopUp;
5848 mixdownPopUp = fAudTrack2MixPopUp;
5849 sampleratePopUp = fAudTrack2RatePopUp;
5850 bitratePopUp = fAudTrack2BitratePopUp;
5851 drcSlider = fAudTrack2DrcSlider;
5852 drcField = fAudTrack2DrcField;
5854 else if (sender == fAudTrack3MixPopUp)
5856 audiotrackPopUp = fAudLang3PopUp;
5857 audiocodecPopUp = fAudTrack3CodecPopUp;
5858 mixdownPopUp = fAudTrack3MixPopUp;
5859 sampleratePopUp = fAudTrack3RatePopUp;
5860 bitratePopUp = fAudTrack3BitratePopUp;
5861 drcSlider = fAudTrack3DrcSlider;
5862 drcField = fAudTrack3DrcField;
5866 audiotrackPopUp = fAudLang4PopUp;
5867 audiocodecPopUp = fAudTrack4CodecPopUp;
5868 mixdownPopUp = fAudTrack4MixPopUp;
5869 sampleratePopUp = fAudTrack4RatePopUp;
5870 bitratePopUp = fAudTrack4BitratePopUp;
5871 drcSlider = fAudTrack4DrcSlider;
5872 drcField = fAudTrack4DrcField;
5874 acodec = [[audiocodecPopUp selectedItem] tag];
5875 /* storage variable for the min and max bitrate allowed for this codec */
5881 case HB_ACODEC_FAAC:
5882 /* check if we have a 6ch discrete conversion in either audio track */
5883 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5885 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5887 /* If either mixdown popup includes 6-channel discrete, then allow up to 448 kbps */
5893 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5895 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
5896 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5901 case HB_ACODEC_CA_AAC:
5902 /* check if we have a 6ch discrete conversion in either audio track */
5903 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5916 case HB_ACODEC_LAME:
5917 /* Lame is happy using our min bitrate of 32 kbps */
5919 /* Lame won't encode if the bitrate is higher than 320 kbps */
5923 case HB_ACODEC_VORBIS:
5924 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5926 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5928 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5934 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5936 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5942 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5948 /* make sure we have a selected title before continuing */
5949 if (fTitle == NULL) return;
5950 /* get the audio so we can find out what input rates are*/
5951 hb_audio_config_t * audio;
5952 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5953 int inputbitrate = audio->in.bitrate / 1000;
5954 int inputsamplerate = audio->in.samplerate;
5956 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
5958 [bitratePopUp removeAllItems];
5960 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5962 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5964 /* add a new menuitem for this bitrate */
5965 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5966 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
5967 action: NULL keyEquivalent: @""];
5968 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5969 [menuItem setTag: hb_audio_bitrates[i].rate];
5973 /* select the default bitrate (but use 384 for 6-ch AAC) */
5974 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5976 [bitratePopUp selectItemWithTag: 384];
5980 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5983 /* populate and set the sample rate popup */
5984 /* Audio samplerate */
5985 [sampleratePopUp removeAllItems];
5986 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5987 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5988 [menuItem setTag: inputsamplerate];
5990 for( int i = 0; i < hb_audio_rates_count; i++ )
5992 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5993 [NSString stringWithUTF8String: hb_audio_rates[i].string]
5994 action: NULL keyEquivalent: @""];
5995 [menuItem setTag: hb_audio_rates[i].rate];
5997 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5998 * and there is no compelling reason to use anything else as default, though the users default
5999 * preset will likely override any setting chosen here.
6001 [sampleratePopUp selectItemWithTag: inputsamplerate];
6004 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6005 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6006 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6008 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6011 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6012 [bitratePopUp removeAllItems];
6013 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6014 [NSString stringWithFormat:@"%d", inputbitrate]
6015 action: NULL keyEquivalent: @""];
6016 [menuItem setTag: inputbitrate];
6017 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6018 [bitratePopUp setEnabled: NO];
6019 [sampleratePopUp setEnabled: NO];
6021 [drcSlider setFloatValue: 0.00];
6022 [self audioDRCSliderChanged: drcSlider];
6023 [drcSlider setEnabled: NO];
6024 [drcField setEnabled: NO];
6028 [sampleratePopUp setEnabled: YES];
6029 [bitratePopUp setEnabled: YES];
6030 [drcSlider setEnabled: YES];
6031 [drcField setEnabled: YES];
6033 [self calculateBitrate:nil];
6036 - (IBAction) audioDRCSliderChanged: (id) sender
6038 NSSlider * drcSlider;
6039 NSTextField * drcField;
6040 if (sender == fAudTrack1DrcSlider)
6042 drcSlider = fAudTrack1DrcSlider;
6043 drcField = fAudTrack1DrcField;
6045 else if (sender == fAudTrack2DrcSlider)
6047 drcSlider = fAudTrack2DrcSlider;
6048 drcField = fAudTrack2DrcField;
6050 else if (sender == fAudTrack3DrcSlider)
6052 drcSlider = fAudTrack3DrcSlider;
6053 drcField = fAudTrack3DrcField;
6057 drcSlider = fAudTrack4DrcSlider;
6058 drcField = fAudTrack4DrcField;
6061 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6062 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6064 [drcSlider setFloatValue:1.0];
6068 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6069 /* For now, do not call this until we have an intelligent way to determine audio track selections
6070 * compared to presets
6072 //[self customSettingUsed: sender];
6077 - (IBAction) browseImportSrtFile: (id) sender
6080 NSOpenPanel * panel;
6082 panel = [NSOpenPanel openPanel];
6083 [panel setAllowsMultipleSelection: NO];
6084 [panel setCanChooseFiles: YES];
6085 [panel setCanChooseDirectories: NO ];
6086 NSString * sourceDirectory;
6087 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6089 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6093 sourceDirectory = @"~/Desktop";
6094 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6096 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6097 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6098 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6099 modalForWindow: fWindow modalDelegate: self
6100 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6101 contextInfo: sender];
6104 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6105 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6107 if( returnCode == NSOKButton )
6109 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6110 NSString *importSrtFilePath = [sheet filename];
6111 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6113 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6114 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6116 [fSubtitlesTable reloadData];
6122 #pragma mark Open New Windows
6124 - (IBAction) openHomepage: (id) sender
6126 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6127 URLWithString:@"http://handbrake.fr/"]];
6130 - (IBAction) openForums: (id) sender
6132 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6133 URLWithString:@"http://handbrake.fr/forum/"]];
6135 - (IBAction) openUserGuide: (id) sender
6137 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6138 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6142 * Shows debug output window.
6144 - (IBAction)showDebugOutputPanel:(id)sender
6146 [outputPanel showOutputPanel:sender];
6150 * Shows preferences window.
6152 - (IBAction) showPreferencesWindow: (id) sender
6154 NSWindow * window = [fPreferencesController window];
6155 if (![window isVisible])
6158 [window makeKeyAndOrderFront: nil];
6162 * Shows queue window.
6164 - (IBAction) showQueueWindow:(id)sender
6166 [fQueueController showQueueWindow:sender];
6170 - (IBAction) toggleDrawer:(id)sender {
6171 [fPresetDrawer toggle:self];
6175 * Shows Picture Settings Window.
6178 - (IBAction) showPicturePanel: (id) sender
6180 [fPictureController showPictureWindow:sender];
6183 - (void) picturePanelFullScreen
6185 [fPictureController setToFullScreenMode];
6188 - (void) picturePanelWindowed
6190 [fPictureController setToWindowedMode];
6193 - (IBAction) showPreviewWindow: (id) sender
6195 [fPictureController showPreviewWindow:sender];
6199 #pragma mark Preset Outline View Methods
6200 #pragma mark - Required
6201 /* These are required by the NSOutlineView Datasource Delegate */
6204 /* used to specify the number of levels to show for each item */
6205 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6207 /* currently use no levels to test outline view viability */
6208 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6210 return [UserPresets count];
6214 /* we need to return the count of the array in ChildrenArray for this folder */
6215 NSArray *children = nil;
6216 children = [item objectForKey:@"ChildrenArray"];
6217 if ([children count] > 0)
6219 return [children count];
6228 /* We use this to deterimine children of an item */
6229 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6232 /* we need to return the count of the array in ChildrenArray for this folder */
6233 NSArray *children = nil;
6236 children = UserPresets;
6240 if ([item objectForKey:@"ChildrenArray"])
6242 children = [item objectForKey:@"ChildrenArray"];
6245 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6251 return [children objectAtIndex:index];
6255 // We are only one level deep, so we can't be asked about children
6256 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6260 /* We use this to determine if an item should be expandable */
6261 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6264 /* we need to return the count of the array in ChildrenArray for this folder */
6265 NSArray *children= nil;
6268 children = UserPresets;
6272 if ([item objectForKey:@"ChildrenArray"])
6274 children = [item objectForKey:@"ChildrenArray"];
6278 /* To deterimine if an item should show a disclosure triangle
6279 * we could do it by the children count as so:
6280 * if ([children count] < 1)
6281 * However, lets leave the triangle show even if there are no
6282 * children to help indicate a folder, just like folder in the
6283 * finder can show a disclosure triangle even when empty
6286 /* We need to determine if the item is a folder */
6287 if ([[item objectForKey:@"Folder"] intValue] == 1)
6298 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6300 // Our outline view has no levels, but we can still expand every item. Doing so
6301 // just makes the row taller. See heightOfRowByItem below.
6302 //return ![(HBQueueOutlineView*)outlineView isDragging];
6308 /* Used to tell the outline view which information is to be displayed per item */
6309 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6311 /* We have two columns right now, icon and PresetName */
6313 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6315 return [item objectForKey:@"PresetName"];
6324 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6326 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6328 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6330 return [NSKeyedArchiver archivedDataWithRootObject:item];
6333 #pragma mark - Added Functionality (optional)
6334 /* Use to customize the font and display characteristics of the title cell */
6335 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6337 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6341 NSColor *shadowColor;
6342 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6343 /*check to see if its a selected row */
6344 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6347 fontColor = [NSColor blackColor];
6348 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6352 if ([[item objectForKey:@"Type"] intValue] == 0)
6354 fontColor = [NSColor blueColor];
6356 else // User created preset, use a black font
6358 fontColor = [NSColor blackColor];
6360 /* check to see if its a folder */
6361 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6363 //fontColor = [NSColor greenColor];
6368 /* We use Bold Text for the HB Default */
6369 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6371 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6373 /* We use Bold Text for the User Specified Default */
6374 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6376 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6380 [cell setTextColor:fontColor];
6381 [cell setFont:txtFont];
6386 /* We use this to edit the name field in the outline view */
6387 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6389 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6394 [theRecord setObject:object forKey:@"PresetName"];
6398 [fPresetsOutlineView reloadData];
6399 /* We save all of the preset data here */
6403 /* We use this to provide tooltips for the items in the presets outline view */
6404 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6406 //if ([[tc identifier] isEqualToString:@"PresetName"])
6408 /* initialize the tooltip contents variable */
6410 /* if there is a description for the preset, we show it in the tooltip */
6411 if ([item objectForKey:@"PresetDescription"])
6413 loc_tip = [item objectForKey:@"PresetDescription"];
6418 loc_tip = @"No description available";
6425 #pragma mark Preset Outline View Methods (dragging related)
6428 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6430 // Dragging is only allowed for custom presets.
6431 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6432 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6436 // Don't retain since this is just holding temporaral drag information, and it is
6437 //only used during a drag! We could put this in the pboard actually.
6438 fDraggedNodes = items;
6439 // Provide data for our custom type, and simple NSStrings.
6440 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6442 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6443 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6448 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6451 // Don't allow dropping ONTO an item since they can't really contain any children.
6453 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6454 if (isOnDropTypeProposal)
6455 return NSDragOperationNone;
6457 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6460 index = [fPresetsOutlineView rowForItem: item] + 1;
6464 // Don't allow dropping into the Built In Presets.
6465 if (index < presetCurrentBuiltInCount)
6467 return NSDragOperationNone;
6468 index = MAX (index, presetCurrentBuiltInCount);
6471 [outlineView setDropItem:item dropChildIndex:index];
6472 return NSDragOperationGeneric;
6477 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6479 /* first, lets see if we are dropping into a folder */
6480 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6482 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6483 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6484 [childrenArray addObject:item];
6485 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6486 [childrenArray autorelease];
6488 else // We are not, so we just move the preset into the existing array
6490 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6492 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6493 while (obj = [enumerator nextObject])
6495 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6497 // Successful drop, lets rearrange the view and save it all
6498 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6500 [fPresetsOutlineView reloadData];
6505 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6507 NSUInteger index = [indexSet lastIndex];
6508 NSUInteger aboveInsertIndexCount = 0;
6510 NSUInteger removeIndex;
6512 if (index >= insertIndex)
6514 removeIndex = index + aboveInsertIndexCount;
6515 aboveInsertIndexCount++;
6519 removeIndex = index;
6523 id object = [[array objectAtIndex:removeIndex] retain];
6524 [array removeObjectAtIndex:removeIndex];
6525 [array insertObject:object atIndex:insertIndex];
6528 index = [indexSet indexLessThanIndex:index];
6533 #pragma mark - Functional Preset NSOutlineView Methods
6535 - (IBAction)selectPreset:(id)sender
6538 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6540 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6541 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6543 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6545 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6549 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6553 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6554 [self formatPopUpChanged:nil];
6556 /* Chapter Markers*/
6557 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6558 /* check to see if we have only one chapter */
6559 [self chapterPopUpChanged:nil];
6561 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6562 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6563 /* Mux mp4 with http optimization */
6564 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6567 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6568 /* We set the advanced opt string here if applicable*/
6569 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6571 /* Lets run through the following functions to get variables set there */
6572 [self videoEncoderPopUpChanged:nil];
6573 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6574 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6575 [self calculateBitrate:nil];
6578 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6580 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6581 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6583 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6584 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6585 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6586 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6587 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6588 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6590 /* For the quality slider we need to convert the old percent's to the new rf scales */
6591 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6592 [fVidQualitySlider setFloatValue:rf];
6597 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6598 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6600 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6604 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6605 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6609 [self videoMatrixChanged:nil];
6611 /* Video framerate */
6612 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6613 detected framerate in the fVidRatePopUp so we use index 0*/
6614 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6616 [fVidRatePopUp selectItemAtIndex: 0];
6620 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6624 /* 2 Pass Encoding */
6625 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6626 [self twoPassCheckboxChanged:nil];
6628 /* Turbo 1st pass for 2 Pass Encoding */
6629 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6632 /* First we check to see if we are using the current audio track layout based on AudioList array */
6633 if ([chosenPreset objectForKey:@"AudioList"])
6636 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6637 NSPopUpButton * trackLangPopUp = nil;
6638 NSPopUpButton * mixdownPopUp = nil;
6639 NSPopUpButton * audiocodecPopUp = nil;
6640 NSPopUpButton * sampleratePopUp = nil;
6641 NSPopUpButton * bitratePopUp = nil;
6642 NSSlider * drcSlider = nil;
6645 /* Populate the audio widgets based on the contents of the AudioList array */
6647 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6649 while (tempObject = [enumerator nextObject])
6654 trackLangPopUp = fAudLang1PopUp;
6655 mixdownPopUp = fAudTrack1MixPopUp;
6656 audiocodecPopUp = fAudTrack1CodecPopUp;
6657 sampleratePopUp = fAudTrack1RatePopUp;
6658 bitratePopUp = fAudTrack1BitratePopUp;
6659 drcSlider = fAudTrack1DrcSlider;
6663 trackLangPopUp = fAudLang2PopUp;
6664 mixdownPopUp = fAudTrack2MixPopUp;
6665 audiocodecPopUp = fAudTrack2CodecPopUp;
6666 sampleratePopUp = fAudTrack2RatePopUp;
6667 bitratePopUp = fAudTrack2BitratePopUp;
6668 drcSlider = fAudTrack2DrcSlider;
6672 trackLangPopUp = fAudLang3PopUp;
6673 mixdownPopUp = fAudTrack3MixPopUp;
6674 audiocodecPopUp = fAudTrack3CodecPopUp;
6675 sampleratePopUp = fAudTrack3RatePopUp;
6676 bitratePopUp = fAudTrack3BitratePopUp;
6677 drcSlider = fAudTrack3DrcSlider;
6681 trackLangPopUp = fAudLang4PopUp;
6682 mixdownPopUp = fAudTrack4MixPopUp;
6683 audiocodecPopUp = fAudTrack4CodecPopUp;
6684 sampleratePopUp = fAudTrack4RatePopUp;
6685 bitratePopUp = fAudTrack4BitratePopUp;
6686 drcSlider = fAudTrack4DrcSlider;
6690 if ([trackLangPopUp indexOfSelectedItem] == 0)
6692 [trackLangPopUp selectItemAtIndex: 1];
6694 [self audioTrackPopUpChanged: trackLangPopUp];
6695 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6696 /* check our pref for core audio and use it in place of faac if applicable */
6697 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6698 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6700 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6703 [self audioTrackPopUpChanged: audiocodecPopUp];
6704 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6705 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6707 if ([mixdownPopUp selectedItem] == nil)
6709 [self audioTrackPopUpChanged: audiocodecPopUp];
6711 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6712 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6713 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6715 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6717 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6718 [self audioDRCSliderChanged: drcSlider];
6721 /* If we are any track greater than 1 check to make sure we have a matching source codec is using ac3 passthru or dts passthru,
6722 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6726 /* Check to see if the preset asks for a passhthru track (AC3 or DTS) and verify there is a matching source track if not, set the track to "None". */
6727 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6729 hb_audio_config_t * audio;
6730 /* get the audio source audio codec */
6731 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6732 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6733 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6735 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6736 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6738 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6740 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6742 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6744 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6745 [trackLangPopUp selectItemAtIndex: 0];
6746 [self audioTrackPopUpChanged: trackLangPopUp];
6752 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6756 [fAudLang4PopUp selectItemAtIndex: 0];
6757 [self audioTrackPopUpChanged: fAudLang4PopUp];
6761 [fAudLang3PopUp selectItemAtIndex: 0];
6762 [self audioTrackPopUpChanged: fAudLang3PopUp];
6766 [fAudLang2PopUp selectItemAtIndex: 0];
6767 [self audioTrackPopUpChanged: fAudLang2PopUp];
6775 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6777 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6779 [fAudLang1PopUp selectItemAtIndex: 1];
6781 [self audioTrackPopUpChanged: fAudLang1PopUp];
6782 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6783 /* check our pref for core audio and use it in place of faac if applicable */
6784 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6785 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6787 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6789 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6790 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6791 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6793 if ([fAudTrack1MixPopUp selectedItem] == nil)
6795 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6797 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6798 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6799 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6801 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6803 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6804 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6807 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6809 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6811 [fAudLang2PopUp selectItemAtIndex: 1];
6813 [self audioTrackPopUpChanged: fAudLang2PopUp];
6814 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6815 /* check our pref for core audio and use it in place of faac if applicable */
6816 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6817 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6819 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6821 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6822 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6823 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6825 if ([fAudTrack2MixPopUp selectedItem] == nil)
6827 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6829 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6830 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6831 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6833 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6835 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6836 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6838 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6840 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6842 [fAudLang3PopUp selectItemAtIndex: 1];
6844 [self audioTrackPopUpChanged: fAudLang3PopUp];
6845 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6846 /* check our pref for core audio and use it in place of faac if applicable */
6847 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6848 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6850 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6852 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6853 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6854 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6856 if ([fAudTrack3MixPopUp selectedItem] == nil)
6858 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6860 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6861 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6862 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6864 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6866 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6867 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6869 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6871 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6873 [fAudLang4PopUp selectItemAtIndex: 1];
6875 [self audioTrackPopUpChanged: fAudLang4PopUp];
6876 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6877 /* check our pref for core audio and use it in place of faac if applicable */
6878 if ([[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6879 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6881 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6883 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6884 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6885 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6887 if ([fAudTrack4MixPopUp selectedItem] == nil)
6889 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6891 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
6892 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6893 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
6895 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
6897 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
6898 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
6901 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6903 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
6905 [fAudLang2PopUp selectItemAtIndex: 0];
6906 [self audioTrackPopUpChanged: fAudLang2PopUp];
6908 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
6910 [fAudLang3PopUp selectItemAtIndex: 0];
6911 [self audioTrackPopUpChanged: fAudLang3PopUp];
6913 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
6915 [fAudLang4PopUp selectItemAtIndex: 0];
6916 [self audioTrackPopUpChanged: fAudLang4PopUp];
6921 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
6922 /* Forced Subtitles */
6923 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
6925 /* Picture Settings */
6926 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
6927 * height, width, keep ar, anamorphic and crop settings.
6928 * picture filters are handled separately below.
6930 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
6931 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
6932 * preset completely ignores any picture sizing values in the preset.
6934 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
6936 hb_job_t * job = fTitle->job;
6938 /* If Cropping is set to custom, then recall all four crop values from
6939 when the preset was created and apply them */
6940 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
6942 [fPictureController setAutoCrop:NO];
6944 /* Here we use the custom crop values saved at the time the preset was saved */
6945 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
6946 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
6947 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
6948 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
6951 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
6953 [fPictureController setAutoCrop:YES];
6954 /* Here we use the auto crop values determined right after scan */
6955 job->crop[0] = AutoCropTop;
6956 job->crop[1] = AutoCropBottom;
6957 job->crop[2] = AutoCropLeft;
6958 job->crop[3] = AutoCropRight;
6963 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
6964 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
6966 /* Use Max Picture settings for whatever the dvd is.*/
6967 [self revertPictureSizeToMax:nil];
6968 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6969 if (job->keep_ratio == 1)
6971 hb_fix_aspect( job, HB_KEEP_WIDTH );
6972 if( job->height > fTitle->height )
6974 job->height = fTitle->height;
6975 hb_fix_aspect( job, HB_KEEP_HEIGHT );
6978 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
6980 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
6982 /* we check to make sure the presets width/height does not exceed the sources width/height */
6983 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
6985 /* if so, then we use the sources height and width to avoid scaling up */
6986 //job->width = fTitle->width;
6987 //job->height = fTitle->height;
6988 [self revertPictureSizeToMax:nil];
6990 else // source width/height is >= the preset height/width
6992 /* we can go ahead and use the presets values for height and width */
6993 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
6994 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
6996 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6997 if (job->keep_ratio == 1)
6999 hb_fix_aspect( job, HB_KEEP_WIDTH );
7000 if( job->height > fTitle->height )
7002 job->height = fTitle->height;
7003 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7006 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7012 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7013 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7017 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7018 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7019 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7022 [fPictureController setUseDecomb:1];
7023 [fPictureController setDecomb:0];
7024 [fPictureController setDeinterlace:0];
7025 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7027 /* we are using decomb */
7029 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7031 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7033 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7034 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7036 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7042 /* We are using Deinterlace */
7044 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7046 [fPictureController setUseDecomb:0];
7047 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7048 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7049 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7051 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7058 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7060 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7061 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7062 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7064 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7069 [fPictureController setDetelecine:0];
7073 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7075 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7076 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7077 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7079 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7084 [fPictureController setDenoise:0];
7088 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7090 /* if its a one, then its the old on/off deblock, set on to 5*/
7091 [fPictureController setDeblock:5];
7095 /* use the settings intValue */
7096 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7099 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7101 [fPictureController setGrayscale:1];
7105 [fPictureController setGrayscale:0];
7108 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7109 [fPictureController SetTitle:fTitle];
7110 [fPictureController SetTitle:fTitle];
7111 [self calculatePictureSizing:nil];
7117 #pragma mark Manage Presets
7119 - (void) loadPresets {
7120 /* We declare the default NSFileManager into fileManager */
7121 NSFileManager * fileManager = [NSFileManager defaultManager];
7122 /*We define the location of the user presets file */
7123 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7124 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7125 /* We check for the presets.plist */
7126 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7128 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7131 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7132 if (nil == UserPresets)
7134 UserPresets = [[NSMutableArray alloc] init];
7135 [self addFactoryPresets:nil];
7137 [fPresetsOutlineView reloadData];
7139 [self checkBuiltInsForUpdates];
7142 - (void) checkBuiltInsForUpdates {
7144 BOOL updateBuiltInPresets = NO;
7146 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7148 while (tempObject = [enumerator nextObject])
7150 /* iterate through the built in presets to see if any have an old build number */
7151 NSMutableDictionary *thisPresetDict = tempObject;
7152 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7153 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7155 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7157 updateBuiltInPresets = YES;
7162 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7163 if ( updateBuiltInPresets == YES)
7165 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7167 /* Show an alert window that built in presets will be updated */
7168 /*On Screen Notification*/
7171 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7172 [NSApp requestUserAttention:NSCriticalRequest];
7174 /* when alert is dismissed, go ahead and update the built in presets */
7175 [self addFactoryPresets:nil];
7181 - (IBAction) showAddPresetPanel: (id) sender
7183 /* Deselect the currently selected Preset if there is one*/
7184 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7186 /* Populate the preset picture settings popup here */
7187 [fPresetNewPicSettingsPopUp removeAllItems];
7188 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7189 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7190 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7191 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7192 /* Uncheck the preset use filters checkbox */
7193 [fPresetNewPicFiltersCheck setState:NSOffState];
7194 // fPresetNewFolderCheck
7195 [fPresetNewFolderCheck setState:NSOffState];
7196 /* Erase info from the input fields*/
7197 [fPresetNewName setStringValue: @""];
7198 [fPresetNewDesc setStringValue: @""];
7199 /* Show the panel */
7200 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7203 - (IBAction) closeAddPresetPanel: (id) sender
7205 [NSApp endSheet: fAddPresetPanel];
7206 [fAddPresetPanel orderOut: self];
7209 - (IBAction)addUserPreset:(id)sender
7211 if (![[fPresetNewName stringValue] length])
7212 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7215 /* Here we create a custom user preset */
7216 [UserPresets addObject:[self createPreset]];
7219 [self closeAddPresetPanel:nil];
7226 /* We Reload the New Table data for presets */
7227 [fPresetsOutlineView reloadData];
7228 /* We save all of the preset data here */
7236 /* We Sort the Presets By Factory or Custom */
7237 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7238 ascending:YES] autorelease];
7239 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7241 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7242 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7243 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7246 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7247 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7248 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7249 [UserPresets setArray:sortedArray];
7254 - (IBAction)insertPreset:(id)sender
7256 int index = [fPresetsOutlineView selectedRow];
7257 [UserPresets insertObject:[self createPreset] atIndex:index];
7258 [fPresetsOutlineView reloadData];
7262 - (NSDictionary *)createPreset
7264 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7265 /* Preset build number */
7266 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7267 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7268 /* Get the New Preset Name from the field in the AddPresetPanel */
7269 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7270 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7271 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7272 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7273 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7274 /*Set whether or not this is default, at creation set to 0*/
7275 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7276 if ([fPresetNewFolderCheck state] == YES)
7278 /* initialize and set an empty array for children here since we are a new folder */
7279 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7280 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7281 [childrenArray autorelease];
7283 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7285 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7286 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7287 /* Get whether or not to use the current Picture Filter settings for the preset */
7288 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7290 /* Get New Preset Description from the field in the AddPresetPanel*/
7291 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7293 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7294 /* Chapter Markers fCreateChapterMarkers*/
7295 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7296 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7297 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7298 /* Mux mp4 with http optimization */
7299 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7300 /* Add iPod uuid atom */
7301 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7305 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7306 /* x264 Option String */
7307 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7309 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7310 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7311 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7312 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7314 /* Video framerate */
7315 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7317 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7319 else // we can record the actual titleOfSelectedItem
7321 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7324 /* 2 Pass Encoding */
7325 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7326 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7327 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7328 /*Picture Settings*/
7329 hb_job_t * job = fTitle->job;
7330 /* Picture Sizing */
7331 /* Use Max Picture settings for whatever the dvd is.*/
7332 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7333 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7334 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7335 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7336 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7338 /* Set crop settings here */
7339 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7340 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7341 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7342 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7343 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7345 /* Picture Filters */
7346 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7347 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7348 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7349 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7350 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7351 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7352 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7353 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7354 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7355 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7356 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7359 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7360 /* we actually call the methods for the nests here */
7361 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7363 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7364 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7365 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7366 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7367 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7368 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7369 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7370 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7371 [audioTrack1Array autorelease];
7372 [audioListArray addObject:audioTrack1Array];
7375 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7377 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7378 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7379 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7380 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7381 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7382 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7383 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7384 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7385 [audioTrack2Array autorelease];
7386 [audioListArray addObject:audioTrack2Array];
7389 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7391 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7392 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7393 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7394 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7395 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7396 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7397 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7398 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7399 [audioTrack3Array autorelease];
7400 [audioListArray addObject:audioTrack3Array];
7403 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7405 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7406 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7407 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7408 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7409 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7410 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7411 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7412 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7413 [audioTrack4Array autorelease];
7414 [audioListArray addObject:audioTrack4Array];
7418 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7421 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7422 * subititle array code. */
7424 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7425 /* Forced Subtitles */
7426 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7428 [preset autorelease];
7435 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7436 /* We get the default preset in case it changed */
7437 [self getDefaultPresets:nil];
7441 - (IBAction)deletePreset:(id)sender
7445 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7449 /* Alert user before deleting preset */
7451 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7453 if ( status == NSAlertDefaultReturn )
7455 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7456 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7457 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7459 NSEnumerator *enumerator;
7460 NSMutableArray *presetsArrayToMod;
7461 NSMutableArray *tempArray;
7463 /* If we are a root level preset, we are modding the UserPresets array */
7464 if (presetToModLevel == 0)
7466 presetsArrayToMod = UserPresets;
7468 else // We have a parent preset, so we modify the chidren array object for key
7470 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7473 enumerator = [presetsArrayToMod objectEnumerator];
7474 tempArray = [NSMutableArray array];
7476 while (tempObject = [enumerator nextObject])
7478 NSDictionary *thisPresetDict = tempObject;
7479 if (thisPresetDict == presetToMod)
7481 [tempArray addObject:tempObject];
7485 [presetsArrayToMod removeObjectsInArray:tempArray];
7486 [fPresetsOutlineView reloadData];
7493 #pragma mark Import Export Preset(s)
7495 - (IBAction) browseExportPresetFile: (id) sender
7497 /* Open a panel to let the user choose where and how to save the export file */
7498 NSSavePanel * panel = [NSSavePanel savePanel];
7499 /* We get the current file name and path from the destination field here */
7500 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7502 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7503 modalForWindow: fWindow modalDelegate: self
7504 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7508 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7509 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7511 if( returnCode == NSOKButton )
7513 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7514 NSString *exportPresetsFile = [sheet filename];
7515 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7516 /* We check for the presets.plist */
7517 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7519 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7521 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7522 if (nil == presetsToExport)
7524 presetsToExport = [[NSMutableArray alloc] init];
7526 /* now get and add selected presets to export */
7529 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7531 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7532 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7540 - (IBAction) browseImportPresetFile: (id) sender
7543 NSOpenPanel * panel;
7545 panel = [NSOpenPanel openPanel];
7546 [panel setAllowsMultipleSelection: NO];
7547 [panel setCanChooseFiles: YES];
7548 [panel setCanChooseDirectories: NO ];
7549 NSString * sourceDirectory;
7550 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7552 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7556 sourceDirectory = @"~/Desktop";
7557 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7559 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7560 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7562 /* set this for allowed file types, not sure if we should allow xml or not */
7563 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7564 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7565 modalForWindow: fWindow modalDelegate: self
7566 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7567 contextInfo: sender];
7570 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7571 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7573 if( returnCode == NSOKButton )
7575 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7576 NSString *importPresetsFile = [sheet filename];
7577 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7578 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7579 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7580 /* iterate though the new array of presets to import and add them to our presets array */
7582 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7584 while (tempObject = [enumerator nextObject])
7586 /* make any changes to the incoming preset we see fit */
7587 /* make sure the incoming preset is not tagged as default */
7588 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7589 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7590 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7591 [tempObject setObject:prependedName forKey:@"PresetName"];
7593 /* actually add the new preset to our presets array */
7594 [UserPresets addObject:tempObject];
7597 [presetsToImport autorelease];
7605 #pragma mark Manage Default Preset
7607 - (IBAction)getDefaultPresets:(id)sender
7609 presetHbDefault = nil;
7610 presetUserDefault = nil;
7611 presetUserDefaultParent = nil;
7612 presetUserDefaultParentParent = nil;
7613 NSMutableDictionary *presetHbDefaultParent = nil;
7614 NSMutableDictionary *presetHbDefaultParentParent = nil;
7617 BOOL userDefaultFound = NO;
7618 presetCurrentBuiltInCount = 0;
7619 /* First we iterate through the root UserPresets array to check for defaults */
7620 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7622 while (tempObject = [enumerator nextObject])
7624 NSMutableDictionary *thisPresetDict = tempObject;
7625 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7627 presetHbDefault = thisPresetDict;
7629 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7631 presetUserDefault = thisPresetDict;
7632 userDefaultFound = YES;
7634 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7636 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7640 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7641 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7643 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7644 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7646 while (tempObject = [enumerator nextObject])
7648 NSMutableDictionary *thisPresetDict = tempObject;
7649 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7651 presetHbDefault = thisPresetDict;
7652 presetHbDefaultParent = thisPresetDictParent;
7654 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7656 presetUserDefault = thisPresetDict;
7657 presetUserDefaultParent = thisPresetDictParent;
7658 userDefaultFound = YES;
7661 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7662 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7664 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7665 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7667 while (tempObject = [enumerator nextObject])
7669 NSMutableDictionary *thisPresetDict = tempObject;
7670 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7672 presetHbDefault = thisPresetDict;
7673 presetHbDefaultParent = thisPresetDictParent;
7674 presetHbDefaultParentParent = thisPresetDictParentParent;
7676 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7678 presetUserDefault = thisPresetDict;
7679 presetUserDefaultParent = thisPresetDictParent;
7680 presetUserDefaultParentParent = thisPresetDictParentParent;
7681 userDefaultFound = YES;
7690 /* check to see if a user specified preset was found, if not then assign the parents for
7691 * the presetHbDefault so that we can open the parents for the nested presets
7693 if (userDefaultFound == NO)
7695 presetUserDefaultParent = presetHbDefaultParent;
7696 presetUserDefaultParentParent = presetHbDefaultParentParent;
7700 - (IBAction)setDefaultPreset:(id)sender
7702 /* We need to determine if the item is a folder */
7703 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7709 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7711 /* First make sure the old user specified default preset is removed */
7712 while (tempObject = [enumerator nextObject])
7714 NSMutableDictionary *thisPresetDict = tempObject;
7715 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7717 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7720 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7721 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7723 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7726 while (tempObject = [enumerator nextObject])
7728 NSMutableDictionary *thisPresetDict1 = tempObject;
7729 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7731 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7733 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7734 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7736 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7739 while (tempObject = [enumerator nextObject])
7741 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7743 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7756 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7757 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7758 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7761 NSMutableArray *presetsArrayToMod;
7762 NSMutableArray *tempArray;
7764 /* If we are a root level preset, we are modding the UserPresets array */
7765 if (presetToModLevel == 0)
7767 presetsArrayToMod = UserPresets;
7769 else // We have a parent preset, so we modify the chidren array object for key
7771 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7774 enumerator = [presetsArrayToMod objectEnumerator];
7775 tempArray = [NSMutableArray array];
7777 while (tempObject = [enumerator nextObject])
7779 NSDictionary *thisPresetDict = tempObject;
7780 if (thisPresetDict == presetToMod)
7782 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7784 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7791 /* We save all of the preset data here */
7793 /* We Reload the New Table data for presets */
7794 [fPresetsOutlineView reloadData];
7797 - (IBAction)selectDefaultPreset:(id)sender
7799 NSMutableDictionary *presetToMod;
7800 /* if there is a user specified default, we use it */
7801 if (presetUserDefault)
7803 presetToMod = presetUserDefault;
7805 else if (presetHbDefault) //else we use the built in default presetHbDefault
7807 presetToMod = presetHbDefault;
7814 if (presetUserDefaultParent != nil)
7816 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7819 if (presetUserDefaultParentParent != nil)
7821 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7825 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7826 [self selectPreset:nil];
7831 #pragma mark Manage Built In Presets
7834 - (IBAction)deleteFactoryPresets:(id)sender
7837 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7841 NSMutableArray *tempArray;
7844 tempArray = [NSMutableArray array];
7845 /* we look here to see if the preset is we move on to the next one */
7846 while ( tempObject = [enumerator nextObject] )
7848 /* if the preset is "Factory" then we put it in the array of
7849 presets to delete */
7850 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7852 [tempArray addObject:tempObject];
7856 [UserPresets removeObjectsInArray:tempArray];
7857 [fPresetsOutlineView reloadData];
7862 /* We use this method to recreate new, updated factory presets */
7863 - (IBAction)addFactoryPresets:(id)sender
7866 /* First, we delete any existing built in presets */
7867 [self deleteFactoryPresets: sender];
7868 /* Then we generate new built in presets programmatically with fPresetsBuiltin
7869 * which is all setup in HBPresets.h and HBPresets.m*/
7870 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
7871 /* update build number for built in presets */
7872 /* iterate though the new array of presets to import and add them to our presets array */
7874 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7876 while (tempObject = [enumerator nextObject])
7878 /* Record the apps current build number in the PresetBuildNumber key */
7879 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7881 /* Preset build number */
7882 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7886 /* report the built in preset updating to the activity log */
7887 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
7897 /*******************************
7898 * Subclass of the HBPresetsOutlineView *
7899 *******************************/
7901 @implementation HBPresetsOutlineView
7902 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
7906 // By default, NSTableView only drags an image of the first column. Change this to
7907 // drag an image of the queue's icon and PresetName columns.
7908 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
7909 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
7914 - (void) mouseDown:(NSEvent *)theEvent
7916 [super mouseDown:theEvent];
7922 - (BOOL) isDragging;