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. */
7 #include "Controller.h"
8 #include "a52dec/a52.h"
9 #import "HBOutputPanelController.h"
10 #import "HBPreferencesController.h"
11 /* Added to integrate scanning into HBController */
12 #include <IOKit/IOKitLib.h>
13 #include <IOKit/storage/IOMedia.h>
14 #include <IOKit/storage/IODVDMedia.h>
15 #include "HBDVDDetector.h"
16 #include "dvdread/dvd_reader.h"
17 #include "HBPresets.h"
19 #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
21 /* We setup the toolbar values here */
22 static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
23 static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
24 static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
25 static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
26 static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
27 static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
28 static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
31 /*******************************
32 * HBController implementation *
33 *******************************/
34 @implementation HBController
44 [HBPreferencesController registerUserDefaults];
47 /* Check for check for the app support directory here as
48 * outputPanel needs it right away, as may other future methods
50 NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
52 YES ) objectAtIndex:0];
53 AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
54 stringByAppendingPathComponent:@"HandBrake"];
55 if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
57 [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
61 outputPanel = [[HBOutputPanelController alloc] init];
62 fPictureController = [[PictureController alloc] initWithDelegate:self];
63 fQueueController = [[HBQueueController alloc] init];
64 fAdvancedOptions = [[HBAdvancedController alloc] init];
65 /* we init the HBPresets class which currently is only used
66 * for updating built in presets, may move more functionality
69 fPresetsBuiltin = [[HBPresets alloc] init];
70 fPreferencesController = [[HBPreferencesController alloc] init];
71 /* Lets report the HandBrake version number here to the activity log and text log file */
72 NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleGetInfoString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
73 [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
79 - (void) applicationDidFinishLaunching: (NSNotification *) notification
81 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
82 fHandle = hb_init(HB_DEBUG_ALL, 0);
84 // Set the Growl Delegate
85 [GrowlApplicationBridge setGrowlDelegate: self];
86 /* Init others controllers */
87 [fPictureController SetHandle: fHandle];
88 [fQueueController setHandle: fHandle];
89 [fQueueController setHBController: self];
91 fChapterTitlesDelegate = [[ChapterTitles alloc] init];
92 [fChapterTable setDataSource:fChapterTitlesDelegate];
93 [fChapterTable setDelegate:fChapterTitlesDelegate];
95 /* Call UpdateUI every 1/2 sec */
96 [[NSRunLoop currentRunLoop] addTimer: [NSTimer
97 scheduledTimerWithTimeInterval: 0.5 target: self
98 selector: @selector( updateUI: ) userInfo: NULL repeats: YES]
99 forMode: NSEventTrackingRunLoopMode];
101 // Open debug output window now if it was visible when HB was closed
102 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
103 [self showDebugOutputPanel:nil];
105 // Open queue window now if it was visible when HB was closed
106 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
107 [self showQueueWindow:nil];
109 [self openMainWindow:nil];
111 /* Show Browse Sources Window ASAP */
112 [self performSelectorOnMainThread: @selector(browseSources:)
113 withObject: NULL waitUntilDone: NO];
116 - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
118 // Warn if encoding a movie
120 hb_get_state( fHandle, &s );
121 HBJobGroup * jobGroup = [fQueueController currentJobGroup];
122 if ( jobGroup && ( s.state != HB_STATE_IDLE ) )
124 int result = NSRunCriticalAlertPanel(
125 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
126 NSLocalizedString(@"%@ is currently encoding. If you quit HandBrake, your movie will be lost. Do you want to quit anyway?", nil),
127 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil,
128 jobGroup ? [jobGroup name] : @"A movie" );
130 if (result == NSAlertDefaultReturn)
132 [self doCancelCurrentJob];
133 return NSTerminateNow;
136 return NSTerminateCancel;
139 // Warn if items still in the queue
140 else if ( hb_count( fHandle ) > 0 )
142 int result = NSRunCriticalAlertPanel(
143 NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
144 NSLocalizedString(@"One or more encodes are queued for encoding. Do you want to quit anyway?", nil),
145 NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
147 if ( result == NSAlertDefaultReturn )
148 return NSTerminateNow;
150 return NSTerminateCancel;
153 return NSTerminateNow;
156 - (void)applicationWillTerminate:(NSNotification *)aNotification
158 [browsedSourceDisplayName release];
159 [outputPanel release];
160 [fQueueController release];
165 - (void) awakeFromNib
168 [fWindow setExcludedFromWindowsMenu:YES];
169 [fAdvancedOptions setView:fAdvancedView];
171 /* lets setup our presets drawer for drag and drop here */
172 [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
173 [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
174 [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
176 /* Initialize currentScanCount so HB can use it to
177 evaluate successive scans */
178 currentScanCount = 0;
180 /* Init UserPresets .plist */
183 fRipIndicatorShown = NO; // initially out of view in the nib
185 /* Show/Dont Show Presets drawer upon launch based
186 on user preference DefaultPresetsDrawerShow*/
187 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0)
189 [fPresetDrawer open];
195 NSMenuItem *menuItem;
196 [fDstFormatPopUp removeAllItems];
198 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
199 [menuItem setTag: HB_MUX_MP4];
201 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
202 [menuItem setTag: HB_MUX_MKV];
204 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"AVI file" action: NULL keyEquivalent: @""];
205 [menuItem setTag: HB_MUX_AVI];
207 menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"OGM file" action: NULL keyEquivalent: @""];
208 [menuItem setTag: HB_MUX_OGM];
209 [fDstFormatPopUp selectItemAtIndex: 0];
211 [self formatPopUpChanged: NULL];
213 /* We enable the create chapters checkbox here since we are .mp4 */
214 [fCreateChapterMarkers setEnabled: YES];
215 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
217 [fCreateChapterMarkers setState: NSOnState];
223 [fDstFile2Field setStringValue: [NSString stringWithFormat:
224 @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
227 [fVidEncoderPopUp removeAllItems];
228 [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
229 [fVidEncoderPopUp addItemWithTitle: @"XviD"];
234 [fVidTargetSizeField setIntValue: 700];
235 [fVidBitrateField setIntValue: 1000];
237 [fVidQualityMatrix selectCell: fVidBitrateCell];
238 [self videoMatrixChanged: NULL];
240 /* Video framerate */
241 [fVidRatePopUp removeAllItems];
242 [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
243 for( int i = 0; i < hb_video_rates_count; i++ )
245 if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
247 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
248 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
250 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
252 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
253 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
255 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
257 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
258 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
262 [fVidRatePopUp addItemWithTitle:
263 [NSString stringWithCString: hb_video_rates[i].string]];
266 [fVidRatePopUp selectItemAtIndex: 0];
268 /* Set Auto Crop to On at launch */
269 [fPictureController setAutoCrop:YES];
272 [fAudTrack1BitratePopUp removeAllItems];
273 for( int i = 0; i < hb_audio_bitrates_count; i++ )
275 [fAudTrack1BitratePopUp addItemWithTitle:
276 [NSString stringWithCString: hb_audio_bitrates[i].string]];
279 [fAudTrack1BitratePopUp selectItemAtIndex: hb_audio_bitrates_default];
281 /* Audio samplerate */
282 [fAudTrack1RatePopUp removeAllItems];
283 for( int i = 0; i < hb_audio_rates_count; i++ )
285 [fAudTrack1RatePopUp addItemWithTitle:
286 [NSString stringWithCString: hb_audio_rates[i].string]];
288 [fAudTrack1RatePopUp selectItemAtIndex: hb_audio_rates_default];
291 [fStatusField setStringValue: @""];
296 [fPresetsActionButton setMenu:fPresetsActionMenu];
298 /* We disable the Turbo 1st pass checkbox since we are not x264 */
299 [fVidTurboPassCheck setEnabled: NO];
300 [fVidTurboPassCheck setState: NSOffState];
303 /* lets get our default prefs here */
304 [self getDefaultPresets: NULL];
305 /* lets initialize the current successful scancount here to 0 */
306 currentSuccessfulScanCount = 0;
310 - (void) enableUI: (bool) b
312 NSControl * controls[] =
313 { fSrcTitleField, fSrcTitlePopUp,
314 fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
315 fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
316 fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
317 fDstBrowseButton, fVidRateField, fVidRatePopUp,
318 fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
319 fVidQualityMatrix, fVidGrayscaleCheck, fSubField, fSubPopUp,
320 fAudSourceLabel, fAudCodecLabel, fAudMixdownLabel, fAudSamplerateLabel, fAudBitrateLabel,
321 fAudTrack1Label, fAudTrack2Label, fAudTrack3Label, fAudTrack4Label,
322 fAudLang1PopUp, fAudLang2PopUp, fAudLang3PopUp, fAudLang4PopUp,
323 fAudTrack1CodecPopUp, fAudTrack2CodecPopUp, fAudTrack3CodecPopUp, fAudTrack4CodecPopUp,
324 fAudTrack1MixPopUp, fAudTrack2MixPopUp, fAudTrack3MixPopUp, fAudTrack4MixPopUp,
325 fAudTrack1RatePopUp, fAudTrack2RatePopUp, fAudTrack3RatePopUp, fAudTrack4RatePopUp,
326 fAudTrack1BitratePopUp, fAudTrack2BitratePopUp, fAudTrack3BitratePopUp, fAudTrack4BitratePopUp,
327 fAudDrcLabel, fAudTrack1DrcSlider, fAudTrack1DrcField, fAudTrack2DrcSlider,
328 fAudTrack2DrcField, fAudTrack3DrcSlider, fAudTrack3DrcField, fAudTrack4DrcSlider,fAudTrack4DrcField,
329 fPictureButton,fQueueStatus,fPicSettingARkeep, fPicSettingDeinterlace,fPicLabelSettings,fPicLabelSrc,
330 fPicLabelOutp,fPicSettingsSrc,fPicSettingsOutp,fPicSettingsAnamorphic,
331 fPicLabelAr,fPicLabelDeinterlace,fPicSettingPAR,fPicLabelAnamorphic,fPresetsAdd,fPresetsDelete,
332 fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fPicLabelAutoCrop,
333 fPicSettingAutoCrop,fPicSettingDetelecine,fPicLabelDetelecine,fPicLabelDenoise,fPicSettingDenoise,
334 fSubForcedCheck,fPicSettingDeblock,fPicLabelDeblock,fPicLabelDecomb,fPicSettingDecomb,fPresetsOutlineView,
335 fAudDrcLabel,fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck};
338 i < sizeof( controls ) / sizeof( NSControl * ); i++ )
340 if( [[controls[i] className] isEqualToString: @"NSTextField"] )
342 NSTextField * tf = (NSTextField *) controls[i];
343 if( ![tf isBezeled] )
345 [tf setTextColor: b ? [NSColor controlTextColor] :
346 [NSColor disabledControlTextColor]];
350 [controls[i] setEnabled: b];
356 /* if we're enabling the interface, check if the audio mixdown controls need to be enabled or not */
357 /* these will have been enabled by the mass control enablement above anyway, so we're sense-checking it here */
358 [self setEnabledStateOfAudioMixdownControls: NULL];
359 /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
360 [self calculatePictureSizing: NULL];
364 [fPresetsOutlineView setEnabled: NO];
368 [self videoMatrixChanged: NULL];
369 [fAdvancedOptions enableUI:b];
373 /***********************************************************************
375 ***********************************************************************
376 * Shows a progression bar on the dock icon, filled according to
377 * 'progress' (0.0 <= progress <= 1.0).
378 * Called with progress < 0.0 or progress > 1.0, restores the original
380 **********************************************************************/
381 - (void) UpdateDockIcon: (float) progress
385 NSBitmapImageRep * bmp;
387 uint32_t black = htonl( 0x000000FF );
388 uint32_t red = htonl( 0xFF0000FF );
389 uint32_t white = htonl( 0xFFFFFFFF );
390 int row_start, row_end;
393 /* Get application original icon */
394 icon = [NSImage imageNamed: @"NSApplicationIcon"];
396 if( progress < 0.0 || progress > 1.0 )
398 [NSApp setApplicationIconImage: icon];
402 /* Get it in a raw bitmap form */
403 tiff = [icon TIFFRepresentationUsingCompression:
404 NSTIFFCompressionNone factor: 1.0];
405 bmp = [NSBitmapImageRep imageRepWithData: tiff];
407 /* Draw the progression bar */
408 /* It's pretty simple (ugly?) now, but I'm no designer */
410 row_start = 3 * (int) [bmp size].height / 4;
411 row_end = 7 * (int) [bmp size].height / 8;
413 for( i = row_start; i < row_start + 2; i++ )
415 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
416 for( j = 0; j < (int) [bmp size].width; j++ )
421 for( i = row_start + 2; i < row_end - 2; i++ )
423 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
426 for( j = 2; j < (int) [bmp size].width - 2; j++ )
428 if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
440 for( i = row_end - 2; i < row_end; i++ )
442 pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
443 for( j = 0; j < (int) [bmp size].width; j++ )
449 /* Now update the dock icon */
450 tiff = [bmp TIFFRepresentationUsingCompression:
451 NSTIFFCompressionNone factor: 1.0];
452 icon = [[NSImage alloc] initWithData: tiff];
453 [NSApp setApplicationIconImage: icon];
457 - (void) updateUI: (NSTimer *) timer
461 list = hb_get_titles( fHandle );
462 /* check to see if there has been a new scan done
463 this bypasses the constraints of HB_STATE_WORKING
464 not allowing setting a newly scanned source */
465 int checkScanCount = hb_get_scancount( fHandle );
466 if (checkScanCount > currentScanCount)
469 currentScanCount = checkScanCount;
470 [fScanIndicator setIndeterminate: NO];
471 [fScanIndicator setDoubleValue: 0.0];
472 [fScanIndicator setHidden: YES];
473 [self showNewScan: NULL];
477 hb_get_state( fHandle, &s );
484 #define p s.param.scanning
485 case HB_STATE_SCANNING:
487 [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
488 NSLocalizedString( @"Scanning title %d of %d...", @"" ),
489 p.title_cur, p.title_count]];
490 [fScanIndicator setHidden: NO];
491 [fScanIndicator setDoubleValue: 100.0 * ( p.title_cur - 1 ) / p.title_count];
496 #define p s.param.scandone
497 case HB_STATE_SCANDONE:
499 [fScanIndicator setIndeterminate: NO];
500 [fScanIndicator setDoubleValue: 0.0];
501 [fScanIndicator setHidden: YES];
502 [self showNewScan: NULL];
503 [[fWindow toolbar] validateVisibleItems];
508 #define p s.param.working
509 case HB_STATE_WORKING:
511 float progress_total;
512 NSMutableString * string;
513 /* Currently, p.job_cur and p.job_count get screwed up when adding
514 jobs during encoding, if they cannot be fixed in libhb, will implement a
515 nasty but working cocoa solution */
516 /* Update text field */
517 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: task %d of %d, %.2f %%", @"" ), p.job_cur, p.job_count, 100.0 * p.progress];
521 [string appendFormat:
522 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
523 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
525 [fStatusField setStringValue: string];
528 progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
529 [fRipIndicator setIndeterminate: NO];
530 [fRipIndicator setDoubleValue: 100.0 * progress_total];
532 // If progress bar hasn't been revealed at the bottom of the window, do
533 // that now. This code used to be in doRip. I moved it to here to handle
534 // the case where hb_start is called by HBQueueController and not from
536 if (!fRipIndicatorShown)
538 NSRect frame = [fWindow frame];
539 if (frame.size.width <= 591)
540 frame.size.width = 591;
541 frame.size.height += 36;
542 frame.origin.y -= 36;
543 [fWindow setFrame:frame display:YES animate:YES];
544 fRipIndicatorShown = YES;
545 /* We check to see if we need to warn the user that the computer will go to sleep
546 or shut down when encoding is finished */
547 [self remindUserOfSleepOrShutdown];
550 /* Update dock icon */
551 [self UpdateDockIcon: progress_total];
553 // Has current job changed? That means the queue has probably changed as
555 [fQueueController libhbStateChanged: s];
561 #define p s.param.muxing
562 case HB_STATE_MUXING:
564 NSMutableString * string;
566 /* Update text field */
567 string = [NSMutableString stringWithFormat:
568 NSLocalizedString( @"Muxing...", @"" )];
569 [fStatusField setStringValue: string];
572 [fRipIndicator setIndeterminate: YES];
573 [fRipIndicator startAnimation: nil];
575 /* Update dock icon */
576 [self UpdateDockIcon: 1.0];
578 // Pass along the info to HBQueueController
579 [fQueueController libhbStateChanged: s];
585 case HB_STATE_PAUSED:
586 [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
588 // Pass along the info to HBQueueController
589 [fQueueController libhbStateChanged: s];
593 case HB_STATE_WORKDONE:
595 // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
596 // or someone calling hb_stop. In the latter case, hb_stop does not clear
597 // out the remaining passes/jobs in the queue. We'll do that here.
599 // Delete all remaining jobs of this encode.
601 while( ( job = hb_job( fHandle, 0 ) ) && ( !IsFirstPass(job->sequence_id) ) )
602 hb_rem( fHandle, job );
604 [fStatusField setStringValue: NSLocalizedString( @"Done.", @"" )];
605 [fRipIndicator setIndeterminate: NO];
606 [fRipIndicator setDoubleValue: 0.0];
607 [[fWindow toolbar] validateVisibleItems];
609 /* Restore dock icon */
610 [self UpdateDockIcon: -1.0];
612 if (fRipIndicatorShown)
614 NSRect frame = [fWindow frame];
615 if (frame.size.width <= 591)
616 frame.size.width = 591;
617 frame.size.height += -36;
618 frame.origin.y -= -36;
619 [fWindow setFrame:frame display:YES animate:YES];
620 fRipIndicatorShown = NO;
623 // Pass along the info to HBQueueController
624 [fQueueController libhbStateChanged: s];
626 /* Check to see if the encode state has not been cancelled
627 to determine if we should check for encode done notifications */
628 if (fEncodeState != 2) {
629 /* If Alert Window or Window and Growl has been selected */
630 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
631 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
633 /*On Screen Notification*/
636 status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake encode is done!", @"OK", nil, nil);
637 [NSApp requestUserAttention:NSCriticalRequest];
638 if ( status == NSAlertDefaultReturn )
640 [self enableUI: YES];
645 [self enableUI: YES];
647 /* If sleep has been selected */
648 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
651 NSDictionary* errorDict;
652 NSAppleEventDescriptor* returnDescriptor = NULL;
653 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
654 @"tell application \"Finder\" to sleep"];
655 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
656 [scriptObject release];
657 [self enableUI: YES];
659 /* If Shutdown has been selected */
660 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
663 NSDictionary* errorDict;
664 NSAppleEventDescriptor* returnDescriptor = NULL;
665 NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
666 @"tell application \"Finder\" to shut down"];
667 returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
668 [scriptObject release];
669 [self enableUI: YES];
675 [self enableUI: YES];
681 /* Lets show the queue status here in the main window */
682 int queue_count = [fQueueController pendingCount];
683 if( queue_count == 1)
684 [fQueueStatus setStringValue: NSLocalizedString( @"1 encode queued", @"" ) ];
685 else if (queue_count > 1)
686 [fQueueStatus setStringValue: [NSString stringWithFormat: NSLocalizedString( @"%d encodes queued", @"" ), queue_count]];
688 [fQueueStatus setStringValue: @""];
691 /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
692 - (void) writeToActivityLog:(char *) format, ...
695 va_start(args, format);
699 vsnprintf( str, 1024, format, args );
701 time_t _now = time( NULL );
702 struct tm * now = localtime( &_now );
703 fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
710 // ============================================================
711 // NSToolbar Related Methods
712 // ============================================================
714 - (void) setupToolbar {
715 NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
717 [toolbar setAllowsUserCustomization: YES];
718 [toolbar setAutosavesConfiguration: YES];
719 [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
721 [toolbar setDelegate: self];
723 [fWindow setToolbar: toolbar];
726 - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
727 (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
728 NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
730 if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
732 [item setLabel: @"Toggle Presets"];
733 [item setPaletteLabel: @"Toggler Presets"];
734 [item setToolTip: @"Open/Close Preset Drawer"];
735 [item setImage: [NSImage imageNamed: @"Drawer"]];
736 [item setTarget: self];
737 [item setAction: @selector(toggleDrawer:)];
738 [item setAutovalidates: NO];
740 else if ([itemIdent isEqualToString: StartEncodingIdentifier])
742 [item setLabel: @"Start"];
743 [item setPaletteLabel: @"Start Encoding"];
744 [item setToolTip: @"Start Encoding"];
745 [item setImage: [NSImage imageNamed: @"Play"]];
746 [item setTarget: self];
747 [item setAction: @selector(Rip:)];
749 else if ([itemIdent isEqualToString: ShowQueueIdentifier])
751 [item setLabel: @"Show Queue"];
752 [item setPaletteLabel: @"Show Queue"];
753 [item setToolTip: @"Show Queue"];
754 [item setImage: [NSImage imageNamed: @"Queue"]];
755 [item setTarget: self];
756 [item setAction: @selector(showQueueWindow:)];
757 [item setAutovalidates: NO];
759 else if ([itemIdent isEqualToString: AddToQueueIdentifier])
761 [item setLabel: @"Add to Queue"];
762 [item setPaletteLabel: @"Add to Queue"];
763 [item setToolTip: @"Add to Queue"];
764 [item setImage: [NSImage imageNamed: @"AddToQueue"]];
765 [item setTarget: self];
766 [item setAction: @selector(addToQueue:)];
768 else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
770 [item setLabel: @"Pause"];
771 [item setPaletteLabel: @"Pause Encoding"];
772 [item setToolTip: @"Pause Encoding"];
773 [item setImage: [NSImage imageNamed: @"Pause"]];
774 [item setTarget: self];
775 [item setAction: @selector(Pause:)];
777 else if ([itemIdent isEqualToString: ShowActivityIdentifier]) {
778 [item setLabel: @"Activity Window"];
779 [item setPaletteLabel: @"Show Activity Window"];
780 [item setToolTip: @"Show Activity Window"];
781 [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
782 [item setTarget: self];
783 [item setAction: @selector(showDebugOutputPanel:)];
784 [item setAutovalidates: NO];
786 else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
788 [item setLabel: @"Source"];
789 [item setPaletteLabel: @"Source"];
790 [item setToolTip: @"Choose Video Source"];
791 [item setImage: [NSImage imageNamed: @"Source"]];
792 [item setTarget: self];
793 [item setAction: @selector(browseSources:)];
803 - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
805 return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
806 PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
807 NSToolbarSpaceItemIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
810 - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
812 return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
813 ChooseSourceIdentifier, ShowQueueIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
814 NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
815 NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
818 - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
820 NSString * ident = [toolbarItem itemIdentifier];
825 hb_get_state2( fHandle, &s );
827 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING)
829 if ([ident isEqualToString: StartEncodingIdentifier])
831 [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
832 [toolbarItem setLabel: @"Stop"];
833 [toolbarItem setPaletteLabel: @"Stop"];
834 [toolbarItem setToolTip: @"Stop Encoding"];
837 if ([ident isEqualToString: PauseEncodingIdentifier])
839 [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
840 [toolbarItem setLabel: @"Pause"];
841 [toolbarItem setPaletteLabel: @"Pause Encoding"];
842 [toolbarItem setToolTip: @"Pause Encoding"];
846 if ([ident isEqualToString: AddToQueueIdentifier])
849 else if (s.state == HB_STATE_PAUSED)
851 if ([ident isEqualToString: PauseEncodingIdentifier])
853 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
854 [toolbarItem setLabel: @"Resume"];
855 [toolbarItem setPaletteLabel: @"Resume Encoding"];
856 [toolbarItem setToolTip: @"Resume Encoding"];
859 if ([ident isEqualToString: StartEncodingIdentifier])
861 if ([ident isEqualToString: AddToQueueIdentifier])
864 else if (s.state == HB_STATE_SCANNING)
866 else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
868 if ([ident isEqualToString: StartEncodingIdentifier])
870 [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
871 if (hb_count(fHandle) > 0)
872 [toolbarItem setLabel: @"Start Queue"];
874 [toolbarItem setLabel: @"Start"];
875 [toolbarItem setPaletteLabel: @"Start Encoding"];
876 [toolbarItem setToolTip: @"Start Encoding"];
879 if ([ident isEqualToString: AddToQueueIdentifier])
885 if ([ident isEqualToString: ShowQueueIdentifier])
887 if ([ident isEqualToString: ToggleDrawerIdentifier])
889 if ([ident isEqualToString: ChooseSourceIdentifier])
891 if ([ident isEqualToString: ShowActivityIdentifier])
897 - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
899 SEL action = [menuItem action];
902 hb_get_state2( fHandle, &s );
906 if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
907 return SuccessfulScan && [fWindow attachedSheet] == nil;
909 if (action == @selector(browseSources:))
911 if (s.state == HB_STATE_SCANNING)
914 return [fWindow attachedSheet] == nil;
916 if (action == @selector(selectDefaultPreset:))
917 return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
918 if (action == @selector(Pause:))
920 if (s.state == HB_STATE_WORKING)
922 if(![[menuItem title] isEqualToString:@"Pause Encoding"])
923 [menuItem setTitle:@"Pause Encoding"];
926 else if (s.state == HB_STATE_PAUSED)
928 if(![[menuItem title] isEqualToString:@"Resume Encoding"])
929 [menuItem setTitle:@"Resume Encoding"];
935 if (action == @selector(Rip:))
936 if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
938 if(![[menuItem title] isEqualToString:@"Stop Encoding"])
939 [menuItem setTitle:@"Stop Encoding"];
942 else if (SuccessfulScan)
944 if(![[menuItem title] isEqualToString:@"Start Encoding"])
945 [menuItem setTitle:@"Start Encoding"];
946 return [fWindow attachedSheet] == nil;
956 #pragma mark Encode Done Actions
957 // register a test notification and make
958 // it enabled by default
959 #define SERVICE_NAME @"Encode Done"
960 - (NSDictionary *)registrationDictionaryForGrowl
962 NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
963 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
964 [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
967 return registrationDictionary;
970 -(void)showGrowlDoneNotification:(NSString *) filePath
972 /* This is called from HBQueueController as jobs roll off of the queue in currentJobChanged */
973 NSString * finishedEncode = filePath;
974 /* strip off the path to just show the file name */
975 finishedEncode = [finishedEncode lastPathComponent];
976 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
977 [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
979 NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
980 [GrowlApplicationBridge
981 notifyWithTitle:@"Put down that cocktail..."
982 description:growlMssg
983 notificationName:SERVICE_NAME
991 -(void)sendToMetaX:(NSString *) filePath
993 /* This is called from HBQueueController as jobs roll off of the queue in currentJobChanged */
994 if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
996 NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@", @"tell application \"MetaX\" to open (POSIX file \"", filePath, @"\")"]];
997 [myScript executeAndReturnError: nil];
1002 #pragma mark Get New Source
1004 /*Opens the source browse window, called from Open Source widgets */
1005 - (IBAction) browseSources: (id) sender
1007 [self enableUI: NO];
1008 NSOpenPanel * panel;
1010 panel = [NSOpenPanel openPanel];
1011 [panel setAllowsMultipleSelection: NO];
1012 [panel setCanChooseFiles: YES];
1013 [panel setCanChooseDirectories: YES ];
1014 NSString * sourceDirectory;
1015 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
1017 sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
1021 sourceDirectory = @"~/Desktop";
1022 sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
1024 /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
1025 * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
1027 [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
1028 modalForWindow: fWindow modalDelegate: self
1029 didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
1030 contextInfo: sender];
1033 - (void) browseSourcesDone: (NSOpenPanel *) sheet
1034 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1036 /* we convert the sender content of contextInfo back into a variable called sender
1037 * mostly just for consistency for evaluation later
1039 id sender = (id)contextInfo;
1040 /* User selected a file to open */
1041 if( returnCode == NSOKButton )
1043 /* Free display name allocated previously by this code */
1044 [browsedSourceDisplayName release];
1046 NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
1047 /* we set the last searched source directory in the prefs here */
1048 NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
1049 [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
1050 /* we order out sheet, which is the browse window as we need to open
1051 * the title selection sheet right away
1053 [sheet orderOut: self];
1055 if (sender == fOpenSourceTitleMMenu)
1057 /* We put the chosen source path in the source display text field for the
1058 * source title selection sheet in which the user specifies the specific title to be
1059 * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
1060 * purposes in the title panel
1063 [fScanSrcTitlePathField setStringValue:scanPath];
1064 NSString *displayTitlescanSourceName;
1066 if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
1068 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
1069 we have to use the title->dvd value so we get the proper name of the volume if a physical dvd is the source*/
1070 displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
1074 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1075 displayTitlescanSourceName = [scanPath lastPathComponent];
1077 /* we set the source display name in the title selection dialogue */
1078 [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
1079 /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
1080 browsedSourceDisplayName = [displayTitlescanSourceName retain];
1081 /* We show the actual sheet where the user specifies the title to be scanned
1082 * as we are going to do a title specific scan
1084 [self showSourceTitleScanPanel:NULL];
1088 /* We are just doing a standard full source scan, so we specify "0" to libhb */
1089 NSString *path = [[sheet filenames] objectAtIndex: 0];
1091 /* We check to see if the chosen file at path is a package */
1092 if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
1094 [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
1095 /* We check to see if this is an .eyetv package */
1096 if ([[path pathExtension] isEqualToString: @"eyetv"])
1098 [self writeToActivityLog:"trying to open eyetv package"];
1099 /* We're looking at an EyeTV package - try to open its enclosed
1101 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1103 int n = [[path stringByAppendingString: @"/"]
1104 completePathIntoString: &mpgname caseSensitive: NO
1105 matchesIntoArray: nil
1106 filterTypes: [NSArray arrayWithObject: @"mpg"]];
1109 /* Found an mpeg inside the eyetv package, make it our scan path
1110 and call performScan on the enclosed mpeg */
1112 [self writeToActivityLog:"found mpeg in eyetv package"];
1113 [self performScan:path scanTitleNum:0];
1117 /* We did not find an mpeg file in our package, so we do not call performScan */
1118 [self writeToActivityLog:"no valid mpeg in eyetv package"];
1121 /* We check to see if this is a .dvdmedia package */
1122 else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
1124 /* path IS a package - but dvdmedia packages can be treaded like normal directories */
1125 browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
1126 [self writeToActivityLog:"trying to open dvdmedia package"];
1127 [self performScan:path scanTitleNum:0];
1131 /* The package is not an eyetv package, so we do not call performScan */
1132 [self writeToActivityLog:"unable to open package"];
1135 else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
1137 /* path is not a package, so we call perform scan directly on our file */
1138 if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
1140 [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
1141 /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
1142 browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
1146 [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
1147 /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
1148 /* make sure we remove any path extension as this can also be an '.mpg' file */
1149 browsedSourceDisplayName = [[path lastPathComponent] retain];
1151 [self performScan:path scanTitleNum:0];
1157 else // User clicked Cancel in browse window
1159 /* if we have a title loaded up */
1160 if ([[fSrcDVD2Field stringValue] length] > 0)
1162 [self enableUI: YES];
1167 /* Here we open the title selection sheet where we can specify an exact title to be scanned */
1168 - (IBAction) showSourceTitleScanPanel: (id) sender
1170 /* We default the title number to be scanned to "0" which results in a full source scan, unless the
1173 [fScanSrcTitleNumField setStringValue: @"0"];
1174 /* Show the panel */
1175 [NSApp beginSheet: fScanSrcTitlePanel modalForWindow: fWindow modalDelegate: NULL didEndSelector: NULL contextInfo: NULL];
1178 - (IBAction) closeSourceTitleScanPanel: (id) sender
1180 [NSApp endSheet: fScanSrcTitlePanel];
1181 [fScanSrcTitlePanel orderOut: self];
1185 if(sender == fScanSrcTitleOpenButton)
1187 /* We setup the scan status in the main window to indicate a source title scan */
1188 [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
1189 [fScanIndicator setHidden: NO];
1190 [fScanIndicator setIndeterminate: YES];
1191 [fScanIndicator startAnimation: nil];
1193 /* We use the performScan method to actually perform the specified scan passing the path and the title
1196 [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
1201 /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
1202 - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
1204 /* use a bool to determine whether or not we can decrypt using vlc */
1205 BOOL cancelScanDecrypt = 0;
1206 NSString *path = scanPath;
1207 HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
1208 if( [detector isVideoDVD] )
1210 // The chosen path was actually on a DVD, so use the raw block
1211 // device path instead.
1212 path = [detector devicePath];
1213 [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
1215 /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
1216 NSString *vlcPath = @"/Applications/VLC.app";
1217 NSFileManager * fileManager = [NSFileManager defaultManager];
1218 if ([fileManager fileExistsAtPath:vlcPath] == 0)
1220 /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
1221 cancelScanDecrypt = 1;
1222 [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
1224 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");
1225 [NSApp requestUserAttention:NSCriticalRequest];
1227 if (status == NSAlertDefaultReturn)
1229 /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
1230 [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
1232 else if (status == NSAlertAlternateReturn)
1234 /* User chose to cancel the scan */
1235 [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
1239 /* 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 */
1240 cancelScanDecrypt = 0;
1241 [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
1247 /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
1248 [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
1255 if (cancelScanDecrypt == 0)
1258 /* we actually pass the scan off to libhb here */
1259 /* If there is no title number passed to scan, we use "0"
1260 * which causes the default behavior of a full source scan
1266 if (scanTitleNum > 0)
1268 [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
1270 hb_scan( fHandle, [path UTF8String], scanTitleNum );
1271 [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
1275 /* if we have a title loaded up */
1276 if ([[fSrcDVD2Field stringValue] length] > 0)
1278 [self enableUI: YES];
1285 - (IBAction) showNewScan:(id)sender
1289 int indxpri=0; // Used to search the longuest title (default in combobox)
1290 int longuestpri=0; // Used to search the longuest title (default in combobox)
1292 list = hb_get_titles( fHandle );
1294 if( !hb_list_count( list ) )
1296 /* We display a message if a valid dvd source was not chosen */
1297 [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
1298 SuccessfulScan = NO;
1300 // Notify ChapterTitles that there's no title
1301 [fChapterTitlesDelegate resetWithTitle:nil];
1302 [fChapterTable reloadData];
1306 /* We increment the successful scancount here by one,
1307 which we use at the end of this function to tell the gui
1308 if this is the first successful scan since launch and whether
1309 or not we should set all settings to the defaults */
1311 currentSuccessfulScanCount++;
1313 [[fWindow toolbar] validateVisibleItems];
1315 [fSrcTitlePopUp removeAllItems];
1316 for( int i = 0; i < hb_list_count( list ); i++ )
1318 title = (hb_title_t *) hb_list_item( list, i );
1320 currentSource = [NSString stringWithUTF8String: title->name];
1322 /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
1323 [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
1325 /* Use the dvd name in the default output field here
1326 May want to add code to remove blank spaces for some dvd names*/
1327 /* Check to see if the last destination has been set,use if so, if not, use Desktop */
1328 if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
1330 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1331 @"%@/%@.mp4", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension]]];
1335 [fDstFile2Field setStringValue: [NSString stringWithFormat:
1336 @"%@/Desktop/%@.mp4", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension]]];
1339 if (longuestpri < title->hours*60*60 + title->minutes *60 + title->seconds)
1341 longuestpri=title->hours*60*60 + title->minutes *60 + title->seconds;
1344 /* Leave this here for now for reference. Keep it commented out or the macgui will crash in a
1345 * fiery wreck if you change sources.
1347 //[self formatPopUpChanged:NULL];
1349 [fSrcTitlePopUp addItemWithTitle: [NSString
1350 stringWithFormat: @"%d - %02dh%02dm%02ds",
1351 title->index, title->hours, title->minutes,
1355 // Select the longuest title
1356 [fSrcTitlePopUp selectItemAtIndex: indxpri];
1357 [self titlePopUpChanged: NULL];
1359 SuccessfulScan = YES;
1360 [self enableUI: YES];
1362 /* if its the initial successful scan after awakeFromNib */
1363 if (currentSuccessfulScanCount == 1)
1365 [self selectDefaultPreset: NULL];
1366 /* if Deinterlace upon launch is specified in the prefs, then set to 1 for "Fast",
1367 if not, then set to 0 for none */
1368 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultDeinterlaceOn"] > 0)
1370 [fPictureController setDeinterlace:1];
1374 [fPictureController setDeinterlace:0];
1376 /* lets set Denoise to index 0 or "None" since this is the first scan */
1377 [fPictureController setDenoise:0];
1379 [fPictureController setInitialPictureFilters];
1387 #pragma mark New Output Destination
1389 - (IBAction) browseFile: (id) sender
1391 /* Open a panel to let the user choose and update the text field */
1392 NSSavePanel * panel = [NSSavePanel savePanel];
1393 /* We get the current file name and path from the destination field here */
1394 [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
1395 modalForWindow: fWindow modalDelegate: self
1396 didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
1400 - (void) browseFileDone: (NSSavePanel *) sheet
1401 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1403 if( returnCode == NSOKButton )
1405 [fDstFile2Field setStringValue: [sheet filename]];
1411 #pragma mark Main Window Control
1413 - (IBAction) openMainWindow: (id) sender
1415 [fWindow makeKeyAndOrderFront:nil];
1418 - (BOOL) windowShouldClose: (id) sender
1423 - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
1426 [fWindow makeKeyAndOrderFront:nil];
1435 #pragma mark Job Handling
1440 hb_list_t * list = hb_get_titles( fHandle );
1441 hb_title_t * title = (hb_title_t *) hb_list_item( list,
1442 [fSrcTitlePopUp indexOfSelectedItem] );
1443 hb_job_t * job = title->job;
1444 hb_audio_config_t * audio;
1446 /* Chapter selection */
1447 job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
1448 job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
1450 /* Format (Muxer) and Video Encoder */
1451 job->mux = [[fDstFormatPopUp selectedItem] tag];
1452 job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
1455 /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
1456 if ([fDstFormatPopUp indexOfSelectedItem] == 0)
1458 /* We set the largeFileSize (64 bit formatting) variable here to allow for > 4gb files based on the format being
1459 mpeg4 and the checkbox being checked
1460 *Note: this will break compatibility with some target devices like iPod, etc.!!!!*/
1461 if ([fDstMp4LargeFileCheck state] == NSOnState)
1463 job->largeFileSize = 1;
1467 job->largeFileSize = 0;
1469 /* We set http optimized mp4 here */
1470 if ([fDstMp4HttpOptFileCheck state] == NSOnState)
1472 job->mp4_optimize = 1;
1476 job->mp4_optimize = 0;
1479 if ([fDstFormatPopUp indexOfSelectedItem] == 0 || [fDstFormatPopUp indexOfSelectedItem] == 1)
1481 /* We set the chapter marker extraction here based on the format being
1482 mpeg4 or mkv and the checkbox being checked */
1483 if ([fCreateChapterMarkers state] == NSOnState)
1485 job->chapter_markers = 1;
1489 job->chapter_markers = 0;
1493 if( job->vcodec & HB_VCODEC_X264 )
1495 if ([fDstMp4iPodFileCheck state] == NSOnState)
1504 /* Set this flag to switch from Constant Quantizer(default) to Constant Rate Factor Thanks jbrjake
1505 Currently only used with Constant Quality setting*/
1506 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultCrf"] > 0 && [fVidQualityMatrix selectedRow] == 2)
1511 /* Below Sends x264 options to the core library if x264 is selected*/
1512 /* Lets use this as per Nyx, Thanks Nyx!*/
1513 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
1514 /* Turbo first pass if two pass and Turbo First pass is selected */
1515 if( [fVidTwoPassCheck state] == NSOnState && [fVidTurboPassCheck state] == NSOnState )
1517 /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
1518 NSString *firstPassOptStringTurbo = @":ref=1:subme=1:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
1519 /* append the "Turbo" string variable to the existing opts string.
1520 Note: the "Turbo" string must be appended, not prepended to work properly*/
1521 NSString *firstPassOptStringCombined = [[fAdvancedOptions optionsString] stringByAppendingString:firstPassOptStringTurbo];
1522 strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
1526 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
1531 /* Video settings */
1532 if( [fVidRatePopUp indexOfSelectedItem] > 0 )
1534 job->vrate = 27000000;
1535 job->vrate_base = hb_video_rates[[fVidRatePopUp
1536 indexOfSelectedItem]-1].rate;
1537 /* We are not same as source so we set job->cfr to 1
1538 * to enable constant frame rate since user has specified
1539 * a specific framerate*/
1544 job->vrate = title->rate;
1545 job->vrate_base = title->rate_base;
1546 /* We are same as source so we set job->cfr to 0
1547 * to enable true same as source framerate */
1551 switch( [fVidQualityMatrix selectedRow] )
1555 Bitrate should already have been calculated and displayed
1556 in fVidBitrateField, so let's just use it */
1558 job->vquality = -1.0;
1559 job->vbitrate = [fVidBitrateField intValue];
1562 job->vquality = [fVidQualitySlider floatValue];
1567 job->grayscale = ( [fVidGrayscaleCheck state] == NSOnState );
1569 /* Subtitle settings */
1570 job->subtitle = [fSubPopUp indexOfSelectedItem] - 2;
1572 /* Audio tracks and mixdowns */
1573 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
1574 int audiotrack_count = hb_list_count(job->list_audio);
1575 for( int i = 0; i < audiotrack_count;i++)
1577 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
1578 hb_list_rem(job->list_audio, temp_audio);
1580 /* Now lets add our new tracks to the audio list here */
1581 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
1583 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
1584 hb_audio_config_init(audio);
1585 audio->in.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
1586 /* We go ahead and assign values to our audio->out.<properties> */
1587 audio->out.track = [fAudLang1PopUp indexOfSelectedItem] - 1;
1588 audio->out.codec = [[fAudTrack1CodecPopUp selectedItem] tag];
1589 audio->out.mixdown = [[fAudTrack1MixPopUp selectedItem] tag];
1590 audio->out.bitrate = [[fAudTrack1BitratePopUp selectedItem] tag];
1591 audio->out.samplerate = [[fAudTrack1RatePopUp selectedItem] tag];
1592 audio->out.dynamic_range_compression = [fAudTrack1DrcField floatValue];
1594 hb_audio_add( job, audio );
1597 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
1599 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
1600 hb_audio_config_init(audio);
1601 audio->in.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
1602 /* We go ahead and assign values to our audio->out.<properties> */
1603 audio->out.track = [fAudLang2PopUp indexOfSelectedItem] - 1;
1604 audio->out.codec = [[fAudTrack2CodecPopUp selectedItem] tag];
1605 audio->out.mixdown = [[fAudTrack2MixPopUp selectedItem] tag];
1606 audio->out.bitrate = [[fAudTrack2BitratePopUp selectedItem] tag];
1607 audio->out.samplerate = [[fAudTrack2RatePopUp selectedItem] tag];
1608 audio->out.dynamic_range_compression = [fAudTrack2DrcField floatValue];
1610 hb_audio_add( job, audio );
1615 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
1617 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
1618 hb_audio_config_init(audio);
1619 audio->in.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
1620 /* We go ahead and assign values to our audio->out.<properties> */
1621 audio->out.track = [fAudLang3PopUp indexOfSelectedItem] - 1;
1622 audio->out.codec = [[fAudTrack3CodecPopUp selectedItem] tag];
1623 audio->out.mixdown = [[fAudTrack3MixPopUp selectedItem] tag];
1624 audio->out.bitrate = [[fAudTrack3BitratePopUp selectedItem] tag];
1625 audio->out.samplerate = [[fAudTrack3RatePopUp selectedItem] tag];
1626 audio->out.dynamic_range_compression = [fAudTrack3DrcField floatValue];
1628 hb_audio_add( job, audio );
1633 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
1635 audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
1636 hb_audio_config_init(audio);
1637 audio->in.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
1638 /* We go ahead and assign values to our audio->out.<properties> */
1639 audio->out.track = [fAudLang4PopUp indexOfSelectedItem] - 1;
1640 audio->out.codec = [[fAudTrack4CodecPopUp selectedItem] tag];
1641 audio->out.mixdown = [[fAudTrack4MixPopUp selectedItem] tag];
1642 audio->out.bitrate = [[fAudTrack4BitratePopUp selectedItem] tag];
1643 audio->out.samplerate = [[fAudTrack4RatePopUp selectedItem] tag];
1644 audio->out.dynamic_range_compression = [fAudTrack4DrcField floatValue];
1646 hb_audio_add( job, audio );
1651 /* set vfr according to the Picture Window */
1652 if ([fPictureController vfr])
1662 job->filters = hb_list_init();
1664 /* Now lets call the filters if applicable.
1665 * The order of the filters is critical
1669 if ([fPictureController detelecine])
1671 hb_list_add( job->filters, &hb_filter_detelecine );
1675 if ([fPictureController decomb] > 0)
1677 /* Run old deinterlacer fd by default */
1679 hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
1680 //hb_filter_decomb.settings = "4:10:15:9:10:35:9"; // <-- jbrjakes recommended parameters as of 5/23/08
1681 hb_list_add( job->filters, &hb_filter_decomb );
1686 if ([fPictureController deinterlace] == 1)
1688 /* Run old deinterlacer fd by default */
1689 hb_filter_deinterlace.settings = "-1";
1690 hb_list_add( job->filters, &hb_filter_deinterlace );
1692 else if ([fPictureController deinterlace] == 2)
1694 /* Yadif mode 0 (without spatial deinterlacing.) */
1695 hb_filter_deinterlace.settings = "2";
1696 hb_list_add( job->filters, &hb_filter_deinterlace );
1698 else if ([fPictureController deinterlace] == 3)
1700 /* Yadif (with spatial deinterlacing) */
1701 hb_filter_deinterlace.settings = "0";
1702 hb_list_add( job->filters, &hb_filter_deinterlace );
1706 if ([fPictureController denoise] == 1) // Weak in popup
1708 hb_filter_denoise.settings = "2:1:2:3";
1709 hb_list_add( job->filters, &hb_filter_denoise );
1711 else if ([fPictureController denoise] == 2) // Medium in popup
1713 hb_filter_denoise.settings = "3:2:2:3";
1714 hb_list_add( job->filters, &hb_filter_denoise );
1716 else if ([fPictureController denoise] == 3) // Strong in popup
1718 hb_filter_denoise.settings = "7:7:5:5";
1719 hb_list_add( job->filters, &hb_filter_denoise );
1722 /* Deblock (uses pp7 default) */
1723 if ([fPictureController deblock])
1725 hb_list_add( job->filters, &hb_filter_deblock );
1732 /* addToQueue: puts up an alert before ultimately calling doAddToQueue
1734 - (IBAction) addToQueue: (id) sender
1736 /* We get the destination directory from the destination field here */
1737 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1738 /* We check for a valid destination here */
1739 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
1741 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
1745 /* We check for duplicate name here */
1746 if( [[NSFileManager defaultManager] fileExistsAtPath:
1747 [fDstFile2Field stringValue]] )
1749 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
1750 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), NULL, fWindow, self,
1751 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
1752 NULL, NULL, [NSString stringWithFormat:
1753 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
1754 [fDstFile2Field stringValue]] );
1755 // overwriteAddToQueueAlertDone: will be called when the alert is dismissed.
1758 // Warn if another pending job in the queue has the same destination path
1759 else if ( ([fQueueController pendingJobGroupWithDestinationPath:[fDstFile2Field stringValue]] != nil)
1760 || ([[[fQueueController currentJobGroup] destinationPath] isEqualToString: [fDstFile2Field stringValue]]) )
1762 NSBeginCriticalAlertSheet( NSLocalizedString( @"Another queued encode has specified the same destination.", @"" ),
1763 NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), NULL, fWindow, self,
1764 @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
1765 NULL, NULL, [NSString stringWithFormat:
1766 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
1767 [fDstFile2Field stringValue]] );
1768 // overwriteAddToQueueAlertDone: will be called when the alert is dismissed.
1773 [self doAddToQueue];
1777 /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
1778 the user if they want to overwrite an exiting movie file.
1780 - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
1781 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1783 if( returnCode == NSAlertAlternateReturn )
1784 [self doAddToQueue];
1787 - (void) doAddToQueue
1789 hb_list_t * list = hb_get_titles( fHandle );
1790 hb_title_t * title = (hb_title_t *) hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
1791 hb_job_t * job = title->job;
1793 // Create a Queue Controller job group. Each job that we submit to libhb will also
1794 // get added to the job group so that the queue can track the jobs.
1795 HBJobGroup * jobGroup = [HBJobGroup jobGroup];
1796 // The job group can maintain meta data that libhb can not...
1797 [jobGroup setPresetName: [fPresetSelectedDisplay stringValue]];
1799 // Job groups require that each job within the group be assigned a unique id so
1800 // that the queue can xref between itself and the private jobs that libhb
1801 // maintains. The ID is composed a group id number and a "sequence" number. libhb
1802 // does not use this id.
1803 static int jobGroupID = 0;
1806 // A sequence number, starting at zero, is used to identifiy to each pass. This is
1807 // used by the queue UI to determine if a pass if the first pass of an encode.
1808 int sequenceNum = -1;
1812 /* Destination file */
1813 job->file = [[fDstFile2Field stringValue] UTF8String];
1815 if( [fSubForcedCheck state] == NSOnState )
1816 job->subtitle_force = 1;
1818 job->subtitle_force = 0;
1821 * subtitle of -1 is a scan
1823 if( job->subtitle == -1 )
1828 * When subtitle scan is enabled do a fast pre-scan job
1829 * which will determine which subtitles to enable, if any.
1832 x264opts_tmp = job->x264opts;
1835 job->x264opts = NULL;
1837 job->indepth_scan = 1;
1839 job->select_subtitle = (hb_subtitle_t**)malloc(sizeof(hb_subtitle_t*));
1840 *(job->select_subtitle) = NULL;
1843 * Add the pre-scan job
1845 job->sequence_id = MakeJobID(jobGroupID, ++sequenceNum);
1846 hb_add( fHandle, job );
1847 [jobGroup addJob:[HBJob jobWithLibhbJob:job]]; // add this pass to the job group
1849 job->x264opts = x264opts_tmp;
1852 job->select_subtitle = NULL;
1854 /* No subtitle were selected, so reset the subtitle to -1 (which before
1855 * this point meant we were scanning
1857 if( job->subtitle == -2 )
1860 if( [fVidTwoPassCheck state] == NSOnState )
1862 hb_subtitle_t **subtitle_tmp = job->select_subtitle;
1863 job->indepth_scan = 0;
1866 * Do not autoselect subtitles on the first pass of a two pass
1868 job->select_subtitle = NULL;
1871 job->sequence_id = MakeJobID(jobGroupID, ++sequenceNum);
1872 hb_add( fHandle, job );
1873 [jobGroup addJob:[HBJob jobWithLibhbJob:job]]; // add this pass to the job group
1876 job->sequence_id = MakeJobID(jobGroupID, ++sequenceNum);
1878 job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
1879 strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
1881 job->select_subtitle = subtitle_tmp;
1883 hb_add( fHandle, job );
1884 [jobGroup addJob:[HBJob jobWithLibhbJob:job]]; // add this pass to the job group
1888 job->indepth_scan = 0;
1890 job->sequence_id = MakeJobID(jobGroupID, ++sequenceNum);
1891 hb_add( fHandle, job );
1892 [jobGroup addJob:[HBJob jobWithLibhbJob:job]]; // add this pass to the job group
1895 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1896 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1898 // Let the queue controller know about the job group
1899 [fQueueController addJobGroup:jobGroup];
1902 /* Rip: puts up an alert before ultimately calling doRip
1904 - (IBAction) Rip: (id) sender
1906 /* Rip or Cancel ? */
1908 hb_get_state2( fHandle, &s );
1910 if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
1912 [self Cancel: sender];
1916 // If there are jobs in the queue, then this is a rip the queue
1918 if (hb_count( fHandle ) > 0)
1924 // Before adding jobs to the queue, check for a valid destination.
1926 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1927 if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
1929 NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
1933 /* We check for duplicate name here */
1934 if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
1936 NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
1937 NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), NULL, fWindow, self,
1938 @selector( overWriteAlertDone:returnCode:contextInfo: ),
1939 NULL, NULL, [NSString stringWithFormat:
1940 NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
1941 [fDstFile2Field stringValue]] );
1943 // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
1947 /* if there are no jobs in the queue, then add this one to the queue and rip
1948 otherwise, just rip the queue */
1949 if( hb_count( fHandle ) == 0)
1951 [self doAddToQueue];
1954 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1955 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1960 /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
1961 want to overwrite an exiting movie file.
1963 - (void) overWriteAlertDone: (NSWindow *) sheet
1964 returnCode: (int) returnCode contextInfo: (void *) contextInfo
1966 if( returnCode == NSAlertAlternateReturn )
1968 /* if there are no jobs in the queue, then add this one to the queue and rip
1969 otherwise, just rip the queue */
1970 if( hb_count( fHandle ) == 0 )
1972 [self doAddToQueue];
1975 NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
1976 [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
1981 - (void) remindUserOfSleepOrShutdown
1983 if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
1985 /*Warn that computer will sleep after encoding*/
1988 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);
1989 [NSApp requestUserAttention:NSCriticalRequest];
1990 if ( reminduser == NSAlertAlternateReturn )
1992 [self showPreferencesWindow:NULL];
1995 else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
1997 /*Warn that computer will shut down after encoding*/
2000 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);
2001 [NSApp requestUserAttention:NSCriticalRequest];
2002 if ( reminduser == NSAlertAlternateReturn )
2004 [self showPreferencesWindow:NULL];
2013 /* Let libhb do the job */
2014 hb_start( fHandle );
2015 /*set the fEncodeState State */
2022 //------------------------------------------------------------------------------------
2023 // Removes all jobs from the queue. Does not cancel the current processing job.
2024 //------------------------------------------------------------------------------------
2025 - (void) doDeleteQueuedJobs
2028 while( ( job = hb_job( fHandle, 0 ) ) )
2029 hb_rem( fHandle, job );
2032 //------------------------------------------------------------------------------------
2033 // Cancels and deletes the current job and stops libhb from processing the remaining
2035 //------------------------------------------------------------------------------------
2036 - (void) doCancelCurrentJob
2038 // Stop the current job. hb_stop will only cancel the current pass and then set
2039 // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
2040 // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
2041 // remaining passes of the job and then start the queue back up if there are any
2044 [fQueueController libhbWillStop];
2046 fEncodeState = 2; // don't alert at end of processing since this was a cancel
2050 //------------------------------------------------------------------------------------
2051 // Displays an alert asking user if the want to cancel encoding of current job.
2052 // Cancel: returns immediately after posting the alert. Later, when the user
2053 // acknowledges the alert, doCancelCurrentJob is called.
2054 //------------------------------------------------------------------------------------
2055 - (IBAction)Cancel: (id)sender
2057 if (!fHandle) return;
2059 HBJobGroup * jobGroup = [fQueueController currentJobGroup];
2060 if (!jobGroup) return;
2062 NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"Stop encoding %@?", nil),
2065 // Which window to attach the sheet to?
2066 NSWindow * docWindow;
2067 if ([sender respondsToSelector: @selector(window)])
2068 docWindow = [sender window];
2070 docWindow = fWindow;
2072 NSBeginCriticalAlertSheet(
2074 NSLocalizedString(@"Keep Encoding", nil),
2076 NSLocalizedString(@"Stop Encoding", nil),
2078 nil, @selector(didDimissCancelCurrentJob:returnCode:contextInfo:), nil,
2079 NSLocalizedString(@"Your movie will be lost if you don't continue encoding.", nil));
2081 // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
2084 - (void) didDimissCancelCurrentJob: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
2086 if (returnCode == NSAlertOtherReturn)
2087 [self doCancelCurrentJob]; // <- this also stops libhb
2094 - (IBAction) Pause: (id) sender
2097 hb_get_state2( fHandle, &s );
2099 if( s.state == HB_STATE_PAUSED )
2101 hb_resume( fHandle );
2105 hb_pause( fHandle );
2110 #pragma mark GUI Controls Changed Methods
2112 - (IBAction) titlePopUpChanged: (id) sender
2114 hb_list_t * list = hb_get_titles( fHandle );
2115 hb_title_t * title = (hb_title_t*)
2116 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
2119 /* If Auto Naming is on. We create an output filename of dvd name - title number */
2120 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0)
2122 [fDstFile2Field setStringValue: [NSString stringWithFormat:
2123 @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
2124 browsedSourceDisplayName,
2126 [[fDstFile2Field stringValue] pathExtension]]];
2129 /* Update chapter popups */
2130 [fSrcChapterStartPopUp removeAllItems];
2131 [fSrcChapterEndPopUp removeAllItems];
2132 for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
2134 [fSrcChapterStartPopUp addItemWithTitle: [NSString
2135 stringWithFormat: @"%d", i + 1]];
2136 [fSrcChapterEndPopUp addItemWithTitle: [NSString
2137 stringWithFormat: @"%d", i + 1]];
2139 [fSrcChapterStartPopUp selectItemAtIndex: 0];
2140 [fSrcChapterEndPopUp selectItemAtIndex:
2141 hb_list_count( title->list_chapter ) - 1];
2142 [self chapterPopUpChanged: NULL];
2144 /* Start Get and set the initial pic size for display */
2145 hb_job_t * job = title->job;
2148 /* Pixel Ratio Setting */
2149 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PixelRatio"])
2151 job->pixel_ratio = 1 ;
2155 job->pixel_ratio = 0 ;
2157 /*Set Source Size Field Here */
2158 [fPicSettingsSrc setStringValue: [NSString stringWithFormat: @"%d x %d", fTitle->width, fTitle->height]];
2160 /* Set Auto Crop to on upon selecting a new title */
2161 [fPictureController setAutoCrop:YES];
2163 /* We get the originial output picture width and height and put them
2164 in variables for use with some presets later on */
2165 PicOrigOutputWidth = job->width;
2166 PicOrigOutputHeight = job->height;
2167 AutoCropTop = job->crop[0];
2168 AutoCropBottom = job->crop[1];
2169 AutoCropLeft = job->crop[2];
2170 AutoCropRight = job->crop[3];
2172 /* Run Through encoderPopUpChanged to see if there
2173 needs to be any pic value modifications based on encoder settings */
2174 //[self encoderPopUpChanged: NULL];
2175 /* END Get and set the initial pic size for display */
2177 /* Update subtitle popups */
2178 hb_subtitle_t * subtitle;
2179 [fSubPopUp removeAllItems];
2180 [fSubPopUp addItemWithTitle: @"None"];
2181 [fSubPopUp addItemWithTitle: @"Autoselect"];
2182 for( int i = 0; i < hb_list_count( title->list_subtitle ); i++ )
2184 subtitle = (hb_subtitle_t *) hb_list_item( title->list_subtitle, i );
2186 /* We cannot use NSPopUpButton's addItemWithTitle because
2187 it checks for duplicate entries */
2188 [[fSubPopUp menu] addItemWithTitle: [NSString stringWithCString:
2189 subtitle->lang] action: NULL keyEquivalent: @""];
2191 [fSubPopUp selectItemAtIndex: 0];
2193 [self subtitleSelectionChanged: NULL];
2195 /* Update chapter table */
2196 [fChapterTitlesDelegate resetWithTitle:title];
2197 [fChapterTable reloadData];
2199 /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
2200 int audiotrack_count = hb_list_count(job->list_audio);
2201 for( int i = 0; i < audiotrack_count;i++)
2203 hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
2204 hb_list_rem(job->list_audio, temp_audio);
2207 /* Update audio popups */
2208 [self addAllAudioTracksToPopUp: fAudLang1PopUp];
2209 [self addAllAudioTracksToPopUp: fAudLang2PopUp];
2210 [self addAllAudioTracksToPopUp: fAudLang3PopUp];
2211 [self addAllAudioTracksToPopUp: fAudLang4PopUp];
2212 /* search for the first instance of our prefs default language for track 1, and set track 2 to "none" */
2213 NSString * audioSearchPrefix = [[NSUserDefaults standardUserDefaults] stringForKey:@"DefaultLanguage"];
2214 [self selectAudioTrackInPopUp: fAudLang1PopUp searchPrefixString: audioSearchPrefix selectIndexIfNotFound: 1];
2215 [self selectAudioTrackInPopUp: fAudLang2PopUp searchPrefixString: NULL selectIndexIfNotFound: 0];
2216 [self selectAudioTrackInPopUp: fAudLang3PopUp searchPrefixString: NULL selectIndexIfNotFound: 0];
2217 [self selectAudioTrackInPopUp: fAudLang4PopUp searchPrefixString: NULL selectIndexIfNotFound: 0];
2219 /* changing the title may have changed the audio channels on offer, */
2220 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
2221 [self audioTrackPopUpChanged: fAudLang1PopUp];
2222 [self audioTrackPopUpChanged: fAudLang2PopUp];
2223 [self audioTrackPopUpChanged: fAudLang3PopUp];
2224 [self audioTrackPopUpChanged: fAudLang4PopUp];
2226 /* We repopulate the Video Framerate popup and show the detected framerate along with "Same as Source"*/
2227 [fVidRatePopUp removeAllItems];
2228 if (fTitle->rate_base == 1126125) // 23.976 NTSC Film
2230 [fVidRatePopUp addItemWithTitle: @"Same as source (23.976)"];
2232 else if (fTitle->rate_base == 1080000) // 25 PAL Film/Video
2234 [fVidRatePopUp addItemWithTitle: @"Same as source (25)"];
2236 else if (fTitle->rate_base == 900900) // 29.97 NTSC Video
2238 [fVidRatePopUp addItemWithTitle: @"Same as source (29.97)"];
2242 /* if none of the common dvd source framerates is detected, just use "Same as source" */
2243 [fVidRatePopUp addItemWithTitle: @"Same as source"];
2245 for( int i = 0; i < hb_video_rates_count; i++ )
2247 if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
2249 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
2250 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Film)"]];
2252 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
2254 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
2255 [NSString stringWithCString: hb_video_rates[i].string], @" (PAL Film/Video)"]];
2257 else if ([[NSString stringWithCString: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
2259 [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
2260 [NSString stringWithCString: hb_video_rates[i].string], @" (NTSC Video)"]];
2264 [fVidRatePopUp addItemWithTitle:
2265 [NSString stringWithCString: hb_video_rates[i].string]];
2268 [fVidRatePopUp selectItemAtIndex: 0];
2270 /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
2271 [self calculatePictureSizing: NULL];
2273 /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
2274 [self selectPreset:NULL];
2278 - (IBAction) chapterPopUpChanged: (id) sender
2281 /* If start chapter popup is greater than end chapter popup,
2282 we set the end chapter popup to the same as start chapter popup */
2283 if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
2285 [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
2289 hb_list_t * list = hb_get_titles( fHandle );
2290 hb_title_t * title = (hb_title_t *)
2291 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
2293 hb_chapter_t * chapter;
2294 int64_t duration = 0;
2295 for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
2296 i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
2298 chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
2299 duration += chapter->duration;
2302 duration /= 90000; /* pts -> seconds */
2303 [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
2304 @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
2307 [self calculateBitrate: sender];
2310 - (IBAction) formatPopUpChanged: (id) sender
2312 NSString * string = [fDstFile2Field stringValue];
2313 int format = [fDstFormatPopUp indexOfSelectedItem];
2315 /* Initially set the large file (64 bit formatting) output checkbox to hidden */
2316 [fDstMp4LargeFileCheck setHidden: YES];
2317 [fDstMp4HttpOptFileCheck setHidden: YES];
2318 [fDstMp4iPodFileCheck setHidden: YES];
2320 /* Update the Video Codec PopUp */
2321 /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
2322 [fVidEncoderPopUp removeAllItems];
2323 NSMenuItem *menuItem;
2324 /* These video encoders are available to all of our current muxers, so lets list them once here */
2325 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
2326 [menuItem setTag: HB_VCODEC_FFMPEG];
2328 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (XviD)" action: NULL keyEquivalent: @""];
2329 [menuItem setTag: HB_VCODEC_XVID];
2333 /*Get Default MP4 File Extension*/
2334 if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultMpegName"] > 0)
2342 /* Add additional video encoders here */
2343 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
2344 [menuItem setTag: HB_VCODEC_X264];
2345 /* We show the mp4 option checkboxes here since we are mp4 */
2346 [fCreateChapterMarkers setEnabled: YES];
2347 [fDstMp4LargeFileCheck setHidden: NO];
2348 [fDstMp4HttpOptFileCheck setHidden: NO];
2349 [fDstMp4iPodFileCheck setHidden: NO];
2354 /* Add additional video encoders here */
2355 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
2356 [menuItem setTag: HB_VCODEC_X264];
2357 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
2358 [menuItem setTag: HB_VCODEC_THEORA];
2359 /* We enable the create chapters checkbox here */
2360 [fCreateChapterMarkers setEnabled: YES];
2365 /* Add additional video encoders here */
2366 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
2367 [menuItem setTag: HB_VCODEC_X264];
2368 /* We disable the create chapters checkbox here and make sure it is unchecked*/
2369 [fCreateChapterMarkers setEnabled: NO];
2370 [fCreateChapterMarkers setState: NSOffState];
2375 /* Add additional video encoders here */
2376 menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
2377 [menuItem setTag: HB_VCODEC_THEORA];
2378 /* We disable the create chapters checkbox here and make sure it is unchecked*/
2379 [fCreateChapterMarkers setEnabled: NO];
2380 [fCreateChapterMarkers setState: NSOffState];
2383 [fVidEncoderPopUp selectItemAtIndex: 0];
2385 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
2386 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
2387 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
2388 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
2390 /* FIX ME: we need to restore changing the file extension as pwer */
2392 if( [string characterAtIndex: [string length] - 4] == '.' )
2394 [fDstFile2Field setStringValue: [NSString stringWithFormat:
2395 @"%@.%s", [string substringToIndex: [string length] - 4],
2400 [fDstFile2Field setStringValue: [NSString stringWithFormat:
2401 @"%@.%s", string, ext]];
2404 if ( SuccessfulScan )
2406 /* Add/replace to the correct extension */
2407 [self audioTrackPopUpChanged: fAudLang1PopUp];
2408 [self audioTrackPopUpChanged: fAudLang2PopUp];
2409 [self audioTrackPopUpChanged: fAudLang3PopUp];
2410 [self audioTrackPopUpChanged: fAudLang4PopUp];
2412 if ( [fVidEncoderPopUp selectedItem] == NULL )
2415 [fVidEncoderPopUp selectItemAtIndex:0];
2416 [self videoEncoderPopUpChanged: NULL];
2418 /* changing the format may mean that we can / can't offer mono or 6ch, */
2419 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
2423 /* We call the method to properly enable/disable turbo 2 pass */
2424 [self twoPassCheckboxChanged: sender];
2425 /* We call method method to change UI to reflect whether a preset is used or not*/
2429 /* Lets check to see if we want to auto set the .m4v extension for mp4 */
2430 [self autoSetM4vExtension: sender];
2431 [self customSettingUsed: sender];
2436 /* if MP4 format and [fDstCodecsPopUp indexOfSelectedItem] > 1 we know that the audio is going to be
2437 * either aac + ac3 passthru, or just ac3 passthru so we need to make sure the output file extension is m4v
2438 * otherwise Quicktime will not play it at all */
2439 - (IBAction) autoSetM4vExtension: (id) sender
2441 /*FIX ME: for this to work, we will now have to iterate through the audio list to see if ac3 in an mp4 is chosen
2442 * for now just comment it out.
2445 if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [fDstCodecsPopUp indexOfSelectedItem] > 1)
2447 NSString *newpath = [[[fDstFile2Field stringValue] stringByDeletingPathExtension] stringByAppendingPathExtension: @"m4v"];
2448 [fDstFile2Field setStringValue: [NSString stringWithFormat:
2453 /* Method to determine if we should change the UI
2454 To reflect whether or not a Preset is being used or if
2455 the user is using "Custom" settings by determining the sender*/
2456 - (IBAction) customSettingUsed: (id) sender
2458 if ([sender stringValue] != NULL)
2460 /* Deselect the currently selected Preset if there is one*/
2461 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
2462 [[fPresetsActionMenu itemAtIndex:0] setEnabled: NO];
2463 /* Change UI to show "Custom" settings are being used */
2464 [fPresetSelectedDisplay setStringValue: @"Custom"];
2466 curUserPresetChosenNum = nil;
2473 #pragma mark - Video
2475 - (IBAction) videoEncoderPopUpChanged: (id) sender
2477 hb_job_t * job = fTitle->job;
2478 int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
2480 [fAdvancedOptions setHidden:YES];
2481 /* If we are using x264 then show the x264 advanced panel*/
2482 if (videoEncoder == HB_VCODEC_X264)
2484 [fAdvancedOptions setHidden:NO];
2485 [self autoSetM4vExtension: sender];
2488 /* We need to set loose anamorphic as available depending on whether or not the ffmpeg encoder
2489 is being used as it borks up loose anamorphic .
2490 For convenience lets use the titleOfSelected index. Probably should revisit whether or not we want
2491 to use the index itself but this is easier */
2492 if (videoEncoder == HB_VCODEC_FFMPEG)
2494 if (job->pixel_ratio == 2)
2496 job->pixel_ratio = 0;
2498 [fPictureController setAllowLooseAnamorphic:NO];
2499 /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
2500 container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
2501 anything other than MP4.
2503 [fDstMp4iPodFileCheck setEnabled: NO];
2504 [fDstMp4iPodFileCheck setState: NSOffState];
2508 [fPictureController setAllowLooseAnamorphic:YES];
2509 [fDstMp4iPodFileCheck setEnabled: YES];
2512 [self calculatePictureSizing: sender];
2513 [self twoPassCheckboxChanged: sender];
2517 - (IBAction) twoPassCheckboxChanged: (id) sender
2519 /* check to see if x264 is chosen */
2520 if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
2522 if( [fVidTwoPassCheck state] == NSOnState)
2524 [fVidTurboPassCheck setHidden: NO];
2528 [fVidTurboPassCheck setHidden: YES];
2529 [fVidTurboPassCheck setState: NSOffState];
2531 /* Make sure Two Pass is checked if Turbo is checked */
2532 if( [fVidTurboPassCheck state] == NSOnState)
2534 [fVidTwoPassCheck setState: NSOnState];
2539 [fVidTurboPassCheck setHidden: YES];
2540 [fVidTurboPassCheck setState: NSOffState];
2543 /* We call method method to change UI to reflect whether a preset is used or not*/
2544 [self customSettingUsed: sender];
2547 - (IBAction ) videoFrameRateChanged: (id) sender
2549 /* We call method method to calculatePictureSizing to error check detelecine*/
2550 [self calculatePictureSizing: sender];
2552 /* We call method method to change UI to reflect whether a preset is used or not*/
2553 [self customSettingUsed: sender];
2555 - (IBAction) videoMatrixChanged: (id) sender;
2557 bool target, bitrate, quality;
2559 target = bitrate = quality = false;
2560 if( [fVidQualityMatrix isEnabled] )
2562 switch( [fVidQualityMatrix selectedRow] )
2575 [fVidTargetSizeField setEnabled: target];
2576 [fVidBitrateField setEnabled: bitrate];
2577 [fVidQualitySlider setEnabled: quality];
2578 [fVidTwoPassCheck setEnabled: !quality &&
2579 [fVidQualityMatrix isEnabled]];
2582 [fVidTwoPassCheck setState: NSOffState];
2583 [fVidTurboPassCheck setHidden: YES];
2584 [fVidTurboPassCheck setState: NSOffState];
2587 [self qualitySliderChanged: sender];
2588 [self calculateBitrate: sender];
2589 [self customSettingUsed: sender];
2592 - (IBAction) qualitySliderChanged: (id) sender
2594 [fVidConstantCell setTitle: [NSString stringWithFormat:
2595 NSLocalizedString( @"Constant quality: %.0f %%", @"" ), 100.0 *
2596 [fVidQualitySlider floatValue]]];
2597 [self customSettingUsed: sender];
2600 - (void) controlTextDidChange: (NSNotification *) notification
2602 [self calculateBitrate: NULL];
2605 - (IBAction) calculateBitrate: (id) sender
2607 if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
2612 hb_list_t * list = hb_get_titles( fHandle );
2613 hb_title_t * title = (hb_title_t *) hb_list_item( list,
2614 [fSrcTitlePopUp indexOfSelectedItem] );
2615 hb_job_t * job = title->job;
2619 [fVidBitrateField setIntValue: hb_calc_bitrate( job,
2620 [fVidTargetSizeField intValue] )];
2624 #pragma mark - Picture
2626 /* lets set the picture size back to the max from right after title scan
2627 Lets use an IBAction here as down the road we could always use a checkbox
2628 in the gui to easily take the user back to max. Remember, the compiler
2629 resolves IBActions down to -(void) during compile anyway */
2630 - (IBAction) revertPictureSizeToMax: (id) sender
2632 hb_job_t * job = fTitle->job;
2633 /* We use the output picture width and height
2634 as calculated from libhb right after title is set
2635 in TitlePopUpChanged */
2636 job->width = PicOrigOutputWidth;
2637 job->height = PicOrigOutputHeight;
2638 [fPictureController setAutoCrop:YES];
2639 /* Here we use the auto crop values determined right after scan */
2640 job->crop[0] = AutoCropTop;
2641 job->crop[1] = AutoCropBottom;
2642 job->crop[2] = AutoCropLeft;
2643 job->crop[3] = AutoCropRight;
2646 [self calculatePictureSizing: sender];
2647 /* We call method to change UI to reflect whether a preset is used or not*/
2648 [self customSettingUsed: sender];
2652 * Registers changes made in the Picture Settings Window.
2655 - (void)pictureSettingsDidChange {
2656 [self calculatePictureSizing: NULL];
2659 /* Get and Display Current Pic Settings in main window */
2660 - (IBAction) calculatePictureSizing: (id) sender
2662 [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", fTitle->job->width, fTitle->job->height]];
2664 if (fTitle->job->pixel_ratio == 1)
2666 int titlewidth = fTitle->width-fTitle->job->crop[2]-fTitle->job->crop[3];
2667 int arpwidth = fTitle->job->pixel_aspect_width;
2668 int arpheight = fTitle->job->pixel_aspect_height;
2669 int displayparwidth = titlewidth * arpwidth / arpheight;
2670 int displayparheight = fTitle->height-fTitle->job->crop[0]-fTitle->job->crop[1];
2671 [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", titlewidth, displayparheight]];
2672 [fPicSettingsAnamorphic setStringValue: [NSString stringWithFormat:@"%d x %d Strict", displayparwidth, displayparheight]];
2673 fTitle->job->keep_ratio = 0;
2675 else if (fTitle->job->pixel_ratio == 2)
2677 hb_job_t * job = fTitle->job;
2678 int output_width, output_height, output_par_width, output_par_height;
2679 hb_set_anamorphic_size(job, &output_width, &output_height, &output_par_width, &output_par_height);
2681 display_width = output_width * output_par_width / output_par_height;
2683 [fPicSettingsOutp setStringValue: [NSString stringWithFormat:@"%d x %d", output_width, output_height]];
2684 [fPicSettingsAnamorphic setStringValue: [NSString stringWithFormat:@"%d x %d Loose", display_width, output_height]];
2686 fTitle->job->keep_ratio = 0;
2690 [fPicSettingsAnamorphic setStringValue:@"Off"];
2693 /* Set ON/Off values for the deinterlace/keep aspect ratio according to boolean */
2694 if (fTitle->job->keep_ratio > 0)
2696 [fPicSettingARkeep setStringValue: @"On"];
2700 [fPicSettingARkeep setStringValue: @"Off"];
2704 if ([fPictureController detelecine]) {
2705 [fPicSettingDetelecine setStringValue: @"Yes"];
2708 [fPicSettingDetelecine setStringValue: @"No"];
2712 if ([fPictureController decomb] == 0)
2714 [fPicSettingDecomb setStringValue: @"Off"];
2716 else if ([fPictureController decomb] == 1)
2718 [fPicSettingDecomb setStringValue: @"4:10:15:9:10:35:9"];
2720 else if ([fPictureController decomb] == 2)
2722 [fPicSettingDecomb setStringValue: [[NSUserDefaults standardUserDefaults] valueForKey:@"DecombCustomString"]];
2723 ///[[NSUserDefaults standardUserDefaults] valueForKey:@"DecombCustomString"]
2726 /* VFR (Variable Frame Rate) */
2727 if ([fPictureController vfr]) {
2728 /* We change the string of the fps popup to warn that vfr is on Framerate (FPS): */
2729 [fVidRateField setStringValue: @"Framerate (VFR On):"];
2730 /* for VFR we select same as source (or title framerate) and disable the popup.
2731 * We know its index 0 as that is determined in titlePopUpChanged */
2732 [fVidRatePopUp selectItemAtIndex: 0];
2733 [fVidRatePopUp setEnabled: NO];
2737 /* make sure the label for framerate is set to its default */
2738 [fVidRateField setStringValue: @"Framerate (FPS):"];
2739 [fVidRatePopUp setEnabled: YES];
2743 if ([fPictureController deinterlace] == 0)
2745 [fPicSettingDeinterlace setStringValue: @"Off"];
2747 else if ([fPictureController deinterlace] == 1)
2749 [fPicSettingDeinterlace setStringValue: @"Fast"];
2751 else if ([fPictureController deinterlace] == 2)
2753 [fPicSettingDeinterlace setStringValue: @"Slow"];
2755 else if ([fPictureController deinterlace] == 3)
2757 [fPicSettingDeinterlace setStringValue: @"Slower"];
2761 if ([fPictureController denoise] == 0)
2763 [fPicSettingDenoise setStringValue: @"Off"];
2765 else if ([fPictureController denoise] == 1)
2767 [fPicSettingDenoise setStringValue: @"Weak"];
2769 else if ([fPictureController denoise] == 2)
2771 [fPicSettingDenoise setStringValue: @"Medium"];
2773 else if ([fPictureController denoise] == 3)
2775 [fPicSettingDenoise setStringValue: @"Strong"];
2779 if ([fPictureController deblock]) {
2780 [fPicSettingDeblock setStringValue: @"Yes"];
2783 [fPicSettingDeblock setStringValue: @"No"];
2786 if (fTitle->job->pixel_ratio > 0)
2788 [fPicSettingPAR setStringValue: @""];
2792 [fPicSettingPAR setStringValue: @"Off"];
2795 /* Set the display field for crop as per boolean */
2796 if (![fPictureController autoCrop])
2798 [fPicSettingAutoCrop setStringValue: @"Custom"];
2802 [fPicSettingAutoCrop setStringValue: @"Auto"];
2810 #pragma mark - Audio and Subtitles
2811 - (IBAction) audioCodecsPopUpChanged: (id) sender
2814 NSPopUpButton * audiotrackPopUp;
2815 NSPopUpButton * sampleratePopUp;
2816 NSPopUpButton * bitratePopUp;
2817 NSPopUpButton * audiocodecPopUp;
2818 if (sender == fAudTrack1CodecPopUp)
2820 audiotrackPopUp = fAudLang1PopUp;
2821 audiocodecPopUp = fAudTrack1CodecPopUp;
2822 sampleratePopUp = fAudTrack1RatePopUp;
2823 bitratePopUp = fAudTrack1BitratePopUp;
2825 else if (sender == fAudTrack2CodecPopUp)
2827 audiotrackPopUp = fAudLang2PopUp;
2828 audiocodecPopUp = fAudTrack2CodecPopUp;
2829 sampleratePopUp = fAudTrack2RatePopUp;
2830 bitratePopUp = fAudTrack2BitratePopUp;
2832 else if (sender == fAudTrack3CodecPopUp)
2834 audiotrackPopUp = fAudLang3PopUp;
2835 audiocodecPopUp = fAudTrack3CodecPopUp;
2836 sampleratePopUp = fAudTrack3RatePopUp;
2837 bitratePopUp = fAudTrack3BitratePopUp;
2841 audiotrackPopUp = fAudLang4PopUp;
2842 audiocodecPopUp = fAudTrack4CodecPopUp;
2843 sampleratePopUp = fAudTrack4RatePopUp;
2844 bitratePopUp = fAudTrack4BitratePopUp;
2847 /* changing the codecs on offer may mean that we can / can't offer mono or 6ch, */
2848 /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
2849 [self audioTrackPopUpChanged: audiotrackPopUp];
2853 - (IBAction) setEnabledStateOfAudioMixdownControls: (id) sender
2855 /* We will be setting the enabled/disabled state of each tracks audio controls based on
2856 * the settings of the source audio for that track. We leave the samplerate and bitrate
2857 * to audiotrackMixdownChanged
2860 /* We will first verify that a lower track number has been selected before enabling each track
2861 * for example, make sure a track is selected for track 1 before enabling track 2, etc.
2863 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2865 [fAudLang2PopUp setEnabled: NO];
2866 [fAudLang2PopUp selectItemAtIndex: 0];
2870 [fAudLang2PopUp setEnabled: YES];
2873 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2875 [fAudLang3PopUp setEnabled: NO];
2876 [fAudLang3PopUp selectItemAtIndex: 0];
2880 [fAudLang3PopUp setEnabled: YES];
2882 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2884 [fAudLang4PopUp setEnabled: NO];
2885 [fAudLang4PopUp selectItemAtIndex: 0];
2889 [fAudLang4PopUp setEnabled: YES];
2891 /* enable/disable the mixdown text and popupbutton for audio track 1 */
2892 [fAudTrack1CodecPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
2893 [fAudTrack1MixPopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
2894 [fAudTrack1RatePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
2895 [fAudTrack1BitratePopUp setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
2896 [fAudTrack1DrcSlider setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
2897 [fAudTrack1DrcField setEnabled: ([fAudLang1PopUp indexOfSelectedItem] == 0) ? NO : YES];
2898 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
2900 [fAudTrack1CodecPopUp removeAllItems];
2901 [fAudTrack1MixPopUp removeAllItems];
2902 [fAudTrack1RatePopUp removeAllItems];
2903 [fAudTrack1BitratePopUp removeAllItems];
2904 [fAudTrack1DrcSlider setFloatValue: 1.00];
2905 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
2907 else if ([[fAudTrack1MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
2909 [fAudTrack1RatePopUp setEnabled: NO];
2910 [fAudTrack1BitratePopUp setEnabled: NO];
2911 [fAudTrack1DrcSlider setEnabled: NO];
2912 [fAudTrack1DrcField setEnabled: NO];
2915 /* enable/disable the mixdown text and popupbutton for audio track 2 */
2916 [fAudTrack2CodecPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
2917 [fAudTrack2MixPopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
2918 [fAudTrack2RatePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
2919 [fAudTrack2BitratePopUp setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
2920 [fAudTrack2DrcSlider setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
2921 [fAudTrack2DrcField setEnabled: ([fAudLang2PopUp indexOfSelectedItem] == 0) ? NO : YES];
2922 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
2924 [fAudTrack2CodecPopUp removeAllItems];
2925 [fAudTrack2MixPopUp removeAllItems];
2926 [fAudTrack2RatePopUp removeAllItems];
2927 [fAudTrack2BitratePopUp removeAllItems];
2928 [fAudTrack2DrcSlider setFloatValue: 1.00];
2929 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
2931 else if ([[fAudTrack2MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
2933 [fAudTrack2RatePopUp setEnabled: NO];
2934 [fAudTrack2BitratePopUp setEnabled: NO];
2935 [fAudTrack2DrcSlider setEnabled: NO];
2936 [fAudTrack2DrcField setEnabled: NO];
2939 /* enable/disable the mixdown text and popupbutton for audio track 3 */
2940 [fAudTrack3CodecPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
2941 [fAudTrack3MixPopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
2942 [fAudTrack3RatePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
2943 [fAudTrack3BitratePopUp setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
2944 [fAudTrack3DrcSlider setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
2945 [fAudTrack3DrcField setEnabled: ([fAudLang3PopUp indexOfSelectedItem] == 0) ? NO : YES];
2946 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
2948 [fAudTrack3CodecPopUp removeAllItems];
2949 [fAudTrack3MixPopUp removeAllItems];
2950 [fAudTrack3RatePopUp removeAllItems];
2951 [fAudTrack3BitratePopUp removeAllItems];
2952 [fAudTrack3DrcSlider setFloatValue: 1.00];
2953 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
2955 else if ([[fAudTrack3MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
2957 [fAudTrack3RatePopUp setEnabled: NO];
2958 [fAudTrack3BitratePopUp setEnabled: NO];
2959 [fAudTrack3DrcSlider setEnabled: NO];
2960 [fAudTrack3DrcField setEnabled: NO];
2963 /* enable/disable the mixdown text and popupbutton for audio track 4 */
2964 [fAudTrack4CodecPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
2965 [fAudTrack4MixPopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
2966 [fAudTrack4RatePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
2967 [fAudTrack4BitratePopUp setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
2968 [fAudTrack4DrcSlider setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
2969 [fAudTrack4DrcField setEnabled: ([fAudLang4PopUp indexOfSelectedItem] == 0) ? NO : YES];
2970 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
2972 [fAudTrack4CodecPopUp removeAllItems];
2973 [fAudTrack4MixPopUp removeAllItems];
2974 [fAudTrack4RatePopUp removeAllItems];
2975 [fAudTrack4BitratePopUp removeAllItems];
2976 [fAudTrack4DrcSlider setFloatValue: 1.00];
2977 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
2979 else if ([[fAudTrack4MixPopUp selectedItem] tag] == HB_ACODEC_AC3)
2981 [fAudTrack4RatePopUp setEnabled: NO];
2982 [fAudTrack4BitratePopUp setEnabled: NO];
2983 [fAudTrack4DrcSlider setEnabled: NO];
2984 [fAudTrack4DrcField setEnabled: NO];
2989 - (IBAction) addAllAudioTracksToPopUp: (id) sender
2992 hb_list_t * list = hb_get_titles( fHandle );
2993 hb_title_t * title = (hb_title_t*)
2994 hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
2996 hb_audio_config_t * audio;
2998 [sender removeAllItems];
2999 [sender addItemWithTitle: NSLocalizedString( @"None", @"" )];
3000 for( int i = 0; i < hb_list_count( title->list_audio ); i++ )
3002 audio = (hb_audio_config_t *) hb_list_audio_config_item( title->list_audio, i );
3003 [[sender menu] addItemWithTitle:
3004 [NSString stringWithCString: audio->lang.description]
3005 action: NULL keyEquivalent: @""];
3007 [sender selectItemAtIndex: 0];
3011 - (IBAction) selectAudioTrackInPopUp: (id) sender searchPrefixString: (NSString *) searchPrefixString selectIndexIfNotFound: (int) selectIndexIfNotFound
3014 /* this method can be used to find a language, or a language-and-source-format combination, by passing in the appropriate string */
3015 /* e.g. to find the first French track, pass in an NSString * of "Francais" */
3016 /* e.g. to find the first English 5.1 AC3 track, pass in an NSString * of "English (AC3) (5.1 ch)" */
3017 /* if no matching track is found, then selectIndexIfNotFound is used to choose which track to select instead */
3019 if (searchPrefixString != NULL)
3022 for( int i = 0; i < [sender numberOfItems]; i++ )
3024 /* Try to find the desired search string */
3025 if ([[[sender itemAtIndex: i] title] hasPrefix:searchPrefixString])
3027 [sender selectItemAtIndex: i];
3031 /* couldn't find the string, so select the requested "search string not found" item */
3032 /* index of 0 means select the "none" item */
3033 /* index of 1 means select the first audio track */
3034 [sender selectItemAtIndex: selectIndexIfNotFound];
3038 /* if no search string is provided, then select the selectIndexIfNotFound item */
3039 [sender selectItemAtIndex: selectIndexIfNotFound];
3043 - (IBAction) audioAddAudioTrackCodecs: (id)sender
3045 int format = [fDstFormatPopUp indexOfSelectedItem];
3047 /* setup pointers to the appropriate popups for the correct track */
3048 NSPopUpButton * audiocodecPopUp;
3049 NSPopUpButton * audiotrackPopUp;
3050 if (sender == fAudTrack1CodecPopUp)
3052 audiotrackPopUp = fAudLang1PopUp;
3053 audiocodecPopUp = fAudTrack1CodecPopUp;
3055 else if (sender == fAudTrack2CodecPopUp)
3057 audiotrackPopUp = fAudLang2PopUp;
3058 audiocodecPopUp = fAudTrack2CodecPopUp;
3060 else if (sender == fAudTrack3CodecPopUp)
3062 audiotrackPopUp = fAudLang3PopUp;
3063 audiocodecPopUp = fAudTrack3CodecPopUp;
3067 audiotrackPopUp = fAudLang4PopUp;
3068 audiocodecPopUp = fAudTrack4CodecPopUp;
3071 [audiocodecPopUp removeAllItems];
3072 /* Make sure "None" isnt selected in the source track */
3073 if ([audiotrackPopUp indexOfSelectedItem] > 0)
3075 [audiocodecPopUp setEnabled:YES];
3076 NSMenuItem *menuItem;
3077 /* We setup our appropriate popups for codecs and put the int value in the popup tag for easy retrieval */
3083 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
3084 [menuItem setTag: HB_ACODEC_FAAC];
3087 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
3088 [menuItem setTag: HB_ACODEC_AC3];
3094 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AAC (faac)" action: NULL keyEquivalent: @""];
3095 [menuItem setTag: HB_ACODEC_FAAC];
3097 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
3098 [menuItem setTag: HB_ACODEC_AC3];
3100 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
3101 [menuItem setTag: HB_ACODEC_LAME];
3103 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
3104 [menuItem setTag: HB_ACODEC_VORBIS];
3110 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
3111 [menuItem setTag: HB_ACODEC_LAME];
3113 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"AC3 Passthru" action: NULL keyEquivalent: @""];
3114 [menuItem setTag: HB_ACODEC_AC3];
3120 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"Vorbis (vorbis)" action: NULL keyEquivalent: @""];
3121 [menuItem setTag: HB_ACODEC_VORBIS];
3123 menuItem = [[audiocodecPopUp menu] addItemWithTitle:@"MP3 (lame)" action: NULL keyEquivalent: @""];
3124 [menuItem setTag: HB_ACODEC_LAME];
3127 [audiocodecPopUp selectItemAtIndex:0];
3131 [audiocodecPopUp setEnabled:NO];
3135 - (IBAction) audioTrackPopUpChanged: (id) sender
3137 /* utility function to call audioTrackPopUpChanged without passing in a mixdown-to-use */
3138 [self audioTrackPopUpChanged: sender mixdownToUse: 0];
3141 - (IBAction) audioTrackPopUpChanged: (id) sender mixdownToUse: (int) mixdownToUse
3144 /* make sure we have a selected title before continuing */
3145 if (fTitle == NULL) return;
3146 /* if the sender is the lanaguage popup and there is nothing in the codec popup, lets call
3147 * audioAddAudioTrackCodecs on the codec popup to populate it properly before moving on
3149 if (sender == fAudLang1PopUp && [[fAudTrack1CodecPopUp menu] numberOfItems] == 0)
3151 [self audioAddAudioTrackCodecs: fAudTrack1CodecPopUp];
3153 if (sender == fAudLang2PopUp && [[fAudTrack2CodecPopUp menu] numberOfItems] == 0)
3155 [self audioAddAudioTrackCodecs: fAudTrack2CodecPopUp];
3157 if (sender == fAudLang3PopUp && [[fAudTrack3CodecPopUp menu] numberOfItems] == 0)
3159 [self audioAddAudioTrackCodecs: fAudTrack3CodecPopUp];
3161 if (sender == fAudLang4PopUp && [[fAudTrack4CodecPopUp menu] numberOfItems] == 0)
3163 [self audioAddAudioTrackCodecs: fAudTrack4CodecPopUp];
3166 /* Now lets make the sender the appropriate Audio Track popup from this point on */
3167 if (sender == fAudTrack1CodecPopUp || sender == fAudTrack1MixPopUp)
3169 sender = fAudLang1PopUp;
3171 if (sender == fAudTrack2CodecPopUp || sender == fAudTrack2MixPopUp)
3173 sender = fAudLang2PopUp;
3175 if (sender == fAudTrack3CodecPopUp || sender == fAudTrack3MixPopUp)
3177 sender = fAudLang3PopUp;
3179 if (sender == fAudTrack4CodecPopUp || sender == fAudTrack4MixPopUp)
3181 sender = fAudLang4PopUp;
3184 /* pointer to this track's mixdown, codec, sample rate and bitrate NSPopUpButton's */
3185 NSPopUpButton * mixdownPopUp;
3186 NSPopUpButton * audiocodecPopUp;
3187 NSPopUpButton * sampleratePopUp;
3188 NSPopUpButton * bitratePopUp;
3189 if (sender == fAudLang1PopUp)
3191 mixdownPopUp = fAudTrack1MixPopUp;
3192 audiocodecPopUp = fAudTrack1CodecPopUp;
3193 sampleratePopUp = fAudTrack1RatePopUp;
3194 bitratePopUp = fAudTrack1BitratePopUp;
3196 else if (sender == fAudLang2PopUp)
3198 mixdownPopUp = fAudTrack2MixPopUp;
3199 audiocodecPopUp = fAudTrack2CodecPopUp;
3200 sampleratePopUp = fAudTrack2RatePopUp;
3201 bitratePopUp = fAudTrack2BitratePopUp;
3203 else if (sender == fAudLang3PopUp)
3205 mixdownPopUp = fAudTrack3MixPopUp;
3206 audiocodecPopUp = fAudTrack3CodecPopUp;
3207 sampleratePopUp = fAudTrack3RatePopUp;
3208 bitratePopUp = fAudTrack3BitratePopUp;
3212 mixdownPopUp = fAudTrack4MixPopUp;
3213 audiocodecPopUp = fAudTrack4CodecPopUp;
3214 sampleratePopUp = fAudTrack4RatePopUp;
3215 bitratePopUp = fAudTrack4BitratePopUp;
3218 /* get the index of the selected audio Track*/
3219 int thisAudioIndex = [sender indexOfSelectedItem] - 1;
3221 /* pointer for the hb_audio_s struct we will use later on */
3222 hb_audio_config_t * audio;
3225 /* check if the audio mixdown controls need their enabled state changing */
3226 [self setEnabledStateOfAudioMixdownControls: NULL];
3228 if (thisAudioIndex != -1)
3232 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, thisAudioIndex );// Should "fTitle" be title and be setup ?
3234 /* actually manipulate the proper mixdowns here */
3235 /* delete the previous audio mixdown options */
3236 [mixdownPopUp removeAllItems];
3238 acodec = [[audiocodecPopUp selectedItem] tag];
3243 /* find out if our selected output audio codec supports mono and / or 6ch */
3244 /* we also check for an input codec of AC3 or DCA,
3245 as they are the only libraries able to do the mixdown to mono / conversion to 6-ch */
3246 /* audioCodecsSupportMono and audioCodecsSupport6Ch are the same for now,
3247 but this may change in the future, so they are separated for flexibility */
3248 int audioCodecsSupportMono =
3249 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3250 (acodec != HB_ACODEC_LAME);
3251 int audioCodecsSupport6Ch =
3252 (audio->in.codec & (HB_ACODEC_AC3|HB_ACODEC_DCA)) &&
3253 (acodec != HB_ACODEC_LAME);
3255 /* check for AC-3 passthru */
3256 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
3259 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
3260 [NSString stringWithCString: "AC3 Passthru"]
3261 action: NULL keyEquivalent: @""];
3262 [menuItem setTag: HB_ACODEC_AC3];
3267 /* add the appropriate audio mixdown menuitems to the popupbutton */
3268 /* in each case, we set the new menuitem's tag to be the amixdown value for that mixdown,
3269 so that we can reference the mixdown later */
3271 /* keep a track of the min and max mixdowns we used, so we can select the best match later */
3272 int minMixdownUsed = 0;
3273 int maxMixdownUsed = 0;
3275 /* get the input channel layout without any lfe channels */
3276 int layout = audio->in.channel_layout & HB_INPUT_CH_LAYOUT_DISCRETE_NO_LFE_MASK;
3278 /* do we want to add a mono option? */
3279 if (audioCodecsSupportMono == 1)
3281 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
3282 [NSString stringWithCString: hb_audio_mixdowns[0].human_readable_name]
3283 action: NULL keyEquivalent: @""];
3284 [menuItem setTag: hb_audio_mixdowns[0].amixdown];
3285 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[0].amixdown;
3286 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[0].amixdown);
3289 /* do we want to add a stereo option? */
3290 /* offer stereo if we have a mono source and non-mono-supporting codecs, as otherwise we won't have a mixdown at all */
3291 /* also offer stereo if we have a stereo-or-better source */
3292 if ((layout == HB_INPUT_CH_LAYOUT_MONO && audioCodecsSupportMono == 0) || layout >= HB_INPUT_CH_LAYOUT_STEREO)
3294 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
3295 [NSString stringWithCString: hb_audio_mixdowns[1].human_readable_name]
3296 action: NULL keyEquivalent: @""];
3297 [menuItem setTag: hb_audio_mixdowns[1].amixdown];
3298 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[1].amixdown;
3299 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[1].amixdown);
3302 /* do we want to add a dolby surround (DPL1) option? */
3303 if (layout == HB_INPUT_CH_LAYOUT_3F1R || layout == HB_INPUT_CH_LAYOUT_3F2R || layout == HB_INPUT_CH_LAYOUT_DOLBY)
3305 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
3306 [NSString stringWithCString: hb_audio_mixdowns[2].human_readable_name]
3307 action: NULL keyEquivalent: @""];
3308 [menuItem setTag: hb_audio_mixdowns[2].amixdown];
3309 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[2].amixdown;
3310 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[2].amixdown);
3313 /* do we want to add a dolby pro logic 2 (DPL2) option? */
3314 if (layout == HB_INPUT_CH_LAYOUT_3F2R)
3316 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
3317 [NSString stringWithCString: hb_audio_mixdowns[3].human_readable_name]
3318 action: NULL keyEquivalent: @""];
3319 [menuItem setTag: hb_audio_mixdowns[3].amixdown];
3320 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[3].amixdown;
3321 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[3].amixdown);
3324 /* do we want to add a 6-channel discrete option? */
3325 if (audioCodecsSupport6Ch == 1 && layout == HB_INPUT_CH_LAYOUT_3F2R && (audio->in.channel_layout & HB_INPUT_CH_LAYOUT_HAS_LFE))
3327 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
3328 [NSString stringWithCString: hb_audio_mixdowns[4].human_readable_name]
3329 action: NULL keyEquivalent: @""];
3330 [menuItem setTag: hb_audio_mixdowns[4].amixdown];
3331 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[4].amixdown;
3332 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[4].amixdown);
3335 /* do we want to add an AC-3 passthrough option? */
3336 if (audio->in.codec == HB_ACODEC_AC3 && acodec == HB_ACODEC_AC3)
3338 NSMenuItem *menuItem = [[mixdownPopUp menu] addItemWithTitle:
3339 [NSString stringWithCString: hb_audio_mixdowns[5].human_readable_name]
3340 action: NULL keyEquivalent: @""];
3341 [menuItem setTag: HB_ACODEC_AC3];
3342 if (minMixdownUsed == 0) minMixdownUsed = hb_audio_mixdowns[5].amixdown;
3343 maxMixdownUsed = MAX(maxMixdownUsed, hb_audio_mixdowns[5].amixdown);
3346 /* auto-select the best mixdown based on our saved mixdown preference */
3348 /* for now, this is hard-coded to a "best" mixdown of HB_AMIXDOWN_DOLBYPLII */
3349 /* ultimately this should be a prefs option */
3352 /* if we passed in a mixdown to use - in order to load a preset - then try and use it */
3353 if (mixdownToUse > 0)
3355 useMixdown = mixdownToUse;
3359 useMixdown = HB_AMIXDOWN_DOLBYPLII;
3362 /* if useMixdown > maxMixdownUsed, then use maxMixdownUsed */
3363 if (useMixdown > maxMixdownUsed)
3365 useMixdown = maxMixdownUsed;
3368 /* if useMixdown < minMixdownUsed, then use minMixdownUsed */
3369 if (useMixdown < minMixdownUsed)
3371 useMixdown = minMixdownUsed;
3374 /* select the (possibly-amended) preferred mixdown */
3375 [mixdownPopUp selectItemWithTag: useMixdown];
3378 /* In the case of a source track that is not AC3 and the user tries to use AC3 Passthru (which does not work)
3379 * we force the Audio Codec choice back to a workable codec. We use MP3 for avi and aac for all
3382 if (audio->in.codec != HB_ACODEC_AC3 && [[audiocodecPopUp selectedItem] tag] == HB_ACODEC_AC3)
3384 /* If we are using the avi container, we select MP3 as there is no aac available*/
3385 if ([[fDstFormatPopUp selectedItem] tag] == HB_MUX_AVI)
3387 [audiocodecPopUp selectItemWithTag: HB_ACODEC_LAME];
3391 [audiocodecPopUp selectItemWithTag: HB_ACODEC_FAAC];
3394 /* Setup our samplerate and bitrate popups we will need based on mixdown */
3395 [self audioTrackMixdownChanged: mixdownPopUp];
3401 - (IBAction) audioTrackMixdownChanged: (id) sender
3405 /* setup pointers to all of the other audio track controls
3406 * we will need later
3408 NSPopUpButton * mixdownPopUp;
3409 NSPopUpButton * sampleratePopUp;
3410 NSPopUpButton * bitratePopUp;
3411 NSPopUpButton * audiocodecPopUp;
3412 NSPopUpButton * audiotrackPopUp;
3413 NSSlider * drcSlider;
3414 NSTextField * drcField;
3415 if (sender == fAudTrack1MixPopUp)
3417 audiotrackPopUp = fAudLang1PopUp;
3418 audiocodecPopUp = fAudTrack1CodecPopUp;
3419 mixdownPopUp = fAudTrack1MixPopUp;
3420 sampleratePopUp = fAudTrack1RatePopUp;
3421 bitratePopUp = fAudTrack1BitratePopUp;
3422 drcSlider = fAudTrack1DrcSlider;
3423 drcField = fAudTrack1DrcField;
3425 else if (sender == fAudTrack2MixPopUp)
3427 audiotrackPopUp = fAudLang2PopUp;
3428 audiocodecPopUp = fAudTrack2CodecPopUp;
3429 mixdownPopUp = fAudTrack2MixPopUp;
3430 sampleratePopUp = fAudTrack2RatePopUp;
3431 bitratePopUp = fAudTrack2BitratePopUp;
3432 drcSlider = fAudTrack2DrcSlider;
3433 drcField = fAudTrack2DrcField;
3435 else if (sender == fAudTrack3MixPopUp)
3437 audiotrackPopUp = fAudLang3PopUp;
3438 audiocodecPopUp = fAudTrack3CodecPopUp;
3439 mixdownPopUp = fAudTrack3MixPopUp;
3440 sampleratePopUp = fAudTrack3RatePopUp;
3441 bitratePopUp = fAudTrack3BitratePopUp;
3442 drcSlider = fAudTrack3DrcSlider;
3443 drcField = fAudTrack3DrcField;
3447 audiotrackPopUp = fAudLang4PopUp;
3448 audiocodecPopUp = fAudTrack4CodecPopUp;
3449 mixdownPopUp = fAudTrack4MixPopUp;
3450 sampleratePopUp = fAudTrack4RatePopUp;
3451 bitratePopUp = fAudTrack4BitratePopUp;
3452 drcSlider = fAudTrack4DrcSlider;
3453 drcField = fAudTrack4DrcField;
3455 acodec = [[audiocodecPopUp selectedItem] tag];
3456 /* storage variable for the min and max bitrate allowed for this codec */
3462 case HB_ACODEC_FAAC:
3463 /* check if we have a 6ch discrete conversion in either audio track */
3464 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
3466 /* FAAC is happy using our min bitrate of 32 kbps, even for 6ch */
3468 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
3474 /* FAAC is happy using our min bitrate of 32 kbps for stereo or mono */
3476 /* FAAC won't honour anything more than 160 for stereo, so let's not offer it */
3477 /* note: haven't dealt with mono separately here, FAAC will just use the max it can */
3482 case HB_ACODEC_LAME:
3483 /* Lame is happy using our min bitrate of 32 kbps */
3485 /* Lame won't encode if the bitrate is higher than 320 kbps */
3489 case HB_ACODEC_VORBIS:
3490 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
3492 /* Vorbis causes a crash if we use a bitrate below 192 kbps with 6 channel */
3494 /* If either mixdown popup includes 6-channel discrete, then allow up to 384 kbps */
3500 /* Vorbis causes a crash if we use a bitrate below 48 kbps */
3502 /* Vorbis can cope with 384 kbps quite happily, even for stereo */
3508 /* AC3 passthru disables the bitrate dropdown anyway, so we might as well just use the min and max bitrate */
3514 /* make sure we have a selected title before continuing */
3515 if (fTitle == NULL) return;
3516 /* get the audio so we can find out what input rates are*/
3517 hb_audio_config_t * audio;
3518 audio = (hb_audio_config_t *) hb_list_audio_config_item( fTitle->list_audio, [audiotrackPopUp indexOfSelectedItem] - 1 );
3519 int inputbitrate = audio->in.bitrate / 1000;
3520 int inputsamplerate = audio->in.samplerate;
3522 if ([[mixdownPopUp selectedItem] tag] != HB_ACODEC_AC3)
3524 [bitratePopUp removeAllItems];
3526 for( int i = 0; i < hb_audio_bitrates_count; i++ )
3528 if (hb_audio_bitrates[i].rate >= minbitrate && hb_audio_bitrates[i].rate <= maxbitrate)
3530 /* add a new menuitem for this bitrate */
3531 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
3532 [NSString stringWithCString: hb_audio_bitrates[i].string]
3533 action: NULL keyEquivalent: @""];
3534 /* set its tag to be the actual bitrate as an integer, so we can retrieve it later */
3535 [menuItem setTag: hb_audio_bitrates[i].rate];
3539 /* select the default bitrate (but use 384 for 6-ch AAC) */
3540 if ([[mixdownPopUp selectedItem] tag] == HB_AMIXDOWN_6CH)
3542 [bitratePopUp selectItemWithTag: 384];
3546 [bitratePopUp selectItemWithTag: hb_audio_bitrates[hb_audio_bitrates_default].rate];
3549 /* populate and set the sample rate popup */
3550 /* Audio samplerate */
3551 [sampleratePopUp removeAllItems];
3552 /* we create a same as source selection (Auto) so that we can choose to use the input sample rate */
3553 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle: @"Auto" action: NULL keyEquivalent: @""];
3554 [menuItem setTag: inputsamplerate];
3556 for( int i = 0; i < hb_audio_rates_count; i++ )
3558 NSMenuItem *menuItem = [[sampleratePopUp menu] addItemWithTitle:
3559 [NSString stringWithCString: hb_audio_rates[i].string]
3560 action: NULL keyEquivalent: @""];
3561 [menuItem setTag: hb_audio_rates[i].rate];
3563 /* We use the input sample rate as the default sample rate as downsampling just makes audio worse
3564 * and there is no compelling reason to use anything else as default, though the users default
3565 * preset will likely override any setting chosen here.
3567 [sampleratePopUp selectItemWithTag: inputsamplerate];
3570 /* Since AC3 Pass Thru uses the input ac3 bitrate and sample rate, we get the input tracks
3571 * bitrate and dispay it in the bitrate popup even though libhb happily ignores any bitrate input from
3572 * the gui. We do this for better user feedback in the audio tab as well as the queue for the most part
3574 if ([[mixdownPopUp selectedItem] tag] == HB_ACODEC_AC3)
3577 /* lets also set the bitrate popup to the input bitrate as thats what passthru will use */
3578 [bitratePopUp removeAllItems];
3579 NSMenuItem *menuItem = [[bitratePopUp menu] addItemWithTitle:
3580 [NSString stringWithFormat:@"%d", inputbitrate]
3581 action: NULL keyEquivalent: @""];
3582 [menuItem setTag: inputbitrate];
3583 /* For ac3 passthru we disable the sample rate and bitrate popups as well as the drc slider*/
3584 [bitratePopUp setEnabled: NO];
3585 [sampleratePopUp setEnabled: NO];
3587 [drcSlider setFloatValue: 1.00];
3588 [self audioDRCSliderChanged: drcSlider];
3589 [drcSlider setEnabled: NO];
3590 [drcField setEnabled: NO];
3594 [sampleratePopUp setEnabled: YES];
3595 [bitratePopUp setEnabled: YES];
3596 [drcSlider setEnabled: YES];
3597 [drcField setEnabled: YES];
3602 - (IBAction) audioDRCSliderChanged: (id) sender
3604 NSSlider * drcSlider;
3605 NSTextField * drcField;
3606 if (sender == fAudTrack1DrcSlider)
3608 drcSlider = fAudTrack1DrcSlider;
3609 drcField = fAudTrack1DrcField;
3611 else if (sender == fAudTrack2DrcSlider)
3613 drcSlider = fAudTrack2DrcSlider;
3614 drcField = fAudTrack2DrcField;
3616 else if (sender == fAudTrack3DrcSlider)
3618 drcSlider = fAudTrack3DrcSlider;
3619 drcField = fAudTrack3DrcField;
3623 drcSlider = fAudTrack4DrcSlider;
3624 drcField = fAudTrack4DrcField;
3626 [drcField setStringValue: [NSString stringWithFormat: @"%.2f", [drcSlider floatValue]]];
3627 /* For now, do not call this until we have an intelligent way to determine audio track selections
3628 * compared to presets
3630 //[self customSettingUsed: sender];
3633 - (IBAction) subtitleSelectionChanged: (id) sender
3635 if ([fSubPopUp indexOfSelectedItem] == 0)
3637 [fSubForcedCheck setState: NSOffState];
3638 [fSubForcedCheck setEnabled: NO];
3642 [fSubForcedCheck setEnabled: YES];
3651 #pragma mark Open New Windows
3653 - (IBAction) openHomepage: (id) sender
3655 [[NSWorkspace sharedWorkspace] openURL: [NSURL
3656 URLWithString:@"http://handbrake.fr/"]];
3659 - (IBAction) openForums: (id) sender
3661 [[NSWorkspace sharedWorkspace] openURL: [NSURL
3662 URLWithString:@"http://handbrake.fr/forum/"]];
3664 - (IBAction) openUserGuide: (id) sender
3666 [[NSWorkspace sharedWorkspace] openURL: [NSURL
3667 URLWithString:@"http://handbrake.fr/trac/wiki/HandBrakeGuide"]];
3671 * Shows debug output window.
3673 - (IBAction)showDebugOutputPanel:(id)sender
3675 [outputPanel showOutputPanel:sender];
3679 * Shows preferences window.
3681 - (IBAction) showPreferencesWindow: (id) sender
3683 NSWindow * window = [fPreferencesController window];
3684 if (![window isVisible])
3687 [window makeKeyAndOrderFront: nil];
3691 * Shows queue window.
3693 - (IBAction) showQueueWindow:(id)sender
3695 [fQueueController showQueueWindow:sender];
3699 - (IBAction) toggleDrawer:(id)sender {
3700 [fPresetDrawer toggle:self];
3704 * Shows Picture Settings Window.
3707 - (IBAction) showPicturePanel: (id) sender
3709 hb_list_t * list = hb_get_titles( fHandle );
3710 hb_title_t * title = (hb_title_t *) hb_list_item( list,
3711 [fSrcTitlePopUp indexOfSelectedItem] );
3712 [fPictureController showPanelInWindow:fWindow forTitle:title];
3716 #pragma mark Preset Outline View Methods
3717 #pragma mark - Required
3718 /* These are required by the NSOutlineView Datasource Delegate */
3719 /* We use this to deterimine children of an item */
3720 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
3723 return [UserPresets objectAtIndex:index];
3725 // We are only one level deep, so we can't be asked about children
3726 NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
3729 /* We use this to determine if an item should be expandable */
3730 - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
3733 /* For now, we maintain one level, so set to no
3734 * when nested, we set to yes for any preset "folders"
3739 /* used to specify the number of levels to show for each item */
3740 - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
3742 /* currently use no levels to test outline view viability */
3744 return [UserPresets count];
3748 /* Used to tell the outline view which information is to be displayed per item */
3749 - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
3751 /* We have two columns right now, icon and PresetName */
3753 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
3755 return [item objectForKey:@"PresetName"];
3759 return @"something";
3763 #pragma mark - Added Functionality (optional)
3764 /* Use to customize the font and display characteristics of the title cell */
3765 - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
3767 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
3769 NSDictionary *userPresetDict = item;
3772 NSColor *shadowColor;
3773 txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
3774 /*check to see if its a selected row */
3775 if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
3778 fontColor = [NSColor blackColor];
3779 shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
3783 if ([[userPresetDict objectForKey:@"Type"] intValue] == 0)
3785 fontColor = [NSColor blueColor];
3787 else // User created preset, use a black font
3789 fontColor = [NSColor blackColor];
3793 /* We use Bold Text for the HB Default */
3794 if ([[userPresetDict objectForKey:@"Default"] intValue] == 1)// 1 is HB default
3796 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
3798 /* We use Bold Text for the User Specified Default */
3799 if ([[userPresetDict objectForKey:@"Default"] intValue] == 2)// 2 is User default
3801 txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
3805 [cell setTextColor:fontColor];
3806 [cell setFont:txtFont];
3811 /* We use this to edit the name field in the outline view */
3812 - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
3814 if ([[tableColumn identifier] isEqualToString:@"PresetName"])
3819 [theRecord setObject:object forKey:@"PresetName"];
3823 [fPresetsOutlineView reloadData];
3824 /* We save all of the preset data here */
3828 /* We use this to provide tooltips for the items in the presets outline view */
3829 - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
3831 //if ([[tc identifier] isEqualToString:@"PresetName"])
3833 /* initialize the tooltip contents variable */
3835 /* if there is a description for the preset, we show it in the tooltip */
3836 if ([item valueForKey:@"PresetDescription"])
3838 loc_tip = [item valueForKey:@"PresetDescription"];
3843 loc_tip = @"No description available";
3850 #pragma mark Preset Outline View Methods (dragging related)
3853 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
3855 // Dragging is only allowed for custom presets.
3856 if ([[[UserPresets objectAtIndex:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
3860 // Don't retain since this is just holding temporaral drag information, and it is
3861 //only used during a drag! We could put this in the pboard actually.
3862 fDraggedNodes = items;
3863 // Provide data for our custom type, and simple NSStrings.
3864 [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
3866 // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
3867 [pboard setData:[NSData data] forType:DragDropSimplePboardType];
3872 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
3874 // Don't allow dropping ONTO an item since they can't really contain any children.
3876 BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
3877 if (isOnDropTypeProposal)
3878 return NSDragOperationNone;
3881 // Don't allow dropping INTO an item since they can't really contain any children as of yet.
3885 index = [fPresetsOutlineView rowForItem: item] + 1;
3889 // Don't allow dropping into the Built In Presets.
3890 if (index < presetCurrentBuiltInCount)
3892 return NSDragOperationNone;
3893 index = MAX (index, presetCurrentBuiltInCount);
3896 [outlineView setDropItem:item dropChildIndex:index];
3897 return NSDragOperationGeneric;
3902 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
3904 NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
3907 NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
3908 while (obj = [enumerator nextObject])
3910 [moveItems addIndex:[UserPresets indexOfObject:obj]];
3912 // Successful drop, lets rearrange the view and save it all
3913 [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
3914 [fPresetsOutlineView reloadData];
3919 - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(unsigned)insertIndex
3921 unsigned index = [indexSet lastIndex];
3922 unsigned aboveInsertIndexCount = 0;
3924 while (index != NSNotFound)
3926 unsigned removeIndex;
3928 if (index >= insertIndex)
3930 removeIndex = index + aboveInsertIndexCount;
3931 aboveInsertIndexCount++;
3935 removeIndex = index;
3939 id object = [[array objectAtIndex:removeIndex] retain];
3940 [array removeObjectAtIndex:removeIndex];
3941 [array insertObject:object atIndex:insertIndex];
3944 index = [indexSet indexLessThanIndex:index];
3950 #pragma mark - Functional Preset NSOutlineView Methods
3952 - (IBAction)selectPreset:(id)sender
3955 if ([fPresetsOutlineView selectedRow] >= 0)
3957 chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
3958 /* we set the preset display field in main window here */
3959 [fPresetSelectedDisplay setStringValue:[chosenPreset valueForKey:@"PresetName"]];
3960 if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
3962 [fPresetSelectedDisplay setStringValue: [NSString stringWithFormat: @"%@ (Default)",[chosenPreset valueForKey:@"PresetName"]]];
3966 [fPresetSelectedDisplay setStringValue:[chosenPreset valueForKey:@"PresetName"]];
3969 [fDstFormatPopUp selectItemWithTitle:[chosenPreset valueForKey:@"FileFormat"]];
3970 [self formatPopUpChanged: NULL];
3972 /* Chapter Markers*/
3973 [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
3974 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
3975 [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
3976 /* Mux mp4 with http optimization */
3977 [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
3980 /* We set the advanced opt string here if applicable*/
3981 [fAdvancedOptions setOptions:[chosenPreset valueForKey:@"x264Option"]];
3982 /* We use a conditional to account for the new x264 encoder dropdown as well as presets made using legacy x264 settings*/
3983 if ([[chosenPreset valueForKey:@"VideoEncoder"] isEqualToString: @"x264 (h.264 Main)"] ||
3984 [[chosenPreset valueForKey:@"VideoEncoder"] isEqualToString: @"x264 (h.264 iPod)"] ||
3985 [[chosenPreset valueForKey:@"VideoEncoder"] isEqualToString: @"x264"])
3987 [fVidEncoderPopUp selectItemWithTitle:@"H.264 (x264)"];
3988 /* special case for legacy preset to check the new fDstMp4HttpOptFileCheck checkbox to set the ipod atom */
3989 if ([[chosenPreset valueForKey:@"VideoEncoder"] isEqualToString: @"x264 (h.264 iPod)"])
3991 [fDstMp4iPodFileCheck setState:NSOnState];
3992 /* We also need to add "level=30:" to the advanced opts string to set the correct level for the iPod when
3993 encountering a legacy preset as it used to be handled separately from the opt string*/
3994 [fAdvancedOptions setOptions:[@"level=30:" stringByAppendingString:[fAdvancedOptions optionsString]]];
3998 [fDstMp4iPodFileCheck setState:NSOffState];
4001 else if ([[chosenPreset valueForKey:@"VideoEncoder"] isEqualToString: @"FFmpeg"])
4003 [fVidEncoderPopUp selectItemWithTitle:@"MPEG-4 (FFmpeg)"];
4005 else if ([[chosenPreset valueForKey:@"VideoEncoder"] isEqualToString: @"XviD"])
4007 [fVidEncoderPopUp selectItemWithTitle:@"MPEG-4 (XviD)"];
4011 [fVidEncoderPopUp selectItemWithTitle:[chosenPreset valueForKey:@"VideoEncoder"]];
4014 /* Lets run through the following functions to get variables set there */
4015 [self videoEncoderPopUpChanged: NULL];
4016 /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
4017 [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
4018 [self calculateBitrate: NULL];
4021 [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
4023 [fVidTargetSizeField setStringValue:[chosenPreset valueForKey:@"VideoTargetSize"]];
4024 [fVidBitrateField setStringValue:[chosenPreset valueForKey:@"VideoAvgBitrate"]];
4025 [fVidQualitySlider setFloatValue: [[chosenPreset valueForKey:@"VideoQualitySlider"] floatValue]];
4027 [self videoMatrixChanged: NULL];
4029 /* Video framerate */
4030 /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
4031 detected framerate in the fVidRatePopUp so we use index 0*/
4032 if ([[chosenPreset valueForKey:@"VideoFramerate"] isEqualToString: @"Same as source"])
4034 [fVidRatePopUp selectItemAtIndex: 0];
4038 [fVidRatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"VideoFramerate"]];
4042 [fVidGrayscaleCheck setState:[[chosenPreset objectForKey:@"VideoGrayScale"] intValue]];
4044 /* 2 Pass Encoding */
4045 [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
4046 [self twoPassCheckboxChanged: NULL];
4047 /* Turbo 1st pass for 2 Pass Encoding */
4048 [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
4051 if ([chosenPreset valueForKey:@"FileCodecs"])
4053 /* We need to handle the audio codec popup by determining what was chosen from the deprecated Codecs PopUp for past presets*/
4054 if ([[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"AVC/H.264 Video / AAC + AC3 Audio"])
4056 /* We need to address setting languages etc. here in the new multi track audio panel */
4057 /* Track One set here */
4058 /*for track one though a track should be selected but lets check here anyway and use track one if its not.*/
4059 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4061 [fAudLang1PopUp selectItemAtIndex: 1];
4062 [self audioTrackPopUpChanged: fAudLang1PopUp];
4064 [fAudTrack1CodecPopUp selectItemWithTitle: @"AAC (faac)"];
4065 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4066 /* Track Two, set source same as track one */
4067 [fAudLang2PopUp selectItemAtIndex: [fAudLang1PopUp indexOfSelectedItem]];
4068 [self audioTrackPopUpChanged: fAudLang2PopUp];
4069 [fAudTrack2CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
4070 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4072 else if ([[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"MPEG-4 Video / AAC Audio"] ||
4073 [[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"AVC/H.264 Video / AAC Audio"])
4075 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4077 [fAudTrack1CodecPopUp selectItemWithTitle: @"AAC (faac)"];
4078 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4080 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4082 [fAudTrack2CodecPopUp selectItemWithTitle: @"AAC (faac)"];
4083 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4085 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4087 [fAudTrack3CodecPopUp selectItemWithTitle: @"AAC (faac)"];
4088 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
4090 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4092 [fAudTrack4CodecPopUp selectItemWithTitle: @"AAC (faac)"];
4093 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
4096 else if ([[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"MPEG-4 Video / AC-3 Audio"] ||
4097 [[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"AVC/H.264 Video / AC-3 Audio"])
4099 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4101 [fAudTrack1CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
4102 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4104 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4106 [fAudTrack2CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
4107 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4109 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4111 [fAudTrack3CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
4112 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
4114 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4116 [fAudTrack4CodecPopUp selectItemWithTitle: @"AC3 Passthru"];
4117 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
4120 else if ([[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"MPEG-4 Video / MP3 Audio"] ||
4121 [[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"AVC/H.264 Video / MP3 Audio"])
4123 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4125 [fAudTrack1CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
4126 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4128 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4130 [fAudTrack2CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
4131 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4133 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4135 [fAudTrack3CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
4136 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
4138 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4140 [fAudTrack4CodecPopUp selectItemWithTitle: @"MP3 (lame)"];
4141 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
4144 else if ([[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"MPEG-4 Video / Vorbis Audio"])
4146 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4148 [fAudTrack1CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
4149 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4151 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4153 [fAudTrack2CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
4154 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4156 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4158 [fAudTrack3CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
4159 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
4161 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4163 [fAudTrack4CodecPopUp selectItemWithTitle: @"Vorbis (vorbis)"];
4164 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
4167 /* We detect here if we have the old audio sample rate and if so we apply samplerate and bitrate to the existing four tracks if chosen
4168 * UNLESS the CodecPopUp is AC3 in which case the preset values are ignored in favor of rates set in audioTrackMixdownChanged*/
4169 if ([chosenPreset valueForKey:@"AudioSampleRate"])
4171 if ([fAudLang1PopUp indexOfSelectedItem] > 0 && [fAudTrack1CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
4173 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioSampleRate"]];
4174 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioBitRate"]];
4176 if ([fAudLang2PopUp indexOfSelectedItem] > 0 && [fAudTrack2CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
4178 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioSampleRate"]];
4179 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioBitRate"]];
4181 if ([fAudLang3PopUp indexOfSelectedItem] > 0 && [fAudTrack3CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
4183 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioSampleRate"]];
4184 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioBitRate"]];
4186 if ([fAudLang4PopUp indexOfSelectedItem] > 0 && [fAudTrack4CodecPopUp titleOfSelectedItem] != @"AC3 Passthru")
4188 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioSampleRate"]];
4189 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"AudioBitRate"]];
4192 /* We detect here if we have the old DRC Slider and if so we apply it to the existing four tracks if chosen */
4193 if ([chosenPreset valueForKey:@"AudioDRCSlider"])
4195 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4197 [fAudTrack1DrcSlider setFloatValue: [[chosenPreset valueForKey:@"AudioDRCSlider"] floatValue]];
4198 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4200 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4202 [fAudTrack2DrcSlider setFloatValue: [[chosenPreset valueForKey:@"AudioDRCSlider"] floatValue]];
4203 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
4205 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4207 [fAudTrack3DrcSlider setFloatValue: [[chosenPreset valueForKey:@"AudioDRCSlider"] floatValue]];
4208 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
4210 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4212 [fAudTrack4DrcSlider setFloatValue: [[chosenPreset valueForKey:@"AudioDRCSlider"] floatValue]];
4213 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
4217 else // since there was no codecs key in the preset we know we can use new multi-audio track presets
4219 if ([chosenPreset valueForKey:@"Audio1Track"] > 0)
4221 if ([fAudLang1PopUp indexOfSelectedItem] == 0)
4223 [fAudLang1PopUp selectItemAtIndex: 1];
4225 [self audioTrackPopUpChanged: fAudLang1PopUp];
4226 [fAudTrack1CodecPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio1Encoder"]];
4227 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4228 [fAudTrack1MixPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio1Mixdown"]];
4229 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
4231 if ([fAudTrack1MixPopUp selectedItem] == nil)
4233 [self audioTrackPopUpChanged: fAudTrack1CodecPopUp];
4235 [fAudTrack1RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio1Samplerate"]];
4236 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
4237 if (![[chosenPreset valueForKey:@"Audio1Encoder"] isEqualToString: @"AC3 Passthru"])
4239 [fAudTrack1BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio1Bitrate"]];
4241 [fAudTrack1DrcSlider setFloatValue: [[chosenPreset valueForKey:@"Audio1TrackDRCSlider"] floatValue]];
4242 [self audioDRCSliderChanged: fAudTrack1DrcSlider];
4244 if ([chosenPreset valueForKey:@"Audio2Track"] > 0)
4246 if ([fAudLang2PopUp indexOfSelectedItem] == 0)
4248 [fAudLang2PopUp selectItemAtIndex: 1];
4250 [self audioTrackPopUpChanged: fAudLang2PopUp];
4251 [fAudTrack2CodecPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio2Encoder"]];
4252 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4253 [fAudTrack2MixPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio2Mixdown"]];
4254 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
4256 if ([fAudTrack2MixPopUp selectedItem] == nil)
4258 [self audioTrackPopUpChanged: fAudTrack2CodecPopUp];
4260 [fAudTrack2RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio2Samplerate"]];
4261 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
4262 if (![[chosenPreset valueForKey:@"Audio2Encoder"] isEqualToString: @"AC3 Passthru"])
4264 [fAudTrack2BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio2Bitrate"]];
4266 [fAudTrack2DrcSlider setFloatValue: [[chosenPreset valueForKey:@"Audio2TrackDRCSlider"] floatValue]];
4267 [self audioDRCSliderChanged: fAudTrack2DrcSlider];
4269 if ([chosenPreset valueForKey:@"Audio3Track"] > 0)
4271 if ([fAudLang3PopUp indexOfSelectedItem] == 0)
4273 [fAudLang3PopUp selectItemAtIndex: 1];
4275 [self audioTrackPopUpChanged: fAudLang3PopUp];
4276 [fAudTrack3CodecPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio3Encoder"]];
4277 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
4278 [fAudTrack3MixPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio3Mixdown"]];
4279 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
4281 if ([fAudTrack3MixPopUp selectedItem] == nil)
4283 [self audioTrackPopUpChanged: fAudTrack3CodecPopUp];
4285 [fAudTrack3RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio3Samplerate"]];
4286 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
4287 if (![[chosenPreset valueForKey:@"Audio3Encoder"] isEqualToString: @"AC3 Passthru"])
4289 [fAudTrack3BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio3Bitrate"]];
4291 [fAudTrack3DrcSlider setFloatValue: [[chosenPreset valueForKey:@"Audio3TrackDRCSlider"] floatValue]];
4292 [self audioDRCSliderChanged: fAudTrack3DrcSlider];
4294 if ([chosenPreset valueForKey:@"Audio4Track"] > 0)
4296 if ([fAudLang4PopUp indexOfSelectedItem] == 0)
4298 [fAudLang4PopUp selectItemAtIndex: 1];
4300 [self audioTrackPopUpChanged: fAudLang4PopUp];
4301 [fAudTrack4CodecPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio4Encoder"]];
4302 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
4303 [fAudTrack4MixPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio4Mixdown"]];
4304 /* check to see if the selections was available, if not, rerun audioTrackPopUpChanged using the codec to just set the default
4306 if ([fAudTrack4MixPopUp selectedItem] == nil)
4308 [self audioTrackPopUpChanged: fAudTrack4CodecPopUp];
4310 [fAudTrack4RatePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio4Samplerate"]];
4311 /* We set the presets bitrate if it is *not* an AC3 track since that uses the input bitrate */
4312 if (![[chosenPreset valueForKey:@"Audio4Encoder"] isEqualToString: @"AC3 Passthru"])
4314 [fAudTrack4BitratePopUp selectItemWithTitle:[chosenPreset valueForKey:@"Audio4Bitrate"]];
4316 [fAudTrack4DrcSlider setFloatValue: [[chosenPreset valueForKey:@"Audio4TrackDRCSlider"] floatValue]];
4317 [self audioDRCSliderChanged: fAudTrack4DrcSlider];
4323 /* We now cleanup any extra audio tracks that may be previously set if we need to, we do it here so we don't have to
4324 * duplicate any code for legacy presets.*/
4325 /* First we handle the legacy Codecs crazy AVC/H.264 Video / AAC + AC3 Audio atv hybrid */
4326 if ([chosenPreset valueForKey:@"FileCodecs"] && [[chosenPreset valueForKey:@"FileCodecs"] isEqualToString: @"AVC/H.264 Video / AAC + AC3 Audio"])
4328 [fAudLang3PopUp selectItemAtIndex: 0];
4329 [self audioTrackPopUpChanged: fAudLang3PopUp];
4330 [fAudLang4PopUp selectItemAtIndex: 0];
4331 [self audioTrackPopUpChanged: fAudLang4PopUp];
4335 if (![chosenPreset objectForKey:@"Audio2Track"] || [chosenPreset valueForKey:@"Audio2Track"] == 0)
4337 [fAudLang2PopUp selectItemAtIndex: 0];
4338 [self audioTrackPopUpChanged: fAudLang2PopUp];
4340 if (![chosenPreset objectForKey:@"Audio3Track"] || [chosenPreset valueForKey:@"Audio3Track"] > 0)
4342 [fAudLang3PopUp selectItemAtIndex: 0];
4343 [self audioTrackPopUpChanged: fAudLang3PopUp];
4345 if (![chosenPreset objectForKey:@"Audio4Track"] || [chosenPreset valueForKey:@"Audio4Track"] > 0)
4347 [fAudLang4PopUp selectItemAtIndex: 0];
4348 [self audioTrackPopUpChanged: fAudLang4PopUp];
4353 [fSubPopUp selectItemWithTitle:[chosenPreset valueForKey:@"Subtitles"]];
4354 /* Forced Subtitles */
4355 [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
4357 /* Picture Settings */
4358 /* Note: objectForKey:@"UsesPictureSettings" now refers to picture size, this encompasses:
4359 * height, width, keep ar, anamorphic and crop settings.
4360 * picture filters are now handled separately.
4361 * We will be able to actually change the key names for legacy preset keys when preset file
4362 * update code is done. But for now, lets hang onto the old legacy key name for backwards compatibility.
4364 /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
4365 * and the preset completely ignores any picture sizing values in the preset.
4367 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
4369 hb_job_t * job = fTitle->job;
4370 /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
4371 if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
4373 /* Use Max Picture settings for whatever the dvd is.*/
4374 [self revertPictureSizeToMax: NULL];
4375 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
4376 if (job->keep_ratio == 1)
4378 hb_fix_aspect( job, HB_KEEP_WIDTH );
4379 if( job->height > fTitle->height )
4381 job->height = fTitle->height;
4382 hb_fix_aspect( job, HB_KEEP_HEIGHT );
4385 job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
4387 else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
4389 /* we check to make sure the presets width/height does not exceed the sources width/height */
4390 if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
4392 /* if so, then we use the sources height and width to avoid scaling up */
4393 job->width = fTitle->width;
4394 job->height = fTitle->height;
4396 else // source width/height is >= the preset height/width
4398 /* we can go ahead and use the presets values for height and width */
4399 job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
4400 job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
4402 job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
4403 if (job->keep_ratio == 1)
4405 hb_fix_aspect( job, HB_KEEP_WIDTH );
4406 if( job->height > fTitle->height )
4408 job->height = fTitle->height;
4409 hb_fix_aspect( job, HB_KEEP_HEIGHT );
4412 job->pixel_ratio = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
4415 /* If Cropping is set to custom, then recall all four crop values from
4416 when the preset was created and apply them */
4417 if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
4419 [fPictureController setAutoCrop:NO];
4421 /* Here we use the custom crop values saved at the time the preset was saved */
4422 job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
4423 job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
4424 job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
4425 job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
4428 else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
4430 [fPictureController setAutoCrop:YES];
4431 /* Here we use the auto crop values determined right after scan */
4432 job->crop[0] = AutoCropTop;
4433 job->crop[1] = AutoCropBottom;
4434 job->crop[2] = AutoCropLeft;
4435 job->crop[3] = AutoCropRight;
4438 /* If the preset has no objectForKey:@"UsesPictureFilters", then we know it is a legacy preset
4439 * and handle the filters here as before.
4440 * NOTE: This should be removed when the update presets code is done as we can be assured that legacy
4441 * presets are updated to work properly with new keys.
4443 if (![chosenPreset objectForKey:@"UsesPictureFilters"])
4447 if ([chosenPreset objectForKey:@"PictureDeinterlace"])
4449 /* We check to see if the preset used the past fourth "Slowest" deinterlaceing and set that to "Slower
4450 * since we no longer have a fourth "Slowest" deinterlacing due to the mcdeint bug */
4451 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
4453 [fPictureController setDeinterlace:3];
4458 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
4463 [fPictureController setDeinterlace:0];
4466 if ([[chosenPreset objectForKey:@"VFR"] intValue] == 1)
4468 [fPictureController setVFR:[[chosenPreset objectForKey:@"VFR"] intValue]];
4472 [fPictureController setVFR:0];
4475 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
4477 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
4481 [fPictureController setDetelecine:0];
4484 if ([chosenPreset objectForKey:@"PictureDenoise"])
4486 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
4490 [fPictureController setDenoise:0];
4493 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
4495 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
4499 [fPictureController setDeblock:0];
4502 [self calculatePictureSizing: NULL];
4509 /* If the preset has an objectForKey:@"UsesPictureFilters", then we know it is a newer style filters preset
4510 * and handle the filters here depending on whether or not the preset specifies applying the filter.
4512 if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
4516 if ([chosenPreset objectForKey:@"PictureDeinterlace"])
4518 /* We check to see if the preset used the past fourth "Slowest" deinterlaceing and set that to "Slower
4519 * since we no longer have a fourth "Slowest" deinterlacing due to the mcdeint bug */
4520 if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 4)
4522 [fPictureController setDeinterlace:3];
4526 [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
4531 [fPictureController setDeinterlace:0];
4534 if ([[chosenPreset objectForKey:@"VFR"] intValue] == 1)
4536 [fPictureController setVFR:[[chosenPreset objectForKey:@"VFR"] intValue]];
4540 [fPictureController setVFR:0];
4543 if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
4545 [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
4549 [fPictureController setDetelecine:0];
4552 if ([chosenPreset objectForKey:@"PictureDenoise"])
4554 [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
4558 [fPictureController setDenoise:0];
4561 if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
4563 [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
4567 [fPictureController setDeblock:0];
4570 /* Even though we currently allow for a custom setting for decomb, ultimately it will only have Off and
4571 * Default so we just pay attention to anything greater than 0 as 1 (Default). 0 is Off. */
4572 if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
4574 [fPictureController setDecomb:1];
4578 [fPictureController setDecomb:0];
4581 [self calculatePictureSizing: NULL];
4582 [[fPresetsActionMenu itemAtIndex:0] setEnabled: YES];
4588 #pragma mark Manage Presets
4590 - (void) loadPresets {
4591 /* We declare the default NSFileManager into fileManager */
4592 NSFileManager * fileManager = [NSFileManager defaultManager];
4593 /*We define the location of the user presets file */
4594 UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
4595 UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
4596 /* We check for the presets.plist */
4597 if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
4599 [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
4602 UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
4603 if (nil == UserPresets)
4605 UserPresets = [[NSMutableArray alloc] init];
4606 [self addFactoryPresets:NULL];
4608 [fPresetsOutlineView reloadData];
4612 - (IBAction) showAddPresetPanel: (id) sender
4614 /* Deselect the currently selected Preset if there is one*/
4615 [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
4617 /* Populate the preset picture settings popup here */
4618 [fPresetNewPicSettingsPopUp removeAllItems];
4619 [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
4620 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Current"];
4621 [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
4622 [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
4623 /* Uncheck the preset use filters checkbox */
4624 [fPresetNewPicFiltersCheck setState:NSOffState];
4625 /* Erase info from the input fields*/
4626 [fPresetNewName setStringValue: @""];
4627 [fPresetNewDesc setStringValue: @""];
4628 /* Show the panel */
4629 [NSApp beginSheet: fAddPresetPanel modalForWindow: fWindow modalDelegate: NULL didEndSelector: NULL contextInfo: NULL];
4632 - (IBAction) closeAddPresetPanel: (id) sender
4634 [NSApp endSheet: fAddPresetPanel];
4635 [fAddPresetPanel orderOut: self];
4638 - (IBAction)addUserPreset:(id)sender
4640 if (![[fPresetNewName stringValue] length])
4641 NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
4644 /* Here we create a custom user preset */
4645 [UserPresets addObject:[self createPreset]];
4648 [self closeAddPresetPanel:NULL];
4655 /* We Reload the New Table data for presets */
4656 [fPresetsOutlineView reloadData];
4657 /* We save all of the preset data here */
4665 /* We Sort the Presets By Factory or Custom */
4666 NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
4667 ascending:YES] autorelease];
4668 /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
4670 NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
4671 ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
4672 //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
4675 /* Since we can drag and drop our custom presets, lets just sort by type and not name */
4676 NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
4677 NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
4678 [UserPresets setArray:sortedArray];
4683 - (IBAction)insertPreset:(id)sender
4685 int index = [fPresetsOutlineView selectedRow];
4686 [UserPresets insertObject:[self createPreset] atIndex:index];
4687 [fPresetsOutlineView reloadData];
4691 - (NSDictionary *)createPreset
4693 NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
4694 /* Get the New Preset Name from the field in the AddPresetPanel */
4695 [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
4696 /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
4697 [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
4698 /*Set whether or not this is default, at creation set to 0*/
4699 [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
4700 /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
4701 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
4702 /* Get whether or not to use the current Picture Filter settings for the preset */
4703 [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
4705 /* Get New Preset Description from the field in the AddPresetPanel*/
4706 [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
4708 [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
4709 /* Chapter Markers fCreateChapterMarkers*/
4710 [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
4711 /* Allow Mpeg4 64 bit formatting +4GB file sizes */
4712 [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
4713 /* Mux mp4 with http optimization */
4714 [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
4715 /* Add iPod uuid atom */
4716 [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
4720 [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
4721 /* x264 Option String */
4722 [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
4724 [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
4725 [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
4726 [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
4727 [preset setObject:[NSNumber numberWithFloat:[fVidQualitySlider floatValue]] forKey:@"VideoQualitySlider"];
4729 /* Video framerate */
4730 if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
4732 [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
4734 else // we can record the actual titleOfSelectedItem
4736 [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
4739 [preset setObject:[NSNumber numberWithInt:[fVidGrayscaleCheck state]] forKey:@"VideoGrayScale"];
4740 /* 2 Pass Encoding */
4741 [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
4742 /* Turbo 2 pass Encoding fVidTurboPassCheck*/
4743 [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
4744 /*Picture Settings*/
4745 hb_job_t * job = fTitle->job;
4746 /* Picture Sizing */
4747 /* Use Max Picture settings for whatever the dvd is.*/
4748 [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
4749 [preset setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
4750 [preset setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
4751 [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
4752 [preset setObject:[NSNumber numberWithInt:fTitle->job->pixel_ratio] forKey:@"PicturePAR"];
4754 /* Set crop settings here */
4755 [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
4756 [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
4757 [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
4758 [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
4759 [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
4761 /* Picture Filters */
4762 [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
4763 [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
4764 [preset setObject:[NSNumber numberWithInt:[fPictureController vfr]] forKey:@"VFR"];
4765 [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
4766 [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
4767 [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
4771 if ([fAudLang1PopUp indexOfSelectedItem] > 0)
4773 [preset setObject:[NSNumber numberWithInt:[fAudLang1PopUp indexOfSelectedItem]] forKey:@"Audio1Track"];
4774 [preset setObject:[fAudLang1PopUp titleOfSelectedItem] forKey:@"Audio1TrackDescription"];
4775 [preset setObject:[fAudTrack1CodecPopUp titleOfSelectedItem] forKey:@"Audio1Encoder"];
4776 [preset setObject:[fAudTrack1MixPopUp titleOfSelectedItem] forKey:@"Audio1Mixdown"];
4777 [preset setObject:[fAudTrack1RatePopUp titleOfSelectedItem] forKey:@"Audio1Samplerate"];
4778 [preset setObject:[fAudTrack1BitratePopUp titleOfSelectedItem] forKey:@"Audio1Bitrate"];
4779 [preset setObject:[NSNumber numberWithFloat:[fAudTrack1DrcSlider floatValue]] forKey:@"Audio1TrackDRCSlider"];
4781 if ([fAudLang2PopUp indexOfSelectedItem] > 0)
4783 [preset setObject:[NSNumber numberWithInt:[fAudLang2PopUp indexOfSelectedItem]] forKey:@"Audio2Track"];
4784 [preset setObject:[fAudLang2PopUp titleOfSelectedItem] forKey:@"Audio2TrackDescription"];
4785 [preset setObject:[fAudTrack2CodecPopUp titleOfSelectedItem] forKey:@"Audio2Encoder"];
4786 [preset setObject:[fAudTrack2MixPopUp titleOfSelectedItem] forKey:@"Audio2Mixdown"];
4787 [preset setObject:[fAudTrack2RatePopUp titleOfSelectedItem] forKey:@"Audio2Samplerate"];
4788 [preset setObject:[fAudTrack2BitratePopUp titleOfSelectedItem] forKey:@"Audio2Bitrate"];
4789 [preset setObject:[NSNumber numberWithFloat:[fAudTrack2DrcSlider floatValue]] forKey:@"Audio2TrackDRCSlider"];
4791 if ([fAudLang3PopUp indexOfSelectedItem] > 0)
4793 [preset setObject:[NSNumber numberWithInt:[fAudLang3PopUp indexOfSelectedItem]] forKey:@"Audio3Track"];
4794 [preset setObject:[fAudLang3PopUp titleOfSelectedItem] forKey:@"Audio3TrackDescription"];
4795 [preset setObject:[fAudTrack3CodecPopUp titleOfSelectedItem] forKey:@"Audio3Encoder"];
4796 [preset setObject:[fAudTrack3MixPopUp titleOfSelectedItem] forKey:@"Audio3Mixdown"];
4797 [preset setObject:[fAudTrack3RatePopUp titleOfSelectedItem] forKey:@"Audio3Samplerate"];
4798 [preset setObject:[fAudTrack3BitratePopUp titleOfSelectedItem] forKey:@"Audio3Bitrate"];
4799 [preset setObject:[NSNumber numberWithFloat:[fAudTrack3DrcSlider floatValue]] forKey:@"Audio3TrackDRCSlider"];
4801 if ([fAudLang4PopUp indexOfSelectedItem] > 0)
4803 [preset setObject:[NSNumber numberWithInt:[fAudLang4PopUp indexOfSelectedItem]] forKey:@"Audio4Track"];
4804 [preset setObject:[fAudLang4PopUp titleOfSelectedItem] forKey:@"Audio4TrackDescription"];
4805 [preset setObject:[fAudTrack4CodecPopUp titleOfSelectedItem] forKey:@"Audio4Encoder"];
4806 [preset setObject:[fAudTrack4MixPopUp titleOfSelectedItem] forKey:@"Audio4Mixdown"];
4807 [preset setObject:[fAudTrack4RatePopUp titleOfSelectedItem] forKey:@"Audio4Samplerate"];
4808 [preset setObject:[fAudTrack4BitratePopUp titleOfSelectedItem] forKey:@"Audio4Bitrate"];
4809 [preset setObject:[NSNumber numberWithFloat:[fAudTrack4DrcSlider floatValue]] forKey:@"Audio4TrackDRCSlider"];
4813 [preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
4814 /* Forced Subtitles */
4815 [preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
4817 [preset autorelease];
4824 [UserPresets writeToFile:UserPresetsFile atomically:YES];
4825 /* We get the default preset in case it changed */
4826 [self getDefaultPresets: NULL];
4830 - (IBAction)deletePreset:(id)sender
4833 NSEnumerator *enumerator;
4835 NSMutableArray *tempArray;
4838 if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
4840 /* Alert user before deleting preset */
4841 /* Comment out for now, tie to user pref eventually */
4844 status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
4846 if ( status == NSAlertDefaultReturn ) {
4847 enumerator = [fPresetsOutlineView selectedRowEnumerator];
4848 tempArray = [NSMutableArray array];
4850 while ( (index = [enumerator nextObject]) ) {
4851 tempObject = [UserPresets objectAtIndex:[index intValue]];
4852 [tempArray addObject:tempObject];
4855 [UserPresets removeObjectsInArray:tempArray];
4856 [fPresetsOutlineView reloadData];
4862 #pragma mark Manage Default Preset
4864 - (IBAction)getDefaultPresets:(id)sender
4867 presetCurrentBuiltInCount = 0;
4868 NSEnumerator *enumerator = [UserPresets objectEnumerator];
4870 while (tempObject = [enumerator nextObject])
4872 NSDictionary *thisPresetDict = tempObject;
4873 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
4875 presetHbDefault = i;
4877 if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
4879 presetUserDefault = i;
4881 if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
4883 presetCurrentBuiltInCount++; // <--increment the current number of built in presets
4889 - (IBAction)setDefaultPreset:(id)sender
4892 NSEnumerator *enumerator = [UserPresets objectEnumerator];
4894 /* First make sure the old user specified default preset is removed */
4895 while (tempObject = [enumerator nextObject])
4897 /* make sure we are not removing the default HB preset */
4898 if ([[[UserPresets objectAtIndex:i] objectForKey:@"Default"] intValue] != 1) // 1 is HB default
4900 [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
4904 /* Second, go ahead and set the appropriate user specfied preset */
4905 /* we get the chosen preset from the UserPresets array */
4906 if ([[[UserPresets objectAtIndex:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1) // 1 is HB default
4908 [[UserPresets objectAtIndex:[fPresetsOutlineView selectedRow]] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
4910 /*FIX ME: I think we now need to use the items not rows in NSOutlineView */
4911 presetUserDefault = [fPresetsOutlineView selectedRow];
4913 /* We save all of the preset data here */
4915 /* We Reload the New Table data for presets */
4916 [fPresetsOutlineView reloadData];
4919 - (IBAction)selectDefaultPreset:(id)sender
4921 /* if there is a user specified default, we use it */
4922 if (presetUserDefault)
4924 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:presetUserDefault] byExtendingSelection:NO];
4925 [self selectPreset:NULL];
4927 else if (presetHbDefault) //else we use the built in default presetHbDefault
4929 [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:presetHbDefault] byExtendingSelection:NO];
4930 [self selectPreset:NULL];
4936 #pragma mark Manage Built In Presets
4939 - (IBAction)deleteFactoryPresets:(id)sender
4942 NSEnumerator *enumerator = [UserPresets objectEnumerator];
4946 NSMutableArray *tempArray;
4949 tempArray = [NSMutableArray array];
4950 /* we look here to see if the preset is we move on to the next one */
4951 while ( tempObject = [enumerator nextObject] )
4953 /* if the preset is "Factory" then we put it in the array of
4954 presets to delete */
4955 if ([[tempObject objectForKey:@"Type"] intValue] == 0)
4957 [tempArray addObject:tempObject];
4961 [UserPresets removeObjectsInArray:tempArray];
4962 [fPresetsOutlineView reloadData];
4967 /* We use this method to recreate new, updated factory
4969 - (IBAction)addFactoryPresets:(id)sender
4972 /* First, we delete any existing built in presets */
4973 [self deleteFactoryPresets: sender];
4974 /* Then we generate new built in presets programmatically with fPresetsBuiltin
4975 * which is all setup in HBPresets.h and HBPresets.m*/
4976 [fPresetsBuiltin generateBuiltinPresets:UserPresets];
4988 /*******************************
4989 * Subclass of the HBPresetsOutlineView *
4990 *******************************/
4992 @implementation HBPresetsOutlineView
4993 - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
4997 // By default, NSTableView only drags an image of the first column. Change this to
4998 // drag an image of the queue's icon and PresetName columns.
4999 NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"icon"], [self tableColumnWithIdentifier:@"PresetName"], nil];
5000 return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
5005 - (void) mouseDown:(NSEvent *)theEvent
5007 [super mouseDown:theEvent];
5013 - (BOOL) isDragging;