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]];
92 - (void) applicationDidFinishLaunching: (NSNotification *) notification
94 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
95 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
96 fHandle = hb_init(loggingLevel, 0);
97 /* Optional dvd nav UseDvdNav*/
98 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
99 /* Init a separate instance of libhb for user scanning and setting up jobs */
100 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
102 // Set the Growl Delegate
103 [GrowlApplicationBridge setGrowlDelegate: self];
104 /* Init others controllers */
105 [fPictureController SetHandle: fHandle];
106 [fPictureController setHBController: self];
108 [fQueueController setHandle: fQueueEncodeLibhb];
109 [fQueueController setHBController: self];
111 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
112 [fChapterTable setDataSource:fChapterTitlesDelegate];
113 [fChapterTable setDelegate:fChapterTitlesDelegate];
115 /* setup the subtitles delegate and connections to table */
116 fSubtitlesDelegate = [[HBSubtitles alloc] init];
117 [fSubtitlesTable setDataSource:fSubtitlesDelegate];
118 [fSubtitlesTable setDelegate:fSubtitlesDelegate];
119 [fSubtitlesTable setRowHeight:25.0];
121 [fPresetsOutlineView setAutosaveName:@"Presets View"];
122 [fPresetsOutlineView setAutosaveExpandedItems:YES];
124 dockIconProgress = 0;
126 /* Call UpdateUI every 1/2 sec */
127 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
128 scheduledTimerWithTimeInterval:0.5 target:self
129 selector:@selector(updateUI:) userInfo:nil repeats:YES]
130 forMode:NSDefaultRunLoopMode];
132 // Open debug output window now if it was visible when HB was closed
133 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
134 [self showDebugOutputPanel:nil];
136 // Open queue window now if it was visible when HB was closed
137 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
138 [self showQueueWindow:nil];
140 [self openMainWindow:nil];
142 /* We have to set the bool to tell hb what to do after a scan
143 * Initially we set it to NO until we start processing the queue
145 applyQueueToScan = NO;
147 /* Now we re-check the queue array to see if there are
148 * any remaining encodes to be done in it and ask the
149 * user if they want to reload the queue */
150 if ([QueueFileArray count] > 0)
152 /* run getQueueStats to see whats in the queue file */
153 [self getQueueStats];
154 /* this results in these values
155 * fEncodingQueueItem = 0;
157 * fCompletedCount = 0;
158 * fCanceledCount = 0;
162 /*On Screen Notification*/
163 NSString * alertTitle;
165 /* We check to see if there is already another instance of hb running.
166 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
168 if ([self hbInstances] > 1)
170 alertTitle = [NSString stringWithFormat:
171 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
172 NSBeginCriticalAlertSheet(
174 NSLocalizedString(@"Reload Queue", nil),
178 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
179 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
183 if (fWorkingCount > 0)
185 alertTitle = [NSString stringWithFormat:
186 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item and %d Pending Item(s) In Your Queue.", @""),
187 fWorkingCount,fPendingCount];
191 alertTitle = [NSString stringWithFormat:
192 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
196 NSBeginCriticalAlertSheet(
198 NSLocalizedString(@"Reload Queue", nil),
200 NSLocalizedString(@"Empty Queue", nil),
202 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
203 NSLocalizedString(@" Do you want to reload them ?", nil));
209 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
210 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
212 [self browseSources:nil];
215 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
217 [self browseSources:(id)fOpenSourceTitleMMenu];
224 /* check to see if another instance of HandBrake.app is running */
225 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
226 NSDictionary *aDictionary;
228 for (aDictionary in runningAppDictionaries)
230 if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
238 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
240 if (returnCode == NSAlertOtherReturn)
242 [self clearQueueAllItems];
243 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
244 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
246 [self browseSources:nil];
249 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
251 [self browseSources:(id)fOpenSourceTitleMMenu];
256 if ([self hbInstances] == 1)
258 [self setQueueEncodingItemsAsPending];
260 [self showQueueWindow:NULL];
264 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
269 hb_get_state( fQueueEncodeLibhb, &s );
271 if ( s.state != HB_STATE_IDLE )
273 int result = NSRunCriticalAlertPanel(
274 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
275 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
276 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
278 if (result == NSAlertDefaultReturn)
280 return NSTerminateNow;
283 return NSTerminateCancel;
286 // Warn if items still in the queue
287 else if ( fPendingCount > 0 )
289 int result = NSRunCriticalAlertPanel(
290 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
291 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
292 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
294 if ( result == NSAlertDefaultReturn )
295 return NSTerminateNow;
297 return NSTerminateCancel;
300 return NSTerminateNow;
303 - (void)applicationWillTerminate:(NSNotification *)aNotification
306 [browsedSourceDisplayName release];
307 [outputPanel release];
308 [fQueueController release];
309 [fPreviewController release];
310 [fPictureController release];
311 [fApplicationIcon release];
314 hb_close(&fQueueEncodeLibhb);
320 - (void) awakeFromNib
323 [fWindow setExcludedFromWindowsMenu:NO];
325 [fAdvancedOptions setView:fAdvancedView];
327 /* lets setup our presets drawer for drag and drop here */
328 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
329 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
330 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
332 /* Initialize currentScanCount so HB can use it to
333 evaluate successive scans */
334 currentScanCount = 0;
337 /* Init UserPresets .plist */
340 /* Init QueueFile .plist */
341 [self loadQueueFile];
343 fRipIndicatorShown = NO; // initially out of view in the nib
345 /* For 64 bit builds, the threaded animation in the progress
346 * indicators conflicts with the animation in the advanced tab
347 * for reasons not completely clear. jbrjake found a note in the
348 * 10.5 dev notes regarding this possiblility. It was also noted
349 * that unless specified, setUsesThreadedAnimation defaults to true.
350 * So, at least for now we set the indicator animation to NO for
351 * both the scan and regular progress indicators for both 32 and 64 bit
352 * as it test out fine on both and there is no reason our progress indicators
353 * should require their own thread.
356 [fScanIndicator setUsesThreadedAnimation:NO];
357 [fRipIndicator setUsesThreadedAnimation:NO];
361 /* Show/Dont Show Presets drawer upon launch based
362 on user preference DefaultPresetsDrawerShow*/
363 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
365 [fPresetDrawer setDelegate:self];
366 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
367 stringForKey:@"Drawer Size"] );
368 if( drawerSize.width )
369 [fPresetDrawer setContentSize: drawerSize];
370 [fPresetDrawer open];
373 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
374 [fSrcAngleLabel setHidden:YES];
375 [fSrcAnglePopUp setHidden:YES];
377 /* Setup the start / stop popup */
378 [fEncodeStartStopPopUp removeAllItems];
379 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
380 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
381 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
382 /* Align the start / stop widgets with the chapter popups */
383 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
384 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
386 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
387 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
390 NSMenuItem *menuItem;
391 [fDstFormatPopUp removeAllItems];
393 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
394 [menuItem setTag: HB_MUX_MP4];
396 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
397 [menuItem setTag: HB_MUX_MKV];
399 [fDstFormatPopUp selectItemAtIndex: 0];
401 [self formatPopUpChanged:nil];
403 /* We enable the create chapters checkbox here since we are .mp4 */
404 [fCreateChapterMarkers setEnabled: YES];
405 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
407 [fCreateChapterMarkers setState: NSOnState];
413 [fDstFile2Field setStringValue: [NSString stringWithFormat:
414 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
417 [fVidEncoderPopUp removeAllItems];
418 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
422 [fVidTargetSizeField setIntValue: 700];
423 [fVidBitrateField setIntValue: 1000];
425 [fVidQualityMatrix selectCell: fVidBitrateCell];
426 [self videoMatrixChanged:nil];
428 /* Video framerate */
429 [fVidRatePopUp removeAllItems];
430 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
431 for( int i = 0; i < hb_video_rates_count; i++ )
433 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
435 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
436 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
438 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
440 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
441 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
443 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
445 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
446 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
450 [fVidRatePopUp addItemWithTitle:
451 [NSString stringWithUTF8String: hb_video_rates[i].string]];
454 [fVidRatePopUp selectItemAtIndex: 0];
456 /* Set Auto Crop to On at launch */
457 [fPictureController setAutoCrop:YES];
460 [fAudTrack1BitratePopUp removeAllItems];
461 for( int i = 0; i < hb_audio_bitrates_count; i++ )
463 [fAudTrack1BitratePopUp addItemWithTitle:
464 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]];
467 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
469 /* Audio samplerate */
470 [fAudTrack1RatePopUp removeAllItems];
471 for( int i = 0; i < hb_audio_rates_count; i++ )
473 [fAudTrack1RatePopUp addItemWithTitle:
474 [NSString stringWithUTF8String: hb_audio_rates[i].string]];
476 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
479 [fStatusField setStringValue: @""];
484 /* We disable the Turbo 1st pass checkbox since we are not x264 */
485 [fVidTurboPassCheck setEnabled: NO];
486 [fVidTurboPassCheck setState: NSOffState];
489 /* lets get our default prefs here */
490 [self getDefaultPresets:nil];
491 /* lets initialize the current successful scancount here to 0 */
492 currentSuccessfulScanCount = 0;
497 - (void) enableUI: (bool) b
499 NSControl * controls[] =
500 { fSrcTitleField, fSrcTitlePopUp,
501 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
502 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
503 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
504 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
505 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
506 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
507 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
508 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
509 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
510 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
511 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
512 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
513 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
514 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
515 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
516 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
517 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
518 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,
519 fSrcFrameEndEncodingField, fLoadChaptersButton, fSaveChaptersButton, fFrameratePfrCheck};
522 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
524 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
526 NSTextField * tf = (NSTextField *) controls[i];
527 if( ![tf isBezeled] )
529 [tf setTextColor: b ? [NSColor controlTextColor] :
530 [NSColor disabledControlTextColor]];
534 [controls[i] setEnabled: b];
540 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
541 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
542 [self setEnabledStateOfAudioMixdownControls:nil];
543 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
544 [self calculatePictureSizing:nil];
548 [fPresetsOutlineView setEnabled: NO];
552 [self videoMatrixChanged:nil];
553 [fAdvancedOptions enableUI:b];
557 /***********************************************************************
559 ***********************************************************************
560 * Shows a progression bar on the dock icon, filled according to
561 * 'progress' (0.0 <= progress <= 1.0).
562 * Called with progress < 0.0 or progress > 1.0, restores the original
564 **********************************************************************/
565 - (void) UpdateDockIcon: (float) progress
568 NSBitmapImageRep * bmp;
570 uint32_t black = htonl( 0x000000FF );
571 uint32_t red = htonl( 0xFF0000FF );
572 uint32_t white = htonl( 0xFFFFFFFF );
573 int row_start, row_end;
576 if( progress < 0.0 || progress > 1.0 )
578 [NSApp setApplicationIconImage: fApplicationIcon];
582 /* Get it in a raw bitmap form */
583 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
584 NSTIFFCompressionNone factor: 1.0];
585 bmp = [NSBitmapImageRep imageRepWithData: tiff];
587 /* Draw the progression bar */
588 /* It's pretty simple (ugly?) now, but I'm no designer */
590 row_start = 3 * (int) [bmp size].height / 4;
591 row_end = 7 * (int) [bmp size].height / 8;
593 for( i = row_start; i < row_start + 2; i++ )
595 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
596 for( j = 0; j < (int) [bmp size].width; j++ )
601 for( i = row_start + 2; i < row_end - 2; i++ )
603 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
606 for( j = 2; j < (int) [bmp size].width - 2; j++ )
608 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
620 for( i = row_end - 2; i < row_end; i++ )
622 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
623 for( j = 0; j < (int) [bmp size].width; j++ )
629 /* Now update the dock icon */
630 tiff = [bmp TIFFRepresentationUsingCompression:
631 NSTIFFCompressionNone factor: 1.0];
632 NSImage* icon = [[NSImage alloc] initWithData: tiff];
633 [NSApp setApplicationIconImage: icon];
637 - (void) updateUI: (NSTimer *) timer
640 /* Update UI for fHandle (user scanning instance of libhb ) */
643 list = hb_get_titles( fHandle );
644 /* check to see if there has been a new scan done
645 this bypasses the constraints of HB_STATE_WORKING
646 not allowing setting a newly scanned source */
647 int checkScanCount = hb_get_scancount( fHandle );
648 if( checkScanCount > currentScanCount )
650 currentScanCount = checkScanCount;
651 [fScanIndicator setIndeterminate: NO];
652 [fScanIndicator setDoubleValue: 0.0];
653 [fScanIndicator setHidden: YES];
654 [self showNewScan:nil];
658 hb_get_state( fHandle, &s );
664 #define p s.param.scanning
665 case HB_STATE_SCANNING:
667 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
668 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
669 p.title_cur, p.title_count]];
670 [fScanIndicator setHidden: NO];
671 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
676 #define p s.param.scandone
677 case HB_STATE_SCANDONE:
679 [fScanIndicator setIndeterminate: NO];
680 [fScanIndicator setDoubleValue: 0.0];
681 [fScanIndicator setHidden: YES];
682 [self writeToActivityLog:"ScanDone state received from fHandle"];
683 [self showNewScan:nil];
684 [[fWindow toolbar] validateVisibleItems];
690 #define p s.param.working
691 case HB_STATE_WORKING:
698 #define p s.param.muxing
699 case HB_STATE_MUXING:
706 case HB_STATE_PAUSED:
709 case HB_STATE_WORKDONE:
716 /* Update UI for fQueueEncodeLibhb */
718 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
719 /* check to see if there has been a new scan done
720 this bypasses the constraints of HB_STATE_WORKING
721 not allowing setting a newly scanned source */
723 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
724 if( checkScanCount > currentScanCount )
726 currentScanCount = checkScanCount;
730 hb_get_state( fQueueEncodeLibhb, &s );
736 #define p s.param.scanning
737 case HB_STATE_SCANNING:
739 [fStatusField setStringValue: [NSString stringWithFormat:
740 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
741 p.title_cur, p.title_count]];
743 /* Set the status string in fQueueController as well */
744 [fQueueController setQueueStatusString: [NSString stringWithFormat:
745 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
746 p.title_cur, p.title_count]];
751 #define p s.param.scandone
752 case HB_STATE_SCANDONE:
754 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
755 [self processNewQueueEncode];
756 [[fWindow toolbar] validateVisibleItems];
763 #define p s.param.working
765 case HB_STATE_SEARCHING:
767 NSMutableString * string;
768 NSString * pass_desc;
770 /* Update text field */
772 //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];
773 /* For now, do not announce "pass x of x for the search phase ... */
774 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
778 [string appendFormat:
779 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
782 [fStatusField setStringValue: string];
783 /* Set the status string in fQueueController as well */
784 [fQueueController setQueueStatusString: string];
786 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
787 [fRipIndicator setIndeterminate: NO];
788 [fRipIndicator setDoubleValue:100.0 * progress_total];
790 // If progress bar hasn't been revealed at the bottom of the window, do
791 // that now. This code used to be in doRip. I moved it to here to handle
792 // the case where hb_start is called by HBQueueController and not from
794 if( !fRipIndicatorShown )
796 NSRect frame = [fWindow frame];
797 if( frame.size.width <= 591 )
798 frame.size.width = 591;
799 frame.size.height += 36;
800 frame.origin.y -= 36;
801 [fWindow setFrame:frame display:YES animate:YES];
802 fRipIndicatorShown = YES;
806 /* Update dock icon */
807 /* Note not done yet */
812 case HB_STATE_WORKING:
814 NSMutableString * string;
815 NSString * pass_desc;
816 /* Update text field */
817 if (p.job_cur == 1 && p.job_count > 1)
819 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
821 pass_desc = @"(subtitle scan)";
833 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
837 [string appendFormat:
838 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
839 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
842 [fStatusField setStringValue: string];
843 /* Set the status string in fQueueController as well */
844 [fQueueController setQueueStatusString: string];
846 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
847 [fRipIndicator setIndeterminate: NO];
848 [fRipIndicator setDoubleValue:100.0 * progress_total];
850 // If progress bar hasn't been revealed at the bottom of the window, do
851 // that now. This code used to be in doRip. I moved it to here to handle
852 // the case where hb_start is called by HBQueueController and not from
854 if( !fRipIndicatorShown )
856 NSRect frame = [fWindow frame];
857 if( frame.size.width <= 591 )
858 frame.size.width = 591;
859 frame.size.height += 36;
860 frame.origin.y -= 36;
861 [fWindow setFrame:frame display:YES animate:YES];
862 fRipIndicatorShown = YES;
866 /* Update dock icon */
867 if( dockIconProgress < 100.0 * progress_total )
869 [self UpdateDockIcon: progress_total];
870 dockIconProgress += 5;
877 #define p s.param.muxing
878 case HB_STATE_MUXING:
880 /* Update text field */
881 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
882 /* Set the status string in fQueueController as well */
883 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
885 [fRipIndicator setIndeterminate: YES];
886 [fRipIndicator startAnimation: nil];
888 /* Update dock icon */
889 [self UpdateDockIcon: 1.0];
895 case HB_STATE_PAUSED:
896 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
897 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
901 case HB_STATE_WORKDONE:
903 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
904 // or someone calling hb_stop. In the latter case, hb_stop does not clear
905 // out the remaining passes/jobs in the queue. We'll do that here.
907 // Delete all remaining jobs of this encode.
908 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
909 /* Set the status string in fQueueController as well */
910 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
911 [fRipIndicator setIndeterminate: NO];
912 [fRipIndicator stopAnimation: nil];
913 [fRipIndicator setDoubleValue: 0.0];
914 [[fWindow toolbar] validateVisibleItems];
916 /* Restore dock icon */
917 [self UpdateDockIcon: -1.0];
918 dockIconProgress = 0;
920 if( fRipIndicatorShown )
922 NSRect frame = [fWindow frame];
923 if( frame.size.width <= 591 )
924 frame.size.width = 591;
925 frame.size.height += -36;
926 frame.origin.y -= -36;
927 [fWindow setFrame:frame display:YES animate:YES];
928 fRipIndicatorShown = NO;
930 /* Since we are done with this encode, tell output to stop writing to the
931 * individual encode log
933 [outputPanel endEncodeLog];
934 /* Check to see if the encode state has not been cancelled
935 to determine if we should check for encode done notifications */
936 if( fEncodeState != 2 )
938 NSString *pathOfFinishedEncode;
939 /* Get the output file name for the finished encode */
940 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
942 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
944 [self showGrowlDoneNotification:pathOfFinishedEncode];
946 [self sendToMetaX:pathOfFinishedEncode];
948 /* since we have successfully completed an encode, we increment the queue counter */
949 [self incrementQueueItemDone:nil];
951 /* all end of queue actions below need to be done after all queue encodes have finished
952 * and there are no pending jobs left to process
954 if (fPendingCount == 0)
956 /* If Alert Window or Window and Growl has been selected */
957 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
958 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
960 /*On Screen Notification*/
963 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
964 [NSApp requestUserAttention:NSCriticalRequest];
967 /* If sleep has been selected */
968 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
971 NSDictionary* errorDict;
972 NSAppleEventDescriptor* returnDescriptor = nil;
973 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
974 @"tell application \"Finder\" to sleep"];
975 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
976 [scriptObject release];
978 /* If Shutdown has been selected */
979 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
982 NSDictionary* errorDict;
983 NSAppleEventDescriptor* returnDescriptor = nil;
984 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
985 @"tell application \"Finder\" to shut down"];
986 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
987 [scriptObject release];
1001 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1002 - (void) writeToActivityLog:(const char *) format, ...
1005 va_start(args, format);
1009 vsnprintf( str, 1024, format, args );
1011 time_t _now = time( NULL );
1012 struct tm * now = localtime( &_now );
1013 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1019 #pragma mark Toolbar
1020 // ============================================================
1021 // NSToolbar Related Methods
1022 // ============================================================
1024 - (void) setupToolbar {
1025 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1027 [toolbar setAllowsUserCustomization: YES];
1028 [toolbar setAutosavesConfiguration: YES];
1029 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1031 [toolbar setDelegate: self];
1033 [fWindow setToolbar: toolbar];
1036 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1037 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1038 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1040 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1042 [item setLabel: @"Toggle Presets"];
1043 [item setPaletteLabel: @"Toggler Presets"];
1044 [item setToolTip: @"Open/Close Preset Drawer"];
1045 [item setImage: [NSImage imageNamed: @"Drawer"]];
1046 [item setTarget: self];
1047 [item setAction: @selector(toggleDrawer:)];
1048 [item setAutovalidates: NO];
1050 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1052 [item setLabel: @"Start"];
1053 [item setPaletteLabel: @"Start Encoding"];
1054 [item setToolTip: @"Start Encoding"];
1055 [item setImage: [NSImage imageNamed: @"Play"]];
1056 [item setTarget: self];
1057 [item setAction: @selector(Rip:)];
1059 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1061 [item setLabel: @"Show Queue"];
1062 [item setPaletteLabel: @"Show Queue"];
1063 [item setToolTip: @"Show Queue"];
1064 [item setImage: [NSImage imageNamed: @"Queue"]];
1065 [item setTarget: self];
1066 [item setAction: @selector(showQueueWindow:)];
1067 [item setAutovalidates: NO];
1069 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1071 [item setLabel: @"Add to Queue"];
1072 [item setPaletteLabel: @"Add to Queue"];
1073 [item setToolTip: @"Add to Queue"];
1074 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1075 [item setTarget: self];
1076 [item setAction: @selector(addToQueue:)];
1078 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1080 [item setLabel: @"Pause"];
1081 [item setPaletteLabel: @"Pause Encoding"];
1082 [item setToolTip: @"Pause Encoding"];
1083 [item setImage: [NSImage imageNamed: @"Pause"]];
1084 [item setTarget: self];
1085 [item setAction: @selector(Pause:)];
1087 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1089 [item setLabel: @"Picture Settings"];
1090 [item setPaletteLabel: @"Show Picture Settings"];
1091 [item setToolTip: @"Show Picture Settings"];
1092 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1093 [item setTarget: self];
1094 [item setAction: @selector(showPicturePanel:)];
1096 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1098 [item setLabel: @"Preview Window"];
1099 [item setPaletteLabel: @"Show Preview"];
1100 [item setToolTip: @"Show Preview"];
1101 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1102 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1103 [item setTarget: self];
1104 [item setAction: @selector(showPreviewWindow:)];
1106 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1108 [item setLabel: @"Activity Window"];
1109 [item setPaletteLabel: @"Show Activity Window"];
1110 [item setToolTip: @"Show Activity Window"];
1111 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1112 [item setTarget: self];
1113 [item setAction: @selector(showDebugOutputPanel:)];
1114 [item setAutovalidates: NO];
1116 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1118 [item setLabel: @"Source"];
1119 [item setPaletteLabel: @"Source"];
1120 [item setToolTip: @"Choose Video Source"];
1121 [item setImage: [NSImage imageNamed: @"Source"]];
1122 [item setTarget: self];
1123 [item setAction: @selector(browseSources:)];
1133 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1135 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1136 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1137 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1140 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1142 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1143 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1144 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1145 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1148 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1150 NSString * ident = [toolbarItem itemIdentifier];
1156 hb_get_state( fHandle, &s );
1157 if (s.state == HB_STATE_SCANNING)
1160 if ([ident isEqualToString: ChooseSourceIdentifier])
1162 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1163 [toolbarItem setLabel: @"Cancel Scan"];
1164 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1165 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1169 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1174 if ([ident isEqualToString: ChooseSourceIdentifier])
1176 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1177 [toolbarItem setLabel: @"Source"];
1178 [toolbarItem setPaletteLabel: @"Source"];
1179 [toolbarItem setToolTip: @"Choose Video Source"];
1184 hb_get_state2( fQueueEncodeLibhb, &s );
1186 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1188 if ([ident isEqualToString: StartEncodingIdentifier])
1190 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1191 [toolbarItem setLabel: @"Stop"];
1192 [toolbarItem setPaletteLabel: @"Stop"];
1193 [toolbarItem setToolTip: @"Stop Encoding"];
1196 if ([ident isEqualToString: PauseEncodingIdentifier])
1198 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1199 [toolbarItem setLabel: @"Pause"];
1200 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1201 [toolbarItem setToolTip: @"Pause Encoding"];
1206 if ([ident isEqualToString: AddToQueueIdentifier])
1208 if ([ident isEqualToString: ShowPictureIdentifier])
1210 if ([ident isEqualToString: ShowPreviewIdentifier])
1214 else if (s.state == HB_STATE_PAUSED)
1216 if ([ident isEqualToString: PauseEncodingIdentifier])
1218 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1219 [toolbarItem setLabel: @"Resume"];
1220 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1221 [toolbarItem setToolTip: @"Resume Encoding"];
1224 if ([ident isEqualToString: StartEncodingIdentifier])
1226 if ([ident isEqualToString: AddToQueueIdentifier])
1228 if ([ident isEqualToString: ShowPictureIdentifier])
1230 if ([ident isEqualToString: ShowPreviewIdentifier])
1233 else if (s.state == HB_STATE_SCANNING)
1235 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1237 if ([ident isEqualToString: StartEncodingIdentifier])
1239 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1240 if (hb_count(fHandle) > 0)
1241 [toolbarItem setLabel: @"Start Queue"];
1243 [toolbarItem setLabel: @"Start"];
1244 [toolbarItem setPaletteLabel: @"Start Encoding"];
1245 [toolbarItem setToolTip: @"Start Encoding"];
1248 if ([ident isEqualToString: AddToQueueIdentifier])
1250 if ([ident isEqualToString: ShowPictureIdentifier])
1252 if ([ident isEqualToString: ShowPreviewIdentifier])
1257 /* If there are any pending queue items, make sure the start/stop button is active */
1258 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1260 if ([ident isEqualToString: ShowQueueIdentifier])
1262 if ([ident isEqualToString: ToggleDrawerIdentifier])
1264 if ([ident isEqualToString: ChooseSourceIdentifier])
1266 if ([ident isEqualToString: ShowActivityIdentifier])
1272 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1274 SEL action = [menuItem action];
1277 hb_get_state2( fHandle, &s );
1281 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1282 return SuccessfulScan && [fWindow attachedSheet] == nil;
1284 if (action == @selector(browseSources:))
1286 if (s.state == HB_STATE_SCANNING)
1289 return [fWindow attachedSheet] == nil;
1291 if (action == @selector(selectDefaultPreset:))
1292 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1293 if (action == @selector(Pause:))
1295 if (s.state == HB_STATE_WORKING)
1297 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1298 [menuItem setTitle:@"Pause Encoding"];
1301 else if (s.state == HB_STATE_PAUSED)
1303 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1304 [menuItem setTitle:@"Resume Encoding"];
1310 if (action == @selector(Rip:))
1312 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1314 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1315 [menuItem setTitle:@"Stop Encoding"];
1318 else if (SuccessfulScan)
1320 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1321 [menuItem setTitle:@"Start Encoding"];
1322 return [fWindow attachedSheet] == nil;
1328 if( action == @selector(setDefaultPreset:) )
1330 return [fPresetsOutlineView selectedRow] != -1;
1337 #pragma mark Encode Done Actions
1338 // register a test notification and make
1339 // it enabled by default
1340 #define SERVICE_NAME @"Encode Done"
1341 - (NSDictionary *)registrationDictionaryForGrowl
1343 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1344 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1345 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1348 return registrationDictionary;
1351 -(void)showGrowlDoneNotification:(NSString *) filePath
1353 /* This end of encode action is called as each encode rolls off of the queue */
1354 NSString * finishedEncode = filePath;
1355 /* strip off the path to just show the file name */
1356 finishedEncode = [finishedEncode lastPathComponent];
1357 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1358 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1360 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1361 [GrowlApplicationBridge
1362 notifyWithTitle:@"Put down that cocktail..."
1363 description:growlMssg
1364 notificationName:SERVICE_NAME
1372 -(void)sendToMetaX:(NSString *) filePath
1374 /* This end of encode action is called as each encode rolls off of the queue */
1375 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1377 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1378 if (![sendToApp isEqualToString:@"None"])
1380 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1381 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1382 [myScript executeAndReturnError: nil];
1389 #pragma mark Get New Source
1391 /*Opens the source browse window, called from Open Source widgets */
1392 - (IBAction) browseSources: (id) sender
1396 hb_get_state( fHandle, &s );
1397 if (s.state == HB_STATE_SCANNING)
1399 [self cancelScanning:nil];
1404 NSOpenPanel * panel;
1406 panel = [NSOpenPanel openPanel];
1407 [panel setAllowsMultipleSelection: NO];
1408 [panel setCanChooseFiles: YES];
1409 [panel setCanChooseDirectories: YES ];
1410 NSString * sourceDirectory;
1411 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1413 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1417 sourceDirectory = @"~/Desktop";
1418 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1420 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1421 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1423 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1424 modalForWindow: fWindow modalDelegate: self
1425 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1426 contextInfo: sender];
1429 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1430 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1432 /* we convert the sender content of contextInfo back into a variable called sender
1433 * mostly just for consistency for evaluation later
1435 id sender = (id)contextInfo;
1436 /* User selected a file to open */
1437 if( returnCode == NSOKButton )
1439 /* Free display name allocated previously by this code */
1440 [browsedSourceDisplayName release];
1442 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1443 /* we set the last searched source directory in the prefs here */
1444 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1445 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1446 /* we order out sheet, which is the browse window as we need to open
1447 * the title selection sheet right away
1449 [sheet orderOut: self];
1451 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1453 /* We put the chosen source path in the source display text field for the
1454 * source title selection sheet in which the user specifies the specific title to be
1455 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1456 * purposes in the title panel
1459 [fScanSrcTitlePathField setStringValue:scanPath];
1460 NSString *displayTitlescanSourceName;
1462 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1464 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1465 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1466 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1470 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1471 displayTitlescanSourceName = [scanPath lastPathComponent];
1473 /* we set the source display name in the title selection dialogue */
1474 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1475 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1476 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1477 /* We show the actual sheet where the user specifies the title to be scanned
1478 * as we are going to do a title specific scan
1480 [self showSourceTitleScanPanel:nil];
1484 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1485 NSString *path = [[sheet filenames] objectAtIndex: 0];
1487 /* We check to see if the chosen file at path is a package */
1488 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1490 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1491 /* We check to see if this is an .eyetv package */
1492 if ([[path pathExtension] isEqualToString: @"eyetv"])
1494 [self writeToActivityLog:"trying to open eyetv package"];
1495 /* We're looking at an EyeTV package - try to open its enclosed
1497 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1499 int n = [[path stringByAppendingString: @"/"]
1500 completePathIntoString: &mpgname caseSensitive: YES
1501 matchesIntoArray: nil
1502 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1505 /* Found an mpeg inside the eyetv package, make it our scan path
1506 and call performScan on the enclosed mpeg */
1508 [self writeToActivityLog:"found mpeg in eyetv package"];
1509 [self performScan:path scanTitleNum:0];
1513 /* We did not find an mpeg file in our package, so we do not call performScan */
1514 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1517 /* We check to see if this is a .dvdmedia package */
1518 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1520 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1521 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1522 [self writeToActivityLog:"trying to open dvdmedia package"];
1523 [self performScan:path scanTitleNum:0];
1527 /* The package is not an eyetv package, so we do not call performScan */
1528 [self writeToActivityLog:"unable to open package"];
1531 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1533 /* path is not a package, so we call perform scan directly on our file */
1534 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1536 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1537 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1538 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1542 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1543 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1544 /* make sure we remove any path extension as this can also be an '.mpg' file */
1545 browsedSourceDisplayName = [[path lastPathComponent] retain];
1547 applyQueueToScan = NO;
1548 [self performScan:path scanTitleNum:0];
1556 - (IBAction)showAboutPanel:(id)sender
1558 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1559 fApplicationIcon, @"ApplicationIcon",
1561 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1565 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1566 - (IBAction) showSourceTitleScanPanel: (id) sender
1568 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1571 [fScanSrcTitleNumField setStringValue: @"0"];
1572 /* Show the panel */
1573 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1576 - (IBAction) closeSourceTitleScanPanel: (id) sender
1578 [NSApp endSheet: fScanSrcTitlePanel];
1579 [fScanSrcTitlePanel orderOut: self];
1581 if(sender == fScanSrcTitleOpenButton)
1583 /* We setup the scan status in the main window to indicate a source title scan */
1584 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1585 [fScanIndicator setHidden: NO];
1586 [fScanIndicator setIndeterminate: YES];
1587 [fScanIndicator startAnimation: nil];
1589 /* We use the performScan method to actually perform the specified scan passing the path and the title
1592 applyQueueToScan = NO;
1593 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1597 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1598 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1601 /* use a bool to determine whether or not we can decrypt using vlc */
1602 BOOL cancelScanDecrypt = 0;
1604 NSString *path = scanPath;
1605 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1607 // Notify ChapterTitles that there's no title
1608 [fChapterTitlesDelegate resetWithTitle:nil];
1609 [fChapterTable reloadData];
1611 // Notify Subtitles that there's no title
1612 [fSubtitlesDelegate resetWithTitle:nil];
1613 [fSubtitlesTable reloadData];
1615 [self enableUI: NO];
1617 if( [detector isVideoDVD] )
1619 // The chosen path was actually on a DVD, so use the raw block
1620 // device path instead.
1621 path = [detector devicePath];
1622 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1624 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1625 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
1628 /*compatible vlc not found, so we set the bool to cancel scanning to 1 */
1629 cancelScanDecrypt = 1;
1630 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1632 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");
1633 [NSApp requestUserAttention:NSCriticalRequest];
1635 if (status == NSAlertDefaultReturn)
1637 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1638 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1640 else if (status == NSAlertAlternateReturn)
1642 /* User chose to cancel the scan */
1643 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1647 /* 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 */
1648 cancelScanDecrypt = 0;
1649 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1655 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1656 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1662 if (cancelScanDecrypt == 0)
1664 /* we actually pass the scan off to libhb here */
1665 /* If there is no title number passed to scan, we use "0"
1666 * which causes the default behavior of a full source scan
1672 if (scanTitleNum > 0)
1674 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1676 /* We use our advance pref to determine how many previews to scan */
1677 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1678 /* set title to NULL */
1680 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 );
1681 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1685 - (IBAction) cancelScanning:(id)sender
1687 hb_scan_stop(fHandle);
1690 - (IBAction) showNewScan:(id)sender
1694 int feature_title=0; // Used to store the main feature title
1696 list = hb_get_titles( fHandle );
1698 if( !hb_list_count( list ) )
1700 /* We display a message if a valid dvd source was not chosen */
1701 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1702 SuccessfulScan = NO;
1704 // Notify ChapterTitles that there's no title
1705 [fSubtitlesDelegate resetWithTitle:nil];
1706 [fSubtitlesTable reloadData];
1708 // Notify Subtitles that there's no title
1709 [fChapterTitlesDelegate resetWithTitle:nil];
1710 [fChapterTable reloadData];
1714 if (applyQueueToScan == YES)
1716 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1717 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1720 else if (applyQueueToScan == NO)
1722 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1726 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1729 /* We increment the successful scancount here by one,
1730 which we use at the end of this function to tell the gui
1731 if this is the first successful scan since launch and whether
1732 or not we should set all settings to the defaults */
1733 currentSuccessfulScanCount++;
1735 [[fWindow toolbar] validateVisibleItems];
1737 [fSrcTitlePopUp removeAllItems];
1738 for( int i = 0; i < hb_list_count( list ); i++ )
1740 title = (hb_title_t *) hb_list_item( list, i );
1742 currentSource = [NSString stringWithUTF8String: title->name];
1743 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1744 if (!browsedSourceDisplayName)
1746 browsedSourceDisplayName = @"NoNameDetected";
1748 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1750 /* If its a queue rescan for edit, get the queue item output path */
1751 /* if not, its a new source scan. */
1752 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1753 if (applyQueueToScan == YES)
1755 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1757 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1759 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1760 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1764 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1765 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1768 /* See if this is the main feature according to libhb */
1769 if (title->index == title->job->feature)
1774 [fSrcTitlePopUp addItemWithTitle: [NSString
1775 stringWithFormat: @"%s %d - %02dh%02dm%02ds",
1776 title->name,title->index, title->hours, title->minutes,
1780 /* if we are a stream, select the first title */
1781 if (title->type == HB_STREAM_TYPE)
1783 [fSrcTitlePopUp selectItemAtIndex: 0];
1787 /* if not then select the main feature title */
1788 [fSrcTitlePopUp selectItemAtIndex: feature_title];
1790 [self titlePopUpChanged:nil];
1792 SuccessfulScan = YES;
1793 [self enableUI: YES];
1795 /* if its the initial successful scan after awakeFromNib */
1796 if (currentSuccessfulScanCount == 1)
1798 [self encodeStartStopPopUpChanged:nil];
1800 [self selectDefaultPreset:nil];
1802 // Open preview window now if it was visible when HB was closed
1803 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1804 [self showPreviewWindow:nil];
1806 // Open picture sizing window now if it was visible when HB was closed
1807 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1808 [self showPicturePanel:nil];
1811 if (applyQueueToScan == YES)
1813 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1814 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1815 [self applyQueueSettingsToMainWindow:nil];
1826 #pragma mark New Output Destination
1828 - (IBAction) browseFile: (id) sender
1830 /* Open a panel to let the user choose and update the text field */
1831 NSSavePanel * panel = [NSSavePanel savePanel];
1832 /* We get the current file name and path from the destination field here */
1833 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1834 modalForWindow: fWindow modalDelegate: self
1835 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1839 - (void) browseFileDone: (NSSavePanel *) sheet
1840 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1842 if( returnCode == NSOKButton )
1844 [fDstFile2Field setStringValue: [sheet filename]];
1845 /* Save this path to the prefs so that on next browse destination window it opens there */
1846 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1847 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1853 #pragma mark Main Window Control
1855 - (IBAction) openMainWindow: (id) sender
1857 [fWindow makeKeyAndOrderFront:nil];
1860 - (BOOL) windowShouldClose: (id) sender
1865 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1868 [fWindow makeKeyAndOrderFront:nil];
1876 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1877 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
1882 #pragma mark Queue File
1884 - (void) loadQueueFile {
1885 /* We declare the default NSFileManager into fileManager */
1886 NSFileManager * fileManager = [NSFileManager defaultManager];
1887 /*We define the location of the user presets file */
1888 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
1889 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
1890 /* We check for the presets.plist */
1891 if ([fileManager fileExistsAtPath:QueueFile] == 0)
1893 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
1896 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1897 /* lets check to see if there is anything in the queue file .plist */
1898 if (nil == QueueFileArray)
1900 /* if not, then lets initialize an empty array */
1901 QueueFileArray = [[NSMutableArray alloc] init];
1903 /* Initialize our curQueueEncodeIndex to 0
1904 * so we can use it to track which queue
1905 * item is to be used to track our encodes */
1906 /* NOTE: this should be changed if and when we
1907 * are able to get the last unfinished encode
1908 * in the case of a crash or shutdown */
1913 [self clearQueueEncodedItems];
1915 currentQueueEncodeIndex = 0;
1918 - (void)addQueueFileItem
1920 [QueueFileArray addObject:[self createQueueFileItem]];
1921 [self saveQueueFileItem];
1925 - (void) removeQueueFileItem:(int) queueItemToRemove
1928 /* Find out if the item we are removing is a cancelled (3) or a finished (0) item*/
1929 if ([[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 3 || [[[QueueFileArray objectAtIndex:queueItemToRemove] objectForKey:@"Status"] intValue] == 0)
1931 /* Since we are removing a cancelled or finished item, WE need to decrement the currentQueueEncodeIndex
1932 * by one to keep in sync with the queue array
1934 currentQueueEncodeIndex--;
1937 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
1938 [self saveQueueFileItem];
1942 - (void)saveQueueFileItem
1944 [QueueFileArray writeToFile:QueueFile atomically:YES];
1945 [fQueueController setQueueArray: QueueFileArray];
1946 [self getQueueStats];
1949 - (void)getQueueStats
1951 /* lets get the stats on the status of the queue array */
1953 fEncodingQueueItem = 0;
1955 fCompletedCount = 0;
1959 /* We use a number system to set the encode status of the queue item
1961 * 0 == already encoded
1962 * 1 == is being encoded
1963 * 2 == is yet to be encoded
1968 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
1970 while (tempObject = [enumerator nextObject])
1972 NSDictionary *thisQueueDict = tempObject;
1973 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
1977 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
1980 fEncodingQueueItem = i;
1982 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
1986 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
1993 /* Set the queue status field in the main window */
1994 NSMutableString * string;
1995 if (fPendingCount == 1)
1997 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending in the queue", @"" ), fPendingCount];
2001 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode(s) pending in the queue", @"" ), fPendingCount];
2003 [fQueueStatus setStringValue:string];
2006 /* This method will set any item marked as encoding back to pending
2007 * currently used right after a queue reload
2009 - (void) setQueueEncodingItemsAsPending
2011 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2013 NSMutableArray *tempArray;
2014 tempArray = [NSMutableArray array];
2015 /* we look here to see if the preset is we move on to the next one */
2016 while ( tempObject = [enumerator nextObject] )
2018 /* If the queue item is marked as "encoding" (1)
2019 * then change its status back to pending (2) which effectively
2020 * puts it back into the queue to be encoded
2022 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2024 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2026 [tempArray addObject:tempObject];
2029 [QueueFileArray setArray:tempArray];
2030 [self saveQueueFileItem];
2034 /* This method will clear the queue of any encodes that are not still pending
2035 * this includes both successfully completed encodes as well as cancelled encodes */
2036 - (void) clearQueueEncodedItems
2038 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2040 NSMutableArray *tempArray;
2041 tempArray = [NSMutableArray array];
2042 /* we look here to see if the preset is we move on to the next one */
2043 while ( tempObject = [enumerator nextObject] )
2045 /* If the queue item is either completed (0) or cancelled (3) from the
2046 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2047 * NOTE: this means we retain pending (2) and also an item that is marked as
2048 * still encoding (1). If the queue has an item that is still marked as encoding
2049 * from a previous session, we can conlude that HB was either shutdown, or crashed
2050 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2052 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2054 [tempArray addObject:tempObject];
2058 [QueueFileArray removeObjectsInArray:tempArray];
2059 [self saveQueueFileItem];
2062 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2063 - (void) clearQueueAllItems
2065 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2067 NSMutableArray *tempArray;
2068 tempArray = [NSMutableArray array];
2069 /* we look here to see if the preset is we move on to the next one */
2070 while ( tempObject = [enumerator nextObject] )
2072 [tempArray addObject:tempObject];
2075 [QueueFileArray removeObjectsInArray:tempArray];
2076 [self saveQueueFileItem];
2079 /* This method will duplicate prepareJob however into the
2080 * queue .plist instead of into the job structure so it can
2081 * be recalled later */
2082 - (NSDictionary *)createQueueFileItem
2084 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2086 hb_list_t * list = hb_get_titles( fHandle );
2087 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2088 [fSrcTitlePopUp indexOfSelectedItem] );
2089 hb_job_t * job = title->job;
2093 /* We use a number system to set the encode status of the queue item
2094 * 0 == already encoded
2095 * 1 == is being encoded
2096 * 2 == is yet to be encoded
2099 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2100 /* Source and Destination Information */
2102 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2103 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2104 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2105 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2107 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2108 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2110 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2112 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2114 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2116 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2118 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2120 /* Chapter encode info */
2121 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2122 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2123 /* Time (pts) encode info */
2124 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2125 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2126 /* Frame number encode info */
2127 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2128 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2131 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2132 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2133 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2135 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2137 /* Lets get the preset info if there is any */
2138 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2139 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2141 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2142 /* Chapter Markers*/
2143 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2144 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2146 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2150 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2153 /* We need to get the list of chapter names to put into an array and store
2154 * in our queue, so they can be reapplied in prepareJob when this queue
2155 * item comes up if Chapter Markers is set to on.
2158 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2159 int chaptercount = hb_list_count( fTitle->list_chapter );
2160 for( i = 0; i < chaptercount; i++ )
2162 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2163 if( chapter != NULL )
2165 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2168 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2169 [ChapterNamesArray autorelease];
2171 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2172 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2173 /* Mux mp4 with http optimization */
2174 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2175 /* Add iPod uuid atom */
2176 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2180 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2181 /* x264 Option String */
2182 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2184 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2185 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2186 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2187 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2189 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2190 [queueFileJob setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
2192 /* 2 Pass Encoding */
2193 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2194 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2195 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2197 /* Picture Sizing */
2198 /* Use Max Picture settings for whatever the dvd is.*/
2199 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2200 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2201 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2202 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2203 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2204 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2205 /* if we are custom anamorphic, store the exact storage, par and display dims */
2206 if (fTitle->job->anamorphic.mode == 3)
2208 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2210 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2211 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2213 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2214 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2216 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2217 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2220 NSString * pictureSummary;
2221 pictureSummary = [fPictureSizeField stringValue];
2222 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2223 /* Set crop settings here */
2224 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2225 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2226 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2227 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2228 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2230 /* Picture Filters */
2231 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2232 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2234 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2235 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2236 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2238 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2239 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2241 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2242 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2244 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2246 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2249 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2251 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
2252 [queueFileJob setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
2253 [queueFileJob setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
2254 [queueFileJob setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
2255 [queueFileJob setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
2256 [queueFileJob setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
2257 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
2259 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2261 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
2262 [queueFileJob setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
2263 [queueFileJob setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
2264 [queueFileJob setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
2265 [queueFileJob setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
2266 [queueFileJob setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
2267 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
2269 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2271 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
2272 [queueFileJob setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
2273 [queueFileJob setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
2274 [queueFileJob setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
2275 [queueFileJob setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
2276 [queueFileJob setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
2277 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
2279 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2281 [queueFileJob setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
2282 [queueFileJob setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
2283 [queueFileJob setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
2284 [queueFileJob setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
2285 [queueFileJob setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
2286 [queueFileJob setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
2287 [queueFileJob setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
2291 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2292 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2293 [subtitlesArray autorelease];
2295 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2297 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2299 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2302 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2306 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2309 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2310 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2311 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2313 /* Picture Sizing */
2314 /* Use Max Picture settings for whatever the dvd is.*/
2315 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2316 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2317 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2318 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2319 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2321 /* Set crop settings here */
2322 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2323 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2324 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2325 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2326 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2330 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
2332 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1CodecPopUp selectedItem] tag]] forKey:@"JobAudio1Encoder"];
2333 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1MixPopUp selectedItem] tag]] forKey:@"JobAudio1Mixdown"];
2334 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1RatePopUp selectedItem] tag]] forKey:@"JobAudio1Samplerate"];
2335 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack1BitratePopUp selectedItem] tag]] forKey:@"JobAudio1Bitrate"];
2337 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
2339 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2CodecPopUp selectedItem] tag]] forKey:@"JobAudio2Encoder"];
2340 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2MixPopUp selectedItem] tag]] forKey:@"JobAudio2Mixdown"];
2341 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2RatePopUp selectedItem] tag]] forKey:@"JobAudio2Samplerate"];
2342 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack2BitratePopUp selectedItem] tag]] forKey:@"JobAudio2Bitrate"];
2344 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
2346 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3CodecPopUp selectedItem] tag]] forKey:@"JobAudio3Encoder"];
2347 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3MixPopUp selectedItem] tag]] forKey:@"JobAudio3Mixdown"];
2348 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3RatePopUp selectedItem] tag]] forKey:@"JobAudio3Samplerate"];
2349 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack3BitratePopUp selectedItem] tag]] forKey:@"JobAudio3Bitrate"];
2351 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
2353 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4CodecPopUp selectedItem] tag]] forKey:@"JobAudio4Encoder"];
2354 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4MixPopUp selectedItem] tag]] forKey:@"JobAudio4Mixdown"];
2355 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4RatePopUp selectedItem] tag]] forKey:@"JobAudio4Samplerate"];
2356 [queueFileJob setObject:[NSNumber numberWithInt:[[fAudTrack4BitratePopUp selectedItem] tag]] forKey:@"JobAudio4Bitrate"];
2359 /* we need to auto relase the queueFileJob and return it */
2360 [queueFileJob autorelease];
2361 return queueFileJob;
2365 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2366 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2368 NSUInteger index = [indexSet lastIndex];
2369 NSUInteger aboveInsertIndexCount = 0;
2372 NSUInteger removeIndex;
2374 if (index >= insertIndex)
2376 removeIndex = index + aboveInsertIndexCount;
2377 aboveInsertIndexCount++;
2381 removeIndex = index;
2385 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2386 [QueueFileArray removeObjectAtIndex:removeIndex];
2387 [QueueFileArray insertObject:object atIndex:insertIndex];
2390 index = [indexSet indexLessThanIndex:index];
2392 /* We save all of the Queue data here
2393 * and it also gets sent back to the queue controller*/
2394 [self saveQueueFileItem];
2400 #pragma mark Queue Job Processing
2402 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2404 int i = currentQueueEncodeIndex;
2405 [[QueueFileArray objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2407 /* We save all of the Queue data here */
2408 [self saveQueueFileItem];
2410 /* Since we have now marked a queue item as done
2411 * we can go ahead and increment currentQueueEncodeIndex
2412 * so that if there is anything left in the queue we can
2413 * go ahead and move to the next item if we want to */
2414 currentQueueEncodeIndex++ ;
2415 int queueItems = [QueueFileArray count];
2416 /* If we still have more items in our queue, lets go to the next one */
2417 if (currentQueueEncodeIndex < queueItems)
2419 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2423 [self writeToActivityLog: "incrementQueueItemDone the %d item queue is complete", currentQueueEncodeIndex - 1];
2427 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2428 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2430 /* Tell HB to output a new activity log file for this encode */
2431 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2433 /* use a bool to determine whether or not we can decrypt using vlc */
2434 BOOL cancelScanDecrypt = 0;
2435 /* set the bool so that showNewScan knows to apply the appropriate queue
2436 * settings as this is a queue rescan
2438 NSString *path = scanPath;
2439 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2441 if( [detector isVideoDVD] )
2443 // The chosen path was actually on a DVD, so use the raw block
2444 // device path instead.
2445 path = [detector devicePath];
2446 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2448 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2449 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
2452 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2453 cancelScanDecrypt = 1;
2454 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2456 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");
2457 [NSApp requestUserAttention:NSCriticalRequest];
2459 if (status == NSAlertDefaultReturn)
2461 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2462 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2464 else if (status == NSAlertAlternateReturn)
2466 /* User chose to cancel the scan */
2467 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2471 /* 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 */
2472 cancelScanDecrypt = 0;
2473 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2479 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2481 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2485 if (cancelScanDecrypt == 0)
2487 /* we actually pass the scan off to libhb here */
2488 /* If there is no title number passed to scan, we use "0"
2489 * which causes the default behavior of a full source scan
2495 if (scanTitleNum > 0)
2497 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2500 /* We use our advance pref to determine how many previews to scan */
2501 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
2502 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, hb_num_previews, 0 );
2506 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2507 - (void) processNewQueueEncode
2509 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2510 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2511 hb_job_t * job = title->job;
2513 if( !hb_list_count( list ) )
2515 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2518 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2519 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2520 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2521 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2525 * If scanning we need to do some extra setup of the job.
2527 if( job->indepth_scan == 1 )
2532 * When subtitle scan is enabled do a fast pre-scan job
2533 * which will determine which subtitles to enable, if any.
2536 x264opts_tmp = job->x264opts;
2538 job->x264opts = NULL;
2540 job->indepth_scan = 1;
2544 * Add the pre-scan job
2546 hb_add( fQueueEncodeLibhb, job );
2547 job->x264opts = x264opts_tmp;
2551 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2553 job->indepth_scan = 0;
2559 hb_add( fQueueEncodeLibhb, job );
2563 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2564 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2566 hb_add( fQueueEncodeLibhb, job );
2571 job->indepth_scan = 0;
2574 hb_add( fQueueEncodeLibhb, job );
2577 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2578 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2579 /* Lets mark our new encode as 1 or "Encoding" */
2580 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2581 [self saveQueueFileItem];
2583 /* we need to clean up the subtitle tracks after the job(s) have been set */
2584 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2586 for(ii = 0; ii < num_subtitle_tracks; ii++)
2588 hb_subtitle_t * subtitle;
2589 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2592 hb_list_rem(job->list_subtitle, subtitle);
2596 /* We should be all setup so let 'er rip */
2603 #pragma mark Queue Item Editing
2605 /* Rescans the chosen queue item back into the main window */
2606 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2608 fqueueEditRescanItemNum = selectedQueueItem;
2609 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2610 applyQueueToScan = YES;
2611 /* Set the browsedSourceDisplayName for showNewScan */
2612 browsedSourceDisplayName = [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"];
2613 [self performScan:scanPath scanTitleNum:scanTitleNum];
2617 /* We use this method after a queue item rescan for edit.
2618 * it largely mirrors -selectPreset in terms of structure.
2619 * Assumes that a queue item has been reloaded into the main window.
2621 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2623 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2624 hb_job_t * job = fTitle->job;
2627 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2629 /* Set title number and chapters */
2630 /* since the queue only scans a single title, its already been selected in showNewScan
2631 so do not try to reset it here. However if we do decide to do full source scans on
2632 a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2633 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2635 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2636 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2639 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2640 [self formatPopUpChanged:nil];
2642 /* Chapter Markers*/
2643 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2644 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2645 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2646 /* Mux mp4 with http optimization */
2647 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2650 /* We set the advanced opt string here if applicable*/
2651 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2652 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2654 /* Lets run through the following functions to get variables set there */
2655 [self videoEncoderPopUpChanged:nil];
2656 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2657 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2658 [self calculateBitrate:nil];
2661 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2663 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2664 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2665 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2666 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2667 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2668 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2669 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2670 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2672 /* For the quality slider we need to convert the old percent's to the new rf scales */
2673 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2674 [fVidQualitySlider setFloatValue:rf];
2679 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2680 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2682 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2686 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2687 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2691 [self videoMatrixChanged:nil];
2693 /* Video framerate */
2694 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2695 detected framerate in the fVidRatePopUp so we use index 0*/
2696 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2698 [fVidRatePopUp selectItemAtIndex: 0];
2702 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2705 /* 2 Pass Encoding */
2706 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2707 [self twoPassCheckboxChanged:nil];
2708 /* Turbo 1st pass for 2 Pass Encoding */
2709 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2714 /* Now lets add our new tracks to the audio list here */
2715 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
2717 [fAudLang1PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio1Track"] intValue]];
2718 [self audioTrackPopUpChanged: fAudLang1PopUp];
2719 [fAudTrack1CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Encoder"]];
2720 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
2722 [fAudTrack1MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Mixdown"]];
2724 [fAudTrack1RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Samplerate"]];
2725 [fAudTrack1BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio1Bitrate"]];
2727 [fAudTrack1DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
2728 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2732 [fAudLang1PopUp selectItemAtIndex: 0];
2733 [self audioTrackPopUpChanged: fAudLang1PopUp];
2735 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
2737 [fAudLang2PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio2Track"] intValue]];
2738 [self audioTrackPopUpChanged: fAudLang2PopUp];
2739 [fAudTrack2CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Encoder"]];
2740 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
2742 [fAudTrack2MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Mixdown"]];
2744 [fAudTrack2RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Samplerate"]];
2745 [fAudTrack2BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio2Bitrate"]];
2747 [fAudTrack2DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
2748 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2752 [fAudLang2PopUp selectItemAtIndex: 0];
2753 [self audioTrackPopUpChanged: fAudLang2PopUp];
2755 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
2757 [fAudLang3PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio3Track"] intValue]];
2758 [self audioTrackPopUpChanged: fAudLang3PopUp];
2759 [fAudTrack3CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Encoder"]];
2760 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
2762 [fAudTrack3MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Mixdown"]];
2764 [fAudTrack3RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Samplerate"]];
2765 [fAudTrack3BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio3Bitrate"]];
2767 [fAudTrack3DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
2768 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2772 [fAudLang3PopUp selectItemAtIndex: 0];
2773 [self audioTrackPopUpChanged: fAudLang3PopUp];
2775 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
2777 [fAudLang4PopUp selectItemAtIndex: [[queueToApply objectForKey:@"Audio4Track"] intValue]];
2778 [self audioTrackPopUpChanged: fAudLang4PopUp];
2779 [fAudTrack4CodecPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Encoder"]];
2780 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
2782 [fAudTrack4MixPopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Mixdown"]];
2784 [fAudTrack4RatePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Samplerate"]];
2785 [fAudTrack4BitratePopUp selectItemWithTitle:[queueToApply objectForKey:@"Audio4Bitrate"]];
2787 [fAudTrack4DrcSlider setFloatValue:[[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
2788 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2792 [fAudLang4PopUp selectItemAtIndex: 0];
2793 [self audioTrackPopUpChanged: fAudLang4PopUp];
2797 /* Crashy crashy right now, working on it */
2798 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2799 [fSubtitlesTable reloadData];
2800 /* Picture Settings */
2802 /* If Cropping is set to custom, then recall all four crop values from
2803 when the preset was created and apply them */
2804 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2806 [fPictureController setAutoCrop:NO];
2808 /* Here we use the custom crop values saved at the time the preset was saved */
2809 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2810 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2811 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2812 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2815 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2817 [fPictureController setAutoCrop:YES];
2818 /* Here we use the auto crop values determined right after scan */
2819 job->crop[0] = AutoCropTop;
2820 job->crop[1] = AutoCropBottom;
2821 job->crop[2] = AutoCropLeft;
2822 job->crop[3] = AutoCropRight;
2826 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2828 /* we check to make sure the presets width/height does not exceed the sources width/height */
2829 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2831 /* if so, then we use the sources height and width to avoid scaling up */
2832 //job->width = fTitle->width;
2833 //job->height = fTitle->height;
2834 [self revertPictureSizeToMax:nil];
2836 else // source width/height is >= the preset height/width
2838 /* we can go ahead and use the presets values for height and width */
2839 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2840 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2842 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2843 if (job->keep_ratio == 1)
2845 hb_fix_aspect( job, HB_KEEP_WIDTH );
2846 if( job->height > fTitle->height )
2848 job->height = fTitle->height;
2849 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2852 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2853 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2857 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2858 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2859 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2862 [fPictureController setUseDecomb:1];
2863 [fPictureController setDecomb:0];
2864 [fPictureController setDeinterlace:0];
2865 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2867 /* we are using decomb */
2869 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2871 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2873 /* if we are using "Custom" in the decomb setting, also set the custom string*/
2874 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
2876 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
2882 /* We are using Deinterlace */
2884 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
2886 [fPictureController setUseDecomb:0];
2887 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2888 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
2889 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
2891 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
2898 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
2900 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2901 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
2902 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
2904 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
2909 [fPictureController setDetelecine:0];
2913 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
2915 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2916 /* if we are using "Custom" in the denoise setting, also set the custom string*/
2917 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
2919 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
2924 [fPictureController setDenoise:0];
2928 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
2930 /* if its a one, then its the old on/off deblock, set on to 5*/
2931 [fPictureController setDeblock:5];
2935 /* use the settings intValue */
2936 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2939 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
2941 [fPictureController setGrayscale:1];
2945 [fPictureController setGrayscale:0];
2948 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
2949 [fPictureController SetTitle:fTitle];
2950 [self calculatePictureSizing:nil];
2952 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2953 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2954 //[queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2955 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2957 /* Deselect the currently selected Preset if there is one*/
2958 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2959 //[self selectPreset:nil];
2961 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2962 /* Change UI to show "Custom" settings are being used */
2963 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2965 curUserPresetChosenNum = nil;
2969 /* Deselect the currently selected Preset if there is one*/
2970 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2971 /* Change UI to show "Custom" settings are being used */
2972 [fPresetSelectedDisplay setStringValue: @"Custom"];
2974 //curUserPresetChosenNum = nil;
2977 /* We need to set this bool back to NO, in case the user wants to do a scan */
2978 //applyQueueToScan = NO;
2980 /* Not that source is loaded and settings applied, delete the queue item from the queue */
2981 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
2982 [self removeQueueFileItem:fqueueEditRescanItemNum];
2988 #pragma mark Live Preview
2989 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
2990 * can encode to its temp preview directory and playback. This is *not* used for any actual user
2993 - (void) prepareJobForPreview
2995 hb_list_t * list = hb_get_titles( fHandle );
2996 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2997 [fSrcTitlePopUp indexOfSelectedItem] );
2998 hb_job_t * job = title->job;
2999 hb_audio_config_t * audio;
3000 /* set job->angle for libdvdnav */
3001 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3002 /* Chapter selection */
3003 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3004 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3006 /* Format (Muxer) and Video Encoder */
3007 job->mux = [[fDstFormatPopUp selectedItem] tag];
3008 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3010 job->chapter_markers = 0;
3012 if( job->vcodec & HB_VCODEC_X264 )
3015 /* Below Sends x264 options to the core library if x264 is selected*/
3016 /* Lets use this as per Nyx, Thanks Nyx!*/
3017 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3018 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3019 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3024 /* Video settings */
3025 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3026 * and detelecine is on, so we handle that in the logic below
3029 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3031 /* a specific framerate has been chosen */
3032 job->vrate = 27000000;
3033 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3034 /* We are not same as source so we set job->cfr to 1
3035 * to enable constant frame rate since user has specified
3036 * a specific framerate*/
3037 if ([fFrameratePfrCheck state] == 1)
3048 /* We are same as source (variable) */
3049 job->vrate = title->rate;
3050 job->vrate_base = title->rate_base;
3051 /* We are same as source so we set job->cfr to 0
3052 * to enable true same as source framerate */
3054 /* If we are same as source and we have detelecine on, we need to turn on
3057 if ([fPictureController detelecine] == 1)
3063 switch( [fVidQualityMatrix selectedRow] )
3067 Bitrate should already have been calculated and displayed
3068 in fVidBitrateField, so let's just use it */
3070 job->vquality = -1.0;
3071 job->vbitrate = [fVidBitrateField intValue];
3074 job->vquality = [fVidQualityRFField floatValue];
3079 /* Subtitle settings */
3080 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3087 bool one_burned = FALSE;
3090 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3092 while (tempObject = [enumerator nextObject])
3095 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3096 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3097 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3098 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3100 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3101 * we want to ignore it for display as well as encoding.
3105 /* if i is 0, then we are in the first item of the subtitles which we need to
3106 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3107 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3110 /* if we are on the first track and using "Foreign Audio Search" */
3111 if (i == 0 && subtitle == 1)
3113 /* NOTE: Currently foreign language search is borked for preview.
3114 * Commented out but left in for initial commit. */
3117 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3119 job->indepth_scan = 1;
3123 job->select_subtitle_config.dest = PASSTHRUSUB;
3127 job->select_subtitle_config.dest = RENDERSUB;
3130 job->select_subtitle_config.force = force;
3131 job->select_subtitle_config.default_track = def;
3136 /* for the actual source tracks, we must subtract the non source entries so
3137 * that the menu index matches the source subtitle_list index for convenience */
3140 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3141 * Foreign Language Search is 1) so subtract 2 */
3142 subtitle = subtitle - 2;
3146 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3149 subtitle = subtitle - 1;
3152 /* We are setting a source subtitle so access the source subtitle info */
3153 hb_subtitle_t * subt;
3155 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3157 /* if we are getting the subtitles from an external srt file */
3158 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3160 hb_subtitle_config_t sub_config;
3162 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3164 /* we need to srncpy file path and char code */
3165 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3166 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3168 sub_config.force = 0;
3169 sub_config.dest = PASSTHRUSUB;
3170 sub_config.default_track = def;
3172 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3177 hb_subtitle_config_t sub_config = subt->config;
3179 if ( !burned && subt->format == PICTURESUB )
3181 sub_config.dest = PASSTHRUSUB;
3183 else if ( burned && subt->format == PICTURESUB )
3185 // Only allow one subtitle to be burned into the video
3190 sub_config.force = force;
3191 sub_config.default_track = def;
3192 hb_subtitle_add( job, &sub_config, subtitle );
3202 [subtitlesArray autorelease];
3205 /* Audio tracks and mixdowns */
3206 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3207 int audiotrack_count = hb_list_count(job->list_audio);
3208 for( int i = 0; i < audiotrack_count;i++)
3210 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3211 hb_list_rem(job->list_audio, temp_audio);
3213 /* Now lets add our new tracks to the audio list here */
3214 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
3216 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3217 hb_audio_config_init(audio);
3218 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3219 /* We go ahead and assign values to our audio->out.<properties> */
3220 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
3221 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
3222 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
3223 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
3224 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
3225 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
3227 hb_audio_add( job, audio );
3230 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
3232 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3233 hb_audio_config_init(audio);
3234 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3235 /* We go ahead and assign values to our audio->out.<properties> */
3236 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
3237 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
3238 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
3239 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
3240 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
3241 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
3243 hb_audio_add( job, audio );
3248 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
3250 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3251 hb_audio_config_init(audio);
3252 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3253 /* We go ahead and assign values to our audio->out.<properties> */
3254 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
3255 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
3256 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
3257 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
3258 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
3259 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
3261 hb_audio_add( job, audio );
3266 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
3268 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3269 hb_audio_config_init(audio);
3270 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3271 /* We go ahead and assign values to our audio->out.<properties> */
3272 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
3273 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
3274 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
3275 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
3276 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
3277 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
3279 hb_audio_add( job, audio );
3288 /* Though Grayscale is not really a filter, per se
3289 * we put it here since its in the filters panel
3292 if ([fPictureController grayscale])
3301 /* Initialize the filters list */
3302 job->filters = hb_list_init();
3304 /* Now lets call the filters if applicable.
3305 * The order of the filters is critical
3309 hb_filter_detelecine.settings = NULL;
3310 if ([fPictureController detelecine] == 1)
3312 /* use a custom detelecine string */
3313 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3314 hb_list_add( job->filters, &hb_filter_detelecine );
3316 if ([fPictureController detelecine] == 2)
3319 hb_list_add( job->filters, &hb_filter_detelecine );
3324 if ([fPictureController useDecomb] == 1)
3327 /* we add the custom string if present */
3328 hb_filter_decomb.settings = NULL;
3329 if ([fPictureController decomb] == 1)
3331 /* use a custom decomb string */
3332 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3333 hb_list_add( job->filters, &hb_filter_decomb );
3335 if ([fPictureController decomb] == 2)
3337 /* Run old deinterlacer fd by default */
3338 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3339 hb_list_add( job->filters, &hb_filter_decomb );
3346 if ([fPictureController deinterlace] == 1)
3348 /* we add the custom string if present */
3349 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3350 hb_list_add( job->filters, &hb_filter_deinterlace );
3352 else if ([fPictureController deinterlace] == 2)
3354 /* Run old deinterlacer fd by default */
3355 hb_filter_deinterlace.settings = "-1";
3356 hb_list_add( job->filters, &hb_filter_deinterlace );
3358 else if ([fPictureController deinterlace] == 3)
3360 /* Yadif mode 0 (without spatial deinterlacing.) */
3361 hb_filter_deinterlace.settings = "2";
3362 hb_list_add( job->filters, &hb_filter_deinterlace );
3364 else if ([fPictureController deinterlace] == 4)
3366 /* Yadif (with spatial deinterlacing) */
3367 hb_filter_deinterlace.settings = "0";
3368 hb_list_add( job->filters, &hb_filter_deinterlace );
3374 if ([fPictureController denoise] == 1) // custom in popup
3376 /* we add the custom string if present */
3377 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3378 hb_list_add( job->filters, &hb_filter_denoise );
3380 else if ([fPictureController denoise] == 2) // Weak in popup
3382 hb_filter_denoise.settings = "2:1:2:3";
3383 hb_list_add( job->filters, &hb_filter_denoise );
3385 else if ([fPictureController denoise] == 3) // Medium in popup
3387 hb_filter_denoise.settings = "3:2:2:3";
3388 hb_list_add( job->filters, &hb_filter_denoise );
3390 else if ([fPictureController denoise] == 4) // Strong in popup
3392 hb_filter_denoise.settings = "7:7:5:5";
3393 hb_list_add( job->filters, &hb_filter_denoise );
3397 /* Deblock (uses pp7 default) */
3398 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3399 * the macgui's purposes a value of 0 actually means to not even use the filter
3400 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3402 if ([fPictureController deblock] != 0)
3404 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3405 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3406 hb_list_add( job->filters, &hb_filter_deblock );
3413 #pragma mark Job Handling
3419 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3420 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3421 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3422 hb_job_t * job = title->job;
3423 hb_audio_config_t * audio;
3424 /* Title Angle for dvdnav */
3425 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3427 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3429 /* Chapter selection */
3430 [self writeToActivityLog: "Start / Stop set to chapters"];
3431 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3432 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3434 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3436 /* we are pts based start / stop */
3437 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3439 /* Point A to Point B. Time to time in seconds.*/
3440 /* get the start seconds from the start seconds field */
3441 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3442 job->pts_to_start = start_seconds * 90000LL;
3443 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3444 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3445 job->pts_to_stop = stop_seconds * 90000LL;
3448 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3450 /* we are frame based start / stop */
3451 [self writeToActivityLog: "Start / Stop set to frames ..."];
3453 /* Point A to Point B. Frame to frame */
3454 /* get the start frame from the start frame field */
3455 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3456 job->frame_to_start = start_frame;
3457 /* get the frame to stop on from the end frame field */
3458 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3459 job->frame_to_stop = stop_frame;
3466 /* Format (Muxer) and Video Encoder */
3467 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3468 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3471 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3472 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3474 job->largeFileSize = 1;
3478 job->largeFileSize = 0;
3480 /* We set http optimized mp4 here */
3481 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3483 job->mp4_optimize = 1;
3487 job->mp4_optimize = 0;
3491 /* We set the chapter marker extraction here based on the format being
3492 mpeg4 or mkv and the checkbox being checked */
3493 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3495 job->chapter_markers = 1;
3497 /* now lets get our saved chapter names out the array in the queue file
3498 * and insert them back into the title chapter list. We have it here,
3499 * because unless we are inserting chapter markers there is no need to
3500 * spend the overhead of iterating through the chapter names array imo
3501 * Also, note that if for some reason we don't apply chapter names, the
3502 * chapters just come out 001, 002, etc. etc.
3505 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3507 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3509 while (tempObject = [enumerator nextObject])
3511 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3512 if( chapter != NULL )
3514 strncpy( chapter->title, [tempObject UTF8String], 1023);
3515 chapter->title[1023] = '\0';
3522 job->chapter_markers = 0;
3525 if( job->vcodec & HB_VCODEC_X264 )
3527 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3537 /* Below Sends x264 options to the core library if x264 is selected*/
3538 /* Lets use this as per Nyx, Thanks Nyx!*/
3539 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3540 /* Turbo first pass if two pass and Turbo First pass is selected */
3541 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3543 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3544 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3545 /* append the "Turbo" string variable to the existing opts string.
3546 Note: the "Turbo" string must be appended, not prepended to work properly*/
3547 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3548 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3552 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3558 /* Picture Size Settings */
3559 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3560 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3562 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3563 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3564 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3565 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3567 /* insert our custom values here for capuj */
3568 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3569 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3571 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3573 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3574 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3576 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3577 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3580 /* Here we use the crop values saved at the time the preset was saved */
3581 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3582 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3583 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3584 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3586 /* Video settings */
3589 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3590 * and detelecine is on, so we handle that in the logic below
3593 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3595 /* a specific framerate has been chosen */
3596 job->vrate = 27000000;
3597 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3598 /* We are not same as source so we set job->cfr to 1
3599 * to enable constant frame rate since user has specified
3600 * a specific framerate*/
3602 if ([[queueToApply objectForKey:@"VideoFrameratePFR"] intValue] == 1)
3613 /* We are same as source (variable) */
3614 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3615 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3616 /* We are same as source so we set job->cfr to 0
3617 * to enable true same as source framerate */
3619 /* If we are same as source and we have detelecine on, we need to turn on
3622 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3628 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3631 Bitrate should already have been calculated and displayed
3632 in fVidBitrateField, so let's just use it same as abr*/
3633 job->vquality = -1.0;
3634 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3636 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3638 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3643 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3648 #pragma mark Process Subtitles to libhb
3650 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3651 * which means that we need to account for the offset of non source language settings in from
3652 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3653 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3654 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3655 * to the source tracks position in title->list_subtitle.
3662 bool one_burned = FALSE;
3665 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3667 while (tempObject = [enumerator nextObject])
3670 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3671 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3672 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3673 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3675 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3676 * we want to ignore it for display as well as encoding.
3680 /* if i is 0, then we are in the first item of the subtitles which we need to
3681 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3682 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3685 /* if we are on the first track and using "Foreign Audio Search" */
3686 if (i == 0 && subtitle == 1)
3688 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3690 job->indepth_scan = 1;
3694 job->select_subtitle_config.dest = PASSTHRUSUB;
3698 job->select_subtitle_config.dest = RENDERSUB;
3701 job->select_subtitle_config.force = force;
3702 job->select_subtitle_config.default_track = def;
3707 /* for the actual source tracks, we must subtract the non source entries so
3708 * that the menu index matches the source subtitle_list index for convenience */
3711 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3712 * Foreign Language Search is 1) so subtract 2 */
3713 subtitle = subtitle - 2;
3717 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3720 subtitle = subtitle - 1;
3723 /* We are setting a source subtitle so access the source subtitle info */
3724 hb_subtitle_t * subt;
3726 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3728 /* if we are getting the subtitles from an external srt file */
3729 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3731 hb_subtitle_config_t sub_config;
3733 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3735 /* we need to srncpy file name and codeset */
3736 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3737 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3739 sub_config.force = 0;
3740 sub_config.dest = PASSTHRUSUB;
3741 sub_config.default_track = def;
3743 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3749 hb_subtitle_config_t sub_config = subt->config;
3751 if ( !burned && subt->format == PICTURESUB )
3753 sub_config.dest = PASSTHRUSUB;
3755 else if ( burned && subt->format == PICTURESUB )
3757 // Only allow one subtitle to be burned into the video
3762 sub_config.force = force;
3763 sub_config.default_track = def;
3764 hb_subtitle_add( job, &sub_config, subtitle );
3775 /* Audio tracks and mixdowns */
3776 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3777 int audiotrack_count = hb_list_count(job->list_audio);
3778 for( int i = 0; i < audiotrack_count;i++)
3780 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3781 hb_list_rem(job->list_audio, temp_audio);
3783 /* Now lets add our new tracks to the audio list here */
3784 if ([[queueToApply objectForKey:@"Audio1Track"] intValue] > 0)
3786 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3787 hb_audio_config_init(audio);
3788 audio->in.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3789 /* We go ahead and assign values to our audio->out.<properties> */
3790 audio->out.track = [[queueToApply objectForKey:@"Audio1Track"] intValue] - 1;
3791 audio->out.codec = [[queueToApply objectForKey:@"JobAudio1Encoder"] intValue];
3792 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio1Mixdown"] intValue];
3793 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio1Bitrate"] intValue];
3794 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio1Samplerate"] intValue];
3795 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio1TrackDRCSlider"] floatValue];
3797 hb_audio_add( job, audio );
3800 if ([[queueToApply objectForKey:@"Audio2Track"] intValue] > 0)
3803 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3804 hb_audio_config_init(audio);
3805 audio->in.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3806 [self writeToActivityLog: "prepareJob audiotrack 2 is: %d", audio->in.track];
3807 /* We go ahead and assign values to our audio->out.<properties> */
3808 audio->out.track = [[queueToApply objectForKey:@"Audio2Track"] intValue] - 1;
3809 audio->out.codec = [[queueToApply objectForKey:@"JobAudio2Encoder"] intValue];
3810 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio2Mixdown"] intValue];
3811 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio2Bitrate"] intValue];
3812 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio2Samplerate"] intValue];
3813 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio2TrackDRCSlider"] floatValue];
3815 hb_audio_add( job, audio );
3819 if ([[queueToApply objectForKey:@"Audio3Track"] intValue] > 0)
3821 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3822 hb_audio_config_init(audio);
3823 audio->in.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3824 /* We go ahead and assign values to our audio->out.<properties> */
3825 audio->out.track = [[queueToApply objectForKey:@"Audio3Track"] intValue] - 1;
3826 audio->out.codec = [[queueToApply objectForKey:@"JobAudio3Encoder"] intValue];
3827 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio3Mixdown"] intValue];
3828 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio3Bitrate"] intValue];
3829 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio3Samplerate"] intValue];
3830 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio3TrackDRCSlider"] floatValue];
3832 hb_audio_add( job, audio );
3836 if ([[queueToApply objectForKey:@"Audio4Track"] intValue] > 0)
3838 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3839 hb_audio_config_init(audio);
3840 audio->in.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3841 /* We go ahead and assign values to our audio->out.<properties> */
3842 audio->out.track = [[queueToApply objectForKey:@"Audio4Track"] intValue] - 1;
3843 audio->out.codec = [[queueToApply objectForKey:@"JobAudio4Encoder"] intValue];
3844 audio->out.mixdown = [[queueToApply objectForKey:@"JobAudio4Mixdown"] intValue];
3845 audio->out.bitrate = [[queueToApply objectForKey:@"JobAudio4Bitrate"] intValue];
3846 audio->out.samplerate = [[queueToApply objectForKey:@"JobAudio4Samplerate"] intValue];
3847 audio->out.dynamic_range_compression = [[queueToApply objectForKey:@"Audio4TrackDRCSlider"] floatValue];
3849 hb_audio_add( job, audio );
3855 job->filters = hb_list_init();
3857 /* Now lets call the filters if applicable.
3858 * The order of the filters is critical
3861 hb_filter_detelecine.settings = NULL;
3862 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3864 /* use a custom detelecine string */
3865 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3866 hb_list_add( job->filters, &hb_filter_detelecine );
3868 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3870 /* Use libhb's default values */
3871 hb_list_add( job->filters, &hb_filter_detelecine );
3874 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3877 /* we add the custom string if present */
3878 hb_filter_decomb.settings = NULL;
3879 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3881 /* use a custom decomb string */
3882 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3883 hb_list_add( job->filters, &hb_filter_decomb );
3885 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3887 /* Use libhb default */
3888 hb_list_add( job->filters, &hb_filter_decomb );
3896 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3898 /* we add the custom string if present */
3899 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3900 hb_list_add( job->filters, &hb_filter_deinterlace );
3902 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3904 /* Run old deinterlacer fd by default */
3905 hb_filter_deinterlace.settings = "-1";
3906 hb_list_add( job->filters, &hb_filter_deinterlace );
3908 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3910 /* Yadif mode 0 (without spatial deinterlacing.) */
3911 hb_filter_deinterlace.settings = "2";
3912 hb_list_add( job->filters, &hb_filter_deinterlace );
3914 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3916 /* Yadif (with spatial deinterlacing) */
3917 hb_filter_deinterlace.settings = "0";
3918 hb_list_add( job->filters, &hb_filter_deinterlace );
3924 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
3926 /* we add the custom string if present */
3927 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3928 hb_list_add( job->filters, &hb_filter_denoise );
3930 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
3932 hb_filter_denoise.settings = "2:1:2:3";
3933 hb_list_add( job->filters, &hb_filter_denoise );
3935 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
3937 hb_filter_denoise.settings = "3:2:2:3";
3938 hb_list_add( job->filters, &hb_filter_denoise );
3940 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
3942 hb_filter_denoise.settings = "7:7:5:5";
3943 hb_list_add( job->filters, &hb_filter_denoise );
3947 /* Deblock (uses pp7 default) */
3948 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3949 * the macgui's purposes a value of 0 actually means to not even use the filter
3950 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3952 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3954 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3955 hb_list_add( job->filters, &hb_filter_deblock );
3957 [self writeToActivityLog: "prepareJob exiting"];
3962 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3964 - (IBAction) addToQueue: (id) sender
3966 /* We get the destination directory from the destination field here */
3967 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3968 /* We check for a valid destination here */
3969 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3971 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3978 BOOL fileExistsInQueue;
3979 fileExistsInQueue = NO;
3981 /* We check for and existing file here */
3982 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3987 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3989 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3991 while (tempObject = [enumerator nextObject])
3993 NSDictionary *thisQueueDict = tempObject;
3994 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3996 fileExistsInQueue = YES;
4002 if(fileExists == YES)
4004 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
4005 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4006 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4007 NULL, NULL, [NSString stringWithFormat:
4008 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4009 [fDstFile2Field stringValue]] );
4011 else if (fileExistsInQueue == YES)
4013 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
4014 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4015 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
4016 NULL, NULL, [NSString stringWithFormat:
4017 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4018 [fDstFile2Field stringValue]] );
4022 [self doAddToQueue];
4026 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
4027 the user if they want to overwrite an exiting movie file.
4029 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
4030 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4032 if( returnCode == NSAlertAlternateReturn )
4033 [self doAddToQueue];
4036 - (void) doAddToQueue
4038 [self addQueueFileItem ];
4043 /* Rip: puts up an alert before ultimately calling doRip
4045 - (IBAction) Rip: (id) sender
4047 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
4048 /* Rip or Cancel ? */
4050 hb_get_state2( fQueueEncodeLibhb, &s );
4052 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
4054 [self Cancel: sender];
4058 /* We check to see if we need to warn the user that the computer will go to sleep
4059 or shut down when encoding is finished */
4060 [self remindUserOfSleepOrShutdown];
4062 // If there are pending jobs in the queue, then this is a rip the queue
4063 if (fPendingCount > 0)
4065 /* here lets start the queue with the first pending item */
4066 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4071 // Before adding jobs to the queue, check for a valid destination.
4073 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4074 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
4076 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
4080 /* We check for duplicate name here */
4081 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
4083 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
4084 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
4085 @selector( overWriteAlertDone:returnCode:contextInfo: ),
4086 NULL, NULL, [NSString stringWithFormat:
4087 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
4088 [fDstFile2Field stringValue]] );
4090 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4094 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4095 otherwise, just rip the queue */
4096 if(fPendingCount == 0)
4098 [self doAddToQueue];
4101 /* go right to processing the new queue encode */
4102 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4107 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4108 want to overwrite an exiting movie file.
4110 - (void) overWriteAlertDone: (NSWindow *) sheet
4111 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4113 if( returnCode == NSAlertAlternateReturn )
4115 /* if there are no jobs in the queue, then add this one to the queue and rip
4116 otherwise, just rip the queue */
4117 if( fPendingCount == 0 )
4119 [self doAddToQueue];
4122 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4123 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4124 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4129 - (void) remindUserOfSleepOrShutdown
4131 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4133 /*Warn that computer will sleep after encoding*/
4136 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);
4137 [NSApp requestUserAttention:NSCriticalRequest];
4138 if ( reminduser == NSAlertAlternateReturn )
4140 [self showPreferencesWindow:nil];
4143 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4145 /*Warn that computer will shut down after encoding*/
4148 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);
4149 [NSApp requestUserAttention:NSCriticalRequest];
4150 if ( reminduser == NSAlertAlternateReturn )
4152 [self showPreferencesWindow:nil];
4161 /* Let libhb do the job */
4162 hb_start( fQueueEncodeLibhb );
4163 /*set the fEncodeState State */
4168 //------------------------------------------------------------------------------------
4169 // Displays an alert asking user if the want to cancel encoding of current job.
4170 // Cancel: returns immediately after posting the alert. Later, when the user
4171 // acknowledges the alert, doCancelCurrentJob is called.
4172 //------------------------------------------------------------------------------------
4173 - (IBAction)Cancel: (id)sender
4175 if (!fQueueController) return;
4177 hb_pause( fQueueEncodeLibhb );
4178 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4180 // Which window to attach the sheet to?
4181 NSWindow * docWindow;
4182 if ([sender respondsToSelector: @selector(window)])
4183 docWindow = [sender window];
4185 docWindow = fWindow;
4187 NSBeginCriticalAlertSheet(
4189 NSLocalizedString(@"Continue Encoding", nil),
4190 NSLocalizedString(@"Cancel Current and Stop", nil),
4191 NSLocalizedString(@"Cancel Current and Continue", nil),
4193 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4194 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4196 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4199 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4201 hb_resume( fQueueEncodeLibhb );
4202 if (returnCode == NSAlertOtherReturn)
4204 [self doCancelCurrentJob]; // <- this also stops libhb
4206 if (returnCode == NSAlertAlternateReturn)
4208 [self doCancelCurrentJobAndStop];
4212 //------------------------------------------------------------------------------------
4213 // Cancels and deletes the current job and stops libhb from processing the remaining
4215 //------------------------------------------------------------------------------------
4216 - (void) doCancelCurrentJob
4218 // Stop the current job. hb_stop will only cancel the current pass and then set
4219 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4220 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4221 // remaining passes of the job and then start the queue back up if there are any
4225 hb_stop( fQueueEncodeLibhb );
4227 // Delete all remaining jobs since libhb doesn't do this on its own.
4229 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4230 hb_rem( fQueueEncodeLibhb, job );
4232 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4234 // now that we've stopped the currently encoding job, lets mark it as cancelled
4235 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4236 // and as always, save it in the queue .plist...
4237 /* We save all of the Queue data here */
4238 [self saveQueueFileItem];
4239 // so now lets move to
4240 currentQueueEncodeIndex++ ;
4241 // ... and see if there are more items left in our queue
4242 int queueItems = [QueueFileArray count];
4243 /* If we still have more items in our queue, lets go to the next one */
4244 if (currentQueueEncodeIndex < queueItems)
4246 [self writeToActivityLog: "doCancelCurrentJob currentQueueEncodeIndex is incremented to: %d", currentQueueEncodeIndex];
4247 [self writeToActivityLog: "doCancelCurrentJob moving to the next job"];
4249 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4253 [self writeToActivityLog: "doCancelCurrentJob the item queue is complete"];
4258 - (void) doCancelCurrentJobAndStop
4260 hb_stop( fQueueEncodeLibhb );
4262 // Delete all remaining jobs since libhb doesn't do this on its own.
4264 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4265 hb_rem( fQueueEncodeLibhb, job );
4268 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4270 // now that we've stopped the currently encoding job, lets mark it as cancelled
4271 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4272 // and as always, save it in the queue .plist...
4273 /* We save all of the Queue data here */
4274 [self saveQueueFileItem];
4275 // so now lets move to
4276 currentQueueEncodeIndex++ ;
4277 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4279 - (IBAction) Pause: (id) sender
4282 hb_get_state2( fQueueEncodeLibhb, &s );
4284 if( s.state == HB_STATE_PAUSED )
4286 hb_resume( fQueueEncodeLibhb );
4290 hb_pause( fQueueEncodeLibhb );
4295 #pragma mark GUI Controls Changed Methods
4297 - (IBAction) titlePopUpChanged: (id) sender
4299 hb_list_t * list = hb_get_titles( fHandle );
4300 hb_title_t * title = (hb_title_t*)
4301 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4303 /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4304 if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4306 /* we set the default name according to the new title->name */
4307 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4308 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4309 [NSString stringWithUTF8String: title->name],
4310 [[fDstFile2Field stringValue] pathExtension]]];
4312 /* Change the source to read out the parent folder also */
4313 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4316 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4317 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4318 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4319 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4320 /* 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 */
4321 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4322 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4323 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4325 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4326 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4328 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4329 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4330 [browsedSourceDisplayName stringByDeletingPathExtension],
4332 [[fDstFile2Field stringValue] pathExtension]]];
4334 /* Update encode start / stop variables */
4338 /* Update chapter popups */
4339 [fSrcChapterStartPopUp removeAllItems];
4340 [fSrcChapterEndPopUp removeAllItems];
4341 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4343 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4344 stringWithFormat: @"%d", i + 1]];
4345 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4346 stringWithFormat: @"%d", i + 1]];
4349 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4350 [fSrcChapterEndPopUp selectItemAtIndex:
4351 hb_list_count( title->list_chapter ) - 1];
4352 [self chapterPopUpChanged:nil];
4354 /* if using dvd nav, show the angle widget */
4355 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4357 [fSrcAngleLabel setHidden:NO];
4358 [fSrcAnglePopUp setHidden:NO];
4360 [fSrcAnglePopUp removeAllItems];
4361 for( int i = 0; i < title->angle_count; i++ )
4363 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4365 [fSrcAnglePopUp selectItemAtIndex: 0];
4369 [fSrcAngleLabel setHidden:YES];
4370 [fSrcAnglePopUp setHidden:YES];
4373 /* Start Get and set the initial pic size for display */
4374 hb_job_t * job = title->job;
4377 /* Set Auto Crop to on upon selecting a new title */
4378 [fPictureController setAutoCrop:YES];
4380 /* We get the originial output picture width and height and put them
4381 in variables for use with some presets later on */
4382 PicOrigOutputWidth = job->width;
4383 PicOrigOutputHeight = job->height;
4384 AutoCropTop = job->crop[0];
4385 AutoCropBottom = job->crop[1];
4386 AutoCropLeft = job->crop[2];
4387 AutoCropRight = job->crop[3];
4389 /* Reset the new title in fPictureController && fPreviewController*/
4390 [fPictureController SetTitle:title];
4393 /* Update Subtitle Table */
4394 [fSubtitlesDelegate resetWithTitle:title];
4395 [fSubtitlesTable reloadData];
4398 /* Update chapter table */
4399 [fChapterTitlesDelegate resetWithTitle:title];
4400 [fChapterTable reloadData];
4402 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4403 int audiotrack_count = hb_list_count(job->list_audio);
4404 for( int i = 0; i < audiotrack_count;i++)
4406 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4407 hb_list_rem(job->list_audio, temp_audio);
4410 /* Update audio popups */
4411 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
4412 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
4413 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
4414 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
4415 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
4416 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
4417 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
4418 [self selectAudioTrackInPopUp:fAudLang2PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4419 [self selectAudioTrackInPopUp:fAudLang3PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4420 [self selectAudioTrackInPopUp:fAudLang4PopUp searchPrefixString:nil selectIndexIfNotFound:0];
4422 /* changing the title may have changed the audio channels on offer, */
4423 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4424 [self audioTrackPopUpChanged: fAudLang1PopUp];
4425 [self audioTrackPopUpChanged: fAudLang2PopUp];
4426 [self audioTrackPopUpChanged: fAudLang3PopUp];
4427 [self audioTrackPopUpChanged: fAudLang4PopUp];
4429 [fVidRatePopUp selectItemAtIndex: 0];
4431 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4432 [self calculatePictureSizing:nil];
4434 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4435 [self selectPreset:nil];
4438 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4440 if( [fEncodeStartStopPopUp isEnabled] )
4442 /* We are chapters */
4443 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4445 [fSrcChapterStartPopUp setHidden: NO];
4446 [fSrcChapterEndPopUp setHidden: NO];
4448 [fSrcTimeStartEncodingField setHidden: YES];
4449 [fSrcTimeEndEncodingField setHidden: YES];
4451 [fSrcFrameStartEncodingField setHidden: YES];
4452 [fSrcFrameEndEncodingField setHidden: YES];
4454 [self chapterPopUpChanged:nil];
4456 /* We are time based (seconds) */
4457 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4459 [fSrcChapterStartPopUp setHidden: YES];
4460 [fSrcChapterEndPopUp setHidden: YES];
4462 [fSrcTimeStartEncodingField setHidden: NO];
4463 [fSrcTimeEndEncodingField setHidden: NO];
4465 [fSrcFrameStartEncodingField setHidden: YES];
4466 [fSrcFrameEndEncodingField setHidden: YES];
4468 [self startEndSecValueChanged:nil];
4470 /* We are frame based */
4471 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4473 [fSrcChapterStartPopUp setHidden: YES];
4474 [fSrcChapterEndPopUp setHidden: YES];
4476 [fSrcTimeStartEncodingField setHidden: YES];
4477 [fSrcTimeEndEncodingField setHidden: YES];
4479 [fSrcFrameStartEncodingField setHidden: NO];
4480 [fSrcFrameEndEncodingField setHidden: NO];
4482 [self startEndFrameValueChanged:nil];
4487 - (IBAction) chapterPopUpChanged: (id) sender
4490 /* If start chapter popup is greater than end chapter popup,
4491 we set the end chapter popup to the same as start chapter popup */
4492 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4494 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4498 hb_list_t * list = hb_get_titles( fHandle );
4499 hb_title_t * title = (hb_title_t *)
4500 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4502 hb_chapter_t * chapter;
4503 int64_t duration = 0;
4504 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4505 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4507 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4508 duration += chapter->duration;
4511 duration /= 90000; /* pts -> seconds */
4512 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4513 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4516 [self calculateBitrate: sender];
4518 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4520 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4521 [fCreateChapterMarkers setEnabled: NO];
4522 [fCreateChapterMarkers setState: NSOffState];
4526 [fCreateChapterMarkers setEnabled: YES];
4530 - (IBAction) startEndSecValueChanged: (id) sender
4533 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4534 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4535 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4538 //[self calculateBitrate: sender];
4542 - (IBAction) startEndFrameValueChanged: (id) sender
4544 hb_list_t * list = hb_get_titles( fHandle );
4545 hb_title_t * title = (hb_title_t*)
4546 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4548 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4549 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4550 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4553 //[self calculateBitrate: sender];
4557 - (IBAction) formatPopUpChanged: (id) sender
4559 NSString * string = [fDstFile2Field stringValue];
4560 int format = [fDstFormatPopUp indexOfSelectedItem];
4562 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4563 [fDstMp4LargeFileCheck setHidden: YES];
4564 [fDstMp4HttpOptFileCheck setHidden: YES];
4565 [fDstMp4iPodFileCheck setHidden: YES];
4567 /* Update the Video Codec PopUp */
4568 /* lets get the tag of the currently selected item first so we might reset it later */
4569 int selectedVidEncoderTag;
4570 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4572 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4573 [fVidEncoderPopUp removeAllItems];
4574 NSMenuItem *menuItem;
4575 /* These video encoders are available to all of our current muxers, so lets list them once here */
4576 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4577 [menuItem setTag: HB_VCODEC_FFMPEG];
4582 /*Get Default MP4 File Extension*/
4583 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4591 /* Add additional video encoders here */
4592 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4593 [menuItem setTag: HB_VCODEC_X264];
4594 /* We show the mp4 option checkboxes here since we are mp4 */
4595 [fCreateChapterMarkers setEnabled: YES];
4596 [fDstMp4LargeFileCheck setHidden: NO];
4597 [fDstMp4HttpOptFileCheck setHidden: NO];
4598 [fDstMp4iPodFileCheck setHidden: NO];
4603 /* Add additional video encoders here */
4604 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4605 [menuItem setTag: HB_VCODEC_X264];
4606 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4607 [menuItem setTag: HB_VCODEC_THEORA];
4608 /* We enable the create chapters checkbox here */
4609 [fCreateChapterMarkers setEnabled: YES];
4614 /* tell fSubtitlesDelegate we have a new video container */
4616 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4617 [fSubtitlesTable reloadData];
4618 /* if we have a previously selected vid encoder tag, then try to select it */
4619 if (selectedVidEncoderTag)
4621 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4625 [fVidEncoderPopUp selectItemAtIndex: 0];
4628 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
4629 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
4630 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
4631 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
4634 [self autoSetM4vExtension: sender];
4636 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4638 if( SuccessfulScan )
4640 /* Add/replace to the correct extension */
4641 [self audioTrackPopUpChanged: fAudLang1PopUp];
4642 [self audioTrackPopUpChanged: fAudLang2PopUp];
4643 [self audioTrackPopUpChanged: fAudLang3PopUp];
4644 [self audioTrackPopUpChanged: fAudLang4PopUp];
4646 if( [fVidEncoderPopUp selectedItem] == nil )
4649 [fVidEncoderPopUp selectItemAtIndex:0];
4650 [self videoEncoderPopUpChanged:nil];
4652 /* changing the format may mean that we can / can't offer mono or 6ch, */
4653 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4655 /* We call the method to properly enable/disable turbo 2 pass */
4656 [self twoPassCheckboxChanged: sender];
4657 /* We call method method to change UI to reflect whether a preset is used or not*/
4660 [self customSettingUsed: sender];
4663 - (IBAction) autoSetM4vExtension: (id) sender
4665 if ( [fDstFormatPopUp indexOfSelectedItem] )
4668 NSString * extension = @"mp4";
4670 if( [[fAudTrack1CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4671 [[fAudTrack3CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4672 [[fAudTrack4CodecPopUp selectedItem] tag] == HB_ACODEC_AC3 ||
4673 [fCreateChapterMarkers state] == NSOnState ||
4674 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4679 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4682 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4683 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4686 /* Method to determine if we should change the UI
4687 To reflect whether or not a Preset is being used or if
4688 the user is using "Custom" settings by determining the sender*/
4689 - (IBAction) customSettingUsed: (id) sender
4691 if ([sender stringValue])
4693 /* Deselect the currently selected Preset if there is one*/
4694 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4695 /* Change UI to show "Custom" settings are being used */
4696 [fPresetSelectedDisplay setStringValue: @"Custom"];
4698 curUserPresetChosenNum = nil;
4700 [self calculateBitrate:nil];
4705 #pragma mark - Video
4707 - (IBAction) videoEncoderPopUpChanged: (id) sender
4709 hb_job_t * job = fTitle->job;
4710 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4712 [fAdvancedOptions setHidden:YES];
4713 /* If we are using x264 then show the x264 advanced panel*/
4714 if (videoEncoder == HB_VCODEC_X264)
4716 [fAdvancedOptions setHidden:NO];
4717 [self autoSetM4vExtension: sender];
4720 if (videoEncoder == HB_VCODEC_FFMPEG)
4722 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4723 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4724 anything other than MP4.
4726 [fDstMp4iPodFileCheck setEnabled: NO];
4727 [fDstMp4iPodFileCheck setState: NSOffState];
4731 [fDstMp4iPodFileCheck setEnabled: YES];
4733 [self setupQualitySlider];
4734 [self calculatePictureSizing: sender];
4735 [self twoPassCheckboxChanged: sender];
4739 - (IBAction) twoPassCheckboxChanged: (id) sender
4741 /* check to see if x264 is chosen */
4742 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4744 if( [fVidTwoPassCheck state] == NSOnState)
4746 [fVidTurboPassCheck setHidden: NO];
4750 [fVidTurboPassCheck setHidden: YES];
4751 [fVidTurboPassCheck setState: NSOffState];
4753 /* Make sure Two Pass is checked if Turbo is checked */
4754 if( [fVidTurboPassCheck state] == NSOnState)
4756 [fVidTwoPassCheck setState: NSOnState];
4761 [fVidTurboPassCheck setHidden: YES];
4762 [fVidTurboPassCheck setState: NSOffState];
4765 /* We call method method to change UI to reflect whether a preset is used or not*/
4766 [self customSettingUsed: sender];
4769 - (IBAction ) videoFrameRateChanged: (id) sender
4771 /* Hide and set the PFR Checkbox to OFF if we are set to Same as Source */
4772 if ([fVidRatePopUp indexOfSelectedItem] == 0)
4774 [fFrameratePfrCheck setHidden:YES];
4775 [fFrameratePfrCheck setState:0];
4779 [fFrameratePfrCheck setHidden:NO];
4782 /* We call method method to calculatePictureSizing to error check detelecine*/
4783 [self calculatePictureSizing: sender];
4785 /* We call method method to change UI to reflect whether a preset is used or not*/
4786 [self customSettingUsed: sender];
4788 - (IBAction) videoMatrixChanged: (id) sender;
4790 bool target, bitrate, quality;
4792 target = bitrate = quality = false;
4793 if( [fVidQualityMatrix isEnabled] )
4795 switch( [fVidQualityMatrix selectedRow] )
4808 [fVidTargetSizeField setEnabled: target];
4809 [fVidBitrateField setEnabled: bitrate];
4810 [fVidQualitySlider setEnabled: quality];
4811 [fVidQualityRFField setEnabled: quality];
4812 [fVidQualityRFLabel setEnabled: quality];
4813 [fVidTwoPassCheck setEnabled: !quality &&
4814 [fVidQualityMatrix isEnabled]];
4817 [fVidTwoPassCheck setState: NSOffState];
4818 [fVidTurboPassCheck setHidden: YES];
4819 [fVidTurboPassCheck setState: NSOffState];
4822 [self qualitySliderChanged: sender];
4823 [self calculateBitrate: sender];
4824 [self customSettingUsed: sender];
4827 /* Use this method to setup the quality slider for cq/rf values depending on
4828 * the video encoder selected.
4830 - (void) setupQualitySlider
4832 /* Get the current slider maxValue to check for a change in slider scale later
4833 * so that we can choose a new similar value on the new slider scale */
4834 float previousMaxValue = [fVidQualitySlider maxValue];
4835 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4836 NSString * qpRFLabelString = @"QP:";
4838 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4840 [fVidQualitySlider setMinValue:0.0];
4841 [fVidQualitySlider setMaxValue:51.0];
4842 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4843 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4844 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4845 qpRFLabelString = @"RF:";
4848 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
4850 [fVidQualitySlider setMinValue:1.0];
4851 [fVidQualitySlider setMaxValue:31.0];
4852 [fVidQualitySlider setNumberOfTickMarks:31];
4855 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4857 [fVidQualitySlider setMinValue:0.0];
4858 [fVidQualitySlider setMaxValue:63.0];
4859 [fVidQualitySlider setNumberOfTickMarks:64];
4861 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4863 /* check to see if we have changed slider scales */
4864 if (previousMaxValue != [fVidQualitySlider maxValue])
4866 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4867 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4868 [fVidQualitySlider setFloatValue:rf];
4871 [self qualitySliderChanged:nil];
4874 - (IBAction) qualitySliderChanged: (id) sender
4876 /* Our constant quality slider is in a range based
4877 * on each encoders qp/rf values. The range depends
4878 * on the encoder. Also, the range is inverse of quality
4879 * for all of the encoders *except* for theora
4880 * (ie. as the "quality" goes up, the cq or rf value
4881 * actually goes down). Since the IB sliders always set
4882 * their max value at the right end of the slider, we
4883 * will calculate the inverse, so as the slider floatValue
4884 * goes up, we will show the inverse in the rf field
4885 * so, the floatValue at the right for x264 would be 51
4886 * and our rf field needs to show 0 and vice versa.
4889 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4890 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4891 //float sliderRfToPercent;
4892 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4894 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4898 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4900 [self customSettingUsed: sender];
4903 - (void) controlTextDidChange: (NSNotification *) notification
4905 [self calculateBitrate:nil];
4908 - (IBAction) calculateBitrate: (id) sender
4910 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4915 hb_list_t * list = hb_get_titles( fHandle );
4916 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4917 [fSrcTitlePopUp indexOfSelectedItem] );
4918 hb_job_t * job = title->job;
4919 hb_audio_config_t * audio;
4920 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4921 * Target Size Field, we also need the job info for the Muxer, the Chapters
4922 * as well as all of the audio track info.
4923 * This used to be accomplished by simply calling prepareJob here, however
4924 * since the resilient queue sets the queue array values instead of the job
4925 * values directly, we duplicate the old prepareJob code here for the variables
4928 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4929 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4930 job->mux = [[fDstFormatPopUp selectedItem] tag];
4932 /* Audio goes here */
4933 int audiotrack_count = hb_list_count(job->list_audio);
4934 for( int i = 0; i < audiotrack_count;i++)
4936 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4937 hb_list_rem(job->list_audio, temp_audio);
4939 /* Now we need our audio info here for each track if applicable */
4940 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4942 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4943 hb_audio_config_init(audio);
4944 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4945 /* We go ahead and assign values to our audio->out.<properties> */
4946 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
4947 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
4948 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
4949 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
4950 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
4951 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
4953 hb_audio_add( job, audio );
4956 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4958 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4959 hb_audio_config_init(audio);
4960 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4961 /* We go ahead and assign values to our audio->out.<properties> */
4962 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
4963 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
4964 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
4965 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
4966 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
4967 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
4969 hb_audio_add( job, audio );
4974 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4976 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4977 hb_audio_config_init(audio);
4978 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4979 /* We go ahead and assign values to our audio->out.<properties> */
4980 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
4981 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
4982 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
4983 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
4984 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
4985 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
4987 hb_audio_add( job, audio );
4992 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4994 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
4995 hb_audio_config_init(audio);
4996 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4997 /* We go ahead and assign values to our audio->out.<properties> */
4998 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
4999 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
5000 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
5001 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
5002 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
5003 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
5005 hb_audio_add( job, audio );
5010 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
5014 #pragma mark - Picture
5016 /* lets set the picture size back to the max from right after title scan
5017 Lets use an IBAction here as down the road we could always use a checkbox
5018 in the gui to easily take the user back to max. Remember, the compiler
5019 resolves IBActions down to -(void) during compile anyway */
5020 - (IBAction) revertPictureSizeToMax: (id) sender
5022 hb_job_t * job = fTitle->job;
5023 /* Here we apply the title source and height */
5024 job->width = fTitle->width;
5025 job->height = fTitle->height;
5027 [self calculatePictureSizing: sender];
5028 /* We call method to change UI to reflect whether a preset is used or not*/
5029 [self customSettingUsed: sender];
5033 * Registers changes made in the Picture Settings Window.
5036 - (void)pictureSettingsDidChange
5038 [self calculatePictureSizing:nil];
5041 /* Get and Display Current Pic Settings in main window */
5042 - (IBAction) calculatePictureSizing: (id) sender
5044 if (fTitle->job->anamorphic.mode > 0)
5046 fTitle->job->keep_ratio = 0;
5049 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
5051 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
5055 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
5057 NSString *picCropping;
5058 /* Set the display field for crop as per boolean */
5059 if (![fPictureController autoCrop])
5061 picCropping = @"Custom";
5065 picCropping = @"Auto";
5067 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]]];
5069 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
5071 NSString *videoFilters;
5074 if ([fPictureController detelecine] == 2)
5076 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
5078 else if ([fPictureController detelecine] == 1)
5080 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
5084 if ([fPictureController useDecomb] == 1)
5087 if ([fPictureController decomb] == 2)
5089 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
5091 else if ([fPictureController decomb] == 1)
5093 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
5099 if ([fPictureController deinterlace] > 0)
5101 fTitle->job->deinterlace = 1;
5105 fTitle->job->deinterlace = 0;
5108 if ([fPictureController deinterlace] == 2)
5110 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
5112 else if ([fPictureController deinterlace] == 3)
5114 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
5116 else if ([fPictureController deinterlace] == 4)
5118 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
5120 else if ([fPictureController deinterlace] == 1)
5122 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
5128 if ([fPictureController denoise] == 2)
5130 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
5132 else if ([fPictureController denoise] == 3)
5134 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
5136 else if ([fPictureController denoise] == 4)
5138 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
5140 else if ([fPictureController denoise] == 1)
5142 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
5146 if ([fPictureController deblock] > 0)
5148 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
5152 if ([fPictureController grayscale])
5154 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
5156 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
5158 //[fPictureController reloadStillPreview];
5163 #pragma mark - Audio and Subtitles
5164 - (IBAction) audioCodecsPopUpChanged: (id) sender
5167 NSPopUpButton * audiotrackPopUp;
5168 NSPopUpButton * sampleratePopUp;
5169 NSPopUpButton * bitratePopUp;
5170 NSPopUpButton * audiocodecPopUp;
5171 if (sender == fAudTrack1CodecPopUp)
5173 audiotrackPopUp = fAudLang1PopUp;
5174 audiocodecPopUp = fAudTrack1CodecPopUp;
5175 sampleratePopUp = fAudTrack1RatePopUp;
5176 bitratePopUp = fAudTrack1BitratePopUp;
5178 else if (sender == fAudTrack2CodecPopUp)
5180 audiotrackPopUp = fAudLang2PopUp;
5181 audiocodecPopUp = fAudTrack2CodecPopUp;
5182 sampleratePopUp = fAudTrack2RatePopUp;
5183 bitratePopUp = fAudTrack2BitratePopUp;
5185 else if (sender == fAudTrack3CodecPopUp)
5187 audiotrackPopUp = fAudLang3PopUp;
5188 audiocodecPopUp = fAudTrack3CodecPopUp;
5189 sampleratePopUp = fAudTrack3RatePopUp;
5190 bitratePopUp = fAudTrack3BitratePopUp;
5194 audiotrackPopUp = fAudLang4PopUp;
5195 audiocodecPopUp = fAudTrack4CodecPopUp;
5196 sampleratePopUp = fAudTrack4RatePopUp;
5197 bitratePopUp = fAudTrack4BitratePopUp;
5200 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
5201 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
5202 [self audioTrackPopUpChanged: audiotrackPopUp];
5206 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
5208 /* We will be setting the enabled/disabled state of each tracks audio controls based on
5209 * the settings of the source audio for that track. We leave the samplerate and bitrate
5210 * to audiotrackMixdownChanged
5213 /* We will first verify that a lower track number has been selected before enabling each track
5214 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
5217 /* If the source has no audio then disable audio track 1 */
5218 if (hb_list_count( fTitle->list_audio ) == 0)
5220 [fAudLang1PopUp selectItemAtIndex:0];
5223 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5225 [fAudLang2PopUp setEnabled: NO];
5226 [fAudLang2PopUp selectItemAtIndex: 0];
5230 [fAudLang2PopUp setEnabled: YES];
5233 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5235 [fAudLang3PopUp setEnabled: NO];
5236 [fAudLang3PopUp selectItemAtIndex: 0];
5240 [fAudLang3PopUp setEnabled: YES];
5242 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5244 [fAudLang4PopUp setEnabled: NO];
5245 [fAudLang4PopUp selectItemAtIndex: 0];
5249 [fAudLang4PopUp setEnabled: YES];
5251 /* enable/disable the mixdown text and popupbutton for audio track 1 */
5252 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5253 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5254 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5255 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5256 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5257 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
5258 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
5260 [fAudTrack1CodecPopUp removeAllItems];
5261 [fAudTrack1MixPopUp removeAllItems];
5262 [fAudTrack1RatePopUp removeAllItems];
5263 [fAudTrack1BitratePopUp removeAllItems];
5264 [fAudTrack1DrcSlider setFloatValue: 0.00];
5265 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
5267 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5269 [fAudTrack1RatePopUp setEnabled: NO];
5270 [fAudTrack1BitratePopUp setEnabled: NO];
5271 [fAudTrack1DrcSlider setEnabled: NO];
5272 [fAudTrack1DrcField setEnabled: NO];
5275 /* enable/disable the mixdown text and popupbutton for audio track 2 */
5276 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5277 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5278 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5279 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5280 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5281 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
5282 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
5284 [fAudTrack2CodecPopUp removeAllItems];
5285 [fAudTrack2MixPopUp removeAllItems];
5286 [fAudTrack2RatePopUp removeAllItems];
5287 [fAudTrack2BitratePopUp removeAllItems];
5288 [fAudTrack2DrcSlider setFloatValue: 0.00];
5289 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
5291 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5293 [fAudTrack2RatePopUp setEnabled: NO];
5294 [fAudTrack2BitratePopUp setEnabled: NO];
5295 [fAudTrack2DrcSlider setEnabled: NO];
5296 [fAudTrack2DrcField setEnabled: NO];
5299 /* enable/disable the mixdown text and popupbutton for audio track 3 */
5300 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5301 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5302 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5303 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5304 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5305 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
5306 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
5308 [fAudTrack3CodecPopUp removeAllItems];
5309 [fAudTrack3MixPopUp removeAllItems];
5310 [fAudTrack3RatePopUp removeAllItems];
5311 [fAudTrack3BitratePopUp removeAllItems];
5312 [fAudTrack3DrcSlider setFloatValue: 0.00];
5313 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
5315 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5317 [fAudTrack3RatePopUp setEnabled: NO];
5318 [fAudTrack3BitratePopUp setEnabled: NO];
5319 [fAudTrack3DrcSlider setEnabled: NO];
5320 [fAudTrack3DrcField setEnabled: NO];
5323 /* enable/disable the mixdown text and popupbutton for audio track 4 */
5324 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5325 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5326 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5327 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5328 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5329 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
5330 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
5332 [fAudTrack4CodecPopUp removeAllItems];
5333 [fAudTrack4MixPopUp removeAllItems];
5334 [fAudTrack4RatePopUp removeAllItems];
5335 [fAudTrack4BitratePopUp removeAllItems];
5336 [fAudTrack4DrcSlider setFloatValue: 0.00];
5337 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
5339 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_DCA)
5341 [fAudTrack4RatePopUp setEnabled: NO];
5342 [fAudTrack4BitratePopUp setEnabled: NO];
5343 [fAudTrack4DrcSlider setEnabled: NO];
5344 [fAudTrack4DrcField setEnabled: NO];
5349 - (IBAction) addAllAudioTracksToPopUp: (id) sender
5352 hb_list_t * list = hb_get_titles( fHandle );
5353 hb_title_t * title = (hb_title_t*)
5354 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
5356 hb_audio_config_t * audio;
5358 [sender removeAllItems];
5359 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
5360 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
5362 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
5363 [[sender menu] addItemWithTitle:
5364 [NSString stringWithUTF8String: audio->lang.description]
5365 action: NULL keyEquivalent: @""];
5367 [sender selectItemAtIndex: 0];
5371 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
5374 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
5375 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
5376 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
5377 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
5378 if (hb_list_count( fTitle->list_audio ) != 0)
5380 if (searchPrefixString)
5383 for( int i = 0; i < [sender numberOfItems]; i++ )
5385 /* Try to find the desired search string */
5386 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
5388 [sender selectItemAtIndex: i];
5392 /* couldn't find the string, so select the requested "search string not found" item */
5393 /* index of 0 means select the "none" item */
5394 /* index of 1 means select the first audio track */
5395 [sender selectItemAtIndex: selectIndexIfNotFound];
5399 /* if no search string is provided, then select the selectIndexIfNotFound item */
5400 [sender selectItemAtIndex: selectIndexIfNotFound];
5405 [sender selectItemAtIndex: 0];
5409 - (IBAction) audioAddAudioTrackCodecs: (id)sender
5411 int format = [fDstFormatPopUp indexOfSelectedItem];
5413 /* setup pointers to the appropriate popups for the correct track */
5414 NSPopUpButton * audiocodecPopUp;
5415 NSPopUpButton * audiotrackPopUp;
5416 if (sender == fAudTrack1CodecPopUp)
5418 audiotrackPopUp = fAudLang1PopUp;
5419 audiocodecPopUp = fAudTrack1CodecPopUp;
5421 else if (sender == fAudTrack2CodecPopUp)
5423 audiotrackPopUp = fAudLang2PopUp;
5424 audiocodecPopUp = fAudTrack2CodecPopUp;
5426 else if (sender == fAudTrack3CodecPopUp)
5428 audiotrackPopUp = fAudLang3PopUp;
5429 audiocodecPopUp = fAudTrack3CodecPopUp;
5433 audiotrackPopUp = fAudLang4PopUp;
5434 audiocodecPopUp = fAudTrack4CodecPopUp;
5437 [audiocodecPopUp removeAllItems];
5438 /* Make sure "None" isnt selected in the source track */
5439 if ([audiotrackPopUp indexOfSelectedItem] > 0)
5441 [audiocodecPopUp setEnabled:YES];
5442 NSMenuItem *menuItem;
5443 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
5449 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5450 [menuItem setTag: HB_ACODEC_CA_AAC];
5452 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5453 [menuItem setTag: HB_ACODEC_FAAC];
5455 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5456 [menuItem setTag: HB_ACODEC_LAME];
5458 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5459 [menuItem setTag: HB_ACODEC_AC3];
5465 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (CoreAudio)" action: NULL keyEquivalent: @""];
5466 [menuItem setTag: HB_ACODEC_CA_AAC];
5468 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
5469 [menuItem setTag: HB_ACODEC_FAAC];
5471 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
5472 [menuItem setTag: HB_ACODEC_AC3];
5474 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"DTS Passthru" action: NULL keyEquivalent: @""];
5475 [menuItem setTag: HB_ACODEC_DCA];
5477 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
5478 [menuItem setTag: HB_ACODEC_LAME];
5480 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
5481 [menuItem setTag: HB_ACODEC_VORBIS];
5484 [audiocodecPopUp selectItemAtIndex:0];
5488 [audiocodecPopUp setEnabled:NO];
5492 - (IBAction) audioTrackPopUpChanged: (id) sender
5494 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
5495 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
5498 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
5501 /* make sure we have a selected title before continuing */
5502 if (fTitle == NULL) return;
5503 /* make sure we have a source audio track before continuing */
5504 if (hb_list_count( fTitle->list_audio ) == 0)
5506 [sender selectItemAtIndex:0];
5509 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
5510 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
5512 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
5514 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
5516 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
5518 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
5520 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
5522 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
5524 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
5526 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
5529 /* Now lets make the sender the appropriate Audio Track popup from this point on */
5530 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
5532 sender = fAudLang1PopUp;
5534 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
5536 sender = fAudLang2PopUp;
5538 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
5540 sender = fAudLang3PopUp;
5542 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
5544 sender = fAudLang4PopUp;
5547 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
5548 NSPopUpButton * mixdownPopUp;
5549 NSPopUpButton * audiocodecPopUp;
5550 NSPopUpButton * sampleratePopUp;
5551 NSPopUpButton * bitratePopUp;
5552 if (sender == fAudLang1PopUp)
5554 mixdownPopUp = fAudTrack1MixPopUp;
5555 audiocodecPopUp = fAudTrack1CodecPopUp;
5556 sampleratePopUp = fAudTrack1RatePopUp;
5557 bitratePopUp = fAudTrack1BitratePopUp;
5559 else if (sender == fAudLang2PopUp)
5561 mixdownPopUp = fAudTrack2MixPopUp;
5562 audiocodecPopUp = fAudTrack2CodecPopUp;
5563 sampleratePopUp = fAudTrack2RatePopUp;
5564 bitratePopUp = fAudTrack2BitratePopUp;
5566 else if (sender == fAudLang3PopUp)
5568 mixdownPopUp = fAudTrack3MixPopUp;
5569 audiocodecPopUp = fAudTrack3CodecPopUp;
5570 sampleratePopUp = fAudTrack3RatePopUp;
5571 bitratePopUp = fAudTrack3BitratePopUp;
5575 mixdownPopUp = fAudTrack4MixPopUp;
5576 audiocodecPopUp = fAudTrack4CodecPopUp;
5577 sampleratePopUp = fAudTrack4RatePopUp;
5578 bitratePopUp = fAudTrack4BitratePopUp;
5581 /* get the index of the selected audio Track*/
5582 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
5584 /* pointer for the hb_audio_s struct we will use later on */
5585 hb_audio_config_t * audio;
5588 /* check if the audio mixdown controls need their enabled state changing */
5589 [self setEnabledStateOfAudioMixdownControls:nil];
5591 if (thisAudioIndex != -1)
5595 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
5597 /* actually manipulate the proper mixdowns here */
5598 /* delete the previous audio mixdown options */
5599 [mixdownPopUp removeAllItems];
5601 acodec = [[audiocodecPopUp selectedItem] tag];
5606 /* find out if our selected output audio codec supports mono and / or 6ch */
5607 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
5608 but this may change in the future, so they are separated for flexibility */
5609 int audioCodecsSupportMono = (audio->in.codec && acodec != HB_ACODEC_LAME);
5610 int audioCodecsSupport6Ch = (audio->in.codec && acodec != HB_ACODEC_LAME);
5612 /* check for AC-3 passthru */
5613 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5616 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5617 [NSString stringWithUTF8String: "AC3 Passthru"]
5618 action: NULL keyEquivalent: @""];
5619 [menuItem setTag: HB_ACODEC_AC3];
5621 else if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5623 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5624 [NSString stringWithUTF8String: "DTS Passthru"]
5625 action: NULL keyEquivalent: @""];
5626 [menuItem setTag: HB_ACODEC_DCA];
5631 /* add the appropriate audio mixdown menuitems to the popupbutton */
5632 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
5633 so that we can reference the mixdown later */
5635 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
5636 int minMixdownUsed = 0;
5637 int maxMixdownUsed = 0;
5639 /* get the input channel layout without any lfe channels */
5640 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
5642 /* do we want to add a mono option? */
5643 if (audioCodecsSupportMono == 1)
5645 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5646 [NSString stringWithUTF8String: hb_audio_mixdowns[0].human_readable_name]
5647 action: NULL keyEquivalent: @""];
5648 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
5649 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
5650 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
5653 /* do we want to add a stereo option? */
5654 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
5655 /* also offer stereo if we have a stereo-or-better source */
5656 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
5658 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5659 [NSString stringWithUTF8String: hb_audio_mixdowns[1].human_readable_name]
5660 action: NULL keyEquivalent: @""];
5661 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
5662 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
5663 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
5666 /* do we want to add a dolby surround (DPL1) option? */
5667 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
5669 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5670 [NSString stringWithUTF8String: hb_audio_mixdowns[2].human_readable_name]
5671 action: NULL keyEquivalent: @""];
5672 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
5673 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
5674 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
5677 /* do we want to add a dolby pro logic 2 (DPL2) option? */
5678 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
5680 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5681 [NSString stringWithUTF8String: hb_audio_mixdowns[3].human_readable_name]
5682 action: NULL keyEquivalent: @""];
5683 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
5684 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
5685 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
5688 /* do we want to add a 6-channel discrete option? */
5689 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
5691 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5692 [NSString stringWithUTF8String: hb_audio_mixdowns[4].human_readable_name]
5693 action: NULL keyEquivalent: @""];
5694 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
5695 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
5696 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
5699 /* do we want to add an AC-3 passthrough option? */
5700 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
5702 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5703 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5704 action: NULL keyEquivalent: @""];
5705 [menuItem setTag: HB_ACODEC_AC3];
5706 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5707 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5710 /* do we want to add a DTS Passthru option ? HB_ACODEC_DCA*/
5711 if (audio->in.codec == HB_ACODEC_DCA && acodec == HB_ACODEC_DCA)
5713 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
5714 [NSString stringWithUTF8String: hb_audio_mixdowns[5].human_readable_name]
5715 action: NULL keyEquivalent: @""];
5716 [menuItem setTag: HB_ACODEC_DCA];
5717 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
5718 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
5721 /* auto-select the best mixdown based on our saved mixdown preference */
5723 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
5724 /* ultimately this should be a prefs option */
5727 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
5728 if (mixdownToUse > 0)
5730 useMixdown = mixdownToUse;
5734 useMixdown = HB_AMIXDOWN_DOLBYPLII;
5737 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
5738 if (useMixdown > maxMixdownUsed)
5740 useMixdown = maxMixdownUsed;
5743 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
5744 if (useMixdown < minMixdownUsed)
5746 useMixdown = minMixdownUsed;
5749 /* select the (possibly-amended) preferred mixdown */
5750 [mixdownPopUp selectItemWithTag: useMixdown];
5753 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
5754 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5756 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
5758 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5761 /* In the case of a source track that is not DTS and the user tries to use DTS Passthru (which does not work)
5762 * we force the Audio Codec choice back to a workable codec. We use CoreAudio aac for all containers.
5764 if (audio->in.codec != HB_ACODEC_DCA && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_DCA)
5766 [audiocodecPopUp selectItemWithTag: HB_ACODEC_CA_AAC];
5769 /* Setup our samplerate and bitrate popups we will need based on mixdown */
5770 [self audioTrackMixdownChanged: mixdownPopUp];
5774 if( [fDstFormatPopUp indexOfSelectedItem] == 0 )
5776 [self autoSetM4vExtension: sender];
5780 - (IBAction) audioTrackMixdownChanged: (id) sender
5784 /* setup pointers to all of the other audio track controls
5785 * we will need later
5787 NSPopUpButton * mixdownPopUp;
5788 NSPopUpButton * sampleratePopUp;
5789 NSPopUpButton * bitratePopUp;
5790 NSPopUpButton * audiocodecPopUp;
5791 NSPopUpButton * audiotrackPopUp;
5792 NSSlider * drcSlider;
5793 NSTextField * drcField;
5794 if (sender == fAudTrack1MixPopUp)
5796 audiotrackPopUp = fAudLang1PopUp;
5797 audiocodecPopUp = fAudTrack1CodecPopUp;
5798 mixdownPopUp = fAudTrack1MixPopUp;
5799 sampleratePopUp = fAudTrack1RatePopUp;
5800 bitratePopUp = fAudTrack1BitratePopUp;
5801 drcSlider = fAudTrack1DrcSlider;
5802 drcField = fAudTrack1DrcField;
5804 else if (sender == fAudTrack2MixPopUp)
5806 audiotrackPopUp = fAudLang2PopUp;
5807 audiocodecPopUp = fAudTrack2CodecPopUp;
5808 mixdownPopUp = fAudTrack2MixPopUp;
5809 sampleratePopUp = fAudTrack2RatePopUp;
5810 bitratePopUp = fAudTrack2BitratePopUp;
5811 drcSlider = fAudTrack2DrcSlider;
5812 drcField = fAudTrack2DrcField;
5814 else if (sender == fAudTrack3MixPopUp)
5816 audiotrackPopUp = fAudLang3PopUp;
5817 audiocodecPopUp = fAudTrack3CodecPopUp;
5818 mixdownPopUp = fAudTrack3MixPopUp;
5819 sampleratePopUp = fAudTrack3RatePopUp;
5820 bitratePopUp = fAudTrack3BitratePopUp;
5821 drcSlider = fAudTrack3DrcSlider;
5822 drcField = fAudTrack3DrcField;
5826 audiotrackPopUp = fAudLang4PopUp;
5827 audiocodecPopUp = fAudTrack4CodecPopUp;
5828 mixdownPopUp = fAudTrack4MixPopUp;
5829 sampleratePopUp = fAudTrack4RatePopUp;
5830 bitratePopUp = fAudTrack4BitratePopUp;
5831 drcSlider = fAudTrack4DrcSlider;
5832 drcField = fAudTrack4DrcField;
5834 acodec = [[audiocodecPopUp selectedItem] tag];
5835 /* storage variable for the min and max bitrate allowed for this codec */
5841 case HB_ACODEC_FAAC:
5842 /* check if we have a 6ch discrete conversion in either audio track */
5843 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5845 /* FAAC has a minimum of 192 kbps for 6-channel discrete */
5847 /* If either mixdown popup includes 6-channel discrete, then allow up to 768 kbps */
5853 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
5855 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
5860 case HB_ACODEC_CA_AAC:
5861 /* check if we have a 6ch discrete conversion in either audio track */
5862 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5875 case HB_ACODEC_LAME:
5876 /* Lame is happy using our min bitrate of 32 kbps */
5878 /* Lame won't encode if the bitrate is higher than 320 kbps */
5882 case HB_ACODEC_VORBIS:
5883 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5885 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
5887 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
5893 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
5895 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
5901 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
5907 /* make sure we have a selected title before continuing */
5908 if (fTitle == NULL || hb_list_count( fTitle->list_audio ) == 0) return;
5909 /* get the audio so we can find out what input rates are*/
5910 hb_audio_config_t * audio;
5911 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
5912 int inputbitrate = audio->in.bitrate / 1000;
5913 int inputsamplerate = audio->in.samplerate;
5915 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3 && [[mixdownPopUp selectedItem] tag] != HB_ACODEC_DCA)
5917 [bitratePopUp removeAllItems];
5919 for( int i = 0; i < hb_audio_bitrates_count; i++ )
5921 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
5923 /* add a new menuitem for this bitrate */
5924 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5925 [NSString stringWithUTF8String: hb_audio_bitrates[i].string]
5926 action: NULL keyEquivalent: @""];
5927 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
5928 [menuItem setTag: hb_audio_bitrates[i].rate];
5932 /* select the default bitrate (but use 384 for 6-ch AAC) */
5933 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
5935 [bitratePopUp selectItemWithTag: 384];
5939 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
5942 /* populate and set the sample rate popup */
5943 /* Audio samplerate */
5944 [sampleratePopUp removeAllItems];
5945 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
5946 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
5947 [menuItem setTag: inputsamplerate];
5949 for( int i = 0; i < hb_audio_rates_count; i++ )
5951 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
5952 [NSString stringWithUTF8String: hb_audio_rates[i].string]
5953 action: NULL keyEquivalent: @""];
5954 [menuItem setTag: hb_audio_rates[i].rate];
5956 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
5957 * and there is no compelling reason to use anything else as default, though the users default
5958 * preset will likely override any setting chosen here.
5960 [sampleratePopUp selectItemWithTag: inputsamplerate];
5963 /* Since AC3 Pass Thru and DTS Pass Thru uses the input bitrate and sample rate, we get the input tracks
5964 * bitrate and display it in the bitrate popup even though libhb happily ignores any bitrate input from
5965 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
5967 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3 || [[mixdownPopUp selectedItem] tag] == HB_ACODEC_DCA)
5970 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
5971 [bitratePopUp removeAllItems];
5972 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
5973 [NSString stringWithFormat:@"%d", inputbitrate]
5974 action: NULL keyEquivalent: @""];
5975 [menuItem setTag: inputbitrate];
5976 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
5977 [bitratePopUp setEnabled: NO];
5978 [sampleratePopUp setEnabled: NO];
5980 [drcSlider setFloatValue: 0.00];
5981 [self audioDRCSliderChanged: drcSlider];
5982 [drcSlider setEnabled: NO];
5983 [drcField setEnabled: NO];
5987 [sampleratePopUp setEnabled: YES];
5988 [bitratePopUp setEnabled: YES];
5989 [drcSlider setEnabled: YES];
5990 [drcField setEnabled: YES];
5992 [self calculateBitrate:nil];
5995 - (IBAction) audioDRCSliderChanged: (id) sender
5997 NSSlider * drcSlider;
5998 NSTextField * drcField;
5999 if (sender == fAudTrack1DrcSlider)
6001 drcSlider = fAudTrack1DrcSlider;
6002 drcField = fAudTrack1DrcField;
6004 else if (sender == fAudTrack2DrcSlider)
6006 drcSlider = fAudTrack2DrcSlider;
6007 drcField = fAudTrack2DrcField;
6009 else if (sender == fAudTrack3DrcSlider)
6011 drcSlider = fAudTrack3DrcSlider;
6012 drcField = fAudTrack3DrcField;
6016 drcSlider = fAudTrack4DrcSlider;
6017 drcField = fAudTrack4DrcField;
6020 /* If we are between 0.0 and 1.0 on the slider, snap it to 1.0 */
6021 if ([drcSlider floatValue] > 0.0 && [drcSlider floatValue] < 1.0)
6023 [drcSlider setFloatValue:1.0];
6027 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
6028 /* For now, do not call this until we have an intelligent way to determine audio track selections
6029 * compared to presets
6031 //[self customSettingUsed: sender];
6036 - (IBAction) browseImportSrtFile: (id) sender
6039 NSOpenPanel * panel;
6041 panel = [NSOpenPanel openPanel];
6042 [panel setAllowsMultipleSelection: NO];
6043 [panel setCanChooseFiles: YES];
6044 [panel setCanChooseDirectories: NO ];
6045 NSString * sourceDirectory;
6046 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
6048 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
6052 sourceDirectory = @"~/Desktop";
6053 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6055 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
6056 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
6057 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6058 modalForWindow: fWindow modalDelegate: self
6059 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
6060 contextInfo: sender];
6063 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
6064 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6066 if( returnCode == NSOKButton )
6068 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6069 NSString *importSrtFilePath = [sheet filename];
6070 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
6072 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
6073 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
6075 [fSubtitlesTable reloadData];
6081 #pragma mark Open New Windows
6083 - (IBAction) openHomepage: (id) sender
6085 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6086 URLWithString:@"http://handbrake.fr/"]];
6089 - (IBAction) openForums: (id) sender
6091 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6092 URLWithString:@"http://handbrake.fr/forum/"]];
6094 - (IBAction) openUserGuide: (id) sender
6096 [[NSWorkspace sharedWorkspace] openURL: [NSURL
6097 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
6101 * Shows debug output window.
6103 - (IBAction)showDebugOutputPanel:(id)sender
6105 [outputPanel showOutputPanel:sender];
6109 * Shows preferences window.
6111 - (IBAction) showPreferencesWindow: (id) sender
6113 NSWindow * window = [fPreferencesController window];
6114 if (![window isVisible])
6117 [window makeKeyAndOrderFront: nil];
6121 * Shows queue window.
6123 - (IBAction) showQueueWindow:(id)sender
6125 [fQueueController showQueueWindow:sender];
6129 - (IBAction) toggleDrawer:(id)sender {
6130 [fPresetDrawer toggle:self];
6134 * Shows Picture Settings Window.
6137 - (IBAction) showPicturePanel: (id) sender
6139 [fPictureController showPictureWindow:sender];
6142 - (void) picturePanelFullScreen
6144 [fPictureController setToFullScreenMode];
6147 - (void) picturePanelWindowed
6149 [fPictureController setToWindowedMode];
6152 - (IBAction) showPreviewWindow: (id) sender
6154 [fPictureController showPreviewWindow:sender];
6158 #pragma mark Preset Outline View Methods
6159 #pragma mark - Required
6160 /* These are required by the NSOutlineView Datasource Delegate */
6163 /* used to specify the number of levels to show for each item */
6164 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
6166 /* currently use no levels to test outline view viability */
6167 if (item == nil) // for an outline view the root level of the hierarchy is always nil
6169 return [UserPresets count];
6173 /* we need to return the count of the array in ChildrenArray for this folder */
6174 NSArray *children = nil;
6175 children = [item objectForKey:@"ChildrenArray"];
6176 if ([children count] > 0)
6178 return [children count];
6187 /* We use this to deterimine children of an item */
6188 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
6191 /* we need to return the count of the array in ChildrenArray for this folder */
6192 NSArray *children = nil;
6195 children = UserPresets;
6199 if ([item objectForKey:@"ChildrenArray"])
6201 children = [item objectForKey:@"ChildrenArray"];
6204 if ((children == nil) || ( [children count] <= (NSUInteger) index))
6210 return [children objectAtIndex:index];
6214 // We are only one level deep, so we can't be asked about children
6215 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
6219 /* We use this to determine if an item should be expandable */
6220 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
6223 /* we need to return the count of the array in ChildrenArray for this folder */
6224 NSArray *children= nil;
6227 children = UserPresets;
6231 if ([item objectForKey:@"ChildrenArray"])
6233 children = [item objectForKey:@"ChildrenArray"];
6237 /* To deterimine if an item should show a disclosure triangle
6238 * we could do it by the children count as so:
6239 * if ([children count] < 1)
6240 * However, lets leave the triangle show even if there are no
6241 * children to help indicate a folder, just like folder in the
6242 * finder can show a disclosure triangle even when empty
6245 /* We need to determine if the item is a folder */
6246 if ([[item objectForKey:@"Folder"] intValue] == 1)
6257 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
6259 // Our outline view has no levels, but we can still expand every item. Doing so
6260 // just makes the row taller. See heightOfRowByItem below.
6261 //return ![(HBQueueOutlineView*)outlineView isDragging];
6267 /* Used to tell the outline view which information is to be displayed per item */
6268 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6270 /* We have two columns right now, icon and PresetName */
6272 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6274 return [item objectForKey:@"PresetName"];
6283 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
6285 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
6287 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
6289 return [NSKeyedArchiver archivedDataWithRootObject:item];
6292 #pragma mark - Added Functionality (optional)
6293 /* Use to customize the font and display characteristics of the title cell */
6294 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
6296 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6300 NSColor *shadowColor;
6301 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
6302 /*check to see if its a selected row */
6303 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
6306 fontColor = [NSColor blackColor];
6307 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
6311 if ([[item objectForKey:@"Type"] intValue] == 0)
6313 fontColor = [NSColor blueColor];
6315 else // User created preset, use a black font
6317 fontColor = [NSColor blackColor];
6319 /* check to see if its a folder */
6320 //if ([[item objectForKey:@"Folder"] intValue] == 1)
6322 //fontColor = [NSColor greenColor];
6327 /* We use Bold Text for the HB Default */
6328 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
6330 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6332 /* We use Bold Text for the User Specified Default */
6333 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
6335 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
6339 [cell setTextColor:fontColor];
6340 [cell setFont:txtFont];
6345 /* We use this to edit the name field in the outline view */
6346 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
6348 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
6353 [theRecord setObject:object forKey:@"PresetName"];
6357 [fPresetsOutlineView reloadData];
6358 /* We save all of the preset data here */
6362 /* We use this to provide tooltips for the items in the presets outline view */
6363 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
6365 //if ([[tc identifier] isEqualToString:@"PresetName"])
6367 /* initialize the tooltip contents variable */
6369 /* if there is a description for the preset, we show it in the tooltip */
6370 if ([item objectForKey:@"PresetDescription"])
6372 loc_tip = [item objectForKey:@"PresetDescription"];
6377 loc_tip = @"No description available";
6384 #pragma mark Preset Outline View Methods (dragging related)
6387 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
6389 // Dragging is only allowed for custom presets.
6390 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
6391 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
6395 // Don't retain since this is just holding temporaral drag information, and it is
6396 //only used during a drag! We could put this in the pboard actually.
6397 fDraggedNodes = items;
6398 // Provide data for our custom type, and simple NSStrings.
6399 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
6401 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
6402 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
6407 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
6410 // Don't allow dropping ONTO an item since they can't really contain any children.
6412 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
6413 if (isOnDropTypeProposal)
6414 return NSDragOperationNone;
6416 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
6419 index = [fPresetsOutlineView rowForItem: item] + 1;
6423 // Don't allow dropping into the Built In Presets.
6424 if (index < presetCurrentBuiltInCount)
6426 return NSDragOperationNone;
6427 index = MAX (index, presetCurrentBuiltInCount);
6430 [outlineView setDropItem:item dropChildIndex:index];
6431 return NSDragOperationGeneric;
6436 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
6438 /* first, lets see if we are dropping into a folder */
6439 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
6441 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
6442 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
6443 [childrenArray addObject:item];
6444 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
6445 [childrenArray autorelease];
6447 else // We are not, so we just move the preset into the existing array
6449 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
6451 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
6452 while (obj = [enumerator nextObject])
6454 [moveItems addIndex:[UserPresets indexOfObject:obj]];
6456 // Successful drop, lets rearrange the view and save it all
6457 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
6459 [fPresetsOutlineView reloadData];
6464 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
6466 NSUInteger index = [indexSet lastIndex];
6467 NSUInteger aboveInsertIndexCount = 0;
6469 NSUInteger removeIndex;
6471 if (index >= insertIndex)
6473 removeIndex = index + aboveInsertIndexCount;
6474 aboveInsertIndexCount++;
6478 removeIndex = index;
6482 id object = [[array objectAtIndex:removeIndex] retain];
6483 [array removeObjectAtIndex:removeIndex];
6484 [array insertObject:object atIndex:insertIndex];
6487 index = [indexSet indexLessThanIndex:index];
6492 #pragma mark - Functional Preset NSOutlineView Methods
6494 - (IBAction)selectPreset:(id)sender
6497 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
6499 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6500 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6502 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
6504 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
6508 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
6512 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
6513 [self formatPopUpChanged:nil];
6515 /* Chapter Markers*/
6516 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
6517 /* check to see if we have only one chapter */
6518 [self chapterPopUpChanged:nil];
6520 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6521 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
6522 /* Mux mp4 with http optimization */
6523 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
6526 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
6527 /* We set the advanced opt string here if applicable*/
6528 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
6530 /* Lets run through the following functions to get variables set there */
6531 [self videoEncoderPopUpChanged:nil];
6532 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
6533 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
6534 [self calculateBitrate:nil];
6537 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
6539 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
6540 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
6542 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
6543 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
6544 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
6545 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
6546 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
6547 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
6549 /* For the quality slider we need to convert the old percent's to the new rf scales */
6550 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
6551 [fVidQualitySlider setFloatValue:rf];
6556 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
6557 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
6559 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6563 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
6564 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
6568 [self videoMatrixChanged:nil];
6570 /* Video framerate */
6571 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
6572 detected framerate in the fVidRatePopUp so we use index 0*/
6573 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
6575 [fVidRatePopUp selectItemAtIndex: 0];
6579 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
6582 [fFrameratePfrCheck setState:[[chosenPreset objectForKey:@"VideoFrameratePFR"] intValue]];
6583 [self videoFrameRateChanged:nil];
6585 /* 2 Pass Encoding */
6586 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
6587 [self twoPassCheckboxChanged:nil];
6589 /* Turbo 1st pass for 2 Pass Encoding */
6590 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
6593 /* First we check to see if we are using the current audio track layout based on AudioList array */
6594 if ([chosenPreset objectForKey:@"AudioList"])
6597 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
6598 NSPopUpButton * trackLangPreviousPopUp = nil;
6599 NSPopUpButton * trackLangPopUp = nil;
6600 NSPopUpButton * mixdownPopUp = nil;
6601 NSPopUpButton * audiocodecPopUp = nil;
6602 NSPopUpButton * sampleratePopUp = nil;
6603 NSPopUpButton * bitratePopUp = nil;
6604 NSSlider * drcSlider = nil;
6607 /* Populate the audio widgets based on the contents of the AudioList array */
6609 NSEnumerator *enumerator = [[chosenPreset objectForKey:@"AudioList"] objectEnumerator];
6611 while (tempObject = [enumerator nextObject])
6616 trackLangPopUp = fAudLang1PopUp;
6617 mixdownPopUp = fAudTrack1MixPopUp;
6618 audiocodecPopUp = fAudTrack1CodecPopUp;
6619 sampleratePopUp = fAudTrack1RatePopUp;
6620 bitratePopUp = fAudTrack1BitratePopUp;
6621 drcSlider = fAudTrack1DrcSlider;
6625 trackLangPreviousPopUp = fAudLang1PopUp;
6626 trackLangPopUp = fAudLang2PopUp;
6627 mixdownPopUp = fAudTrack2MixPopUp;
6628 audiocodecPopUp = fAudTrack2CodecPopUp;
6629 sampleratePopUp = fAudTrack2RatePopUp;
6630 bitratePopUp = fAudTrack2BitratePopUp;
6631 drcSlider = fAudTrack2DrcSlider;
6635 trackLangPreviousPopUp = fAudLang2PopUp;
6636 trackLangPopUp = fAudLang3PopUp;
6637 mixdownPopUp = fAudTrack3MixPopUp;
6638 audiocodecPopUp = fAudTrack3CodecPopUp;
6639 sampleratePopUp = fAudTrack3RatePopUp;
6640 bitratePopUp = fAudTrack3BitratePopUp;
6641 drcSlider = fAudTrack3DrcSlider;
6645 trackLangPreviousPopUp = fAudLang3PopUp;
6646 trackLangPopUp = fAudLang4PopUp;
6647 mixdownPopUp = fAudTrack4MixPopUp;
6648 audiocodecPopUp = fAudTrack4CodecPopUp;
6649 sampleratePopUp = fAudTrack4RatePopUp;
6650 bitratePopUp = fAudTrack4BitratePopUp;
6651 drcSlider = fAudTrack4DrcSlider;
6655 if ([trackLangPopUp indexOfSelectedItem] == 0)
6659 [trackLangPopUp selectItemAtIndex: 1];
6663 /* if we are greater than track 1, select
6664 * the same track as the previous track */
6665 [trackLangPopUp selectItemAtIndex: [trackLangPreviousPopUp indexOfSelectedItem]];
6668 [self audioTrackPopUpChanged: trackLangPopUp];
6669 [audiocodecPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioEncoder"]];
6670 /* check our pref for core audio and use it in place of faac if preset is a built in */
6671 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6672 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6673 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString: @"AAC (faac)"])
6675 [audiocodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6678 [self audioTrackPopUpChanged: audiocodecPopUp];
6679 [mixdownPopUp selectItemWithTitle:[tempObject objectForKey:@"AudioMixdown"]];
6680 [self audioTrackMixdownChanged: mixdownPopUp];
6681 /* check to see if the selection was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6683 if ([mixdownPopUp selectedItem] == nil)
6685 [self audioTrackPopUpChanged: audiocodecPopUp];
6686 [self writeToActivityLog: "presetSelected mixdown not selected, rerun audioTrackPopUpChanged"];
6688 [sampleratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioSamplerate"]];
6689 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6690 if (![[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6692 [bitratePopUp selectItemWithTitle:[tempObject objectForKey:@"AudioBitrate"]];
6693 /* check to see if the bitrate selection was available, if not, rerun audioTrackMixdownChanged using the mixdown to just set the
6694 *default mixdown bitrate*/
6695 if ([bitratePopUp selectedItem] == nil)
6697 [self audioTrackMixdownChanged: mixdownPopUp];
6700 [drcSlider setFloatValue:[[tempObject objectForKey:@"AudioTrackDRCSlider"] floatValue]];
6701 [self audioDRCSliderChanged: drcSlider];
6704 /* 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,
6705 * if not we will set the track to "None". Track 1 is allowed to mixdown to a suitable DPL2 mix if we cannot passthru */
6709 /* 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". */
6710 if (([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] || [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"]) && [trackLangPopUp indexOfSelectedItem] != 0)
6712 hb_audio_config_t * audio;
6713 /* get the audio source audio codec */
6714 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [trackLangPopUp indexOfSelectedItem] - 1 );
6715 if (audio != NULL && [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"] && audio->in.codec != HB_ACODEC_AC3 ||
6716 [[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"] && audio->in.codec != HB_ACODEC_DCA )
6718 /* We have a preset using ac3 passthru but no ac3 source audio, so set the track to "None" and bail */
6719 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"AC3 Passthru"])
6721 [self writeToActivityLog: "Preset calls for AC3 Pass thru ..."];
6723 if ([[tempObject objectForKey:@"AudioEncoder"] isEqualToString:@"DTS Passthru"])
6725 [self writeToActivityLog: "Preset calls for DTS Pass thru ..."];
6727 [self writeToActivityLog: "No matching source codec, setting track %d to None", i];
6728 [trackLangPopUp selectItemAtIndex: 0];
6729 [self audioTrackPopUpChanged: trackLangPopUp];
6735 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6739 [fAudLang4PopUp selectItemAtIndex: 0];
6740 [self audioTrackPopUpChanged: fAudLang4PopUp];
6744 [fAudLang3PopUp selectItemAtIndex: 0];
6745 [self audioTrackPopUpChanged: fAudLang3PopUp];
6749 [fAudLang2PopUp selectItemAtIndex: 0];
6750 [self audioTrackPopUpChanged: fAudLang2PopUp];
6758 if ([chosenPreset objectForKey:@"Audio1Track"] > 0)
6760 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
6762 [fAudLang1PopUp selectItemAtIndex: 1];
6764 [self audioTrackPopUpChanged: fAudLang1PopUp];
6765 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Encoder"]];
6766 /* check our pref for core audio and use it in place of faac if preset is built in */
6767 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6768 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6769 [[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString: @"AAC (faac)"])
6771 [fAudTrack1CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6774 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6775 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Mixdown"]];
6776 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6778 if ([fAudTrack1MixPopUp selectedItem] == nil)
6780 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
6782 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Samplerate"]];
6783 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6784 if (![[chosenPreset objectForKey:@"Audio1Encoder"] isEqualToString:@"AC3 Passthru"])
6786 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio1Bitrate"]];
6788 [fAudTrack1DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio1TrackDRCSlider"] floatValue]];
6789 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
6792 if ([chosenPreset objectForKey:@"Audio2Track"] > 0)
6794 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
6796 [fAudLang2PopUp selectItemAtIndex: 1];
6798 [self audioTrackPopUpChanged: fAudLang2PopUp];
6799 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Encoder"]];
6800 /* check our pref for core audio and use it in place of faac if preset is built in */
6801 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6802 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6803 [[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString: @"AAC (faac)"])
6805 [fAudTrack2CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6807 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6808 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Mixdown"]];
6809 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6811 if ([fAudTrack2MixPopUp selectedItem] == nil)
6813 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
6815 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Samplerate"]];
6816 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6817 if (![[chosenPreset objectForKey:@"Audio2Encoder"] isEqualToString:@"AC3 Passthru"])
6819 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio2Bitrate"]];
6821 [fAudTrack2DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio2TrackDRCSlider"] floatValue]];
6822 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
6824 if ([chosenPreset objectForKey:@"Audio3Track"] > 0)
6826 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
6828 [fAudLang3PopUp selectItemAtIndex: 1];
6830 [self audioTrackPopUpChanged: fAudLang3PopUp];
6831 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Encoder"]];
6832 /* check our pref for core audio and use it in place of faac if preset is built in */
6833 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6834 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6835 [[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AAC (faac)"])
6837 [fAudTrack3CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6839 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6840 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Mixdown"]];
6841 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6843 if ([fAudTrack3MixPopUp selectedItem] == nil)
6845 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
6847 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Samplerate"]];
6848 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6849 if (![[chosenPreset objectForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
6851 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio3Bitrate"]];
6853 [fAudTrack3DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio3TrackDRCSlider"] floatValue]];
6854 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
6856 if ([chosenPreset objectForKey:@"Audio4Track"] > 0)
6858 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
6860 [fAudLang4PopUp selectItemAtIndex: 1];
6862 [self audioTrackPopUpChanged: fAudLang4PopUp];
6863 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Encoder"]];
6864 /* check our pref for core audio and use it in place of faac if preset is built in */
6865 if ([[chosenPreset objectForKey:@"Type"] intValue] == 0 &&
6866 [[NSUserDefaults standardUserDefaults] boolForKey: @"UseCoreAudio"] == YES &&
6867 [[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString: @"AAC (faac)"])
6869 [fAudTrack4CodecPopUp selectItemWithTitle:@"AAC (CoreAudio)"];
6871 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6872 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Mixdown"]];
6873 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
6875 if ([fAudTrack4MixPopUp selectedItem] == nil)
6877 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
6879 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Samplerate"]];
6880 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
6881 if (![[chosenPreset objectForKey:@"Audio4Encoder"] isEqualToString:@"AC3 Passthru"])
6883 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset objectForKey:@"Audio4Bitrate"]];
6885 [fAudTrack4DrcSlider setFloatValue:[[chosenPreset objectForKey:@"Audio4TrackDRCSlider"] floatValue]];
6886 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
6889 /* We now cleanup any extra audio tracks that may have been previously set if we need to */
6891 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset objectForKey:@"Audio2Track"] == 0)
6893 [fAudLang2PopUp selectItemAtIndex: 0];
6894 [self audioTrackPopUpChanged: fAudLang2PopUp];
6896 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset objectForKey:@"Audio3Track"] > 0)
6898 [fAudLang3PopUp selectItemAtIndex: 0];
6899 [self audioTrackPopUpChanged: fAudLang3PopUp];
6901 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset objectForKey:@"Audio4Track"] > 0)
6903 [fAudLang4PopUp selectItemAtIndex: 0];
6904 [self audioTrackPopUpChanged: fAudLang4PopUp];
6909 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
6910 /* Forced Subtitles */
6911 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
6913 /* Picture Settings */
6914 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
6915 * height, width, keep ar, anamorphic and crop settings.
6916 * picture filters are handled separately below.
6918 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
6919 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
6920 * preset completely ignores any picture sizing values in the preset.
6922 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
6924 hb_job_t * job = fTitle->job;
6926 /* If Cropping is set to custom, then recall all four crop values from
6927 when the preset was created and apply them */
6928 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
6930 [fPictureController setAutoCrop:NO];
6932 /* Here we use the custom crop values saved at the time the preset was saved */
6933 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
6934 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
6935 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
6936 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
6939 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
6941 [fPictureController setAutoCrop:YES];
6942 /* Here we use the auto crop values determined right after scan */
6943 job->crop[0] = AutoCropTop;
6944 job->crop[1] = AutoCropBottom;
6945 job->crop[2] = AutoCropLeft;
6946 job->crop[3] = AutoCropRight;
6951 if ([chosenPreset objectForKey:@"PictureModulus"])
6953 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
6960 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
6961 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
6963 /* Use Max Picture settings for whatever the dvd is.*/
6964 [self revertPictureSizeToMax:nil];
6965 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6966 if (job->keep_ratio == 1)
6968 hb_fix_aspect( job, HB_KEEP_WIDTH );
6969 if( job->height > fTitle->height )
6971 job->height = fTitle->height;
6972 hb_fix_aspect( job, HB_KEEP_HEIGHT );
6975 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
6977 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
6979 /* we check to make sure the presets width/height does not exceed the sources width/height */
6980 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
6982 /* if so, then we use the sources height and width to avoid scaling up */
6983 //job->width = fTitle->width;
6984 //job->height = fTitle->height;
6985 [self revertPictureSizeToMax:nil];
6987 else // source width/height is >= the preset height/width
6989 /* we can go ahead and use the presets values for height and width */
6990 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
6991 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
6993 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
6994 if (job->keep_ratio == 1)
6996 hb_fix_aspect( job, HB_KEEP_WIDTH );
6997 if( job->height > fTitle->height )
6999 job->height = fTitle->height;
7000 hb_fix_aspect( job, HB_KEEP_HEIGHT );
7003 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
7009 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
7010 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
7014 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
7015 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
7016 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
7019 [fPictureController setUseDecomb:1];
7020 [fPictureController setDecomb:0];
7021 [fPictureController setDeinterlace:0];
7022 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7024 /* we are using decomb */
7026 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
7028 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
7030 /* if we are using "Custom" in the decomb setting, also set the custom string*/
7031 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
7033 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
7039 /* We are using Deinterlace */
7041 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
7043 [fPictureController setUseDecomb:0];
7044 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
7045 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
7046 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
7048 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
7055 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
7057 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
7058 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
7059 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
7061 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
7066 [fPictureController setDetelecine:0];
7070 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
7072 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
7073 /* if we are using "Custom" in the denoise setting, also set the custom string*/
7074 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
7076 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
7081 [fPictureController setDenoise:0];
7085 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
7087 /* if its a one, then its the old on/off deblock, set on to 5*/
7088 [fPictureController setDeblock:5];
7092 /* use the settings intValue */
7093 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
7096 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
7098 [fPictureController setGrayscale:1];
7102 [fPictureController setGrayscale:0];
7105 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
7106 [fPictureController SetTitle:fTitle];
7107 [fPictureController SetTitle:fTitle];
7108 [self calculatePictureSizing:nil];
7114 #pragma mark Manage Presets
7116 - (void) loadPresets {
7117 /* We declare the default NSFileManager into fileManager */
7118 NSFileManager * fileManager = [NSFileManager defaultManager];
7119 /*We define the location of the user presets file */
7120 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
7121 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
7122 /* We check for the presets.plist */
7123 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
7125 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
7128 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
7129 if (nil == UserPresets)
7131 UserPresets = [[NSMutableArray alloc] init];
7132 [self addFactoryPresets:nil];
7134 [fPresetsOutlineView reloadData];
7136 [self checkBuiltInsForUpdates];
7139 - (void) checkBuiltInsForUpdates {
7141 BOOL updateBuiltInPresets = NO;
7143 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7145 while (tempObject = [enumerator nextObject])
7147 /* iterate through the built in presets to see if any have an old build number */
7148 NSMutableDictionary *thisPresetDict = tempObject;
7149 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
7150 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
7152 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
7154 updateBuiltInPresets = YES;
7159 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
7160 if ( updateBuiltInPresets == YES)
7162 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
7164 /* Show an alert window that built in presets will be updated */
7165 /*On Screen Notification*/
7168 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
7169 [NSApp requestUserAttention:NSCriticalRequest];
7171 /* when alert is dismissed, go ahead and update the built in presets */
7172 [self addFactoryPresets:nil];
7178 - (IBAction) showAddPresetPanel: (id) sender
7180 /* Deselect the currently selected Preset if there is one*/
7181 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
7183 /* Populate the preset picture settings popup here */
7184 [fPresetNewPicSettingsPopUp removeAllItems];
7185 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
7186 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
7187 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
7188 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
7189 /* Uncheck the preset use filters checkbox */
7190 [fPresetNewPicFiltersCheck setState:NSOffState];
7191 // fPresetNewFolderCheck
7192 [fPresetNewFolderCheck setState:NSOffState];
7193 /* Erase info from the input fields*/
7194 [fPresetNewName setStringValue: @""];
7195 [fPresetNewDesc setStringValue: @""];
7196 /* Show the panel */
7197 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
7200 - (IBAction) closeAddPresetPanel: (id) sender
7202 [NSApp endSheet: fAddPresetPanel];
7203 [fAddPresetPanel orderOut: self];
7206 - (IBAction)addUserPreset:(id)sender
7208 if (![[fPresetNewName stringValue] length])
7209 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
7212 /* Here we create a custom user preset */
7213 [UserPresets addObject:[self createPreset]];
7216 [self closeAddPresetPanel:nil];
7223 /* We Reload the New Table data for presets */
7224 [fPresetsOutlineView reloadData];
7225 /* We save all of the preset data here */
7233 /* We Sort the Presets By Factory or Custom */
7234 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
7235 ascending:YES] autorelease];
7236 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
7238 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
7239 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
7240 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
7243 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
7244 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
7245 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
7246 [UserPresets setArray:sortedArray];
7251 - (IBAction)insertPreset:(id)sender
7253 int index = [fPresetsOutlineView selectedRow];
7254 [UserPresets insertObject:[self createPreset] atIndex:index];
7255 [fPresetsOutlineView reloadData];
7259 - (NSDictionary *)createPreset
7261 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
7262 /* Preset build number */
7263 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7264 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7265 /* Get the New Preset Name from the field in the AddPresetPanel */
7266 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
7267 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
7268 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
7269 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
7270 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
7271 /*Set whether or not this is default, at creation set to 0*/
7272 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7273 if ([fPresetNewFolderCheck state] == YES)
7275 /* initialize and set an empty array for children here since we are a new folder */
7276 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
7277 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
7278 [childrenArray autorelease];
7280 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
7282 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
7283 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
7284 /* Get whether or not to use the current Picture Filter settings for the preset */
7285 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
7287 /* Get New Preset Description from the field in the AddPresetPanel*/
7288 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
7290 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
7291 /* Chapter Markers fCreateChapterMarkers*/
7292 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
7293 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
7294 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
7295 /* Mux mp4 with http optimization */
7296 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
7297 /* Add iPod uuid atom */
7298 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
7302 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
7303 /* x264 Option String */
7304 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
7306 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
7307 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
7308 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
7309 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
7311 /* Video framerate */
7312 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
7314 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
7316 else // we can record the actual titleOfSelectedItem
7318 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
7320 [preset setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
7322 /* 2 Pass Encoding */
7323 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
7324 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
7325 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
7326 /*Picture Settings*/
7327 hb_job_t * job = fTitle->job;
7328 /* Picture Sizing */
7329 /* Use Max Picture settings for whatever the dvd is.*/
7330 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
7331 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
7332 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
7333 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
7334 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
7335 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
7337 /* Set crop settings here */
7338 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
7339 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
7340 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
7341 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
7342 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
7344 /* Picture Filters */
7345 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
7346 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
7347 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
7348 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
7349 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
7350 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
7351 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
7352 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
7353 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
7354 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
7355 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
7358 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
7359 /* we actually call the methods for the nests here */
7360 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
7362 NSMutableDictionary *audioTrack1Array = [[NSMutableDictionary alloc] init];
7363 [audioTrack1Array setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7364 [audioTrack1Array setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7365 [audioTrack1Array setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7366 [audioTrack1Array setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7367 [audioTrack1Array setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7368 [audioTrack1Array setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7369 [audioTrack1Array setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7370 [audioTrack1Array autorelease];
7371 [audioListArray addObject:audioTrack1Array];
7374 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
7376 NSMutableDictionary *audioTrack2Array = [[NSMutableDictionary alloc] init];
7377 [audioTrack2Array setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7378 [audioTrack2Array setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7379 [audioTrack2Array setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7380 [audioTrack2Array setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7381 [audioTrack2Array setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7382 [audioTrack2Array setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7383 [audioTrack2Array setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7384 [audioTrack2Array autorelease];
7385 [audioListArray addObject:audioTrack2Array];
7388 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
7390 NSMutableDictionary *audioTrack3Array = [[NSMutableDictionary alloc] init];
7391 [audioTrack3Array setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7392 [audioTrack3Array setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7393 [audioTrack3Array setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7394 [audioTrack3Array setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7395 [audioTrack3Array setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7396 [audioTrack3Array setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7397 [audioTrack3Array setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7398 [audioTrack3Array autorelease];
7399 [audioListArray addObject:audioTrack3Array];
7402 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
7404 NSMutableDictionary *audioTrack4Array = [[NSMutableDictionary alloc] init];
7405 [audioTrack4Array setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"AudioTrack"];
7406 [audioTrack4Array setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"AudioTrackDescription"];
7407 [audioTrack4Array setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"AudioEncoder"];
7408 [audioTrack4Array setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"AudioMixdown"];
7409 [audioTrack4Array setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"AudioSamplerate"];
7410 [audioTrack4Array setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"AudioBitrate"];
7411 [audioTrack4Array setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"AudioTrackDRCSlider"];
7412 [audioTrack4Array autorelease];
7413 [audioListArray addObject:audioTrack4Array];
7417 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
7420 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
7421 * subititle array code. */
7423 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
7424 /* Forced Subtitles */
7425 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
7427 [preset autorelease];
7434 [UserPresets writeToFile:UserPresetsFile atomically:YES];
7435 /* We get the default preset in case it changed */
7436 [self getDefaultPresets:nil];
7440 - (IBAction)deletePreset:(id)sender
7444 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
7448 /* Alert user before deleting preset */
7450 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
7452 if ( status == NSAlertDefaultReturn )
7454 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7455 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7456 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7458 NSEnumerator *enumerator;
7459 NSMutableArray *presetsArrayToMod;
7460 NSMutableArray *tempArray;
7462 /* If we are a root level preset, we are modding the UserPresets array */
7463 if (presetToModLevel == 0)
7465 presetsArrayToMod = UserPresets;
7467 else // We have a parent preset, so we modify the chidren array object for key
7469 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7472 enumerator = [presetsArrayToMod objectEnumerator];
7473 tempArray = [NSMutableArray array];
7475 while (tempObject = [enumerator nextObject])
7477 NSDictionary *thisPresetDict = tempObject;
7478 if (thisPresetDict == presetToMod)
7480 [tempArray addObject:tempObject];
7484 [presetsArrayToMod removeObjectsInArray:tempArray];
7485 [fPresetsOutlineView reloadData];
7492 #pragma mark Import Export Preset(s)
7494 - (IBAction) browseExportPresetFile: (id) sender
7496 /* Open a panel to let the user choose where and how to save the export file */
7497 NSSavePanel * panel = [NSSavePanel savePanel];
7498 /* We get the current file name and path from the destination field here */
7499 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
7501 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
7502 modalForWindow: fWindow modalDelegate: self
7503 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
7507 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
7508 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7510 if( returnCode == NSOKButton )
7512 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7513 NSString *exportPresetsFile = [sheet filename];
7514 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
7515 /* We check for the presets.plist */
7516 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
7518 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
7520 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
7521 if (nil == presetsToExport)
7523 presetsToExport = [[NSMutableArray alloc] init];
7525 /* now get and add selected presets to export */
7528 if ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1)
7530 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7531 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
7539 - (IBAction) browseImportPresetFile: (id) sender
7542 NSOpenPanel * panel;
7544 panel = [NSOpenPanel openPanel];
7545 [panel setAllowsMultipleSelection: NO];
7546 [panel setCanChooseFiles: YES];
7547 [panel setCanChooseDirectories: NO ];
7548 NSString * sourceDirectory;
7549 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
7551 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
7555 sourceDirectory = @"~/Desktop";
7556 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
7558 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
7559 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
7561 /* set this for allowed file types, not sure if we should allow xml or not */
7562 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
7563 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
7564 modalForWindow: fWindow modalDelegate: self
7565 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
7566 contextInfo: sender];
7569 - (void) browseImportPresetDone: (NSSavePanel *) sheet
7570 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7572 if( returnCode == NSOKButton )
7574 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
7575 NSString *importPresetsFile = [sheet filename];
7576 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
7577 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
7578 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
7579 /* iterate though the new array of presets to import and add them to our presets array */
7581 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
7583 while (tempObject = [enumerator nextObject])
7585 /* make any changes to the incoming preset we see fit */
7586 /* make sure the incoming preset is not tagged as default */
7587 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7588 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
7589 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
7590 [tempObject setObject:prependedName forKey:@"PresetName"];
7592 /* actually add the new preset to our presets array */
7593 [UserPresets addObject:tempObject];
7596 [presetsToImport autorelease];
7604 #pragma mark Manage Default Preset
7606 - (IBAction)getDefaultPresets:(id)sender
7608 presetHbDefault = nil;
7609 presetUserDefault = nil;
7610 presetUserDefaultParent = nil;
7611 presetUserDefaultParentParent = nil;
7612 NSMutableDictionary *presetHbDefaultParent = nil;
7613 NSMutableDictionary *presetHbDefaultParentParent = nil;
7616 BOOL userDefaultFound = NO;
7617 presetCurrentBuiltInCount = 0;
7618 /* First we iterate through the root UserPresets array to check for defaults */
7619 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7621 while (tempObject = [enumerator nextObject])
7623 NSMutableDictionary *thisPresetDict = tempObject;
7624 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7626 presetHbDefault = thisPresetDict;
7628 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7630 presetUserDefault = thisPresetDict;
7631 userDefaultFound = YES;
7633 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7635 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
7639 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7640 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7642 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
7643 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7645 while (tempObject = [enumerator nextObject])
7647 NSMutableDictionary *thisPresetDict = tempObject;
7648 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7650 presetHbDefault = thisPresetDict;
7651 presetHbDefaultParent = thisPresetDictParent;
7653 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7655 presetUserDefault = thisPresetDict;
7656 presetUserDefaultParent = thisPresetDictParent;
7657 userDefaultFound = YES;
7660 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7661 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7663 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
7664 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7666 while (tempObject = [enumerator nextObject])
7668 NSMutableDictionary *thisPresetDict = tempObject;
7669 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
7671 presetHbDefault = thisPresetDict;
7672 presetHbDefaultParent = thisPresetDictParent;
7673 presetHbDefaultParentParent = thisPresetDictParentParent;
7675 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
7677 presetUserDefault = thisPresetDict;
7678 presetUserDefaultParent = thisPresetDictParent;
7679 presetUserDefaultParentParent = thisPresetDictParentParent;
7680 userDefaultFound = YES;
7689 /* check to see if a user specified preset was found, if not then assign the parents for
7690 * the presetHbDefault so that we can open the parents for the nested presets
7692 if (userDefaultFound == NO)
7694 presetUserDefaultParent = presetHbDefaultParent;
7695 presetUserDefaultParentParent = presetHbDefaultParentParent;
7699 - (IBAction)setDefaultPreset:(id)sender
7701 /* We need to determine if the item is a folder */
7702 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
7708 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7710 /* First make sure the old user specified default preset is removed */
7711 while (tempObject = [enumerator nextObject])
7713 NSMutableDictionary *thisPresetDict = tempObject;
7714 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7716 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7719 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
7720 if ([thisPresetDict objectForKey:@"ChildrenArray"])
7722 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
7725 while (tempObject = [enumerator nextObject])
7727 NSMutableDictionary *thisPresetDict1 = tempObject;
7728 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7730 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7732 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
7733 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
7735 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
7738 while (tempObject = [enumerator nextObject])
7740 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
7742 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
7755 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
7756 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
7757 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
7760 NSMutableArray *presetsArrayToMod;
7761 NSMutableArray *tempArray;
7763 /* If we are a root level preset, we are modding the UserPresets array */
7764 if (presetToModLevel == 0)
7766 presetsArrayToMod = UserPresets;
7768 else // We have a parent preset, so we modify the chidren array object for key
7770 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
7773 enumerator = [presetsArrayToMod objectEnumerator];
7774 tempArray = [NSMutableArray array];
7776 while (tempObject = [enumerator nextObject])
7778 NSDictionary *thisPresetDict = tempObject;
7779 if (thisPresetDict == presetToMod)
7781 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
7783 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
7790 /* We save all of the preset data here */
7792 /* We Reload the New Table data for presets */
7793 [fPresetsOutlineView reloadData];
7796 - (IBAction)selectDefaultPreset:(id)sender
7798 NSMutableDictionary *presetToMod;
7799 /* if there is a user specified default, we use it */
7800 if (presetUserDefault)
7802 presetToMod = presetUserDefault;
7804 else if (presetHbDefault) //else we use the built in default presetHbDefault
7806 presetToMod = presetHbDefault;
7813 if (presetUserDefaultParent != nil)
7815 [fPresetsOutlineView expandItem:presetUserDefaultParent];
7818 if (presetUserDefaultParentParent != nil)
7820 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
7824 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
7825 [self selectPreset:nil];
7830 #pragma mark Manage Built In Presets
7833 - (IBAction)deleteFactoryPresets:(id)sender
7836 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7840 NSMutableArray *tempArray;
7843 tempArray = [NSMutableArray array];
7844 /* we look here to see if the preset is we move on to the next one */
7845 while ( tempObject = [enumerator nextObject] )
7847 /* if the preset is "Factory" then we put it in the array of
7848 presets to delete */
7849 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
7851 [tempArray addObject:tempObject];
7855 [UserPresets removeObjectsInArray:tempArray];
7856 [fPresetsOutlineView reloadData];
7861 /* We use this method to recreate new, updated factory presets */
7862 - (IBAction)addFactoryPresets:(id)sender
7865 /* First, we delete any existing built in presets */
7866 [self deleteFactoryPresets: sender];
7867 /* Then we generate new built in presets programmatically with fPresetsBuiltin
7868 * which is all setup in HBPresets.h and HBPresets.m*/
7869 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
7870 /* update build number for built in presets */
7871 /* iterate though the new array of presets to import and add them to our presets array */
7873 NSEnumerator *enumerator = [UserPresets objectEnumerator];
7875 while (tempObject = [enumerator nextObject])
7877 /* Record the apps current build number in the PresetBuildNumber key */
7878 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
7880 /* Preset build number */
7881 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
7885 /* report the built in preset updating to the activity log */
7886 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
7894 #pragma mark Chapter Files Import / Export
7896 - (IBAction) browseForChapterFile: (id) sender
7898 /* Open a panel to let the user choose the file */
7899 NSOpenPanel * panel = [NSOpenPanel openPanel];
7900 /* We get the current file name and path from the destination field here */
7901 [panel beginSheetForDirectory: [NSString stringWithFormat:@"%@/",
7902 [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"]]
7904 types: [NSArray arrayWithObjects:@"csv",nil]
7905 modalForWindow: fWindow modalDelegate: self
7906 didEndSelector: @selector( browseForChapterFileDone:returnCode:contextInfo: )
7910 - (void) browseForChapterFileDone: (NSOpenPanel *) sheet
7911 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7913 NSArray *chaptersArray; /* temp array for chapters */
7914 NSMutableArray *chaptersMutableArray; /* temp array for chapters */
7915 NSString *chapterName; /* temp string from file */
7918 if( returnCode == NSOKButton ) /* if they click OK */
7920 chapterName = [[NSString alloc] initWithContentsOfFile:[sheet filename] encoding:NSUTF8StringEncoding error:NULL];
7921 chaptersArray = [chapterName componentsSeparatedByString:@"\n"];
7922 chaptersMutableArray= [chaptersArray mutableCopy];
7923 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
7924 if ([chaptersMutableArray count] > 0)
7926 /* if last item is empty remove it */
7927 if ([[chaptersMutableArray objectAtIndex:[chaptersArray count]-1] length] == 0)
7929 [chaptersMutableArray removeLastObject];
7932 /* if chapters in table is not equal to array count */
7933 if ((unsigned int) chapters != [chaptersMutableArray count])
7936 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
7937 defaultButton:NSLocalizedString(@"OK", @"OK")
7938 alternateButton:NULL
7940 informativeTextWithFormat:NSLocalizedString(@"%d chapters expected, %d chapters found in %@", @"%d chapters expected, %d chapters found in %@"),
7941 chapters, [chaptersMutableArray count], [[sheet filename] lastPathComponent]] runModal];
7944 /* otherwise, go ahead and populate table with array */
7945 for (i=0; i<chapters; i++)
7948 if([[chaptersMutableArray objectAtIndex:i] length] > 5)
7950 /* avoid a segfault */
7951 /* Get the Range.location of the first comma in the line and then put everything after that into chapterTitle */
7952 NSRange firstCommaRange = [[chaptersMutableArray objectAtIndex:i] rangeOfString:@","];
7953 NSString *chapterTitle = [[chaptersMutableArray objectAtIndex:i] substringFromIndex:firstCommaRange.location + 1];
7954 /* Since we store our chapterTitle commas as "\," for the cli, we now need to remove the escaping "\" from the title */
7955 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"\\," withString:@","];
7956 [fChapterTitlesDelegate tableView:fChapterTable
7957 setObjectValue:chapterTitle
7958 forTableColumn:fChapterTableNameColumn
7964 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
7965 defaultButton:NSLocalizedString(@"OK", @"OK")
7966 alternateButton:NULL
7968 informativeTextWithFormat:NSLocalizedString(@"%@ was not formatted as expected.", @"%@ was not formatted as expected."), [[sheet filename] lastPathComponent]] runModal];
7969 [fChapterTable reloadData];
7973 [fChapterTable reloadData];
7977 - (IBAction) browseForChapterFileSave: (id) sender
7979 NSSavePanel *panel = [NSSavePanel savePanel];
7980 /* Open a panel to let the user save to a file */
7981 [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv",nil]];
7982 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent]
7983 file: [[[[fDstFile2Field stringValue] lastPathComponent] stringByDeletingPathExtension]
7984 stringByAppendingString:@"-chapters.csv"]
7985 modalForWindow: fWindow
7987 didEndSelector: @selector( browseForChapterFileSaveDone:returnCode:contextInfo: )
7991 - (void) browseForChapterFileSaveDone: (NSSavePanel *) sheet
7992 returnCode: (int) returnCode contextInfo: (void *) contextInfo
7994 NSString *chapterName; /* pointer for string for later file-writing */
7995 NSString *chapterTitle;
7996 NSError *saveError = [[NSError alloc] init];
7997 int chapters, i; /* ints for the number of chapters in the table and the loop */
7999 if( returnCode == NSOKButton ) /* if they clicked OK */
8001 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
8002 chapterName = [NSString string];
8003 for (i=0; i<chapters; i++)
8005 /* put each chapter title from the table into the array */
8007 { /* if i is from 0 to 8 (chapters 1 to 9) add two leading zeros */
8008 chapterName = [chapterName stringByAppendingFormat:@"00%d,",i+1];
8011 { /* if i is from 9 to 98 (chapters 10 to 99) add one leading zero */
8012 chapterName = [chapterName stringByAppendingFormat:@"0%d,",i+1];
8015 { /* in case i is from 99 to 998 (chapters 100 to 999) no leading zeros */
8016 chapterName = [chapterName stringByAppendingFormat:@"%d,",i+1];
8019 chapterTitle = [fChapterTitlesDelegate tableView:fChapterTable objectValueForTableColumn:fChapterTableNameColumn row:i];
8020 /* escape any commas in the chapter name with "\," */
8021 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"," withString:@"\\,"];
8022 chapterName = [chapterName stringByAppendingString:chapterTitle];
8023 if (i+1 != chapters)
8024 { /* if not the last chapter */
8025 chapterName = [chapterName stringByAppendingString:@ "\n"];
8030 /* try to write it to where the user wanted */
8031 if (![chapterName writeToFile:[sheet filename]
8033 encoding:NSUTF8StringEncoding
8037 [[NSAlert alertWithError:saveError] runModal];
8044 /*******************************
8045 * Subclass of the HBPresetsOutlineView *
8046 *******************************/
8048 @implementation HBPresetsOutlineView
8049 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
8053 // By default, NSTableView only drags an image of the first column. Change this to
8054 // drag an image of the queue's icon and PresetName columns.
8055 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
8056 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
8061 - (void) mouseDown:(NSEvent *)theEvent
8063 [super mouseDown:theEvent];
8069 - (BOOL) isDragging;