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 unsigned int maximumNumberOfAllowedAudioTracks = 24;
16 NSString *HBContainerChangedNotification = @"HBContainerChangedNotification";
17 NSString *keyContainerTag = @"keyContainerTag";
18 NSString *HBTitleChangedNotification = @"HBTitleChangedNotification";
19 NSString *keyTitleTag = @"keyTitleTag";
21 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
23 /* We setup the toolbar values here ShowPreviewIdentifier */
24 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
25 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
26 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
27 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
28 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
29 static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
30 static NSString * ShowPreviewIdentifier = @"Show Preview Window Item Identifier";
31 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
32 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
35 /*******************************
36 * HBController implementation *
37 *******************************/
38 @implementation HBController
40 + (unsigned int) maximumNumberOfAllowedAudioTracks { return maximumNumberOfAllowedAudioTracks; }
50 /* replace bundled app icon with one which is 32/64-bit savvy */
51 #if defined( __LP64__ )
52 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
54 fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
56 if( fApplicationIcon != nil )
57 [NSApp setApplicationIconImage:fApplicationIcon];
59 [HBPreferencesController registerUserDefaults];
61 fQueueEncodeLibhb = NULL;
62 /* Check for check for the app support directory here as
63 * outputPanel needs it right away, as may other future methods
65 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
67 YES ) objectAtIndex:0];
68 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
69 stringByAppendingPathComponent:@"HandBrake"];
70 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
72 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
75 /* Check for and create the App Support Preview directory if necessary */
76 NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
77 if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
79 [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
82 outputPanel = [[HBOutputPanelController alloc] init];
83 fPictureController = [[PictureController alloc] init];
84 fQueueController = [[HBQueueController alloc] init];
85 fAdvancedOptions = [[HBAdvancedController alloc] init];
86 /* we init the HBPresets class which currently is only used
87 * for updating built in presets, may move more functionality
90 fPresetsBuiltin = [[HBPresets alloc] init];
91 fPreferencesController = [[HBPreferencesController alloc] init];
92 /* Lets report the HandBrake version number here to the activity log and text log file */
93 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
94 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
100 - (void) applicationDidFinishLaunching: (NSNotification *) notification
102 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
103 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
104 fHandle = hb_init(loggingLevel, 0);
105 /* Optional dvd nav UseDvdNav*/
106 hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
107 /* Init a separate instance of libhb for user scanning and setting up jobs */
108 fQueueEncodeLibhb = hb_init(loggingLevel, 0);
110 // Set the Growl Delegate
111 [GrowlApplicationBridge setGrowlDelegate: self];
112 /* Init others controllers */
113 [fPictureController SetHandle: fHandle];
114 [fPictureController setHBController: self];
116 [fQueueController setHandle: fQueueEncodeLibhb];
117 [fQueueController setHBController: self];
119 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
120 [fChapterTable setDataSource:fChapterTitlesDelegate];
121 [fChapterTable setDelegate:fChapterTitlesDelegate];
123 /* setup the subtitles delegate and connections to table */
124 fSubtitlesDelegate = [[HBSubtitles alloc] init];
125 [fSubtitlesTable setDataSource:fSubtitlesDelegate];
126 [fSubtitlesTable setDelegate:fSubtitlesDelegate];
127 [fSubtitlesTable setRowHeight:25.0];
129 /* setup the audio controller */
130 [fAudioDelegate setHBController: self];
131 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(autoSetM4vExtension:) name: HBMixdownChangedNotification object: nil];
133 [fPresetsOutlineView setAutosaveName:@"Presets View"];
134 [fPresetsOutlineView setAutosaveExpandedItems:YES];
136 dockIconProgress = 0;
138 /* Init QueueFile .plist */
139 [self loadQueueFile];
140 /* Run hbInstances to get any info on other instances as well as set the
141 * pid number for this instance in the case of multi-instance encoding. */
142 hbInstanceNum = [self hbInstances];
144 /* If we are a single instance it is safe to clean up the previews if there are any
145 * left over. This is a bit of a kludge but will prevent a build up of old instance
146 * live preview cruft. No danger of removing an active preview directory since they
147 * are created later in HBPreviewController if they don't exist at the moment a live
148 * preview encode is initiated. */
149 if (hbInstanceNum == 1)
151 NSString *PreviewDirectory = [NSString stringWithFormat:@"~/Library/Application Support/HandBrake/Previews"];
152 PreviewDirectory = [PreviewDirectory stringByExpandingTildeInPath];
154 NSArray *files = [ [NSFileManager defaultManager] contentsOfDirectoryAtPath: PreviewDirectory error: &error ];
155 for( NSString *file in files )
157 if( file != @"." && file != @".." )
159 [ [NSFileManager defaultManager] removeItemAtPath: [ PreviewDirectory stringByAppendingPathComponent: file ] error: &error ];
162 //an error occurred...
163 [self writeToActivityLog: "Could not remove existing preview at : %s",[file UTF8String] ];
172 /* Call UpdateUI every 1/2 sec */
174 [[NSRunLoop currentRunLoop] addTimer:[NSTimer
175 scheduledTimerWithTimeInterval:0.5
177 selector:@selector(updateUI:)
178 userInfo:nil repeats:YES]
179 forMode:NSDefaultRunLoopMode];
182 // Open debug output window now if it was visible when HB was closed
183 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
184 [self showDebugOutputPanel:nil];
186 // Open queue window now if it was visible when HB was closed
187 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
188 [self showQueueWindow:nil];
190 [self openMainWindow:nil];
192 /* We have to set the bool to tell hb what to do after a scan
193 * Initially we set it to NO until we start processing the queue
195 applyQueueToScan = NO;
197 /* Now we re-check the queue array to see if there are
198 * any remaining encodes to be done in it and ask the
199 * user if they want to reload the queue */
200 if ([QueueFileArray count] > 0)
202 /* run getQueueStats to see whats in the queue file */
203 [self getQueueStats];
204 /* this results in these values
205 * fEncodingQueueItem = 0;
207 * fCompletedCount = 0;
208 * fCanceledCount = 0;
212 /*On Screen Notification*/
213 NSString * alertTitle;
215 /* We check to see if there is already another instance of hb running.
216 * Note: hbInstances == 1 means we are the only instance of HandBrake.app
218 if (hbInstanceNum > 1)
220 alertTitle = [NSString stringWithFormat:
221 NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
222 NSBeginCriticalAlertSheet(
224 NSLocalizedString(@"Reload Queue", nil),
228 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
229 NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
233 if (fWorkingCount > 0 || fPendingCount > 0)
235 if (fWorkingCount > 0)
237 alertTitle = [NSString stringWithFormat:
238 NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item(s) and %d Pending Item(s) In Your Queue.", @""),
239 fWorkingCount,fPendingCount];
243 alertTitle = [NSString stringWithFormat:
244 NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
248 NSBeginCriticalAlertSheet(
250 NSLocalizedString(@"Reload Queue", nil),
252 NSLocalizedString(@"Empty Queue", nil),
254 nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
255 NSLocalizedString(@" Do you want to reload them ?", nil));
259 /* Since we addressed any pending or previously encoding items above, we go ahead and make sure the queue
260 * is empty of any finished items or cancelled items */
261 [self clearQueueAllItems];
262 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
263 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
265 [self browseSources:nil];
268 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
270 [self browseSources:(id)fOpenSourceTitleMMenu];
278 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
279 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
281 [self browseSources:nil];
284 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
286 [self browseSources:(id)fOpenSourceTitleMMenu];
289 currentQueueEncodeNameString = @"";
293 #pragma mark Multiple Instances
295 /* hbInstances checks to see if other instances of HB are running and also sets the pid for this instance for multi-instance queue encoding */
297 /* Note for now since we are in early phases of multi-instance I have put in quite a bit of logging. Can be removed as we see fit. */
300 /* check to see if another instance of HandBrake.app is running */
301 NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
302 NSDictionary *runningAppsDictionary;
304 NSString * thisInstanceAppPath = [[NSBundle mainBundle] bundlePath];
305 NSString * runningInstanceAppPath;
306 int runningInstancePidNum;
307 [self writeToActivityLog: "hbInstances path to this instance: %s", [thisInstanceAppPath UTF8String]];
308 for (runningAppsDictionary in runningAppDictionaries)
310 if ([[runningAppsDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
312 /*Report the path to each active instances app path */
313 runningInstancePidNum = [[runningAppsDictionary valueForKey:@"NSApplicationProcessIdentifier"] intValue];
314 runningInstanceAppPath = [runningAppsDictionary valueForKey:@"NSApplicationPath"];
315 [self writeToActivityLog: "hbInstance found instance pidnum:%d at path: %s", runningInstancePidNum, [runningInstanceAppPath UTF8String]];
316 /* see if this is us by comparing the app path */
317 if ([runningInstanceAppPath isEqualToString: thisInstanceAppPath])
319 /* If so this is our pidnum */
320 [self writeToActivityLog: "hbInstance MATCH FOUND, our pidnum is:%d", runningInstancePidNum];
321 /* Get the PID number for this hb instance, used in multi instance encoding */
322 pidNum = runningInstancePidNum;
323 /* Report this pid to the activity log */
324 [self writeToActivityLog: "Pid for this instance:%d", pidNum];
325 /* Tell fQueueController what our pidNum is */
326 [fQueueController setPidNum:pidNum];
341 - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
344 [self writeToActivityLog: "didDimissReloadQueue number of hb instances:%d", hbInstanceNum];
345 if (returnCode == NSAlertOtherReturn)
347 [self writeToActivityLog: "didDimissReloadQueue NSAlertOtherReturn Chosen"];
348 [self clearQueueAllItems];
350 /* We show whichever open source window specified in LaunchSourceBehavior preference key */
351 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
353 [self browseSources:nil];
356 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
358 [self browseSources:(id)fOpenSourceTitleMMenu];
363 [self writeToActivityLog: "didDimissReloadQueue First Button Chosen"];
364 if (hbInstanceNum == 1)
367 [self setQueueEncodingItemsAsPending];
369 [self showQueueWindow:NULL];
373 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
378 hb_get_state( fQueueEncodeLibhb, &s );
380 if ( s.state != HB_STATE_IDLE )
382 int result = NSRunCriticalAlertPanel(
383 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
384 NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
385 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
387 if (result == NSAlertDefaultReturn)
389 return NSTerminateNow;
392 return NSTerminateCancel;
395 // Warn if items still in the queue
396 else if ( fPendingCount > 0 )
398 int result = NSRunCriticalAlertPanel(
399 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
400 NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
401 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
403 if ( result == NSAlertDefaultReturn )
404 return NSTerminateNow;
406 return NSTerminateCancel;
409 return NSTerminateNow;
412 - (void)applicationWillTerminate:(NSNotification *)aNotification
414 [currentQueueEncodeNameString release];
415 [browsedSourceDisplayName release];
416 [outputPanel release];
417 [fQueueController release];
418 [fPreviewController release];
419 [fPictureController release];
420 [fApplicationIcon release];
423 hb_close(&fQueueEncodeLibhb);
429 - (void) awakeFromNib
432 [fWindow setExcludedFromWindowsMenu:NO];
434 [fAdvancedOptions setView:fAdvancedView];
436 /* lets setup our presets drawer for drag and drop here */
437 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
438 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
439 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
441 /* Initialize currentScanCount so HB can use it to
442 evaluate successive scans */
443 currentScanCount = 0;
446 /* Init UserPresets .plist */
449 fRipIndicatorShown = NO; // initially out of view in the nib
451 /* For 64 bit builds, the threaded animation in the progress
452 * indicators conflicts with the animation in the advanced tab
453 * for reasons not completely clear. jbrjake found a note in the
454 * 10.5 dev notes regarding this possiblility. It was also noted
455 * that unless specified, setUsesThreadedAnimation defaults to true.
456 * So, at least for now we set the indicator animation to NO for
457 * both the scan and regular progress indicators for both 32 and 64 bit
458 * as it test out fine on both and there is no reason our progress indicators
459 * should require their own thread.
462 [fScanIndicator setUsesThreadedAnimation:NO];
463 [fRipIndicator setUsesThreadedAnimation:NO];
467 /* Show/Dont Show Presets drawer upon launch based
468 on user preference DefaultPresetsDrawerShow*/
469 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
471 [fPresetDrawer setDelegate:self];
472 NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
473 stringForKey:@"Drawer Size"] );
474 if( drawerSize.width )
475 [fPresetDrawer setContentSize: drawerSize];
476 [fPresetDrawer open];
479 /* Initially set the dvd angle widgets to hidden (dvdnav only) */
480 [fSrcAngleLabel setHidden:YES];
481 [fSrcAnglePopUp setHidden:YES];
483 /* Setup the start / stop popup */
484 [fEncodeStartStopPopUp removeAllItems];
485 [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
486 [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
487 [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
488 /* Align the start / stop widgets with the chapter popups */
489 [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
490 [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
492 [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
493 [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
496 NSMenuItem *menuItem;
497 [fDstFormatPopUp removeAllItems];
499 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
500 [menuItem setTag: HB_MUX_MP4];
502 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
503 [menuItem setTag: HB_MUX_MKV];
505 [fDstFormatPopUp selectItemAtIndex: 0];
507 [self formatPopUpChanged:nil];
509 /* We enable the create chapters checkbox here since we are .mp4 */
510 [fCreateChapterMarkers setEnabled: YES];
511 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
513 [fCreateChapterMarkers setState: NSOnState];
519 [fDstFile2Field setStringValue: [NSString stringWithFormat:
520 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
523 [fVidEncoderPopUp removeAllItems];
524 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
528 [fVidTargetSizeField setIntValue: 700];
529 [fVidBitrateField setIntValue: 1000];
531 [fVidQualityMatrix selectCell: fVidBitrateCell];
532 [self videoMatrixChanged:nil];
534 /* Video framerate */
535 [fVidRatePopUp removeAllItems];
536 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
537 for( int i = 0; i < hb_video_rates_count; i++ )
539 if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
541 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
542 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
544 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
546 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
547 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
549 else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
551 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
552 [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
556 [fVidRatePopUp addItemWithTitle:
557 [NSString stringWithUTF8String: hb_video_rates[i].string]];
560 [fVidRatePopUp selectItemAtIndex: 0];
562 /* Set Auto Crop to On at launch */
563 [fPictureController setAutoCrop:YES];
566 [fStatusField setStringValue: @""];
571 /* We disable the Turbo 1st pass checkbox since we are not x264 */
572 [fVidTurboPassCheck setEnabled: NO];
573 [fVidTurboPassCheck setState: NSOffState];
576 /* lets get our default prefs here */
577 [self getDefaultPresets:nil];
578 /* lets initialize the current successful scancount here to 0 */
579 currentSuccessfulScanCount = 0;
582 - (void) enableUI: (bool) b
584 NSControl * controls[] =
585 { fSrcTitleField, fSrcTitlePopUp,
586 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
587 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
588 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
589 fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
590 fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
591 fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
592 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
593 fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
594 fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,
595 fSrcFrameEndEncodingField, fLoadChaptersButton, fSaveChaptersButton, fFrameratePfrCheck};
598 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
600 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
602 NSTextField * tf = (NSTextField *) controls[i];
603 if( ![tf isBezeled] )
605 [tf setTextColor: b ? [NSColor controlTextColor] :
606 [NSColor disabledControlTextColor]];
610 [controls[i] setEnabled: b];
617 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
618 [self calculatePictureSizing:nil];
619 /* Also enable the preview window hud controls */
620 [fPictureController enablePreviewHudControls];
625 [fPresetsOutlineView setEnabled: NO];
626 [fPictureController disablePreviewHudControls];
629 [self videoMatrixChanged:nil];
630 [fAdvancedOptions enableUI:b];
634 /***********************************************************************
636 ***********************************************************************
637 * Shows a progression bar on the dock icon, filled according to
638 * 'progress' (0.0 <= progress <= 1.0).
639 * Called with progress < 0.0 or progress > 1.0, restores the original
641 **********************************************************************/
642 - (void) UpdateDockIcon: (float) progress
645 NSBitmapImageRep * bmp;
647 uint32_t black = htonl( 0x000000FF );
648 uint32_t red = htonl( 0xFF0000FF );
649 uint32_t white = htonl( 0xFFFFFFFF );
650 int row_start, row_end;
653 if( progress < 0.0 || progress > 1.0 )
655 [NSApp setApplicationIconImage: fApplicationIcon];
659 /* Get it in a raw bitmap form */
660 tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
661 NSTIFFCompressionNone factor: 1.0];
662 bmp = [NSBitmapImageRep imageRepWithData: tiff];
664 /* Draw the progression bar */
665 /* It's pretty simple (ugly?) now, but I'm no designer */
667 row_start = 3 * (int) [bmp size].height / 4;
668 row_end = 7 * (int) [bmp size].height / 8;
670 for( i = row_start; i < row_start + 2; i++ )
672 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
673 for( j = 0; j < (int) [bmp size].width; j++ )
678 for( i = row_start + 2; i < row_end - 2; i++ )
680 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
683 for( j = 2; j < (int) [bmp size].width - 2; j++ )
685 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
697 for( i = row_end - 2; i < row_end; i++ )
699 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
700 for( j = 0; j < (int) [bmp size].width; j++ )
706 /* Now update the dock icon */
707 tiff = [bmp TIFFRepresentationUsingCompression:
708 NSTIFFCompressionNone factor: 1.0];
709 NSImage* icon = [[NSImage alloc] initWithData: tiff];
710 [NSApp setApplicationIconImage: icon];
714 - (void) updateUI: (NSTimer *) timer
717 /* Update UI for fHandle (user scanning instance of libhb ) */
720 list = hb_get_titles( fHandle );
721 /* check to see if there has been a new scan done
722 this bypasses the constraints of HB_STATE_WORKING
723 not allowing setting a newly scanned source */
724 int checkScanCount = hb_get_scancount( fHandle );
725 if( checkScanCount > currentScanCount )
727 currentScanCount = checkScanCount;
728 [fScanIndicator setIndeterminate: NO];
729 [fScanIndicator setDoubleValue: 0.0];
730 [fScanIndicator setHidden: YES];
731 [self showNewScan:nil];
735 hb_get_state( fHandle, &s );
741 #define p s.param.scanning
742 case HB_STATE_SCANNING:
744 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
745 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
746 p.title_cur, p.title_count]];
747 [fScanIndicator setHidden: NO];
748 [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
753 #define p s.param.scandone
754 case HB_STATE_SCANDONE:
756 [fScanIndicator setIndeterminate: NO];
757 [fScanIndicator setDoubleValue: 0.0];
758 [fScanIndicator setHidden: YES];
759 [self writeToActivityLog:"ScanDone state received from fHandle"];
760 [self showNewScan:nil];
761 [[fWindow toolbar] validateVisibleItems];
767 #define p s.param.working
768 case HB_STATE_WORKING:
775 #define p s.param.muxing
776 case HB_STATE_MUXING:
783 case HB_STATE_PAUSED:
786 case HB_STATE_WORKDONE:
793 /* Update UI for fQueueEncodeLibhb */
795 // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
796 /* check to see if there has been a new scan done
797 this bypasses the constraints of HB_STATE_WORKING
798 not allowing setting a newly scanned source */
800 checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
801 if( checkScanCount > currentScanCount )
803 currentScanCount = checkScanCount;
807 hb_get_state( fQueueEncodeLibhb, &s );
813 #define p s.param.scanning
814 case HB_STATE_SCANNING:
816 [fStatusField setStringValue: [NSString stringWithFormat:
817 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
818 p.title_cur, p.title_count]];
820 /* Set the status string in fQueueController as well */
821 [fQueueController setQueueStatusString: [NSString stringWithFormat:
822 NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
823 p.title_cur, p.title_count]];
828 #define p s.param.scandone
829 case HB_STATE_SCANDONE:
831 [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
832 [self processNewQueueEncode];
833 [[fWindow toolbar] validateVisibleItems];
840 #define p s.param.working
842 case HB_STATE_SEARCHING:
844 NSMutableString * string;
845 NSString * pass_desc;
847 /* Update text field */
849 //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];
850 /* For now, do not announce "pass x of x for the search phase ... */
851 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
855 [string appendFormat:
856 NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
859 [fStatusField setStringValue: string];
860 /* Set the status string in fQueueController as well */
861 [fQueueController setQueueStatusString: string];
863 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
864 [fRipIndicator setIndeterminate: NO];
865 [fRipIndicator setDoubleValue:100.0 * progress_total];
867 // If progress bar hasn't been revealed at the bottom of the window, do
868 // that now. This code used to be in doRip. I moved it to here to handle
869 // the case where hb_start is called by HBQueueController and not from
871 if( !fRipIndicatorShown )
873 NSRect frame = [fWindow frame];
874 if( frame.size.width <= 591 )
875 frame.size.width = 591;
876 frame.size.height += 36;
877 frame.origin.y -= 36;
878 [fWindow setFrame:frame display:YES animate:YES];
879 fRipIndicatorShown = YES;
883 /* Update dock icon */
884 /* Note not done yet */
889 case HB_STATE_WORKING:
891 NSMutableString * string;
892 NSString * pass_desc;
893 /* Update text field */
894 if (p.job_cur == 1 && p.job_count > 1)
896 if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
898 pass_desc = @"(subtitle scan)";
910 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: %@ \nPass %d %@ of %d, %.2f %%", @"" ), currentQueueEncodeNameString, p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
914 [string appendFormat:
915 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
916 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
918 [fStatusField setStringValue: string];
919 [fQueueController setQueueStatusString:string];
922 CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
923 [fRipIndicator setIndeterminate: NO];
924 [fRipIndicator setDoubleValue:100.0 * progress_total];
926 // If progress bar hasn't been revealed at the bottom of the window, do
927 // that now. This code used to be in doRip. I moved it to here to handle
928 // the case where hb_start is called by HBQueueController and not from
930 if( !fRipIndicatorShown )
932 NSRect frame = [fWindow frame];
933 if( frame.size.width <= 591 )
934 frame.size.width = 591;
935 frame.size.height += 36;
936 frame.origin.y -= 36;
937 [fWindow setFrame:frame display:YES animate:YES];
938 fRipIndicatorShown = YES;
942 /* Update dock icon */
943 if( dockIconProgress < 100.0 * progress_total )
945 [self UpdateDockIcon: progress_total];
946 dockIconProgress += 5;
953 #define p s.param.muxing
954 case HB_STATE_MUXING:
956 /* Update text field */
957 [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
958 /* Set the status string in fQueueController as well */
959 [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
961 [fRipIndicator setIndeterminate: YES];
962 [fRipIndicator startAnimation: nil];
964 /* Update dock icon */
965 [self UpdateDockIcon: 1.0];
971 case HB_STATE_PAUSED:
972 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
973 [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
977 case HB_STATE_WORKDONE:
979 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
980 // or someone calling hb_stop. In the latter case, hb_stop does not clear
981 // out the remaining passes/jobs in the queue. We'll do that here.
983 // Delete all remaining jobs of this encode.
984 [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
985 /* Set the status string in fQueueController as well */
986 [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
987 [fRipIndicator setIndeterminate: NO];
988 [fRipIndicator stopAnimation: nil];
989 [fRipIndicator setDoubleValue: 0.0];
990 [[fWindow toolbar] validateVisibleItems];
992 /* Restore dock icon */
993 [self UpdateDockIcon: -1.0];
994 dockIconProgress = 0;
996 if( fRipIndicatorShown )
998 NSRect frame = [fWindow frame];
999 if( frame.size.width <= 591 )
1000 frame.size.width = 591;
1001 frame.size.height += -36;
1002 frame.origin.y -= -36;
1003 [fWindow setFrame:frame display:YES animate:YES];
1004 fRipIndicatorShown = NO;
1006 /* Since we are done with this encode, tell output to stop writing to the
1007 * individual encode log
1009 [outputPanel endEncodeLog];
1010 /* Check to see if the encode state has not been cancelled
1011 to determine if we should check for encode done notifications */
1012 if( fEncodeState != 2 )
1014 NSString *pathOfFinishedEncode;
1015 /* Get the output file name for the finished encode */
1016 pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
1018 /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
1019 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
1020 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
1022 /* If Play System Alert has been selected in Preferences */
1023 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
1027 [self showGrowlDoneNotification:pathOfFinishedEncode];
1031 [self sendToMetaX:pathOfFinishedEncode];
1033 /* since we have successfully completed an encode, we increment the queue counter */
1034 [self incrementQueueItemDone:currentQueueEncodeIndex];
1042 /* Since we can use multiple instance off of the same queue file it is imperative that we keep the QueueFileArray updated off of the QueueFile.plist
1043 * so we go ahead and do it in this existing timer as opposed to using a new one */
1045 NSMutableArray * tempQueueArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
1046 [QueueFileArray setArray:tempQueueArray];
1047 [tempQueueArray release];
1048 /* Send Fresh QueueFileArray to fQueueController to update queue window */
1049 [fQueueController setQueueArray: QueueFileArray];
1050 [self getQueueStats];
1054 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
1055 - (void) writeToActivityLog:(const char *) format, ...
1058 va_start(args, format);
1062 vsnprintf( str, 1024, format, args );
1064 time_t _now = time( NULL );
1065 struct tm * now = localtime( &_now );
1066 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
1072 #pragma mark Toolbar
1073 // ============================================================
1074 // NSToolbar Related Methods
1075 // ============================================================
1077 - (void) setupToolbar {
1078 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
1080 [toolbar setAllowsUserCustomization: YES];
1081 [toolbar setAutosavesConfiguration: YES];
1082 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
1084 [toolbar setDelegate: self];
1086 [fWindow setToolbar: toolbar];
1089 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
1090 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
1091 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
1093 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
1095 [item setLabel: @"Toggle Presets"];
1096 [item setPaletteLabel: @"Toggler Presets"];
1097 [item setToolTip: @"Open/Close Preset Drawer"];
1098 [item setImage: [NSImage imageNamed: @"Drawer"]];
1099 [item setTarget: self];
1100 [item setAction: @selector(toggleDrawer:)];
1101 [item setAutovalidates: NO];
1103 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
1105 [item setLabel: @"Start"];
1106 [item setPaletteLabel: @"Start Encoding"];
1107 [item setToolTip: @"Start Encoding"];
1108 [item setImage: [NSImage imageNamed: @"Play"]];
1109 [item setTarget: self];
1110 [item setAction: @selector(Rip:)];
1112 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
1114 [item setLabel: @"Show Queue"];
1115 [item setPaletteLabel: @"Show Queue"];
1116 [item setToolTip: @"Show Queue"];
1117 [item setImage: [NSImage imageNamed: @"Queue"]];
1118 [item setTarget: self];
1119 [item setAction: @selector(showQueueWindow:)];
1120 [item setAutovalidates: NO];
1122 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
1124 [item setLabel: @"Add to Queue"];
1125 [item setPaletteLabel: @"Add to Queue"];
1126 [item setToolTip: @"Add to Queue"];
1127 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
1128 [item setTarget: self];
1129 [item setAction: @selector(addToQueue:)];
1131 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
1133 [item setLabel: @"Pause"];
1134 [item setPaletteLabel: @"Pause Encoding"];
1135 [item setToolTip: @"Pause Encoding"];
1136 [item setImage: [NSImage imageNamed: @"Pause"]];
1137 [item setTarget: self];
1138 [item setAction: @selector(Pause:)];
1140 else if ([itemIdent isEqualToString: ShowPictureIdentifier])
1142 [item setLabel: @"Picture Settings"];
1143 [item setPaletteLabel: @"Show Picture Settings"];
1144 [item setToolTip: @"Show Picture Settings"];
1145 [item setImage: [NSImage imageNamed: @"pref-picture"]];
1146 [item setTarget: self];
1147 [item setAction: @selector(showPicturePanel:)];
1149 else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
1151 [item setLabel: @"Preview Window"];
1152 [item setPaletteLabel: @"Show Preview"];
1153 [item setToolTip: @"Show Preview"];
1154 //[item setImage: [NSImage imageNamed: @"pref-picture"]];
1155 [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
1156 [item setTarget: self];
1157 [item setAction: @selector(showPreviewWindow:)];
1159 else if ([itemIdent isEqualToString: ShowActivityIdentifier])
1161 [item setLabel: @"Activity Window"];
1162 [item setPaletteLabel: @"Show Activity Window"];
1163 [item setToolTip: @"Show Activity Window"];
1164 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
1165 [item setTarget: self];
1166 [item setAction: @selector(showDebugOutputPanel:)];
1167 [item setAutovalidates: NO];
1169 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
1171 [item setLabel: @"Source"];
1172 [item setPaletteLabel: @"Source"];
1173 [item setToolTip: @"Choose Video Source"];
1174 [item setImage: [NSImage imageNamed: @"Source"]];
1175 [item setTarget: self];
1176 [item setAction: @selector(browseSources:)];
1186 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
1188 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
1189 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1190 NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
1193 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
1195 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
1196 ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
1197 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
1198 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
1201 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1203 NSString * ident = [toolbarItem itemIdentifier];
1209 hb_get_state( fHandle, &s );
1210 if (s.state == HB_STATE_SCANNING)
1213 if ([ident isEqualToString: ChooseSourceIdentifier])
1215 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1216 [toolbarItem setLabel: @"Cancel Scan"];
1217 [toolbarItem setPaletteLabel: @"Cancel Scanning"];
1218 [toolbarItem setToolTip: @"Cancel Scanning Source"];
1222 if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
1227 if ([ident isEqualToString: ChooseSourceIdentifier])
1229 [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
1230 [toolbarItem setLabel: @"Source"];
1231 [toolbarItem setPaletteLabel: @"Source"];
1232 [toolbarItem setToolTip: @"Choose Video Source"];
1237 hb_get_state2( fQueueEncodeLibhb, &s );
1239 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
1241 if ([ident isEqualToString: StartEncodingIdentifier])
1243 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
1244 [toolbarItem setLabel: @"Stop"];
1245 [toolbarItem setPaletteLabel: @"Stop"];
1246 [toolbarItem setToolTip: @"Stop Encoding"];
1249 if ([ident isEqualToString: PauseEncodingIdentifier])
1251 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
1252 [toolbarItem setLabel: @"Pause"];
1253 [toolbarItem setPaletteLabel: @"Pause Encoding"];
1254 [toolbarItem setToolTip: @"Pause Encoding"];
1259 if ([ident isEqualToString: AddToQueueIdentifier])
1261 if ([ident isEqualToString: ShowPictureIdentifier])
1263 if ([ident isEqualToString: ShowPreviewIdentifier])
1267 else if (s.state == HB_STATE_PAUSED)
1269 if ([ident isEqualToString: PauseEncodingIdentifier])
1271 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1272 [toolbarItem setLabel: @"Resume"];
1273 [toolbarItem setPaletteLabel: @"Resume Encoding"];
1274 [toolbarItem setToolTip: @"Resume Encoding"];
1277 if ([ident isEqualToString: StartEncodingIdentifier])
1279 if ([ident isEqualToString: AddToQueueIdentifier])
1281 if ([ident isEqualToString: ShowPictureIdentifier])
1283 if ([ident isEqualToString: ShowPreviewIdentifier])
1286 else if (s.state == HB_STATE_SCANNING)
1288 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
1290 if ([ident isEqualToString: StartEncodingIdentifier])
1292 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
1293 if (hb_count(fHandle) > 0)
1294 [toolbarItem setLabel: @"Start Queue"];
1296 [toolbarItem setLabel: @"Start"];
1297 [toolbarItem setPaletteLabel: @"Start Encoding"];
1298 [toolbarItem setToolTip: @"Start Encoding"];
1301 if ([ident isEqualToString: AddToQueueIdentifier])
1303 if ([ident isEqualToString: ShowPictureIdentifier])
1305 if ([ident isEqualToString: ShowPreviewIdentifier])
1310 /* If there are any pending queue items, make sure the start/stop button is active */
1311 if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
1313 if ([ident isEqualToString: ShowQueueIdentifier])
1315 if ([ident isEqualToString: ToggleDrawerIdentifier])
1317 if ([ident isEqualToString: ChooseSourceIdentifier])
1319 if ([ident isEqualToString: ShowActivityIdentifier])
1325 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1327 SEL action = [menuItem action];
1330 hb_get_state2( fHandle, &s );
1334 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
1335 return SuccessfulScan && [fWindow attachedSheet] == nil;
1337 if (action == @selector(browseSources:))
1339 if (s.state == HB_STATE_SCANNING)
1342 return [fWindow attachedSheet] == nil;
1344 if (action == @selector(selectDefaultPreset:))
1345 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
1346 if (action == @selector(Pause:))
1348 if (s.state == HB_STATE_WORKING)
1350 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
1351 [menuItem setTitle:@"Pause Encoding"];
1354 else if (s.state == HB_STATE_PAUSED)
1356 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
1357 [menuItem setTitle:@"Resume Encoding"];
1363 if (action == @selector(Rip:))
1365 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
1367 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
1368 [menuItem setTitle:@"Stop Encoding"];
1371 else if (SuccessfulScan)
1373 if(![[menuItem title] isEqualToString:@"Start Encoding"])
1374 [menuItem setTitle:@"Start Encoding"];
1375 return [fWindow attachedSheet] == nil;
1381 if( action == @selector(setDefaultPreset:) )
1383 return [fPresetsOutlineView selectedRow] != -1;
1390 #pragma mark Encode Done Actions
1391 // register a test notification and make
1392 // it enabled by default
1393 #define SERVICE_NAME @"Encode Done"
1394 - (NSDictionary *)registrationDictionaryForGrowl
1396 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
1397 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
1398 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
1401 return registrationDictionary;
1404 -(void)showGrowlDoneNotification:(NSString *) filePath
1406 /* This end of encode action is called as each encode rolls off of the queue */
1407 /* Setup the Growl stuff ... */
1408 NSString * finishedEncode = filePath;
1409 /* strip off the path to just show the file name */
1410 finishedEncode = [finishedEncode lastPathComponent];
1411 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
1412 [GrowlApplicationBridge
1413 notifyWithTitle:@"Put down that cocktail..."
1414 description:growlMssg
1415 notificationName:SERVICE_NAME
1421 -(void)sendToMetaX:(NSString *) filePath
1423 /* This end of encode action is called as each encode rolls off of the queue */
1424 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
1426 NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
1427 if (![sendToApp isEqualToString:@"None"])
1429 [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
1430 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
1431 [myScript executeAndReturnError: nil];
1438 - (void) queueCompletedAlerts
1440 /* If Play System Alert has been selected in Preferences */
1441 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
1446 /* If Alert Window or Window and Growl has been selected */
1447 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
1448 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
1450 /*On Screen Notification*/
1452 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
1453 [NSApp requestUserAttention:NSCriticalRequest];
1456 /* If sleep has been selected */
1457 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
1460 NSDictionary* errorDict;
1461 NSAppleEventDescriptor* returnDescriptor = nil;
1462 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
1463 @"tell application \"Finder\" to sleep"];
1464 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1465 [scriptObject release];
1467 /* If Shutdown has been selected */
1468 if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
1471 NSDictionary* errorDict;
1472 NSAppleEventDescriptor* returnDescriptor = nil;
1473 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
1474 @"tell application \"Finder\" to shut down"];
1475 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
1476 [scriptObject release];
1481 #pragma mark Get New Source
1483 /*Opens the source browse window, called from Open Source widgets */
1484 - (IBAction) browseSources: (id) sender
1488 hb_get_state( fHandle, &s );
1489 if (s.state == HB_STATE_SCANNING)
1491 [self cancelScanning:nil];
1496 NSOpenPanel * panel;
1498 panel = [NSOpenPanel openPanel];
1499 [panel setAllowsMultipleSelection: NO];
1500 [panel setCanChooseFiles: YES];
1501 [panel setCanChooseDirectories: YES ];
1502 NSString * sourceDirectory;
1503 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1505 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1509 sourceDirectory = @"~/Desktop";
1510 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1512 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1513 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1515 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1516 modalForWindow: fWindow modalDelegate: self
1517 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1518 contextInfo: sender];
1521 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1522 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1524 /* we convert the sender content of contextInfo back into a variable called sender
1525 * mostly just for consistency for evaluation later
1527 id sender = (id)contextInfo;
1528 /* User selected a file to open */
1529 if( returnCode == NSOKButton )
1531 /* Free display name allocated previously by this code */
1532 [browsedSourceDisplayName release];
1534 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1535 /* we set the last searched source directory in the prefs here */
1536 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1537 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1538 /* we order out sheet, which is the browse window as we need to open
1539 * the title selection sheet right away
1541 [sheet orderOut: self];
1543 if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
1545 /* We put the chosen source path in the source display text field for the
1546 * source title selection sheet in which the user specifies the specific title to be
1547 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1548 * purposes in the title panel
1551 [fScanSrcTitlePathField setStringValue:scanPath];
1552 NSString *displayTitlescanSourceName;
1554 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1556 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1557 we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
1558 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1562 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1563 displayTitlescanSourceName = [scanPath lastPathComponent];
1565 /* we set the source display name in the title selection dialogue */
1566 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1567 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1568 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1569 /* We show the actual sheet where the user specifies the title to be scanned
1570 * as we are going to do a title specific scan
1572 [self showSourceTitleScanPanel:nil];
1576 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1577 NSString *path = [[sheet filenames] objectAtIndex: 0];
1579 /* We check to see if the chosen file at path is a package */
1580 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1582 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1583 /* We check to see if this is an .eyetv package */
1584 if ([[path pathExtension] isEqualToString: @"eyetv"])
1586 [self writeToActivityLog:"trying to open eyetv package"];
1587 /* We're looking at an EyeTV package - try to open its enclosed
1589 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1591 int n = [[path stringByAppendingString: @"/"]
1592 completePathIntoString: &mpgname caseSensitive: YES
1593 matchesIntoArray: nil
1594 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1597 /* Found an mpeg inside the eyetv package, make it our scan path
1598 and call performScan on the enclosed mpeg */
1600 [self writeToActivityLog:"found mpeg in eyetv package"];
1601 [self performScan:path scanTitleNum:0];
1605 /* We did not find an mpeg file in our package, so we do not call performScan */
1606 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1609 /* We check to see if this is a .dvdmedia package */
1610 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1612 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1613 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1614 [self writeToActivityLog:"trying to open dvdmedia package"];
1615 [self performScan:path scanTitleNum:0];
1619 /* The package is not an eyetv package, so we do not call performScan */
1620 [self writeToActivityLog:"unable to open package"];
1623 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1625 /* path is not a package, so we call perform scan directly on our file */
1626 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1628 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1629 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1630 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1634 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1635 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1636 /* make sure we remove any path extension as this can also be an '.mpg' file */
1637 browsedSourceDisplayName = [[path lastPathComponent] retain];
1639 applyQueueToScan = NO;
1640 [self performScan:path scanTitleNum:0];
1648 - (IBAction)showAboutPanel:(id)sender
1650 NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
1651 fApplicationIcon, @"ApplicationIcon",
1653 [NSApp orderFrontStandardAboutPanelWithOptions:d];
1657 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1658 - (IBAction) showSourceTitleScanPanel: (id) sender
1660 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1663 [fScanSrcTitleNumField setStringValue: @"0"];
1664 /* Show the panel */
1665 [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
1668 - (IBAction) closeSourceTitleScanPanel: (id) sender
1670 [NSApp endSheet: fScanSrcTitlePanel];
1671 [fScanSrcTitlePanel orderOut: self];
1673 if(sender == fScanSrcTitleOpenButton)
1675 /* We setup the scan status in the main window to indicate a source title scan */
1676 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1677 [fScanIndicator setHidden: NO];
1678 [fScanIndicator setIndeterminate: YES];
1679 [fScanIndicator startAnimation: nil];
1681 /* We use the performScan method to actually perform the specified scan passing the path and the title
1684 applyQueueToScan = NO;
1685 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1689 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1690 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1693 /* use a bool to determine whether or not we can decrypt using vlc */
1694 BOOL cancelScanDecrypt = 0;
1696 NSString *path = scanPath;
1697 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1699 // Notify ChapterTitles that there's no title
1700 [fChapterTitlesDelegate resetWithTitle:nil];
1701 [fChapterTable reloadData];
1703 // Notify Subtitles that there's no title
1704 [fSubtitlesDelegate resetWithTitle:nil];
1705 [fSubtitlesTable reloadData];
1707 // Notify anyone interested (audio controller) that there's no title
1708 [[NSNotificationCenter defaultCenter] postNotification:
1709 [NSNotification notificationWithName: HBTitleChangedNotification
1711 userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
1712 [NSData dataWithBytesNoCopy: &fTitle length: sizeof(fTitle) freeWhenDone: NO], keyTitleTag,
1715 [self enableUI: NO];
1717 if( [detector isVideoDVD] )
1719 // The chosen path was actually on a DVD, so use the raw block
1720 // device path instead.
1721 path = [detector devicePath];
1722 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1724 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1725 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
1728 /*compatible vlc not found, so we set the bool to cancel scanning to 1 */
1729 cancelScanDecrypt = 1;
1730 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1732 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");
1733 [NSApp requestUserAttention:NSCriticalRequest];
1735 if (status == NSAlertDefaultReturn)
1737 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1738 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
1740 else if (status == NSAlertAlternateReturn)
1742 /* User chose to cancel the scan */
1743 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1747 /* 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 */
1748 cancelScanDecrypt = 0;
1749 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1755 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1756 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1762 if (cancelScanDecrypt == 0)
1764 /* we actually pass the scan off to libhb here */
1765 /* If there is no title number passed to scan, we use "0"
1766 * which causes the default behavior of a full source scan
1772 if (scanTitleNum > 0)
1774 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1776 /* We use our advanced pref to determine how many previews to scan */
1777 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
1778 /* We use our advanced pref to determine the minimum title length to use in seconds*/
1779 uint64_t min_title_duration_seconds = 90000L * [[[NSUserDefaults standardUserDefaults] objectForKey:@"MinTitleScanSeconds"] intValue];
1780 /* set title to NULL */
1782 [self writeToActivityLog: "Minimum length of title for scan: %d", min_title_duration_seconds];
1783 hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 , min_title_duration_seconds );
1784 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1788 - (IBAction) cancelScanning:(id)sender
1790 hb_scan_stop(fHandle);
1793 - (IBAction) showNewScan:(id)sender
1796 hb_title_t * title = NULL;
1797 int feature_title=0; // Used to store the main feature title
1799 list = hb_get_titles( fHandle );
1801 if( !hb_list_count( list ) )
1803 /* We display a message if a valid dvd source was not chosen */
1804 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1805 SuccessfulScan = NO;
1807 // Notify ChapterTitles that there's no title
1808 [fSubtitlesDelegate resetWithTitle:nil];
1809 [fSubtitlesTable reloadData];
1811 // Notify Subtitles that there's no title
1812 [fChapterTitlesDelegate resetWithTitle:nil];
1813 [fChapterTable reloadData];
1815 // Notify anyone interested (audio controller) that there's no title
1816 [[NSNotificationCenter defaultCenter] postNotification:
1817 [NSNotification notificationWithName: HBTitleChangedNotification
1819 userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
1820 [NSData dataWithBytesNoCopy: &fTitle length: sizeof(fTitle) freeWhenDone: NO], keyTitleTag,
1825 if (applyQueueToScan == YES)
1827 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1828 [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
1831 else if (applyQueueToScan == NO)
1833 [self writeToActivityLog: "showNewScan: This is a new source item scan"];
1837 [self writeToActivityLog: "showNewScan: cannot grok scan status"];
1840 /* We increment the successful scancount here by one,
1841 which we use at the end of this function to tell the gui
1842 if this is the first successful scan since launch and whether
1843 or not we should set all settings to the defaults */
1844 currentSuccessfulScanCount++;
1846 [[fWindow toolbar] validateVisibleItems];
1848 [fSrcTitlePopUp removeAllItems];
1849 for( int i = 0; i < hb_list_count( list ); i++ )
1851 title = (hb_title_t *) hb_list_item( list, i );
1853 currentSource = [NSString stringWithUTF8String: title->name];
1854 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1855 if (!browsedSourceDisplayName)
1857 browsedSourceDisplayName = @"NoNameDetected";
1859 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1861 // use the correct extension based on the container
1862 int format = [fDstFormatPopUp indexOfSelectedItem];
1869 /* If its a queue rescan for edit, get the queue item output path */
1870 /* if not, its a new source scan. */
1871 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1872 if (applyQueueToScan == YES)
1874 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
1876 else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1878 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1879 @"%@/%@.%s", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension],ext]];
1883 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1884 @"%@/Desktop/%@.%s", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension],ext]];
1887 // set m4v extension if necessary - do not override user-specified .mp4 extension
1888 if (format == 0 && applyQueueToScan != YES)
1890 [self autoSetM4vExtension: sender];
1893 /* See if this is the main feature according to libhb */
1894 if (title->index == title->job->feature)
1899 [fSrcTitlePopUp addItemWithTitle: [NSString
1900 stringWithFormat: @"%@ %d - %02dh%02dm%02ds",
1901 currentSource, title->index, title->hours, title->minutes,
1905 /* if we are a stream, select the first title */
1906 if (title->type == HB_STREAM_TYPE)
1908 [fSrcTitlePopUp selectItemAtIndex: 0];
1912 /* if not then select the main feature title */
1913 [fSrcTitlePopUp selectItemAtIndex: feature_title];
1915 [self titlePopUpChanged:nil];
1917 SuccessfulScan = YES;
1918 [self enableUI: YES];
1920 /* if its the initial successful scan after awakeFromNib */
1921 if (currentSuccessfulScanCount == 1)
1923 [self encodeStartStopPopUpChanged:nil];
1925 [self selectDefaultPreset:nil];
1927 // Open preview window now if it was visible when HB was closed
1928 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
1929 [self showPreviewWindow:nil];
1931 // Open picture sizing window now if it was visible when HB was closed
1932 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
1933 [self showPicturePanel:nil];
1936 if (applyQueueToScan == YES)
1938 /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
1939 [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
1940 [self applyQueueSettingsToMainWindow:nil];
1951 #pragma mark New Output Destination
1953 - (IBAction) browseFile: (id) sender
1955 /* Open a panel to let the user choose and update the text field */
1956 NSSavePanel * panel = [NSSavePanel savePanel];
1957 /* We get the current file name and path from the destination field here */
1958 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1959 modalForWindow: fWindow modalDelegate: self
1960 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1964 - (void) browseFileDone: (NSSavePanel *) sheet
1965 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1967 if( returnCode == NSOKButton )
1969 [fDstFile2Field setStringValue: [sheet filename]];
1970 /* Save this path to the prefs so that on next browse destination window it opens there */
1971 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1972 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1978 #pragma mark Main Window Control
1980 - (IBAction) openMainWindow: (id) sender
1982 [fWindow makeKeyAndOrderFront:nil];
1985 - (BOOL) windowShouldClose: (id) sender
1990 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1993 [fWindow makeKeyAndOrderFront:nil];
1998 - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
1999 [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
2004 #pragma mark Queue File
2006 - (void) loadQueueFile {
2007 /* We declare the default NSFileManager into fileManager */
2008 NSFileManager * fileManager = [NSFileManager defaultManager];
2009 /*We define the location of the user presets file */
2010 QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
2011 QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
2012 /* We check for the Queue.plist */
2013 if ([fileManager fileExistsAtPath:QueueFile] == 0)
2015 [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
2018 QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
2019 /* lets check to see if there is anything in the queue file .plist */
2020 if (nil == QueueFileArray)
2022 /* if not, then lets initialize an empty array */
2023 QueueFileArray = [[NSMutableArray alloc] init];
2027 /* ONLY clear out encoded items if we are single instance */
2028 if (hbInstanceNum == 1)
2030 [self clearQueueEncodedItems];
2035 - (void)addQueueFileItem
2037 [QueueFileArray addObject:[self createQueueFileItem]];
2038 [self saveQueueFileItem];
2042 - (void) removeQueueFileItem:(int) queueItemToRemove
2044 [QueueFileArray removeObjectAtIndex:queueItemToRemove];
2045 [self saveQueueFileItem];
2049 - (void)saveQueueFileItem
2051 [QueueFileArray writeToFile:QueueFile atomically:YES];
2052 [fQueueController setQueueArray: QueueFileArray];
2053 [self getQueueStats];
2056 - (void)getQueueStats
2058 /* lets get the stats on the status of the queue array */
2060 fEncodingQueueItem = 0;
2062 fCompletedCount = 0;
2066 /* We use a number system to set the encode status of the queue item
2068 * 0 == already encoded
2069 * 1 == is being encoded
2070 * 2 == is yet to be encoded
2075 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2077 while (tempObject = [enumerator nextObject])
2079 NSDictionary *thisQueueDict = tempObject;
2080 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
2084 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
2087 fEncodingQueueItem = i;
2088 /* check to see if we are the instance doing this encoding */
2089 if ([thisQueueDict objectForKey:@"EncodingPID"] && [[thisQueueDict objectForKey:@"EncodingPID"] intValue] == pidNum)
2091 currentQueueEncodeIndex = i;
2095 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
2099 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
2106 /* Set the queue status field in the main window */
2107 NSMutableString * string;
2108 if (fPendingCount == 0)
2110 string = [NSMutableString stringWithFormat: NSLocalizedString( @"No encode pending", @"" )];
2112 else if (fPendingCount == 1)
2114 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending", @"" ), fPendingCount];
2118 string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encodes pending", @"" ), fPendingCount];
2120 [fQueueStatus setStringValue:string];
2123 /* Used to get the next pending queue item index and return it if found */
2124 - (int)getNextPendingQueueIndex
2126 /* initialize nextPendingIndex to -1, this value tells incrementQueueItemDone that there are no pending items in the queue */
2127 int nextPendingIndex = -1;
2128 BOOL nextPendingFound = NO;
2129 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2132 while (tempObject = [enumerator nextObject])
2134 NSDictionary *thisQueueDict = tempObject;
2135 if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2 && nextPendingFound == NO) // pending
2137 nextPendingFound = YES;
2138 nextPendingIndex = [QueueFileArray indexOfObject: tempObject];
2139 [self writeToActivityLog: "getNextPendingQueueIndex next pending encode index is:%d", nextPendingIndex];
2143 return nextPendingIndex;
2147 /* This method will set any item marked as encoding back to pending
2148 * currently used right after a queue reload
2150 - (void) setQueueEncodingItemsAsPending
2152 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2154 NSMutableArray *tempArray;
2155 tempArray = [NSMutableArray array];
2156 /* we look here to see if the preset is we move on to the next one */
2157 while ( tempObject = [enumerator nextObject] )
2159 /* We want to keep any queue item that is pending or was previously being encoded */
2160 if ([[tempObject objectForKey:@"Status"] intValue] == 1 || [[tempObject objectForKey:@"Status"] intValue] == 2)
2162 /* If the queue item is marked as "encoding" (1)
2163 * then change its status back to pending (2) which effectively
2164 * puts it back into the queue to be encoded
2166 if ([[tempObject objectForKey:@"Status"] intValue] == 1)
2168 [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
2170 [tempArray addObject:tempObject];
2174 [QueueFileArray setArray:tempArray];
2175 [self saveQueueFileItem];
2179 /* This method will clear the queue of any encodes that are not still pending
2180 * this includes both successfully completed encodes as well as cancelled encodes */
2181 - (void) clearQueueEncodedItems
2183 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2185 NSMutableArray *tempArray;
2186 tempArray = [NSMutableArray array];
2187 /* we look here to see if the preset is we move on to the next one */
2188 while ( tempObject = [enumerator nextObject] )
2190 /* If the queue item is either completed (0) or cancelled (3) from the
2191 * last session, then we put it in tempArray to be deleted from QueueFileArray.
2192 * NOTE: this means we retain pending (2) and also an item that is marked as
2193 * still encoding (1). If the queue has an item that is still marked as encoding
2194 * from a previous session, we can conlude that HB was either shutdown, or crashed
2195 * during the encodes so we keep it and tell the user in the "Load Queue Alert"
2197 if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
2199 [tempArray addObject:tempObject];
2203 [QueueFileArray removeObjectsInArray:tempArray];
2204 [self saveQueueFileItem];
2207 /* This method will clear the queue of all encodes. effectively creating an empty queue */
2208 - (void) clearQueueAllItems
2210 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
2212 NSMutableArray *tempArray;
2213 tempArray = [NSMutableArray array];
2214 /* we look here to see if the preset is we move on to the next one */
2215 while ( tempObject = [enumerator nextObject] )
2217 [tempArray addObject:tempObject];
2220 [QueueFileArray removeObjectsInArray:tempArray];
2221 [self saveQueueFileItem];
2224 /* This method will duplicate prepareJob however into the
2225 * queue .plist instead of into the job structure so it can
2226 * be recalled later */
2227 - (NSDictionary *)createQueueFileItem
2229 NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
2231 hb_list_t * list = hb_get_titles( fHandle );
2232 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2233 [fSrcTitlePopUp indexOfSelectedItem] );
2234 hb_job_t * job = title->job;
2238 /* We use a number system to set the encode status of the queue item
2239 * 0 == already encoded
2240 * 1 == is being encoded
2241 * 2 == is yet to be encoded
2244 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
2245 /* Source and Destination Information */
2247 [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
2248 [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
2249 [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
2250 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
2252 /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
2253 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
2255 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
2257 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
2259 [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
2261 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
2263 [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
2265 /* Chapter encode info */
2266 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
2267 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
2268 /* Time (pts) encode info */
2269 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
2270 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
2271 /* Frame number encode info */
2272 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
2273 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
2276 /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
2277 int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
2278 [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
2280 [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
2282 /* Lets get the preset info if there is any */
2283 [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2284 [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2286 [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
2287 /* Chapter Markers*/
2288 /* If we have only one chapter or a title without chapters, set chapter markers to off */
2289 if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
2291 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
2295 [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
2298 /* We need to get the list of chapter names to put into an array and store
2299 * in our queue, so they can be reapplied in prepareJob when this queue
2300 * item comes up if Chapter Markers is set to on.
2303 NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
2304 int chaptercount = hb_list_count( fTitle->list_chapter );
2305 for( i = 0; i < chaptercount; i++ )
2307 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
2308 if( chapter != NULL )
2310 [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
2313 [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
2314 [ChapterNamesArray autorelease];
2316 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2317 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
2318 /* Mux mp4 with http optimization */
2319 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
2320 /* Add iPod uuid atom */
2321 [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
2325 [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
2326 /* x264 Option String */
2327 [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
2329 [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
2330 [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
2331 [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
2332 [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
2334 [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
2335 [queueFileJob setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
2337 /* 2 Pass Encoding */
2338 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
2339 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
2340 [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
2342 /* Picture Sizing */
2343 /* Use Max Picture settings for whatever the dvd is.*/
2344 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2345 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2346 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2347 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2348 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2349 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
2350 /* if we are custom anamorphic, store the exact storage, par and display dims */
2351 if (fTitle->job->anamorphic.mode == 3)
2353 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
2355 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
2356 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
2358 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
2359 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
2361 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
2362 [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
2365 NSString * pictureSummary;
2366 pictureSummary = [fPictureSizeField stringValue];
2367 [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
2368 /* Set crop settings here */
2369 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2370 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2371 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2372 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2373 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2375 /* Picture Filters */
2376 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
2377 [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
2379 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
2380 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
2381 [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
2383 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
2384 [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
2386 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
2387 [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
2389 [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
2391 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
2394 [fAudioDelegate prepareAudioForQueueFileJob: queueFileJob];
2397 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
2398 [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
2399 [subtitlesArray autorelease];
2401 /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
2403 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
2405 [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
2408 [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
2412 [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
2415 [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
2416 [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
2417 [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
2419 /* Picture Sizing */
2420 /* Use Max Picture settings for whatever the dvd is.*/
2421 [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
2422 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
2423 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
2424 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
2425 [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
2427 /* Set crop settings here */
2428 [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
2429 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
2430 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
2431 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
2432 [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
2436 /* we need to auto relase the queueFileJob and return it */
2437 [queueFileJob autorelease];
2438 return queueFileJob;
2442 /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
2443 - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
2445 NSUInteger index = [indexSet lastIndex];
2446 NSUInteger aboveInsertIndexCount = 0;
2449 NSUInteger removeIndex;
2451 if (index >= insertIndex)
2453 removeIndex = index + aboveInsertIndexCount;
2454 aboveInsertIndexCount++;
2458 removeIndex = index;
2462 id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
2463 [QueueFileArray removeObjectAtIndex:removeIndex];
2464 [QueueFileArray insertObject:object atIndex:insertIndex];
2467 index = [indexSet indexLessThanIndex:index];
2469 /* We save all of the Queue data here
2470 * and it also gets sent back to the queue controller*/
2471 [self saveQueueFileItem];
2477 #pragma mark Queue Job Processing
2479 - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
2481 /* Mark the encode just finished as done (status 0)*/
2482 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
2484 /* We save all of the Queue data here */
2485 [self saveQueueFileItem];
2487 /* Since we have now marked a queue item as done
2488 * we can go ahead and increment currentQueueEncodeIndex
2489 * so that if there is anything left in the queue we can
2490 * go ahead and move to the next item if we want to */
2491 int queueItems = [QueueFileArray count];
2492 /* Check to see if there are any more pending items in the queue */
2493 int newQueueItemIndex = [self getNextPendingQueueIndex];
2494 /* If we still have more pending items in our queue, lets go to the next one */
2495 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
2497 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
2498 currentQueueEncodeIndex = newQueueItemIndex;
2499 /* now we mark the queue item as Status = 1 ( being encoded ) so another instance can not come along and try to scan it while we are scanning */
2500 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2501 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
2502 [self saveQueueFileItem];
2503 /* now we can go ahead and scan the new pending queue item */
2504 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
2509 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
2510 /*Since there are no more items to encode, go to queueCompletedAlerts for user specified alerts after queue completed*/
2511 [self queueCompletedAlerts];
2515 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
2516 - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
2518 /* Tell HB to output a new activity log file for this encode */
2519 [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
2521 /* We now flag the queue item as being owned by this instance of HB using the PID */
2522 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:pidNum] forKey:@"EncodingPID"];
2523 /* Get the currentQueueEncodeNameString from the queue item to display in the status field */
2524 currentQueueEncodeNameString = [[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"] lastPathComponent]retain];
2525 /* We save all of the Queue data here */
2526 [self saveQueueFileItem];
2528 /* use a bool to determine whether or not we can decrypt using vlc */
2529 BOOL cancelScanDecrypt = 0;
2530 /* set the bool so that showNewScan knows to apply the appropriate queue
2531 * settings as this is a queue rescan
2533 NSString *path = scanPath;
2534 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
2536 if( [detector isVideoDVD] )
2538 // The chosen path was actually on a DVD, so use the raw block
2539 // device path instead.
2540 path = [detector devicePath];
2541 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
2543 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
2544 void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
2547 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
2548 cancelScanDecrypt = 1;
2549 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
2551 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");
2552 [NSApp requestUserAttention:NSCriticalRequest];
2554 if (status == NSAlertDefaultReturn)
2556 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
2557 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
2559 else if (status == NSAlertAlternateReturn)
2561 /* User chose to cancel the scan */
2562 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
2566 /* 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 */
2567 cancelScanDecrypt = 0;
2568 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
2574 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
2576 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
2580 if (cancelScanDecrypt == 0)
2582 /* we actually pass the scan off to libhb here */
2583 /* If there is no title number passed to scan, we use "0"
2584 * which causes the default behavior of a full source scan
2590 if (scanTitleNum > 0)
2592 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
2595 /* Only scan 10 previews before an encode - additional previews are only useful for autocrop and static previews,
2596 * which are already taken care of at this point */
2597 hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, 10, 0, 0 );
2601 /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
2602 - (void) processNewQueueEncode
2604 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
2605 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
2606 hb_job_t * job = title->job;
2608 if( !hb_list_count( list ) )
2610 [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
2613 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
2614 [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
2615 [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
2616 job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
2620 * If scanning we need to do some extra setup of the job.
2622 if( job->indepth_scan == 1 )
2627 * When subtitle scan is enabled do a fast pre-scan job
2628 * which will determine which subtitles to enable, if any.
2631 x264opts_tmp = job->x264opts;
2633 job->x264opts = NULL;
2635 job->indepth_scan = 1;
2639 * Add the pre-scan job
2641 hb_add( fQueueEncodeLibhb, job );
2642 job->x264opts = x264opts_tmp;
2646 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
2648 job->indepth_scan = 0;
2654 hb_add( fQueueEncodeLibhb, job );
2658 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
2659 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
2661 hb_add( fQueueEncodeLibhb, job );
2666 job->indepth_scan = 0;
2669 hb_add( fQueueEncodeLibhb, job );
2672 NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
2673 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
2674 /* Lets mark our new encode as 1 or "Encoding" */
2675 [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
2676 [self saveQueueFileItem];
2678 /* we need to clean up the subtitle tracks after the job(s) have been set */
2679 int num_subtitle_tracks = hb_list_count(job->list_subtitle);
2681 for(ii = 0; ii < num_subtitle_tracks; ii++)
2683 hb_subtitle_t * subtitle;
2684 subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
2687 hb_list_rem(job->list_subtitle, subtitle);
2691 /* We should be all setup so let 'er rip */
2696 #pragma mark Queue Item Editing
2698 /* Rescans the chosen queue item back into the main window */
2699 - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
2701 fqueueEditRescanItemNum = selectedQueueItem;
2702 [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
2703 applyQueueToScan = YES;
2704 /* Make sure we release the display name before reassigning it */
2705 [browsedSourceDisplayName release];
2706 /* Set the browsedSourceDisplayName for showNewScan */
2707 browsedSourceDisplayName = [[[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"] retain];
2708 [self performScan:scanPath scanTitleNum:scanTitleNum];
2712 /* We use this method after a queue item rescan for edit.
2713 * it largely mirrors -selectPreset in terms of structure.
2714 * Assumes that a queue item has been reloaded into the main window.
2716 - (IBAction)applyQueueSettingsToMainWindow:(id)sender
2718 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
2719 hb_job_t * job = fTitle->job;
2722 [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
2724 /* Set title number and chapters */
2725 /* since the queue only scans a single title, its already been selected in showNewScan
2726 so do not try to reset it here. However if we do decide to do full source scans on
2727 a queue edit rescan, we would need it. So leaving in for now but commenting out. */
2728 //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
2730 [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
2731 [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
2734 [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
2735 [self formatPopUpChanged:nil];
2737 /* Chapter Markers*/
2738 [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
2739 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
2740 [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
2741 /* Mux mp4 with http optimization */
2742 [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
2745 /* We set the advanced opt string here if applicable*/
2746 [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
2747 [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
2749 /* Lets run through the following functions to get variables set there */
2750 [self videoEncoderPopUpChanged:nil];
2751 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
2752 [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
2753 [self calculateBitrate:nil];
2756 [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
2758 [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
2759 [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
2760 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
2761 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
2762 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
2763 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
2764 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
2765 if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
2767 /* For the quality slider we need to convert the old percent's to the new rf scales */
2768 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
2769 [fVidQualitySlider setFloatValue:rf];
2774 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
2775 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
2777 [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2781 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
2782 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
2786 [self videoMatrixChanged:nil];
2788 /* Video framerate */
2789 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
2790 detected framerate in the fVidRatePopUp so we use index 0*/
2791 if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
2793 [fVidRatePopUp selectItemAtIndex: 0];
2797 [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
2800 /* 2 Pass Encoding */
2801 [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
2802 [self twoPassCheckboxChanged:nil];
2803 /* Turbo 1st pass for 2 Pass Encoding */
2804 [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
2809 /* Now lets add our new tracks to the audio list here */
2810 [fAudioDelegate addTracksFromQueue: queueToApply];
2813 /* Crashy crashy right now, working on it */
2814 [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
2815 [fSubtitlesTable reloadData];
2816 /* Picture Settings */
2818 /* If Cropping is set to custom, then recall all four crop values from
2819 when the preset was created and apply them */
2820 if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
2822 [fPictureController setAutoCrop:NO];
2824 /* Here we use the custom crop values saved at the time the preset was saved */
2825 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
2826 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
2827 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
2828 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
2831 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
2833 [fPictureController setAutoCrop:YES];
2834 /* Here we use the auto crop values determined right after scan */
2835 job->crop[0] = AutoCropTop;
2836 job->crop[1] = AutoCropBottom;
2837 job->crop[2] = AutoCropLeft;
2838 job->crop[3] = AutoCropRight;
2842 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2844 /* we check to make sure the presets width/height does not exceed the sources width/height */
2845 if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
2847 /* if so, then we use the sources height and width to avoid scaling up */
2848 //job->width = fTitle->width;
2849 //job->height = fTitle->height;
2850 [self revertPictureSizeToMax:nil];
2852 else // source width/height is >= the preset height/width
2854 /* we can go ahead and use the presets values for height and width */
2855 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
2856 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
2858 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
2859 if (job->keep_ratio == 1)
2861 hb_fix_aspect( job, HB_KEEP_WIDTH );
2862 if( job->height > fTitle->height )
2864 job->height = fTitle->height;
2865 hb_fix_aspect( job, HB_KEEP_HEIGHT );
2868 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
2869 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
2873 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
2874 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
2875 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
2878 [fPictureController setUseDecomb:1];
2879 [fPictureController setDecomb:0];
2880 [fPictureController setDeinterlace:0];
2881 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2883 /* we are using decomb */
2885 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
2887 [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
2889 /* if we are using "Custom" in the decomb setting, also set the custom string*/
2890 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
2892 [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
2898 /* We are using Deinterlace */
2900 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
2902 [fPictureController setUseDecomb:0];
2903 [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
2904 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
2905 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
2907 [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
2914 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
2916 [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
2917 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
2918 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
2920 [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
2925 [fPictureController setDetelecine:0];
2929 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
2931 [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
2932 /* if we are using "Custom" in the denoise setting, also set the custom string*/
2933 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
2935 [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
2940 [fPictureController setDenoise:0];
2944 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
2946 /* if its a one, then its the old on/off deblock, set on to 5*/
2947 [fPictureController setDeblock:5];
2951 /* use the settings intValue */
2952 [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
2955 if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
2957 [fPictureController setGrayscale:1];
2961 [fPictureController setGrayscale:0];
2964 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
2965 [fPictureController SetTitle:fTitle];
2966 [self calculatePictureSizing:nil];
2968 /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
2969 //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
2970 //[queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
2971 if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
2973 /* Deselect the currently selected Preset if there is one*/
2974 //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
2975 //[self selectPreset:nil];
2977 //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
2978 /* Change UI to show "Custom" settings are being used */
2979 //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
2981 curUserPresetChosenNum = nil;
2985 /* Deselect the currently selected Preset if there is one*/
2986 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2987 /* Change UI to show "Custom" settings are being used */
2988 [fPresetSelectedDisplay setStringValue: @"Custom"];
2990 //curUserPresetChosenNum = nil;
2993 /* We need to set this bool back to NO, in case the user wants to do a scan */
2994 //applyQueueToScan = NO;
2996 /* Not that source is loaded and settings applied, delete the queue item from the queue */
2997 [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
2998 [self removeQueueFileItem:fqueueEditRescanItemNum];
3004 #pragma mark Live Preview
3005 /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
3006 * can encode to its temp preview directory and playback. This is *not* used for any actual user
3009 - (void) prepareJobForPreview
3011 hb_list_t * list = hb_get_titles( fHandle );
3012 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3013 [fSrcTitlePopUp indexOfSelectedItem] );
3014 hb_job_t * job = title->job;
3015 hb_audio_config_t * audio;
3016 /* set job->angle for libdvdnav */
3017 job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
3018 /* Chapter selection */
3019 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
3020 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
3022 /* Format (Muxer) and Video Encoder */
3023 job->mux = [[fDstFormatPopUp selectedItem] tag];
3024 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
3026 job->chapter_markers = 0;
3028 if( job->vcodec & HB_VCODEC_X264 )
3031 /* Below Sends x264 options to the core library if x264 is selected*/
3032 /* Lets use this as per Nyx, Thanks Nyx!*/
3033 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3034 /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
3035 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
3040 /* Video settings */
3041 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3042 * and detelecine is on, so we handle that in the logic below
3045 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
3047 /* a specific framerate has been chosen */
3048 job->vrate = 27000000;
3049 job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
3050 /* We are not same as source so we set job->cfr to 1
3051 * to enable constant frame rate since user has specified
3052 * a specific framerate*/
3053 if ([fFrameratePfrCheck state] == 1)
3064 /* We are same as source (variable) */
3065 job->vrate = title->rate;
3066 job->vrate_base = title->rate_base;
3067 /* We are same as source so we set job->cfr to 0
3068 * to enable true same as source framerate */
3070 /* If we are same as source and we have detelecine on, we need to turn on
3073 if ([fPictureController detelecine] == 1)
3079 switch( [fVidQualityMatrix selectedRow] )
3083 Bitrate should already have been calculated and displayed
3084 in fVidBitrateField, so let's just use it */
3086 job->vquality = -1.0;
3087 job->vbitrate = [fVidBitrateField intValue];
3090 job->vquality = [fVidQualityRFField floatValue];
3095 /* Subtitle settings */
3096 NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
3103 bool one_burned = FALSE;
3106 NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
3108 while (tempObject = [enumerator nextObject])
3111 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3112 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3113 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3114 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3116 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3117 * we want to ignore it for display as well as encoding.
3121 /* if i is 0, then we are in the first item of the subtitles which we need to
3122 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3123 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3126 /* if we are on the first track and using "Foreign Audio Search" */
3127 if (i == 0 && subtitle == 1)
3129 /* NOTE: Currently foreign language search is borked for preview.
3130 * Commented out but left in for initial commit. */
3133 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3135 job->indepth_scan = 1;
3139 job->select_subtitle_config.dest = PASSTHRUSUB;
3143 job->select_subtitle_config.dest = RENDERSUB;
3146 job->select_subtitle_config.force = force;
3147 job->select_subtitle_config.default_track = def;
3152 /* for the actual source tracks, we must subtract the non source entries so
3153 * that the menu index matches the source subtitle_list index for convenience */
3156 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3157 * Foreign Language Search is 1) so subtract 2 */
3158 subtitle = subtitle - 2;
3162 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3165 subtitle = subtitle - 1;
3168 /* We are setting a source subtitle so access the source subtitle info */
3169 hb_subtitle_t * subt;
3171 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3173 /* if we are getting the subtitles from an external srt file */
3174 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3176 hb_subtitle_config_t sub_config;
3178 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3180 /* we need to srncpy file path and char code */
3181 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 255);
3182 sub_config.src_filename[255] = 0;
3183 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 39);
3184 sub_config.src_codeset[39] = 0;
3186 sub_config.force = 0;
3187 sub_config.dest = PASSTHRUSUB;
3188 sub_config.default_track = def;
3190 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3195 hb_subtitle_config_t sub_config = subt->config;
3197 if ( !burned && subt->format == PICTURESUB )
3199 sub_config.dest = PASSTHRUSUB;
3201 else if ( burned && subt->format == PICTURESUB )
3203 // Only allow one subtitle to be burned into the video
3209 /* Besides VOBSUBS we can also burn in SSA text subs */
3210 if (subt->source == SSASUB && burned)
3212 sub_config.dest = RENDERSUB;
3215 sub_config.force = force;
3216 sub_config.default_track = def;
3217 hb_subtitle_add( job, &sub_config, subtitle );
3227 [subtitlesArray autorelease];
3230 /* Audio tracks and mixdowns */
3231 [fAudioDelegate prepareAudioForJob: job];
3237 /* Though Grayscale is not really a filter, per se
3238 * we put it here since its in the filters panel
3241 if ([fPictureController grayscale])
3250 /* Initialize the filters list */
3251 job->filters = hb_list_init();
3253 /* Now lets call the filters if applicable.
3254 * The order of the filters is critical
3258 hb_filter_detelecine.settings = NULL;
3259 if ([fPictureController detelecine] == 1)
3261 /* use a custom detelecine string */
3262 hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
3263 hb_list_add( job->filters, &hb_filter_detelecine );
3265 if ([fPictureController detelecine] == 2)
3268 hb_list_add( job->filters, &hb_filter_detelecine );
3273 if ([fPictureController useDecomb] == 1)
3276 /* we add the custom string if present */
3277 hb_filter_decomb.settings = NULL;
3278 if ([fPictureController decomb] == 1)
3280 /* use a custom decomb string */
3281 hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
3282 hb_list_add( job->filters, &hb_filter_decomb );
3284 if ([fPictureController decomb] == 2)
3286 /* Run old deinterlacer fd by default */
3287 //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
3288 hb_list_add( job->filters, &hb_filter_decomb );
3295 if ([fPictureController deinterlace] == 1)
3297 /* we add the custom string if present */
3298 hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
3299 hb_list_add( job->filters, &hb_filter_deinterlace );
3301 else if ([fPictureController deinterlace] == 2)
3303 /* Run old deinterlacer fd by default */
3304 hb_filter_deinterlace.settings = "-1";
3305 hb_list_add( job->filters, &hb_filter_deinterlace );
3307 else if ([fPictureController deinterlace] == 3)
3309 /* Yadif mode 0 (without spatial deinterlacing.) */
3310 hb_filter_deinterlace.settings = "2";
3311 hb_list_add( job->filters, &hb_filter_deinterlace );
3313 else if ([fPictureController deinterlace] == 4)
3315 /* Yadif (with spatial deinterlacing) */
3316 hb_filter_deinterlace.settings = "0";
3317 hb_list_add( job->filters, &hb_filter_deinterlace );
3323 if ([fPictureController denoise] == 1) // custom in popup
3325 /* we add the custom string if present */
3326 hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
3327 hb_list_add( job->filters, &hb_filter_denoise );
3329 else if ([fPictureController denoise] == 2) // Weak in popup
3331 hb_filter_denoise.settings = "2:1:2:3";
3332 hb_list_add( job->filters, &hb_filter_denoise );
3334 else if ([fPictureController denoise] == 3) // Medium in popup
3336 hb_filter_denoise.settings = "3:2:2:3";
3337 hb_list_add( job->filters, &hb_filter_denoise );
3339 else if ([fPictureController denoise] == 4) // Strong in popup
3341 hb_filter_denoise.settings = "7:7:5:5";
3342 hb_list_add( job->filters, &hb_filter_denoise );
3346 /* Deblock (uses pp7 default) */
3347 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3348 * the macgui's purposes a value of 0 actually means to not even use the filter
3349 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3351 if ([fPictureController deblock] != 0)
3353 NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
3354 hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
3355 hb_list_add( job->filters, &hb_filter_deblock );
3362 #pragma mark Job Handling
3368 NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
3369 hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
3370 hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
3371 hb_job_t * job = title->job;
3372 hb_audio_config_t * audio;
3373 /* Title Angle for dvdnav */
3374 job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
3376 if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
3378 /* Chapter selection */
3379 [self writeToActivityLog: "Start / Stop set to chapters"];
3380 job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
3381 job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
3383 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
3385 /* we are pts based start / stop */
3386 [self writeToActivityLog: "Start / Stop set to seconds ..."];
3388 /* Point A to Point B. Time to time in seconds.*/
3389 /* get the start seconds from the start seconds field */
3390 int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
3391 job->pts_to_start = start_seconds * 90000LL;
3392 /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
3393 int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
3394 job->pts_to_stop = stop_seconds * 90000LL;
3397 else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
3399 /* we are frame based start / stop */
3400 [self writeToActivityLog: "Start / Stop set to frames ..."];
3402 /* Point A to Point B. Frame to frame */
3403 /* get the start frame from the start frame field */
3404 int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
3405 job->frame_to_start = start_frame;
3406 /* get the frame to stop on from the end frame field */
3407 int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
3408 job->frame_to_stop = stop_frame;
3415 /* Format (Muxer) and Video Encoder */
3416 job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
3417 job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
3420 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
3421 if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
3423 job->largeFileSize = 1;
3427 job->largeFileSize = 0;
3429 /* We set http optimized mp4 here */
3430 if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
3432 job->mp4_optimize = 1;
3436 job->mp4_optimize = 0;
3440 /* We set the chapter marker extraction here based on the format being
3441 mpeg4 or mkv and the checkbox being checked */
3442 if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
3444 job->chapter_markers = 1;
3446 /* now lets get our saved chapter names out the array in the queue file
3447 * and insert them back into the title chapter list. We have it here,
3448 * because unless we are inserting chapter markers there is no need to
3449 * spend the overhead of iterating through the chapter names array imo
3450 * Also, note that if for some reason we don't apply chapter names, the
3451 * chapters just come out 001, 002, etc. etc.
3454 NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
3456 NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
3458 while (tempObject = [enumerator nextObject])
3460 hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
3461 if( chapter != NULL )
3463 strncpy( chapter->title, [tempObject UTF8String], 1023);
3464 chapter->title[1023] = '\0';
3471 job->chapter_markers = 0;
3474 if( job->vcodec & HB_VCODEC_X264 )
3476 if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
3486 /* Below Sends x264 options to the core library if x264 is selected*/
3487 /* Lets use this as per Nyx, Thanks Nyx!*/
3488 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
3489 /* Turbo first pass if two pass and Turbo First pass is selected */
3490 if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
3492 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
3493 NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
3494 /* append the "Turbo" string variable to the existing opts string.
3495 Note: the "Turbo" string must be appended, not prepended to work properly*/
3496 NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
3497 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
3501 strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
3507 /* Picture Size Settings */
3508 job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
3509 job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
3511 job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
3512 job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
3513 job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
3514 if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
3516 /* insert our custom values here for capuj */
3517 job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
3518 job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
3520 job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
3522 job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
3523 job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
3525 job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
3526 job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
3529 /* Here we use the crop values saved at the time the preset was saved */
3530 job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
3531 job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
3532 job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
3533 job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
3535 /* Video settings */
3538 /* Set vfr to 0 as it's only on if using same as source in the framerate popup
3539 * and detelecine is on, so we handle that in the logic below
3542 if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
3544 /* a specific framerate has been chosen */
3545 job->vrate = 27000000;
3546 job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
3547 /* We are not same as source so we set job->cfr to 1
3548 * to enable constant frame rate since user has specified
3549 * a specific framerate*/
3551 if ([[queueToApply objectForKey:@"VideoFrameratePFR"] intValue] == 1)
3562 /* We are same as source (variable) */
3563 job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
3564 job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
3565 /* We are same as source so we set job->cfr to 0
3566 * to enable true same as source framerate */
3568 /* If we are same as source and we have detelecine on, we need to turn on
3571 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3577 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
3580 Bitrate should already have been calculated and displayed
3581 in fVidBitrateField, so let's just use it same as abr*/
3582 job->vquality = -1.0;
3583 job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
3585 if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
3587 job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
3592 job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
3597 #pragma mark Process Subtitles to libhb
3599 /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
3600 * which means that we need to account for the offset of non source language settings in from
3601 * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
3602 * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
3603 * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
3604 * to the source tracks position in title->list_subtitle.
3611 bool one_burned = FALSE;
3614 NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
3616 while (tempObject = [enumerator nextObject])
3619 subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
3620 force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
3621 burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
3622 def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
3624 /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
3625 * we want to ignore it for display as well as encoding.
3629 /* if i is 0, then we are in the first item of the subtitles which we need to
3630 * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
3631 * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
3634 /* if we are on the first track and using "Foreign Audio Search" */
3635 if (i == 0 && subtitle == 1)
3637 [self writeToActivityLog: "Foreign Language Search: %d", 1];
3639 job->indepth_scan = 1;
3643 job->select_subtitle_config.dest = PASSTHRUSUB;
3647 job->select_subtitle_config.dest = RENDERSUB;
3650 job->select_subtitle_config.force = force;
3651 job->select_subtitle_config.default_track = def;
3656 /* for the actual source tracks, we must subtract the non source entries so
3657 * that the menu index matches the source subtitle_list index for convenience */
3660 /* for the first track, the source tracks start at menu index 2 ( None is 0,
3661 * Foreign Language Search is 1) so subtract 2 */
3662 subtitle = subtitle - 2;
3666 /* for all other tracks, the source tracks start at menu index 1 (None is 0)
3669 subtitle = subtitle - 1;
3672 /* We are setting a source subtitle so access the source subtitle info */
3673 hb_subtitle_t * subt;
3675 subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
3677 /* if we are getting the subtitles from an external srt file */
3678 if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
3680 hb_subtitle_config_t sub_config;
3682 sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
3684 /* we need to srncpy file name and codeset */
3685 strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
3686 strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
3688 sub_config.force = 0;
3689 sub_config.dest = PASSTHRUSUB;
3690 sub_config.default_track = def;
3692 hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
3698 hb_subtitle_config_t sub_config = subt->config;
3700 if ( !burned && subt->format == PICTURESUB )
3702 sub_config.dest = PASSTHRUSUB;
3706 // Only allow one subtitle to be burned into the video
3712 /* Besides VOBSUBS we can also burn in SSA text subs */
3713 if (subt->source == SSASUB && burned)
3715 sub_config.dest = RENDERSUB;
3718 sub_config.force = force;
3719 sub_config.default_track = def;
3720 hb_subtitle_add( job, &sub_config, subtitle );
3731 /* Audio tracks and mixdowns */
3732 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
3733 int audiotrack_count = hb_list_count(job->list_audio);
3734 for( int i = 0; i < audiotrack_count;i++)
3736 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
3737 hb_list_rem(job->list_audio, temp_audio);
3739 /* Now lets add our new tracks to the audio list here */
3740 for (unsigned int counter = 0; counter < maximumNumberOfAllowedAudioTracks; counter++) {
3741 NSString *prefix = [NSString stringWithFormat: @"Audio%d", counter + 1];
3742 if ([[queueToApply objectForKey: [prefix stringByAppendingString: @"Track"]] intValue] > 0) {
3743 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
3744 hb_audio_config_init(audio);
3745 audio->in.track = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Track"]] intValue] - 1;
3746 /* We go ahead and assign values to our audio->out.<properties> */
3747 audio->out.track = audio->in.track;
3748 audio->out.dynamic_range_compression = [[queueToApply objectForKey: [prefix stringByAppendingString: @"TrackDRCSlider"]] floatValue];
3749 prefix = [NSString stringWithFormat: @"JobAudio%d", counter + 1];
3750 audio->out.codec = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Encoder"]] intValue];
3751 audio->out.mixdown = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Mixdown"]] intValue];
3752 audio->out.bitrate = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Bitrate"]] intValue];
3753 audio->out.samplerate = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Samplerate"]] intValue];
3755 hb_audio_add( job, audio );
3761 job->filters = hb_list_init();
3763 /* Now lets call the filters if applicable.
3764 * The order of the filters is critical
3767 hb_filter_detelecine.settings = NULL;
3768 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
3770 /* use a custom detelecine string */
3771 hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
3772 hb_list_add( job->filters, &hb_filter_detelecine );
3774 if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
3776 /* Use libhb's default values */
3777 hb_list_add( job->filters, &hb_filter_detelecine );
3780 if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
3783 /* we add the custom string if present */
3784 hb_filter_decomb.settings = NULL;
3785 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
3787 /* use a custom decomb string */
3788 hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
3789 hb_list_add( job->filters, &hb_filter_decomb );
3791 if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
3793 /* Use libhb default */
3794 hb_list_add( job->filters, &hb_filter_decomb );
3802 if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
3804 /* we add the custom string if present */
3805 hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
3806 hb_list_add( job->filters, &hb_filter_deinterlace );
3808 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
3810 /* Run old deinterlacer fd by default */
3811 hb_filter_deinterlace.settings = "-1";
3812 hb_list_add( job->filters, &hb_filter_deinterlace );
3814 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
3816 /* Yadif mode 0 (without spatial deinterlacing.) */
3817 hb_filter_deinterlace.settings = "2";
3818 hb_list_add( job->filters, &hb_filter_deinterlace );
3820 else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
3822 /* Yadif (with spatial deinterlacing) */
3823 hb_filter_deinterlace.settings = "0";
3824 hb_list_add( job->filters, &hb_filter_deinterlace );
3830 if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
3832 /* we add the custom string if present */
3833 hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
3834 hb_list_add( job->filters, &hb_filter_denoise );
3836 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
3838 hb_filter_denoise.settings = "2:1:2:3";
3839 hb_list_add( job->filters, &hb_filter_denoise );
3841 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
3843 hb_filter_denoise.settings = "3:2:2:3";
3844 hb_list_add( job->filters, &hb_filter_denoise );
3846 else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
3848 hb_filter_denoise.settings = "7:7:5:5";
3849 hb_list_add( job->filters, &hb_filter_denoise );
3853 /* Deblock (uses pp7 default) */
3854 /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
3855 * the macgui's purposes a value of 0 actually means to not even use the filter
3856 * current hb_filter_deblock.settings valid ranges are from 5 - 15
3858 if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
3860 hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
3861 hb_list_add( job->filters, &hb_filter_deblock );
3863 [self writeToActivityLog: "prepareJob exiting"];
3868 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
3870 - (IBAction) addToQueue: (id) sender
3872 /* We get the destination directory from the destination field here */
3873 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3874 /* We check for a valid destination here */
3875 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3877 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3884 BOOL fileExistsInQueue;
3885 fileExistsInQueue = NO;
3887 /* We check for and existing file here */
3888 if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
3893 /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
3895 NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
3897 while (tempObject = [enumerator nextObject])
3899 NSDictionary *thisQueueDict = tempObject;
3900 if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
3902 fileExistsInQueue = YES;
3908 if(fileExists == YES)
3910 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
3911 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3912 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3913 NULL, NULL, [NSString stringWithFormat:
3914 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3915 [fDstFile2Field stringValue]] );
3917 else if (fileExistsInQueue == YES)
3919 NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
3920 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3921 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
3922 NULL, NULL, [NSString stringWithFormat:
3923 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3924 [fDstFile2Field stringValue]] );
3928 [self doAddToQueue];
3932 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
3933 the user if they want to overwrite an exiting movie file.
3935 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
3936 returnCode: (int) returnCode contextInfo: (void *) contextInfo
3938 if( returnCode == NSAlertAlternateReturn )
3939 [self doAddToQueue];
3942 - (void) doAddToQueue
3944 [self addQueueFileItem ];
3949 /* Rip: puts up an alert before ultimately calling doRip
3951 - (IBAction) Rip: (id) sender
3953 [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
3954 /* Rip or Cancel ? */
3956 hb_get_state2( fQueueEncodeLibhb, &s );
3958 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
3960 [self Cancel: sender];
3964 /* We check to see if we need to warn the user that the computer will go to sleep
3965 or shut down when encoding is finished */
3966 [self remindUserOfSleepOrShutdown];
3968 // If there are pending jobs in the queue, then this is a rip the queue
3969 if (fPendingCount > 0)
3971 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
3972 /* here lets start the queue with the first pending item */
3973 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
3978 // Before adding jobs to the queue, check for a valid destination.
3980 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
3981 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
3983 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
3987 /* We check for duplicate name here */
3988 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
3990 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
3991 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
3992 @selector( overWriteAlertDone:returnCode:contextInfo: ),
3993 NULL, NULL, [NSString stringWithFormat:
3994 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
3995 [fDstFile2Field stringValue]] );
3997 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
4001 /* if there are no pending jobs in the queue, then add this one to the queue and rip
4002 otherwise, just rip the queue */
4003 if(fPendingCount == 0)
4005 [self doAddToQueue];
4008 /* go right to processing the new queue encode */
4009 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4010 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4015 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
4016 want to overwrite an exiting movie file.
4018 - (void) overWriteAlertDone: (NSWindow *) sheet
4019 returnCode: (int) returnCode contextInfo: (void *) contextInfo
4021 if( returnCode == NSAlertAlternateReturn )
4023 /* if there are no jobs in the queue, then add this one to the queue and rip
4024 otherwise, just rip the queue */
4025 if( fPendingCount == 0 )
4027 [self doAddToQueue];
4030 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
4031 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
4032 currentQueueEncodeIndex = [self getNextPendingQueueIndex];
4033 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4038 - (void) remindUserOfSleepOrShutdown
4040 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
4042 /*Warn that computer will sleep after encoding*/
4045 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);
4046 [NSApp requestUserAttention:NSCriticalRequest];
4047 if ( reminduser == NSAlertAlternateReturn )
4049 [self showPreferencesWindow:nil];
4052 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
4054 /*Warn that computer will shut down after encoding*/
4057 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);
4058 [NSApp requestUserAttention:NSCriticalRequest];
4059 if ( reminduser == NSAlertAlternateReturn )
4061 [self showPreferencesWindow:nil];
4070 /* Let libhb do the job */
4071 hb_start( fQueueEncodeLibhb );
4072 /*set the fEncodeState State */
4077 //------------------------------------------------------------------------------------
4078 // Displays an alert asking user if the want to cancel encoding of current job.
4079 // Cancel: returns immediately after posting the alert. Later, when the user
4080 // acknowledges the alert, doCancelCurrentJob is called.
4081 //------------------------------------------------------------------------------------
4082 - (IBAction)Cancel: (id)sender
4084 if (!fQueueController) return;
4086 hb_pause( fQueueEncodeLibhb );
4087 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
4089 // Which window to attach the sheet to?
4090 NSWindow * docWindow;
4091 if ([sender respondsToSelector: @selector(window)])
4092 docWindow = [sender window];
4094 docWindow = fWindow;
4096 NSBeginCriticalAlertSheet(
4098 NSLocalizedString(@"Continue Encoding", nil),
4099 NSLocalizedString(@"Cancel Current and Stop", nil),
4100 NSLocalizedString(@"Cancel Current and Continue", nil),
4102 nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
4103 NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
4105 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
4108 - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
4110 hb_resume( fQueueEncodeLibhb );
4111 if (returnCode == NSAlertOtherReturn)
4113 [self doCancelCurrentJob]; // <- this also stops libhb
4115 if (returnCode == NSAlertAlternateReturn)
4117 [self doCancelCurrentJobAndStop];
4121 //------------------------------------------------------------------------------------
4122 // Cancels and deletes the current job and stops libhb from processing the remaining
4124 //------------------------------------------------------------------------------------
4125 - (void) doCancelCurrentJob
4127 // Stop the current job. hb_stop will only cancel the current pass and then set
4128 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
4129 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
4130 // remaining passes of the job and then start the queue back up if there are any
4134 hb_stop( fQueueEncodeLibhb );
4136 // Delete all remaining jobs since libhb doesn't do this on its own.
4138 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4139 hb_rem( fQueueEncodeLibhb, job );
4141 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4143 // now that we've stopped the currently encoding job, lets mark it as cancelled
4144 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4145 // and as always, save it in the queue .plist...
4146 /* We save all of the Queue data here */
4147 [self saveQueueFileItem];
4149 // ... and see if there are more items left in our queue
4150 int queueItems = [QueueFileArray count];
4151 /* If we still have more items in our queue, lets go to the next one */
4152 /* Check to see if there are any more pending items in the queue */
4153 int newQueueItemIndex = [self getNextPendingQueueIndex];
4154 /* If we still have more pending items in our queue, lets go to the next one */
4155 if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
4157 /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
4158 currentQueueEncodeIndex = newQueueItemIndex;
4159 /* now we mark the queue item as Status = 1 ( being encoded ) so another instance can not come along and try to scan it while we are scanning */
4160 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
4161 [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
4162 [self saveQueueFileItem];
4163 /* now we can go ahead and scan the new pending queue item */
4164 [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
4169 [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
4173 - (void) doCancelCurrentJobAndStop
4175 hb_stop( fQueueEncodeLibhb );
4177 // Delete all remaining jobs since libhb doesn't do this on its own.
4179 while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
4180 hb_rem( fQueueEncodeLibhb, job );
4183 fEncodeState = 2; // don't alert at end of processing since this was a cancel
4185 // now that we've stopped the currently encoding job, lets mark it as cancelled
4186 [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
4187 // and as always, save it in the queue .plist...
4188 /* We save all of the Queue data here */
4189 [self saveQueueFileItem];
4190 // so now lets move to
4191 currentQueueEncodeIndex++ ;
4192 [self writeToActivityLog: "cancelling current job and stopping the queue"];
4194 - (IBAction) Pause: (id) sender
4197 hb_get_state2( fQueueEncodeLibhb, &s );
4199 if( s.state == HB_STATE_PAUSED )
4201 hb_resume( fQueueEncodeLibhb );
4205 hb_pause( fQueueEncodeLibhb );
4210 #pragma mark GUI Controls Changed Methods
4212 - (IBAction) titlePopUpChanged: (id) sender
4214 hb_list_t * list = hb_get_titles( fHandle );
4215 hb_title_t * title = (hb_title_t*)
4216 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4218 /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
4219 if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
4221 /* we set the default name according to the new title->name */
4222 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4223 @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4224 [NSString stringWithUTF8String: title->name],
4225 [[fDstFile2Field stringValue] pathExtension]]];
4227 /* Change the source to read out the parent folder also */
4228 [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
4231 /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
4232 int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
4233 [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
4234 [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
4235 /* 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 */
4236 [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
4237 //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
4238 [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
4240 /* If Auto Naming is on. We create an output filename of dvd name - title number */
4241 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
4243 [fDstFile2Field setStringValue: [NSString stringWithFormat:
4244 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
4245 [browsedSourceDisplayName stringByDeletingPathExtension],
4247 [[fDstFile2Field stringValue] pathExtension]]];
4249 /* Update encode start / stop variables */
4253 /* Update chapter popups */
4254 [fSrcChapterStartPopUp removeAllItems];
4255 [fSrcChapterEndPopUp removeAllItems];
4256 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
4258 [fSrcChapterStartPopUp addItemWithTitle: [NSString
4259 stringWithFormat: @"%d", i + 1]];
4260 [fSrcChapterEndPopUp addItemWithTitle: [NSString
4261 stringWithFormat: @"%d", i + 1]];
4264 [fSrcChapterStartPopUp selectItemAtIndex: 0];
4265 [fSrcChapterEndPopUp selectItemAtIndex:
4266 hb_list_count( title->list_chapter ) - 1];
4267 [self chapterPopUpChanged:nil];
4269 /* if using dvd nav, show the angle widget */
4270 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
4272 [fSrcAngleLabel setHidden:NO];
4273 [fSrcAnglePopUp setHidden:NO];
4275 [fSrcAnglePopUp removeAllItems];
4276 for( int i = 0; i < title->angle_count; i++ )
4278 [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
4280 [fSrcAnglePopUp selectItemAtIndex: 0];
4284 [fSrcAngleLabel setHidden:YES];
4285 [fSrcAnglePopUp setHidden:YES];
4288 /* Start Get and set the initial pic size for display */
4289 hb_job_t * job = title->job;
4292 /* Set Auto Crop to on upon selecting a new title */
4293 [fPictureController setAutoCrop:YES];
4295 /* We get the originial output picture width and height and put them
4296 in variables for use with some presets later on */
4297 PicOrigOutputWidth = job->width;
4298 PicOrigOutputHeight = job->height;
4299 AutoCropTop = job->crop[0];
4300 AutoCropBottom = job->crop[1];
4301 AutoCropLeft = job->crop[2];
4302 AutoCropRight = job->crop[3];
4304 /* Reset the new title in fPictureController && fPreviewController*/
4305 [fPictureController SetTitle:title];
4308 /* Update Subtitle Table */
4309 [fSubtitlesDelegate resetWithTitle:title];
4310 [fSubtitlesTable reloadData];
4313 /* Update chapter table */
4314 [fChapterTitlesDelegate resetWithTitle:title];
4315 [fChapterTable reloadData];
4317 /* Update audio table */
4318 [[NSNotificationCenter defaultCenter] postNotification:
4319 [NSNotification notificationWithName: HBTitleChangedNotification
4321 userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
4322 [NSData dataWithBytesNoCopy: &fTitle length: sizeof(fTitle) freeWhenDone: NO], keyTitleTag,
4325 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
4326 int audiotrack_count = hb_list_count(job->list_audio);
4327 for( int i = 0; i < audiotrack_count;i++)
4329 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
4330 hb_list_rem(job->list_audio, temp_audio);
4334 [fVidRatePopUp selectItemAtIndex: 0];
4336 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
4337 [self calculatePictureSizing:nil];
4339 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
4340 [self selectPreset:nil];
4343 - (IBAction) encodeStartStopPopUpChanged: (id) sender;
4345 if( [fEncodeStartStopPopUp isEnabled] )
4347 /* We are chapters */
4348 if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
4350 [fSrcChapterStartPopUp setHidden: NO];
4351 [fSrcChapterEndPopUp setHidden: NO];
4353 [fSrcTimeStartEncodingField setHidden: YES];
4354 [fSrcTimeEndEncodingField setHidden: YES];
4356 [fSrcFrameStartEncodingField setHidden: YES];
4357 [fSrcFrameEndEncodingField setHidden: YES];
4359 [self chapterPopUpChanged:nil];
4361 /* We are time based (seconds) */
4362 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
4364 [fSrcChapterStartPopUp setHidden: YES];
4365 [fSrcChapterEndPopUp setHidden: YES];
4367 [fSrcTimeStartEncodingField setHidden: NO];
4368 [fSrcTimeEndEncodingField setHidden: NO];
4370 [fSrcFrameStartEncodingField setHidden: YES];
4371 [fSrcFrameEndEncodingField setHidden: YES];
4373 [self startEndSecValueChanged:nil];
4375 /* We are frame based */
4376 else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
4378 [fSrcChapterStartPopUp setHidden: YES];
4379 [fSrcChapterEndPopUp setHidden: YES];
4381 [fSrcTimeStartEncodingField setHidden: YES];
4382 [fSrcTimeEndEncodingField setHidden: YES];
4384 [fSrcFrameStartEncodingField setHidden: NO];
4385 [fSrcFrameEndEncodingField setHidden: NO];
4387 [self startEndFrameValueChanged:nil];
4392 - (IBAction) chapterPopUpChanged: (id) sender
4395 /* If start chapter popup is greater than end chapter popup,
4396 we set the end chapter popup to the same as start chapter popup */
4397 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
4399 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
4403 hb_list_t * list = hb_get_titles( fHandle );
4404 hb_title_t * title = (hb_title_t *)
4405 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4407 hb_chapter_t * chapter;
4408 int64_t duration = 0;
4409 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
4410 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
4412 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
4413 duration += chapter->duration;
4416 duration /= 90000; /* pts -> seconds */
4417 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4418 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
4421 [self calculateBitrate: sender];
4423 if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
4425 /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
4426 [fCreateChapterMarkers setEnabled: NO];
4427 [fCreateChapterMarkers setState: NSOffState];
4431 [fCreateChapterMarkers setEnabled: YES];
4435 - (IBAction) startEndSecValueChanged: (id) sender
4438 int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
4439 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4440 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4443 //[self calculateBitrate: sender];
4447 - (IBAction) startEndFrameValueChanged: (id) sender
4449 hb_list_t * list = hb_get_titles( fHandle );
4450 hb_title_t * title = (hb_title_t*)
4451 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
4453 int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
4454 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
4455 @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
4458 //[self calculateBitrate: sender];
4462 - (IBAction) formatPopUpChanged: (id) sender
4464 NSString * string = [fDstFile2Field stringValue];
4465 int format = [fDstFormatPopUp indexOfSelectedItem];
4467 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
4468 [fDstMp4LargeFileCheck setHidden: YES];
4469 [fDstMp4HttpOptFileCheck setHidden: YES];
4470 [fDstMp4iPodFileCheck setHidden: YES];
4472 /* Update the Video Codec PopUp */
4473 /* lets get the tag of the currently selected item first so we might reset it later */
4474 int selectedVidEncoderTag;
4475 selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
4477 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
4478 [fVidEncoderPopUp removeAllItems];
4479 NSMenuItem *menuItem;
4480 /* These video encoders are available to all of our current muxers, so lets list them once here */
4481 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
4482 [menuItem setTag: HB_VCODEC_FFMPEG];
4487 /*Get Default MP4 File Extension*/
4488 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
4496 /* Add additional video encoders here */
4497 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4498 [menuItem setTag: HB_VCODEC_X264];
4499 /* We show the mp4 option checkboxes here since we are mp4 */
4500 [fCreateChapterMarkers setEnabled: YES];
4501 [fDstMp4LargeFileCheck setHidden: NO];
4502 [fDstMp4HttpOptFileCheck setHidden: NO];
4503 [fDstMp4iPodFileCheck setHidden: NO];
4508 /* Add additional video encoders here */
4509 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
4510 [menuItem setTag: HB_VCODEC_X264];
4511 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
4512 [menuItem setTag: HB_VCODEC_THEORA];
4513 /* We enable the create chapters checkbox here */
4514 [fCreateChapterMarkers setEnabled: YES];
4519 /* tell fSubtitlesDelegate we have a new video container */
4521 [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
4522 [fSubtitlesTable reloadData];
4524 /* post a notification for any interested observers to indicate that our video container has changed */
4525 [[NSNotificationCenter defaultCenter] postNotification:
4526 [NSNotification notificationWithName: HBContainerChangedNotification
4528 userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
4529 [NSNumber numberWithInt: [[fDstFormatPopUp selectedItem] tag]], keyContainerTag,
4532 /* if we have a previously selected vid encoder tag, then try to select it */
4533 if (selectedVidEncoderTag)
4535 [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
4539 [fVidEncoderPopUp selectItemAtIndex: 0];
4544 [self autoSetM4vExtension: sender];
4546 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
4548 if( SuccessfulScan )
4550 /* Add/replace to the correct extension */
4552 if( [fVidEncoderPopUp selectedItem] == nil )
4555 [fVidEncoderPopUp selectItemAtIndex:0];
4556 [self videoEncoderPopUpChanged:nil];
4558 /* changing the format may mean that we can / can't offer mono or 6ch, */
4559 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
4561 /* We call the method to properly enable/disable turbo 2 pass */
4562 [self twoPassCheckboxChanged: sender];
4563 /* We call method method to change UI to reflect whether a preset is used or not*/
4566 [self customSettingUsed: sender];
4569 - (IBAction) autoSetM4vExtension: (id) sender
4571 if ( [fDstFormatPopUp indexOfSelectedItem] )
4574 NSString * extension = @"mp4";
4576 BOOL anyCodecAC3 = [fAudioDelegate anyCodecMatches: HB_ACODEC_AC3] || [fAudioDelegate anyCodecMatches: HB_ACODEC_AC3_PASS];
4577 if (YES == anyCodecAC3 ||
4578 [fCreateChapterMarkers state] == NSOnState ||
4579 [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0 )
4584 if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
4587 [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
4588 [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
4591 /* Method to determine if we should change the UI
4592 To reflect whether or not a Preset is being used or if
4593 the user is using "Custom" settings by determining the sender*/
4594 - (IBAction) customSettingUsed: (id) sender
4596 if ([sender stringValue])
4598 /* Deselect the currently selected Preset if there is one*/
4599 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4600 /* Change UI to show "Custom" settings are being used */
4601 [fPresetSelectedDisplay setStringValue: @"Custom"];
4603 curUserPresetChosenNum = nil;
4605 [self calculateBitrate:nil];
4610 #pragma mark - Video
4612 - (IBAction) videoEncoderPopUpChanged: (id) sender
4614 hb_job_t * job = fTitle->job;
4615 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
4617 [fAdvancedOptions setHidden:YES];
4618 /* If we are using x264 then show the x264 advanced panel*/
4619 if (videoEncoder == HB_VCODEC_X264)
4621 [fAdvancedOptions setHidden:NO];
4622 [self autoSetM4vExtension: sender];
4625 if (videoEncoder == HB_VCODEC_FFMPEG)
4627 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
4628 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
4629 anything other than MP4.
4631 [fDstMp4iPodFileCheck setEnabled: NO];
4632 [fDstMp4iPodFileCheck setState: NSOffState];
4636 [fDstMp4iPodFileCheck setEnabled: YES];
4638 [self setupQualitySlider];
4639 [self calculatePictureSizing: sender];
4640 [self twoPassCheckboxChanged: sender];
4644 - (IBAction) twoPassCheckboxChanged: (id) sender
4646 /* check to see if x264 is chosen */
4647 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4649 if( [fVidTwoPassCheck state] == NSOnState)
4651 [fVidTurboPassCheck setHidden: NO];
4655 [fVidTurboPassCheck setHidden: YES];
4656 [fVidTurboPassCheck setState: NSOffState];
4658 /* Make sure Two Pass is checked if Turbo is checked */
4659 if( [fVidTurboPassCheck state] == NSOnState)
4661 [fVidTwoPassCheck setState: NSOnState];
4666 [fVidTurboPassCheck setHidden: YES];
4667 [fVidTurboPassCheck setState: NSOffState];
4670 /* We call method method to change UI to reflect whether a preset is used or not*/
4671 [self customSettingUsed: sender];
4674 - (IBAction ) videoFrameRateChanged: (id) sender
4676 /* Hide and set the PFR Checkbox to OFF if we are set to Same as Source */
4677 if ([fVidRatePopUp indexOfSelectedItem] == 0)
4679 [fFrameratePfrCheck setHidden:YES];
4680 [fFrameratePfrCheck setState:0];
4684 [fFrameratePfrCheck setHidden:NO];
4687 /* We call method method to calculatePictureSizing to error check detelecine*/
4688 [self calculatePictureSizing: sender];
4690 /* We call method method to change UI to reflect whether a preset is used or not*/
4691 [self customSettingUsed: sender];
4693 - (IBAction) videoMatrixChanged: (id) sender;
4695 bool target, bitrate, quality;
4697 target = bitrate = quality = false;
4698 if( [fVidQualityMatrix isEnabled] )
4700 switch( [fVidQualityMatrix selectedRow] )
4713 [fVidTargetSizeField setEnabled: target];
4714 [fVidBitrateField setEnabled: bitrate];
4715 [fVidQualitySlider setEnabled: quality];
4716 [fVidQualityRFField setEnabled: quality];
4717 [fVidQualityRFLabel setEnabled: quality];
4718 [fVidTwoPassCheck setEnabled: !quality &&
4719 [fVidQualityMatrix isEnabled]];
4722 [fVidTwoPassCheck setState: NSOffState];
4723 [fVidTurboPassCheck setHidden: YES];
4724 [fVidTurboPassCheck setState: NSOffState];
4727 [self qualitySliderChanged: sender];
4728 [self calculateBitrate: sender];
4729 [self customSettingUsed: sender];
4732 /* Use this method to setup the quality slider for cq/rf values depending on
4733 * the video encoder selected.
4735 - (void) setupQualitySlider
4737 /* Get the current slider maxValue to check for a change in slider scale later
4738 * so that we can choose a new similar value on the new slider scale */
4739 float previousMaxValue = [fVidQualitySlider maxValue];
4740 float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
4741 NSString * qpRFLabelString = @"QP:";
4743 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
4745 [fVidQualitySlider setMinValue:0.0];
4746 [fVidQualitySlider setMaxValue:51.0];
4747 /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
4748 int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
4749 [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
4750 qpRFLabelString = @"RF:";
4753 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
4755 [fVidQualitySlider setMinValue:1.0];
4756 [fVidQualitySlider setMaxValue:31.0];
4757 [fVidQualitySlider setNumberOfTickMarks:31];
4760 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4762 [fVidQualitySlider setMinValue:0.0];
4763 [fVidQualitySlider setMaxValue:63.0];
4764 [fVidQualitySlider setNumberOfTickMarks:64];
4766 [fVidQualityRFLabel setStringValue:qpRFLabelString];
4768 /* check to see if we have changed slider scales */
4769 if (previousMaxValue != [fVidQualitySlider maxValue])
4771 /* if so, convert the old setting to the new scale as close as possible based on percentages */
4772 float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
4773 [fVidQualitySlider setFloatValue:rf];
4776 [self qualitySliderChanged:nil];
4779 - (IBAction) qualitySliderChanged: (id) sender
4781 /* Our constant quality slider is in a range based
4782 * on each encoders qp/rf values. The range depends
4783 * on the encoder. Also, the range is inverse of quality
4784 * for all of the encoders *except* for theora
4785 * (ie. as the "quality" goes up, the cq or rf value
4786 * actually goes down). Since the IB sliders always set
4787 * their max value at the right end of the slider, we
4788 * will calculate the inverse, so as the slider floatValue
4789 * goes up, we will show the inverse in the rf field
4790 * so, the floatValue at the right for x264 would be 51
4791 * and our rf field needs to show 0 and vice versa.
4794 float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
4795 /* If the encoder is theora, use the float, otherwise use the inverse float*/
4796 //float sliderRfToPercent;
4797 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
4799 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
4803 [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
4805 [self customSettingUsed: sender];
4808 - (void) controlTextDidChange: (NSNotification *) notification
4810 [self calculateBitrate:nil];
4813 - (IBAction) calculateBitrate: (id) sender
4815 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
4820 hb_list_t * list = hb_get_titles( fHandle );
4821 hb_title_t * title = (hb_title_t *) hb_list_item( list,
4822 [fSrcTitlePopUp indexOfSelectedItem] );
4823 hb_job_t * job = title->job;
4824 hb_audio_config_t * audio;
4825 /* For hb_calc_bitrate in addition to the Target Size in MB out of the
4826 * Target Size Field, we also need the job info for the Muxer, the Chapters
4827 * as well as all of the audio track info.
4828 * This used to be accomplished by simply calling prepareJob here, however
4829 * since the resilient queue sets the queue array values instead of the job
4830 * values directly, we duplicate the old prepareJob code here for the variables
4833 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
4834 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
4835 job->mux = [[fDstFormatPopUp selectedItem] tag];
4837 /* Audio goes here */
4838 [fAudioDelegate prepareAudioForJob: job];
4840 [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
4844 #pragma mark - Picture
4846 /* lets set the picture size back to the max from right after title scan
4847 Lets use an IBAction here as down the road we could always use a checkbox
4848 in the gui to easily take the user back to max. Remember, the compiler
4849 resolves IBActions down to -(void) during compile anyway */
4850 - (IBAction) revertPictureSizeToMax: (id) sender
4852 hb_job_t * job = fTitle->job;
4853 /* Here we apply the title source and height */
4854 job->width = fTitle->width;
4855 job->height = fTitle->height;
4857 [self calculatePictureSizing: sender];
4858 /* We call method to change UI to reflect whether a preset is used or not*/
4859 [self customSettingUsed: sender];
4863 * Registers changes made in the Picture Settings Window.
4866 - (void)pictureSettingsDidChange
4868 [self calculatePictureSizing:nil];
4871 /* Get and Display Current Pic Settings in main window */
4872 - (IBAction) calculatePictureSizing: (id) sender
4874 if (fTitle->job->anamorphic.mode > 0)
4876 fTitle->job->keep_ratio = 0;
4879 if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
4881 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
4885 [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
4887 NSString *picCropping;
4888 /* Set the display field for crop as per boolean */
4889 if (![fPictureController autoCrop])
4891 picCropping = @"Custom";
4895 picCropping = @"Auto";
4897 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]]];
4899 [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
4901 NSString *videoFilters;
4904 if ([fPictureController detelecine] == 2)
4906 videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
4908 else if ([fPictureController detelecine] == 1)
4910 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
4914 if ([fPictureController useDecomb] == 1)
4917 if ([fPictureController decomb] == 2)
4919 videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
4921 else if ([fPictureController decomb] == 1)
4923 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
4929 if ([fPictureController deinterlace] > 0)
4931 fTitle->job->deinterlace = 1;
4935 fTitle->job->deinterlace = 0;
4938 if ([fPictureController deinterlace] == 2)
4940 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
4942 else if ([fPictureController deinterlace] == 3)
4944 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
4946 else if ([fPictureController deinterlace] == 4)
4948 videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
4950 else if ([fPictureController deinterlace] == 1)
4952 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
4958 if ([fPictureController denoise] == 2)
4960 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
4962 else if ([fPictureController denoise] == 3)
4964 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
4966 else if ([fPictureController denoise] == 4)
4968 videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
4970 else if ([fPictureController denoise] == 1)
4972 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
4976 if ([fPictureController deblock] > 0)
4978 videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
4982 if ([fPictureController grayscale])
4984 videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
4986 [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
4988 //[fPictureController reloadStillPreview];
4993 #pragma mark - Audio and Subtitles
4998 - (BOOL) hasValidPresetSelected
5001 return ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1);
5004 // This causes all audio tracks from the title to be used based on the current preset
5005 - (IBAction) addAllAudioTracks: (id) sender
5008 [fAudioDelegate addAllTracksFromPreset: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
5012 - (IBAction) browseImportSrtFile: (id) sender
5015 NSOpenPanel * panel;
5017 panel = [NSOpenPanel openPanel];
5018 [panel setAllowsMultipleSelection: NO];
5019 [panel setCanChooseFiles: YES];
5020 [panel setCanChooseDirectories: NO ];
5021 NSString * sourceDirectory;
5022 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
5024 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
5028 sourceDirectory = @"~/Desktop";
5029 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
5031 /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
5032 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
5033 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
5034 modalForWindow: fWindow modalDelegate: self
5035 didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
5036 contextInfo: sender];
5039 - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
5040 returnCode: (int) returnCode contextInfo: (void *) contextInfo
5042 if( returnCode == NSOKButton )
5044 NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
5045 NSString *importSrtFilePath = [sheet filename];
5046 [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
5048 /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
5049 [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
5051 [fSubtitlesTable reloadData];
5057 #pragma mark Open New Windows
5059 - (IBAction) openHomepage: (id) sender
5061 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5062 URLWithString:@"http://handbrake.fr/"]];
5065 - (IBAction) openForums: (id) sender
5067 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5068 URLWithString:@"http://forum.handbrake.fr/"]];
5070 - (IBAction) openUserGuide: (id) sender
5072 [[NSWorkspace sharedWorkspace] openURL: [NSURL
5073 URLWithString:@"http://trac.handbrake.fr/wiki/HandBrakeGuide"]];
5077 * Shows debug output window.
5079 - (IBAction)showDebugOutputPanel:(id)sender
5081 [outputPanel showOutputPanel:sender];
5085 * Shows preferences window.
5087 - (IBAction) showPreferencesWindow: (id) sender
5089 NSWindow * window = [fPreferencesController window];
5090 if (![window isVisible])
5093 [window makeKeyAndOrderFront: nil];
5097 * Shows queue window.
5099 - (IBAction) showQueueWindow:(id)sender
5101 [fQueueController showQueueWindow:sender];
5105 - (IBAction) toggleDrawer:(id)sender {
5106 [fPresetDrawer toggle:self];
5110 * Shows Picture Settings Window.
5113 - (IBAction) showPicturePanel: (id) sender
5115 [fPictureController showPictureWindow:sender];
5118 - (void) picturePanelFullScreen
5120 [fPictureController setToFullScreenMode];
5123 - (void) picturePanelWindowed
5125 [fPictureController setToWindowedMode];
5128 - (IBAction) showPreviewWindow: (id) sender
5130 [fPictureController showPreviewWindow:sender];
5134 #pragma mark Preset Outline View Methods
5135 #pragma mark - Required
5136 /* These are required by the NSOutlineView Datasource Delegate */
5139 /* used to specify the number of levels to show for each item */
5140 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
5142 /* currently use no levels to test outline view viability */
5143 if (item == nil) // for an outline view the root level of the hierarchy is always nil
5145 return [UserPresets count];
5149 /* we need to return the count of the array in ChildrenArray for this folder */
5150 NSArray *children = nil;
5151 children = [item objectForKey:@"ChildrenArray"];
5152 if ([children count] > 0)
5154 return [children count];
5163 /* We use this to deterimine children of an item */
5164 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
5167 /* we need to return the count of the array in ChildrenArray for this folder */
5168 NSArray *children = nil;
5171 children = UserPresets;
5175 if ([item objectForKey:@"ChildrenArray"])
5177 children = [item objectForKey:@"ChildrenArray"];
5180 if ((children == nil) || ( [children count] <= (NSUInteger) index))
5186 return [children objectAtIndex:index];
5190 // We are only one level deep, so we can't be asked about children
5191 //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
5195 /* We use this to determine if an item should be expandable */
5196 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
5199 /* we need to return the count of the array in ChildrenArray for this folder */
5200 NSArray *children= nil;
5203 children = UserPresets;
5207 if ([item objectForKey:@"ChildrenArray"])
5209 children = [item objectForKey:@"ChildrenArray"];
5213 /* To deterimine if an item should show a disclosure triangle
5214 * we could do it by the children count as so:
5215 * if ([children count] < 1)
5216 * However, lets leave the triangle show even if there are no
5217 * children to help indicate a folder, just like folder in the
5218 * finder can show a disclosure triangle even when empty
5221 /* We need to determine if the item is a folder */
5222 if ([[item objectForKey:@"Folder"] intValue] == 1)
5233 - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
5235 // Our outline view has no levels, but we can still expand every item. Doing so
5236 // just makes the row taller. See heightOfRowByItem below.
5237 //return ![(HBQueueOutlineView*)outlineView isDragging];
5243 /* Used to tell the outline view which information is to be displayed per item */
5244 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5246 /* We have two columns right now, icon and PresetName */
5248 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5250 return [item objectForKey:@"PresetName"];
5259 - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
5261 return [NSKeyedUnarchiver unarchiveObjectWithData:object];
5263 - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
5265 return [NSKeyedArchiver archivedDataWithRootObject:item];
5268 #pragma mark - Added Functionality (optional)
5269 /* Use to customize the font and display characteristics of the title cell */
5270 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
5272 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5276 NSColor *shadowColor;
5277 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
5278 /*check to see if its a selected row */
5279 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
5282 fontColor = [NSColor blackColor];
5283 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
5287 if ([[item objectForKey:@"Type"] intValue] == 0)
5289 fontColor = [NSColor blueColor];
5291 else // User created preset, use a black font
5293 fontColor = [NSColor blackColor];
5295 /* check to see if its a folder */
5296 //if ([[item objectForKey:@"Folder"] intValue] == 1)
5298 //fontColor = [NSColor greenColor];
5303 /* We use Bold Text for the HB Default */
5304 if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
5306 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5308 /* We use Bold Text for the User Specified Default */
5309 if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
5311 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
5315 [cell setTextColor:fontColor];
5316 [cell setFont:txtFont];
5321 /* We use this to edit the name field in the outline view */
5322 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
5324 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
5329 [theRecord setObject:object forKey:@"PresetName"];
5333 [fPresetsOutlineView reloadData];
5334 /* We save all of the preset data here */
5338 /* We use this to provide tooltips for the items in the presets outline view */
5339 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
5341 //if ([[tc identifier] isEqualToString:@"PresetName"])
5343 /* initialize the tooltip contents variable */
5345 /* if there is a description for the preset, we show it in the tooltip */
5346 if ([item objectForKey:@"PresetDescription"])
5348 loc_tip = [item objectForKey:@"PresetDescription"];
5353 loc_tip = @"No description available";
5359 - (void) outlineViewSelectionDidChange: (NSNotification *) ignored
5362 [self willChangeValueForKey: @"hasValidPresetSelected"];
5363 [self didChangeValueForKey: @"hasValidPresetSelected"];
5368 #pragma mark Preset Outline View Methods (dragging related)
5371 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
5373 // Dragging is only allowed for custom presets.
5374 //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
5375 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
5379 // Don't retain since this is just holding temporaral drag information, and it is
5380 //only used during a drag! We could put this in the pboard actually.
5381 fDraggedNodes = items;
5382 // Provide data for our custom type, and simple NSStrings.
5383 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
5385 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
5386 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
5391 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
5394 // Don't allow dropping ONTO an item since they can't really contain any children.
5396 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
5397 if (isOnDropTypeProposal)
5398 return NSDragOperationNone;
5400 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
5403 index = [fPresetsOutlineView rowForItem: item] + 1;
5407 // Don't allow dropping into the Built In Presets.
5408 if (index < presetCurrentBuiltInCount)
5410 return NSDragOperationNone;
5411 index = MAX (index, presetCurrentBuiltInCount);
5414 [outlineView setDropItem:item dropChildIndex:index];
5415 return NSDragOperationGeneric;
5420 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
5422 /* first, lets see if we are dropping into a folder */
5423 if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
5425 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
5426 childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
5427 [childrenArray addObject:item];
5428 [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
5429 [childrenArray autorelease];
5431 else // We are not, so we just move the preset into the existing array
5433 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
5435 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
5436 while (obj = [enumerator nextObject])
5438 [moveItems addIndex:[UserPresets indexOfObject:obj]];
5440 // Successful drop, lets rearrange the view and save it all
5441 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
5443 [fPresetsOutlineView reloadData];
5448 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
5450 NSUInteger index = [indexSet lastIndex];
5451 NSUInteger aboveInsertIndexCount = 0;
5453 NSUInteger removeIndex;
5455 if (index >= insertIndex)
5457 removeIndex = index + aboveInsertIndexCount;
5458 aboveInsertIndexCount++;
5462 removeIndex = index;
5466 id object = [[array objectAtIndex:removeIndex] retain];
5467 [array removeObjectAtIndex:removeIndex];
5468 [array insertObject:object atIndex:insertIndex];
5471 index = [indexSet indexLessThanIndex:index];
5476 #pragma mark - Functional Preset NSOutlineView Methods
5478 - (IBAction)selectPreset:(id)sender
5481 if (YES == [self hasValidPresetSelected])
5483 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
5484 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5486 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
5488 [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
5492 [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
5496 [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
5497 [self formatPopUpChanged:nil];
5499 /* Chapter Markers*/
5500 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
5501 /* check to see if we have only one chapter */
5502 [self chapterPopUpChanged:nil];
5504 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
5505 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
5506 /* Mux mp4 with http optimization */
5507 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
5510 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
5511 /* We set the advanced opt string here if applicable*/
5512 [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
5514 /* Lets run through the following functions to get variables set there */
5515 [self videoEncoderPopUpChanged:nil];
5516 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
5517 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
5518 [self calculateBitrate:nil];
5521 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
5523 [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
5524 [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
5526 /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
5527 * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
5528 * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
5529 * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
5530 * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
5531 if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
5533 /* For the quality slider we need to convert the old percent's to the new rf scales */
5534 float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
5535 [fVidQualitySlider setFloatValue:rf];
5540 /* Since theora's qp value goes up from left to right, we can just set the slider float value */
5541 if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
5543 [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
5547 /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
5548 [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
5552 [self videoMatrixChanged:nil];
5554 /* Video framerate */
5555 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
5556 detected framerate in the fVidRatePopUp so we use index 0*/
5557 if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
5559 [fVidRatePopUp selectItemAtIndex: 0];
5563 [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
5566 [fFrameratePfrCheck setState:[[chosenPreset objectForKey:@"VideoFrameratePFR"] intValue]];
5567 [self videoFrameRateChanged:nil];
5569 /* 2 Pass Encoding */
5570 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
5571 [self twoPassCheckboxChanged:nil];
5573 /* Turbo 1st pass for 2 Pass Encoding */
5574 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
5577 [fAudioDelegate addTracksFromPreset: chosenPreset];
5580 [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
5581 /* Forced Subtitles */
5582 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
5584 /* Picture Settings */
5585 /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
5586 * height, width, keep ar, anamorphic and crop settings.
5587 * picture filters are handled separately below.
5589 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
5590 * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
5591 * preset completely ignores any picture sizing values in the preset.
5593 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
5595 hb_job_t * job = fTitle->job;
5597 /* If Cropping is set to custom, then recall all four crop values from
5598 when the preset was created and apply them */
5599 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
5601 [fPictureController setAutoCrop:NO];
5603 /* Here we use the custom crop values saved at the time the preset was saved */
5604 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
5605 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
5606 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
5607 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
5610 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
5612 [fPictureController setAutoCrop:YES];
5613 /* Here we use the auto crop values determined right after scan */
5614 job->crop[0] = AutoCropTop;
5615 job->crop[1] = AutoCropBottom;
5616 job->crop[2] = AutoCropLeft;
5617 job->crop[3] = AutoCropRight;
5622 if ([chosenPreset objectForKey:@"PictureModulus"])
5624 job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
5631 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
5632 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
5634 /* Use Max Picture settings for whatever the dvd is.*/
5635 [self revertPictureSizeToMax:nil];
5636 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5637 if (job->keep_ratio == 1)
5639 hb_fix_aspect( job, HB_KEEP_WIDTH );
5640 if( job->height > fTitle->height )
5642 job->height = fTitle->height;
5643 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5646 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5648 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
5650 /* we check to make sure the presets width/height does not exceed the sources width/height */
5651 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
5653 /* if so, then we use the sources height and width to avoid scaling up */
5654 //job->width = fTitle->width;
5655 //job->height = fTitle->height;
5656 [self revertPictureSizeToMax:nil];
5658 else // source width/height is >= the preset height/width
5660 /* we can go ahead and use the presets values for height and width */
5661 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
5662 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
5664 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
5665 if (job->keep_ratio == 1)
5667 int height = fTitle->height;
5669 if ( job->height && job->height < fTitle->height )
5670 height = job->height;
5672 hb_fix_aspect( job, HB_KEEP_WIDTH );
5673 // Make sure the resulting height is less than
5674 // the title height and less than the height
5675 // requested in the preset.
5676 if( job->height > height )
5678 job->height = height;
5679 hb_fix_aspect( job, HB_KEEP_HEIGHT );
5682 job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
5683 if ( job->anamorphic.mode > 0 )
5685 int w, h, par_w, par_h;
5687 job->anamorphic.par_width = fTitle->pixel_aspect_width;
5688 job->anamorphic.par_height = fTitle->pixel_aspect_height;
5689 job->maxWidth = job->width;
5690 job->maxHeight = job->height;
5691 hb_set_anamorphic_size( job, &w, &h, &par_w, &par_h );
5702 /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
5703 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
5707 /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
5708 * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
5709 * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
5712 [fPictureController setUseDecomb:1];
5713 [fPictureController setDecomb:0];
5714 [fPictureController setDeinterlace:0];
5715 if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
5717 /* we are using decomb */
5719 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
5721 [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
5723 /* if we are using "Custom" in the decomb setting, also set the custom string*/
5724 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
5726 [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
5732 /* We are using Deinterlace */
5734 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
5736 [fPictureController setUseDecomb:0];
5737 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
5738 /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
5739 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
5741 [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
5748 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
5750 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
5751 /* if we are using "Custom" in the detelecine setting, also set the custom string*/
5752 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
5754 [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
5759 [fPictureController setDetelecine:0];
5763 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
5765 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
5766 /* if we are using "Custom" in the denoise setting, also set the custom string*/
5767 if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
5769 [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
5774 [fPictureController setDenoise:0];
5778 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
5780 /* if its a one, then its the old on/off deblock, set on to 5*/
5781 [fPictureController setDeblock:5];
5785 /* use the settings intValue */
5786 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
5789 if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
5791 [fPictureController setGrayscale:1];
5795 [fPictureController setGrayscale:0];
5798 /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
5799 [fPictureController SetTitle:fTitle];
5800 [fPictureController SetTitle:fTitle];
5801 [self calculatePictureSizing:nil];
5807 #pragma mark Manage Presets
5809 - (void) loadPresets {
5810 /* We declare the default NSFileManager into fileManager */
5811 NSFileManager * fileManager = [NSFileManager defaultManager];
5812 /*We define the location of the user presets file */
5813 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
5814 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
5815 /* We check for the presets.plist */
5816 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
5818 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
5821 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
5822 if (nil == UserPresets)
5824 UserPresets = [[NSMutableArray alloc] init];
5825 [self addFactoryPresets:nil];
5827 [fPresetsOutlineView reloadData];
5829 [self checkBuiltInsForUpdates];
5832 - (void) checkBuiltInsForUpdates {
5834 BOOL updateBuiltInPresets = NO;
5836 NSEnumerator *enumerator = [UserPresets objectEnumerator];
5838 while (tempObject = [enumerator nextObject])
5840 /* iterate through the built in presets to see if any have an old build number */
5841 NSMutableDictionary *thisPresetDict = tempObject;
5842 /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
5843 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
5845 if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
5847 updateBuiltInPresets = YES;
5852 /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
5853 if ( updateBuiltInPresets == YES)
5855 if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
5857 /* Show an alert window that built in presets will be updated */
5858 /*On Screen Notification*/
5861 status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
5862 [NSApp requestUserAttention:NSCriticalRequest];
5864 /* when alert is dismissed, go ahead and update the built in presets */
5865 [self addFactoryPresets:nil];
5871 - (IBAction) addPresetPicDropdownChanged: (id) sender
5873 if ([fPresetNewPicSettingsPopUp indexOfSelectedItem] == 1)
5875 [fPresetNewPicWidthHeightBox setHidden:NO];
5879 [fPresetNewPicWidthHeightBox setHidden:YES];
5883 - (IBAction) showAddPresetPanel: (id) sender
5885 /* Deselect the currently selected Preset if there is one*/
5886 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
5888 /* Populate the preset picture settings popup here */
5889 [fPresetNewPicSettingsPopUp removeAllItems];
5890 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
5891 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Custom"];
5892 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
5893 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
5894 /* Uncheck the preset use filters checkbox */
5895 [fPresetNewPicFiltersCheck setState:NSOffState];
5896 // fPresetNewFolderCheck
5897 [fPresetNewFolderCheck setState:NSOffState];
5898 /* Erase info from the input fields*/
5899 [fPresetNewName setStringValue: @""];
5900 [fPresetNewDesc setStringValue: @""];
5902 /* Initialize custom height and width settings to current values */
5904 [fPresetNewPicWidth setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->width]];
5905 [fPresetNewPicHeight setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->height]];
5906 [self addPresetPicDropdownChanged:nil];
5907 /* Show the panel */
5908 [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
5911 - (IBAction) closeAddPresetPanel: (id) sender
5913 [NSApp endSheet: fAddPresetPanel];
5914 [fAddPresetPanel orderOut: self];
5917 - (IBAction)addUserPreset:(id)sender
5919 if (![[fPresetNewName stringValue] length])
5920 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
5923 /* Here we create a custom user preset */
5924 [UserPresets addObject:[self createPreset]];
5927 [self closeAddPresetPanel:nil];
5934 /* We Reload the New Table data for presets */
5935 [fPresetsOutlineView reloadData];
5936 /* We save all of the preset data here */
5944 /* We Sort the Presets By Factory or Custom */
5945 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
5946 ascending:YES] autorelease];
5947 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
5949 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
5950 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
5951 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
5954 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
5955 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
5956 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
5957 [UserPresets setArray:sortedArray];
5962 - (IBAction)insertPreset:(id)sender
5964 int index = [fPresetsOutlineView selectedRow];
5965 [UserPresets insertObject:[self createPreset] atIndex:index];
5966 [fPresetsOutlineView reloadData];
5970 - (NSDictionary *)createPreset
5972 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
5973 /* Preset build number */
5974 [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
5975 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
5976 /* Get the New Preset Name from the field in the AddPresetPanel */
5977 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
5978 /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
5979 [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
5980 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
5981 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
5982 /*Set whether or not this is default, at creation set to 0*/
5983 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
5984 if ([fPresetNewFolderCheck state] == YES)
5986 /* initialize and set an empty array for children here since we are a new folder */
5987 NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
5988 [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
5989 [childrenArray autorelease];
5991 else // we are not creating a preset folder, so we go ahead with the rest of the preset info
5993 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
5994 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
5995 /* Get whether or not to use the current Picture Filter settings for the preset */
5996 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
5998 /* Get New Preset Description from the field in the AddPresetPanel*/
5999 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
6001 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
6002 /* Chapter Markers fCreateChapterMarkers*/
6003 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
6004 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
6005 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
6006 /* Mux mp4 with http optimization */
6007 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
6008 /* Add iPod uuid atom */
6009 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
6013 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
6014 /* x264 Option String */
6015 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
6017 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
6018 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
6019 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
6020 [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
6022 /* Video framerate */
6023 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
6025 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
6027 else // we can record the actual titleOfSelectedItem
6029 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
6031 [preset setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
6033 /* 2 Pass Encoding */
6034 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
6035 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
6036 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
6037 /*Picture Settings*/
6038 hb_job_t * job = fTitle->job;
6040 /* Picture Sizing */
6041 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
6042 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicWidth intValue]] forKey:@"PictureWidth"];
6043 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicHeight intValue]] forKey:@"PictureHeight"];
6044 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
6045 [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
6046 [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
6048 /* Set crop settings here */
6049 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
6050 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
6051 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
6052 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
6053 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
6055 /* Picture Filters */
6056 [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
6057 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
6058 [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
6059 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
6060 [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
6061 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
6062 [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
6063 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
6064 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
6065 [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
6066 [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
6069 NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
6070 [fAudioDelegate prepareAudioForPreset: audioListArray];
6073 [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
6076 /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
6077 * subititle array code. */
6079 //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
6080 /* Forced Subtitles */
6081 //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
6083 [preset autorelease];
6090 [UserPresets writeToFile:UserPresetsFile atomically:YES];
6091 /* We get the default preset in case it changed */
6092 [self getDefaultPresets:nil];
6096 - (IBAction)deletePreset:(id)sender
6100 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
6104 /* Alert user before deleting preset */
6106 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
6108 if ( status == NSAlertDefaultReturn )
6110 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6111 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6112 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6114 NSEnumerator *enumerator;
6115 NSMutableArray *presetsArrayToMod;
6116 NSMutableArray *tempArray;
6118 /* If we are a root level preset, we are modding the UserPresets array */
6119 if (presetToModLevel == 0)
6121 presetsArrayToMod = UserPresets;
6123 else // We have a parent preset, so we modify the chidren array object for key
6125 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6128 enumerator = [presetsArrayToMod objectEnumerator];
6129 tempArray = [NSMutableArray array];
6131 while (tempObject = [enumerator nextObject])
6133 NSDictionary *thisPresetDict = tempObject;
6134 if (thisPresetDict == presetToMod)
6136 [tempArray addObject:tempObject];
6140 [presetsArrayToMod removeObjectsInArray:tempArray];
6141 [fPresetsOutlineView reloadData];
6148 #pragma mark Import Export Preset(s)
6150 - (IBAction) browseExportPresetFile: (id) sender
6152 /* Open a panel to let the user choose where and how to save the export file */
6153 NSSavePanel * panel = [NSSavePanel savePanel];
6154 /* We get the current file name and path from the destination field here */
6155 NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
6157 [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
6158 modalForWindow: fWindow modalDelegate: self
6159 didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
6163 - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
6164 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6166 if( returnCode == NSOKButton )
6168 NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6169 NSString *exportPresetsFile = [sheet filename];
6170 [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
6171 /* We check for the presets.plist */
6172 if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
6174 [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
6176 NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
6177 if (nil == presetsToExport)
6179 presetsToExport = [[NSMutableArray alloc] init];
6181 /* now get and add selected presets to export */
6184 if (YES == [self hasValidPresetSelected])
6186 [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6187 [presetsToExport writeToFile:exportPresetsFile atomically:YES];
6195 - (IBAction) browseImportPresetFile: (id) sender
6198 NSOpenPanel * panel;
6200 panel = [NSOpenPanel openPanel];
6201 [panel setAllowsMultipleSelection: NO];
6202 [panel setCanChooseFiles: YES];
6203 [panel setCanChooseDirectories: NO ];
6204 NSString * sourceDirectory;
6205 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
6207 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
6211 sourceDirectory = @"~/Desktop";
6212 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
6214 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
6215 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
6217 /* set this for allowed file types, not sure if we should allow xml or not */
6218 NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
6219 [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
6220 modalForWindow: fWindow modalDelegate: self
6221 didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
6222 contextInfo: sender];
6225 - (void) browseImportPresetDone: (NSSavePanel *) sheet
6226 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6228 if( returnCode == NSOKButton )
6230 NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
6231 NSString *importPresetsFile = [sheet filename];
6232 [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
6233 /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
6234 NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
6235 /* iterate though the new array of presets to import and add them to our presets array */
6237 NSEnumerator *enumerator = [presetsToImport objectEnumerator];
6239 while (tempObject = [enumerator nextObject])
6241 /* make any changes to the incoming preset we see fit */
6242 /* make sure the incoming preset is not tagged as default */
6243 [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6244 /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
6245 NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
6246 [tempObject setObject:prependedName forKey:@"PresetName"];
6248 /* actually add the new preset to our presets array */
6249 [UserPresets addObject:tempObject];
6252 [presetsToImport autorelease];
6260 #pragma mark Manage Default Preset
6262 - (IBAction)getDefaultPresets:(id)sender
6264 presetHbDefault = nil;
6265 presetUserDefault = nil;
6266 presetUserDefaultParent = nil;
6267 presetUserDefaultParentParent = nil;
6268 NSMutableDictionary *presetHbDefaultParent = nil;
6269 NSMutableDictionary *presetHbDefaultParentParent = nil;
6272 BOOL userDefaultFound = NO;
6273 presetCurrentBuiltInCount = 0;
6274 /* First we iterate through the root UserPresets array to check for defaults */
6275 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6277 while (tempObject = [enumerator nextObject])
6279 NSMutableDictionary *thisPresetDict = tempObject;
6280 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6282 presetHbDefault = thisPresetDict;
6284 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6286 presetUserDefault = thisPresetDict;
6287 userDefaultFound = YES;
6289 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
6291 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
6295 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6296 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6298 NSMutableDictionary *thisPresetDictParent = thisPresetDict;
6299 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6301 while (tempObject = [enumerator nextObject])
6303 NSMutableDictionary *thisPresetDict = tempObject;
6304 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6306 presetHbDefault = thisPresetDict;
6307 presetHbDefaultParent = thisPresetDictParent;
6309 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6311 presetUserDefault = thisPresetDict;
6312 presetUserDefaultParent = thisPresetDictParent;
6313 userDefaultFound = YES;
6316 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6317 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6319 NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
6320 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6322 while (tempObject = [enumerator nextObject])
6324 NSMutableDictionary *thisPresetDict = tempObject;
6325 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
6327 presetHbDefault = thisPresetDict;
6328 presetHbDefaultParent = thisPresetDictParent;
6329 presetHbDefaultParentParent = thisPresetDictParentParent;
6331 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
6333 presetUserDefault = thisPresetDict;
6334 presetUserDefaultParent = thisPresetDictParent;
6335 presetUserDefaultParentParent = thisPresetDictParentParent;
6336 userDefaultFound = YES;
6345 /* check to see if a user specified preset was found, if not then assign the parents for
6346 * the presetHbDefault so that we can open the parents for the nested presets
6348 if (userDefaultFound == NO)
6350 presetUserDefaultParent = presetHbDefaultParent;
6351 presetUserDefaultParentParent = presetHbDefaultParentParent;
6355 - (IBAction)setDefaultPreset:(id)sender
6357 /* We need to determine if the item is a folder */
6358 if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
6364 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6366 /* First make sure the old user specified default preset is removed */
6367 while (tempObject = [enumerator nextObject])
6369 NSMutableDictionary *thisPresetDict = tempObject;
6370 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6372 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6375 /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
6376 if ([thisPresetDict objectForKey:@"ChildrenArray"])
6378 NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
6381 while (tempObject = [enumerator nextObject])
6383 NSMutableDictionary *thisPresetDict1 = tempObject;
6384 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6386 [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6388 /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
6389 if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
6391 NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
6394 while (tempObject = [enumerator nextObject])
6396 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
6398 [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
6411 int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
6412 NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
6413 NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
6416 NSMutableArray *presetsArrayToMod;
6417 NSMutableArray *tempArray;
6419 /* If we are a root level preset, we are modding the UserPresets array */
6420 if (presetToModLevel == 0)
6422 presetsArrayToMod = UserPresets;
6424 else // We have a parent preset, so we modify the chidren array object for key
6426 presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
6429 enumerator = [presetsArrayToMod objectEnumerator];
6430 tempArray = [NSMutableArray array];
6432 while (tempObject = [enumerator nextObject])
6434 NSDictionary *thisPresetDict = tempObject;
6435 if (thisPresetDict == presetToMod)
6437 if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
6439 [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
6446 /* We save all of the preset data here */
6448 /* We Reload the New Table data for presets */
6449 [fPresetsOutlineView reloadData];
6452 - (IBAction)selectDefaultPreset:(id)sender
6454 NSMutableDictionary *presetToMod;
6455 /* if there is a user specified default, we use it */
6456 if (presetUserDefault)
6458 presetToMod = presetUserDefault;
6460 else if (presetHbDefault) //else we use the built in default presetHbDefault
6462 presetToMod = presetHbDefault;
6469 if (presetUserDefaultParent != nil)
6471 [fPresetsOutlineView expandItem:presetUserDefaultParent];
6474 if (presetUserDefaultParentParent != nil)
6476 [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
6480 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
6481 [self selectPreset:nil];
6486 #pragma mark Manage Built In Presets
6489 - (IBAction)deleteFactoryPresets:(id)sender
6492 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6496 NSMutableArray *tempArray;
6499 tempArray = [NSMutableArray array];
6500 /* we look here to see if the preset is we move on to the next one */
6501 while ( tempObject = [enumerator nextObject] )
6503 /* if the preset is "Factory" then we put it in the array of
6504 presets to delete */
6505 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
6507 [tempArray addObject:tempObject];
6511 [UserPresets removeObjectsInArray:tempArray];
6512 [fPresetsOutlineView reloadData];
6517 /* We use this method to recreate new, updated factory presets */
6518 - (IBAction)addFactoryPresets:(id)sender
6521 /* First, we delete any existing built in presets */
6522 [self deleteFactoryPresets: sender];
6523 /* Then we generate new built in presets programmatically with fPresetsBuiltin
6524 * which is all setup in HBPresets.h and HBPresets.m*/
6525 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
6526 /* update build number for built in presets */
6527 /* iterate though the new array of presets to import and add them to our presets array */
6529 NSEnumerator *enumerator = [UserPresets objectEnumerator];
6531 while (tempObject = [enumerator nextObject])
6533 /* Record the apps current build number in the PresetBuildNumber key */
6534 if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
6536 /* Preset build number */
6537 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
6541 /* report the built in preset updating to the activity log */
6542 [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
6550 #pragma mark Chapter Files Import / Export
6552 - (IBAction) browseForChapterFile: (id) sender
6554 /* Open a panel to let the user choose the file */
6555 NSOpenPanel * panel = [NSOpenPanel openPanel];
6556 /* We get the current file name and path from the destination field here */
6557 [panel beginSheetForDirectory: [NSString stringWithFormat:@"%@/",
6558 [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"]]
6560 types: [NSArray arrayWithObjects:@"csv",nil]
6561 modalForWindow: fWindow modalDelegate: self
6562 didEndSelector: @selector( browseForChapterFileDone:returnCode:contextInfo: )
6566 - (void) browseForChapterFileDone: (NSOpenPanel *) sheet
6567 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6569 NSArray *chaptersArray; /* temp array for chapters */
6570 NSMutableArray *chaptersMutableArray; /* temp array for chapters */
6571 NSString *chapterName; /* temp string from file */
6574 if( returnCode == NSOKButton ) /* if they click OK */
6576 chapterName = [[NSString alloc] initWithContentsOfFile:[sheet filename] encoding:NSUTF8StringEncoding error:NULL];
6577 chaptersArray = [chapterName componentsSeparatedByString:@"\n"];
6578 chaptersMutableArray= [chaptersArray mutableCopy];
6579 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
6580 if ([chaptersMutableArray count] > 0)
6582 /* if last item is empty remove it */
6583 if ([[chaptersMutableArray objectAtIndex:[chaptersArray count]-1] length] == 0)
6585 [chaptersMutableArray removeLastObject];
6588 /* if chapters in table is not equal to array count */
6589 if ((unsigned int) chapters != [chaptersMutableArray count])
6592 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
6593 defaultButton:NSLocalizedString(@"OK", @"OK")
6594 alternateButton:NULL
6596 informativeTextWithFormat:NSLocalizedString(@"%d chapters expected, %d chapters found in %@", @"%d chapters expected, %d chapters found in %@"),
6597 chapters, [chaptersMutableArray count], [[sheet filename] lastPathComponent]] runModal];
6600 /* otherwise, go ahead and populate table with array */
6601 for (i=0; i<chapters; i++)
6604 if([[chaptersMutableArray objectAtIndex:i] length] > 5)
6606 /* avoid a segfault */
6607 /* Get the Range.location of the first comma in the line and then put everything after that into chapterTitle */
6608 NSRange firstCommaRange = [[chaptersMutableArray objectAtIndex:i] rangeOfString:@","];
6609 NSString *chapterTitle = [[chaptersMutableArray objectAtIndex:i] substringFromIndex:firstCommaRange.location + 1];
6610 /* Since we store our chapterTitle commas as "\," for the cli, we now need to remove the escaping "\" from the title */
6611 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"\\," withString:@","];
6612 [fChapterTitlesDelegate tableView:fChapterTable
6613 setObjectValue:chapterTitle
6614 forTableColumn:fChapterTableNameColumn
6620 [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
6621 defaultButton:NSLocalizedString(@"OK", @"OK")
6622 alternateButton:NULL
6624 informativeTextWithFormat:NSLocalizedString(@"%@ was not formatted as expected.", @"%@ was not formatted as expected."), [[sheet filename] lastPathComponent]] runModal];
6625 [fChapterTable reloadData];
6629 [fChapterTable reloadData];
6633 - (IBAction) browseForChapterFileSave: (id) sender
6635 NSSavePanel *panel = [NSSavePanel savePanel];
6636 /* Open a panel to let the user save to a file */
6637 [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv",nil]];
6638 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent]
6639 file: [[[[fDstFile2Field stringValue] lastPathComponent] stringByDeletingPathExtension]
6640 stringByAppendingString:@"-chapters.csv"]
6641 modalForWindow: fWindow
6643 didEndSelector: @selector( browseForChapterFileSaveDone:returnCode:contextInfo: )
6647 - (void) browseForChapterFileSaveDone: (NSSavePanel *) sheet
6648 returnCode: (int) returnCode contextInfo: (void *) contextInfo
6650 NSString *chapterName; /* pointer for string for later file-writing */
6651 NSString *chapterTitle;
6652 NSError *saveError = [[NSError alloc] init];
6653 int chapters, i; /* ints for the number of chapters in the table and the loop */
6655 if( returnCode == NSOKButton ) /* if they clicked OK */
6657 chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
6658 chapterName = [NSString string];
6659 for (i=0; i<chapters; i++)
6661 /* put each chapter title from the table into the array */
6663 { /* if i is from 0 to 8 (chapters 1 to 9) add two leading zeros */
6664 chapterName = [chapterName stringByAppendingFormat:@"00%d,",i+1];
6667 { /* if i is from 9 to 98 (chapters 10 to 99) add one leading zero */
6668 chapterName = [chapterName stringByAppendingFormat:@"0%d,",i+1];
6671 { /* in case i is from 99 to 998 (chapters 100 to 999) no leading zeros */
6672 chapterName = [chapterName stringByAppendingFormat:@"%d,",i+1];
6675 chapterTitle = [fChapterTitlesDelegate tableView:fChapterTable objectValueForTableColumn:fChapterTableNameColumn row:i];
6676 /* escape any commas in the chapter name with "\," */
6677 chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"," withString:@"\\,"];
6678 chapterName = [chapterName stringByAppendingString:chapterTitle];
6679 if (i+1 != chapters)
6680 { /* if not the last chapter */
6681 chapterName = [chapterName stringByAppendingString:@ "\n"];
6686 /* try to write it to where the user wanted */
6687 if (![chapterName writeToFile:[sheet filename]
6689 encoding:NSUTF8StringEncoding
6693 [[NSAlert alertWithError:saveError] runModal];
6700 /*******************************
6701 * Subclass of the HBPresetsOutlineView *
6702 *******************************/
6704 @implementation HBPresetsOutlineView
6705 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
6709 // By default, NSTableView only drags an image of the first column. Change this to
6710 // drag an image of the queue's icon and PresetName columns.
6711 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
6712 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
6717 - (void) mouseDown:(NSEvent *)theEvent
6719 [super mouseDown:theEvent];
6725 - (BOOL) isDragging;