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. */
9 #import "HBOutputPanelController.h"
10 #import "HBPreferencesController.h"
11 #import "HBDVDDetector.h"
13 #import "HBPreviewController.h"
15 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
17 /* We setup the toolbar values here ShowPreviewIdentifier */
18 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
19 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
20 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
21 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
22 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
23 static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
24 static NSString * ShowPreviewIdentifier = @"Show Preview Window Item Identifier";
25 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
26 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
29 /*******************************
30 * HBController implementation *
31 *******************************/
32 @implementation HBController
42 /* replace bundled app icon with one which is 32/64-bit savvy */
43 #if defined( __LP64__ )
44 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
46 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
48 if( fApplicationIcon != nil )
49 [NSApp setApplicationIconImage:fApplicationIcon];
51 [HBPreferencesController registerUserDefaults];
53 fQueueEncodeLibhb = NULL;
54 /* Check for check for the app support directory here as
55 * outputPanel needs it right away, as may other future methods
57 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
59 YES ) objectAtIndex:0];
60 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
61 stringByAppendingPathComponent:@"HandBrake"];
62 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
64 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
67 /* Check for and create the App Support Preview directory if necessary */
68 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
69 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
71 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
74 outputPanel = [[HBOutputPanelController alloc] init];
75 fPictureController = [[PictureController alloc] init];
76 fQueueController = [[HBQueueController alloc] init];
77 fAdvancedOptions = [[HBAdvancedController alloc] init];
78 /* we init the HBPresets class which currently is only used
79 * for updating built in presets, may move more functionality
82 fPresetsBuiltin = [[HBPresets alloc] init];
83 fPreferencesController = [[HBPreferencesController alloc] init];
84 /* Lets report the HandBrake version number here to the activity log and text log file */
85 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
86 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
88 /* Get the PID number for this hb instance, used in multi instance encoding */
89 pidNum = [self getThisHBInstancePID];
90 /* Report this pid to the activity log */
91 [self writeToActivityLog: "Pid for this instance:%d", pidNum];
97 - (void) applicationDidFinishLaunching: (NSNotification *) notification
99 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
100 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
101 fHandle = hb_init(loggingLevel, 0);
102 /* Optional dvd nav UseDvdNav*/
103 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
104 /* Init a separate instance of libhb for user scanning and setting up jobs */
105 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
107 // Set the Growl Delegate
108 [GrowlApplicationBridge setGrowlDelegate: self];
109 /* Init others controllers */
110 [fPictureController SetHandle: fHandle];
111 [fPictureController setHBController: self];
113 [fQueueController setHandle: fQueueEncodeLibhb];
114 [fQueueController setHBController: self];
116 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
117 [fChapterTable setDataSource:fChapterTitlesDelegate];
118 [fChapterTable setDelegate:fChapterTitlesDelegate];
120 /* setup the subtitles delegate and connections to table */
121 fSubtitlesDelegate = [[HBSubtitles alloc] init];
122 [fSubtitlesTable setDataSource:fSubtitlesDelegate];
123 [fSubtitlesTable setDelegate:fSubtitlesDelegate];
124 [fSubtitlesTable setRowHeight:25.0];
126 [fPresetsOutlineView setAutosaveName:@"Presets View"];
127 [fPresetsOutlineView setAutosaveExpandedItems:YES];
129 dockIconProgress = 0;
131 /* Init QueueFile .plist */
132 [self loadQueueFile];
134 /* Call UpdateUI every 1/2 sec */
136 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
137 scheduledTimerWithTimeInterval:0.5
139 selector:@selector(updateUI:)
140 userInfo:nil repeats:YES]
141 forMode:NSDefaultRunLoopMode];
144 // Open debug output window now if it was visible when HB was closed
145 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
146 [self showDebugOutputPanel:nil];
148 // Open queue window now if it was visible when HB was closed
149 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
150 [self showQueueWindow:nil];
152 [self openMainWindow:nil];
154 /* We have to set the bool to tell hb what to do after a scan
155 * Initially we set it to NO until we start processing the queue
157 applyQueueToScan = NO;
159 /* Now we re-check the queue array to see if there are
160 * any remaining encodes to be done in it and ask the
161 * user if they want to reload the queue */
162 if ([QueueFileArray count] > 0)
164 /* run getQueueStats to see whats in the queue file */
165 [self getQueueStats];
166 /* this results in these values
167 * fEncodingQueueItem = 0;
169 * fCompletedCount = 0;
170 * fCanceledCount = 0;
174 /*On Screen Notification*/
175 NSString * alertTitle;
177 /* We check to see if there is already another instance of hb running.
178 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
180 if ([self hbInstances] > 1)
182 alertTitle = [NSString stringWithFormat:
183 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
184 NSBeginCriticalAlertSheet(
186 NSLocalizedString(@"Reload Queue", nil),
190 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
191 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
195 if (fWorkingCount > 0)
197 alertTitle = [NSString stringWithFormat:
198 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
199 fWorkingCount,fPendingCount];
203 alertTitle = [NSString stringWithFormat:
204 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
208 NSBeginCriticalAlertSheet(
210 NSLocalizedString(@"Reload Queue", nil),
212 NSLocalizedString(@"Empty Queue", nil),
214 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
215 NSLocalizedString(@" Do you want to reload them ?", nil));
221 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
222 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
224 [self browseSources:nil];
227 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
229 [self browseSources:(id)fOpenSourceTitleMMenu];
232 currentQueueEncodeNameString = @"";
236 #pragma mark Multiple Instances
239 /* check to see if another instance of HandBrake.app is running */
240 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
241 NSDictionary *runningAppsDictionary;
243 for (runningAppsDictionary in runningAppDictionaries)
245 if ([[runningAppsDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
252 /* Gets the Process Identifer (PID) for this instance and returns it as an integer */
253 - (int) getThisHBInstancePID
255 /* Get the PID of this HB instance */
256 int hbInstancePID = [[NSRunningApplication currentApplication] processIdentifier];
257 return hbInstancePID;
262 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
264 if (returnCode == NSAlertOtherReturn)
266 [self clearQueueAllItems];
268 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
269 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
271 [self browseSources:nil];
274 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
276 [self browseSources:(id)fOpenSourceTitleMMenu];
281 if ([self hbInstances] == 1)
283 [self setQueueEncodingItemsAsPending];
285 [self showQueueWindow:NULL];
289 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
294 hb_get_state( fQueueEncodeLibhb, &s );
296 if ( s.state != HB_STATE_IDLE )
298 int result = NSRunCriticalAlertPanel(
299 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
300 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
301 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
303 if (result == NSAlertDefaultReturn)
305 return NSTerminateNow;
308 return NSTerminateCancel;
311 // Warn if items still in the queue
312 else if ( fPendingCount > 0 )
314 int result = NSRunCriticalAlertPanel(
315 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
316 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
317 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
319 if ( result == NSAlertDefaultReturn )
320 return NSTerminateNow;
322 return NSTerminateCancel;
325 return NSTerminateNow;
328 - (void)applicationWillTerminate:(NSNotification *)aNotification
330 [currentQueueEncodeNameString release];
331 [browsedSourceDisplayName release];
332 [outputPanel release];
333 [fQueueController release];
334 [fPreviewController release];
335 [fPictureController release];
336 [fApplicationIcon release];
339 hb_close(&fQueueEncodeLibhb);
345 - (void) awakeFromNib
348 [fWindow setExcludedFromWindowsMenu:NO];
350 [fAdvancedOptions setView:fAdvancedView];
352 /* lets setup our presets drawer for drag and drop here */
353 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
354 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
355 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
357 /* Initialize currentScanCount so HB can use it to
358 evaluate successive scans */
359 currentScanCount = 0;
362 /* Init UserPresets .plist */
365 fRipIndicatorShown = NO; // initially out of view in the nib
367 /* For 64 bit builds, the threaded animation in the progress
368 * indicators conflicts with the animation in the advanced tab
369 * for reasons not completely clear. jbrjake found a note in the
370 * 10.5 dev notes regarding this possiblility. It was also noted
371 * that unless specified, setUsesThreadedAnimation defaults to true.
372 * So, at least for now we set the indicator animation to NO for
373 * both the scan and regular progress indicators for both 32 and 64 bit
374 * as it test out fine on both and there is no reason our progress indicators
375 * should require their own thread.
378 [fScanIndicator setUsesThreadedAnimation:NO];
379 [fRipIndicator setUsesThreadedAnimation:NO];
383 /* Show/Dont Show Presets drawer upon launch based
384 on user preference DefaultPresetsDrawerShow*/
385 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
387 [fPresetDrawer setDelegate:self];
388 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
389 stringForKey:@"Drawer Size"] );
390 if( drawerSize.width )
391 [fPresetDrawer setContentSize: drawerSize];
392 [fPresetDrawer open];
395 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
396 [fSrcAngleLabel setHidden:YES];
397 [fSrcAnglePopUp setHidden:YES];
399 /* Setup the start / stop popup */
400 [fEncodeStartStopPopUp removeAllItems];
401 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
402 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
403 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
404 /* Align the start / stop widgets with the chapter popups */
405 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
406 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
408 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
409 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
412 NSMenuItem *menuItem;
413 [fDstFormatPopUp removeAllItems];
415 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
416 [menuItem setTag: HB_MUX_MP4];
418 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
419 [menuItem setTag: HB_MUX_MKV];
421 [fDstFormatPopUp selectItemAtIndex: 0];
423 [self formatPopUpChanged:nil];
425 /* We enable the create chapters checkbox here since we are .mp4 */
426 [fCreateChapterMarkers setEnabled: YES];
427 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
429 [fCreateChapterMarkers setState: NSOnState];
435 [fDstFile2Field setStringValue: [NSString stringWithFormat:
436 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
439 [fVidEncoderPopUp removeAllItems];
440 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
444 [fVidTargetSizeField setIntValue: 700];
445 [fVidBitrateField setIntValue: 1000];
447 [fVidQualityMatrix selectCell: fVidBitrateCell];
448 [self videoMatrixChanged:nil];
450 /* Video framerate */
451 [fVidRatePopUp removeAllItems];
452 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
453 for( int i = 0; i < hb_video_rates_count; i++ )
455 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
457 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
458 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
460 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
462 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
463 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
465 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
467 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
468 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
472 [fVidRatePopUp addItemWithTitle:
473 [NSString stringWithUTF8String: hb_video_rates[i].string]];
476 [fVidRatePopUp selectItemAtIndex: 0];
478 /* Set Auto Crop to On at launch */
479 [fPictureController setAutoCrop:YES];
482 [fAudTrack1BitratePopUp removeAllItems];
483 for( int i = 0; i < hb_audio_bitrates_count; i++ )
485 [fAudTrack1BitratePopUp addItemWithTitle:
486 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
489 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
491 /* Audio samplerate */
492 [fAudTrack1RatePopUp removeAllItems];
493 for( int i = 0; i < hb_audio_rates_count; i++ )
495 [fAudTrack1RatePopUp addItemWithTitle:
496 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
498 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
501 [fStatusField setStringValue: @""];
506 /* We disable the Turbo 1st pass checkbox since we are not x264 */
507 [fVidTurboPassCheck setEnabled: NO];
508 [fVidTurboPassCheck setState: NSOffState];
511 /* lets get our default prefs here */
512 [self getDefaultPresets:nil];
513 /* lets initialize the current successful scancount here to 0 */
514 currentSuccessfulScanCount = 0;
517 - (void) enableUI: (bool) b
519 NSControl * controls[] =
520 { fSrcTitleField, fSrcTitlePopUp,
521 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
522 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
523 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
524 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
525 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
526 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
527 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
528 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
529 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
530 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
531 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
532 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
533 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
534 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
535 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
536 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
537 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
538 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,
539 fSrcFrameEndEncodingField, fLoadChaptersButton, fSaveChaptersButton, fFrameratePfrCheck};
542 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
544 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
546 NSTextField * tf = (NSTextField *) controls[i];
547 if( ![tf isBezeled] )
549 [tf setTextColor: b ? [NSColor controlTextColor] :
550 [NSColor disabledControlTextColor]];
554 [controls[i] setEnabled: b];
560 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
561 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
562 [self setEnabledStateOfAudioMixdownControls:nil];
563 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
564 [self calculatePictureSizing:nil];
568 [fPresetsOutlineView setEnabled: NO];
572 [self videoMatrixChanged:nil];
573 [fAdvancedOptions enableUI:b];
577 /***********************************************************************
579 ***********************************************************************
580 * Shows a progression bar on the dock icon, filled according to
581 * 'progress' (0.0 <= progress <= 1.0).
582 * Called with progress < 0.0 or progress > 1.0, restores the original
584 **********************************************************************/
585 - (void) UpdateDockIcon: (float) progress
588 NSBitmapImageRep * bmp;
590 uint32_t black = htonl( 0x000000FF );
591 uint32_t red = htonl( 0xFF0000FF );
592 uint32_t white = htonl( 0xFFFFFFFF );
593 int row_start, row_end;
596 if( progress < 0.0 || progress > 1.0 )
598 [NSApp setApplicationIconImage: fApplicationIcon];
602 /* Get it in a raw bitmap form */
603 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
604 NSTIFFCompressionNone factor: 1.0];
605 bmp = [NSBitmapImageRep imageRepWithData: tiff];
607 /* Draw the progression bar */
608 /* It's pretty simple (ugly?) now, but I'm no designer */
610 row_start = 3 * (int) [bmp size].height / 4;
611 row_end = 7 * (int) [bmp size].height / 8;
613 for( i = row_start; i < row_start + 2; i++ )
615 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
616 for( j = 0; j < (int) [bmp size].width; j++ )
621 for( i = row_start + 2; i < row_end - 2; i++ )
623 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
626 for( j = 2; j < (int) [bmp size].width - 2; j++ )
628 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
640 for( i = row_end - 2; i < row_end; i++ )
642 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
643 for( j = 0; j < (int) [bmp size].width; j++ )
649 /* Now update the dock icon */
650 tiff = [bmp TIFFRepresentationUsingCompression:
651 NSTIFFCompressionNone factor: 1.0];
652 NSImage* icon = [[NSImage alloc] initWithData: tiff];
653 [NSApp setApplicationIconImage: icon];
657 - (void) updateUI: (NSTimer *) timer
660 /* Update UI for fHandle (user scanning instance of libhb ) */
663 list = hb_get_titles( fHandle );
664 /* check to see if there has been a new scan done
665 this bypasses the constraints of HB_STATE_WORKING
666 not allowing setting a newly scanned source */
667 int checkScanCount = hb_get_scancount( fHandle );
668 if( checkScanCount > currentScanCount )
670 currentScanCount = checkScanCount;
671 [fScanIndicator setIndeterminate: NO];
672 [fScanIndicator setDoubleValue: 0.0];
673 [fScanIndicator setHidden: YES];
674 [self showNewScan:nil];
678 hb_get_state( fHandle, &s );
684 #define p s.param.scanning
685 case HB_STATE_SCANNING:
687 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
688 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
689 p.title_cur, p.title_count]];
690 [fScanIndicator setHidden: NO];
691 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
696 #define p s.param.scandone
697 case HB_STATE_SCANDONE:
699 [fScanIndicator setIndeterminate: NO];
700 [fScanIndicator setDoubleValue: 0.0];
701 [fScanIndicator setHidden: YES];
702 [self writeToActivityLog:"ScanDone state received from fHandle"];
703 [self showNewScan:nil];
704 [[fWindow toolbar] validateVisibleItems];
710 #define p s.param.working
711 case HB_STATE_WORKING:
718 #define p s.param.muxing
719 case HB_STATE_MUXING:
726 case HB_STATE_PAUSED:
729 case HB_STATE_WORKDONE:
736 /* Update UI for fQueueEncodeLibhb */
738 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
739 /* check to see if there has been a new scan done
740 this bypasses the constraints of HB_STATE_WORKING
741 not allowing setting a newly scanned source */
743 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
744 if( checkScanCount > currentScanCount )
746 currentScanCount = checkScanCount;
750 hb_get_state( fQueueEncodeLibhb, &s );
756 #define p s.param.scanning
757 case HB_STATE_SCANNING:
759 [fStatusField setStringValue: [NSString stringWithFormat:
760 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
761 p.title_cur, p.title_count]];
763 /* Set the status string in fQueueController as well */
764 [fQueueController setQueueStatusString: [NSString stringWithFormat:
765 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
766 p.title_cur, p.title_count]];
771 #define p s.param.scandone
772 case HB_STATE_SCANDONE:
774 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
775 [self processNewQueueEncode];
776 [[fWindow toolbar] validateVisibleItems];
783 #define p s.param.working
785 case HB_STATE_SEARCHING:
787 NSMutableString * string;
788 NSString * pass_desc;
790 /* Update text field */
792 //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];
793 /* For now, do not announce "pass x of x for the search phase ... */
794 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
798 [string appendFormat:
799 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
802 [fStatusField setStringValue: string];
803 /* Set the status string in fQueueController as well */
804 [fQueueController setQueueStatusString: string];
806 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
807 [fRipIndicator setIndeterminate: NO];
808 [fRipIndicator setDoubleValue:100.0 * progress_total];
810 // If progress bar hasn't been revealed at the bottom of the window, do
811 // that now. This code used to be in doRip. I moved it to here to handle
812 // the case where hb_start is called by HBQueueController and not from
814 if( !fRipIndicatorShown )
816 NSRect frame = [fWindow frame];
817 if( frame.size.width <= 591 )
818 frame.size.width = 591;
819 frame.size.height += 36;
820 frame.origin.y -= 36;
821 [fWindow setFrame:frame display:YES animate:YES];
822 fRipIndicatorShown = YES;
826 /* Update dock icon */
827 /* Note not done yet */
832 case HB_STATE_WORKING:
834 NSMutableString * string;
835 NSString * pass_desc;
836 /* Update text field */
837 if (p.job_cur == 1 && p.job_count > 1)
839 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
841 pass_desc = @"(subtitle scan)";
853 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
857 [string appendFormat:
858 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
859 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
862 [fStatusField setStringValue: string];
863 /* Set the status string in fQueueController as well but add currentQueueEncodeNameString to delineate
864 * which encode is being worked on by this instance in a multiple instance situation
866 NSString * queueStatusString = [NSString stringWithFormat:@"%@ -> %@",string,currentQueueEncodeNameString];
867 [fQueueController setQueueStatusString:queueStatusString];
870 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
871 [fRipIndicator setIndeterminate: NO];
872 [fRipIndicator setDoubleValue:100.0 * progress_total];
874 // If progress bar hasn't been revealed at the bottom of the window, do
875 // that now. This code used to be in doRip. I moved it to here to handle
876 // the case where hb_start is called by HBQueueController and not from
878 if( !fRipIndicatorShown )
880 NSRect frame = [fWindow frame];
881 if( frame.size.width <= 591 )
882 frame.size.width = 591;
883 frame.size.height += 36;
884 frame.origin.y -= 36;
885 [fWindow setFrame:frame display:YES animate:YES];
886 fRipIndicatorShown = YES;
890 /* Update dock icon */
891 if( dockIconProgress < 100.0 * progress_total )
893 [self UpdateDockIcon: progress_total];
894 dockIconProgress += 5;
901 #define p s.param.muxing
902 case HB_STATE_MUXING:
904 /* Update text field */
905 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
906 /* Set the status string in fQueueController as well */
907 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
909 [fRipIndicator setIndeterminate: YES];
910 [fRipIndicator startAnimation: nil];
912 /* Update dock icon */
913 [self UpdateDockIcon: 1.0];
919 case HB_STATE_PAUSED:
920 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
921 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
925 case HB_STATE_WORKDONE:
927 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
928 // or someone calling hb_stop. In the latter case, hb_stop does not clear
929 // out the remaining passes/jobs in the queue. We'll do that here.
931 // Delete all remaining jobs of this encode.
932 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
933 /* Set the status string in fQueueController as well */
934 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
935 [fRipIndicator setIndeterminate: NO];
936 [fRipIndicator stopAnimation: nil];
937 [fRipIndicator setDoubleValue: 0.0];
938 [[fWindow toolbar] validateVisibleItems];
940 /* Restore dock icon */
941 [self UpdateDockIcon: -1.0];
942 dockIconProgress = 0;
944 if( fRipIndicatorShown )
946 NSRect frame = [fWindow frame];
947 if( frame.size.width <= 591 )
948 frame.size.width = 591;
949 frame.size.height += -36;
950 frame.origin.y -= -36;
951 [fWindow setFrame:frame display:YES animate:YES];
952 fRipIndicatorShown = NO;
954 /* Since we are done with this encode, tell output to stop writing to the
955 * individual encode log
957 [outputPanel endEncodeLog];
958 /* Check to see if the encode state has not been cancelled
959 to determine if we should check for encode done notifications */
960 if( fEncodeState != 2 )
962 NSString *pathOfFinishedEncode;
963 /* Get the output file name for the finished encode */
964 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
966 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
968 [self showGrowlDoneNotification:pathOfFinishedEncode];
970 [self sendToMetaX:pathOfFinishedEncode];
972 /* since we have successfully completed an encode, we increment the queue counter */
973 [self incrementQueueItemDone:currentQueueEncodeIndex];
975 /* all end of queue actions below need to be done after all queue encodes have finished
976 * and there are no pending jobs left to process
978 if (fPendingCount == 0)
980 /* If Alert Window or Window and Growl has been selected */
981 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
982 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
984 /*On Screen Notification*/
987 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
988 [NSApp requestUserAttention:NSCriticalRequest];
991 /* If sleep has been selected */
992 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
995 NSDictionary* errorDict;
996 NSAppleEventDescriptor* returnDescriptor = nil;
997 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
998 @"tell application \"Finder\" to sleep"];
999 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1000 [scriptObject release];
1002 /* If Shutdown has been selected */
1003 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
1006 NSDictionary* errorDict;
1007 NSAppleEventDescriptor* returnDescriptor = nil;
1008 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
1009 @"tell application \"Finder\" to shut down"];
1010 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1011 [scriptObject release];
1020 /* Since we can use multiple instance off of the same queue file it is imperative that we keep the QueueFileArray updated off of the QueueFile.plist
1021 * so we go ahead and do it in this existing timer as opposed to using a new one */
1023 NSMutableArray * tempQueueArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1024 [QueueFileArray setArray:tempQueueArray];
1025 [tempQueueArray release];
1026 /* Send Fresh QueueFileArray to fQueueController to update queue window */
1027 [fQueueController setQueueArray: QueueFileArray];
1028 [self getQueueStats];
1032 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1033 - (void) writeToActivityLog:(const char *) format, ...
1036 va_start(args, format);
1040 vsnprintf( str, 1024, format, args );
1042 time_t _now = time( NULL );
1043 struct tm * now = localtime( &_now );
1044 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1050 #pragma mark Toolbar
1051 // ============================================================
1052 // NSToolbar Related Methods
1053 // ============================================================
1055 - (void) setupToolbar {
1056 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1058 [toolbar setAllowsUserCustomization: YES];
1059 [toolbar setAutosavesConfiguration: YES];
1060 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1062 [toolbar setDelegate: self];
1064 [fWindow setToolbar: toolbar];
1067 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1068 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1069 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1071 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1073 [item setLabel: @"Toggle Presets"];
1074 [item setPaletteLabel: @"Toggler Presets"];
1075 [item setToolTip: @"Open/Close Preset Drawer"];
1076 [item setImage: [NSImage imageNamed: @"Drawer"]];
1077 [item setTarget: self];
1078 [item setAction: @selector(toggleDrawer:)];
1079 [item setAutovalidates: NO];
1081 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1083 [item setLabel: @"Start"];
1084 [item setPaletteLabel: @"Start Encoding"];
1085 [item setToolTip: @"Start Encoding"];
1086 [item setImage: [NSImage imageNamed: @"Play"]];
1087 [item setTarget: self];
1088 [item setAction: @selector(Rip:)];
1090 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1092 [item setLabel: @"Show Queue"];
1093 [item setPaletteLabel: @"Show Queue"];
1094 [item setToolTip: @"Show Queue"];
1095 [item setImage: [NSImage imageNamed: @"Queue"]];
1096 [item setTarget: self];
1097 [item setAction: @selector(showQueueWindow:)];
1098 [item setAutovalidates: NO];
1100 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1102 [item setLabel: @"Add to Queue"];
1103 [item setPaletteLabel: @"Add to Queue"];
1104 [item setToolTip: @"Add to Queue"];
1105 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1106 [item setTarget: self];
1107 [item setAction: @selector(addToQueue:)];
1109 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1111 [item setLabel: @"Pause"];
1112 [item setPaletteLabel: @"Pause Encoding"];
1113 [item setToolTip: @"Pause Encoding"];
1114 [item setImage: [NSImage imageNamed: @"Pause"]];
1115 [item setTarget: self];
1116 [item setAction: @selector(Pause:)];
1118 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1120 [item setLabel: @"Picture Settings"];
1121 [item setPaletteLabel: @"Show Picture Settings"];
1122 [item setToolTip: @"Show Picture Settings"];
1123 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1124 [item setTarget: self];
1125 [item setAction: @selector(showPicturePanel:)];
1127 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1129 [item setLabel: @"Preview Window"];
1130 [item setPaletteLabel: @"Show Preview"];
1131 [item setToolTip: @"Show Preview"];
1132 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1133 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1134 [item setTarget: self];
1135 [item setAction: @selector(showPreviewWindow:)];
1137 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1139 [item setLabel: @"Activity Window"];
1140 [item setPaletteLabel: @"Show Activity Window"];
1141 [item setToolTip: @"Show Activity Window"];
1142 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1143 [item setTarget: self];
1144 [item setAction: @selector(showDebugOutputPanel:)];
1145 [item setAutovalidates: NO];
1147 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1149 [item setLabel: @"Source"];
1150 [item setPaletteLabel: @"Source"];
1151 [item setToolTip: @"Choose Video Source"];
1152 [item setImage: [NSImage imageNamed: @"Source"]];
1153 [item setTarget: self];
1154 [item setAction: @selector(browseSources:)];
1164 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1166 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1167 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1168 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1171 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1173 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1174 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1175 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1176 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1179 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1181 NSString * ident = [toolbarItem itemIdentifier];
1187 hb_get_state( fHandle, &s );
1188 if (s.state == HB_STATE_SCANNING)
1191 if ([ident isEqualToString: ChooseSourceIdentifier])
1193 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1194 [toolbarItem setLabel: @"Cancel Scan"];
1195 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1196 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1200 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1205 if ([ident isEqualToString: ChooseSourceIdentifier])
1207 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1208 [toolbarItem setLabel: @"Source"];
1209 [toolbarItem setPaletteLabel: @"Source"];
1210 [toolbarItem setToolTip: @"Choose Video Source"];
1215 hb_get_state2( fQueueEncodeLibhb, &s );
1217 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1219 if ([ident isEqualToString: StartEncodingIdentifier])
1221 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1222 [toolbarItem setLabel: @"Stop"];
1223 [toolbarItem setPaletteLabel: @"Stop"];
1224 [toolbarItem setToolTip: @"Stop Encoding"];
1227 if ([ident isEqualToString: PauseEncodingIdentifier])
1229 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1230 [toolbarItem setLabel: @"Pause"];
1231 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1232 [toolbarItem setToolTip: @"Pause Encoding"];
1237 if ([ident isEqualToString: AddToQueueIdentifier])
1239 if ([ident isEqualToString: ShowPictureIdentifier])
1241 if ([ident isEqualToString: ShowPreviewIdentifier])
1245 else if (s.state == HB_STATE_PAUSED)
1247 if ([ident isEqualToString: PauseEncodingIdentifier])
1249 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1250 [toolbarItem setLabel: @"Resume"];
1251 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1252 [toolbarItem setToolTip: @"Resume Encoding"];
1255 if ([ident isEqualToString: StartEncodingIdentifier])
1257 if ([ident isEqualToString: AddToQueueIdentifier])
1259 if ([ident isEqualToString: ShowPictureIdentifier])
1261 if ([ident isEqualToString: ShowPreviewIdentifier])
1264 else if (s.state == HB_STATE_SCANNING)
1266 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1268 if ([ident isEqualToString: StartEncodingIdentifier])
1270 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1271 if (hb_count(fHandle) > 0)
1272 [toolbarItem setLabel: @"Start Queue"];
1274 [toolbarItem setLabel: @"Start"];
1275 [toolbarItem setPaletteLabel: @"Start Encoding"];
1276 [toolbarItem setToolTip: @"Start Encoding"];
1279 if ([ident isEqualToString: AddToQueueIdentifier])
1281 if ([ident isEqualToString: ShowPictureIdentifier])
1283 if ([ident isEqualToString: ShowPreviewIdentifier])
1288 /* If there are any pending queue items, make sure the start/stop button is active */
1289 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1291 if ([ident isEqualToString: ShowQueueIdentifier])
1293 if ([ident isEqualToString: ToggleDrawerIdentifier])
1295 if ([ident isEqualToString: ChooseSourceIdentifier])
1297 if ([ident isEqualToString: ShowActivityIdentifier])
1303 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1305 SEL action = [menuItem action];
1308 hb_get_state2( fHandle, &s );
1312 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1313 return SuccessfulScan && [fWindow attachedSheet] == nil;
1315 if (action == @selector(browseSources:))
1317 if (s.state == HB_STATE_SCANNING)
1320 return [fWindow attachedSheet] == nil;
1322 if (action == @selector(selectDefaultPreset:))
1323 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1324 if (action == @selector(Pause:))
1326 if (s.state == HB_STATE_WORKING)
1328 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1329 [menuItem setTitle:@"Pause Encoding"];
1332 else if (s.state == HB_STATE_PAUSED)
1334 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1335 [menuItem setTitle:@"Resume Encoding"];
1341 if (action == @selector(Rip:))
1343 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1345 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1346 [menuItem setTitle:@"Stop Encoding"];
1349 else if (SuccessfulScan)
1351 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1352 [menuItem setTitle:@"Start Encoding"];
1353 return [fWindow attachedSheet] == nil;
1359 if( action == @selector(setDefaultPreset:) )
1361 return [fPresetsOutlineView selectedRow] != -1;
1368 #pragma mark Encode Done Actions
1369 // register a test notification and make
1370 // it enabled by default
1371 #define SERVICE_NAME @"Encode Done"
1372 - (NSDictionary *)registrationDictionaryForGrowl
1374 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1375 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1376 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1379 return registrationDictionary;
1382 -(void)showGrowlDoneNotification:(NSString *) filePath
1384 /* This end of encode action is called as each encode rolls off of the queue */
1385 NSString * finishedEncode = filePath;
1386 /* strip off the path to just show the file name */
1387 finishedEncode = [finishedEncode lastPathComponent];
1388 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1389 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1391 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1392 [GrowlApplicationBridge
1393 notifyWithTitle:@"Put down that cocktail..."
1394 description:growlMssg
1395 notificationName:SERVICE_NAME
1403 -(void)sendToMetaX:(NSString *) filePath
1405 /* This end of encode action is called as each encode rolls off of the queue */
1406 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1408 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1409 if (![sendToApp isEqualToString:@"None"])
1411 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1412 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1413 [myScript executeAndReturnError: nil];
1420 #pragma mark Get New Source
1422 /*Opens the source browse window, called from Open Source widgets */
1423 - (IBAction) browseSources: (id) sender
1427 hb_get_state( fHandle, &s );
1428 if (s.state == HB_STATE_SCANNING)
1430 [self cancelScanning:nil];
1435 NSOpenPanel * panel;
1437 panel = [NSOpenPanel openPanel];
1438 [panel setAllowsMultipleSelection: NO];
1439 [panel setCanChooseFiles: YES];
1440 [panel setCanChooseDirectories: YES ];
1441 NSString * sourceDirectory;
1442 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1444 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1448 sourceDirectory = @"~/Desktop";
1449 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1451 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1452 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1454 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1455 modalForWindow: fWindow modalDelegate: self
1456 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1457 contextInfo: sender];
1460 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1461 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1463 /* we convert the sender content of contextInfo back into a variable called sender
1464 * mostly just for consistency for evaluation later
1466 id sender = (id)contextInfo;
1467 /* User selected a file to open */
1468 if( returnCode == NSOKButton )
1470 /* Free display name allocated previously by this code */
1471 [browsedSourceDisplayName release];
1473 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1474 /* we set the last searched source directory in the prefs here */
1475 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1476 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1477 /* we order out sheet, which is the browse window as we need to open
1478 * the title selection sheet right away
1480 [sheet orderOut: self];
1482 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1484 /* We put the chosen source path in the source display text field for the
1485 * source title selection sheet in which the user specifies the specific title to be
1486 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1487 * purposes in the title panel
1490 [fScanSrcTitlePathField setStringValue:scanPath];
1491 NSString *displayTitlescanSourceName;
1493 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1495 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1496 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1497 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1501 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1502 displayTitlescanSourceName = [scanPath lastPathComponent];
1504 /* we set the source display name in the title selection dialogue */
1505 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1506 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1507 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1508 /* We show the actual sheet where the user specifies the title to be scanned
1509 * as we are going to do a title specific scan
1511 [self showSourceTitleScanPanel:nil];
1515 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1516 NSString *path = [[sheet filenames] objectAtIndex: 0];
1518 /* We check to see if the chosen file at path is a package */
1519 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1521 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1522 /* We check to see if this is an .eyetv package */
1523 if ([[path pathExtension] isEqualToString: @"eyetv"])
1525 [self writeToActivityLog:"trying to open eyetv package"];
1526 /* We're looking at an EyeTV package - try to open its enclosed
1528 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1530 int n = [[path stringByAppendingString: @"/"]
1531 completePathIntoString: &mpgname caseSensitive: YES
1532 matchesIntoArray: nil
1533 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1536 /* Found an mpeg inside the eyetv package, make it our scan path
1537 and call performScan on the enclosed mpeg */
1539 [self writeToActivityLog:"found mpeg in eyetv package"];
1540 [self performScan:path scanTitleNum:0];
1544 /* We did not find an mpeg file in our package, so we do not call performScan */
1545 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1548 /* We check to see if this is a .dvdmedia package */
1549 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1551 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1552 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1553 [self writeToActivityLog:"trying to open dvdmedia package"];
1554 [self performScan:path scanTitleNum:0];
1558 /* The package is not an eyetv package, so we do not call performScan */
1559 [self writeToActivityLog:"unable to open package"];
1562 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1564 /* path is not a package, so we call perform scan directly on our file */
1565 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1567 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1568 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1569 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1573 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1574 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1575 /* make sure we remove any path extension as this can also be an '.mpg' file */
1576 browsedSourceDisplayName = [[path lastPathComponent] retain];
1578 applyQueueToScan = NO;
1579 [self performScan:path scanTitleNum:0];
1587 - (IBAction)showAboutPanel:(id)sender
1589 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1590 fApplicationIcon, @"ApplicationIcon",
1592 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1596 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1597 - (IBAction) showSourceTitleScanPanel: (id) sender
1599 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1602 [fScanSrcTitleNumField setStringValue: @"0"];
1603 /* Show the panel */
1604 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1607 - (IBAction) closeSourceTitleScanPanel: (id) sender
1609 [NSApp endSheet: fScanSrcTitlePanel];
1610 [fScanSrcTitlePanel orderOut: self];
1612 if(sender == fScanSrcTitleOpenButton)
1614 /* We setup the scan status in the main window to indicate a source title scan */
1615 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1616 [fScanIndicator setHidden: NO];
1617 [fScanIndicator setIndeterminate: YES];
1618 [fScanIndicator startAnimation: nil];
1620 /* We use the performScan method to actually perform the specified scan passing the path and the title
1623 applyQueueToScan = NO;
1624 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1628 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1629 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1632 /* use a bool to determine whether or not we can decrypt using vlc */
1633 BOOL cancelScanDecrypt = 0;
1635 NSString *path = scanPath;
1636 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1638 // Notify ChapterTitles that there's no title
1639 [fChapterTitlesDelegate resetWithTitle:nil];
1640 [fChapterTable reloadData];
1642 // Notify Subtitles that there's no title
1643 [fSubtitlesDelegate resetWithTitle:nil];
1644 [fSubtitlesTable reloadData];
1646 [self enableUI: NO];
1648 if( [detector isVideoDVD] )
1650 // The chosen path was actually on a DVD, so use the raw block
1651 // device path instead.
1652 path = [detector devicePath];
1653 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1655 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1656 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
1659 /*compatible vlc not found, so we set the bool to cancel scanning to 1 */
1660 cancelScanDecrypt = 1;
1661 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1663 status = NSRunAlertPanel(@"HandBrake could not find VLC or your VLC is incompatible (Note: 32 bit vlc is not compatible with 64 bit HandBrake and vice-versa).",@"Please download and install VLC media player if you wish to read encrypted DVDs.", @"Get VLC", @"Cancel Scan", @"Attempt Scan Anyway");
1664 [NSApp requestUserAttention:NSCriticalRequest];
1666 if (status == NSAlertDefaultReturn)
1668 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1669 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1671 else if (status == NSAlertAlternateReturn)
1673 /* User chose to cancel the scan */
1674 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1678 /* 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 */
1679 cancelScanDecrypt = 0;
1680 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1686 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1687 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1693 if (cancelScanDecrypt == 0)
1695 /* we actually pass the scan off to libhb here */
1696 /* If there is no title number passed to scan, we use "0"
1697 * which causes the default behavior of a full source scan
1703 if (scanTitleNum > 0)
1705 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1707 /* We use our advance pref to determine how many previews to scan */
1708 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1709 /* set title to NULL */
1711 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1712 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1716 - (IBAction) cancelScanning:(id)sender
1718 hb_scan_stop(fHandle);
1721 - (IBAction) showNewScan:(id)sender
1725 int feature_title=0; // Used to store the main feature title
1727 list = hb_get_titles( fHandle );
1729 if( !hb_list_count( list ) )
1731 /* We display a message if a valid dvd source was not chosen */
1732 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1733 SuccessfulScan = NO;
1735 // Notify ChapterTitles that there's no title
1736 [fSubtitlesDelegate resetWithTitle:nil];
1737 [fSubtitlesTable reloadData];
1739 // Notify Subtitles that there's no title
1740 [fChapterTitlesDelegate resetWithTitle:nil];
1741 [fChapterTable reloadData];
1745 if (applyQueueToScan == YES)
1747 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1748 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1751 else if (applyQueueToScan == NO)
1753 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1757 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1760 /* We increment the successful scancount here by one,
1761 which we use at the end of this function to tell the gui
1762 if this is the first successful scan since launch and whether
1763 or not we should set all settings to the defaults */
1764 currentSuccessfulScanCount++;
1766 [[fWindow toolbar] validateVisibleItems];
1768 [fSrcTitlePopUp removeAllItems];
1769 for( int i = 0; i < hb_list_count( list ); i++ )
1771 title = (hb_title_t *) hb_list_item( list, i );
1773 currentSource = [NSString stringWithUTF8String: title->name];
1774 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1775 if (!browsedSourceDisplayName)
1777 browsedSourceDisplayName = @"NoNameDetected";
1779 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1781 /* If its a queue rescan for edit, get the queue item output path */
1782 /* if not, its a new source scan. */
1783 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1784 if (applyQueueToScan == YES)
1786 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1788 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1790 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1791 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1795 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1796 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1799 /* See if this is the main feature according to libhb */
1800 if (title->index == title->job->feature)
1805 [fSrcTitlePopUp addItemWithTitle: [NSString
1806 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1807 title->name,title->index, title->hours, title->minutes,
1811 /* if we are a stream, select the first title */
1812 if (title->type == HB_STREAM_TYPE)
1814 [fSrcTitlePopUp selectItemAtIndex: 0];
1818 /* if not then select the main feature title */
1819 [fSrcTitlePopUp selectItemAtIndex: feature_title];
1821 [self titlePopUpChanged:nil];
1823 SuccessfulScan = YES;
1824 [self enableUI: YES];
1826 /* if its the initial successful scan after awakeFromNib */
1827 if (currentSuccessfulScanCount == 1)
1829 [self encodeStartStopPopUpChanged:nil];
1831 [self selectDefaultPreset:nil];
1833 // Open preview window now if it was visible when HB was closed
1834 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1835 [self showPreviewWindow:nil];
1837 // Open picture sizing window now if it was visible when HB was closed
1838 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1839 [self showPicturePanel:nil];
1842 if (applyQueueToScan == YES)
1844 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1845 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1846 [self applyQueueSettingsToMainWindow:nil];
1857 #pragma mark New Output Destination
1859 - (IBAction) browseFile: (id) sender
1861 /* Open a panel to let the user choose and update the text field */
1862 NSSavePanel * panel = [NSSavePanel savePanel];
1863 /* We get the current file name and path from the destination field here */
1864 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1865 modalForWindow: fWindow modalDelegate: self
1866 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1870 - (void) browseFileDone: (NSSavePanel *) sheet
1871 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1873 if( returnCode == NSOKButton )
1875 [fDstFile2Field setStringValue: [sheet filename]];
1876 /* Save this path to the prefs so that on next browse destination window it opens there */
1877 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1878 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1884 #pragma mark Main Window Control
1886 - (IBAction) openMainWindow: (id) sender
1888 [fWindow makeKeyAndOrderFront:nil];
1891 - (BOOL) windowShouldClose: (id) sender
1896 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1899 [fWindow makeKeyAndOrderFront:nil];
1907 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1908 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1913 #pragma mark Queue File
1915 - (void) loadQueueFile {
1916 /* We declare the default NSFileManager into fileManager */
1917 NSFileManager * fileManager = [NSFileManager defaultManager];
1918 /*We define the location of the user presets file */
1919 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1920 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1921 /* We check for the Queue.plist */
1922 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1924 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1927 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1928 /* lets check to see if there is anything in the queue file .plist */
1929 if (nil == QueueFileArray)
1931 /* if not, then lets initialize an empty array */
1932 QueueFileArray = [[NSMutableArray alloc] init];
1936 /* ONLY clear out encoded items if we are single instance */
1937 if ([self hbInstances] == 1)
1939 [self clearQueueEncodedItems];
1944 - (void)addQueueFileItem
1946 [QueueFileArray addObject:[self createQueueFileItem]];
1947 [self saveQueueFileItem];
1951 - (void) removeQueueFileItem:(int) queueItemToRemove
1953 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1954 [self saveQueueFileItem];
1958 - (void)saveQueueFileItem
1960 [QueueFileArray writeToFile:QueueFile atomically:YES];
1961 [fQueueController setQueueArray: QueueFileArray];
1962 [self getQueueStats];
1965 - (void)getQueueStats
1967 /* lets get the stats on the status of the queue array */
1969 fEncodingQueueItem = 0;
1971 fCompletedCount = 0;
1975 /* We use a number system to set the encode status of the queue item
1977 * 0 == already encoded
1978 * 1 == is being encoded
1979 * 2 == is yet to be encoded
1984 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1986 while (tempObject = [enumerator nextObject])
1988 NSDictionary *thisQueueDict = tempObject;
1989 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1993 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1996 fEncodingQueueItem = i;
1997 /* check to see if we are the instance doing this encoding */
1998 if ([thisQueueDict objectForKey:@"EncodingPID"] && [[thisQueueDict objectForKey:@"EncodingPID"] intValue] == pidNum)
2000 currentQueueEncodeIndex = i;
2004 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2008 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2015 /* Set the queue status field in the main window */
2016 NSMutableString * string;
2017 if (fPendingCount == 1)
2019 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2023 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2025 [fQueueStatus setStringValue:string];
2028 /* Used to get the next pending queue item index and return it if found */
2029 - (int)getNextPendingQueueIndex
2031 /* initialize nextPendingIndex to -1, this value tells incrementQueueItemDone that there are no pending items in the queue */
2032 int nextPendingIndex = -1;
2033 BOOL nextPendingFound = NO;
2034 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2037 while (tempObject = [enumerator nextObject])
2039 NSDictionary *thisQueueDict = tempObject;
2040 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2 && nextPendingFound == NO) // pending
2042 nextPendingFound = YES;
2043 nextPendingIndex = [QueueFileArray indexOfObject: tempObject];
2044 [self writeToActivityLog: "getNextPendingQueueIndex next pending encod index is:%d", nextPendingIndex];
2048 return nextPendingIndex;
2052 /* This method will set any item marked as encoding back to pending
2053 * currently used right after a queue reload
2055 - (void) setQueueEncodingItemsAsPending
2057 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2059 NSMutableArray *tempArray;
2060 tempArray = [NSMutableArray array];
2061 /* we look here to see if the preset is we move on to the next one */
2062 while ( tempObject = [enumerator nextObject] )
2064 /* If the queue item is marked as "encoding" (1)
2065 * then change its status back to pending (2) which effectively
2066 * puts it back into the queue to be encoded
2068 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2070 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2072 [tempArray addObject:tempObject];
2075 [QueueFileArray setArray:tempArray];
2076 [self saveQueueFileItem];
2080 /* This method will clear the queue of any encodes that are not still pending
2081 * this includes both successfully completed encodes as well as cancelled encodes */
2082 - (void) clearQueueEncodedItems
2084 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2086 NSMutableArray *tempArray;
2087 tempArray = [NSMutableArray array];
2088 /* we look here to see if the preset is we move on to the next one */
2089 while ( tempObject = [enumerator nextObject] )
2091 /* If the queue item is either completed (0) or cancelled (3) from the
2092 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2093 * NOTE: this means we retain pending (2) and also an item that is marked as
2094 * still encoding (1). If the queue has an item that is still marked as encoding
2095 * from a previous session, we can conlude that HB was either shutdown, or crashed
2096 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2098 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2100 [tempArray addObject:tempObject];
2104 [QueueFileArray removeObjectsInArray:tempArray];
2105 [self saveQueueFileItem];
2108 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2109 - (void) clearQueueAllItems
2111 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2113 NSMutableArray *tempArray;
2114 tempArray = [NSMutableArray array];
2115 /* we look here to see if the preset is we move on to the next one */
2116 while ( tempObject = [enumerator nextObject] )
2118 [tempArray addObject:tempObject];
2121 [QueueFileArray removeObjectsInArray:tempArray];
2122 [self saveQueueFileItem];
2125 /* This method will duplicate prepareJob however into the
2126 * queue .plist instead of into the job structure so it can
2127 * be recalled later */
2128 - (NSDictionary *)createQueueFileItem
2130 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2132 hb_list_t * list = hb_get_titles( fHandle );
2133 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2134 [fSrcTitlePopUp indexOfSelectedItem] );
2135 hb_job_t * job = title->job;
2139 /* We use a number system to set the encode status of the queue item
2140 * 0 == already encoded
2141 * 1 == is being encoded
2142 * 2 == is yet to be encoded
2145 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2146 /* Source and Destination Information */
2148 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2149 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2150 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2151 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2153 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2154 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2156 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2158 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2160 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2162 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2164 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2166 /* Chapter encode info */
2167 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2168 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2169 /* Time (pts) encode info */
2170 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2171 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2172 /* Frame number encode info */
2173 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2174 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2177 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2178 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2179 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2181 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2183 /* Lets get the preset info if there is any */
2184 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2185 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2187 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2188 /* Chapter Markers*/
2189 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2190 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2192 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2196 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2199 /* We need to get the list of chapter names to put into an array and store
2200 * in our queue, so they can be reapplied in prepareJob when this queue
2201 * item comes up if Chapter Markers is set to on.
2204 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2205 int chaptercount = hb_list_count( fTitle->list_chapter );
2206 for( i = 0; i < chaptercount; i++ )
2208 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2209 if( chapter != NULL )
2211 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2214 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2215 [ChapterNamesArray autorelease];
2217 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2218 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2219 /* Mux mp4 with http optimization */
2220 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2221 /* Add iPod uuid atom */
2222 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2226 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2227 /* x264 Option String */
2228 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2230 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2231 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2232 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2233 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2235 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2236 [queueFileJob setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
2238 /* 2 Pass Encoding */
2239 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2240 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2241 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2243 /* Picture Sizing */
2244 /* Use Max Picture settings for whatever the dvd is.*/
2245 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2246 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2247 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2248 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2249 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2250 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2251 /* if we are custom anamorphic, store the exact storage, par and display dims */
2252 if (fTitle->job->anamorphic.mode == 3)
2254 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2256 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2257 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2259 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2260 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2262 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2263 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2266 NSString * pictureSummary;
2267 pictureSummary = [fPictureSizeField stringValue];
2268 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2269 /* Set crop settings here */
2270 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2271 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2272 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2273 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2274 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2276 /* Picture Filters */
2277 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2278 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2280 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2281 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2282 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2284 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2285 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2287 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2288 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2290 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2292 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2295 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2297 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2298 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2299 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2300 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2301 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2302 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2303 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2305 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2307 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2308 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2309 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2310 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2311 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2312 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2313 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2315 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2317 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2318 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2319 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2320 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2321 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2322 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2323 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2325 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2327 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2328 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2329 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2330 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2331 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2332 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2333 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2337 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2338 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2339 [subtitlesArray autorelease];
2341 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2343 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2345 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2348 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2352 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2355 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2356 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2357 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2359 /* Picture Sizing */
2360 /* Use Max Picture settings for whatever the dvd is.*/
2361 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2362 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2363 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2364 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2365 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2367 /* Set crop settings here */
2368 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2369 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2370 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2371 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2372 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2376 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2378 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2379 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2380 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2381 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2383 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2385 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2386 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2387 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2388 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2390 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2392 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2393 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2394 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2395 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2397 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2399 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2400 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2401 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2402 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2405 /* we need to auto relase the queueFileJob and return it */
2406 [queueFileJob autorelease];
2407 return queueFileJob;
2411 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2412 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2414 NSUInteger index = [indexSet lastIndex];
2415 NSUInteger aboveInsertIndexCount = 0;
2418 NSUInteger removeIndex;
2420 if (index >= insertIndex)
2422 removeIndex = index + aboveInsertIndexCount;
2423 aboveInsertIndexCount++;
2427 removeIndex = index;
2431 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2432 [QueueFileArray removeObjectAtIndex:removeIndex];
2433 [QueueFileArray insertObject:object atIndex:insertIndex];
2436 index = [indexSet indexLessThanIndex:index];
2438 /* We save all of the Queue data here
2439 * and it also gets sent back to the queue controller*/
2440 [self saveQueueFileItem];
2446 #pragma mark Queue Job Processing
2448 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2450 /* Mark the encode just finished as done (status 0)*/
2451 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2453 /* We save all of the Queue data here */
2454 [self saveQueueFileItem];
2456 /* Since we have now marked a queue item as done
2457 * we can go ahead and increment currentQueueEncodeIndex
2458 * so that if there is anything left in the queue we can
2459 * go ahead and move to the next item if we want to */
2460 int queueItems = [QueueFileArray count];
2461 /* Check to see if there are any more pending items in the queue */
2462 int newQueueItemIndex = [self getNextPendingQueueIndex];
2463 /* If we still have more pending items in our queue, lets go to the next one */
2464 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
2466 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
2467 currentQueueEncodeIndex = newQueueItemIndex;
2468 /* now we mark the queue item as Status = 1 ( being encoded ) so another instance can not come along and try to scan it while we are scanning */
2469 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2470 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
2471 [self saveQueueFileItem];
2472 /* now we can go ahead and scan the new pending queue item */
2473 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2478 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
2482 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2483 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2485 /* Tell HB to output a new activity log file for this encode */
2486 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2488 /* We now flag the queue item as being owned by this instance of HB using the PID */
2489 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:pidNum] forKey:@"EncodingPID"];
2490 /* Get the currentQueueEncodeNameString from the queue item to display in the status field */
2491 currentQueueEncodeNameString = [[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"] lastPathComponent]retain];
2492 /* We save all of the Queue data here */
2493 [self saveQueueFileItem];
2495 /* use a bool to determine whether or not we can decrypt using vlc */
2496 BOOL cancelScanDecrypt = 0;
2497 /* set the bool so that showNewScan knows to apply the appropriate queue
2498 * settings as this is a queue rescan
2500 NSString *path = scanPath;
2501 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2503 if( [detector isVideoDVD] )
2505 // The chosen path was actually on a DVD, so use the raw block
2506 // device path instead.
2507 path = [detector devicePath];
2508 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2510 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2511 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
2514 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2515 cancelScanDecrypt = 1;
2516 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2518 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");
2519 [NSApp requestUserAttention:NSCriticalRequest];
2521 if (status == NSAlertDefaultReturn)
2523 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2524 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2526 else if (status == NSAlertAlternateReturn)
2528 /* User chose to cancel the scan */
2529 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2533 /* 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 */
2534 cancelScanDecrypt = 0;
2535 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2541 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2543 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2547 if (cancelScanDecrypt == 0)
2549 /* we actually pass the scan off to libhb here */
2550 /* If there is no title number passed to scan, we use "0"
2551 * which causes the default behavior of a full source scan
2557 if (scanTitleNum > 0)
2559 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2562 /* We use our advance pref to determine how many previews to scan */
2563 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2564 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2568 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2569 - (void) processNewQueueEncode
2571 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2572 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2573 hb_job_t * job = title->job;
2575 if( !hb_list_count( list ) )
2577 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2580 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2581 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2582 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2583 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2587 * If scanning we need to do some extra setup of the job.
2589 if( job->indepth_scan == 1 )
2594 * When subtitle scan is enabled do a fast pre-scan job
2595 * which will determine which subtitles to enable, if any.
2598 x264opts_tmp = job->x264opts;
2600 job->x264opts = NULL;
2602 job->indepth_scan = 1;
2606 * Add the pre-scan job
2608 hb_add( fQueueEncodeLibhb, job );
2609 job->x264opts = x264opts_tmp;
2613 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2615 job->indepth_scan = 0;
2621 hb_add( fQueueEncodeLibhb, job );
2625 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2626 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2628 hb_add( fQueueEncodeLibhb, job );
2633 job->indepth_scan = 0;
2636 hb_add( fQueueEncodeLibhb, job );
2639 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2640 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2641 /* Lets mark our new encode as 1 or "Encoding" */
2642 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2643 [self saveQueueFileItem];
2645 /* we need to clean up the subtitle tracks after the job(s) have been set */
2646 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2648 for(ii = 0; ii < num_subtitle_tracks; ii++)
2650 hb_subtitle_t * subtitle;
2651 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2654 hb_list_rem(job->list_subtitle, subtitle);
2658 /* We should be all setup so let 'er rip */
2665 #pragma mark Queue Item Editing
2667 /* Rescans the chosen queue item back into the main window */
2668 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2670 fqueueEditRescanItemNum = selectedQueueItem;
2671 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2672 applyQueueToScan = YES;
2673 /* Set the browsedSourceDisplayName for showNewScan */
2674 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2675 [self performScan:scanPath scanTitleNum:scanTitleNum];
2679 /* We use this method after a queue item rescan for edit.
2680 * it largely mirrors -selectPreset in terms of structure.
2681 * Assumes that a queue item has been reloaded into the main window.
2683 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2685 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2686 hb_job_t * job = fTitle->job;
2689 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2691 /* Set title number and chapters */
2692 /* since the queue only scans a single title, its already been selected in showNewScan
2693 so do not try to reset it here. However if we do decide to do full source scans on
2694 a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2695 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2697 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2698 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2701 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2702 [self formatPopUpChanged:nil];
2704 /* Chapter Markers*/
2705 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2706 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2707 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2708 /* Mux mp4 with http optimization */
2709 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2712 /* We set the advanced opt string here if applicable*/
2713 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2714 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2716 /* Lets run through the following functions to get variables set there */
2717 [self videoEncoderPopUpChanged:nil];
2718 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2719 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2720 [self calculateBitrate:nil];
2723 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2725 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2726 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2727 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2728 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2729 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2730 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2731 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2732 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2734 /* For the quality slider we need to convert the old percent's to the new rf scales */
2735 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2736 [fVidQualitySlider setFloatValue:rf];
2741 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2742 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2744 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2748 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2749 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2753 [self videoMatrixChanged:nil];
2755 /* Video framerate */
2756 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2757 detected framerate in the fVidRatePopUp so we use index 0*/
2758 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2760 [fVidRatePopUp selectItemAtIndex: 0];
2764 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2767 /* 2 Pass Encoding */
2768 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2769 [self twoPassCheckboxChanged:nil];
2770 /* Turbo 1st pass for 2 Pass Encoding */
2771 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2776 /* Now lets add our new tracks to the audio list here */
2777 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2779 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2780 [self audioTrackPopUpChanged: fAudLang1PopUp];
2781 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2782 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2784 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2786 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2787 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2789 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2790 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2794 [fAudLang1PopUp selectItemAtIndex: 0];
2795 [self audioTrackPopUpChanged: fAudLang1PopUp];
2797 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2799 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2800 [self audioTrackPopUpChanged: fAudLang2PopUp];
2801 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2802 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2804 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2806 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2807 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2809 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2810 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2814 [fAudLang2PopUp selectItemAtIndex: 0];
2815 [self audioTrackPopUpChanged: fAudLang2PopUp];
2817 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2819 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2820 [self audioTrackPopUpChanged: fAudLang3PopUp];
2821 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2822 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2824 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2826 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2827 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2829 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2830 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2834 [fAudLang3PopUp selectItemAtIndex: 0];
2835 [self audioTrackPopUpChanged: fAudLang3PopUp];
2837 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2839 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2840 [self audioTrackPopUpChanged: fAudLang4PopUp];
2841 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2842 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2844 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2846 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2847 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2849 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2850 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2854 [fAudLang4PopUp selectItemAtIndex: 0];
2855 [self audioTrackPopUpChanged: fAudLang4PopUp];
2859 /* Crashy crashy right now, working on it */
2860 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2861 [fSubtitlesTable reloadData];
2862 /* Picture Settings */
2864 /* If Cropping is set to custom, then recall all four crop values from
2865 when the preset was created and apply them */
2866 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2868 [fPictureController setAutoCrop:NO];
2870 /* Here we use the custom crop values saved at the time the preset was saved */
2871 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2872 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2873 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2874 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2877 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2879 [fPictureController setAutoCrop:YES];
2880 /* Here we use the auto crop values determined right after scan */
2881 job->crop[0] = AutoCropTop;
2882 job->crop[1] = AutoCropBottom;
2883 job->crop[2] = AutoCropLeft;
2884 job->crop[3] = AutoCropRight;
2888 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2890 /* we check to make sure the presets width/height does not exceed the sources width/height */
2891 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2893 /* if so, then we use the sources height and width to avoid scaling up */
2894 //job->width = fTitle->width;
2895 //job->height = fTitle->height;
2896 [self revertPictureSizeToMax:nil];
2898 else // source width/height is >= the preset height/width
2900 /* we can go ahead and use the presets values for height and width */
2901 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2902 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2904 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2905 if (job->keep_ratio == 1)
2907 hb_fix_aspect( job, HB_KEEP_WIDTH );
2908 if( job->height > fTitle->height )
2910 job->height = fTitle->height;
2911 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2914 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2915 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2919 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2920 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2921 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2924 [fPictureController setUseDecomb:1];
2925 [fPictureController setDecomb:0];
2926 [fPictureController setDeinterlace:0];
2927 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2929 /* we are using decomb */
2931 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2933 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2935 /* if we are using "Custom" in the decomb setting, also set the custom string*/
2936 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
2938 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
2944 /* We are using Deinterlace */
2946 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
2948 [fPictureController setUseDecomb:0];
2949 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2950 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
2951 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
2953 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
2960 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
2962 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2963 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
2964 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
2966 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
2971 [fPictureController setDetelecine:0];
2975 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
2977 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2978 /* if we are using "Custom" in the denoise setting, also set the custom string*/
2979 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
2981 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
2986 [fPictureController setDenoise:0];
2990 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
2992 /* if its a one, then its the old on/off deblock, set on to 5*/
2993 [fPictureController setDeblock:5];
2997 /* use the settings intValue */
2998 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
3001 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
3003 [fPictureController setGrayscale:1];
3007 [fPictureController setGrayscale:0];
3010 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
3011 [fPictureController SetTitle:fTitle];
3012 [self calculatePictureSizing:nil];
3014 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
3015 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
3016 //[queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
3017 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
3019 /* Deselect the currently selected Preset if there is one*/
3020 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
3021 //[self selectPreset:nil];
3023 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
3024 /* Change UI to show "Custom" settings are being used */
3025 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
3027 curUserPresetChosenNum = nil;
3031 /* Deselect the currently selected Preset if there is one*/
3032 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
3033 /* Change UI to show "Custom" settings are being used */
3034 [fPresetSelectedDisplay setStringValue: @"Custom"];
3036 //curUserPresetChosenNum = nil;
3039 /* We need to set this bool back to NO, in case the user wants to do a scan */
3040 //applyQueueToScan = NO;
3042 /* Not that source is loaded and settings applied, delete the queue item from the queue */
3043 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
3044 [self removeQueueFileItem:fqueueEditRescanItemNum];
3050 #pragma mark Live Preview
3051 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3052 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3055 - (void) prepareJobForPreview
3057 hb_list_t * list = hb_get_titles( fHandle );
3058 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3059 [fSrcTitlePopUp indexOfSelectedItem] );
3060 hb_job_t * job = title->job;
3061 hb_audio_config_t * audio;
3062 /* set job->angle for libdvdnav */
3063 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3064 /* Chapter selection */
3065 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3066 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3068 /* Format (Muxer) and Video Encoder */
3069 job->mux = [[fDstFormatPopUp selectedItem] tag];
3070 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3072 job->chapter_markers = 0;
3074 if( job->vcodec & HB_VCODEC_X264 )
3077 /* Below Sends x264 options to the core library if x264 is selected*/
3078 /* Lets use this as per Nyx, Thanks Nyx!*/
3079 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3080 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3081 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3086 /* Video settings */
3087 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3088 * and detelecine is on, so we handle that in the logic below
3091 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3093 /* a specific framerate has been chosen */
3094 job->vrate = 27000000;
3095 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3096 /* We are not same as source so we set job->cfr to 1
3097 * to enable constant frame rate since user has specified
3098 * a specific framerate*/
3099 if ([fFrameratePfrCheck state] == 1)
3110 /* We are same as source (variable) */
3111 job->vrate = title->rate;
3112 job->vrate_base = title->rate_base;
3113 /* We are same as source so we set job->cfr to 0
3114 * to enable true same as source framerate */
3116 /* If we are same as source and we have detelecine on, we need to turn on
3119 if ([fPictureController detelecine] == 1)
3125 switch( [fVidQualityMatrix selectedRow] )
3129 Bitrate should already have been calculated and displayed
3130 in fVidBitrateField, so let's just use it */
3132 job->vquality = -1.0;
3133 job->vbitrate = [fVidBitrateField intValue];
3136 job->vquality = [fVidQualityRFField floatValue];
3141 /* Subtitle settings */
3142 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3149 bool one_burned = FALSE;
3152 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3154 while (tempObject = [enumerator nextObject])
3157 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3158 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3159 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3160 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3162 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3163 * we want to ignore it for display as well as encoding.
3167 /* if i is 0, then we are in the first item of the subtitles which we need to
3168 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3169 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3172 /* if we are on the first track and using "Foreign Audio Search" */
3173 if (i == 0 && subtitle == 1)
3175 /* NOTE: Currently foreign language search is borked for preview.
3176 * Commented out but left in for initial commit. */
3179 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3181 job->indepth_scan = 1;
3185 job->select_subtitle_config.dest = PASSTHRUSUB;
3189 job->select_subtitle_config.dest = RENDERSUB;
3192 job->select_subtitle_config.force = force;
3193 job->select_subtitle_config.default_track = def;
3198 /* for the actual source tracks, we must subtract the non source entries so
3199 * that the menu index matches the source subtitle_list index for convenience */
3202 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3203 * Foreign Language Search is 1) so subtract 2 */
3204 subtitle = subtitle - 2;
3208 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3211 subtitle = subtitle - 1;
3214 /* We are setting a source subtitle so access the source subtitle info */
3215 hb_subtitle_t * subt;
3217 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3219 /* if we are getting the subtitles from an external srt file */
3220 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3222 hb_subtitle_config_t sub_config;
3224 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3226 /* we need to srncpy file path and char code */
3227 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3228 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3230 sub_config.force = 0;
3231 sub_config.dest = PASSTHRUSUB;
3232 sub_config.default_track = def;
3234 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3239 hb_subtitle_config_t sub_config = subt->config;
3241 if ( !burned && subt->format == PICTURESUB )
3243 sub_config.dest = PASSTHRUSUB;
3245 else if ( burned && subt->format == PICTURESUB )
3247 // Only allow one subtitle to be burned into the video
3252 sub_config.force = force;
3253 sub_config.default_track = def;
3254 hb_subtitle_add( job, &sub_config, subtitle );
3264 [subtitlesArray autorelease];
3267 /* Audio tracks and mixdowns */
3268 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3269 int audiotrack_count = hb_list_count(job->list_audio);
3270 for( int i = 0; i < audiotrack_count;i++)
3272 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3273 hb_list_rem(job->list_audio, temp_audio);
3275 /* Now lets add our new tracks to the audio list here */
3276 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3278 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3279 hb_audio_config_init(audio);
3280 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3281 /* We go ahead and assign values to our audio->out.<properties> */
3282 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3283 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3284 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3285 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3286 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3287 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3289 hb_audio_add( job, audio );
3292 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3294 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3295 hb_audio_config_init(audio);
3296 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3297 /* We go ahead and assign values to our audio->out.<properties> */
3298 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3299 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3300 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3301 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3302 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3303 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3305 hb_audio_add( job, audio );
3310 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3312 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3313 hb_audio_config_init(audio);
3314 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3315 /* We go ahead and assign values to our audio->out.<properties> */
3316 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3317 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3318 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3319 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3320 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3321 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3323 hb_audio_add( job, audio );
3328 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3330 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3331 hb_audio_config_init(audio);
3332 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3333 /* We go ahead and assign values to our audio->out.<properties> */
3334 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3335 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3336 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3337 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3338 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3339 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3341 hb_audio_add( job, audio );
3350 /* Though Grayscale is not really a filter, per se
3351 * we put it here since its in the filters panel
3354 if ([fPictureController grayscale])
3363 /* Initialize the filters list */
3364 job->filters = hb_list_init();
3366 /* Now lets call the filters if applicable.
3367 * The order of the filters is critical
3371 hb_filter_detelecine.settings = NULL;
3372 if ([fPictureController detelecine] == 1)
3374 /* use a custom detelecine string */
3375 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3376 hb_list_add( job->filters, &hb_filter_detelecine );
3378 if ([fPictureController detelecine] == 2)
3381 hb_list_add( job->filters, &hb_filter_detelecine );
3386 if ([fPictureController useDecomb] == 1)
3389 /* we add the custom string if present */
3390 hb_filter_decomb.settings = NULL;
3391 if ([fPictureController decomb] == 1)
3393 /* use a custom decomb string */
3394 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3395 hb_list_add( job->filters, &hb_filter_decomb );
3397 if ([fPictureController decomb] == 2)
3399 /* Run old deinterlacer fd by default */
3400 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3401 hb_list_add( job->filters, &hb_filter_decomb );
3408 if ([fPictureController deinterlace] == 1)
3410 /* we add the custom string if present */
3411 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3412 hb_list_add( job->filters, &hb_filter_deinterlace );
3414 else if ([fPictureController deinterlace] == 2)
3416 /* Run old deinterlacer fd by default */
3417 hb_filter_deinterlace.settings = "-1";
3418 hb_list_add( job->filters, &hb_filter_deinterlace );
3420 else if ([fPictureController deinterlace] == 3)
3422 /* Yadif mode 0 (without spatial deinterlacing.) */
3423 hb_filter_deinterlace.settings = "2";
3424 hb_list_add( job->filters, &hb_filter_deinterlace );
3426 else if ([fPictureController deinterlace] == 4)
3428 /* Yadif (with spatial deinterlacing) */
3429 hb_filter_deinterlace.settings = "0";
3430 hb_list_add( job->filters, &hb_filter_deinterlace );
3436 if ([fPictureController denoise] == 1) // custom in popup
3438 /* we add the custom string if present */
3439 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3440 hb_list_add( job->filters, &hb_filter_denoise );
3442 else if ([fPictureController denoise] == 2) // Weak in popup
3444 hb_filter_denoise.settings = "2:1:2:3";
3445 hb_list_add( job->filters, &hb_filter_denoise );
3447 else if ([fPictureController denoise] == 3) // Medium in popup
3449 hb_filter_denoise.settings = "3:2:2:3";
3450 hb_list_add( job->filters, &hb_filter_denoise );
3452 else if ([fPictureController denoise] == 4) // Strong in popup
3454 hb_filter_denoise.settings = "7:7:5:5";
3455 hb_list_add( job->filters, &hb_filter_denoise );
3459 /* Deblock (uses pp7 default) */
3460 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3461 * the macgui's purposes a value of 0 actually means to not even use the filter
3462 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3464 if ([fPictureController deblock] != 0)
3466 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3467 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3468 hb_list_add( job->filters, &hb_filter_deblock );
3475 #pragma mark Job Handling
3481 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3482 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3483 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3484 hb_job_t * job = title->job;
3485 hb_audio_config_t * audio;
3486 /* Title Angle for dvdnav */
3487 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3489 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3491 /* Chapter selection */
3492 [self writeToActivityLog: "Start / Stop set to chapters"];
3493 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3494 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3496 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3498 /* we are pts based start / stop */
3499 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3501 /* Point A to Point B. Time to time in seconds.*/
3502 /* get the start seconds from the start seconds field */
3503 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3504 job->pts_to_start = start_seconds * 90000LL;
3505 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3506 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3507 job->pts_to_stop = stop_seconds * 90000LL;
3510 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3512 /* we are frame based start / stop */
3513 [self writeToActivityLog: "Start / Stop set to frames ..."];
3515 /* Point A to Point B. Frame to frame */
3516 /* get the start frame from the start frame field */
3517 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3518 job->frame_to_start = start_frame;
3519 /* get the frame to stop on from the end frame field */
3520 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3521 job->frame_to_stop = stop_frame;
3528 /* Format (Muxer) and Video Encoder */
3529 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3530 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3533 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3534 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3536 job->largeFileSize = 1;
3540 job->largeFileSize = 0;
3542 /* We set http optimized mp4 here */
3543 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3545 job->mp4_optimize = 1;
3549 job->mp4_optimize = 0;
3553 /* We set the chapter marker extraction here based on the format being
3554 mpeg4 or mkv and the checkbox being checked */
3555 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3557 job->chapter_markers = 1;
3559 /* now lets get our saved chapter names out the array in the queue file
3560 * and insert them back into the title chapter list. We have it here,
3561 * because unless we are inserting chapter markers there is no need to
3562 * spend the overhead of iterating through the chapter names array imo
3563 * Also, note that if for some reason we don't apply chapter names, the
3564 * chapters just come out 001, 002, etc. etc.
3567 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3569 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3571 while (tempObject = [enumerator nextObject])
3573 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3574 if( chapter != NULL )
3576 strncpy( chapter->title, [tempObject UTF8String], 1023);
3577 chapter->title[1023] = '\0';
3584 job->chapter_markers = 0;
3587 if( job->vcodec & HB_VCODEC_X264 )
3589 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3599 /* Below Sends x264 options to the core library if x264 is selected*/
3600 /* Lets use this as per Nyx, Thanks Nyx!*/
3601 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3602 /* Turbo first pass if two pass and Turbo First pass is selected */
3603 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3605 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3606 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3607 /* append the "Turbo" string variable to the existing opts string.
3608 Note: the "Turbo" string must be appended, not prepended to work properly*/
3609 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3610 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3614 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3620 /* Picture Size Settings */
3621 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3622 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3624 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3625 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3626 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3627 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3629 /* insert our custom values here for capuj */
3630 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3631 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3633 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3635 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3636 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3638 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3639 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3642 /* Here we use the crop values saved at the time the preset was saved */
3643 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3644 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3645 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3646 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3648 /* Video settings */
3651 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3652 * and detelecine is on, so we handle that in the logic below
3655 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3657 /* a specific framerate has been chosen */
3658 job->vrate = 27000000;
3659 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3660 /* We are not same as source so we set job->cfr to 1
3661 * to enable constant frame rate since user has specified
3662 * a specific framerate*/
3664 if ([[queueToApply objectForKey:@"VideoFrameratePFR"] intValue] == 1)
3675 /* We are same as source (variable) */
3676 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3677 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3678 /* We are same as source so we set job->cfr to 0
3679 * to enable true same as source framerate */
3681 /* If we are same as source and we have detelecine on, we need to turn on
3684 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3690 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3693 Bitrate should already have been calculated and displayed
3694 in fVidBitrateField, so let's just use it same as abr*/
3695 job->vquality = -1.0;
3696 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3698 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3700 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3705 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3710 #pragma mark Process Subtitles to libhb
3712 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3713 * which means that we need to account for the offset of non source language settings in from
3714 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3715 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3716 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3717 * to the source tracks position in title->list_subtitle.
3724 bool one_burned = FALSE;
3727 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3729 while (tempObject = [enumerator nextObject])
3732 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3733 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3734 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3735 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3737 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3738 * we want to ignore it for display as well as encoding.
3742 /* if i is 0, then we are in the first item of the subtitles which we need to
3743 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3744 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3747 /* if we are on the first track and using "Foreign Audio Search" */
3748 if (i == 0 && subtitle == 1)
3750 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3752 job->indepth_scan = 1;
3756 job->select_subtitle_config.dest = PASSTHRUSUB;
3760 job->select_subtitle_config.dest = RENDERSUB;
3763 job->select_subtitle_config.force = force;
3764 job->select_subtitle_config.default_track = def;
3769 /* for the actual source tracks, we must subtract the non source entries so
3770 * that the menu index matches the source subtitle_list index for convenience */
3773 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3774 * Foreign Language Search is 1) so subtract 2 */
3775 subtitle = subtitle - 2;
3779 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3782 subtitle = subtitle - 1;
3785 /* We are setting a source subtitle so access the source subtitle info */
3786 hb_subtitle_t * subt;
3788 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3790 /* if we are getting the subtitles from an external srt file */
3791 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3793 hb_subtitle_config_t sub_config;
3795 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3797 /* we need to srncpy file name and codeset */
3798 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3799 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3801 sub_config.force = 0;
3802 sub_config.dest = PASSTHRUSUB;
3803 sub_config.default_track = def;
3805 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3811 hb_subtitle_config_t sub_config = subt->config;
3813 if ( !burned && subt->format == PICTURESUB )
3815 sub_config.dest = PASSTHRUSUB;
3817 else if ( burned && subt->format == PICTURESUB )
3819 // Only allow one subtitle to be burned into the video
3824 sub_config.force = force;
3825 sub_config.default_track = def;
3826 hb_subtitle_add( job, &sub_config, subtitle );
3837 /* Audio tracks and mixdowns */
3838 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3839 int audiotrack_count = hb_list_count(job->list_audio);
3840 for( int i = 0; i < audiotrack_count;i++)
3842 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3843 hb_list_rem(job->list_audio, temp_audio);
3845 /* Now lets add our new tracks to the audio list here */
3846 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3848 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3849 hb_audio_config_init(audio);
3850 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3851 /* We go ahead and assign values to our audio->out.<properties> */
3852 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3853 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3854 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3855 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3856 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3857 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3859 hb_audio_add( job, audio );
3862 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3865 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3866 hb_audio_config_init(audio);
3867 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3868 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3869 /* We go ahead and assign values to our audio->out.<properties> */
3870 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3871 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3872 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3873 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3874 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3875 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3877 hb_audio_add( job, audio );
3881 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3883 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3884 hb_audio_config_init(audio);
3885 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3886 /* We go ahead and assign values to our audio->out.<properties> */
3887 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3888 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3889 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3890 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3891 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3892 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3894 hb_audio_add( job, audio );
3898 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3900 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3901 hb_audio_config_init(audio);
3902 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3903 /* We go ahead and assign values to our audio->out.<properties> */
3904 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3905 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3906 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3907 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3908 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3909 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3911 hb_audio_add( job, audio );
3917 job->filters = hb_list_init();
3919 /* Now lets call the filters if applicable.
3920 * The order of the filters is critical
3923 hb_filter_detelecine.settings = NULL;
3924 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3926 /* use a custom detelecine string */
3927 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3928 hb_list_add( job->filters, &hb_filter_detelecine );
3930 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3932 /* Use libhb's default values */
3933 hb_list_add( job->filters, &hb_filter_detelecine );
3936 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3939 /* we add the custom string if present */
3940 hb_filter_decomb.settings = NULL;
3941 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3943 /* use a custom decomb string */
3944 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3945 hb_list_add( job->filters, &hb_filter_decomb );
3947 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3949 /* Use libhb default */
3950 hb_list_add( job->filters, &hb_filter_decomb );
3958 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3960 /* we add the custom string if present */
3961 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3962 hb_list_add( job->filters, &hb_filter_deinterlace );
3964 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3966 /* Run old deinterlacer fd by default */
3967 hb_filter_deinterlace.settings = "-1";
3968 hb_list_add( job->filters, &hb_filter_deinterlace );
3970 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3972 /* Yadif mode 0 (without spatial deinterlacing.) */
3973 hb_filter_deinterlace.settings = "2";
3974 hb_list_add( job->filters, &hb_filter_deinterlace );
3976 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3978 /* Yadif (with spatial deinterlacing) */
3979 hb_filter_deinterlace.settings = "0";
3980 hb_list_add( job->filters, &hb_filter_deinterlace );
3986 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
3988 /* we add the custom string if present */
3989 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3990 hb_list_add( job->filters, &hb_filter_denoise );
3992 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
3994 hb_filter_denoise.settings = "2:1:2:3";
3995 hb_list_add( job->filters, &hb_filter_denoise );
3997 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
3999 hb_filter_denoise.settings = "3:2:2:3";
4000 hb_list_add( job->filters, &hb_filter_denoise );
4002 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
4004 hb_filter_denoise.settings = "7:7:5:5";
4005 hb_list_add( job->filters, &hb_filter_denoise );
4009 /* Deblock (uses pp7 default) */
4010 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
4011 * the macgui's purposes a value of 0 actually means to not even use the filter
4012 * current hb_filter_deblock.settings valid ranges are from 5 - 15
4014 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
4016 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
4017 hb_list_add( job->filters, &hb_filter_deblock );
4019 [self writeToActivityLog: "prepareJob exiting"];
4024 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
4026 - (IBAction) addToQueue: (id) sender
4028 /* We get the destination directory from the destination field here */
4029 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4030 /* We check for a valid destination here */
4031 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4033 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4040 BOOL fileExistsInQueue;
4041 fileExistsInQueue = NO;
4043 /* We check for and existing file here */
4044 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
4049 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
4051 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
4053 while (tempObject = [enumerator nextObject])
4055 NSDictionary *thisQueueDict = tempObject;
4056 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
4058 fileExistsInQueue = YES;
4064 if(fileExists == YES)
4066 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4067 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4068 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4069 NULL, NULL, [NSString stringWithFormat:
4070 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4071 [fDstFile2Field stringValue]] );
4073 else if (fileExistsInQueue == YES)
4075 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4076 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4077 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4078 NULL, NULL, [NSString stringWithFormat:
4079 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4080 [fDstFile2Field stringValue]] );
4084 [self doAddToQueue];
4088 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4089 the user if they want to overwrite an exiting movie file.
4091 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4092 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4094 if( returnCode == NSAlertAlternateReturn )
4095 [self doAddToQueue];
4098 - (void) doAddToQueue
4100 [self addQueueFileItem ];
4105 /* Rip: puts up an alert before ultimately calling doRip
4107 - (IBAction) Rip: (id) sender
4109 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4110 /* Rip or Cancel ? */
4112 hb_get_state2( fQueueEncodeLibhb, &s );
4114 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4116 [self Cancel: sender];
4120 /* We check to see if we need to warn the user that the computer will go to sleep
4121 or shut down when encoding is finished */
4122 [self remindUserOfSleepOrShutdown];
4124 // If there are pending jobs in the queue, then this is a rip the queue
4125 if (fPendingCount > 0)
4127 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4128 /* here lets start the queue with the first pending item */
4129 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4134 // Before adding jobs to the queue, check for a valid destination.
4136 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4137 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4139 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4143 /* We check for duplicate name here */
4144 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4146 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4147 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4148 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4149 NULL, NULL, [NSString stringWithFormat:
4150 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4151 [fDstFile2Field stringValue]] );
4153 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4157 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4158 otherwise, just rip the queue */
4159 if(fPendingCount == 0)
4161 [self doAddToQueue];
4164 /* go right to processing the new queue encode */
4165 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4166 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4171 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4172 want to overwrite an exiting movie file.
4174 - (void) overWriteAlertDone: (NSWindow *) sheet
4175 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4177 if( returnCode == NSAlertAlternateReturn )
4179 /* if there are no jobs in the queue, then add this one to the queue and rip
4180 otherwise, just rip the queue */
4181 if( fPendingCount == 0 )
4183 [self doAddToQueue];
4186 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4187 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4188 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4193 - (void) remindUserOfSleepOrShutdown
4195 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4197 /*Warn that computer will sleep after encoding*/
4200 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);
4201 [NSApp requestUserAttention:NSCriticalRequest];
4202 if ( reminduser == NSAlertAlternateReturn )
4204 [self showPreferencesWindow:nil];
4207 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4209 /*Warn that computer will shut down after encoding*/
4212 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);
4213 [NSApp requestUserAttention:NSCriticalRequest];
4214 if ( reminduser == NSAlertAlternateReturn )
4216 [self showPreferencesWindow:nil];
4225 /* Let libhb do the job */
4226 hb_start( fQueueEncodeLibhb );
4227 /*set the fEncodeState State */
4232 //------------------------------------------------------------------------------------
4233 // Displays an alert asking user if the want to cancel encoding of current job.
4234 // Cancel: returns immediately after posting the alert. Later, when the user
4235 // acknowledges the alert, doCancelCurrentJob is called.
4236 //------------------------------------------------------------------------------------
4237 - (IBAction)Cancel: (id)sender
4239 if (!fQueueController) return;
4241 hb_pause( fQueueEncodeLibhb );
4242 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4244 // Which window to attach the sheet to?
4245 NSWindow * docWindow;
4246 if ([sender respondsToSelector: @selector(window)])
4247 docWindow = [sender window];
4249 docWindow = fWindow;
4251 NSBeginCriticalAlertSheet(
4253 NSLocalizedString(@"Continue Encoding", nil),
4254 NSLocalizedString(@"Cancel Current and Stop", nil),
4255 NSLocalizedString(@"Cancel Current and Continue", nil),
4257 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4258 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4260 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4263 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4265 hb_resume( fQueueEncodeLibhb );
4266 if (returnCode == NSAlertOtherReturn)
4268 [self doCancelCurrentJob]; // <- this also stops libhb
4270 if (returnCode == NSAlertAlternateReturn)
4272 [self doCancelCurrentJobAndStop];
4276 //------------------------------------------------------------------------------------
4277 // Cancels and deletes the current job and stops libhb from processing the remaining
4279 //------------------------------------------------------------------------------------
4280 - (void) doCancelCurrentJob
4282 // Stop the current job. hb_stop will only cancel the current pass and then set
4283 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4284 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4285 // remaining passes of the job and then start the queue back up if there are any
4289 hb_stop( fQueueEncodeLibhb );
4291 // Delete all remaining jobs since libhb doesn't do this on its own.
4293 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4294 hb_rem( fQueueEncodeLibhb, job );
4296 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4298 // now that we've stopped the currently encoding job, lets mark it as cancelled
4299 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4300 // and as always, save it in the queue .plist...
4301 /* We save all of the Queue data here */
4302 [self saveQueueFileItem];
4304 // ... and see if there are more items left in our queue
4305 int queueItems = [QueueFileArray count];
4306 /* If we still have more items in our queue, lets go to the next one */
4307 /* Check to see if there are any more pending items in the queue */
4308 int newQueueItemIndex = [self getNextPendingQueueIndex];
4309 /* If we still have more pending items in our queue, lets go to the next one */
4310 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
4312 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
4313 currentQueueEncodeIndex = newQueueItemIndex;
4314 /* now we mark the queue item as Status = 1 ( being encoded ) so another instance can not come along and try to scan it while we are scanning */
4315 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
4316 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
4317 [self saveQueueFileItem];
4318 /* now we can go ahead and scan the new pending queue item */
4319 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4324 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
4328 - (void) doCancelCurrentJobAndStop
4330 hb_stop( fQueueEncodeLibhb );
4332 // Delete all remaining jobs since libhb doesn't do this on its own.
4334 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4335 hb_rem( fQueueEncodeLibhb, job );
4338 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4340 // now that we've stopped the currently encoding job, lets mark it as cancelled
4341 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4342 // and as always, save it in the queue .plist...
4343 /* We save all of the Queue data here */
4344 [self saveQueueFileItem];
4345 // so now lets move to
4346 currentQueueEncodeIndex++ ;
4347 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4349 - (IBAction) Pause: (id) sender
4352 hb_get_state2( fQueueEncodeLibhb, &s );
4354 if( s.state == HB_STATE_PAUSED )
4356 hb_resume( fQueueEncodeLibhb );
4360 hb_pause( fQueueEncodeLibhb );
4365 #pragma mark GUI Controls Changed Methods
4367 - (IBAction) titlePopUpChanged: (id) sender
4369 hb_list_t * list = hb_get_titles( fHandle );
4370 hb_title_t * title = (hb_title_t*)
4371 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4373 /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4374 if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4376 /* we set the default name according to the new title->name */
4377 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4378 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4379 [NSString stringWithUTF8String: title->name],
4380 [[fDstFile2Field stringValue] pathExtension]]];
4382 /* Change the source to read out the parent folder also */
4383 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4386 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4387 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4388 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4389 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4390 /* 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 */
4391 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4392 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4393 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4395 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4396 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4398 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4399 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4400 [browsedSourceDisplayName stringByDeletingPathExtension],
4402 [[fDstFile2Field stringValue] pathExtension]]];
4404 /* Update encode start / stop variables */
4408 /* Update chapter popups */
4409 [fSrcChapterStartPopUp removeAllItems];
4410 [fSrcChapterEndPopUp removeAllItems];
4411 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4413 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4414 stringWithFormat: @"%d", i + 1]];
4415 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4416 stringWithFormat: @"%d", i + 1]];
4419 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4420 [fSrcChapterEndPopUp selectItemAtIndex:
4421 hb_list_count( title->list_chapter ) - 1];
4422 [self chapterPopUpChanged:nil];
4424 /* if using dvd nav, show the angle widget */
4425 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4427 [fSrcAngleLabel setHidden:NO];
4428 [fSrcAnglePopUp setHidden:NO];
4430 [fSrcAnglePopUp removeAllItems];
4431 for( int i = 0; i < title->angle_count; i++ )
4433 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4435 [fSrcAnglePopUp selectItemAtIndex: 0];
4439 [fSrcAngleLabel setHidden:YES];
4440 [fSrcAnglePopUp setHidden:YES];
4443 /* Start Get and set the initial pic size for display */
4444 hb_job_t * job = title->job;
4447 /* Set Auto Crop to on upon selecting a new title */
4448 [fPictureController setAutoCrop:YES];
4450 /* We get the originial output picture width and height and put them
4451 in variables for use with some presets later on */
4452 PicOrigOutputWidth = job->width;
4453 PicOrigOutputHeight = job->height;
4454 AutoCropTop = job->crop[0];
4455 AutoCropBottom = job->crop[1];
4456 AutoCropLeft = job->crop[2];
4457 AutoCropRight = job->crop[3];
4459 /* Reset the new title in fPictureController && fPreviewController*/
4460 [fPictureController SetTitle:title];
4463 /* Update Subtitle Table */
4464 [fSubtitlesDelegate resetWithTitle:title];
4465 [fSubtitlesTable reloadData];
4468 /* Update chapter table */
4469 [fChapterTitlesDelegate resetWithTitle:title];
4470 [fChapterTable reloadData];
4472 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4473 int audiotrack_count = hb_list_count(job->list_audio);
4474 for( int i = 0; i < audiotrack_count;i++)
4476 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4477 hb_list_rem(job->list_audio, temp_audio);
4480 /* Update audio popups */
4481 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4482 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4483 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4484 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4485 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4486 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4487 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4488 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4489 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4490 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4492 /* changing the title may have changed the audio channels on offer, */
4493 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4494 [self audioTrackPopUpChanged: fAudLang1PopUp];
4495 [self audioTrackPopUpChanged: fAudLang2PopUp];
4496 [self audioTrackPopUpChanged: fAudLang3PopUp];
4497 [self audioTrackPopUpChanged: fAudLang4PopUp];
4499 [fVidRatePopUp selectItemAtIndex: 0];
4501 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4502 [self calculatePictureSizing:nil];
4504 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4505 [self selectPreset:nil];
4508 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4510 if( [fEncodeStartStopPopUp isEnabled] )
4512 /* We are chapters */
4513 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4515 [fSrcChapterStartPopUp setHidden: NO];
4516 [fSrcChapterEndPopUp setHidden: NO];
4518 [fSrcTimeStartEncodingField setHidden: YES];
4519 [fSrcTimeEndEncodingField setHidden: YES];
4521 [fSrcFrameStartEncodingField setHidden: YES];
4522 [fSrcFrameEndEncodingField setHidden: YES];
4524 [self chapterPopUpChanged:nil];
4526 /* We are time based (seconds) */
4527 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4529 [fSrcChapterStartPopUp setHidden: YES];
4530 [fSrcChapterEndPopUp setHidden: YES];
4532 [fSrcTimeStartEncodingField setHidden: NO];
4533 [fSrcTimeEndEncodingField setHidden: NO];
4535 [fSrcFrameStartEncodingField setHidden: YES];
4536 [fSrcFrameEndEncodingField setHidden: YES];
4538 [self startEndSecValueChanged:nil];
4540 /* We are frame based */
4541 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4543 [fSrcChapterStartPopUp setHidden: YES];
4544 [fSrcChapterEndPopUp setHidden: YES];
4546 [fSrcTimeStartEncodingField setHidden: YES];
4547 [fSrcTimeEndEncodingField setHidden: YES];
4549 [fSrcFrameStartEncodingField setHidden: NO];
4550 [fSrcFrameEndEncodingField setHidden: NO];
4552 [self startEndFrameValueChanged:nil];
4557 - (IBAction) chapterPopUpChanged: (id) sender
4560 /* If start chapter popup is greater than end chapter popup,
4561 we set the end chapter popup to the same as start chapter popup */
4562 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4564 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4568 hb_list_t * list = hb_get_titles( fHandle );
4569 hb_title_t * title = (hb_title_t *)
4570 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4572 hb_chapter_t * chapter;
4573 int64_t duration = 0;
4574 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4575 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4577 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4578 duration += chapter->duration;
4581 duration /= 90000; /* pts -> seconds */
4582 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4583 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4586 [self calculateBitrate: sender];
4588 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4590 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4591 [fCreateChapterMarkers setEnabled: NO];
4592 [fCreateChapterMarkers setState: NSOffState];
4596 [fCreateChapterMarkers setEnabled: YES];
4600 - (IBAction) startEndSecValueChanged: (id) sender
4603 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4604 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4605 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4608 //[self calculateBitrate: sender];
4612 - (IBAction) startEndFrameValueChanged: (id) sender
4614 hb_list_t * list = hb_get_titles( fHandle );
4615 hb_title_t * title = (hb_title_t*)
4616 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4618 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4619 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4620 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4623 //[self calculateBitrate: sender];
4627 - (IBAction) formatPopUpChanged: (id) sender
4629 NSString * string = [fDstFile2Field stringValue];
4630 int format = [fDstFormatPopUp indexOfSelectedItem];
4632 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4633 [fDstMp4LargeFileCheck setHidden: YES];
4634 [fDstMp4HttpOptFileCheck setHidden: YES];
4635 [fDstMp4iPodFileCheck setHidden: YES];
4637 /* Update the Video Codec PopUp */
4638 /* lets get the tag of the currently selected item first so we might reset it later */
4639 int selectedVidEncoderTag;
4640 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4642 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4643 [fVidEncoderPopUp removeAllItems];
4644 NSMenuItem *menuItem;
4645 /* These video encoders are available to all of our current muxers, so lets list them once here */
4646 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4647 [menuItem setTag: HB_VCODEC_FFMPEG];
4652 /*Get Default MP4 File Extension*/
4653 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4661 /* Add additional video encoders here */
4662 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4663 [menuItem setTag: HB_VCODEC_X264];
4664 /* We show the mp4 option checkboxes here since we are mp4 */
4665 [fCreateChapterMarkers setEnabled: YES];
4666 [fDstMp4LargeFileCheck setHidden: NO];
4667 [fDstMp4HttpOptFileCheck setHidden: NO];
4668 [fDstMp4iPodFileCheck setHidden: NO];
4673 /* Add additional video encoders here */
4674 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4675 [menuItem setTag: HB_VCODEC_X264];
4676 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4677 [menuItem setTag: HB_VCODEC_THEORA];
4678 /* We enable the create chapters checkbox here */
4679 [fCreateChapterMarkers setEnabled: YES];
4684 /* tell fSubtitlesDelegate we have a new video container */
4686 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4687 [fSubtitlesTable reloadData];
4688 /* if we have a previously selected vid encoder tag, then try to select it */
4689 if (selectedVidEncoderTag)
4691 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4695 [fVidEncoderPopUp selectItemAtIndex: 0];
4698 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4699 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4700 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4701 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4704 [self autoSetM4vExtension: sender];
4706 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4708 if( SuccessfulScan )
4710 /* Add/replace to the correct extension */
4711 [self audioTrackPopUpChanged: fAudLang1PopUp];
4712 [self audioTrackPopUpChanged: fAudLang2PopUp];
4713 [self audioTrackPopUpChanged: fAudLang3PopUp];
4714 [self audioTrackPopUpChanged: fAudLang4PopUp];
4716 if( [fVidEncoderPopUp selectedItem] == nil )
4719 [fVidEncoderPopUp selectItemAtIndex:0];
4720 [self videoEncoderPopUpChanged:nil];
4722 /* changing the format may mean that we can / can't offer mono or 6ch, */
4723 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4725 /* We call the method to properly enable/disable turbo 2 pass */
4726 [self twoPassCheckboxChanged: sender];
4727 /* We call method method to change UI to reflect whether a preset is used or not*/
4730 [self customSettingUsed: sender];
4733 - (IBAction) autoSetM4vExtension: (id) sender
4735 if ( [fDstFormatPopUp indexOfSelectedItem] )
4738 NSString * extension = @"mp4";
4740 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4741 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4742 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4743 [fCreateChapterMarkers state] == NSOnState ||
4744 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4749 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4752 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4753 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4756 /* Method to determine if we should change the UI
4757 To reflect whether or not a Preset is being used or if
4758 the user is using "Custom" settings by determining the sender*/
4759 - (IBAction) customSettingUsed: (id) sender
4761 if ([sender stringValue])
4763 /* Deselect the currently selected Preset if there is one*/
4764 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4765 /* Change UI to show "Custom" settings are being used */
4766 [fPresetSelectedDisplay setStringValue: @"Custom"];
4768 curUserPresetChosenNum = nil;
4770 [self calculateBitrate:nil];
4775 #pragma mark - Video
4777 - (IBAction) videoEncoderPopUpChanged: (id) sender
4779 hb_job_t * job = fTitle->job;
4780 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4782 [fAdvancedOptions setHidden:YES];
4783 /* If we are using x264 then show the x264 advanced panel*/
4784 if (videoEncoder == HB_VCODEC_X264)
4786 [fAdvancedOptions setHidden:NO];
4787 [self autoSetM4vExtension: sender];
4790 if (videoEncoder == HB_VCODEC_FFMPEG)
4792 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4793 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4794 anything other than MP4.
4796 [fDstMp4iPodFileCheck setEnabled: NO];
4797 [fDstMp4iPodFileCheck setState: NSOffState];
4801 [fDstMp4iPodFileCheck setEnabled: YES];
4803 [self setupQualitySlider];
4804 [self calculatePictureSizing: sender];
4805 [self twoPassCheckboxChanged: sender];
4809 - (IBAction) twoPassCheckboxChanged: (id) sender
4811 /* check to see if x264 is chosen */
4812 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4814 if( [fVidTwoPassCheck state] == NSOnState)
4816 [fVidTurboPassCheck setHidden: NO];
4820 [fVidTurboPassCheck setHidden: YES];
4821 [fVidTurboPassCheck setState: NSOffState];
4823 /* Make sure Two Pass is checked if Turbo is checked */
4824 if( [fVidTurboPassCheck state] == NSOnState)
4826 [fVidTwoPassCheck setState: NSOnState];
4831 [fVidTurboPassCheck setHidden: YES];
4832 [fVidTurboPassCheck setState: NSOffState];
4835 /* We call method method to change UI to reflect whether a preset is used or not*/
4836 [self customSettingUsed: sender];
4839 - (IBAction ) videoFrameRateChanged: (id) sender
4841 /* Hide and set the PFR Checkbox to OFF if we are set to Same as Source */
4842 if ([fVidRatePopUp indexOfSelectedItem] == 0)
4844 [fFrameratePfrCheck setHidden:YES];
4845 [fFrameratePfrCheck setState:0];
4849 [fFrameratePfrCheck setHidden:NO];
4852 /* We call method method to calculatePictureSizing to error check detelecine*/
4853 [self calculatePictureSizing: sender];
4855 /* We call method method to change UI to reflect whether a preset is used or not*/
4856 [self customSettingUsed: sender];
4858 - (IBAction) videoMatrixChanged: (id) sender;
4860 bool target, bitrate, quality;
4862 target = bitrate = quality = false;
4863 if( [fVidQualityMatrix isEnabled] )
4865 switch( [fVidQualityMatrix selectedRow] )
4878 [fVidTargetSizeField setEnabled: target];
4879 [fVidBitrateField setEnabled: bitrate];
4880 [fVidQualitySlider setEnabled: quality];
4881 [fVidQualityRFField setEnabled: quality];
4882 [fVidQualityRFLabel setEnabled: quality];
4883 [fVidTwoPassCheck setEnabled: !quality &&
4884 [fVidQualityMatrix isEnabled]];
4887 [fVidTwoPassCheck setState: NSOffState];
4888 [fVidTurboPassCheck setHidden: YES];
4889 [fVidTurboPassCheck setState: NSOffState];
4892 [self qualitySliderChanged: sender];
4893 [self calculateBitrate: sender];
4894 [self customSettingUsed: sender];
4897 /* Use this method to setup the quality slider for cq/rf values depending on
4898 * the video encoder selected.
4900 - (void) setupQualitySlider
4902 /* Get the current slider maxValue to check for a change in slider scale later
4903 * so that we can choose a new similar value on the new slider scale */
4904 float previousMaxValue = [fVidQualitySlider maxValue];
4905 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4906 NSString * qpRFLabelString = @"QP:";
4908 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4910 [fVidQualitySlider setMinValue:0.0];
4911 [fVidQualitySlider setMaxValue:51.0];
4912 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4913 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4914 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4915 qpRFLabelString = @"RF:";
4918 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
4920 [fVidQualitySlider setMinValue:1.0];
4921 [fVidQualitySlider setMaxValue:31.0];
4922 [fVidQualitySlider setNumberOfTickMarks:31];
4925 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4927 [fVidQualitySlider setMinValue:0.0];
4928 [fVidQualitySlider setMaxValue:63.0];
4929 [fVidQualitySlider setNumberOfTickMarks:64];
4931 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4933 /* check to see if we have changed slider scales */
4934 if (previousMaxValue != [fVidQualitySlider maxValue])
4936 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4937 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4938 [fVidQualitySlider setFloatValue:rf];
4941 [self qualitySliderChanged:nil];
4944 - (IBAction) qualitySliderChanged: (id) sender
4946 /* Our constant quality slider is in a range based
4947 * on each encoders qp/rf values. The range depends
4948 * on the encoder. Also, the range is inverse of quality
4949 * for all of the encoders *except* for theora
4950 * (ie. as the "quality" goes up, the cq or rf value
4951 * actually goes down). Since the IB sliders always set
4952 * their max value at the right end of the slider, we
4953 * will calculate the inverse, so as the slider floatValue
4954 * goes up, we will show the inverse in the rf field
4955 * so, the floatValue at the right for x264 would be 51
4956 * and our rf field needs to show 0 and vice versa.
4959 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4960 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4961 //float sliderRfToPercent;
4962 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4964 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4968 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4970 [self customSettingUsed: sender];
4973 - (void) controlTextDidChange: (NSNotification *) notification
4975 [self calculateBitrate:nil];
4978 - (IBAction) calculateBitrate: (id) sender
4980 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4985 hb_list_t * list = hb_get_titles( fHandle );
4986 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4987 [fSrcTitlePopUp indexOfSelectedItem] );
4988 hb_job_t * job = title->job;
4989 hb_audio_config_t * audio;
4990 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4991 * Target Size Field, we also need the job info for the Muxer, the Chapters
4992 * as well as all of the audio track info.
4993 * This used to be accomplished by simply calling prepareJob here, however
4994 * since the resilient queue sets the queue array values instead of the job
4995 * values directly, we duplicate the old prepareJob code here for the variables
4998 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4999 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
5000 job->mux = [[fDstFormatPopUp selectedItem] tag];
5002 /* Audio goes here */
5003 int audiotrack_count = hb_list_count(job->list_audio);
5004 for( int i = 0; i < audiotrack_count;i++)
5006 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
5007 hb_list_rem(job->list_audio, temp_audio);
5009 /* Now we need our audio info here for each track if applicable */
5010 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
5012 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5013 hb_audio_config_init(audio);
5014 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5015 /* We go ahead and assign values to our audio->out.<properties> */
5016 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
5017 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
5018 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
5019 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
5020 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
5021 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
5023 hb_audio_add( job, audio );
5026 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
5028 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5029 hb_audio_config_init(audio);
5030 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5031 /* We go ahead and assign values to our audio->out.<properties> */
5032 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
5033 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
5034 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
5035 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
5036 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
5037 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
5039 hb_audio_add( job, audio );
5044 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
5046 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5047 hb_audio_config_init(audio);
5048 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5049 /* We go ahead and assign values to our audio->out.<properties> */
5050 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
5051 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
5052 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
5053 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
5054 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
5055 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
5057 hb_audio_add( job, audio );
5062 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
5064 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
5065 hb_audio_config_init(audio);
5066 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5067 /* We go ahead and assign values to our audio->out.<properties> */
5068 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
5069 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5070 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5071 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5072 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5073 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5075 hb_audio_add( job, audio );
5080 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5084 #pragma mark - Picture
5086 /* lets set the picture size back to the max from right after title scan
5087 Lets use an IBAction here as down the road we could always use a checkbox
5088 in the gui to easily take the user back to max. Remember, the compiler
5089 resolves IBActions down to -(void) during compile anyway */
5090 - (IBAction) revertPictureSizeToMax: (id) sender
5092 hb_job_t * job = fTitle->job;
5093 /* Here we apply the title source and height */
5094 job->width = fTitle->width;
5095 job->height = fTitle->height;
5097 [self calculatePictureSizing: sender];
5098 /* We call method to change UI to reflect whether a preset is used or not*/
5099 [self customSettingUsed: sender];
5103 * Registers changes made in the Picture Settings Window.
5106 - (void)pictureSettingsDidChange
5108 [self calculatePictureSizing:nil];
5111 /* Get and Display Current Pic Settings in main window */
5112 - (IBAction) calculatePictureSizing: (id) sender
5114 if (fTitle->job->anamorphic.mode > 0)
5116 fTitle->job->keep_ratio = 0;
5119 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5121 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5125 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5127 NSString *picCropping;
5128 /* Set the display field for crop as per boolean */
5129 if (![fPictureController autoCrop])
5131 picCropping = @"Custom";
5135 picCropping = @"Auto";
5137 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]]];
5139 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5141 NSString *videoFilters;
5144 if ([fPictureController detelecine] == 2)
5146 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5148 else if ([fPictureController detelecine] == 1)
5150 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5154 if ([fPictureController useDecomb] == 1)
5157 if ([fPictureController decomb] == 2)
5159 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5161 else if ([fPictureController decomb] == 1)
5163 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5169 if ([fPictureController deinterlace] > 0)
5171 fTitle->job->deinterlace = 1;
5175 fTitle->job->deinterlace = 0;
5178 if ([fPictureController deinterlace] == 2)
5180 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5182 else if ([fPictureController deinterlace] == 3)
5184 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5186 else if ([fPictureController deinterlace] == 4)
5188 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5190 else if ([fPictureController deinterlace] == 1)
5192 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5198 if ([fPictureController denoise] == 2)
5200 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5202 else if ([fPictureController denoise] == 3)
5204 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5206 else if ([fPictureController denoise] == 4)
5208 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5210 else if ([fPictureController denoise] == 1)
5212 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5216 if ([fPictureController deblock] > 0)
5218 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5222 if ([fPictureController grayscale])
5224 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5226 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5228 //[fPictureController reloadStillPreview];
5233 #pragma mark - Audio and Subtitles
5234 - (IBAction) audioCodecsPopUpChanged: (id) sender
5237 NSPopUpButton * audiotrackPopUp;
5238 NSPopUpButton * sampleratePopUp;
5239 NSPopUpButton * bitratePopUp;
5240 NSPopUpButton * audiocodecPopUp;
5241 if (sender == fAudTrack1CodecPopUp)
5243 audiotrackPopUp = fAudLang1PopUp;
5244 audiocodecPopUp = fAudTrack1CodecPopUp;
5245 sampleratePopUp = fAudTrack1RatePopUp;
5246 bitratePopUp = fAudTrack1BitratePopUp;
5248 else if (sender == fAudTrack2CodecPopUp)
5250 audiotrackPopUp = fAudLang2PopUp;
5251 audiocodecPopUp = fAudTrack2CodecPopUp;
5252 sampleratePopUp = fAudTrack2RatePopUp;
5253 bitratePopUp = fAudTrack2BitratePopUp;
5255 else if (sender == fAudTrack3CodecPopUp)
5257 audiotrackPopUp = fAudLang3PopUp;
5258 audiocodecPopUp = fAudTrack3CodecPopUp;
5259 sampleratePopUp = fAudTrack3RatePopUp;
5260 bitratePopUp = fAudTrack3BitratePopUp;
5264 audiotrackPopUp = fAudLang4PopUp;
5265 audiocodecPopUp = fAudTrack4CodecPopUp;
5266 sampleratePopUp = fAudTrack4RatePopUp;
5267 bitratePopUp = fAudTrack4BitratePopUp;
5270 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5271 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5272 [self audioTrackPopUpChanged: audiotrackPopUp];
5276 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5278 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5279 * the settings of the source audio for that track. We leave the samplerate and bitrate
5280 * to audiotrackMixdownChanged
5283 /* We will first verify that a lower track number has been selected before enabling each track
5284 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5287 /* If the source has no audio then disable audio track 1 */
5288 if (hb_list_count( fTitle->list_audio ) == 0)
5290 [fAudLang1PopUp selectItemAtIndex:0];
5293 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5295 [fAudLang2PopUp setEnabled: NO];
5296 [fAudLang2PopUp selectItemAtIndex: 0];
5300 [fAudLang2PopUp setEnabled: YES];
5303 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5305 [fAudLang3PopUp setEnabled: NO];
5306 [fAudLang3PopUp selectItemAtIndex: 0];
5310 [fAudLang3PopUp setEnabled: YES];
5312 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5314 [fAudLang4PopUp setEnabled: NO];
5315 [fAudLang4PopUp selectItemAtIndex: 0];
5319 [fAudLang4PopUp setEnabled: YES];
5321 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5322 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5323 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5324 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5325 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5326 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5327 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5328 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5330 [fAudTrack1CodecPopUp removeAllItems];
5331 [fAudTrack1MixPopUp removeAllItems];
5332 [fAudTrack1RatePopUp removeAllItems];
5333 [fAudTrack1BitratePopUp removeAllItems];
5334 [fAudTrack1DrcSlider setFloatValue: 0.00];
5335 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5337 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5339 [fAudTrack1RatePopUp setEnabled: NO];
5340 [fAudTrack1BitratePopUp setEnabled: NO];
5341 [fAudTrack1DrcSlider setEnabled: NO];
5342 [fAudTrack1DrcField setEnabled: NO];
5345 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5346 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5347 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5348 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5349 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5350 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5351 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5352 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5354 [fAudTrack2CodecPopUp removeAllItems];
5355 [fAudTrack2MixPopUp removeAllItems];
5356 [fAudTrack2RatePopUp removeAllItems];
5357 [fAudTrack2BitratePopUp removeAllItems];
5358 [fAudTrack2DrcSlider setFloatValue: 0.00];
5359 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5361 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5363 [fAudTrack2RatePopUp setEnabled: NO];
5364 [fAudTrack2BitratePopUp setEnabled: NO];
5365 [fAudTrack2DrcSlider setEnabled: NO];
5366 [fAudTrack2DrcField setEnabled: NO];
5369 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5370 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5371 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5372 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5373 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5374 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5375 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5376 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5378 [fAudTrack3CodecPopUp removeAllItems];
5379 [fAudTrack3MixPopUp removeAllItems];
5380 [fAudTrack3RatePopUp removeAllItems];
5381 [fAudTrack3BitratePopUp removeAllItems];
5382 [fAudTrack3DrcSlider setFloatValue: 0.00];
5383 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5385 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5387 [fAudTrack3RatePopUp setEnabled: NO];
5388 [fAudTrack3BitratePopUp setEnabled: NO];
5389 [fAudTrack3DrcSlider setEnabled: NO];
5390 [fAudTrack3DrcField setEnabled: NO];
5393 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5394 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5395 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5396 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5397 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5398 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5399 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5400 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5402 [fAudTrack4CodecPopUp removeAllItems];
5403 [fAudTrack4MixPopUp removeAllItems];
5404 [fAudTrack4RatePopUp removeAllItems];
5405 [fAudTrack4BitratePopUp removeAllItems];
5406 [fAudTrack4DrcSlider setFloatValue: 0.00];
5407 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5409 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5411 [fAudTrack4RatePopUp setEnabled: NO];
5412 [fAudTrack4BitratePopUp setEnabled: NO];
5413 [fAudTrack4DrcSlider setEnabled: NO];
5414 [fAudTrack4DrcField setEnabled: NO];
5419 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5422 hb_list_t * list = hb_get_titles( fHandle );
5423 hb_title_t * title = (hb_title_t*)
5424 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5426 hb_audio_config_t * audio;
5428 [sender removeAllItems];
5429 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5430 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5432 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5433 [[sender menu] addItemWithTitle:
5434 [NSString stringWithUTF8String: audio->lang.description]
5435 action: NULL keyEquivalent: @""];
5437 [sender selectItemAtIndex: 0];
5441 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5444 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5445 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5446 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5447 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5448 if (hb_list_count( fTitle->list_audio ) != 0)
5450 if (searchPrefixString)
5453 for( int i = 0; i < [sender numberOfItems]; i++ )
5455 /* Try to find the desired search string */
5456 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5458 [sender selectItemAtIndex: i];
5462 /* couldn't find the string, so select the requested "search string not found" item */
5463 /* index of 0 means select the "none" item */
5464 /* index of 1 means select the first audio track */
5465 [sender selectItemAtIndex: selectIndexIfNotFound];
5469 /* if no search string is provided, then select the selectIndexIfNotFound item */
5470 [sender selectItemAtIndex: selectIndexIfNotFound];
5475 [sender selectItemAtIndex: 0];
5479 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5481 int format = [fDstFormatPopUp indexOfSelectedItem];
5483 /* setup pointers to the appropriate popups for the correct track */
5484 NSPopUpButton * audiocodecPopUp;
5485 NSPopUpButton * audiotrackPopUp;
5486 if (sender == fAudTrack1CodecPopUp)
5488 audiotrackPopUp = fAudLang1PopUp;
5489 audiocodecPopUp = fAudTrack1CodecPopUp;
5491 else if (sender == fAudTrack2CodecPopUp)
5493 audiotrackPopUp = fAudLang2PopUp;
5494 audiocodecPopUp = fAudTrack2CodecPopUp;
5496 else if (sender == fAudTrack3CodecPopUp)
5498 audiotrackPopUp = fAudLang3PopUp;
5499 audiocodecPopUp = fAudTrack3CodecPopUp;
5503 audiotrackPopUp = fAudLang4PopUp;
5504 audiocodecPopUp = fAudTrack4CodecPopUp;
5507 [audiocodecPopUp removeAllItems];
5508 /* Make sure "None" isnt selected in the source track */
5509 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5511 [audiocodecPopUp setEnabled:YES];
5512 NSMenuItem *menuItem;
5513 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5519 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5520 [menuItem setTag: HB_ACODEC_CA_AAC];
5522 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5523 [menuItem setTag: HB_ACODEC_FAAC];
5525 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5526 [menuItem setTag: HB_ACODEC_LAME];
5528 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5529 [menuItem setTag: HB_ACODEC_AC3];
5535 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5536 [menuItem setTag: HB_ACODEC_CA_AAC];
5538 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5539 [menuItem setTag: HB_ACODEC_FAAC];
5541 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5542 [menuItem setTag: HB_ACODEC_AC3];
5544 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5545 [menuItem setTag: HB_ACODEC_DCA];
5547 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5548 [menuItem setTag: HB_ACODEC_LAME];
5550 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5551 [menuItem setTag: HB_ACODEC_VORBIS];
5554 [audiocodecPopUp selectItemAtIndex:0];
5558 [audiocodecPopUp setEnabled:NO];
5562 - (IBAction) audioTrackPopUpChanged: (id) sender
5564 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5565 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5568 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5571 /* make sure we have a selected title before continuing */
5572 if (fTitle == NULL) return;
5573 /* make sure we have a source audio track before continuing */
5574 if (hb_list_count( fTitle->list_audio ) == 0)
5576 [sender selectItemAtIndex:0];
5579 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5580 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5582 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5584 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5586 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5588 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5590 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5592 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5594 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5596 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5599 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5600 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5602 sender = fAudLang1PopUp;
5604 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5606 sender = fAudLang2PopUp;
5608 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5610 sender = fAudLang3PopUp;
5612 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5614 sender = fAudLang4PopUp;
5617 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5618 NSPopUpButton * mixdownPopUp;
5619 NSPopUpButton * audiocodecPopUp;
5620 NSPopUpButton * sampleratePopUp;
5621 NSPopUpButton * bitratePopUp;
5622 if (sender == fAudLang1PopUp)
5624 mixdownPopUp = fAudTrack1MixPopUp;
5625 audiocodecPopUp = fAudTrack1CodecPopUp;
5626 sampleratePopUp = fAudTrack1RatePopUp;
5627 bitratePopUp = fAudTrack1BitratePopUp;
5629 else if (sender == fAudLang2PopUp)
5631 mixdownPopUp = fAudTrack2MixPopUp;
5632 audiocodecPopUp = fAudTrack2CodecPopUp;
5633 sampleratePopUp = fAudTrack2RatePopUp;
5634 bitratePopUp = fAudTrack2BitratePopUp;
5636 else if (sender == fAudLang3PopUp)
5638 mixdownPopUp = fAudTrack3MixPopUp;
5639 audiocodecPopUp = fAudTrack3CodecPopUp;
5640 sampleratePopUp = fAudTrack3RatePopUp;
5641 bitratePopUp = fAudTrack3BitratePopUp;
5645 mixdownPopUp = fAudTrack4MixPopUp;
5646 audiocodecPopUp = fAudTrack4CodecPopUp;
5647 sampleratePopUp = fAudTrack4RatePopUp;
5648 bitratePopUp = fAudTrack4BitratePopUp;
5651 /* get the index of the selected audio Track*/
5652 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5654 /* pointer for the hb_audio_s struct we will use later on */
5655 hb_audio_config_t * audio;
5658 /* check if the audio mixdown controls need their enabled state changing */
5659 [self setEnabledStateOfAudioMixdownControls:nil];
5661 if (thisAudioIndex != -1)
5665 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5667 /* actually manipulate the proper mixdowns here */
5668 /* delete the previous audio mixdown options */
5669 [mixdownPopUp removeAllItems];
5671 acodec = [[audiocodecPopUp selectedItem] tag];
5676 /* find out if our selected output audio codec supports 6ch */
5677 int audioCodecsSupport6Ch = (audio->in.codec && acodec != HB_ACODEC_LAME);
5679 /* check for AC-3 passthru */
5680 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5683 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5684 [NSString stringWithUTF8String: "AC3 Passthru"]
5685 action: NULL keyEquivalent: @""];
5686 [menuItem setTag: HB_ACODEC_AC3];
5688 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5690 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5691 [NSString stringWithUTF8String: "DTS Passthru"]
5692 action: NULL keyEquivalent: @""];
5693 [menuItem setTag: HB_ACODEC_DCA];
5698 /* add the appropriate audio mixdown menuitems to the popupbutton */
5699 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5700 so that we can reference the mixdown later */
5702 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5703 int minMixdownUsed = 0;
5704 int maxMixdownUsed = 0;
5706 /* get the input channel layout without any lfe channels */
5707 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5709 /* add a mono option */
5710 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5711 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5712 action: NULL keyEquivalent: @""];
5713 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5714 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5715 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5717 /* do we want to add a stereo option? */
5718 /* offer stereo if we have a stereo-or-better source */
5719 if (layout >= HB_INPUT_CH_LAYOUT_STEREO)
5721 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5722 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5723 action: NULL keyEquivalent: @""];
5724 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5725 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5726 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5729 /* do we want to add a dolby surround (DPL1) option? */
5730 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5732 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5733 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5734 action: NULL keyEquivalent: @""];
5735 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5736 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5737 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5740 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5741 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5743 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5744 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5745 action: NULL keyEquivalent: @""];
5746 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5747 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5748 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5751 /* do we want to add a 6-channel discrete option? */
5752 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5754 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5755 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5756 action: NULL keyEquivalent: @""];
5757 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5758 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5759 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5762 /* do we want to add an AC-3 passthrough option? */
5763 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5765 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5766 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5767 action: NULL keyEquivalent: @""];
5768 [menuItem setTag: HB_ACODEC_AC3];
5769 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5770 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5773 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5774 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5776 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5777 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5778 action: NULL keyEquivalent: @""];
5779 [menuItem setTag: HB_ACODEC_DCA];
5780 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5781 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5784 /* auto-select the best mixdown based on our saved mixdown preference */
5786 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5787 /* ultimately this should be a prefs option */
5790 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5791 if (mixdownToUse > 0)
5793 useMixdown = mixdownToUse;
5797 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5800 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5801 if (useMixdown > maxMixdownUsed)
5803 useMixdown = maxMixdownUsed;
5806 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5807 if (useMixdown < minMixdownUsed)
5809 useMixdown = minMixdownUsed;
5812 /* select the (possibly-amended) preferred mixdown */
5813 [mixdownPopUp selectItemWithTag: useMixdown];
5816 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5817 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5819 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5821 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5824 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5825 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5827 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5829 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5832 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5833 [self audioTrackMixdownChanged: mixdownPopUp];
5837 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5839 [self autoSetM4vExtension: sender];
5843 - (IBAction) audioTrackMixdownChanged: (id) sender
5847 /* setup pointers to all of the other audio track controls
5848 * we will need later
5850 NSPopUpButton * mixdownPopUp;
5851 NSPopUpButton * sampleratePopUp;
5852 NSPopUpButton * bitratePopUp;
5853 NSPopUpButton * audiocodecPopUp;
5854 NSPopUpButton * audiotrackPopUp;
5855 NSSlider * drcSlider;
5856 NSTextField * drcField;
5857 if (sender == fAudTrack1MixPopUp)
5859 audiotrackPopUp = fAudLang1PopUp;
5860 audiocodecPopUp = fAudTrack1CodecPopUp;
5861 mixdownPopUp = fAudTrack1MixPopUp;
5862 sampleratePopUp = fAudTrack1RatePopUp;
5863 bitratePopUp = fAudTrack1BitratePopUp;
5864 drcSlider = fAudTrack1DrcSlider;
5865 drcField = fAudTrack1DrcField;
5867 else if (sender == fAudTrack2MixPopUp)
5869 audiotrackPopUp = fAudLang2PopUp;
5870 audiocodecPopUp = fAudTrack2CodecPopUp;
5871 mixdownPopUp = fAudTrack2MixPopUp;
5872 sampleratePopUp = fAudTrack2RatePopUp;
5873 bitratePopUp = fAudTrack2BitratePopUp;
5874 drcSlider = fAudTrack2DrcSlider;
5875 drcField = fAudTrack2DrcField;
5877 else if (sender == fAudTrack3MixPopUp)
5879 audiotrackPopUp = fAudLang3PopUp;
5880 audiocodecPopUp = fAudTrack3CodecPopUp;
5881 mixdownPopUp = fAudTrack3MixPopUp;
5882 sampleratePopUp = fAudTrack3RatePopUp;
5883 bitratePopUp = fAudTrack3BitratePopUp;
5884 drcSlider = fAudTrack3DrcSlider;
5885 drcField = fAudTrack3DrcField;
5889 audiotrackPopUp = fAudLang4PopUp;
5890 audiocodecPopUp = fAudTrack4CodecPopUp;
5891 mixdownPopUp = fAudTrack4MixPopUp;
5892 sampleratePopUp = fAudTrack4RatePopUp;
5893 bitratePopUp = fAudTrack4BitratePopUp;
5894 drcSlider = fAudTrack4DrcSlider;
5895 drcField = fAudTrack4DrcField;
5897 acodec = [[audiocodecPopUp selectedItem] tag];
5898 /* storage variable for the min and max bitrate allowed for this codec */
5904 case HB_ACODEC_FAAC:
5905 /* check if we have a 6ch discrete conversion in either audio track */
5906 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5908 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5910 /* If either mixdown popup includes 6-channel discrete, then allow up to 768 kbps */
5916 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5918 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5923 case HB_ACODEC_CA_AAC:
5924 /* check if we have a 6ch discrete conversion in either audio track */
5925 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5938 case HB_ACODEC_LAME:
5939 /* Lame is happy using our min bitrate of 32 kbps */
5941 /* Lame won't encode if the bitrate is higher than 320 kbps */
5945 case HB_ACODEC_VORBIS:
5946 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5948 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5950 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5956 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5958 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5964 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5970 /* make sure we have a selected title before continuing */
5971 if (fTitle == NULL || hb_list_count( fTitle->list_audio ) == 0) return;
5972 /* get the audio so we can find out what input rates are*/
5973 hb_audio_config_t * audio;
5974 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5975 int inputbitrate = audio->in.bitrate / 1000;
5976 int inputsamplerate = audio->in.samplerate;
5978 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
5980 [bitratePopUp removeAllItems];
5982 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5984 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5986 /* add a new menuitem for this bitrate */
5987 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5988 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
5989 action: NULL keyEquivalent: @""];
5990 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5991 [menuItem setTag: hb_audio_bitrates[i].rate];
5995 /* select the default bitrate (but use 384 for 6-ch AAC) */
5996 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5998 [bitratePopUp selectItemWithTag: 384];
6002 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
6005 /* populate and set the sample rate popup */
6006 /* Audio samplerate */
6007 [sampleratePopUp removeAllItems];
6008 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
6009 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
6010 [menuItem setTag: inputsamplerate];
6012 for( int i = 0; i < hb_audio_rates_count; i++ )
6014 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
6015 [NSString stringWithUTF8String: hb_audio_rates[i].string]
6016 action: NULL keyEquivalent: @""];
6017 [menuItem setTag: hb_audio_rates[i].rate];
6019 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
6020 * and there is no compelling reason to use anything else as default, though the users default
6021 * preset will likely override any setting chosen here.
6023 [sampleratePopUp selectItemWithTag: inputsamplerate];
6026 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
6027 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
6028 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
6030 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
6033 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
6034 [bitratePopUp removeAllItems];
6035 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
6036 [NSString stringWithFormat:@"%d", inputbitrate]
6037 action: NULL keyEquivalent: @""];
6038 [menuItem setTag: inputbitrate];
6039 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
6040 [bitratePopUp setEnabled: NO];
6041 [sampleratePopUp setEnabled: NO];
6043 [drcSlider setFloatValue: 0.00];
6044 [self audioDRCSliderChanged: drcSlider];
6045 [drcSlider setEnabled: NO];
6046 [drcField setEnabled: NO];
6050 [sampleratePopUp setEnabled: YES];
6051 [bitratePopUp setEnabled: YES];
6052 [drcSlider setEnabled: YES];
6053 [drcField setEnabled: YES];
6055 [self calculateBitrate:nil];
6058 - (IBAction) audioDRCSliderChanged: (id) sender
6060 NSSlider * drcSlider;
6061 NSTextField * drcField;
6062 if (sender == fAudTrack1DrcSlider)
6064 drcSlider = fAudTrack1DrcSlider;
6065 drcField = fAudTrack1DrcField;
6067 else if (sender == fAudTrack2DrcSlider)
6069 drcSlider = fAudTrack2DrcSlider;
6070 drcField = fAudTrack2DrcField;
6072 else if (sender == fAudTrack3DrcSlider)
6074 drcSlider = fAudTrack3DrcSlider;
6075 drcField = fAudTrack3DrcField;
6079 drcSlider = fAudTrack4DrcSlider;
6080 drcField = fAudTrack4DrcField;
6083 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6084 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6086 [drcSlider setFloatValue:1.0];
6090 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6091 /* For now, do not call this until we have an intelligent way to determine audio track selections
6092 * compared to presets
6094 //[self customSettingUsed: sender];
6099 - (IBAction) browseImportSrtFile: (id) sender
6102 NSOpenPanel * panel;
6104 panel = [NSOpenPanel openPanel];
6105 [panel setAllowsMultipleSelection: NO];
6106 [panel setCanChooseFiles: YES];
6107 [panel setCanChooseDirectories: NO ];
6108 NSString * sourceDirectory;
6109 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6111 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6115 sourceDirectory = @"~/Desktop";
6116 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6118 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6119 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6120 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6121 modalForWindow: fWindow modalDelegate: self
6122 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6123 contextInfo: sender];
6126 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6127 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6129 if( returnCode == NSOKButton )
6131 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6132 NSString *importSrtFilePath = [sheet filename];
6133 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6135 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6136 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6138 [fSubtitlesTable reloadData];
6144 #pragma mark Open New Windows
6146 - (IBAction) openHomepage: (id) sender
6148 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6149 URLWithString:@"http://handbrake.fr/"]];
6152 - (IBAction) openForums: (id) sender
6154 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6155 URLWithString:@"http://handbrake.fr/forum/"]];
6157 - (IBAction) openUserGuide: (id) sender
6159 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6160 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6164 * Shows debug output window.
6166 - (IBAction)showDebugOutputPanel:(id)sender
6168 [outputPanel showOutputPanel:sender];
6172 * Shows preferences window.
6174 - (IBAction) showPreferencesWindow: (id) sender
6176 NSWindow * window = [fPreferencesController window];
6177 if (![window isVisible])
6180 [window makeKeyAndOrderFront: nil];
6184 * Shows queue window.
6186 - (IBAction) showQueueWindow:(id)sender
6188 [fQueueController showQueueWindow:sender];
6192 - (IBAction) toggleDrawer:(id)sender {
6193 [fPresetDrawer toggle:self];
6197 * Shows Picture Settings Window.
6200 - (IBAction) showPicturePanel: (id) sender
6202 [fPictureController showPictureWindow:sender];
6205 - (void) picturePanelFullScreen
6207 [fPictureController setToFullScreenMode];
6210 - (void) picturePanelWindowed
6212 [fPictureController setToWindowedMode];
6215 - (IBAction) showPreviewWindow: (id) sender
6217 [fPictureController showPreviewWindow:sender];
6221 #pragma mark Preset Outline View Methods
6222 #pragma mark - Required
6223 /* These are required by the NSOutlineView Datasource Delegate */
6226 /* used to specify the number of levels to show for each item */
6227 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6229 /* currently use no levels to test outline view viability */
6230 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6232 return [UserPresets count];
6236 /* we need to return the count of the array in ChildrenArray for this folder */
6237 NSArray *children = nil;
6238 children = [item objectForKey:@"ChildrenArray"];
6239 if ([children count] > 0)
6241 return [children count];
6250 /* We use this to deterimine children of an item */
6251 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6254 /* we need to return the count of the array in ChildrenArray for this folder */
6255 NSArray *children = nil;
6258 children = UserPresets;
6262 if ([item objectForKey:@"ChildrenArray"])
6264 children = [item objectForKey:@"ChildrenArray"];
6267 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6273 return [children objectAtIndex:index];
6277 // We are only one level deep, so we can't be asked about children
6278 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6282 /* We use this to determine if an item should be expandable */
6283 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6286 /* we need to return the count of the array in ChildrenArray for this folder */
6287 NSArray *children= nil;
6290 children = UserPresets;
6294 if ([item objectForKey:@"ChildrenArray"])
6296 children = [item objectForKey:@"ChildrenArray"];
6300 /* To deterimine if an item should show a disclosure triangle
6301 * we could do it by the children count as so:
6302 * if ([children count] < 1)
6303 * However, lets leave the triangle show even if there are no
6304 * children to help indicate a folder, just like folder in the
6305 * finder can show a disclosure triangle even when empty
6308 /* We need to determine if the item is a folder */
6309 if ([[item objectForKey:@"Folder"] intValue] == 1)
6320 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6322 // Our outline view has no levels, but we can still expand every item. Doing so
6323 // just makes the row taller. See heightOfRowByItem below.
6324 //return ![(HBQueueOutlineView*)outlineView isDragging];
6330 /* Used to tell the outline view which information is to be displayed per item */
6331 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6333 /* We have two columns right now, icon and PresetName */
6335 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6337 return [item objectForKey:@"PresetName"];
6346 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6348 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6350 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6352 return [NSKeyedArchiver archivedDataWithRootObject:item];
6355 #pragma mark - Added Functionality (optional)
6356 /* Use to customize the font and display characteristics of the title cell */
6357 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6359 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6363 NSColor *shadowColor;
6364 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6365 /*check to see if its a selected row */
6366 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6369 fontColor = [NSColor blackColor];
6370 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6374 if ([[item objectForKey:@"Type"] intValue] == 0)
6376 fontColor = [NSColor blueColor];
6378 else // User created preset, use a black font
6380 fontColor = [NSColor blackColor];
6382 /* check to see if its a folder */
6383 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6385 //fontColor = [NSColor greenColor];
6390 /* We use Bold Text for the HB Default */
6391 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6393 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6395 /* We use Bold Text for the User Specified Default */
6396 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6398 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6402 [cell setTextColor:fontColor];
6403 [cell setFont:txtFont];
6408 /* We use this to edit the name field in the outline view */
6409 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6411 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6416 [theRecord setObject:object forKey:@"PresetName"];
6420 [fPresetsOutlineView reloadData];
6421 /* We save all of the preset data here */
6425 /* We use this to provide tooltips for the items in the presets outline view */
6426 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6428 //if ([[tc identifier] isEqualToString:@"PresetName"])
6430 /* initialize the tooltip contents variable */
6432 /* if there is a description for the preset, we show it in the tooltip */
6433 if ([item objectForKey:@"PresetDescription"])
6435 loc_tip = [item objectForKey:@"PresetDescription"];
6440 loc_tip = @"No description available";
6447 #pragma mark Preset Outline View Methods (dragging related)
6450 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6452 // Dragging is only allowed for custom presets.
6453 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6454 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6458 // Don't retain since this is just holding temporaral drag information, and it is
6459 //only used during a drag! We could put this in the pboard actually.
6460 fDraggedNodes = items;
6461 // Provide data for our custom type, and simple NSStrings.
6462 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6464 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6465 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6470 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6473 // Don't allow dropping ONTO an item since they can't really contain any children.
6475 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6476 if (isOnDropTypeProposal)
6477 return NSDragOperationNone;
6479 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6482 index = [fPresetsOutlineView rowForItem: item] + 1;
6486 // Don't allow dropping into the Built In Presets.
6487 if (index < presetCurrentBuiltInCount)
6489 return NSDragOperationNone;
6490 index = MAX (index, presetCurrentBuiltInCount);
6493 [outlineView setDropItem:item dropChildIndex:index];
6494 return NSDragOperationGeneric;
6499 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6501 /* first, lets see if we are dropping into a folder */
6502 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6504 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6505 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6506 [childrenArray addObject:item];
6507 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6508 [childrenArray autorelease];
6510 else // We are not, so we just move the preset into the existing array
6512 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6514 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6515 while (obj = [enumerator nextObject])
6517 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6519 // Successful drop, lets rearrange the view and save it all
6520 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6522 [fPresetsOutlineView reloadData];
6527 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6529 NSUInteger index = [indexSet lastIndex];
6530 NSUInteger aboveInsertIndexCount = 0;
6532 NSUInteger removeIndex;
6534 if (index >= insertIndex)
6536 removeIndex = index + aboveInsertIndexCount;
6537 aboveInsertIndexCount++;
6541 removeIndex = index;
6545 id object = [[array objectAtIndex:removeIndex] retain];
6546 [array removeObjectAtIndex:removeIndex];
6547 [array insertObject:object atIndex:insertIndex];
6550 index = [indexSet indexLessThanIndex:index];
6555 #pragma mark - Functional Preset NSOutlineView Methods
6557 - (IBAction)selectPreset:(id)sender
6560 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6562 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6563 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6565 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6567 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6571 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6575 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6576 [self formatPopUpChanged:nil];
6578 /* Chapter Markers*/
6579 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6580 /* check to see if we have only one chapter */
6581 [self chapterPopUpChanged:nil];
6583 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6584 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6585 /* Mux mp4 with http optimization */
6586 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6589 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6590 /* We set the advanced opt string here if applicable*/
6591 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6593 /* Lets run through the following functions to get variables set there */
6594 [self videoEncoderPopUpChanged:nil];
6595 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6596 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6597 [self calculateBitrate:nil];
6600 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6602 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6603 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6605 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6606 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6607 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6608 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6609 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6610 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6612 /* For the quality slider we need to convert the old percent's to the new rf scales */
6613 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6614 [fVidQualitySlider setFloatValue:rf];
6619 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6620 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6622 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6626 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6627 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6631 [self videoMatrixChanged:nil];
6633 /* Video framerate */
6634 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6635 detected framerate in the fVidRatePopUp so we use index 0*/
6636 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6638 [fVidRatePopUp selectItemAtIndex: 0];
6642 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6645 [fFrameratePfrCheck setState:[[chosenPreset objectForKey:@"VideoFrameratePFR"] intValue]];
6646 [self videoFrameRateChanged:nil];
6648 /* 2 Pass Encoding */
6649 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6650 [self twoPassCheckboxChanged:nil];
6652 /* Turbo 1st pass for 2 Pass Encoding */
6653 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6656 /* First we check to see if we are using the current audio track layout based on AudioList array */
6657 if ([chosenPreset objectForKey:@"AudioList"])
6660 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6661 NSPopUpButton * trackLangPreviousPopUp = nil;
6662 NSPopUpButton * trackLangPopUp = nil;
6663 NSPopUpButton * mixdownPopUp = nil;
6664 NSPopUpButton * audiocodecPopUp = nil;
6665 NSPopUpButton * sampleratePopUp = nil;
6666 NSPopUpButton * bitratePopUp = nil;
6667 NSSlider * drcSlider = nil;
6670 /* Populate the audio widgets based on the contents of the AudioList array */
6672 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6674 while (tempObject = [enumerator nextObject])
6679 trackLangPopUp = fAudLang1PopUp;
6680 mixdownPopUp = fAudTrack1MixPopUp;
6681 audiocodecPopUp = fAudTrack1CodecPopUp;
6682 sampleratePopUp = fAudTrack1RatePopUp;
6683 bitratePopUp = fAudTrack1BitratePopUp;
6684 drcSlider = fAudTrack1DrcSlider;
6688 trackLangPreviousPopUp = fAudLang1PopUp;
6689 trackLangPopUp = fAudLang2PopUp;
6690 mixdownPopUp = fAudTrack2MixPopUp;
6691 audiocodecPopUp = fAudTrack2CodecPopUp;
6692 sampleratePopUp = fAudTrack2RatePopUp;
6693 bitratePopUp = fAudTrack2BitratePopUp;
6694 drcSlider = fAudTrack2DrcSlider;
6698 trackLangPreviousPopUp = fAudLang2PopUp;
6699 trackLangPopUp = fAudLang3PopUp;
6700 mixdownPopUp = fAudTrack3MixPopUp;
6701 audiocodecPopUp = fAudTrack3CodecPopUp;
6702 sampleratePopUp = fAudTrack3RatePopUp;
6703 bitratePopUp = fAudTrack3BitratePopUp;
6704 drcSlider = fAudTrack3DrcSlider;
6708 trackLangPreviousPopUp = fAudLang3PopUp;
6709 trackLangPopUp = fAudLang4PopUp;
6710 mixdownPopUp = fAudTrack4MixPopUp;
6711 audiocodecPopUp = fAudTrack4CodecPopUp;
6712 sampleratePopUp = fAudTrack4RatePopUp;
6713 bitratePopUp = fAudTrack4BitratePopUp;
6714 drcSlider = fAudTrack4DrcSlider;
6718 if ([trackLangPopUp indexOfSelectedItem] == 0)
6722 [trackLangPopUp selectItemAtIndex: 1];
6726 /* if we are greater than track 1, select
6727 * the same track as the previous track */
6728 [trackLangPopUp selectItemAtIndex: [trackLangPreviousPopUp indexOfSelectedItem]];
6731 [self audioTrackPopUpChanged: trackLangPopUp];
6732 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6733 /* check our pref for core audio and use it in place of faac if preset is a built in */
6734 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6735 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6736 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6738 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6741 [self audioTrackPopUpChanged: audiocodecPopUp];
6742 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6743 [self audioTrackMixdownChanged: mixdownPopUp];
6744 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6746 if ([mixdownPopUp selectedItem] == nil)
6748 [self audioTrackPopUpChanged: audiocodecPopUp];
6749 [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6751 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6752 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6753 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6755 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6756 /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6757 *default mixdown bitrate*/
6758 if ([bitratePopUp selectedItem] == nil)
6760 [self audioTrackMixdownChanged: mixdownPopUp];
6763 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6764 [self audioDRCSliderChanged: drcSlider];
6767 /* 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,
6768 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6772 /* 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". */
6773 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6775 hb_audio_config_t * audio;
6776 /* get the audio source audio codec */
6777 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6778 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6779 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6781 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6782 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6784 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6786 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6788 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6790 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6791 [trackLangPopUp selectItemAtIndex: 0];
6792 [self audioTrackPopUpChanged: trackLangPopUp];
6798 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6802 [fAudLang4PopUp selectItemAtIndex: 0];
6803 [self audioTrackPopUpChanged: fAudLang4PopUp];
6807 [fAudLang3PopUp selectItemAtIndex: 0];
6808 [self audioTrackPopUpChanged: fAudLang3PopUp];
6812 [fAudLang2PopUp selectItemAtIndex: 0];
6813 [self audioTrackPopUpChanged: fAudLang2PopUp];
6821 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6823 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6825 [fAudLang1PopUp selectItemAtIndex: 1];
6827 [self audioTrackPopUpChanged: fAudLang1PopUp];
6828 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6829 /* check our pref for core audio and use it in place of faac if preset is built in */
6830 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6831 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6832 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6834 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6837 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6838 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6839 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6841 if ([fAudTrack1MixPopUp selectedItem] == nil)
6843 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6845 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6846 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6847 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6849 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6851 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6852 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6855 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6857 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6859 [fAudLang2PopUp selectItemAtIndex: 1];
6861 [self audioTrackPopUpChanged: fAudLang2PopUp];
6862 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6863 /* check our pref for core audio and use it in place of faac if preset is built in */
6864 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6865 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6866 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6868 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6870 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6871 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6872 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6874 if ([fAudTrack2MixPopUp selectedItem] == nil)
6876 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6878 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6879 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6880 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6882 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6884 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6885 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6887 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6889 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6891 [fAudLang3PopUp selectItemAtIndex: 1];
6893 [self audioTrackPopUpChanged: fAudLang3PopUp];
6894 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6895 /* check our pref for core audio and use it in place of faac if preset is built in */
6896 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6897 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6898 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6900 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6902 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6903 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6904 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6906 if ([fAudTrack3MixPopUp selectedItem] == nil)
6908 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6910 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6911 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6912 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6914 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6916 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6917 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6919 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6921 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6923 [fAudLang4PopUp selectItemAtIndex: 1];
6925 [self audioTrackPopUpChanged: fAudLang4PopUp];
6926 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6927 /* check our pref for core audio and use it in place of faac if preset is built in */
6928 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6929 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6930 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6932 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6934 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6935 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6936 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6938 if ([fAudTrack4MixPopUp selectedItem] == nil)
6940 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6942 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
6943 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6944 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
6946 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
6948 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
6949 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
6952 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6954 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
6956 [fAudLang2PopUp selectItemAtIndex: 0];
6957 [self audioTrackPopUpChanged: fAudLang2PopUp];
6959 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
6961 [fAudLang3PopUp selectItemAtIndex: 0];
6962 [self audioTrackPopUpChanged: fAudLang3PopUp];
6964 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
6966 [fAudLang4PopUp selectItemAtIndex: 0];
6967 [self audioTrackPopUpChanged: fAudLang4PopUp];
6972 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
6973 /* Forced Subtitles */
6974 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
6976 /* Picture Settings */
6977 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
6978 * height, width, keep ar, anamorphic and crop settings.
6979 * picture filters are handled separately below.
6981 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
6982 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
6983 * preset completely ignores any picture sizing values in the preset.
6985 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
6987 hb_job_t * job = fTitle->job;
6989 /* If Cropping is set to custom, then recall all four crop values from
6990 when the preset was created and apply them */
6991 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
6993 [fPictureController setAutoCrop:NO];
6995 /* Here we use the custom crop values saved at the time the preset was saved */
6996 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
6997 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
6998 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
6999 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
7002 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
7004 [fPictureController setAutoCrop:YES];
7005 /* Here we use the auto crop values determined right after scan */
7006 job->crop[0] = AutoCropTop;
7007 job->crop[1] = AutoCropBottom;
7008 job->crop[2] = AutoCropLeft;
7009 job->crop[3] = AutoCropRight;
7014 if ([chosenPreset objectForKey:@"PictureModulus"])
7016 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
7023 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
7024 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
7026 /* Use Max Picture settings for whatever the dvd is.*/
7027 [self revertPictureSizeToMax:nil];
7028 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7029 if (job->keep_ratio == 1)
7031 hb_fix_aspect( job, HB_KEEP_WIDTH );
7032 if( job->height > fTitle->height )
7034 job->height = fTitle->height;
7035 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7038 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7040 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
7042 /* we check to make sure the presets width/height does not exceed the sources width/height */
7043 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
7045 /* if so, then we use the sources height and width to avoid scaling up */
7046 //job->width = fTitle->width;
7047 //job->height = fTitle->height;
7048 [self revertPictureSizeToMax:nil];
7050 else // source width/height is >= the preset height/width
7052 /* we can go ahead and use the presets values for height and width */
7053 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
7054 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
7056 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
7057 if (job->keep_ratio == 1)
7059 int height = fTitle->height;
7061 if ( job->height && job->height < fTitle->height )
7062 height = job->height;
7064 hb_fix_aspect( job, HB_KEEP_WIDTH );
7065 // Make sure the resulting height is less than
7066 // the title height and less than the height
7067 // requested in the preset.
7068 if( job->height > height )
7070 job->height = height;
7071 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7074 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7075 if ( job->anamorphic.mode > 0 )
7077 int w, h, par_w, par_h;
7079 job->anamorphic.par_width = fTitle->pixel_aspect_width;
7080 job->anamorphic.par_height = fTitle->pixel_aspect_height;
7081 job->maxWidth = job->width;
7082 job->maxHeight = job->height;
7083 hb_set_anamorphic_size( job, &w, &h, &par_w, &par_h );
7094 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7095 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7099 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7100 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7101 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7104 [fPictureController setUseDecomb:1];
7105 [fPictureController setDecomb:0];
7106 [fPictureController setDeinterlace:0];
7107 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7109 /* we are using decomb */
7111 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7113 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7115 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7116 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7118 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7124 /* We are using Deinterlace */
7126 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7128 [fPictureController setUseDecomb:0];
7129 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7130 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7131 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7133 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7140 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7142 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7143 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7144 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7146 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7151 [fPictureController setDetelecine:0];
7155 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7157 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7158 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7159 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7161 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7166 [fPictureController setDenoise:0];
7170 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7172 /* if its a one, then its the old on/off deblock, set on to 5*/
7173 [fPictureController setDeblock:5];
7177 /* use the settings intValue */
7178 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7181 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7183 [fPictureController setGrayscale:1];
7187 [fPictureController setGrayscale:0];
7190 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7191 [fPictureController SetTitle:fTitle];
7192 [fPictureController SetTitle:fTitle];
7193 [self calculatePictureSizing:nil];
7199 #pragma mark Manage Presets
7201 - (void) loadPresets {
7202 /* We declare the default NSFileManager into fileManager */
7203 NSFileManager * fileManager = [NSFileManager defaultManager];
7204 /*We define the location of the user presets file */
7205 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7206 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7207 /* We check for the presets.plist */
7208 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7210 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7213 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7214 if (nil == UserPresets)
7216 UserPresets = [[NSMutableArray alloc] init];
7217 [self addFactoryPresets:nil];
7219 [fPresetsOutlineView reloadData];
7221 [self checkBuiltInsForUpdates];
7224 - (void) checkBuiltInsForUpdates {
7226 BOOL updateBuiltInPresets = NO;
7228 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7230 while (tempObject = [enumerator nextObject])
7232 /* iterate through the built in presets to see if any have an old build number */
7233 NSMutableDictionary *thisPresetDict = tempObject;
7234 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7235 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7237 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7239 updateBuiltInPresets = YES;
7244 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7245 if ( updateBuiltInPresets == YES)
7247 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7249 /* Show an alert window that built in presets will be updated */
7250 /*On Screen Notification*/
7253 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7254 [NSApp requestUserAttention:NSCriticalRequest];
7256 /* when alert is dismissed, go ahead and update the built in presets */
7257 [self addFactoryPresets:nil];
7263 - (IBAction) addPresetPicDropdownChanged: (id) sender
7265 if ([fPresetNewPicSettingsPopUp indexOfSelectedItem] == 1)
7267 [fPresetNewPicWidthHeightBox setHidden:NO];
7271 [fPresetNewPicWidthHeightBox setHidden:YES];
7275 - (IBAction) showAddPresetPanel: (id) sender
7277 /* Deselect the currently selected Preset if there is one*/
7278 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7280 /* Populate the preset picture settings popup here */
7281 [fPresetNewPicSettingsPopUp removeAllItems];
7282 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7283 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Custom"];
7284 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7285 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7286 /* Uncheck the preset use filters checkbox */
7287 [fPresetNewPicFiltersCheck setState:NSOffState];
7288 // fPresetNewFolderCheck
7289 [fPresetNewFolderCheck setState:NSOffState];
7290 /* Erase info from the input fields*/
7291 [fPresetNewName setStringValue: @""];
7292 [fPresetNewDesc setStringValue: @""];
7294 /* Initialize custom height and width settings to current values */
7296 [fPresetNewPicWidth setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->width]];
7297 [fPresetNewPicHeight setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->height]];
7298 [self addPresetPicDropdownChanged:nil];
7299 /* Show the panel */
7300 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7303 - (IBAction) closeAddPresetPanel: (id) sender
7305 [NSApp endSheet: fAddPresetPanel];
7306 [fAddPresetPanel orderOut: self];
7309 - (IBAction)addUserPreset:(id)sender
7311 if (![[fPresetNewName stringValue] length])
7312 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7315 /* Here we create a custom user preset */
7316 [UserPresets addObject:[self createPreset]];
7319 [self closeAddPresetPanel:nil];
7326 /* We Reload the New Table data for presets */
7327 [fPresetsOutlineView reloadData];
7328 /* We save all of the preset data here */
7336 /* We Sort the Presets By Factory or Custom */
7337 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7338 ascending:YES] autorelease];
7339 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7341 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7342 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7343 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7346 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7347 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7348 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7349 [UserPresets setArray:sortedArray];
7354 - (IBAction)insertPreset:(id)sender
7356 int index = [fPresetsOutlineView selectedRow];
7357 [UserPresets insertObject:[self createPreset] atIndex:index];
7358 [fPresetsOutlineView reloadData];
7362 - (NSDictionary *)createPreset
7364 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7365 /* Preset build number */
7366 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7367 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7368 /* Get the New Preset Name from the field in the AddPresetPanel */
7369 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7370 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7371 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7372 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7373 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7374 /*Set whether or not this is default, at creation set to 0*/
7375 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7376 if ([fPresetNewFolderCheck state] == YES)
7378 /* initialize and set an empty array for children here since we are a new folder */
7379 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7380 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7381 [childrenArray autorelease];
7383 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7385 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7386 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7387 /* Get whether or not to use the current Picture Filter settings for the preset */
7388 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7390 /* Get New Preset Description from the field in the AddPresetPanel*/
7391 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7393 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7394 /* Chapter Markers fCreateChapterMarkers*/
7395 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7396 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7397 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7398 /* Mux mp4 with http optimization */
7399 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7400 /* Add iPod uuid atom */
7401 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7405 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7406 /* x264 Option String */
7407 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7409 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7410 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7411 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7412 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7414 /* Video framerate */
7415 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7417 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7419 else // we can record the actual titleOfSelectedItem
7421 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7423 [preset setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
7425 /* 2 Pass Encoding */
7426 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7427 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7428 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7429 /*Picture Settings*/
7430 hb_job_t * job = fTitle->job;
7432 /* Picture Sizing */
7433 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7434 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicWidth intValue]] forKey:@"PictureWidth"];
7435 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicHeight intValue]] forKey:@"PictureHeight"];
7436 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7437 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7438 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7440 /* Set crop settings here */
7441 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7442 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7443 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7444 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7445 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7447 /* Picture Filters */
7448 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7449 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7450 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7451 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7452 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7453 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7454 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7455 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7456 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7457 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7458 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7461 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7462 /* we actually call the methods for the nests here */
7463 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7465 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7466 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7467 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7468 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7469 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7470 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7471 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7472 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7473 [audioTrack1Array autorelease];
7474 [audioListArray addObject:audioTrack1Array];
7477 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7479 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7480 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7481 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7482 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7483 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7484 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7485 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7486 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7487 [audioTrack2Array autorelease];
7488 [audioListArray addObject:audioTrack2Array];
7491 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7493 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7494 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7495 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7496 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7497 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7498 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7499 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7500 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7501 [audioTrack3Array autorelease];
7502 [audioListArray addObject:audioTrack3Array];
7505 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7507 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7508 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7509 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7510 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7511 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7512 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7513 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7514 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7515 [audioTrack4Array autorelease];
7516 [audioListArray addObject:audioTrack4Array];
7520 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7523 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7524 * subititle array code. */
7526 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7527 /* Forced Subtitles */
7528 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7530 [preset autorelease];
7537 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7538 /* We get the default preset in case it changed */
7539 [self getDefaultPresets:nil];
7543 - (IBAction)deletePreset:(id)sender
7547 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7551 /* Alert user before deleting preset */
7553 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7555 if ( status == NSAlertDefaultReturn )
7557 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7558 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7559 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7561 NSEnumerator *enumerator;
7562 NSMutableArray *presetsArrayToMod;
7563 NSMutableArray *tempArray;
7565 /* If we are a root level preset, we are modding the UserPresets array */
7566 if (presetToModLevel == 0)
7568 presetsArrayToMod = UserPresets;
7570 else // We have a parent preset, so we modify the chidren array object for key
7572 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7575 enumerator = [presetsArrayToMod objectEnumerator];
7576 tempArray = [NSMutableArray array];
7578 while (tempObject = [enumerator nextObject])
7580 NSDictionary *thisPresetDict = tempObject;
7581 if (thisPresetDict == presetToMod)
7583 [tempArray addObject:tempObject];
7587 [presetsArrayToMod removeObjectsInArray:tempArray];
7588 [fPresetsOutlineView reloadData];
7595 #pragma mark Import Export Preset(s)
7597 - (IBAction) browseExportPresetFile: (id) sender
7599 /* Open a panel to let the user choose where and how to save the export file */
7600 NSSavePanel * panel = [NSSavePanel savePanel];
7601 /* We get the current file name and path from the destination field here */
7602 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7604 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7605 modalForWindow: fWindow modalDelegate: self
7606 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7610 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7611 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7613 if( returnCode == NSOKButton )
7615 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7616 NSString *exportPresetsFile = [sheet filename];
7617 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7618 /* We check for the presets.plist */
7619 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7621 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7623 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7624 if (nil == presetsToExport)
7626 presetsToExport = [[NSMutableArray alloc] init];
7628 /* now get and add selected presets to export */
7631 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7633 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7634 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7642 - (IBAction) browseImportPresetFile: (id) sender
7645 NSOpenPanel * panel;
7647 panel = [NSOpenPanel openPanel];
7648 [panel setAllowsMultipleSelection: NO];
7649 [panel setCanChooseFiles: YES];
7650 [panel setCanChooseDirectories: NO ];
7651 NSString * sourceDirectory;
7652 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7654 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7658 sourceDirectory = @"~/Desktop";
7659 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7661 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7662 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7664 /* set this for allowed file types, not sure if we should allow xml or not */
7665 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7666 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7667 modalForWindow: fWindow modalDelegate: self
7668 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7669 contextInfo: sender];
7672 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7673 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7675 if( returnCode == NSOKButton )
7677 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7678 NSString *importPresetsFile = [sheet filename];
7679 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7680 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7681 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7682 /* iterate though the new array of presets to import and add them to our presets array */
7684 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7686 while (tempObject = [enumerator nextObject])
7688 /* make any changes to the incoming preset we see fit */
7689 /* make sure the incoming preset is not tagged as default */
7690 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7691 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7692 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7693 [tempObject setObject:prependedName forKey:@"PresetName"];
7695 /* actually add the new preset to our presets array */
7696 [UserPresets addObject:tempObject];
7699 [presetsToImport autorelease];
7707 #pragma mark Manage Default Preset
7709 - (IBAction)getDefaultPresets:(id)sender
7711 presetHbDefault = nil;
7712 presetUserDefault = nil;
7713 presetUserDefaultParent = nil;
7714 presetUserDefaultParentParent = nil;
7715 NSMutableDictionary *presetHbDefaultParent = nil;
7716 NSMutableDictionary *presetHbDefaultParentParent = nil;
7719 BOOL userDefaultFound = NO;
7720 presetCurrentBuiltInCount = 0;
7721 /* First we iterate through the root UserPresets array to check for defaults */
7722 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7724 while (tempObject = [enumerator nextObject])
7726 NSMutableDictionary *thisPresetDict = tempObject;
7727 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7729 presetHbDefault = thisPresetDict;
7731 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7733 presetUserDefault = thisPresetDict;
7734 userDefaultFound = YES;
7736 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7738 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7742 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7743 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7745 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7746 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7748 while (tempObject = [enumerator nextObject])
7750 NSMutableDictionary *thisPresetDict = tempObject;
7751 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7753 presetHbDefault = thisPresetDict;
7754 presetHbDefaultParent = thisPresetDictParent;
7756 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7758 presetUserDefault = thisPresetDict;
7759 presetUserDefaultParent = thisPresetDictParent;
7760 userDefaultFound = YES;
7763 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7764 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7766 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7767 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7769 while (tempObject = [enumerator nextObject])
7771 NSMutableDictionary *thisPresetDict = tempObject;
7772 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7774 presetHbDefault = thisPresetDict;
7775 presetHbDefaultParent = thisPresetDictParent;
7776 presetHbDefaultParentParent = thisPresetDictParentParent;
7778 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7780 presetUserDefault = thisPresetDict;
7781 presetUserDefaultParent = thisPresetDictParent;
7782 presetUserDefaultParentParent = thisPresetDictParentParent;
7783 userDefaultFound = YES;
7792 /* check to see if a user specified preset was found, if not then assign the parents for
7793 * the presetHbDefault so that we can open the parents for the nested presets
7795 if (userDefaultFound == NO)
7797 presetUserDefaultParent = presetHbDefaultParent;
7798 presetUserDefaultParentParent = presetHbDefaultParentParent;
7802 - (IBAction)setDefaultPreset:(id)sender
7804 /* We need to determine if the item is a folder */
7805 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7811 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7813 /* First make sure the old user specified default preset is removed */
7814 while (tempObject = [enumerator nextObject])
7816 NSMutableDictionary *thisPresetDict = tempObject;
7817 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7819 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7822 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7823 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7825 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7828 while (tempObject = [enumerator nextObject])
7830 NSMutableDictionary *thisPresetDict1 = tempObject;
7831 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7833 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7835 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7836 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7838 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7841 while (tempObject = [enumerator nextObject])
7843 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7845 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7858 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7859 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7860 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7863 NSMutableArray *presetsArrayToMod;
7864 NSMutableArray *tempArray;
7866 /* If we are a root level preset, we are modding the UserPresets array */
7867 if (presetToModLevel == 0)
7869 presetsArrayToMod = UserPresets;
7871 else // We have a parent preset, so we modify the chidren array object for key
7873 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7876 enumerator = [presetsArrayToMod objectEnumerator];
7877 tempArray = [NSMutableArray array];
7879 while (tempObject = [enumerator nextObject])
7881 NSDictionary *thisPresetDict = tempObject;
7882 if (thisPresetDict == presetToMod)
7884 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7886 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7893 /* We save all of the preset data here */
7895 /* We Reload the New Table data for presets */
7896 [fPresetsOutlineView reloadData];
7899 - (IBAction)selectDefaultPreset:(id)sender
7901 NSMutableDictionary *presetToMod;
7902 /* if there is a user specified default, we use it */
7903 if (presetUserDefault)
7905 presetToMod = presetUserDefault;
7907 else if (presetHbDefault) //else we use the built in default presetHbDefault
7909 presetToMod = presetHbDefault;
7916 if (presetUserDefaultParent != nil)
7918 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7921 if (presetUserDefaultParentParent != nil)
7923 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7927 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7928 [self selectPreset:nil];
7933 #pragma mark Manage Built In Presets
7936 - (IBAction)deleteFactoryPresets:(id)sender
7939 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7943 NSMutableArray *tempArray;
7946 tempArray = [NSMutableArray array];
7947 /* we look here to see if the preset is we move on to the next one */
7948 while ( tempObject = [enumerator nextObject] )
7950 /* if the preset is "Factory" then we put it in the array of
7951 presets to delete */
7952 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7954 [tempArray addObject:tempObject];
7958 [UserPresets removeObjectsInArray:tempArray];
7959 [fPresetsOutlineView reloadData];
7964 /* We use this method to recreate new, updated factory presets */
7965 - (IBAction)addFactoryPresets:(id)sender
7968 /* First, we delete any existing built in presets */
7969 [self deleteFactoryPresets: sender];
7970 /* Then we generate new built in presets programmatically with fPresetsBuiltin
7971 * which is all setup in HBPresets.h and HBPresets.m*/
7972 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
7973 /* update build number for built in presets */
7974 /* iterate though the new array of presets to import and add them to our presets array */
7976 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7978 while (tempObject = [enumerator nextObject])
7980 /* Record the apps current build number in the PresetBuildNumber key */
7981 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7983 /* Preset build number */
7984 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7988 /* report the built in preset updating to the activity log */
7989 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
7997 #pragma mark Chapter Files Import / Export
7999 - (IBAction) browseForChapterFile: (id) sender
8001 /* Open a panel to let the user choose the file */
8002 NSOpenPanel * panel = [NSOpenPanel openPanel];
8003 /* We get the current file name and path from the destination field here */
8004 [panel beginSheetForDirectory: [NSString stringWithFormat:@"%@/",
8005 [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"]]
8007 types: [NSArray arrayWithObjects:@"csv",nil]
8008 modalForWindow: fWindow modalDelegate: self
8009 didEndSelector: @selector( browseForChapterFileDone:returnCode:contextInfo: )
8013 - (void) browseForChapterFileDone: (NSOpenPanel *) sheet
8014 returnCode: (int) returnCode contextInfo: (void *) contextInfo
8016 NSArray *chaptersArray; /* temp array for chapters */
8017 NSMutableArray *chaptersMutableArray; /* temp array for chapters */
8018 NSString *chapterName; /* temp string from file */
8021 if( returnCode == NSOKButton ) /* if they click OK */
8023 chapterName = [[NSString alloc] initWithContentsOfFile:[sheet filename] encoding:NSUTF8StringEncoding error:NULL];
8024 chaptersArray = [chapterName componentsSeparatedByString:@"\n"];
8025 chaptersMutableArray= [chaptersArray mutableCopy];
8026 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
8027 if ([chaptersMutableArray count] > 0)
8029 /* if last item is empty remove it */
8030 if ([[chaptersMutableArray objectAtIndex:[chaptersArray count]-1] length] == 0)
8032 [chaptersMutableArray removeLastObject];
8035 /* if chapters in table is not equal to array count */
8036 if ((unsigned int) chapters != [chaptersMutableArray count])
8039 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
8040 defaultButton:NSLocalizedString(@"OK", @"OK")
8041 alternateButton:NULL
8043 informativeTextWithFormat:NSLocalizedString(@"%d chapters expected, %d chapters found in %@", @"%d chapters expected, %d chapters found in %@"),
8044 chapters, [chaptersMutableArray count], [[sheet filename] lastPathComponent]] runModal];
8047 /* otherwise, go ahead and populate table with array */
8048 for (i=0; i<chapters; i++)
8051 if([[chaptersMutableArray objectAtIndex:i] length] > 5)
8053 /* avoid a segfault */
8054 /* Get the Range.location of the first comma in the line and then put everything after that into chapterTitle */
8055 NSRange firstCommaRange = [[chaptersMutableArray objectAtIndex:i] rangeOfString:@","];
8056 NSString *chapterTitle = [[chaptersMutableArray objectAtIndex:i] substringFromIndex:firstCommaRange.location + 1];
8057 /* Since we store our chapterTitle commas as "\," for the cli, we now need to remove the escaping "\" from the title */
8058 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"\\," withString:@","];
8059 [fChapterTitlesDelegate tableView:fChapterTable
8060 setObjectValue:chapterTitle
8061 forTableColumn:fChapterTableNameColumn
8067 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
8068 defaultButton:NSLocalizedString(@"OK", @"OK")
8069 alternateButton:NULL
8071 informativeTextWithFormat:NSLocalizedString(@"%@ was not formatted as expected.", @"%@ was not formatted as expected."), [[sheet filename] lastPathComponent]] runModal];
8072 [fChapterTable reloadData];
8076 [fChapterTable reloadData];
8080 - (IBAction) browseForChapterFileSave: (id) sender
8082 NSSavePanel *panel = [NSSavePanel savePanel];
8083 /* Open a panel to let the user save to a file */
8084 [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv",nil]];
8085 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent]
8086 file: [[[[fDstFile2Field stringValue] lastPathComponent] stringByDeletingPathExtension]
8087 stringByAppendingString:@"-chapters.csv"]
8088 modalForWindow: fWindow
8090 didEndSelector: @selector( browseForChapterFileSaveDone:returnCode:contextInfo: )
8094 - (void) browseForChapterFileSaveDone: (NSSavePanel *) sheet
8095 returnCode: (int) returnCode contextInfo: (void *) contextInfo
8097 NSString *chapterName; /* pointer for string for later file-writing */
8098 NSString *chapterTitle;
8099 NSError *saveError = [[NSError alloc] init];
8100 int chapters, i; /* ints for the number of chapters in the table and the loop */
8102 if( returnCode == NSOKButton ) /* if they clicked OK */
8104 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
8105 chapterName = [NSString string];
8106 for (i=0; i<chapters; i++)
8108 /* put each chapter title from the table into the array */
8110 { /* if i is from 0 to 8 (chapters 1 to 9) add two leading zeros */
8111 chapterName = [chapterName stringByAppendingFormat:@"00%d,",i+1];
8114 { /* if i is from 9 to 98 (chapters 10 to 99) add one leading zero */
8115 chapterName = [chapterName stringByAppendingFormat:@"0%d,",i+1];
8118 { /* in case i is from 99 to 998 (chapters 100 to 999) no leading zeros */
8119 chapterName = [chapterName stringByAppendingFormat:@"%d,",i+1];
8122 chapterTitle = [fChapterTitlesDelegate tableView:fChapterTable objectValueForTableColumn:fChapterTableNameColumn row:i];
8123 /* escape any commas in the chapter name with "\," */
8124 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"," withString:@"\\,"];
8125 chapterName = [chapterName stringByAppendingString:chapterTitle];
8126 if (i+1 != chapters)
8127 { /* if not the last chapter */
8128 chapterName = [chapterName stringByAppendingString:@ "\n"];
8133 /* try to write it to where the user wanted */
8134 if (![chapterName writeToFile:[sheet filename]
8136 encoding:NSUTF8StringEncoding
8140 [[NSAlert alertWithError:saveError] runModal];
8147 /*******************************
8148 * Subclass of the HBPresetsOutlineView *
8149 *******************************/
8151 @implementation HBPresetsOutlineView
8152 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8156 // By default, NSTableView only drags an image of the first column. Change this to
8157 // drag an image of the queue's icon and PresetName columns.
8158 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8159 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8164 - (void) mouseDown:(NSEvent *)theEvent
8166 [super mouseDown:theEvent];
8172 - (BOOL) isDragging;