PageRenderTime 93ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/macosx/Controller.m

https://github.com/griff/HandBrake
Objective C | 6731 lines | 4636 code | 972 blank | 1123 comment | 908 complexity | d7b57d2e706aa732da110d208559e42e MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, BSD-2-Clause, MIT
  1. /* $Id: Controller.mm,v 1.79 2005/11/04 19:41:32 titer Exp $
  2. This file is part of the HandBrake source code.
  3. Homepage: <http://handbrake.fr/>.
  4. It may be used under the terms of the GNU General Public License. */
  5. #include <dlfcn.h>
  6. #import "Controller.h"
  7. #import "HBOutputPanelController.h"
  8. #import "HBPreferencesController.h"
  9. #import "HBDVDDetector.h"
  10. #import "HBPresets.h"
  11. #import "HBPreviewController.h"
  12. unsigned int maximumNumberOfAllowedAudioTracks = 24;
  13. NSString *HBContainerChangedNotification = @"HBContainerChangedNotification";
  14. NSString *keyContainerTag = @"keyContainerTag";
  15. NSString *HBTitleChangedNotification = @"HBTitleChangedNotification";
  16. NSString *keyTitleTag = @"keyTitleTag";
  17. #define DragDropSimplePboardType @"MyCustomOutlineViewPboardType"
  18. /* We setup the toolbar values here ShowPreviewIdentifier */
  19. static NSString * ToggleDrawerIdentifier = @"Toggle Drawer Item Identifier";
  20. static NSString * StartEncodingIdentifier = @"Start Encoding Item Identifier";
  21. static NSString * PauseEncodingIdentifier = @"Pause Encoding Item Identifier";
  22. static NSString * ShowQueueIdentifier = @"Show Queue Item Identifier";
  23. static NSString * AddToQueueIdentifier = @"Add to Queue Item Identifier";
  24. static NSString * ShowPictureIdentifier = @"Show Picture Window Item Identifier";
  25. static NSString * ShowPreviewIdentifier = @"Show Preview Window Item Identifier";
  26. static NSString * ShowActivityIdentifier = @"Debug Output Item Identifier";
  27. static NSString * ChooseSourceIdentifier = @"Choose Source Item Identifier";
  28. /*******************************
  29. * HBController implementation *
  30. *******************************/
  31. @implementation HBController
  32. + (unsigned int) maximumNumberOfAllowedAudioTracks { return maximumNumberOfAllowedAudioTracks; }
  33. - (id)init
  34. {
  35. self = [super init];
  36. if( !self )
  37. {
  38. return nil;
  39. }
  40. /* replace bundled app icon with one which is 32/64-bit savvy */
  41. #if defined( __LP64__ )
  42. fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake-64.icns"]];
  43. #else
  44. fApplicationIcon = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForImageResource:@"HandBrake.icns"]];
  45. #endif
  46. if( fApplicationIcon != nil )
  47. [NSApp setApplicationIconImage:fApplicationIcon];
  48. [HBPreferencesController registerUserDefaults];
  49. fHandle = NULL;
  50. fQueueEncodeLibhb = NULL;
  51. /* Check for check for the app support directory here as
  52. * outputPanel needs it right away, as may other future methods
  53. */
  54. NSString *libraryDir = [NSSearchPathForDirectoriesInDomains( NSLibraryDirectory,
  55. NSUserDomainMask,
  56. YES ) objectAtIndex:0];
  57. AppSupportDirectory = [[libraryDir stringByAppendingPathComponent:@"Application Support"]
  58. stringByAppendingPathComponent:@"HandBrake"];
  59. if( ![[NSFileManager defaultManager] fileExistsAtPath:AppSupportDirectory] )
  60. {
  61. [[NSFileManager defaultManager] createDirectoryAtPath:AppSupportDirectory
  62. attributes:nil];
  63. }
  64. /* Check for and create the App Support Preview directory if necessary */
  65. NSString *PreviewDirectory = [AppSupportDirectory stringByAppendingPathComponent:@"Previews"];
  66. if( ![[NSFileManager defaultManager] fileExistsAtPath:PreviewDirectory] )
  67. {
  68. [[NSFileManager defaultManager] createDirectoryAtPath:PreviewDirectory
  69. attributes:nil];
  70. }
  71. outputPanel = [[HBOutputPanelController alloc] init];
  72. fPictureController = [[PictureController alloc] init];
  73. fQueueController = [[HBQueueController alloc] init];
  74. fAdvancedOptions = [[HBAdvancedController alloc] init];
  75. /* we init the HBPresets class which currently is only used
  76. * for updating built in presets, may move more functionality
  77. * there in the future
  78. */
  79. fPresetsBuiltin = [[HBPresets alloc] init];
  80. fPreferencesController = [[HBPreferencesController alloc] init];
  81. /* Lets report the HandBrake version number here to the activity log and text log file */
  82. NSString *versionStringFull = [[NSString stringWithFormat: @"Handbrake Version: %@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]] stringByAppendingString: [NSString stringWithFormat: @" (%@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]]];
  83. [self writeToActivityLog: "%s", [versionStringFull UTF8String]];
  84. return self;
  85. }
  86. - (void) applicationDidFinishLaunching: (NSNotification *) notification
  87. {
  88. /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
  89. int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
  90. fHandle = hb_init(loggingLevel, 0);
  91. /* Optional dvd nav UseDvdNav*/
  92. hb_dvd_set_dvdnav([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue]);
  93. /* Init a separate instance of libhb for user scanning and setting up jobs */
  94. fQueueEncodeLibhb = hb_init(loggingLevel, 0);
  95. // Set the Growl Delegate
  96. [GrowlApplicationBridge setGrowlDelegate: self];
  97. /* Init others controllers */
  98. [fPictureController SetHandle: fHandle];
  99. [fPictureController setHBController: self];
  100. [fQueueController setHandle: fQueueEncodeLibhb];
  101. [fQueueController setHBController: self];
  102. fChapterTitlesDelegate = [[ChapterTitles alloc] init];
  103. [fChapterTable setDataSource:fChapterTitlesDelegate];
  104. [fChapterTable setDelegate:fChapterTitlesDelegate];
  105. /* setup the subtitles delegate and connections to table */
  106. fSubtitlesDelegate = [[HBSubtitles alloc] init];
  107. [fSubtitlesTable setDataSource:fSubtitlesDelegate];
  108. [fSubtitlesTable setDelegate:fSubtitlesDelegate];
  109. [fSubtitlesTable setRowHeight:25.0];
  110. /* setup the audio controller */
  111. [fAudioDelegate setHBController: self];
  112. [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(autoSetM4vExtension:) name: HBMixdownChangedNotification object: nil];
  113. [fPresetsOutlineView setAutosaveName:@"Presets View"];
  114. [fPresetsOutlineView setAutosaveExpandedItems:YES];
  115. dockIconProgress = 0;
  116. /* Init QueueFile .plist */
  117. [self loadQueueFile];
  118. /* Run hbInstances to get any info on other instances as well as set the
  119. * pid number for this instance in the case of multi-instance encoding. */
  120. hbInstanceNum = [self hbInstances];
  121. /* If we are a single instance it is safe to clean up the previews if there are any
  122. * left over. This is a bit of a kludge but will prevent a build up of old instance
  123. * live preview cruft. No danger of removing an active preview directory since they
  124. * are created later in HBPreviewController if they don't exist at the moment a live
  125. * preview encode is initiated. */
  126. if (hbInstanceNum == 1)
  127. {
  128. NSString *PreviewDirectory = [NSString stringWithFormat:@"~/Library/Application Support/HandBrake/Previews"];
  129. PreviewDirectory = [PreviewDirectory stringByExpandingTildeInPath];
  130. NSError *error;
  131. NSArray *files = [ [NSFileManager defaultManager] contentsOfDirectoryAtPath: PreviewDirectory error: &error ];
  132. for( NSString *file in files )
  133. {
  134. if( file != @"." && file != @".." )
  135. {
  136. [ [NSFileManager defaultManager] removeItemAtPath: [ PreviewDirectory stringByAppendingPathComponent: file ] error: &error ];
  137. if( error )
  138. {
  139. //an error occurred...
  140. [self writeToActivityLog: "Could not remove existing preview at : %s",[file UTF8String] ];
  141. }
  142. }
  143. }
  144. }
  145. /* Call UpdateUI every 1/2 sec */
  146. [[NSRunLoop currentRunLoop] addTimer:[NSTimer
  147. scheduledTimerWithTimeInterval:0.5
  148. target:self
  149. selector:@selector(updateUI:)
  150. userInfo:nil repeats:YES]
  151. forMode:NSDefaultRunLoopMode];
  152. // Open debug output window now if it was visible when HB was closed
  153. if ([[NSUserDefaults standardUserDefaults] boolForKey:@"OutputPanelIsOpen"])
  154. [self showDebugOutputPanel:nil];
  155. // Open queue window now if it was visible when HB was closed
  156. if ([[NSUserDefaults standardUserDefaults] boolForKey:@"QueueWindowIsOpen"])
  157. [self showQueueWindow:nil];
  158. [self openMainWindow:nil];
  159. /* We have to set the bool to tell hb what to do after a scan
  160. * Initially we set it to NO until we start processing the queue
  161. */
  162. applyQueueToScan = NO;
  163. /* Now we re-check the queue array to see if there are
  164. * any remaining encodes to be done in it and ask the
  165. * user if they want to reload the queue */
  166. if ([QueueFileArray count] > 0)
  167. {
  168. /* run getQueueStats to see whats in the queue file */
  169. [self getQueueStats];
  170. /* this results in these values
  171. * fEncodingQueueItem = 0;
  172. * fPendingCount = 0;
  173. * fCompletedCount = 0;
  174. * fCanceledCount = 0;
  175. * fWorkingCount = 0;
  176. */
  177. /*On Screen Notification*/
  178. NSString * alertTitle;
  179. /* We check to see if there is already another instance of hb running.
  180. * Note: hbInstances == 1 means we are the only instance of HandBrake.app
  181. */
  182. if (hbInstanceNum > 1)
  183. {
  184. alertTitle = [NSString stringWithFormat:
  185. NSLocalizedString(@"There is already an instance of HandBrake running.", @"")];
  186. NSBeginCriticalAlertSheet(
  187. alertTitle,
  188. NSLocalizedString(@"Reload Queue", nil),
  189. nil,
  190. nil,
  191. fWindow, self,
  192. nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
  193. NSLocalizedString(@" HandBrake will now load up the existing queue.", nil));
  194. }
  195. else
  196. {
  197. if (fWorkingCount > 0 || fPendingCount > 0)
  198. {
  199. if (fWorkingCount > 0)
  200. {
  201. alertTitle = [NSString stringWithFormat:
  202. NSLocalizedString(@"HandBrake Has Detected %d Previously Encoding Item(s) and %d Pending Item(s) In Your Queue.", @""),
  203. fWorkingCount,fPendingCount];
  204. }
  205. else
  206. {
  207. alertTitle = [NSString stringWithFormat:
  208. NSLocalizedString(@"HandBrake Has Detected %d Pending Item(s) In Your Queue.", @""),
  209. fPendingCount];
  210. }
  211. NSBeginCriticalAlertSheet(
  212. alertTitle,
  213. NSLocalizedString(@"Reload Queue", nil),
  214. nil,
  215. NSLocalizedString(@"Empty Queue", nil),
  216. fWindow, self,
  217. nil, @selector(didDimissReloadQueue:returnCode:contextInfo:), nil,
  218. NSLocalizedString(@" Do you want to reload them ?", nil));
  219. }
  220. else
  221. {
  222. /* Since we addressed any pending or previously encoding items above, we go ahead and make sure the queue
  223. * is empty of any finished items or cancelled items */
  224. [self clearQueueAllItems];
  225. /* We show whichever open source window specified in LaunchSourceBehavior preference key */
  226. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
  227. {
  228. [self browseSources:nil];
  229. }
  230. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
  231. {
  232. [self browseSources:(id)fOpenSourceTitleMMenu];
  233. }
  234. }
  235. }
  236. }
  237. else
  238. {
  239. /* We show whichever open source window specified in LaunchSourceBehavior preference key */
  240. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
  241. {
  242. [self browseSources:nil];
  243. }
  244. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
  245. {
  246. [self browseSources:(id)fOpenSourceTitleMMenu];
  247. }
  248. }
  249. currentQueueEncodeNameString = @"";
  250. }
  251. #pragma mark -
  252. #pragma mark Multiple Instances
  253. /* hbInstances checks to see if other instances of HB are running and also sets the pid for this instance for multi-instance queue encoding */
  254. /* Note for now since we are in early phases of multi-instance I have put in quite a bit of logging. Can be removed as we see fit. */
  255. - (int) hbInstances
  256. {
  257. /* check to see if another instance of HandBrake.app is running */
  258. NSArray *runningAppDictionaries = [[NSWorkspace sharedWorkspace] launchedApplications];
  259. NSDictionary *runningAppsDictionary;
  260. int hbInstances = 0;
  261. NSString * thisInstanceAppPath = [[NSBundle mainBundle] bundlePath];
  262. NSString * runningInstanceAppPath;
  263. int runningInstancePidNum;
  264. [self writeToActivityLog: "hbInstances path to this instance: %s", [thisInstanceAppPath UTF8String]];
  265. for (runningAppsDictionary in runningAppDictionaries)
  266. {
  267. if ([[runningAppsDictionary valueForKey:@"NSApplicationName"] isEqualToString:@"HandBrake"])
  268. {
  269. /*Report the path to each active instances app path */
  270. runningInstancePidNum = [[runningAppsDictionary valueForKey:@"NSApplicationProcessIdentifier"] intValue];
  271. runningInstanceAppPath = [runningAppsDictionary valueForKey:@"NSApplicationPath"];
  272. [self writeToActivityLog: "hbInstance found instance pidnum:%d at path: %s", runningInstancePidNum, [runningInstanceAppPath UTF8String]];
  273. /* see if this is us by comparing the app path */
  274. if ([runningInstanceAppPath isEqualToString: thisInstanceAppPath])
  275. {
  276. /* If so this is our pidnum */
  277. [self writeToActivityLog: "hbInstance MATCH FOUND, our pidnum is:%d", runningInstancePidNum];
  278. /* Get the PID number for this hb instance, used in multi instance encoding */
  279. pidNum = runningInstancePidNum;
  280. /* Report this pid to the activity log */
  281. [self writeToActivityLog: "Pid for this instance:%d", pidNum];
  282. /* Tell fQueueController what our pidNum is */
  283. [fQueueController setPidNum:pidNum];
  284. }
  285. hbInstances++;
  286. }
  287. }
  288. return hbInstances;
  289. }
  290. - (int) getPidnum
  291. {
  292. return pidNum;
  293. }
  294. #pragma mark -
  295. - (void) didDimissReloadQueue: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
  296. {
  297. [self writeToActivityLog: "didDimissReloadQueue number of hb instances:%d", hbInstanceNum];
  298. if (returnCode == NSAlertOtherReturn)
  299. {
  300. [self writeToActivityLog: "didDimissReloadQueue NSAlertOtherReturn Chosen"];
  301. [self clearQueueAllItems];
  302. /* We show whichever open source window specified in LaunchSourceBehavior preference key */
  303. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source"])
  304. {
  305. [self browseSources:nil];
  306. }
  307. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"LaunchSourceBehavior"] isEqualToString: @"Open Source (Title Specific)"])
  308. {
  309. [self browseSources:(id)fOpenSourceTitleMMenu];
  310. }
  311. }
  312. else
  313. {
  314. [self writeToActivityLog: "didDimissReloadQueue First Button Chosen"];
  315. if (hbInstanceNum == 1)
  316. {
  317. [self setQueueEncodingItemsAsPending];
  318. }
  319. [self showQueueWindow:NULL];
  320. }
  321. }
  322. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) app
  323. {
  324. hb_state_t s;
  325. hb_get_state( fQueueEncodeLibhb, &s );
  326. if ( s.state != HB_STATE_IDLE )
  327. {
  328. int result = NSRunCriticalAlertPanel(
  329. NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
  330. NSLocalizedString(@"If you quit HandBrake your current encode will be reloaded into your queue at next launch. Do you want to quit anyway?", nil),
  331. NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil, @"A movie" );
  332. if (result == NSAlertDefaultReturn)
  333. {
  334. return NSTerminateNow;
  335. }
  336. else
  337. return NSTerminateCancel;
  338. }
  339. // Warn if items still in the queue
  340. else if ( fPendingCount > 0 )
  341. {
  342. int result = NSRunCriticalAlertPanel(
  343. NSLocalizedString(@"Are you sure you want to quit HandBrake?", nil),
  344. NSLocalizedString(@"There are pending encodes in your queue. Do you want to quit anyway?",nil),
  345. NSLocalizedString(@"Quit", nil), NSLocalizedString(@"Don't Quit", nil), nil);
  346. if ( result == NSAlertDefaultReturn )
  347. return NSTerminateNow;
  348. else
  349. return NSTerminateCancel;
  350. }
  351. return NSTerminateNow;
  352. }
  353. - (void)applicationWillTerminate:(NSNotification *)aNotification
  354. {
  355. [currentQueueEncodeNameString release];
  356. [browsedSourceDisplayName release];
  357. [outputPanel release];
  358. [fQueueController release];
  359. [fPreviewController release];
  360. [fPictureController release];
  361. [fApplicationIcon release];
  362. hb_close(&fHandle);
  363. hb_close(&fQueueEncodeLibhb);
  364. hb_global_close();
  365. }
  366. - (void) awakeFromNib
  367. {
  368. [fWindow center];
  369. [fWindow setExcludedFromWindowsMenu:NO];
  370. [fAdvancedOptions setView:fAdvancedView];
  371. /* lets setup our presets drawer for drag and drop here */
  372. [fPresetsOutlineView registerForDraggedTypes: [NSArray arrayWithObject:DragDropSimplePboardType] ];
  373. [fPresetsOutlineView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
  374. [fPresetsOutlineView setVerticalMotionCanBeginDrag: YES];
  375. /* Initialize currentScanCount so HB can use it to
  376. evaluate successive scans */
  377. currentScanCount = 0;
  378. /* Init UserPresets .plist */
  379. [self loadPresets];
  380. fRipIndicatorShown = NO; // initially out of view in the nib
  381. /* For 64 bit builds, the threaded animation in the progress
  382. * indicators conflicts with the animation in the advanced tab
  383. * for reasons not completely clear. jbrjake found a note in the
  384. * 10.5 dev notes regarding this possiblility. It was also noted
  385. * that unless specified, setUsesThreadedAnimation defaults to true.
  386. * So, at least for now we set the indicator animation to NO for
  387. * both the scan and regular progress indicators for both 32 and 64 bit
  388. * as it test out fine on both and there is no reason our progress indicators
  389. * should require their own thread.
  390. */
  391. [fScanIndicator setUsesThreadedAnimation:NO];
  392. [fRipIndicator setUsesThreadedAnimation:NO];
  393. /* Show/Dont Show Presets drawer upon launch based
  394. on user preference DefaultPresetsDrawerShow*/
  395. if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultPresetsDrawerShow"] > 0 )
  396. {
  397. [fPresetDrawer setDelegate:self];
  398. NSSize drawerSize = NSSizeFromString( [[NSUserDefaults standardUserDefaults]
  399. stringForKey:@"Drawer Size"] );
  400. if( drawerSize.width )
  401. [fPresetDrawer setContentSize: drawerSize];
  402. [fPresetDrawer open];
  403. }
  404. /* Initially set the dvd angle widgets to hidden (dvdnav only) */
  405. [fSrcAngleLabel setHidden:YES];
  406. [fSrcAnglePopUp setHidden:YES];
  407. /* Setup the start / stop popup */
  408. [fEncodeStartStopPopUp removeAllItems];
  409. [fEncodeStartStopPopUp addItemWithTitle: @"Chapters"];
  410. [fEncodeStartStopPopUp addItemWithTitle: @"Seconds"];
  411. [fEncodeStartStopPopUp addItemWithTitle: @"Frames"];
  412. /* Align the start / stop widgets with the chapter popups */
  413. [fSrcTimeStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
  414. [fSrcTimeEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
  415. [fSrcFrameStartEncodingField setFrameOrigin:[fSrcChapterStartPopUp frame].origin];
  416. [fSrcFrameEndEncodingField setFrameOrigin:[fSrcChapterEndPopUp frame].origin];
  417. /* Destination box*/
  418. NSMenuItem *menuItem;
  419. [fDstFormatPopUp removeAllItems];
  420. // MP4 file
  421. menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MP4 file" action: NULL keyEquivalent: @""];
  422. [menuItem setTag: HB_MUX_MP4];
  423. // MKV file
  424. menuItem = [[fDstFormatPopUp menu] addItemWithTitle:@"MKV file" action: NULL keyEquivalent: @""];
  425. [menuItem setTag: HB_MUX_MKV];
  426. [fDstFormatPopUp selectItemAtIndex: 0];
  427. [self formatPopUpChanged:nil];
  428. /* We enable the create chapters checkbox here since we are .mp4 */
  429. [fCreateChapterMarkers setEnabled: YES];
  430. if ([fDstFormatPopUp indexOfSelectedItem] == 0 && [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultChapterMarkers"] > 0)
  431. {
  432. [fCreateChapterMarkers setState: NSOnState];
  433. }
  434. [fDstFile2Field setStringValue: [NSString stringWithFormat:
  435. @"%@/Desktop/Movie.mp4", NSHomeDirectory()]];
  436. /* Video encoder */
  437. [fVidEncoderPopUp removeAllItems];
  438. [fVidEncoderPopUp addItemWithTitle: @"FFmpeg"];
  439. /* Video quality */
  440. [fVidTargetSizeField setIntValue: 700];
  441. [fVidBitrateField setIntValue: 1000];
  442. [fVidQualityMatrix selectCell: fVidBitrateCell];
  443. [self videoMatrixChanged:nil];
  444. /* Video framerate */
  445. [fVidRatePopUp removeAllItems];
  446. [fVidRatePopUp addItemWithTitle: NSLocalizedString( @"Same as source", @"" )];
  447. for( int i = 0; i < hb_video_rates_count; i++ )
  448. {
  449. if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.3f",23.976]])
  450. {
  451. [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
  452. [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Film)"]];
  453. }
  454. else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%d",25]])
  455. {
  456. [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
  457. [NSString stringWithUTF8String: hb_video_rates[i].string], @" (PAL Film/Video)"]];
  458. }
  459. else if ([[NSString stringWithUTF8String: hb_video_rates[i].string] isEqualToString: [NSString stringWithFormat: @"%.2f",29.97]])
  460. {
  461. [fVidRatePopUp addItemWithTitle:[NSString stringWithFormat: @"%@%@",
  462. [NSString stringWithUTF8String: hb_video_rates[i].string], @" (NTSC Video)"]];
  463. }
  464. else
  465. {
  466. [fVidRatePopUp addItemWithTitle:
  467. [NSString stringWithUTF8String: hb_video_rates[i].string]];
  468. }
  469. }
  470. [fVidRatePopUp selectItemAtIndex: 0];
  471. /* Set Auto Crop to On at launch */
  472. [fPictureController setAutoCrop:YES];
  473. /* Bottom */
  474. [fStatusField setStringValue: @""];
  475. [self enableUI: NO];
  476. [self setupToolbar];
  477. /* We disable the Turbo 1st pass checkbox since we are not x264 */
  478. [fVidTurboPassCheck setEnabled: NO];
  479. [fVidTurboPassCheck setState: NSOffState];
  480. /* lets get our default prefs here */
  481. [self getDefaultPresets:nil];
  482. /* lets initialize the current successful scancount here to 0 */
  483. currentSuccessfulScanCount = 0;
  484. }
  485. - (void) enableUI: (bool) b
  486. {
  487. NSControl * controls[] =
  488. { fSrcTitleField, fSrcTitlePopUp,
  489. fSrcChapterField, fSrcChapterStartPopUp, fSrcChapterToField,
  490. fSrcChapterEndPopUp, fSrcDuration1Field, fSrcDuration2Field,
  491. fDstFormatField, fDstFormatPopUp, fDstFile1Field, fDstFile2Field,
  492. fDstBrowseButton, fVidRateField, fVidRatePopUp,fVidEncoderField, fVidEncoderPopUp, fVidQualityField,
  493. fPictureSizeField,fPictureCroppingField, fVideoFiltersField,fVidQualityMatrix, fSubField, fSubPopUp,
  494. fQueueStatus,fPresetsAdd,fPresetsDelete,fSrcAngleLabel,fSrcAnglePopUp,
  495. fCreateChapterMarkers,fVidTurboPassCheck,fDstMp4LargeFileCheck,fSubForcedCheck,fPresetsOutlineView,
  496. fDstMp4HttpOptFileCheck,fDstMp4iPodFileCheck,fVidQualityRFField,fVidQualityRFLabel,
  497. fEncodeStartStopPopUp,fSrcTimeStartEncodingField,fSrcTimeEndEncodingField,fSrcFrameStartEncodingField,
  498. fSrcFrameEndEncodingField, fLoadChaptersButton, fSaveChaptersButton, fFrameratePfrCheck};
  499. for( unsigned i = 0;
  500. i < sizeof( controls ) / sizeof( NSControl * ); i++ )
  501. {
  502. if( [[controls[i] className] isEqualToString: @"NSTextField"] )
  503. {
  504. NSTextField * tf = (NSTextField *) controls[i];
  505. if( ![tf isBezeled] )
  506. {
  507. [tf setTextColor: b ? [NSColor controlTextColor] :
  508. [NSColor disabledControlTextColor]];
  509. continue;
  510. }
  511. }
  512. [controls[i] setEnabled: b];
  513. }
  514. if (b)
  515. {
  516. /* we also call calculatePictureSizing here to sense check if we already have vfr selected */
  517. [self calculatePictureSizing:nil];
  518. /* Also enable the preview window hud controls */
  519. [fPictureController enablePreviewHudControls];
  520. }
  521. else
  522. {
  523. [fPresetsOutlineView setEnabled: NO];
  524. [fPictureController disablePreviewHudControls];
  525. }
  526. [self videoMatrixChanged:nil];
  527. [fAdvancedOptions enableUI:b];
  528. }
  529. /***********************************************************************
  530. * UpdateDockIcon
  531. ***********************************************************************
  532. * Shows a progression bar on the dock icon, filled according to
  533. * 'progress' (0.0 <= progress <= 1.0).
  534. * Called with progress < 0.0 or progress > 1.0, restores the original
  535. * icon.
  536. **********************************************************************/
  537. - (void) UpdateDockIcon: (float) progress
  538. {
  539. NSData * tiff;
  540. NSBitmapImageRep * bmp;
  541. uint32_t * pen;
  542. uint32_t black = htonl( 0x000000FF );
  543. uint32_t red = htonl( 0xFF0000FF );
  544. uint32_t white = htonl( 0xFFFFFFFF );
  545. int row_start, row_end;
  546. int i, j;
  547. if( progress < 0.0 || progress > 1.0 )
  548. {
  549. [NSApp setApplicationIconImage: fApplicationIcon];
  550. return;
  551. }
  552. /* Get it in a raw bitmap form */
  553. tiff = [fApplicationIcon TIFFRepresentationUsingCompression:
  554. NSTIFFCompressionNone factor: 1.0];
  555. bmp = [NSBitmapImageRep imageRepWithData: tiff];
  556. /* Draw the progression bar */
  557. /* It's pretty simple (ugly?) now, but I'm no designer */
  558. row_start = 3 * (int) [bmp size].height / 4;
  559. row_end = 7 * (int) [bmp size].height / 8;
  560. for( i = row_start; i < row_start + 2; i++ )
  561. {
  562. pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
  563. for( j = 0; j < (int) [bmp size].width; j++ )
  564. {
  565. pen[j] = black;
  566. }
  567. }
  568. for( i = row_start + 2; i < row_end - 2; i++ )
  569. {
  570. pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
  571. pen[0] = black;
  572. pen[1] = black;
  573. for( j = 2; j < (int) [bmp size].width - 2; j++ )
  574. {
  575. if( j < 2 + (int) ( ( [bmp size].width - 4.0 ) * progress ) )
  576. {
  577. pen[j] = red;
  578. }
  579. else
  580. {
  581. pen[j] = white;
  582. }
  583. }
  584. pen[j] = black;
  585. pen[j+1] = black;
  586. }
  587. for( i = row_end - 2; i < row_end; i++ )
  588. {
  589. pen = (uint32_t *) ( [bmp bitmapData] + i * [bmp bytesPerRow] );
  590. for( j = 0; j < (int) [bmp size].width; j++ )
  591. {
  592. pen[j] = black;
  593. }
  594. }
  595. /* Now update the dock icon */
  596. tiff = [bmp TIFFRepresentationUsingCompression:
  597. NSTIFFCompressionNone factor: 1.0];
  598. NSImage* icon = [[NSImage alloc] initWithData: tiff];
  599. [NSApp setApplicationIconImage: icon];
  600. [icon release];
  601. }
  602. - (void) updateUI: (NSTimer *) timer
  603. {
  604. /* Update UI for fHandle (user scanning instance of libhb ) */
  605. hb_list_t * list;
  606. list = hb_get_titles( fHandle );
  607. /* check to see if there has been a new scan done
  608. this bypasses the constraints of HB_STATE_WORKING
  609. not allowing setting a newly scanned source */
  610. int checkScanCount = hb_get_scancount( fHandle );
  611. if( checkScanCount > currentScanCount )
  612. {
  613. currentScanCount = checkScanCount;
  614. [fScanIndicator setIndeterminate: NO];
  615. [fScanIndicator setDoubleValue: 0.0];
  616. [fScanIndicator setHidden: YES];
  617. [self showNewScan:nil];
  618. }
  619. hb_state_t s;
  620. hb_get_state( fHandle, &s );
  621. switch( s.state )
  622. {
  623. case HB_STATE_IDLE:
  624. break;
  625. #define p s.param.scanning
  626. case HB_STATE_SCANNING:
  627. {
  628. [fSrcDVD2Field setStringValue: [NSString stringWithFormat:
  629. NSLocalizedString( @"Scanning title %d of %d...", @"" ),
  630. p.title_cur, p.title_count]];
  631. [fScanIndicator setHidden: NO];
  632. [fScanIndicator setDoubleValue: 100.0 * ((double)( p.title_cur - 1 ) / p.title_count)];
  633. break;
  634. }
  635. #undef p
  636. #define p s.param.scandone
  637. case HB_STATE_SCANDONE:
  638. {
  639. [fScanIndicator setIndeterminate: NO];
  640. [fScanIndicator setDoubleValue: 0.0];
  641. [fScanIndicator setHidden: YES];
  642. [self writeToActivityLog:"ScanDone state received from fHandle"];
  643. [self showNewScan:nil];
  644. [[fWindow toolbar] validateVisibleItems];
  645. break;
  646. }
  647. #undef p
  648. #define p s.param.working
  649. case HB_STATE_WORKING:
  650. {
  651. break;
  652. }
  653. #undef p
  654. #define p s.param.muxing
  655. case HB_STATE_MUXING:
  656. {
  657. break;
  658. }
  659. #undef p
  660. case HB_STATE_PAUSED:
  661. break;
  662. case HB_STATE_WORKDONE:
  663. {
  664. break;
  665. }
  666. }
  667. /* Update UI for fQueueEncodeLibhb */
  668. // hb_list_t * list;
  669. // list = hb_get_titles( fQueueEncodeLibhb ); //fQueueEncodeLibhb
  670. /* check to see if there has been a new scan done
  671. this bypasses the constraints of HB_STATE_WORKING
  672. not allowing setting a newly scanned source */
  673. checkScanCount = hb_get_scancount( fQueueEncodeLibhb );
  674. if( checkScanCount > currentScanCount )
  675. {
  676. currentScanCount = checkScanCount;
  677. }
  678. //hb_state_t s;
  679. hb_get_state( fQueueEncodeLibhb, &s );
  680. switch( s.state )
  681. {
  682. case HB_STATE_IDLE:
  683. break;
  684. #define p s.param.scanning
  685. case HB_STATE_SCANNING:
  686. {
  687. [fStatusField setStringValue: [NSString stringWithFormat:
  688. NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
  689. p.title_cur, p.title_count]];
  690. /* Set the status string in fQueueController as well */
  691. [fQueueController setQueueStatusString: [NSString stringWithFormat:
  692. NSLocalizedString( @"Queue Scanning title %d of %d...", @"" ),
  693. p.title_cur, p.title_count]];
  694. break;
  695. }
  696. #undef p
  697. #define p s.param.scandone
  698. case HB_STATE_SCANDONE:
  699. {
  700. [self writeToActivityLog:"ScanDone state received from fQueueEncodeLibhb"];
  701. [self processNewQueueEncode];
  702. [[fWindow toolbar] validateVisibleItems];
  703. break;
  704. }
  705. #undef p
  706. #define p s.param.working
  707. case HB_STATE_SEARCHING:
  708. {
  709. NSMutableString * string;
  710. NSString * pass_desc;
  711. /* Update text field */
  712. pass_desc = @"";
  713. //string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point: pass %d %@ of %d, %.2f %%", @"" ), p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
  714. /* For now, do not announce "pass x of x for the search phase ... */
  715. string = [NSMutableString stringWithFormat: NSLocalizedString( @"Searching for start point ... : %.2f %%", @"" ), 100.0 * p.progress];
  716. if( p.seconds > -1 )
  717. {
  718. [string appendFormat:
  719. NSLocalizedString( @" (ETA %02dh%02dm%02ds)", @"" ), p.hours, p.minutes, p.seconds];
  720. }
  721. [fStatusField setStringValue: string];
  722. /* Set the status string in fQueueController as well */
  723. [fQueueController setQueueStatusString: string];
  724. /* Update slider */
  725. CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
  726. [fRipIndicator setIndeterminate: NO];
  727. [fRipIndicator setDoubleValue:100.0 * progress_total];
  728. // If progress bar hasn't been revealed at the bottom of the window, do
  729. // that now. This code used to be in doRip. I moved it to here to handle
  730. // the case where hb_start is called by HBQueueController and not from
  731. // HBController.
  732. if( !fRipIndicatorShown )
  733. {
  734. NSRect frame = [fWindow frame];
  735. if( frame.size.width <= 591 )
  736. frame.size.width = 591;
  737. frame.size.height += 36;
  738. frame.origin.y -= 36;
  739. [fWindow setFrame:frame display:YES animate:YES];
  740. fRipIndicatorShown = YES;
  741. }
  742. /* Update dock icon */
  743. /* Note not done yet */
  744. break;
  745. }
  746. case HB_STATE_WORKING:
  747. {
  748. NSMutableString * string;
  749. NSString * pass_desc;
  750. /* Update text field */
  751. if (p.job_cur == 1 && p.job_count > 1)
  752. {
  753. if ([[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SubtitleList"] && [[[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex]objectForKey:@"SubtitleList"] objectAtIndex:0] objectForKey:@"subtitleSourceTrackNum"] intValue] == 1)
  754. {
  755. pass_desc = @"(subtitle scan)";
  756. }
  757. else
  758. {
  759. pass_desc = @"";
  760. }
  761. }
  762. else
  763. {
  764. pass_desc = @"";
  765. }
  766. string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding: %@ \nPass %d %@ of %d, %.2f %%", @"" ), currentQueueEncodeNameString, p.job_cur, pass_desc, p.job_count, 100.0 * p.progress];
  767. if( p.seconds > -1 )
  768. {
  769. [string appendFormat:
  770. NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
  771. p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
  772. }
  773. [fStatusField setStringValue: string];
  774. [fQueueController setQueueStatusString:string];
  775. /* Update slider */
  776. CGFloat progress_total = ( p.progress + p.job_cur - 1 ) / p.job_count;
  777. [fRipIndicator setIndeterminate: NO];
  778. [fRipIndicator setDoubleValue:100.0 * progress_total];
  779. // If progress bar hasn't been revealed at the bottom of the window, do
  780. // that now. This code used to be in doRip. I moved it to here to handle
  781. // the case where hb_start is called by HBQueueController and not from
  782. // HBController.
  783. if( !fRipIndicatorShown )
  784. {
  785. NSRect frame = [fWindow frame];
  786. if( frame.size.width <= 591 )
  787. frame.size.width = 591;
  788. frame.size.height += 36;
  789. frame.origin.y -= 36;
  790. [fWindow setFrame:frame display:YES animate:YES];
  791. fRipIndicatorShown = YES;
  792. }
  793. /* Update dock icon */
  794. if( dockIconProgress < 100.0 * progress_total )
  795. {
  796. [self UpdateDockIcon: progress_total];
  797. dockIconProgress += 5;
  798. }
  799. break;
  800. }
  801. #undef p
  802. #define p s.param.muxing
  803. case HB_STATE_MUXING:
  804. {
  805. /* Update text field */
  806. [fStatusField setStringValue: NSLocalizedString( @"Muxing...", @"" )];
  807. /* Set the status string in fQueueController as well */
  808. [fQueueController setQueueStatusString: NSLocalizedString( @"Muxing...", @"" )];
  809. /* Update slider */
  810. [fRipIndicator setIndeterminate: YES];
  811. [fRipIndicator startAnimation: nil];
  812. /* Update dock icon */
  813. [self UpdateDockIcon: 1.0];
  814. break;
  815. }
  816. #undef p
  817. case HB_STATE_PAUSED:
  818. [fStatusField setStringValue: NSLocalizedString( @"Paused", @"" )];
  819. [fQueueController setQueueStatusString: NSLocalizedString( @"Paused", @"" )];
  820. break;
  821. case HB_STATE_WORKDONE:
  822. {
  823. // HB_STATE_WORKDONE happpens as a result of libhb finishing all its jobs
  824. // or someone calling hb_stop. In the latter case, hb_stop does not clear
  825. // out the remaining passes/jobs in the queue. We'll do that here.
  826. // Delete all remaining jobs of this encode.
  827. [fStatusField setStringValue: NSLocalizedString( @"Encode Finished.", @"" )];
  828. /* Set the status string in fQueueController as well */
  829. [fQueueController setQueueStatusString: NSLocalizedString( @"Encode Finished.", @"" )];
  830. [fRipIndicator setIndeterminate: NO];
  831. [fRipIndicator stopAnimation: nil];
  832. [fRipIndicator setDoubleValue: 0.0];
  833. [[fWindow toolbar] validateVisibleItems];
  834. /* Restore dock icon */
  835. [self UpdateDockIcon: -1.0];
  836. dockIconProgress = 0;
  837. if( fRipIndicatorShown )
  838. {
  839. NSRect frame = [fWindow frame];
  840. if( frame.size.width <= 591 )
  841. frame.size.width = 591;
  842. frame.size.height += -36;
  843. frame.origin.y -= -36;
  844. [fWindow setFrame:frame display:YES animate:YES];
  845. fRipIndicatorShown = NO;
  846. }
  847. /* Since we are done with this encode, tell output to stop writing to the
  848. * individual encode log
  849. */
  850. [outputPanel endEncodeLog];
  851. /* Check to see if the encode state has not been cancelled
  852. to determine if we should check for encode done notifications */
  853. if( fEncodeState != 2 )
  854. {
  855. NSString *pathOfFinishedEncode;
  856. /* Get the output file name for the finished encode */
  857. pathOfFinishedEncode = [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"];
  858. /* Both the Growl Alert and Sending to MetaX can be done as encodes roll off the queue */
  859. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Growl Notification"] ||
  860. [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"])
  861. {
  862. /* If Play System Alert has been selected in Preferences */
  863. if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
  864. {
  865. NSBeep();
  866. }
  867. [self showGrowlDoneNotification:pathOfFinishedEncode];
  868. }
  869. /* Send to MetaX */
  870. [self sendToMetaX:pathOfFinishedEncode];
  871. /* since we have successfully completed an encode, we increment the queue counter */
  872. [self incrementQueueItemDone:currentQueueEncodeIndex];
  873. }
  874. break;
  875. }
  876. }
  877. /* Since we can use multiple instance off of the same queue file it is imperative that we keep the QueueFileArray updated off of the QueueFile.plist
  878. * so we go ahead and do it in this existing timer as opposed to using a new one */
  879. NSMutableArray * tempQueueArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
  880. [QueueFileArray setArray:tempQueueArray];
  881. [tempQueueArray release];
  882. /* Send Fresh QueueFileArray to fQueueController to update queue window */
  883. [fQueueController setQueueArray: QueueFileArray];
  884. [self getQueueStats];
  885. }
  886. /* We use this to write messages to stderr from the macgui which show up in the activity window and log*/
  887. - (void) writeToActivityLog:(const char *) format, ...
  888. {
  889. va_list args;
  890. va_start(args, format);
  891. if (format != nil)
  892. {
  893. char str[1024];
  894. vsnprintf( str, 1024, format, args );
  895. time_t _now = time( NULL );
  896. struct tm * now = localtime( &_now );
  897. fprintf(stderr, "[%02d:%02d:%02d] macgui: %s\n", now->tm_hour, now->tm_min, now->tm_sec, str );
  898. }
  899. va_end(args);
  900. }
  901. #pragma mark -
  902. #pragma mark Toolbar
  903. // ============================================================
  904. // NSToolbar Related Methods
  905. // ============================================================
  906. - (void) setupToolbar {
  907. NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: @"HandBrake Toolbar"] autorelease];
  908. [toolbar setAllowsUserCustomization: YES];
  909. [toolbar setAutosavesConfiguration: YES];
  910. [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];
  911. [toolbar setDelegate: self];
  912. [fWindow setToolbar: toolbar];
  913. }
  914. - (NSToolbarItem *) toolbar: (NSToolbar *)toolbar itemForItemIdentifier:
  915. (NSString *) itemIdent willBeInsertedIntoToolbar:(BOOL) willBeInserted {
  916. NSToolbarItem * item = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease];
  917. if ([itemIdent isEqualToString: ToggleDrawerIdentifier])
  918. {
  919. [item setLabel: @"Toggle Presets"];
  920. [item setPaletteLabel: @"Toggler Presets"];
  921. [item setToolTip: @"Open/Close Preset Drawer"];
  922. [item setImage: [NSImage imageNamed: @"Drawer"]];
  923. [item setTarget: self];
  924. [item setAction: @selector(toggleDrawer:)];
  925. [item setAutovalidates: NO];
  926. }
  927. else if ([itemIdent isEqualToString: StartEncodingIdentifier])
  928. {
  929. [item setLabel: @"Start"];
  930. [item setPaletteLabel: @"Start Encoding"];
  931. [item setToolTip: @"Start Encoding"];
  932. [item setImage: [NSImage imageNamed: @"Play"]];
  933. [item setTarget: self];
  934. [item setAction: @selector(Rip:)];
  935. }
  936. else if ([itemIdent isEqualToString: ShowQueueIdentifier])
  937. {
  938. [item setLabel: @"Show Queue"];
  939. [item setPaletteLabel: @"Show Queue"];
  940. [item setToolTip: @"Show Queue"];
  941. [item setImage: [NSImage imageNamed: @"Queue"]];
  942. [item setTarget: self];
  943. [item setAction: @selector(showQueueWindow:)];
  944. [item setAutovalidates: NO];
  945. }
  946. else if ([itemIdent isEqualToString: AddToQueueIdentifier])
  947. {
  948. [item setLabel: @"Add to Queue"];
  949. [item setPaletteLabel: @"Add to Queue"];
  950. [item setToolTip: @"Add to Queue"];
  951. [item setImage: [NSImage imageNamed: @"AddToQueue"]];
  952. [item setTarget: self];
  953. [item setAction: @selector(addToQueue:)];
  954. }
  955. else if ([itemIdent isEqualToString: PauseEncodingIdentifier])
  956. {
  957. [item setLabel: @"Pause"];
  958. [item setPaletteLabel: @"Pause Encoding"];
  959. [item setToolTip: @"Pause Encoding"];
  960. [item setImage: [NSImage imageNamed: @"Pause"]];
  961. [item setTarget: self];
  962. [item setAction: @selector(Pause:)];
  963. }
  964. else if ([itemIdent isEqualToString: ShowPictureIdentifier])
  965. {
  966. [item setLabel: @"Picture Settings"];
  967. [item setPaletteLabel: @"Show Picture Settings"];
  968. [item setToolTip: @"Show Picture Settings"];
  969. [item setImage: [NSImage imageNamed: @"pref-picture"]];
  970. [item setTarget: self];
  971. [item setAction: @selector(showPicturePanel:)];
  972. }
  973. else if ([itemIdent isEqualToString: ShowPreviewIdentifier])
  974. {
  975. [item setLabel: @"Preview Window"];
  976. [item setPaletteLabel: @"Show Preview"];
  977. [item setToolTip: @"Show Preview"];
  978. //[item setImage: [NSImage imageNamed: @"pref-picture"]];
  979. [item setImage: [NSImage imageNamed: @"Brushed_Window"]];
  980. [item setTarget: self];
  981. [item setAction: @selector(showPreviewWindow:)];
  982. }
  983. else if ([itemIdent isEqualToString: ShowActivityIdentifier])
  984. {
  985. [item setLabel: @"Activity Window"];
  986. [item setPaletteLabel: @"Show Activity Window"];
  987. [item setToolTip: @"Show Activity Window"];
  988. [item setImage: [NSImage imageNamed: @"ActivityWindow"]];
  989. [item setTarget: self];
  990. [item setAction: @selector(showDebugOutputPanel:)];
  991. [item setAutovalidates: NO];
  992. }
  993. else if ([itemIdent isEqualToString: ChooseSourceIdentifier])
  994. {
  995. [item setLabel: @"Source"];
  996. [item setPaletteLabel: @"Source"];
  997. [item setToolTip: @"Choose Video Source"];
  998. [item setImage: [NSImage imageNamed: @"Source"]];
  999. [item setTarget: self];
  1000. [item setAction: @selector(browseSources:)];
  1001. }
  1002. else
  1003. {
  1004. return nil;
  1005. }
  1006. return item;
  1007. }
  1008. - (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar
  1009. {
  1010. return [NSArray arrayWithObjects: ChooseSourceIdentifier, NSToolbarSeparatorItemIdentifier, StartEncodingIdentifier,
  1011. PauseEncodingIdentifier, AddToQueueIdentifier, ShowQueueIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
  1012. NSToolbarSpaceItemIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier, nil];
  1013. }
  1014. - (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar
  1015. {
  1016. return [NSArray arrayWithObjects: StartEncodingIdentifier, PauseEncodingIdentifier, AddToQueueIdentifier,
  1017. ChooseSourceIdentifier, ShowQueueIdentifier, ShowPictureIdentifier, ShowPreviewIdentifier, ShowActivityIdentifier, ToggleDrawerIdentifier,
  1018. NSToolbarCustomizeToolbarItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier,
  1019. NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, nil];
  1020. }
  1021. - (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
  1022. {
  1023. NSString * ident = [toolbarItem itemIdentifier];
  1024. if (fHandle)
  1025. {
  1026. hb_state_t s;
  1027. hb_get_state( fHandle, &s );
  1028. if (s.state == HB_STATE_SCANNING)
  1029. {
  1030. if ([ident isEqualToString: ChooseSourceIdentifier])
  1031. {
  1032. [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
  1033. [toolbarItem setLabel: @"Cancel Scan"];
  1034. [toolbarItem setPaletteLabel: @"Cancel Scanning"];
  1035. [toolbarItem setToolTip: @"Cancel Scanning Source"];
  1036. return YES;
  1037. }
  1038. if ([ident isEqualToString: StartEncodingIdentifier] || [ident isEqualToString: AddToQueueIdentifier])
  1039. return NO;
  1040. }
  1041. else
  1042. {
  1043. if ([ident isEqualToString: ChooseSourceIdentifier])
  1044. {
  1045. [toolbarItem setImage: [NSImage imageNamed: @"Source"]];
  1046. [toolbarItem setLabel: @"Source"];
  1047. [toolbarItem setPaletteLabel: @"Source"];
  1048. [toolbarItem setToolTip: @"Choose Video Source"];
  1049. return YES;
  1050. }
  1051. }
  1052. hb_get_state2( fQueueEncodeLibhb, &s );
  1053. if (s.state == HB_STATE_WORKING || s.state == HB_STATE_SEARCHING || s.state == HB_STATE_MUXING)
  1054. {
  1055. if ([ident isEqualToString: StartEncodingIdentifier])
  1056. {
  1057. [toolbarItem setImage: [NSImage imageNamed: @"Stop"]];
  1058. [toolbarItem setLabel: @"Stop"];
  1059. [toolbarItem setPaletteLabel: @"Stop"];
  1060. [toolbarItem setToolTip: @"Stop Encoding"];
  1061. return YES;
  1062. }
  1063. if ([ident isEqualToString: PauseEncodingIdentifier])
  1064. {
  1065. [toolbarItem setImage: [NSImage imageNamed: @"Pause"]];
  1066. [toolbarItem setLabel: @"Pause"];
  1067. [toolbarItem setPaletteLabel: @"Pause Encoding"];
  1068. [toolbarItem setToolTip: @"Pause Encoding"];
  1069. return YES;
  1070. }
  1071. if (SuccessfulScan)
  1072. {
  1073. if ([ident isEqualToString: AddToQueueIdentifier])
  1074. return YES;
  1075. if ([ident isEqualToString: ShowPictureIdentifier])
  1076. return YES;
  1077. if ([ident isEqualToString: ShowPreviewIdentifier])
  1078. return YES;
  1079. }
  1080. }
  1081. else if (s.state == HB_STATE_PAUSED)
  1082. {
  1083. if ([ident isEqualToString: PauseEncodingIdentifier])
  1084. {
  1085. [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
  1086. [toolbarItem setLabel: @"Resume"];
  1087. [toolbarItem setPaletteLabel: @"Resume Encoding"];
  1088. [toolbarItem setToolTip: @"Resume Encoding"];
  1089. return YES;
  1090. }
  1091. if ([ident isEqualToString: StartEncodingIdentifier])
  1092. return YES;
  1093. if ([ident isEqualToString: AddToQueueIdentifier])
  1094. return YES;
  1095. if ([ident isEqualToString: ShowPictureIdentifier])
  1096. return YES;
  1097. if ([ident isEqualToString: ShowPreviewIdentifier])
  1098. return YES;
  1099. }
  1100. else if (s.state == HB_STATE_SCANNING)
  1101. return NO;
  1102. else if (s.state == HB_STATE_WORKDONE || s.state == HB_STATE_SCANDONE || SuccessfulScan)
  1103. {
  1104. if ([ident isEqualToString: StartEncodingIdentifier])
  1105. {
  1106. [toolbarItem setImage: [NSImage imageNamed: @"Play"]];
  1107. if (hb_count(fHandle) > 0)
  1108. [toolbarItem setLabel: @"Start Queue"];
  1109. else
  1110. [toolbarItem setLabel: @"Start"];
  1111. [toolbarItem setPaletteLabel: @"Start Encoding"];
  1112. [toolbarItem setToolTip: @"Start Encoding"];
  1113. return YES;
  1114. }
  1115. if ([ident isEqualToString: AddToQueueIdentifier])
  1116. return YES;
  1117. if ([ident isEqualToString: ShowPictureIdentifier])
  1118. return YES;
  1119. if ([ident isEqualToString: ShowPreviewIdentifier])
  1120. return YES;
  1121. }
  1122. }
  1123. /* If there are any pending queue items, make sure the start/stop button is active */
  1124. if ([ident isEqualToString: StartEncodingIdentifier] && fPendingCount > 0)
  1125. return YES;
  1126. if ([ident isEqualToString: ShowQueueIdentifier])
  1127. return YES;
  1128. if ([ident isEqualToString: ToggleDrawerIdentifier])
  1129. return YES;
  1130. if ([ident isEqualToString: ChooseSourceIdentifier])
  1131. return YES;
  1132. if ([ident isEqualToString: ShowActivityIdentifier])
  1133. return YES;
  1134. return NO;
  1135. }
  1136. - (BOOL) validateMenuItem: (NSMenuItem *) menuItem
  1137. {
  1138. SEL action = [menuItem action];
  1139. hb_state_t s;
  1140. hb_get_state2( fHandle, &s );
  1141. if (fHandle)
  1142. {
  1143. if (action == @selector(addToQueue:) || action == @selector(showPicturePanel:) || action == @selector(showAddPresetPanel:))
  1144. return SuccessfulScan && [fWindow attachedSheet] == nil;
  1145. if (action == @selector(browseSources:))
  1146. {
  1147. if (s.state == HB_STATE_SCANNING)
  1148. return NO;
  1149. else
  1150. return [fWindow attachedSheet] == nil;
  1151. }
  1152. if (action == @selector(selectDefaultPreset:))
  1153. return [fPresetsOutlineView selectedRow] >= 0 && [fWindow attachedSheet] == nil;
  1154. if (action == @selector(Pause:))
  1155. {
  1156. if (s.state == HB_STATE_WORKING)
  1157. {
  1158. if(![[menuItem title] isEqualToString:@"Pause Encoding"])
  1159. [menuItem setTitle:@"Pause Encoding"];
  1160. return YES;
  1161. }
  1162. else if (s.state == HB_STATE_PAUSED)
  1163. {
  1164. if(![[menuItem title] isEqualToString:@"Resume Encoding"])
  1165. [menuItem setTitle:@"Resume Encoding"];
  1166. return YES;
  1167. }
  1168. else
  1169. return NO;
  1170. }
  1171. if (action == @selector(Rip:))
  1172. {
  1173. if (s.state == HB_STATE_WORKING || s.state == HB_STATE_MUXING || s.state == HB_STATE_PAUSED)
  1174. {
  1175. if(![[menuItem title] isEqualToString:@"Stop Encoding"])
  1176. [menuItem setTitle:@"Stop Encoding"];
  1177. return YES;
  1178. }
  1179. else if (SuccessfulScan)
  1180. {
  1181. if(![[menuItem title] isEqualToString:@"Start Encoding"])
  1182. [menuItem setTitle:@"Start Encoding"];
  1183. return [fWindow attachedSheet] == nil;
  1184. }
  1185. else
  1186. return NO;
  1187. }
  1188. }
  1189. if( action == @selector(setDefaultPreset:) )
  1190. {
  1191. return [fPresetsOutlineView selectedRow] != -1;
  1192. }
  1193. return YES;
  1194. }
  1195. #pragma mark -
  1196. #pragma mark Encode Done Actions
  1197. // register a test notification and make
  1198. // it enabled by default
  1199. #define SERVICE_NAME @"Encode Done"
  1200. - (NSDictionary *)registrationDictionaryForGrowl
  1201. {
  1202. NSDictionary *registrationDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
  1203. [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_ALL,
  1204. [NSArray arrayWithObjects:SERVICE_NAME,nil], GROWL_NOTIFICATIONS_DEFAULT,
  1205. nil];
  1206. return registrationDictionary;
  1207. }
  1208. -(void)showGrowlDoneNotification:(NSString *) filePath
  1209. {
  1210. /* This end of encode action is called as each encode rolls off of the queue */
  1211. /* Setup the Growl stuff ... */
  1212. NSString * finishedEncode = filePath;
  1213. /* strip off the path to just show the file name */
  1214. finishedEncode = [finishedEncode lastPathComponent];
  1215. NSString * growlMssg = [NSString stringWithFormat: @"your HandBrake encode %@ is done!",finishedEncode];
  1216. [GrowlApplicationBridge
  1217. notifyWithTitle:@"Put down that cocktail..."
  1218. description:growlMssg
  1219. notificationName:SERVICE_NAME
  1220. iconData:nil
  1221. priority:0
  1222. isSticky:1
  1223. clickContext:nil];
  1224. }
  1225. -(void)sendToMetaX:(NSString *) filePath
  1226. {
  1227. /* This end of encode action is called as each encode rolls off of the queue */
  1228. if([[NSUserDefaults standardUserDefaults] boolForKey: @"sendToMetaX"] == YES)
  1229. {
  1230. NSString *sendToApp = [[NSUserDefaults standardUserDefaults] objectForKey: @"SendCompletedEncodeToApp"];
  1231. if (![sendToApp isEqualToString:@"None"])
  1232. {
  1233. [self writeToActivityLog: "trying to send encode to: %s", [sendToApp UTF8String]];
  1234. NSAppleScript *myScript = [[NSAppleScript alloc] initWithSource: [NSString stringWithFormat: @"%@%@%@%@%@", @"tell application \"",sendToApp,@"\" to open (POSIX file \"", filePath, @"\")"]];
  1235. [myScript executeAndReturnError: nil];
  1236. [myScript release];
  1237. }
  1238. }
  1239. }
  1240. - (void) queueCompletedAlerts
  1241. {
  1242. /* If Play System Alert has been selected in Preferences */
  1243. if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertWhenDoneSound"] == YES )
  1244. {
  1245. NSBeep();
  1246. }
  1247. /* If Alert Window or Window and Growl has been selected */
  1248. if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window"] ||
  1249. [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Alert Window And Growl"] )
  1250. {
  1251. /*On Screen Notification*/
  1252. int status;
  1253. status = NSRunAlertPanel(@"Put down that cocktail...",@"Your HandBrake queue is done!", @"OK", nil, nil);
  1254. [NSApp requestUserAttention:NSCriticalRequest];
  1255. }
  1256. /* If sleep has been selected */
  1257. if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"] )
  1258. {
  1259. /* Sleep */
  1260. NSDictionary* errorDict;
  1261. NSAppleEventDescriptor* returnDescriptor = nil;
  1262. NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
  1263. @"tell application \"Finder\" to sleep"];
  1264. returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
  1265. [scriptObject release];
  1266. }
  1267. /* If Shutdown has been selected */
  1268. if( [[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"] )
  1269. {
  1270. /* Shut Down */
  1271. NSDictionary* errorDict;
  1272. NSAppleEventDescriptor* returnDescriptor = nil;
  1273. NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
  1274. @"tell application \"Finder\" to shut down"];
  1275. returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
  1276. [scriptObject release];
  1277. }
  1278. }
  1279. #pragma mark -
  1280. #pragma mark Get New Source
  1281. /*Opens the source browse window, called from Open Source widgets */
  1282. - (IBAction) browseSources: (id) sender
  1283. {
  1284. hb_state_t s;
  1285. hb_get_state( fHandle, &s );
  1286. if (s.state == HB_STATE_SCANNING)
  1287. {
  1288. [self cancelScanning:nil];
  1289. return;
  1290. }
  1291. NSOpenPanel * panel;
  1292. panel = [NSOpenPanel openPanel];
  1293. [panel setAllowsMultipleSelection: NO];
  1294. [panel setCanChooseFiles: YES];
  1295. [panel setCanChooseDirectories: YES ];
  1296. NSString * sourceDirectory;
  1297. if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"])
  1298. {
  1299. sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSourceDirectory"];
  1300. }
  1301. else
  1302. {
  1303. sourceDirectory = @"~/Desktop";
  1304. sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
  1305. }
  1306. /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
  1307. * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
  1308. */
  1309. [panel beginSheetForDirectory: sourceDirectory file: nil types: nil
  1310. modalForWindow: fWindow modalDelegate: self
  1311. didEndSelector: @selector( browseSourcesDone:returnCode:contextInfo: )
  1312. contextInfo: sender];
  1313. }
  1314. - (void) browseSourcesDone: (NSOpenPanel *) sheet
  1315. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  1316. {
  1317. /* we convert the sender content of contextInfo back into a variable called sender
  1318. * mostly just for consistency for evaluation later
  1319. */
  1320. id sender = (id)contextInfo;
  1321. /* User selected a file to open */
  1322. if( returnCode == NSOKButton )
  1323. {
  1324. /* Free display name allocated previously by this code */
  1325. [browsedSourceDisplayName release];
  1326. NSString *scanPath = [[sheet filenames] objectAtIndex: 0];
  1327. /* we set the last searched source directory in the prefs here */
  1328. NSString *sourceDirectory = [scanPath stringByDeletingLastPathComponent];
  1329. [[NSUserDefaults standardUserDefaults] setObject:sourceDirectory forKey:@"LastSourceDirectory"];
  1330. /* we order out sheet, which is the browse window as we need to open
  1331. * the title selection sheet right away
  1332. */
  1333. [sheet orderOut: self];
  1334. if (sender == fOpenSourceTitleMMenu || [[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
  1335. {
  1336. /* We put the chosen source path in the source display text field for the
  1337. * source title selection sheet in which the user specifies the specific title to be
  1338. * scanned as well as the short source name in fSrcDsplyNameTitleScan just for display
  1339. * purposes in the title panel
  1340. */
  1341. /* Full Path */
  1342. [fScanSrcTitlePathField setStringValue:scanPath];
  1343. NSString *displayTitlescanSourceName;
  1344. if ([[scanPath lastPathComponent] isEqualToString: @"VIDEO_TS"])
  1345. {
  1346. /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name
  1347. we have to use the title->path value so we get the proper name of the volume if a physical dvd is the source*/
  1348. displayTitlescanSourceName = [[scanPath stringByDeletingLastPathComponent] lastPathComponent];
  1349. }
  1350. else
  1351. {
  1352. /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
  1353. displayTitlescanSourceName = [scanPath lastPathComponent];
  1354. }
  1355. /* we set the source display name in the title selection dialogue */
  1356. [fSrcDsplyNameTitleScan setStringValue:displayTitlescanSourceName];
  1357. /* we set the attempted scans display name for main window to displayTitlescanSourceName*/
  1358. browsedSourceDisplayName = [displayTitlescanSourceName retain];
  1359. /* We show the actual sheet where the user specifies the title to be scanned
  1360. * as we are going to do a title specific scan
  1361. */
  1362. [self showSourceTitleScanPanel:nil];
  1363. }
  1364. else
  1365. {
  1366. /* We are just doing a standard full source scan, so we specify "0" to libhb */
  1367. NSString *path = [[sheet filenames] objectAtIndex: 0];
  1368. /* We check to see if the chosen file at path is a package */
  1369. if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:path])
  1370. {
  1371. [self writeToActivityLog: "trying to open a package at: %s", [path UTF8String]];
  1372. /* We check to see if this is an .eyetv package */
  1373. if ([[path pathExtension] isEqualToString: @"eyetv"])
  1374. {
  1375. [self writeToActivityLog:"trying to open eyetv package"];
  1376. /* We're looking at an EyeTV package - try to open its enclosed
  1377. .mpg media file */
  1378. browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
  1379. NSString *mpgname;
  1380. int n = [[path stringByAppendingString: @"/"]
  1381. completePathIntoString: &mpgname caseSensitive: YES
  1382. matchesIntoArray: nil
  1383. filterTypes: [NSArray arrayWithObject: @"mpg"]];
  1384. if (n > 0)
  1385. {
  1386. /* Found an mpeg inside the eyetv package, make it our scan path
  1387. and call performScan on the enclosed mpeg */
  1388. path = mpgname;
  1389. [self writeToActivityLog:"found mpeg in eyetv package"];
  1390. [self performScan:path scanTitleNum:0];
  1391. }
  1392. else
  1393. {
  1394. /* We did not find an mpeg file in our package, so we do not call performScan */
  1395. [self writeToActivityLog:"no valid mpeg in eyetv package"];
  1396. }
  1397. }
  1398. /* We check to see if this is a .dvdmedia package */
  1399. else if ([[path pathExtension] isEqualToString: @"dvdmedia"])
  1400. {
  1401. /* path IS a package - but dvdmedia packages can be treaded like normal directories */
  1402. browsedSourceDisplayName = [[[path stringByDeletingPathExtension] lastPathComponent] retain];
  1403. [self writeToActivityLog:"trying to open dvdmedia package"];
  1404. [self performScan:path scanTitleNum:0];
  1405. }
  1406. else
  1407. {
  1408. /* The package is not an eyetv package, so we do not call performScan */
  1409. [self writeToActivityLog:"unable to open package"];
  1410. }
  1411. }
  1412. else // path is not a package, so we treat it as a dvd parent folder or VIDEO_TS folder
  1413. {
  1414. /* path is not a package, so we call perform scan directly on our file */
  1415. if ([[path lastPathComponent] isEqualToString: @"VIDEO_TS"])
  1416. {
  1417. [self writeToActivityLog:"trying to open video_ts folder (video_ts folder chosen)"];
  1418. /* If VIDEO_TS Folder is chosen, choose its parent folder for the source display name*/
  1419. browsedSourceDisplayName = [[[path stringByDeletingLastPathComponent] lastPathComponent] retain];
  1420. }
  1421. else
  1422. {
  1423. [self writeToActivityLog:"trying to open video_ts folder (parent directory chosen)"];
  1424. /* if not the VIDEO_TS Folder, we can assume the chosen folder is the source name */
  1425. /* make sure we remove any path extension as this can also be an '.mpg' file */
  1426. browsedSourceDisplayName = [[path lastPathComponent] retain];
  1427. }
  1428. applyQueueToScan = NO;
  1429. [self performScan:path scanTitleNum:0];
  1430. }
  1431. }
  1432. }
  1433. }
  1434. - (IBAction)showAboutPanel:(id)sender
  1435. {
  1436. NSMutableDictionary* d = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
  1437. fApplicationIcon, @"ApplicationIcon",
  1438. nil ];
  1439. [NSApp orderFrontStandardAboutPanelWithOptions:d];
  1440. [d release];
  1441. }
  1442. /* Here we open the title selection sheet where we can specify an exact title to be scanned */
  1443. - (IBAction) showSourceTitleScanPanel: (id) sender
  1444. {
  1445. /* We default the title number to be scanned to "0" which results in a full source scan, unless the
  1446. * user changes it
  1447. */
  1448. [fScanSrcTitleNumField setStringValue: @"0"];
  1449. /* Show the panel */
  1450. [NSApp beginSheet:fScanSrcTitlePanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
  1451. }
  1452. - (IBAction) closeSourceTitleScanPanel: (id) sender
  1453. {
  1454. [NSApp endSheet: fScanSrcTitlePanel];
  1455. [fScanSrcTitlePanel orderOut: self];
  1456. if(sender == fScanSrcTitleOpenButton)
  1457. {
  1458. /* We setup the scan status in the main window to indicate a source title scan */
  1459. [fSrcDVD2Field setStringValue: @"Opening a new source title ..."];
  1460. [fScanIndicator setHidden: NO];
  1461. [fScanIndicator setIndeterminate: YES];
  1462. [fScanIndicator startAnimation: nil];
  1463. /* We use the performScan method to actually perform the specified scan passing the path and the title
  1464. * to be scanned
  1465. */
  1466. applyQueueToScan = NO;
  1467. [self performScan:[fScanSrcTitlePathField stringValue] scanTitleNum:[fScanSrcTitleNumField intValue]];
  1468. }
  1469. }
  1470. /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
  1471. - (void) performScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
  1472. {
  1473. /* use a bool to determine whether or not we can decrypt using vlc */
  1474. BOOL cancelScanDecrypt = 0;
  1475. BOOL vlcFound = 0;
  1476. NSString *path = scanPath;
  1477. HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
  1478. // Notify ChapterTitles that there's no title
  1479. [fChapterTitlesDelegate resetWithTitle:nil];
  1480. [fChapterTable reloadData];
  1481. // Notify Subtitles that there's no title
  1482. [fSubtitlesDelegate resetWithTitle:nil];
  1483. [fSubtitlesTable reloadData];
  1484. // Notify anyone interested (audio controller) that there's no title
  1485. [[NSNotificationCenter defaultCenter] postNotification:
  1486. [NSNotification notificationWithName: HBTitleChangedNotification
  1487. object: self
  1488. userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
  1489. [NSData dataWithBytesNoCopy: &fTitle length: sizeof(fTitle) freeWhenDone: NO], keyTitleTag,
  1490. nil]]];
  1491. [self enableUI: NO];
  1492. if( [detector isVideoDVD] )
  1493. {
  1494. // The chosen path was actually on a DVD, so use the raw block
  1495. // device path instead.
  1496. path = [detector devicePath];
  1497. [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
  1498. /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
  1499. void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
  1500. if (dvdcss == NULL)
  1501. {
  1502. /*compatible vlc not found, so we set the bool to cancel scanning to 1 */
  1503. cancelScanDecrypt = 1;
  1504. [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
  1505. int status;
  1506. status = NSRunAlertPanel(@"HandBrake could not find VLC or your VLC is incompatible (Note: 32 bit vlc is not compatible with 64 bit HandBrake and vice-versa).",@"Please download and install VLC media player if you wish to read encrypted DVDs.", @"Get VLC", @"Cancel Scan", @"Attempt Scan Anyway");
  1507. [NSApp requestUserAttention:NSCriticalRequest];
  1508. if (status == NSAlertDefaultReturn)
  1509. {
  1510. /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
  1511. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/vlc/download-macosx.html"]];
  1512. }
  1513. else if (status == NSAlertAlternateReturn)
  1514. {
  1515. /* User chose to cancel the scan */
  1516. [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
  1517. }
  1518. else
  1519. {
  1520. /* 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 */
  1521. cancelScanDecrypt = 0;
  1522. [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
  1523. }
  1524. }
  1525. else
  1526. {
  1527. /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
  1528. [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
  1529. vlcFound = 1;
  1530. dlclose(dvdcss);
  1531. }
  1532. }
  1533. if (cancelScanDecrypt == 0)
  1534. {
  1535. /* we actually pass the scan off to libhb here */
  1536. /* If there is no title number passed to scan, we use "0"
  1537. * which causes the default behavior of a full source scan
  1538. */
  1539. if (!scanTitleNum)
  1540. {
  1541. scanTitleNum = 0;
  1542. }
  1543. if (scanTitleNum > 0)
  1544. {
  1545. [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
  1546. }
  1547. /* We use our advanced pref to determine how many previews to scan */
  1548. int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
  1549. /* We use our advanced pref to determine the minimum title length to use in seconds*/
  1550. uint64_t min_title_duration_seconds = 90000L * [[[NSUserDefaults standardUserDefaults] objectForKey:@"MinTitleScanSeconds"] intValue];
  1551. /* set title to NULL */
  1552. fTitle = NULL;
  1553. [self writeToActivityLog: "Minimum length of title for scan: %d", min_title_duration_seconds];
  1554. hb_scan( fHandle, [path UTF8String], scanTitleNum, hb_num_previews, 1 , min_title_duration_seconds );
  1555. [fSrcDVD2Field setStringValue:@"Scanning new source ..."];
  1556. }
  1557. }
  1558. - (IBAction) cancelScanning:(id)sender
  1559. {
  1560. hb_scan_stop(fHandle);
  1561. }
  1562. - (IBAction) showNewScan:(id)sender
  1563. {
  1564. hb_list_t * list;
  1565. hb_title_t * title = NULL;
  1566. int feature_title=0; // Used to store the main feature title
  1567. list = hb_get_titles( fHandle );
  1568. if( !hb_list_count( list ) )
  1569. {
  1570. /* We display a message if a valid dvd source was not chosen */
  1571. [fSrcDVD2Field setStringValue: @"No Valid Source Found"];
  1572. SuccessfulScan = NO;
  1573. // Notify ChapterTitles that there's no title
  1574. [fSubtitlesDelegate resetWithTitle:nil];
  1575. [fSubtitlesTable reloadData];
  1576. // Notify Subtitles that there's no title
  1577. [fChapterTitlesDelegate resetWithTitle:nil];
  1578. [fChapterTable reloadData];
  1579. // Notify anyone interested (audio controller) that there's no title
  1580. [[NSNotificationCenter defaultCenter] postNotification:
  1581. [NSNotification notificationWithName: HBTitleChangedNotification
  1582. object: self
  1583. userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
  1584. [NSData dataWithBytesNoCopy: &fTitle length: sizeof(fTitle) freeWhenDone: NO], keyTitleTag,
  1585. nil]]];
  1586. }
  1587. else
  1588. {
  1589. if (applyQueueToScan == YES)
  1590. {
  1591. /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
  1592. [self writeToActivityLog: "showNewScan: This is a queued item rescan"];
  1593. }
  1594. else if (applyQueueToScan == NO)
  1595. {
  1596. [self writeToActivityLog: "showNewScan: This is a new source item scan"];
  1597. }
  1598. else
  1599. {
  1600. [self writeToActivityLog: "showNewScan: cannot grok scan status"];
  1601. }
  1602. /* We increment the successful scancount here by one,
  1603. which we use at the end of this function to tell the gui
  1604. if this is the first successful scan since launch and whether
  1605. or not we should set all settings to the defaults */
  1606. currentSuccessfulScanCount++;
  1607. [[fWindow toolbar] validateVisibleItems];
  1608. [fSrcTitlePopUp removeAllItems];
  1609. for( int i = 0; i < hb_list_count( list ); i++ )
  1610. {
  1611. title = (hb_title_t *) hb_list_item( list, i );
  1612. currentSource = [NSString stringWithUTF8String: title->name];
  1613. /*Set DVD Name at top of window with the browsedSourceDisplayName grokked right before -performScan */
  1614. if (!browsedSourceDisplayName)
  1615. {
  1616. browsedSourceDisplayName = @"NoNameDetected";
  1617. }
  1618. [fSrcDVD2Field setStringValue:browsedSourceDisplayName];
  1619. // use the correct extension based on the container
  1620. int format = [fDstFormatPopUp indexOfSelectedItem];
  1621. char *ext = "mp4";
  1622. if (format == 1)
  1623. {
  1624. ext = "mkv";
  1625. }
  1626. /* If its a queue rescan for edit, get the queue item output path */
  1627. /* if not, its a new source scan. */
  1628. /* Check to see if the last destination has been set,use if so, if not, use Desktop */
  1629. if (applyQueueToScan == YES)
  1630. {
  1631. [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@", [[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"DestinationPath"]]];
  1632. }
  1633. else if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"])
  1634. {
  1635. [fDstFile2Field setStringValue: [NSString stringWithFormat:
  1636. @"%@/%@.%s", [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"],[browsedSourceDisplayName stringByDeletingPathExtension],ext]];
  1637. }
  1638. else
  1639. {
  1640. [fDstFile2Field setStringValue: [NSString stringWithFormat:
  1641. @"%@/Desktop/%@.%s", NSHomeDirectory(),[browsedSourceDisplayName stringByDeletingPathExtension],ext]];
  1642. }
  1643. // set m4v extension if necessary - do not override user-specified .mp4 extension
  1644. if (format == 0 && applyQueueToScan != YES)
  1645. {
  1646. [self autoSetM4vExtension: sender];
  1647. }
  1648. /* See if this is the main feature according to libhb */
  1649. if (title->index == title->job->feature)
  1650. {
  1651. feature_title = i;
  1652. }
  1653. [fSrcTitlePopUp addItemWithTitle: [NSString
  1654. stringWithFormat: @"%@ %d - %02dh%02dm%02ds",
  1655. currentSource, title->index, title->hours, title->minutes,
  1656. title->seconds]];
  1657. }
  1658. /* if we are a stream, select the first title */
  1659. if (title->type == HB_STREAM_TYPE)
  1660. {
  1661. [fSrcTitlePopUp selectItemAtIndex: 0];
  1662. }
  1663. else
  1664. {
  1665. /* if not then select the main feature title */
  1666. [fSrcTitlePopUp selectItemAtIndex: feature_title];
  1667. }
  1668. [self titlePopUpChanged:nil];
  1669. SuccessfulScan = YES;
  1670. [self enableUI: YES];
  1671. /* if its the initial successful scan after awakeFromNib */
  1672. if (currentSuccessfulScanCount == 1)
  1673. {
  1674. [self encodeStartStopPopUpChanged:nil];
  1675. [self selectDefaultPreset:nil];
  1676. // Open preview window now if it was visible when HB was closed
  1677. if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PreviewWindowIsOpen"])
  1678. [self showPreviewWindow:nil];
  1679. // Open picture sizing window now if it was visible when HB was closed
  1680. if ([[NSUserDefaults standardUserDefaults] boolForKey:@"PictureSizeWindowIsOpen"])
  1681. [self showPicturePanel:nil];
  1682. }
  1683. if (applyQueueToScan == YES)
  1684. {
  1685. /* we are a rescan of an existing queue item and need to apply the queued settings to the scan */
  1686. [self writeToActivityLog: "showNewScan: calling applyQueueSettingsToMainWindow"];
  1687. [self applyQueueSettingsToMainWindow:nil];
  1688. }
  1689. }
  1690. }
  1691. #pragma mark -
  1692. #pragma mark New Output Destination
  1693. - (IBAction) browseFile: (id) sender
  1694. {
  1695. /* Open a panel to let the user choose and update the text field */
  1696. NSSavePanel * panel = [NSSavePanel savePanel];
  1697. /* We get the current file name and path from the destination field here */
  1698. [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent] file: [[fDstFile2Field stringValue] lastPathComponent]
  1699. modalForWindow: fWindow modalDelegate: self
  1700. didEndSelector: @selector( browseFileDone:returnCode:contextInfo: )
  1701. contextInfo: NULL];
  1702. }
  1703. - (void) browseFileDone: (NSSavePanel *) sheet
  1704. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  1705. {
  1706. if( returnCode == NSOKButton )
  1707. {
  1708. [fDstFile2Field setStringValue: [sheet filename]];
  1709. /* Save this path to the prefs so that on next browse destination window it opens there */
  1710. NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
  1711. [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
  1712. }
  1713. }
  1714. #pragma mark -
  1715. #pragma mark Main Window Control
  1716. - (IBAction) openMainWindow: (id) sender
  1717. {
  1718. [fWindow makeKeyAndOrderFront:nil];
  1719. }
  1720. - (BOOL) windowShouldClose: (id) sender
  1721. {
  1722. return YES;
  1723. }
  1724. - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
  1725. {
  1726. if( !flag ) {
  1727. [fWindow makeKeyAndOrderFront:nil];
  1728. }
  1729. return YES;
  1730. }
  1731. - (NSSize) drawerWillResizeContents:(NSDrawer *) drawer toSize:(NSSize) contentSize {
  1732. [[NSUserDefaults standardUserDefaults] setObject:NSStringFromSize( contentSize ) forKey:@"Drawer Size"];
  1733. return contentSize;
  1734. }
  1735. #pragma mark -
  1736. #pragma mark Queue File
  1737. - (void) loadQueueFile {
  1738. /* We declare the default NSFileManager into fileManager */
  1739. NSFileManager * fileManager = [NSFileManager defaultManager];
  1740. /*We define the location of the user presets file */
  1741. QueueFile = @"~/Library/Application Support/HandBrake/Queue.plist";
  1742. QueueFile = [[QueueFile stringByExpandingTildeInPath]retain];
  1743. /* We check for the Queue.plist */
  1744. if ([fileManager fileExistsAtPath:QueueFile] == 0)
  1745. {
  1746. [fileManager createFileAtPath:QueueFile contents:nil attributes:nil];
  1747. }
  1748. QueueFileArray = [[NSMutableArray alloc] initWithContentsOfFile:QueueFile];
  1749. /* lets check to see if there is anything in the queue file .plist */
  1750. if (nil == QueueFileArray)
  1751. {
  1752. /* if not, then lets initialize an empty array */
  1753. QueueFileArray = [[NSMutableArray alloc] init];
  1754. }
  1755. else
  1756. {
  1757. /* ONLY clear out encoded items if we are single instance */
  1758. if (hbInstanceNum == 1)
  1759. {
  1760. [self clearQueueEncodedItems];
  1761. }
  1762. }
  1763. }
  1764. - (void)addQueueFileItem
  1765. {
  1766. [QueueFileArray addObject:[self createQueueFileItem]];
  1767. [self saveQueueFileItem];
  1768. }
  1769. - (void) removeQueueFileItem:(int) queueItemToRemove
  1770. {
  1771. [QueueFileArray removeObjectAtIndex:queueItemToRemove];
  1772. [self saveQueueFileItem];
  1773. }
  1774. - (void)saveQueueFileItem
  1775. {
  1776. [QueueFileArray writeToFile:QueueFile atomically:YES];
  1777. [fQueueController setQueueArray: QueueFileArray];
  1778. [self getQueueStats];
  1779. }
  1780. - (void)getQueueStats
  1781. {
  1782. /* lets get the stats on the status of the queue array */
  1783. fEncodingQueueItem = 0;
  1784. fPendingCount = 0;
  1785. fCompletedCount = 0;
  1786. fCanceledCount = 0;
  1787. fWorkingCount = 0;
  1788. /* We use a number system to set the encode status of the queue item
  1789. * in controller.mm
  1790. * 0 == already encoded
  1791. * 1 == is being encoded
  1792. * 2 == is yet to be encoded
  1793. * 3 == cancelled
  1794. */
  1795. int i = 0;
  1796. NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
  1797. id tempObject;
  1798. while (tempObject = [enumerator nextObject])
  1799. {
  1800. NSDictionary *thisQueueDict = tempObject;
  1801. if ([[thisQueueDict objectForKey:@"Status"] intValue] == 0) // Completed
  1802. {
  1803. fCompletedCount++;
  1804. }
  1805. if ([[thisQueueDict objectForKey:@"Status"] intValue] == 1) // being encoded
  1806. {
  1807. fWorkingCount++;
  1808. fEncodingQueueItem = i;
  1809. /* check to see if we are the instance doing this encoding */
  1810. if ([thisQueueDict objectForKey:@"EncodingPID"] && [[thisQueueDict objectForKey:@"EncodingPID"] intValue] == pidNum)
  1811. {
  1812. currentQueueEncodeIndex = i;
  1813. }
  1814. }
  1815. if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2) // pending
  1816. {
  1817. fPendingCount++;
  1818. }
  1819. if ([[thisQueueDict objectForKey:@"Status"] intValue] == 3) // cancelled
  1820. {
  1821. fCanceledCount++;
  1822. }
  1823. i++;
  1824. }
  1825. /* Set the queue status field in the main window */
  1826. NSMutableString * string;
  1827. if (fPendingCount == 0)
  1828. {
  1829. string = [NSMutableString stringWithFormat: NSLocalizedString( @"No encode pending", @"" )];
  1830. }
  1831. else if (fPendingCount == 1)
  1832. {
  1833. string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encode pending", @"" ), fPendingCount];
  1834. }
  1835. else
  1836. {
  1837. string = [NSMutableString stringWithFormat: NSLocalizedString( @"%d encodes pending", @"" ), fPendingCount];
  1838. }
  1839. [fQueueStatus setStringValue:string];
  1840. }
  1841. /* Used to get the next pending queue item index and return it if found */
  1842. - (int)getNextPendingQueueIndex
  1843. {
  1844. /* initialize nextPendingIndex to -1, this value tells incrementQueueItemDone that there are no pending items in the queue */
  1845. int nextPendingIndex = -1;
  1846. BOOL nextPendingFound = NO;
  1847. NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
  1848. id tempObject;
  1849. int i = 0;
  1850. while (tempObject = [enumerator nextObject])
  1851. {
  1852. NSDictionary *thisQueueDict = tempObject;
  1853. if ([[thisQueueDict objectForKey:@"Status"] intValue] == 2 && nextPendingFound == NO) // pending
  1854. {
  1855. nextPendingFound = YES;
  1856. nextPendingIndex = [QueueFileArray indexOfObject: tempObject];
  1857. [self writeToActivityLog: "getNextPendingQueueIndex next pending encode index is:%d", nextPendingIndex];
  1858. }
  1859. i++;
  1860. }
  1861. return nextPendingIndex;
  1862. }
  1863. /* This method will set any item marked as encoding back to pending
  1864. * currently used right after a queue reload
  1865. */
  1866. - (void) setQueueEncodingItemsAsPending
  1867. {
  1868. NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
  1869. id tempObject;
  1870. NSMutableArray *tempArray;
  1871. tempArray = [NSMutableArray array];
  1872. /* we look here to see if the preset is we move on to the next one */
  1873. while ( tempObject = [enumerator nextObject] )
  1874. {
  1875. /* We want to keep any queue item that is pending or was previously being encoded */
  1876. if ([[tempObject objectForKey:@"Status"] intValue] == 1 || [[tempObject objectForKey:@"Status"] intValue] == 2)
  1877. {
  1878. /* If the queue item is marked as "encoding" (1)
  1879. * then change its status back to pending (2) which effectively
  1880. * puts it back into the queue to be encoded
  1881. */
  1882. if ([[tempObject objectForKey:@"Status"] intValue] == 1)
  1883. {
  1884. [tempObject setObject:[NSNumber numberWithInt: 2] forKey:@"Status"];
  1885. }
  1886. [tempArray addObject:tempObject];
  1887. }
  1888. }
  1889. [QueueFileArray setArray:tempArray];
  1890. [self saveQueueFileItem];
  1891. }
  1892. /* This method will clear the queue of any encodes that are not still pending
  1893. * this includes both successfully completed encodes as well as cancelled encodes */
  1894. - (void) clearQueueEncodedItems
  1895. {
  1896. NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
  1897. id tempObject;
  1898. NSMutableArray *tempArray;
  1899. tempArray = [NSMutableArray array];
  1900. /* we look here to see if the preset is we move on to the next one */
  1901. while ( tempObject = [enumerator nextObject] )
  1902. {
  1903. /* If the queue item is either completed (0) or cancelled (3) from the
  1904. * last session, then we put it in tempArray to be deleted from QueueFileArray.
  1905. * NOTE: this means we retain pending (2) and also an item that is marked as
  1906. * still encoding (1). If the queue has an item that is still marked as encoding
  1907. * from a previous session, we can conlude that HB was either shutdown, or crashed
  1908. * during the encodes so we keep it and tell the user in the "Load Queue Alert"
  1909. */
  1910. if ([[tempObject objectForKey:@"Status"] intValue] == 0 || [[tempObject objectForKey:@"Status"] intValue] == 3)
  1911. {
  1912. [tempArray addObject:tempObject];
  1913. }
  1914. }
  1915. [QueueFileArray removeObjectsInArray:tempArray];
  1916. [self saveQueueFileItem];
  1917. }
  1918. /* This method will clear the queue of all encodes. effectively creating an empty queue */
  1919. - (void) clearQueueAllItems
  1920. {
  1921. NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
  1922. id tempObject;
  1923. NSMutableArray *tempArray;
  1924. tempArray = [NSMutableArray array];
  1925. /* we look here to see if the preset is we move on to the next one */
  1926. while ( tempObject = [enumerator nextObject] )
  1927. {
  1928. [tempArray addObject:tempObject];
  1929. }
  1930. [QueueFileArray removeObjectsInArray:tempArray];
  1931. [self saveQueueFileItem];
  1932. }
  1933. /* This method will duplicate prepareJob however into the
  1934. * queue .plist instead of into the job structure so it can
  1935. * be recalled later */
  1936. - (NSDictionary *)createQueueFileItem
  1937. {
  1938. NSMutableDictionary *queueFileJob = [[NSMutableDictionary alloc] init];
  1939. hb_list_t * list = hb_get_titles( fHandle );
  1940. hb_title_t * title = (hb_title_t *) hb_list_item( list,
  1941. [fSrcTitlePopUp indexOfSelectedItem] );
  1942. hb_job_t * job = title->job;
  1943. /* We use a number system to set the encode status of the queue item
  1944. * 0 == already encoded
  1945. * 1 == is being encoded
  1946. * 2 == is yet to be encoded
  1947. * 3 == cancelled
  1948. */
  1949. [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"Status"];
  1950. /* Source and Destination Information */
  1951. [queueFileJob setObject:[NSString stringWithUTF8String: title->path] forKey:@"SourcePath"];
  1952. [queueFileJob setObject:[fSrcDVD2Field stringValue] forKey:@"SourceName"];
  1953. [queueFileJob setObject:[NSNumber numberWithInt:title->index] forKey:@"TitleNumber"];
  1954. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcAnglePopUp indexOfSelectedItem] + 1] forKey:@"TitleAngle"];
  1955. /* Determine and set a variable to tell hb what start and stop times to use ... chapters vs seconds */
  1956. if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
  1957. {
  1958. [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"fEncodeStartStop"];
  1959. }
  1960. else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
  1961. {
  1962. [queueFileJob setObject:[NSNumber numberWithInt:1] forKey:@"fEncodeStartStop"];
  1963. }
  1964. else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
  1965. {
  1966. [queueFileJob setObject:[NSNumber numberWithInt:2] forKey:@"fEncodeStartStop"];
  1967. }
  1968. /* Chapter encode info */
  1969. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"ChapterStart"];
  1970. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"ChapterEnd"];
  1971. /* Time (pts) encode info */
  1972. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeStartEncodingField intValue]] forKey:@"StartSeconds"];
  1973. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue]] forKey:@"StopSeconds"];
  1974. /* Frame number encode info */
  1975. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameStartEncodingField intValue]] forKey:@"StartFrame"];
  1976. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]] forKey:@"StopFrame"];
  1977. /* The number of seek points equals the number of seconds announced in the title as that is our current granularity */
  1978. int title_duration_seconds = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
  1979. [queueFileJob setObject:[NSNumber numberWithInt:title_duration_seconds] forKey:@"SourceTotalSeconds"];
  1980. [queueFileJob setObject:[fDstFile2Field stringValue] forKey:@"DestinationPath"];
  1981. /* Lets get the preset info if there is any */
  1982. [queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
  1983. [queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
  1984. [queueFileJob setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
  1985. /* Chapter Markers*/
  1986. /* If we have only one chapter or a title without chapters, set chapter markers to off */
  1987. if ([fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem])
  1988. {
  1989. [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"ChapterMarkers"];
  1990. }
  1991. else
  1992. {
  1993. [queueFileJob setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
  1994. }
  1995. /* We need to get the list of chapter names to put into an array and store
  1996. * in our queue, so they can be reapplied in prepareJob when this queue
  1997. * item comes up if Chapter Markers is set to on.
  1998. */
  1999. int i;
  2000. NSMutableArray *ChapterNamesArray = [[NSMutableArray alloc] init];
  2001. int chaptercount = hb_list_count( fTitle->list_chapter );
  2002. for( i = 0; i < chaptercount; i++ )
  2003. {
  2004. hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( fTitle->list_chapter, i );
  2005. if( chapter != NULL )
  2006. {
  2007. [ChapterNamesArray addObject:[NSString stringWithCString:chapter->title encoding:NSUTF8StringEncoding]];
  2008. }
  2009. }
  2010. [queueFileJob setObject:[NSMutableArray arrayWithArray: ChapterNamesArray] forKey:@"ChapterNames"];
  2011. [ChapterNamesArray autorelease];
  2012. /* Allow Mpeg4 64 bit formatting +4GB file sizes */
  2013. [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
  2014. /* Mux mp4 with http optimization */
  2015. [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
  2016. /* Add iPod uuid atom */
  2017. [queueFileJob setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
  2018. /* Codecs */
  2019. /* Video encoder */
  2020. [queueFileJob setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
  2021. /* x264 Option String */
  2022. [queueFileJob setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
  2023. [queueFileJob setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
  2024. [queueFileJob setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
  2025. [queueFileJob setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
  2026. [queueFileJob setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
  2027. /* Framerate */
  2028. [queueFileJob setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
  2029. [queueFileJob setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
  2030. /* 2 Pass Encoding */
  2031. [queueFileJob setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
  2032. /* Turbo 2 pass Encoding fVidTurboPassCheck*/
  2033. [queueFileJob setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
  2034. /* Picture Sizing */
  2035. /* Use Max Picture settings for whatever the dvd is.*/
  2036. [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
  2037. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
  2038. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
  2039. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
  2040. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
  2041. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
  2042. /* if we are custom anamorphic, store the exact storage, par and display dims */
  2043. if (fTitle->job->anamorphic.mode == 3)
  2044. {
  2045. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PicturePARModulus"];
  2046. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PicturePARStorageWidth"];
  2047. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PicturePARStorageHeight"];
  2048. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_width] forKey:@"PicturePARPixelWidth"];
  2049. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.par_height] forKey:@"PicturePARPixelHeight"];
  2050. [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_width] forKey:@"PicturePARDisplayWidth"];
  2051. [queueFileJob setObject:[NSNumber numberWithFloat:fTitle->job->anamorphic.dar_height] forKey:@"PicturePARDisplayHeight"];
  2052. }
  2053. NSString * pictureSummary;
  2054. pictureSummary = [fPictureSizeField stringValue];
  2055. [queueFileJob setObject:pictureSummary forKey:@"PictureSizingSummary"];
  2056. /* Set crop settings here */
  2057. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
  2058. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
  2059. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
  2060. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
  2061. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
  2062. /* Picture Filters */
  2063. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
  2064. [queueFileJob setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
  2065. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
  2066. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
  2067. [queueFileJob setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
  2068. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
  2069. [queueFileJob setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
  2070. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
  2071. [queueFileJob setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
  2072. [queueFileJob setObject:[NSString stringWithFormat:@"%d",[fPictureController deblock]] forKey:@"PictureDeblock"];
  2073. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
  2074. /*Audio*/
  2075. [fAudioDelegate prepareAudioForQueueFileJob: queueFileJob];
  2076. /* Subtitles*/
  2077. NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
  2078. [queueFileJob setObject:[NSArray arrayWithArray: subtitlesArray] forKey:@"SubtitleList"];
  2079. [subtitlesArray autorelease];
  2080. /* Now we go ahead and set the "job->values in the plist for passing right to fQueueEncodeLibhb */
  2081. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterStartPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterStart"];
  2082. [queueFileJob setObject:[NSNumber numberWithInt:[fSrcChapterEndPopUp indexOfSelectedItem] + 1] forKey:@"JobChapterEnd"];
  2083. [queueFileJob setObject:[NSNumber numberWithInt:[[fDstFormatPopUp selectedItem] tag]] forKey:@"JobFileFormatMux"];
  2084. /* Codecs */
  2085. /* Video encoder */
  2086. [queueFileJob setObject:[NSNumber numberWithInt:[[fVidEncoderPopUp selectedItem] tag]] forKey:@"JobVideoEncoderVcodec"];
  2087. /* Framerate */
  2088. [queueFileJob setObject:[NSNumber numberWithInt:[fVidRatePopUp indexOfSelectedItem]] forKey:@"JobIndexVideoFramerate"];
  2089. [queueFileJob setObject:[NSNumber numberWithInt:title->rate] forKey:@"JobVrate"];
  2090. [queueFileJob setObject:[NSNumber numberWithInt:title->rate_base] forKey:@"JobVrateBase"];
  2091. /* Picture Sizing */
  2092. /* Use Max Picture settings for whatever the dvd is.*/
  2093. [queueFileJob setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
  2094. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->width] forKey:@"PictureWidth"];
  2095. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->height] forKey:@"PictureHeight"];
  2096. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
  2097. [queueFileJob setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
  2098. /* Set crop settings here */
  2099. [queueFileJob setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
  2100. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
  2101. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
  2102. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
  2103. [queueFileJob setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
  2104. /* we need to auto relase the queueFileJob and return it */
  2105. [queueFileJob autorelease];
  2106. return queueFileJob;
  2107. }
  2108. /* this is actually called from the queue controller to modify the queue array and return it back to the queue controller */
  2109. - (void)moveObjectsInQueueArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
  2110. {
  2111. NSUInteger index = [indexSet lastIndex];
  2112. NSUInteger aboveInsertIndexCount = 0;
  2113. NSUInteger removeIndex;
  2114. if (index >= insertIndex)
  2115. {
  2116. removeIndex = index + aboveInsertIndexCount;
  2117. aboveInsertIndexCount++;
  2118. }
  2119. else
  2120. {
  2121. removeIndex = index;
  2122. insertIndex--;
  2123. }
  2124. id object = [[QueueFileArray objectAtIndex:removeIndex] retain];
  2125. [QueueFileArray removeObjectAtIndex:removeIndex];
  2126. [QueueFileArray insertObject:object atIndex:insertIndex];
  2127. [object release];
  2128. index = [indexSet indexLessThanIndex:index];
  2129. /* We save all of the Queue data here
  2130. * and it also gets sent back to the queue controller*/
  2131. [self saveQueueFileItem];
  2132. }
  2133. #pragma mark -
  2134. #pragma mark Queue Job Processing
  2135. - (void) incrementQueueItemDone:(int) queueItemDoneIndexNum
  2136. {
  2137. /* Mark the encode just finished as done (status 0)*/
  2138. [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:0] forKey:@"Status"];
  2139. /* We save all of the Queue data here */
  2140. [self saveQueueFileItem];
  2141. /* Since we have now marked a queue item as done
  2142. * we can go ahead and increment currentQueueEncodeIndex
  2143. * so that if there is anything left in the queue we can
  2144. * go ahead and move to the next item if we want to */
  2145. int queueItems = [QueueFileArray count];
  2146. /* Check to see if there are any more pending items in the queue */
  2147. int newQueueItemIndex = [self getNextPendingQueueIndex];
  2148. /* If we still have more pending items in our queue, lets go to the next one */
  2149. if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
  2150. {
  2151. /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
  2152. currentQueueEncodeIndex = newQueueItemIndex;
  2153. /* now we mark the queue item as Status = 1 ( being encoded ) so another instance can not come along and try to scan it while we are scanning */
  2154. [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
  2155. [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
  2156. [self saveQueueFileItem];
  2157. /* now we can go ahead and scan the new pending queue item */
  2158. [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
  2159. }
  2160. else
  2161. {
  2162. [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
  2163. /*Since there are no more items to encode, go to queueCompletedAlerts for user specified alerts after queue completed*/
  2164. [self queueCompletedAlerts];
  2165. }
  2166. }
  2167. /* Here we actually tell hb_scan to perform the source scan, using the path to source and title number*/
  2168. - (void) performNewQueueScan:(NSString *) scanPath scanTitleNum: (int) scanTitleNum
  2169. {
  2170. /* Tell HB to output a new activity log file for this encode */
  2171. [outputPanel startEncodeLog:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"]];
  2172. /* We now flag the queue item as being owned by this instance of HB using the PID */
  2173. [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:pidNum] forKey:@"EncodingPID"];
  2174. /* Get the currentQueueEncodeNameString from the queue item to display in the status field */
  2175. currentQueueEncodeNameString = [[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"DestinationPath"] lastPathComponent]retain];
  2176. /* We save all of the Queue data here */
  2177. [self saveQueueFileItem];
  2178. /* use a bool to determine whether or not we can decrypt using vlc */
  2179. BOOL cancelScanDecrypt = 0;
  2180. /* set the bool so that showNewScan knows to apply the appropriate queue
  2181. * settings as this is a queue rescan
  2182. */
  2183. NSString *path = scanPath;
  2184. HBDVDDetector *detector = [HBDVDDetector detectorForPath:path];
  2185. if( [detector isVideoDVD] )
  2186. {
  2187. // The chosen path was actually on a DVD, so use the raw block
  2188. // device path instead.
  2189. path = [detector devicePath];
  2190. [self writeToActivityLog: "trying to open a physical dvd at: %s", [scanPath UTF8String]];
  2191. /* lets check for vlc here to make sure we have a dylib available to use for decrypting */
  2192. void *dvdcss = dlopen("libdvdcss.2.dylib", RTLD_LAZY);
  2193. if (dvdcss == NULL)
  2194. {
  2195. /*vlc not found in /Applications so we set the bool to cancel scanning to 1 */
  2196. cancelScanDecrypt = 1;
  2197. [self writeToActivityLog: "VLC app not found for decrypting physical dvd"];
  2198. int status;
  2199. 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");
  2200. [NSApp requestUserAttention:NSCriticalRequest];
  2201. if (status == NSAlertDefaultReturn)
  2202. {
  2203. /* User chose to go download vlc (as they rightfully should) so we send them to the vlc site */
  2204. [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.videolan.org/"]];
  2205. }
  2206. else if (status == NSAlertAlternateReturn)
  2207. {
  2208. /* User chose to cancel the scan */
  2209. [self writeToActivityLog: "cannot open physical dvd , scan cancelled"];
  2210. }
  2211. else
  2212. {
  2213. /* 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 */
  2214. cancelScanDecrypt = 0;
  2215. [self writeToActivityLog: "user overrode vlc warning -trying to open physical dvd without decryption"];
  2216. }
  2217. }
  2218. else
  2219. {
  2220. /* VLC was found in /Applications so all is well, we can carry on using vlc's libdvdcss.dylib for decrypting if needed */
  2221. dlclose(dvdcss);
  2222. [self writeToActivityLog: "VLC app found for decrypting physical dvd"];
  2223. }
  2224. }
  2225. if (cancelScanDecrypt == 0)
  2226. {
  2227. /* we actually pass the scan off to libhb here */
  2228. /* If there is no title number passed to scan, we use "0"
  2229. * which causes the default behavior of a full source scan
  2230. */
  2231. if (!scanTitleNum)
  2232. {
  2233. scanTitleNum = 0;
  2234. }
  2235. if (scanTitleNum > 0)
  2236. {
  2237. [self writeToActivityLog: "scanning specifically for title: %d", scanTitleNum];
  2238. }
  2239. /* Only scan 10 previews before an encode - additional previews are only useful for autocrop and static previews,
  2240. * which are already taken care of at this point */
  2241. hb_scan( fQueueEncodeLibhb, [path UTF8String], scanTitleNum, 10, 0, 0 );
  2242. }
  2243. }
  2244. /* This assumes that we have re-scanned and loaded up a new queue item to send to libhb as fQueueEncodeLibhb */
  2245. - (void) processNewQueueEncode
  2246. {
  2247. hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
  2248. hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
  2249. hb_job_t * job = title->job;
  2250. if( !hb_list_count( list ) )
  2251. {
  2252. [self writeToActivityLog: "processNewQueueEncode WARNING nothing found in the title list"];
  2253. }
  2254. NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
  2255. [self writeToActivityLog: "Preset: %s", [[queueToApply objectForKey:@"PresetName"] UTF8String]];
  2256. [self writeToActivityLog: "processNewQueueEncode number of passes expected is: %d", ([[queueToApply objectForKey:@"VideoTwoPass"] intValue] + 1)];
  2257. job->file = [[queueToApply objectForKey:@"DestinationPath"] UTF8String];
  2258. [self prepareJob];
  2259. /*
  2260. * If scanning we need to do some extra setup of the job.
  2261. */
  2262. if( job->indepth_scan == 1 )
  2263. {
  2264. char *x264opts_tmp;
  2265. /*
  2266. * When subtitle scan is enabled do a fast pre-scan job
  2267. * which will determine which subtitles to enable, if any.
  2268. */
  2269. job->pass = -1;
  2270. x264opts_tmp = job->x264opts;
  2271. job->x264opts = NULL;
  2272. job->indepth_scan = 1;
  2273. /*
  2274. * Add the pre-scan job
  2275. */
  2276. hb_add( fQueueEncodeLibhb, job );
  2277. job->x264opts = x264opts_tmp;
  2278. }
  2279. if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 )
  2280. {
  2281. job->indepth_scan = 0;
  2282. job->pass = 1;
  2283. hb_add( fQueueEncodeLibhb, job );
  2284. job->pass = 2;
  2285. job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
  2286. strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
  2287. hb_add( fQueueEncodeLibhb, job );
  2288. }
  2289. else
  2290. {
  2291. job->indepth_scan = 0;
  2292. job->pass = 0;
  2293. hb_add( fQueueEncodeLibhb, job );
  2294. }
  2295. NSString *destinationDirectory = [[queueToApply objectForKey:@"DestinationPath"] stringByDeletingLastPathComponent];
  2296. [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
  2297. /* Lets mark our new encode as 1 or "Encoding" */
  2298. [queueToApply setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
  2299. [self saveQueueFileItem];
  2300. /* we need to clean up the subtitle tracks after the job(s) have been set */
  2301. int num_subtitle_tracks = hb_list_count(job->list_subtitle);
  2302. int ii;
  2303. for(ii = 0; ii < num_subtitle_tracks; ii++)
  2304. {
  2305. hb_subtitle_t * subtitle;
  2306. subtitle = (hb_subtitle_t *)hb_list_item(job->list_subtitle, 0);
  2307. hb_list_rem(job->list_subtitle, subtitle);
  2308. free(subtitle);
  2309. }
  2310. /* We should be all setup so let 'er rip */
  2311. [self doRip];
  2312. }
  2313. #pragma mark -
  2314. #pragma mark Queue Item Editing
  2315. /* Rescans the chosen queue item back into the main window */
  2316. - (void)rescanQueueItemToMainWindow:(NSString *) scanPath scanTitleNum: (int) scanTitleNum selectedQueueItem: (int) selectedQueueItem
  2317. {
  2318. fqueueEditRescanItemNum = selectedQueueItem;
  2319. [self writeToActivityLog: "rescanQueueItemToMainWindow: Re-scanning queue item at index:%d",fqueueEditRescanItemNum];
  2320. applyQueueToScan = YES;
  2321. /* Make sure we release the display name before reassigning it */
  2322. [browsedSourceDisplayName release];
  2323. /* Set the browsedSourceDisplayName for showNewScan */
  2324. browsedSourceDisplayName = [[[QueueFileArray objectAtIndex:fqueueEditRescanItemNum] objectForKey:@"SourceName"] retain];
  2325. [self performScan:scanPath scanTitleNum:scanTitleNum];
  2326. }
  2327. /* We use this method after a queue item rescan for edit.
  2328. * it largely mirrors -selectPreset in terms of structure.
  2329. * Assumes that a queue item has been reloaded into the main window.
  2330. */
  2331. - (IBAction)applyQueueSettingsToMainWindow:(id)sender
  2332. {
  2333. NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:fqueueEditRescanItemNum];
  2334. hb_job_t * job = fTitle->job;
  2335. if (queueToApply)
  2336. {
  2337. [self writeToActivityLog: "applyQueueSettingsToMainWindow: queue item found"];
  2338. }
  2339. /* Set title number and chapters */
  2340. /* since the queue only scans a single title, its already been selected in showNewScan
  2341. so do not try to reset it here. However if we do decide to do full source scans on
  2342. a queue edit rescan, we would need it. So leaving in for now but commenting out. */
  2343. //[fSrcTitlePopUp selectItemAtIndex: [[queueToApply objectForKey:@"TitleNumber"] intValue] - 1];
  2344. [fSrcChapterStartPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterStart"] intValue] - 1];
  2345. [fSrcChapterEndPopUp selectItemAtIndex: [[queueToApply objectForKey:@"ChapterEnd"] intValue] - 1];
  2346. /* File Format */
  2347. [fDstFormatPopUp selectItemWithTitle:[queueToApply objectForKey:@"FileFormat"]];
  2348. [self formatPopUpChanged:nil];
  2349. /* Chapter Markers*/
  2350. [fCreateChapterMarkers setState:[[queueToApply objectForKey:@"ChapterMarkers"] intValue]];
  2351. /* Allow Mpeg4 64 bit formatting +4GB file sizes */
  2352. [fDstMp4LargeFileCheck setState:[[queueToApply objectForKey:@"Mp4LargeFile"] intValue]];
  2353. /* Mux mp4 with http optimization */
  2354. [fDstMp4HttpOptFileCheck setState:[[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue]];
  2355. /* Video encoder */
  2356. /* We set the advanced opt string here if applicable*/
  2357. [fVidEncoderPopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoEncoder"]];
  2358. [fAdvancedOptions setOptions:[queueToApply objectForKey:@"x264Option"]];
  2359. /* Lets run through the following functions to get variables set there */
  2360. [self videoEncoderPopUpChanged:nil];
  2361. /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
  2362. [fDstMp4iPodFileCheck setState:[[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue]];
  2363. [self calculateBitrate:nil];
  2364. /* Video quality */
  2365. [fVidQualityMatrix selectCellAtRow:[[queueToApply objectForKey:@"VideoQualityType"] intValue] column:0];
  2366. [fVidTargetSizeField setStringValue:[queueToApply objectForKey:@"VideoTargetSize"]];
  2367. [fVidBitrateField setStringValue:[queueToApply objectForKey:@"VideoAvgBitrate"]];
  2368. /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
  2369. * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
  2370. * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
  2371. * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
  2372. * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
  2373. if ([[queueToApply objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
  2374. {
  2375. /* For the quality slider we need to convert the old percent's to the new rf scales */
  2376. float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]);
  2377. [fVidQualitySlider setFloatValue:rf];
  2378. }
  2379. else
  2380. {
  2381. /* Since theora's qp value goes up from left to right, we can just set the slider float value */
  2382. if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
  2383. {
  2384. [fVidQualitySlider setFloatValue:[[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
  2385. }
  2386. else
  2387. {
  2388. /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
  2389. [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue]];
  2390. }
  2391. }
  2392. [self videoMatrixChanged:nil];
  2393. /* Video framerate */
  2394. /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
  2395. detected framerate in the fVidRatePopUp so we use index 0*/
  2396. if ([[queueToApply objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
  2397. {
  2398. [fVidRatePopUp selectItemAtIndex: 0];
  2399. }
  2400. else
  2401. {
  2402. [fVidRatePopUp selectItemWithTitle:[queueToApply objectForKey:@"VideoFramerate"]];
  2403. }
  2404. /* 2 Pass Encoding */
  2405. [fVidTwoPassCheck setState:[[queueToApply objectForKey:@"VideoTwoPass"] intValue]];
  2406. [self twoPassCheckboxChanged:nil];
  2407. /* Turbo 1st pass for 2 Pass Encoding */
  2408. [fVidTurboPassCheck setState:[[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue]];
  2409. /*Audio*/
  2410. /* Now lets add our new tracks to the audio list here */
  2411. [fAudioDelegate addTracksFromQueue: queueToApply];
  2412. /*Subtitles*/
  2413. /* Crashy crashy right now, working on it */
  2414. [fSubtitlesDelegate setNewSubtitles:[queueToApply objectForKey:@"SubtitleList"]];
  2415. [fSubtitlesTable reloadData];
  2416. /* Picture Settings */
  2417. /* If Cropping is set to custom, then recall all four crop values from
  2418. when the preset was created and apply them */
  2419. if ([[queueToApply objectForKey:@"PictureAutoCrop"] intValue] == 0)
  2420. {
  2421. [fPictureController setAutoCrop:NO];
  2422. /* Here we use the custom crop values saved at the time the preset was saved */
  2423. job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
  2424. job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
  2425. job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
  2426. job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
  2427. }
  2428. else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
  2429. {
  2430. [fPictureController setAutoCrop:YES];
  2431. /* Here we use the auto crop values determined right after scan */
  2432. job->crop[0] = AutoCropTop;
  2433. job->crop[1] = AutoCropBottom;
  2434. job->crop[2] = AutoCropLeft;
  2435. job->crop[3] = AutoCropRight;
  2436. }
  2437. job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
  2438. /* we check to make sure the presets width/height does not exceed the sources width/height */
  2439. if (fTitle->width < [[queueToApply objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[queueToApply objectForKey:@"PictureHeight"] intValue])
  2440. {
  2441. /* if so, then we use the sources height and width to avoid scaling up */
  2442. //job->width = fTitle->width;
  2443. //job->height = fTitle->height;
  2444. [self revertPictureSizeToMax:nil];
  2445. }
  2446. else // source width/height is >= the preset height/width
  2447. {
  2448. /* we can go ahead and use the presets values for height and width */
  2449. job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
  2450. job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
  2451. }
  2452. job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
  2453. if (job->keep_ratio == 1)
  2454. {
  2455. hb_fix_aspect( job, HB_KEEP_WIDTH );
  2456. if( job->height > fTitle->height )
  2457. {
  2458. job->height = fTitle->height;
  2459. hb_fix_aspect( job, HB_KEEP_HEIGHT );
  2460. }
  2461. }
  2462. job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
  2463. job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
  2464. /* Filters */
  2465. /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
  2466. * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
  2467. * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
  2468. * sane.
  2469. */
  2470. [fPictureController setUseDecomb:1];
  2471. [fPictureController setDecomb:0];
  2472. [fPictureController setDeinterlace:0];
  2473. if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
  2474. {
  2475. /* we are using decomb */
  2476. /* Decomb */
  2477. if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] > 0)
  2478. {
  2479. [fPictureController setDecomb:[[queueToApply objectForKey:@"PictureDecomb"] intValue]];
  2480. /* if we are using "Custom" in the decomb setting, also set the custom string*/
  2481. if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
  2482. {
  2483. [fPictureController setDecombCustomString:[queueToApply objectForKey:@"PictureDecombCustom"]];
  2484. }
  2485. }
  2486. }
  2487. else
  2488. {
  2489. /* We are using Deinterlace */
  2490. /* Deinterlace */
  2491. if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] > 0)
  2492. {
  2493. [fPictureController setUseDecomb:0];
  2494. [fPictureController setDeinterlace:[[queueToApply objectForKey:@"PictureDeinterlace"] intValue]];
  2495. /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
  2496. if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
  2497. {
  2498. [fPictureController setDeinterlaceCustomString:[queueToApply objectForKey:@"PictureDeinterlaceCustom"]];
  2499. }
  2500. }
  2501. }
  2502. /* Detelecine */
  2503. if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] > 0)
  2504. {
  2505. [fPictureController setDetelecine:[[queueToApply objectForKey:@"PictureDetelecine"] intValue]];
  2506. /* if we are using "Custom" in the detelecine setting, also set the custom string*/
  2507. if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
  2508. {
  2509. [fPictureController setDetelecineCustomString:[queueToApply objectForKey:@"PictureDetelecineCustom"]];
  2510. }
  2511. }
  2512. else
  2513. {
  2514. [fPictureController setDetelecine:0];
  2515. }
  2516. /* Denoise */
  2517. if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] > 0)
  2518. {
  2519. [fPictureController setDenoise:[[queueToApply objectForKey:@"PictureDenoise"] intValue]];
  2520. /* if we are using "Custom" in the denoise setting, also set the custom string*/
  2521. if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1)
  2522. {
  2523. [fPictureController setDenoiseCustomString:[queueToApply objectForKey:@"PictureDenoiseCustom"]];
  2524. }
  2525. }
  2526. else
  2527. {
  2528. [fPictureController setDenoise:0];
  2529. }
  2530. /* Deblock */
  2531. if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] == 1)
  2532. {
  2533. /* if its a one, then its the old on/off deblock, set on to 5*/
  2534. [fPictureController setDeblock:5];
  2535. }
  2536. else
  2537. {
  2538. /* use the settings intValue */
  2539. [fPictureController setDeblock:[[queueToApply objectForKey:@"PictureDeblock"] intValue]];
  2540. }
  2541. if ([[queueToApply objectForKey:@"VideoGrayScale"] intValue] == 1)
  2542. {
  2543. [fPictureController setGrayscale:1];
  2544. }
  2545. else
  2546. {
  2547. [fPictureController setGrayscale:0];
  2548. }
  2549. /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
  2550. [fPictureController SetTitle:fTitle];
  2551. [self calculatePictureSizing:nil];
  2552. /* somehow we need to figure out a way to tie the queue item to a preset if it used one */
  2553. //[queueFileJob setObject:[fPresetSelectedDisplay stringValue] forKey:@"PresetName"];
  2554. //[queueFileJob setObject:[NSNumber numberWithInt:[fPresetsOutlineView selectedRow]] forKey:@"PresetIndexNum"];
  2555. if ([queueToApply objectForKey:@"PresetIndexNum"]) // This item used a preset so insert that info
  2556. {
  2557. /* Deselect the currently selected Preset if there is one*/
  2558. //[fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]] byExtendingSelection:NO];
  2559. //[self selectPreset:nil];
  2560. //[fPresetsOutlineView selectRow:[[queueToApply objectForKey:@"PresetIndexNum"] intValue]];
  2561. /* Change UI to show "Custom" settings are being used */
  2562. //[fPresetSelectedDisplay setStringValue: [[queueToApply objectForKey:@"PresetName"] stringValue]];
  2563. curUserPresetChosenNum = nil;
  2564. }
  2565. else
  2566. {
  2567. /* Deselect the currently selected Preset if there is one*/
  2568. [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
  2569. /* Change UI to show "Custom" settings are being used */
  2570. [fPresetSelectedDisplay setStringValue: @"Custom"];
  2571. //curUserPresetChosenNum = nil;
  2572. }
  2573. /* We need to set this bool back to NO, in case the user wants to do a scan */
  2574. //applyQueueToScan = NO;
  2575. /* Not that source is loaded and settings applied, delete the queue item from the queue */
  2576. [self writeToActivityLog: "applyQueueSettingsToMainWindow: deleting queue item:%d",fqueueEditRescanItemNum];
  2577. [self removeQueueFileItem:fqueueEditRescanItemNum];
  2578. }
  2579. #pragma mark -
  2580. #pragma mark Live Preview
  2581. /* Note,this is much like prepareJob, but directly sets the job vars so Picture Preview
  2582. * can encode to its temp preview directory and playback. This is *not* used for any actual user
  2583. * encodes
  2584. */
  2585. - (void) prepareJobForPreview
  2586. {
  2587. hb_list_t * list = hb_get_titles( fHandle );
  2588. hb_title_t * title = (hb_title_t *) hb_list_item( list,
  2589. [fSrcTitlePopUp indexOfSelectedItem] );
  2590. hb_job_t * job = title->job;
  2591. hb_audio_config_t * audio;
  2592. /* set job->angle for libdvdnav */
  2593. job->angle = [fSrcAnglePopUp indexOfSelectedItem] + 1;
  2594. /* Chapter selection */
  2595. job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
  2596. job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
  2597. /* Format (Muxer) and Video Encoder */
  2598. job->mux = [[fDstFormatPopUp selectedItem] tag];
  2599. job->vcodec = [[fVidEncoderPopUp selectedItem] tag];
  2600. job->chapter_markers = 0;
  2601. if( job->vcodec & HB_VCODEC_X264 )
  2602. {
  2603. /* Below Sends x264 options to the core library if x264 is selected*/
  2604. /* Lets use this as per Nyx, Thanks Nyx!*/
  2605. job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
  2606. /* For previews we ignore the turbo option for the first pass of two since we only use 1 pass */
  2607. strcpy(job->x264opts, [[fAdvancedOptions optionsString] UTF8String]);
  2608. }
  2609. /* Video settings */
  2610. /* Set vfr to 0 as it's only on if using same as source in the framerate popup
  2611. * and detelecine is on, so we handle that in the logic below
  2612. */
  2613. job->vfr = 0;
  2614. if( [fVidRatePopUp indexOfSelectedItem] > 0 )
  2615. {
  2616. /* a specific framerate has been chosen */
  2617. job->vrate = 27000000;
  2618. job->vrate_base = hb_video_rates[[fVidRatePopUp indexOfSelectedItem]-1].rate;
  2619. /* We are not same as source so we set job->cfr to 1
  2620. * to enable constant frame rate since user has specified
  2621. * a specific framerate*/
  2622. if ([fFrameratePfrCheck state] == 1)
  2623. {
  2624. job->cfr = 2;
  2625. }
  2626. else
  2627. {
  2628. job->cfr = 1;
  2629. }
  2630. }
  2631. else
  2632. {
  2633. /* We are same as source (variable) */
  2634. job->vrate = title->rate;
  2635. job->vrate_base = title->rate_base;
  2636. /* We are same as source so we set job->cfr to 0
  2637. * to enable true same as source framerate */
  2638. job->cfr = 0;
  2639. /* If we are same as source and we have detelecine on, we need to turn on
  2640. * job->vfr
  2641. */
  2642. if ([fPictureController detelecine] == 1)
  2643. {
  2644. job->vfr = 1;
  2645. }
  2646. }
  2647. switch( [fVidQualityMatrix selectedRow] )
  2648. {
  2649. case 0:
  2650. /* Target size.
  2651. Bitrate should already have been calculated and displayed
  2652. in fVidBitrateField, so let's just use it */
  2653. case 1:
  2654. job->vquality = -1.0;
  2655. job->vbitrate = [fVidBitrateField intValue];
  2656. break;
  2657. case 2:
  2658. job->vquality = [fVidQualityRFField floatValue];
  2659. job->vbitrate = 0;
  2660. break;
  2661. }
  2662. /* Subtitle settings */
  2663. NSMutableArray *subtitlesArray = [[NSMutableArray alloc] initWithArray:[fSubtitlesDelegate getSubtitleArray] copyItems:YES];
  2664. int subtitle = nil;
  2665. int force;
  2666. int burned;
  2667. int def;
  2668. bool one_burned = FALSE;
  2669. int i = 0;
  2670. NSEnumerator *enumerator = [subtitlesArray objectEnumerator];
  2671. id tempObject;
  2672. while (tempObject = [enumerator nextObject])
  2673. {
  2674. subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
  2675. force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
  2676. burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
  2677. def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
  2678. /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
  2679. * we want to ignore it for display as well as encoding.
  2680. */
  2681. if (subtitle > 0)
  2682. {
  2683. /* if i is 0, then we are in the first item of the subtitles which we need to
  2684. * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
  2685. * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
  2686. */
  2687. /* if we are on the first track and using "Foreign Audio Search" */
  2688. if (i == 0 && subtitle == 1)
  2689. {
  2690. /* NOTE: Currently foreign language search is borked for preview.
  2691. * Commented out but left in for initial commit. */
  2692. [self writeToActivityLog: "Foreign Language Search: %d", 1];
  2693. job->indepth_scan = 1;
  2694. if (burned != 1)
  2695. {
  2696. job->select_subtitle_config.dest = PASSTHRUSUB;
  2697. }
  2698. else
  2699. {
  2700. job->select_subtitle_config.dest = RENDERSUB;
  2701. }
  2702. job->select_subtitle_config.force = force;
  2703. job->select_subtitle_config.default_track = def;
  2704. }
  2705. else
  2706. {
  2707. /* for the actual source tracks, we must subtract the non source entries so
  2708. * that the menu index matches the source subtitle_list index for convenience */
  2709. if (i == 0)
  2710. {
  2711. /* for the first track, the source tracks start at menu index 2 ( None is 0,
  2712. * Foreign Language Search is 1) so subtract 2 */
  2713. subtitle = subtitle - 2;
  2714. }
  2715. else
  2716. {
  2717. /* for all other tracks, the source tracks start at menu index 1 (None is 0)
  2718. * so subtract 1. */
  2719. subtitle = subtitle - 1;
  2720. }
  2721. /* We are setting a source subtitle so access the source subtitle info */
  2722. hb_subtitle_t * subt;
  2723. subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
  2724. /* if we are getting the subtitles from an external srt file */
  2725. if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
  2726. {
  2727. hb_subtitle_config_t sub_config;
  2728. sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
  2729. /* we need to srncpy file path and char code */
  2730. strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 255);
  2731. sub_config.src_filename[255] = 0;
  2732. strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 39);
  2733. sub_config.src_codeset[39] = 0;
  2734. sub_config.force = 0;
  2735. sub_config.dest = PASSTHRUSUB;
  2736. sub_config.default_track = def;
  2737. hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
  2738. }
  2739. if (subt != NULL)
  2740. {
  2741. hb_subtitle_config_t sub_config = subt->config;
  2742. if ( !burned && subt->format == PICTURESUB )
  2743. {
  2744. sub_config.dest = PASSTHRUSUB;
  2745. }
  2746. else if ( burned && subt->format == PICTURESUB )
  2747. {
  2748. // Only allow one subtitle to be burned into the video
  2749. if (one_burned)
  2750. continue;
  2751. one_burned = TRUE;
  2752. }
  2753. /* Besides VOBSUBS we can also burn in SSA text subs */
  2754. if (subt->source == SSASUB && burned)
  2755. {
  2756. sub_config.dest = RENDERSUB;
  2757. }
  2758. sub_config.force = force;
  2759. sub_config.default_track = def;
  2760. hb_subtitle_add( job, &sub_config, subtitle );
  2761. }
  2762. }
  2763. }
  2764. i++;
  2765. }
  2766. [subtitlesArray autorelease];
  2767. /* Audio tracks and mixdowns */
  2768. [fAudioDelegate prepareAudioForJob: job];
  2769. /* Filters */
  2770. /* Though Grayscale is not really a filter, per se
  2771. * we put it here since its in the filters panel
  2772. */
  2773. if ([fPictureController grayscale])
  2774. {
  2775. job->grayscale = 1;
  2776. }
  2777. else
  2778. {
  2779. job->grayscale = 0;
  2780. }
  2781. /* Initialize the filters list */
  2782. job->filters = hb_list_init();
  2783. /* Now lets call the filters if applicable.
  2784. * The order of the filters is critical
  2785. */
  2786. /* Detelecine */
  2787. hb_filter_detelecine.settings = NULL;
  2788. if ([fPictureController detelecine] == 1)
  2789. {
  2790. /* use a custom detelecine string */
  2791. hb_filter_detelecine.settings = (char *) [[fPictureController detelecineCustomString] UTF8String];
  2792. hb_list_add( job->filters, &hb_filter_detelecine );
  2793. }
  2794. if ([fPictureController detelecine] == 2)
  2795. {
  2796. /* Default */
  2797. hb_list_add( job->filters, &hb_filter_detelecine );
  2798. }
  2799. if ([fPictureController useDecomb] == 1)
  2800. {
  2801. /* Decomb */
  2802. /* we add the custom string if present */
  2803. hb_filter_decomb.settings = NULL;
  2804. if ([fPictureController decomb] == 1)
  2805. {
  2806. /* use a custom decomb string */
  2807. hb_filter_decomb.settings = (char *) [[fPictureController decombCustomString] UTF8String];
  2808. hb_list_add( job->filters, &hb_filter_decomb );
  2809. }
  2810. if ([fPictureController decomb] == 2)
  2811. {
  2812. /* Run old deinterlacer fd by default */
  2813. //hb_filter_decomb.settings = (char *) [[fPicSettingDecomb stringValue] UTF8String];
  2814. hb_list_add( job->filters, &hb_filter_decomb );
  2815. }
  2816. }
  2817. else
  2818. {
  2819. /* Deinterlace */
  2820. if ([fPictureController deinterlace] == 1)
  2821. {
  2822. /* we add the custom string if present */
  2823. hb_filter_deinterlace.settings = (char *) [[fPictureController deinterlaceCustomString] UTF8String];
  2824. hb_list_add( job->filters, &hb_filter_deinterlace );
  2825. }
  2826. else if ([fPictureController deinterlace] == 2)
  2827. {
  2828. /* Run old deinterlacer fd by default */
  2829. hb_filter_deinterlace.settings = "-1";
  2830. hb_list_add( job->filters, &hb_filter_deinterlace );
  2831. }
  2832. else if ([fPictureController deinterlace] == 3)
  2833. {
  2834. /* Yadif mode 0 (without spatial deinterlacing.) */
  2835. hb_filter_deinterlace.settings = "2";
  2836. hb_list_add( job->filters, &hb_filter_deinterlace );
  2837. }
  2838. else if ([fPictureController deinterlace] == 4)
  2839. {
  2840. /* Yadif (with spatial deinterlacing) */
  2841. hb_filter_deinterlace.settings = "0";
  2842. hb_list_add( job->filters, &hb_filter_deinterlace );
  2843. }
  2844. }
  2845. /* Denoise */
  2846. if ([fPictureController denoise] == 1) // custom in popup
  2847. {
  2848. /* we add the custom string if present */
  2849. hb_filter_denoise.settings = (char *) [[fPictureController denoiseCustomString] UTF8String];
  2850. hb_list_add( job->filters, &hb_filter_denoise );
  2851. }
  2852. else if ([fPictureController denoise] == 2) // Weak in popup
  2853. {
  2854. hb_filter_denoise.settings = "2:1:2:3";
  2855. hb_list_add( job->filters, &hb_filter_denoise );
  2856. }
  2857. else if ([fPictureController denoise] == 3) // Medium in popup
  2858. {
  2859. hb_filter_denoise.settings = "3:2:2:3";
  2860. hb_list_add( job->filters, &hb_filter_denoise );
  2861. }
  2862. else if ([fPictureController denoise] == 4) // Strong in popup
  2863. {
  2864. hb_filter_denoise.settings = "7:7:5:5";
  2865. hb_list_add( job->filters, &hb_filter_denoise );
  2866. }
  2867. /* Deblock (uses pp7 default) */
  2868. /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
  2869. * the macgui's purposes a value of 0 actually means to not even use the filter
  2870. * current hb_filter_deblock.settings valid ranges are from 5 - 15
  2871. */
  2872. if ([fPictureController deblock] != 0)
  2873. {
  2874. NSString *deblockStringValue = [NSString stringWithFormat: @"%d",[fPictureController deblock]];
  2875. hb_filter_deblock.settings = (char *) [deblockStringValue UTF8String];
  2876. hb_list_add( job->filters, &hb_filter_deblock );
  2877. }
  2878. }
  2879. #pragma mark -
  2880. #pragma mark Job Handling
  2881. - (void) prepareJob
  2882. {
  2883. NSMutableDictionary * queueToApply = [QueueFileArray objectAtIndex:currentQueueEncodeIndex];
  2884. hb_list_t * list = hb_get_titles( fQueueEncodeLibhb );
  2885. hb_title_t * title = (hb_title_t *) hb_list_item( list,0 ); // is always zero since now its a single title scan
  2886. hb_job_t * job = title->job;
  2887. hb_audio_config_t * audio;
  2888. /* Title Angle for dvdnav */
  2889. job->angle = [[queueToApply objectForKey:@"TitleAngle"] intValue];
  2890. if([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 0)
  2891. {
  2892. /* Chapter selection */
  2893. [self writeToActivityLog: "Start / Stop set to chapters"];
  2894. job->chapter_start = [[queueToApply objectForKey:@"JobChapterStart"] intValue];
  2895. job->chapter_end = [[queueToApply objectForKey:@"JobChapterEnd"] intValue];
  2896. }
  2897. else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 1)
  2898. {
  2899. /* we are pts based start / stop */
  2900. [self writeToActivityLog: "Start / Stop set to seconds ..."];
  2901. /* Point A to Point B. Time to time in seconds.*/
  2902. /* get the start seconds from the start seconds field */
  2903. int start_seconds = [[queueToApply objectForKey:@"StartSeconds"] intValue];
  2904. job->pts_to_start = start_seconds * 90000LL;
  2905. /* Stop seconds is actually the duration of encode, so subtract the end seconds from the start seconds */
  2906. int stop_seconds = [[queueToApply objectForKey:@"StopSeconds"] intValue];
  2907. job->pts_to_stop = stop_seconds * 90000LL;
  2908. }
  2909. else if ([[queueToApply objectForKey:@"fEncodeStartStop"] intValue] == 2)
  2910. {
  2911. /* we are frame based start / stop */
  2912. [self writeToActivityLog: "Start / Stop set to frames ..."];
  2913. /* Point A to Point B. Frame to frame */
  2914. /* get the start frame from the start frame field */
  2915. int start_frame = [[queueToApply objectForKey:@"StartFrame"] intValue];
  2916. job->frame_to_start = start_frame;
  2917. /* get the frame to stop on from the end frame field */
  2918. int stop_frame = [[queueToApply objectForKey:@"StopFrame"] intValue];
  2919. job->frame_to_stop = stop_frame;
  2920. }
  2921. /* Format (Muxer) and Video Encoder */
  2922. job->mux = [[queueToApply objectForKey:@"JobFileFormatMux"] intValue];
  2923. job->vcodec = [[queueToApply objectForKey:@"JobVideoEncoderVcodec"] intValue];
  2924. /* If mpeg-4, then set mpeg-4 specific options like chapters and > 4gb file sizes */
  2925. if( [[queueToApply objectForKey:@"Mp4LargeFile"] intValue] == 1)
  2926. {
  2927. job->largeFileSize = 1;
  2928. }
  2929. else
  2930. {
  2931. job->largeFileSize = 0;
  2932. }
  2933. /* We set http optimized mp4 here */
  2934. if( [[queueToApply objectForKey:@"Mp4HttpOptimize"] intValue] == 1 )
  2935. {
  2936. job->mp4_optimize = 1;
  2937. }
  2938. else
  2939. {
  2940. job->mp4_optimize = 0;
  2941. }
  2942. /* We set the chapter marker extraction here based on the format being
  2943. mpeg4 or mkv and the checkbox being checked */
  2944. if ([[queueToApply objectForKey:@"ChapterMarkers"] intValue] == 1)
  2945. {
  2946. job->chapter_markers = 1;
  2947. /* now lets get our saved chapter names out the array in the queue file
  2948. * and insert them back into the title chapter list. We have it here,
  2949. * because unless we are inserting chapter markers there is no need to
  2950. * spend the overhead of iterating through the chapter names array imo
  2951. * Also, note that if for some reason we don't apply chapter names, the
  2952. * chapters just come out 001, 002, etc. etc.
  2953. */
  2954. NSMutableArray *ChapterNamesArray = [queueToApply objectForKey:@"ChapterNames"];
  2955. int i = 0;
  2956. NSEnumerator *enumerator = [ChapterNamesArray objectEnumerator];
  2957. id tempObject;
  2958. while (tempObject = [enumerator nextObject])
  2959. {
  2960. hb_chapter_t *chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
  2961. if( chapter != NULL )
  2962. {
  2963. strncpy( chapter->title, [tempObject UTF8String], 1023);
  2964. chapter->title[1023] = '\0';
  2965. }
  2966. i++;
  2967. }
  2968. }
  2969. else
  2970. {
  2971. job->chapter_markers = 0;
  2972. }
  2973. if( job->vcodec & HB_VCODEC_X264 )
  2974. {
  2975. if ([[queueToApply objectForKey:@"Mp4iPodCompatible"] intValue] == 1)
  2976. {
  2977. job->ipod_atom = 1;
  2978. }
  2979. else
  2980. {
  2981. job->ipod_atom = 0;
  2982. }
  2983. /* Below Sends x264 options to the core library if x264 is selected*/
  2984. /* Lets use this as per Nyx, Thanks Nyx!*/
  2985. job->x264opts = (char *)calloc(1024, 1); /* Fixme, this just leaks */
  2986. /* Turbo first pass if two pass and Turbo First pass is selected */
  2987. if( [[queueToApply objectForKey:@"VideoTwoPass"] intValue] == 1 && [[queueToApply objectForKey:@"VideoTurboTwoPass"] intValue] == 1 )
  2988. {
  2989. /* pass the "Turbo" string to be appended to the existing x264 opts string into a variable for the first pass */
  2990. NSString *firstPassOptStringTurbo = @":ref=1:subme=2:me=dia:analyse=none:trellis=0:no-fast-pskip=0:8x8dct=0:weightb=0";
  2991. /* append the "Turbo" string variable to the existing opts string.
  2992. Note: the "Turbo" string must be appended, not prepended to work properly*/
  2993. NSString *firstPassOptStringCombined = [[queueToApply objectForKey:@"x264Option"] stringByAppendingString:firstPassOptStringTurbo];
  2994. strcpy(job->x264opts, [firstPassOptStringCombined UTF8String]);
  2995. }
  2996. else
  2997. {
  2998. strcpy(job->x264opts, [[queueToApply objectForKey:@"x264Option"] UTF8String]);
  2999. }
  3000. }
  3001. /* Picture Size Settings */
  3002. job->width = [[queueToApply objectForKey:@"PictureWidth"] intValue];
  3003. job->height = [[queueToApply objectForKey:@"PictureHeight"] intValue];
  3004. job->keep_ratio = [[queueToApply objectForKey:@"PictureKeepRatio"] intValue];
  3005. job->anamorphic.mode = [[queueToApply objectForKey:@"PicturePAR"] intValue];
  3006. job->modulus = [[queueToApply objectForKey:@"PictureModulus"] intValue];
  3007. if ([[queueToApply objectForKey:@"PicturePAR"] intValue] == 3)
  3008. {
  3009. /* insert our custom values here for capuj */
  3010. job->width = [[queueToApply objectForKey:@"PicturePARStorageWidth"] intValue];
  3011. job->height = [[queueToApply objectForKey:@"PicturePARStorageHeight"] intValue];
  3012. job->modulus = [[queueToApply objectForKey:@"PicturePARModulus"] intValue];
  3013. job->anamorphic.par_width = [[queueToApply objectForKey:@"PicturePARPixelWidth"] intValue];
  3014. job->anamorphic.par_height = [[queueToApply objectForKey:@"PicturePARPixelHeight"] intValue];
  3015. job->anamorphic.dar_width = [[queueToApply objectForKey:@"PicturePARDisplayWidth"] floatValue];
  3016. job->anamorphic.dar_height = [[queueToApply objectForKey:@"PicturePARDisplayHeight"] floatValue];
  3017. }
  3018. /* Here we use the crop values saved at the time the preset was saved */
  3019. job->crop[0] = [[queueToApply objectForKey:@"PictureTopCrop"] intValue];
  3020. job->crop[1] = [[queueToApply objectForKey:@"PictureBottomCrop"] intValue];
  3021. job->crop[2] = [[queueToApply objectForKey:@"PictureLeftCrop"] intValue];
  3022. job->crop[3] = [[queueToApply objectForKey:@"PictureRightCrop"] intValue];
  3023. /* Video settings */
  3024. /* Framerate */
  3025. /* Set vfr to 0 as it's only on if using same as source in the framerate popup
  3026. * and detelecine is on, so we handle that in the logic below
  3027. */
  3028. job->vfr = 0;
  3029. if( [[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue] > 0 )
  3030. {
  3031. /* a specific framerate has been chosen */
  3032. job->vrate = 27000000;
  3033. job->vrate_base = hb_video_rates[[[queueToApply objectForKey:@"JobIndexVideoFramerate"] intValue]-1].rate;
  3034. /* We are not same as source so we set job->cfr to 1
  3035. * to enable constant frame rate since user has specified
  3036. * a specific framerate*/
  3037. if ([[queueToApply objectForKey:@"VideoFrameratePFR"] intValue] == 1)
  3038. {
  3039. job->cfr = 2;
  3040. }
  3041. else
  3042. {
  3043. job->cfr = 1;
  3044. }
  3045. }
  3046. else
  3047. {
  3048. /* We are same as source (variable) */
  3049. job->vrate = [[queueToApply objectForKey:@"JobVrate"] intValue];
  3050. job->vrate_base = [[queueToApply objectForKey:@"JobVrateBase"] intValue];
  3051. /* We are same as source so we set job->cfr to 0
  3052. * to enable true same as source framerate */
  3053. job->cfr = 0;
  3054. /* If we are same as source and we have detelecine on, we need to turn on
  3055. * job->vfr
  3056. */
  3057. if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
  3058. {
  3059. job->vfr = 1;
  3060. }
  3061. }
  3062. if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] != 2 )
  3063. {
  3064. /* Target size.
  3065. Bitrate should already have been calculated and displayed
  3066. in fVidBitrateField, so let's just use it same as abr*/
  3067. job->vquality = -1.0;
  3068. job->vbitrate = [[queueToApply objectForKey:@"VideoAvgBitrate"] intValue];
  3069. }
  3070. if ( [[queueToApply objectForKey:@"VideoQualityType"] intValue] == 2 )
  3071. {
  3072. job->vquality = [[queueToApply objectForKey:@"VideoQualitySlider"] floatValue];
  3073. job->vbitrate = 0;
  3074. }
  3075. job->grayscale = [[queueToApply objectForKey:@"VideoGrayScale"] intValue];
  3076. #pragma mark -
  3077. #pragma mark Process Subtitles to libhb
  3078. /* Map the settings in the dictionaries for the SubtitleList array to match title->list_subtitle
  3079. * which means that we need to account for the offset of non source language settings in from
  3080. * the NSPopUpCell menu. For all of the objects in the SubtitleList array this means 0 is "None"
  3081. * from the popup menu, additionally the first track has "Foreign Audio Search" at 1. So we use
  3082. * an int to offset the index number for the objectForKey:@"subtitleSourceTrackNum" to map that
  3083. * to the source tracks position in title->list_subtitle.
  3084. */
  3085. int subtitle = nil;
  3086. int force;
  3087. int burned;
  3088. int def;
  3089. bool one_burned = FALSE;
  3090. int i = 0;
  3091. NSEnumerator *enumerator = [[queueToApply objectForKey:@"SubtitleList"] objectEnumerator];
  3092. id tempObject;
  3093. while (tempObject = [enumerator nextObject])
  3094. {
  3095. subtitle = [[tempObject objectForKey:@"subtitleSourceTrackNum"] intValue];
  3096. force = [[tempObject objectForKey:@"subtitleTrackForced"] intValue];
  3097. burned = [[tempObject objectForKey:@"subtitleTrackBurned"] intValue];
  3098. def = [[tempObject objectForKey:@"subtitleTrackDefault"] intValue];
  3099. /* since the subtitleSourceTrackNum 0 is "None" in our array of the subtitle popups,
  3100. * we want to ignore it for display as well as encoding.
  3101. */
  3102. if (subtitle > 0)
  3103. {
  3104. /* if i is 0, then we are in the first item of the subtitles which we need to
  3105. * check for the "Foreign Audio Search" which would be subtitleSourceTrackNum of 1
  3106. * bearing in mind that for all tracks subtitleSourceTrackNum of 0 is None.
  3107. */
  3108. /* if we are on the first track and using "Foreign Audio Search" */
  3109. if (i == 0 && subtitle == 1)
  3110. {
  3111. [self writeToActivityLog: "Foreign Language Search: %d", 1];
  3112. job->indepth_scan = 1;
  3113. if (burned != 1)
  3114. {
  3115. job->select_subtitle_config.dest = PASSTHRUSUB;
  3116. }
  3117. else
  3118. {
  3119. job->select_subtitle_config.dest = RENDERSUB;
  3120. }
  3121. job->select_subtitle_config.force = force;
  3122. job->select_subtitle_config.default_track = def;
  3123. }
  3124. else
  3125. {
  3126. /* for the actual source tracks, we must subtract the non source entries so
  3127. * that the menu index matches the source subtitle_list index for convenience */
  3128. if (i == 0)
  3129. {
  3130. /* for the first track, the source tracks start at menu index 2 ( None is 0,
  3131. * Foreign Language Search is 1) so subtract 2 */
  3132. subtitle = subtitle - 2;
  3133. }
  3134. else
  3135. {
  3136. /* for all other tracks, the source tracks start at menu index 1 (None is 0)
  3137. * so subtract 1. */
  3138. subtitle = subtitle - 1;
  3139. }
  3140. /* We are setting a source subtitle so access the source subtitle info */
  3141. hb_subtitle_t * subt;
  3142. subt = (hb_subtitle_t *)hb_list_item(title->list_subtitle, subtitle);
  3143. /* if we are getting the subtitles from an external srt file */
  3144. if ([[tempObject objectForKey:@"subtitleSourceTrackType"] isEqualToString:@"SRT"])
  3145. {
  3146. hb_subtitle_config_t sub_config;
  3147. sub_config.offset = [[tempObject objectForKey:@"subtitleTrackSrtOffset"] intValue];
  3148. /* we need to srncpy file name and codeset */
  3149. strncpy(sub_config.src_filename, [[tempObject objectForKey:@"subtitleSourceSrtFilePath"] UTF8String], 128);
  3150. strncpy(sub_config.src_codeset, [[tempObject objectForKey:@"subtitleTrackSrtCharCode"] UTF8String], 40);
  3151. sub_config.force = 0;
  3152. sub_config.dest = PASSTHRUSUB;
  3153. sub_config.default_track = def;
  3154. hb_srt_add( job, &sub_config, [[tempObject objectForKey:@"subtitleTrackSrtLanguageIso3"] UTF8String]);
  3155. }
  3156. if (subt != NULL)
  3157. {
  3158. hb_subtitle_config_t sub_config = subt->config;
  3159. if ( !burned && subt->format == PICTURESUB )
  3160. {
  3161. sub_config.dest = PASSTHRUSUB;
  3162. }
  3163. else if ( burned )
  3164. {
  3165. // Only allow one subtitle to be burned into the video
  3166. if (one_burned)
  3167. continue;
  3168. one_burned = TRUE;
  3169. }
  3170. /* Besides VOBSUBS we can also burn in SSA text subs */
  3171. if (subt->source == SSASUB && burned)
  3172. {
  3173. sub_config.dest = RENDERSUB;
  3174. }
  3175. sub_config.force = force;
  3176. sub_config.default_track = def;
  3177. hb_subtitle_add( job, &sub_config, subtitle );
  3178. }
  3179. }
  3180. }
  3181. i++;
  3182. }
  3183. #pragma mark -
  3184. /* Audio tracks and mixdowns */
  3185. /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
  3186. int audiotrack_count = hb_list_count(job->list_audio);
  3187. for( int i = 0; i < audiotrack_count;i++)
  3188. {
  3189. hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
  3190. hb_list_rem(job->list_audio, temp_audio);
  3191. }
  3192. /* Now lets add our new tracks to the audio list here */
  3193. for (unsigned int counter = 0; counter < maximumNumberOfAllowedAudioTracks; counter++) {
  3194. NSString *prefix = [NSString stringWithFormat: @"Audio%d", counter + 1];
  3195. if ([[queueToApply objectForKey: [prefix stringByAppendingString: @"Track"]] intValue] > 0) {
  3196. audio = (hb_audio_config_t *) calloc(1, sizeof(*audio));
  3197. hb_audio_config_init(audio);
  3198. audio->in.track = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Track"]] intValue] - 1;
  3199. /* We go ahead and assign values to our audio->out.<properties> */
  3200. audio->out.track = audio->in.track;
  3201. audio->out.dynamic_range_compression = [[queueToApply objectForKey: [prefix stringByAppendingString: @"TrackDRCSlider"]] floatValue];
  3202. prefix = [NSString stringWithFormat: @"JobAudio%d", counter + 1];
  3203. audio->out.codec = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Encoder"]] intValue];
  3204. audio->out.mixdown = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Mixdown"]] intValue];
  3205. audio->out.bitrate = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Bitrate"]] intValue];
  3206. audio->out.samplerate = [[queueToApply objectForKey: [prefix stringByAppendingString: @"Samplerate"]] intValue];
  3207. hb_audio_add( job, audio );
  3208. free(audio);
  3209. }
  3210. }
  3211. /* Filters */
  3212. job->filters = hb_list_init();
  3213. /* Now lets call the filters if applicable.
  3214. * The order of the filters is critical
  3215. */
  3216. /* Detelecine */
  3217. hb_filter_detelecine.settings = NULL;
  3218. if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 1)
  3219. {
  3220. /* use a custom detelecine string */
  3221. hb_filter_detelecine.settings = (char *) [[queueToApply objectForKey:@"PictureDetelecineCustom"] UTF8String];
  3222. hb_list_add( job->filters, &hb_filter_detelecine );
  3223. }
  3224. if ([[queueToApply objectForKey:@"PictureDetelecine"] intValue] == 2)
  3225. {
  3226. /* Use libhb's default values */
  3227. hb_list_add( job->filters, &hb_filter_detelecine );
  3228. }
  3229. if ([[queueToApply objectForKey:@"PictureDecombDeinterlace"] intValue] == 1)
  3230. {
  3231. /* Decomb */
  3232. /* we add the custom string if present */
  3233. hb_filter_decomb.settings = NULL;
  3234. if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 1)
  3235. {
  3236. /* use a custom decomb string */
  3237. hb_filter_decomb.settings = (char *) [[queueToApply objectForKey:@"PictureDecombCustom"] UTF8String];
  3238. hb_list_add( job->filters, &hb_filter_decomb );
  3239. }
  3240. if ([[queueToApply objectForKey:@"PictureDecomb"] intValue] == 2)
  3241. {
  3242. /* Use libhb default */
  3243. hb_list_add( job->filters, &hb_filter_decomb );
  3244. }
  3245. }
  3246. else
  3247. {
  3248. /* Deinterlace */
  3249. if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 1)
  3250. {
  3251. /* we add the custom string if present */
  3252. hb_filter_deinterlace.settings = (char *) [[queueToApply objectForKey:@"PictureDeinterlaceCustom"] UTF8String];
  3253. hb_list_add( job->filters, &hb_filter_deinterlace );
  3254. }
  3255. else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 2)
  3256. {
  3257. /* Run old deinterlacer fd by default */
  3258. hb_filter_deinterlace.settings = "-1";
  3259. hb_list_add( job->filters, &hb_filter_deinterlace );
  3260. }
  3261. else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 3)
  3262. {
  3263. /* Yadif mode 0 (without spatial deinterlacing.) */
  3264. hb_filter_deinterlace.settings = "2";
  3265. hb_list_add( job->filters, &hb_filter_deinterlace );
  3266. }
  3267. else if ([[queueToApply objectForKey:@"PictureDeinterlace"] intValue] == 4)
  3268. {
  3269. /* Yadif (with spatial deinterlacing) */
  3270. hb_filter_deinterlace.settings = "0";
  3271. hb_list_add( job->filters, &hb_filter_deinterlace );
  3272. }
  3273. }
  3274. /* Denoise */
  3275. if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 1) // Custom in popup
  3276. {
  3277. /* we add the custom string if present */
  3278. hb_filter_denoise.settings = (char *) [[queueToApply objectForKey:@"PictureDenoiseCustom"] UTF8String];
  3279. hb_list_add( job->filters, &hb_filter_denoise );
  3280. }
  3281. else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 2) // Weak in popup
  3282. {
  3283. hb_filter_denoise.settings = "2:1:2:3";
  3284. hb_list_add( job->filters, &hb_filter_denoise );
  3285. }
  3286. else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 3) // Medium in popup
  3287. {
  3288. hb_filter_denoise.settings = "3:2:2:3";
  3289. hb_list_add( job->filters, &hb_filter_denoise );
  3290. }
  3291. else if ([[queueToApply objectForKey:@"PictureDenoise"] intValue] == 4) // Strong in popup
  3292. {
  3293. hb_filter_denoise.settings = "7:7:5:5";
  3294. hb_list_add( job->filters, &hb_filter_denoise );
  3295. }
  3296. /* Deblock (uses pp7 default) */
  3297. /* NOTE: even though there is a valid deblock setting of 0 for the filter, for
  3298. * the macgui's purposes a value of 0 actually means to not even use the filter
  3299. * current hb_filter_deblock.settings valid ranges are from 5 - 15
  3300. */
  3301. if ([[queueToApply objectForKey:@"PictureDeblock"] intValue] != 0)
  3302. {
  3303. hb_filter_deblock.settings = (char *) [[queueToApply objectForKey:@"PictureDeblock"] UTF8String];
  3304. hb_list_add( job->filters, &hb_filter_deblock );
  3305. }
  3306. [self writeToActivityLog: "prepareJob exiting"];
  3307. }
  3308. /* addToQueue: puts up an alert before ultimately calling doAddToQueue
  3309. */
  3310. - (IBAction) addToQueue: (id) sender
  3311. {
  3312. /* We get the destination directory from the destination field here */
  3313. NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
  3314. /* We check for a valid destination here */
  3315. if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
  3316. {
  3317. NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
  3318. return;
  3319. }
  3320. BOOL fileExists;
  3321. fileExists = NO;
  3322. BOOL fileExistsInQueue;
  3323. fileExistsInQueue = NO;
  3324. /* We check for and existing file here */
  3325. if([[NSFileManager defaultManager] fileExistsAtPath: [fDstFile2Field stringValue]])
  3326. {
  3327. fileExists = YES;
  3328. }
  3329. /* We now run through the queue and make sure we are not overwriting an exisiting queue item */
  3330. int i = 0;
  3331. NSEnumerator *enumerator = [QueueFileArray objectEnumerator];
  3332. id tempObject;
  3333. while (tempObject = [enumerator nextObject])
  3334. {
  3335. NSDictionary *thisQueueDict = tempObject;
  3336. if ([[thisQueueDict objectForKey:@"DestinationPath"] isEqualToString: [fDstFile2Field stringValue]])
  3337. {
  3338. fileExistsInQueue = YES;
  3339. }
  3340. i++;
  3341. }
  3342. if(fileExists == YES)
  3343. {
  3344. NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists.", @"" ),
  3345. NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
  3346. @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
  3347. NULL, NULL, [NSString stringWithFormat:
  3348. NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
  3349. [fDstFile2Field stringValue]] );
  3350. }
  3351. else if (fileExistsInQueue == YES)
  3352. {
  3353. NSBeginCriticalAlertSheet( NSLocalizedString( @"There is already a queue item for this destination.", @"" ),
  3354. NSLocalizedString( @"Cancel", @"" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
  3355. @selector( overwriteAddToQueueAlertDone:returnCode:contextInfo: ),
  3356. NULL, NULL, [NSString stringWithFormat:
  3357. NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
  3358. [fDstFile2Field stringValue]] );
  3359. }
  3360. else
  3361. {
  3362. [self doAddToQueue];
  3363. }
  3364. }
  3365. /* overwriteAddToQueueAlertDone: called from the alert posted by addToQueue that asks
  3366. the user if they want to overwrite an exiting movie file.
  3367. */
  3368. - (void) overwriteAddToQueueAlertDone: (NSWindow *) sheet
  3369. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  3370. {
  3371. if( returnCode == NSAlertAlternateReturn )
  3372. [self doAddToQueue];
  3373. }
  3374. - (void) doAddToQueue
  3375. {
  3376. [self addQueueFileItem ];
  3377. }
  3378. /* Rip: puts up an alert before ultimately calling doRip
  3379. */
  3380. - (IBAction) Rip: (id) sender
  3381. {
  3382. [self writeToActivityLog: "Rip: Pending queue count is %d", fPendingCount];
  3383. /* Rip or Cancel ? */
  3384. hb_state_t s;
  3385. hb_get_state2( fQueueEncodeLibhb, &s );
  3386. if(s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED)
  3387. {
  3388. [self Cancel: sender];
  3389. return;
  3390. }
  3391. /* We check to see if we need to warn the user that the computer will go to sleep
  3392. or shut down when encoding is finished */
  3393. [self remindUserOfSleepOrShutdown];
  3394. // If there are pending jobs in the queue, then this is a rip the queue
  3395. if (fPendingCount > 0)
  3396. {
  3397. currentQueueEncodeIndex = [self getNextPendingQueueIndex];
  3398. /* here lets start the queue with the first pending item */
  3399. [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
  3400. return;
  3401. }
  3402. // Before adding jobs to the queue, check for a valid destination.
  3403. NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
  3404. if ([[NSFileManager defaultManager] fileExistsAtPath:destinationDirectory] == 0)
  3405. {
  3406. NSRunAlertPanel(@"Warning!", @"This is not a valid destination directory!", @"OK", nil, nil);
  3407. return;
  3408. }
  3409. /* We check for duplicate name here */
  3410. if( [[NSFileManager defaultManager] fileExistsAtPath:[fDstFile2Field stringValue]] )
  3411. {
  3412. NSBeginCriticalAlertSheet( NSLocalizedString( @"File already exists", @"" ),
  3413. NSLocalizedString( @"Cancel", "" ), NSLocalizedString( @"Overwrite", @"" ), nil, fWindow, self,
  3414. @selector( overWriteAlertDone:returnCode:contextInfo: ),
  3415. NULL, NULL, [NSString stringWithFormat:
  3416. NSLocalizedString( @"Do you want to overwrite %@?", @"" ),
  3417. [fDstFile2Field stringValue]] );
  3418. // overWriteAlertDone: will be called when the alert is dismissed. It will call doRip.
  3419. }
  3420. else
  3421. {
  3422. /* if there are no pending jobs in the queue, then add this one to the queue and rip
  3423. otherwise, just rip the queue */
  3424. if(fPendingCount == 0)
  3425. {
  3426. [self doAddToQueue];
  3427. }
  3428. /* go right to processing the new queue encode */
  3429. currentQueueEncodeIndex = [self getNextPendingQueueIndex];
  3430. [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
  3431. }
  3432. }
  3433. /* overWriteAlertDone: called from the alert posted by Rip: that asks the user if they
  3434. want to overwrite an exiting movie file.
  3435. */
  3436. - (void) overWriteAlertDone: (NSWindow *) sheet
  3437. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  3438. {
  3439. if( returnCode == NSAlertAlternateReturn )
  3440. {
  3441. /* if there are no jobs in the queue, then add this one to the queue and rip
  3442. otherwise, just rip the queue */
  3443. if( fPendingCount == 0 )
  3444. {
  3445. [self doAddToQueue];
  3446. }
  3447. NSString *destinationDirectory = [[fDstFile2Field stringValue] stringByDeletingLastPathComponent];
  3448. [[NSUserDefaults standardUserDefaults] setObject:destinationDirectory forKey:@"LastDestinationDirectory"];
  3449. currentQueueEncodeIndex = [self getNextPendingQueueIndex];
  3450. [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
  3451. }
  3452. }
  3453. - (void) remindUserOfSleepOrShutdown
  3454. {
  3455. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Put Computer To Sleep"])
  3456. {
  3457. /*Warn that computer will sleep after encoding*/
  3458. int reminduser;
  3459. NSBeep();
  3460. 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);
  3461. [NSApp requestUserAttention:NSCriticalRequest];
  3462. if ( reminduser == NSAlertAlternateReturn )
  3463. {
  3464. [self showPreferencesWindow:nil];
  3465. }
  3466. }
  3467. else if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AlertWhenDone"] isEqualToString: @"Shut Down Computer"])
  3468. {
  3469. /*Warn that computer will shut down after encoding*/
  3470. int reminduser;
  3471. NSBeep();
  3472. 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);
  3473. [NSApp requestUserAttention:NSCriticalRequest];
  3474. if ( reminduser == NSAlertAlternateReturn )
  3475. {
  3476. [self showPreferencesWindow:nil];
  3477. }
  3478. }
  3479. }
  3480. - (void) doRip
  3481. {
  3482. /* Let libhb do the job */
  3483. hb_start( fQueueEncodeLibhb );
  3484. /*set the fEncodeState State */
  3485. fEncodeState = 1;
  3486. }
  3487. //------------------------------------------------------------------------------------
  3488. // Displays an alert asking user if the want to cancel encoding of current job.
  3489. // Cancel: returns immediately after posting the alert. Later, when the user
  3490. // acknowledges the alert, doCancelCurrentJob is called.
  3491. //------------------------------------------------------------------------------------
  3492. - (IBAction)Cancel: (id)sender
  3493. {
  3494. if (!fQueueController) return;
  3495. hb_pause( fQueueEncodeLibhb );
  3496. NSString * alertTitle = [NSString stringWithFormat:NSLocalizedString(@"You are currently encoding. What would you like to do ?", nil)];
  3497. // Which window to attach the sheet to?
  3498. NSWindow * docWindow;
  3499. if ([sender respondsToSelector: @selector(window)])
  3500. docWindow = [sender window];
  3501. else
  3502. docWindow = fWindow;
  3503. NSBeginCriticalAlertSheet(
  3504. alertTitle,
  3505. NSLocalizedString(@"Continue Encoding", nil),
  3506. NSLocalizedString(@"Cancel Current and Stop", nil),
  3507. NSLocalizedString(@"Cancel Current and Continue", nil),
  3508. docWindow, self,
  3509. nil, @selector(didDimissCancel:returnCode:contextInfo:), nil,
  3510. NSLocalizedString(@"Your encode will be cancelled if you don't continue encoding.", nil));
  3511. // didDimissCancelCurrentJob:returnCode:contextInfo: will be called when the dialog is dismissed
  3512. }
  3513. - (void) didDimissCancel: (NSWindow *)sheet returnCode: (int)returnCode contextInfo: (void *)contextInfo
  3514. {
  3515. hb_resume( fQueueEncodeLibhb );
  3516. if (returnCode == NSAlertOtherReturn)
  3517. {
  3518. [self doCancelCurrentJob]; // <- this also stops libhb
  3519. }
  3520. if (returnCode == NSAlertAlternateReturn)
  3521. {
  3522. [self doCancelCurrentJobAndStop];
  3523. }
  3524. }
  3525. //------------------------------------------------------------------------------------
  3526. // Cancels and deletes the current job and stops libhb from processing the remaining
  3527. // encodes.
  3528. //------------------------------------------------------------------------------------
  3529. - (void) doCancelCurrentJob
  3530. {
  3531. // Stop the current job. hb_stop will only cancel the current pass and then set
  3532. // its state to HB_STATE_WORKDONE. It also does this asynchronously. So when we
  3533. // see the state has changed to HB_STATE_WORKDONE (in updateUI), we'll delete the
  3534. // remaining passes of the job and then start the queue back up if there are any
  3535. // remaining jobs.
  3536. hb_stop( fQueueEncodeLibhb );
  3537. // Delete all remaining jobs since libhb doesn't do this on its own.
  3538. hb_job_t * job;
  3539. while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
  3540. hb_rem( fQueueEncodeLibhb, job );
  3541. fEncodeState = 2; // don't alert at end of processing since this was a cancel
  3542. // now that we've stopped the currently encoding job, lets mark it as cancelled
  3543. [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
  3544. // and as always, save it in the queue .plist...
  3545. /* We save all of the Queue data here */
  3546. [self saveQueueFileItem];
  3547. // ... and see if there are more items left in our queue
  3548. int queueItems = [QueueFileArray count];
  3549. /* If we still have more items in our queue, lets go to the next one */
  3550. /* Check to see if there are any more pending items in the queue */
  3551. int newQueueItemIndex = [self getNextPendingQueueIndex];
  3552. /* If we still have more pending items in our queue, lets go to the next one */
  3553. if (newQueueItemIndex >= 0 && newQueueItemIndex < queueItems)
  3554. {
  3555. /*Set our currentQueueEncodeIndex now to the newly found Pending encode as we own it */
  3556. currentQueueEncodeIndex = newQueueItemIndex;
  3557. /* now we mark the queue item as Status = 1 ( being encoded ) so another instance can not come along and try to scan it while we are scanning */
  3558. [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:1] forKey:@"Status"];
  3559. [self writeToActivityLog: "incrementQueueItemDone new pending items found: %d", currentQueueEncodeIndex];
  3560. [self saveQueueFileItem];
  3561. /* now we can go ahead and scan the new pending queue item */
  3562. [self performNewQueueScan:[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"SourcePath"] scanTitleNum:[[[QueueFileArray objectAtIndex:currentQueueEncodeIndex] objectForKey:@"TitleNumber"]intValue]];
  3563. }
  3564. else
  3565. {
  3566. [self writeToActivityLog: "incrementQueueItemDone there are no more pending encodes"];
  3567. }
  3568. }
  3569. - (void) doCancelCurrentJobAndStop
  3570. {
  3571. hb_stop( fQueueEncodeLibhb );
  3572. // Delete all remaining jobs since libhb doesn't do this on its own.
  3573. hb_job_t * job;
  3574. while( ( job = hb_job(fQueueEncodeLibhb, 0) ) )
  3575. hb_rem( fQueueEncodeLibhb, job );
  3576. fEncodeState = 2; // don't alert at end of processing since this was a cancel
  3577. // now that we've stopped the currently encoding job, lets mark it as cancelled
  3578. [[QueueFileArray objectAtIndex:currentQueueEncodeIndex] setObject:[NSNumber numberWithInt:3] forKey:@"Status"];
  3579. // and as always, save it in the queue .plist...
  3580. /* We save all of the Queue data here */
  3581. [self saveQueueFileItem];
  3582. // so now lets move to
  3583. currentQueueEncodeIndex++ ;
  3584. [self writeToActivityLog: "cancelling current job and stopping the queue"];
  3585. }
  3586. - (IBAction) Pause: (id) sender
  3587. {
  3588. hb_state_t s;
  3589. hb_get_state2( fQueueEncodeLibhb, &s );
  3590. if( s.state == HB_STATE_PAUSED )
  3591. {
  3592. hb_resume( fQueueEncodeLibhb );
  3593. }
  3594. else
  3595. {
  3596. hb_pause( fQueueEncodeLibhb );
  3597. }
  3598. }
  3599. #pragma mark -
  3600. #pragma mark GUI Controls Changed Methods
  3601. - (IBAction) titlePopUpChanged: (id) sender
  3602. {
  3603. hb_list_t * list = hb_get_titles( fHandle );
  3604. hb_title_t * title = (hb_title_t*)
  3605. hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
  3606. /* If we are a stream type and a batch scan, grok the output file name from title->name upon title change */
  3607. if (title->type == HB_STREAM_TYPE && hb_list_count( list ) > 1 )
  3608. {
  3609. /* we set the default name according to the new title->name */
  3610. [fDstFile2Field setStringValue: [NSString stringWithFormat:
  3611. @"%@/%@.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
  3612. [NSString stringWithUTF8String: title->name],
  3613. [[fDstFile2Field stringValue] pathExtension]]];
  3614. /* Change the source to read out the parent folder also */
  3615. [fSrcDVD2Field setStringValue:[NSString stringWithFormat:@"%@/%@", browsedSourceDisplayName,[NSString stringWithUTF8String: title->name]]];
  3616. }
  3617. /* For point a to point b pts encoding, set the start and end fields to 0 and the title duration in seconds respectively */
  3618. int duration = (title->hours * 3600) + (title->minutes * 60) + (title->seconds);
  3619. [fSrcTimeStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 0]];
  3620. [fSrcTimeEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration]];
  3621. /* For point a to point b frame encoding, set the start and end fields to 0 and the title duration * announced fps in seconds respectively */
  3622. [fSrcFrameStartEncodingField setStringValue: [NSString stringWithFormat: @"%d", 1]];
  3623. //[fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", ((title->hours * 3600) + (title->minutes * 60) + (title->seconds)) * 24]];
  3624. [fSrcFrameEndEncodingField setStringValue: [NSString stringWithFormat: @"%d", duration * (title->rate / title->rate_base)]];
  3625. /* If Auto Naming is on. We create an output filename of dvd name - title number */
  3626. if( [[NSUserDefaults standardUserDefaults] boolForKey:@"DefaultAutoNaming"] > 0 && ( hb_list_count( list ) > 1 ) )
  3627. {
  3628. [fDstFile2Field setStringValue: [NSString stringWithFormat:
  3629. @"%@/%@-%d.%@", [[fDstFile2Field stringValue] stringByDeletingLastPathComponent],
  3630. [browsedSourceDisplayName stringByDeletingPathExtension],
  3631. title->index,
  3632. [[fDstFile2Field stringValue] pathExtension]]];
  3633. }
  3634. /* Update encode start / stop variables */
  3635. /* Update chapter popups */
  3636. [fSrcChapterStartPopUp removeAllItems];
  3637. [fSrcChapterEndPopUp removeAllItems];
  3638. for( int i = 0; i < hb_list_count( title->list_chapter ); i++ )
  3639. {
  3640. [fSrcChapterStartPopUp addItemWithTitle: [NSString
  3641. stringWithFormat: @"%d", i + 1]];
  3642. [fSrcChapterEndPopUp addItemWithTitle: [NSString
  3643. stringWithFormat: @"%d", i + 1]];
  3644. }
  3645. [fSrcChapterStartPopUp selectItemAtIndex: 0];
  3646. [fSrcChapterEndPopUp selectItemAtIndex:
  3647. hb_list_count( title->list_chapter ) - 1];
  3648. [self chapterPopUpChanged:nil];
  3649. /* if using dvd nav, show the angle widget */
  3650. if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UseDvdNav"] boolValue])
  3651. {
  3652. [fSrcAngleLabel setHidden:NO];
  3653. [fSrcAnglePopUp setHidden:NO];
  3654. [fSrcAnglePopUp removeAllItems];
  3655. for( int i = 0; i < title->angle_count; i++ )
  3656. {
  3657. [fSrcAnglePopUp addItemWithTitle: [NSString stringWithFormat: @"%d", i + 1]];
  3658. }
  3659. [fSrcAnglePopUp selectItemAtIndex: 0];
  3660. }
  3661. else
  3662. {
  3663. [fSrcAngleLabel setHidden:YES];
  3664. [fSrcAnglePopUp setHidden:YES];
  3665. }
  3666. /* Start Get and set the initial pic size for display */
  3667. hb_job_t * job = title->job;
  3668. fTitle = title;
  3669. /* Set Auto Crop to on upon selecting a new title */
  3670. [fPictureController setAutoCrop:YES];
  3671. /* We get the originial output picture width and height and put them
  3672. in variables for use with some presets later on */
  3673. PicOrigOutputWidth = job->width;
  3674. PicOrigOutputHeight = job->height;
  3675. AutoCropTop = job->crop[0];
  3676. AutoCropBottom = job->crop[1];
  3677. AutoCropLeft = job->crop[2];
  3678. AutoCropRight = job->crop[3];
  3679. /* Reset the new title in fPictureController && fPreviewController*/
  3680. [fPictureController SetTitle:title];
  3681. /* Update Subtitle Table */
  3682. [fSubtitlesDelegate resetWithTitle:title];
  3683. [fSubtitlesTable reloadData];
  3684. /* Update chapter table */
  3685. [fChapterTitlesDelegate resetWithTitle:title];
  3686. [fChapterTable reloadData];
  3687. /* Update audio table */
  3688. [[NSNotificationCenter defaultCenter] postNotification:
  3689. [NSNotification notificationWithName: HBTitleChangedNotification
  3690. object: self
  3691. userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
  3692. [NSData dataWithBytesNoCopy: &fTitle length: sizeof(fTitle) freeWhenDone: NO], keyTitleTag,
  3693. nil]]];
  3694. /* Lets make sure there arent any erroneous audio tracks in the job list, so lets make sure its empty*/
  3695. int audiotrack_count = hb_list_count(job->list_audio);
  3696. for( int i = 0; i < audiotrack_count;i++)
  3697. {
  3698. hb_audio_t * temp_audio = (hb_audio_t*) hb_list_item( job->list_audio, 0 );
  3699. hb_list_rem(job->list_audio, temp_audio);
  3700. }
  3701. [fVidRatePopUp selectItemAtIndex: 0];
  3702. /* we run the picture size values through calculatePictureSizing to get all picture setting information*/
  3703. [self calculatePictureSizing:nil];
  3704. /* lets call tableViewSelected to make sure that any preset we have selected is enforced after a title change */
  3705. [self selectPreset:nil];
  3706. }
  3707. - (IBAction) encodeStartStopPopUpChanged: (id) sender;
  3708. {
  3709. if( [fEncodeStartStopPopUp isEnabled] )
  3710. {
  3711. /* We are chapters */
  3712. if( [fEncodeStartStopPopUp indexOfSelectedItem] == 0 )
  3713. {
  3714. [fSrcChapterStartPopUp setHidden: NO];
  3715. [fSrcChapterEndPopUp setHidden: NO];
  3716. [fSrcTimeStartEncodingField setHidden: YES];
  3717. [fSrcTimeEndEncodingField setHidden: YES];
  3718. [fSrcFrameStartEncodingField setHidden: YES];
  3719. [fSrcFrameEndEncodingField setHidden: YES];
  3720. [self chapterPopUpChanged:nil];
  3721. }
  3722. /* We are time based (seconds) */
  3723. else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 1)
  3724. {
  3725. [fSrcChapterStartPopUp setHidden: YES];
  3726. [fSrcChapterEndPopUp setHidden: YES];
  3727. [fSrcTimeStartEncodingField setHidden: NO];
  3728. [fSrcTimeEndEncodingField setHidden: NO];
  3729. [fSrcFrameStartEncodingField setHidden: YES];
  3730. [fSrcFrameEndEncodingField setHidden: YES];
  3731. [self startEndSecValueChanged:nil];
  3732. }
  3733. /* We are frame based */
  3734. else if ([fEncodeStartStopPopUp indexOfSelectedItem] == 2)
  3735. {
  3736. [fSrcChapterStartPopUp setHidden: YES];
  3737. [fSrcChapterEndPopUp setHidden: YES];
  3738. [fSrcTimeStartEncodingField setHidden: YES];
  3739. [fSrcTimeEndEncodingField setHidden: YES];
  3740. [fSrcFrameStartEncodingField setHidden: NO];
  3741. [fSrcFrameEndEncodingField setHidden: NO];
  3742. [self startEndFrameValueChanged:nil];
  3743. }
  3744. }
  3745. }
  3746. - (IBAction) chapterPopUpChanged: (id) sender
  3747. {
  3748. /* If start chapter popup is greater than end chapter popup,
  3749. we set the end chapter popup to the same as start chapter popup */
  3750. if ([fSrcChapterStartPopUp indexOfSelectedItem] > [fSrcChapterEndPopUp indexOfSelectedItem])
  3751. {
  3752. [fSrcChapterEndPopUp selectItemAtIndex: [fSrcChapterStartPopUp indexOfSelectedItem]];
  3753. }
  3754. hb_list_t * list = hb_get_titles( fHandle );
  3755. hb_title_t * title = (hb_title_t *)
  3756. hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
  3757. hb_chapter_t * chapter;
  3758. int64_t duration = 0;
  3759. for( int i = [fSrcChapterStartPopUp indexOfSelectedItem];
  3760. i <= [fSrcChapterEndPopUp indexOfSelectedItem]; i++ )
  3761. {
  3762. chapter = (hb_chapter_t *) hb_list_item( title->list_chapter, i );
  3763. duration += chapter->duration;
  3764. }
  3765. duration /= 90000; /* pts -> seconds */
  3766. [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
  3767. @"%02lld:%02lld:%02lld", duration / 3600, ( duration / 60 ) % 60,
  3768. duration % 60]];
  3769. [self calculateBitrate: sender];
  3770. if ( [fSrcChapterStartPopUp indexOfSelectedItem] == [fSrcChapterEndPopUp indexOfSelectedItem] )
  3771. {
  3772. /* Disable chapter markers for any source with less than two chapters as it makes no sense. */
  3773. [fCreateChapterMarkers setEnabled: NO];
  3774. [fCreateChapterMarkers setState: NSOffState];
  3775. }
  3776. else
  3777. {
  3778. [fCreateChapterMarkers setEnabled: YES];
  3779. }
  3780. }
  3781. - (IBAction) startEndSecValueChanged: (id) sender
  3782. {
  3783. int duration = [fSrcTimeEndEncodingField intValue] - [fSrcTimeStartEncodingField intValue];
  3784. [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
  3785. @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
  3786. duration % 60]];
  3787. //[self calculateBitrate: sender];
  3788. }
  3789. - (IBAction) startEndFrameValueChanged: (id) sender
  3790. {
  3791. hb_list_t * list = hb_get_titles( fHandle );
  3792. hb_title_t * title = (hb_title_t*)
  3793. hb_list_item( list, [fSrcTitlePopUp indexOfSelectedItem] );
  3794. int duration = ([fSrcFrameEndEncodingField intValue] - [fSrcFrameStartEncodingField intValue]) / (title->rate / title->rate_base);
  3795. [fSrcDuration2Field setStringValue: [NSString stringWithFormat:
  3796. @"%02d:%02d:%02d", duration / 3600, ( duration / 60 ) % 60,
  3797. duration % 60]];
  3798. //[self calculateBitrate: sender];
  3799. }
  3800. - (IBAction) formatPopUpChanged: (id) sender
  3801. {
  3802. NSString * string = [fDstFile2Field stringValue];
  3803. int format = [fDstFormatPopUp indexOfSelectedItem];
  3804. char * ext = NULL;
  3805. /* Initially set the large file (64 bit formatting) output checkbox to hidden */
  3806. [fDstMp4LargeFileCheck setHidden: YES];
  3807. [fDstMp4HttpOptFileCheck setHidden: YES];
  3808. [fDstMp4iPodFileCheck setHidden: YES];
  3809. /* Update the Video Codec PopUp */
  3810. /* lets get the tag of the currently selected item first so we might reset it later */
  3811. int selectedVidEncoderTag;
  3812. selectedVidEncoderTag = [[fVidEncoderPopUp selectedItem] tag];
  3813. /* Note: we now store the video encoder int values from common.c in the tags of each popup for easy retrieval later */
  3814. [fVidEncoderPopUp removeAllItems];
  3815. NSMenuItem *menuItem;
  3816. /* These video encoders are available to all of our current muxers, so lets list them once here */
  3817. menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"MPEG-4 (FFmpeg)" action: NULL keyEquivalent: @""];
  3818. [menuItem setTag: HB_VCODEC_FFMPEG];
  3819. switch( format )
  3820. {
  3821. case 0:
  3822. [self autoSetM4vExtension: nil];
  3823. /* Add additional video encoders here */
  3824. menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
  3825. [menuItem setTag: HB_VCODEC_X264];
  3826. /* We show the mp4 option checkboxes here since we are mp4 */
  3827. [fCreateChapterMarkers setEnabled: YES];
  3828. [fDstMp4LargeFileCheck setHidden: NO];
  3829. [fDstMp4HttpOptFileCheck setHidden: NO];
  3830. [fDstMp4iPodFileCheck setHidden: NO];
  3831. break;
  3832. case 1:
  3833. ext = "mkv";
  3834. /* Add additional video encoders here */
  3835. menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"H.264 (x264)" action: NULL keyEquivalent: @""];
  3836. [menuItem setTag: HB_VCODEC_X264];
  3837. menuItem = [[fVidEncoderPopUp menu] addItemWithTitle:@"VP3 (Theora)" action: NULL keyEquivalent: @""];
  3838. [menuItem setTag: HB_VCODEC_THEORA];
  3839. /* We enable the create chapters checkbox here */
  3840. [fCreateChapterMarkers setEnabled: YES];
  3841. break;
  3842. }
  3843. /* tell fSubtitlesDelegate we have a new video container */
  3844. [fSubtitlesDelegate containerChanged:[[fDstFormatPopUp selectedItem] tag]];
  3845. [fSubtitlesTable reloadData];
  3846. /* post a notification for any interested observers to indicate that our video container has changed */
  3847. [[NSNotificationCenter defaultCenter] postNotification:
  3848. [NSNotification notificationWithName: HBContainerChangedNotification
  3849. object: self
  3850. userInfo: [NSDictionary dictionaryWithObjectsAndKeys:
  3851. [NSNumber numberWithInt: [[fDstFormatPopUp selectedItem] tag]], keyContainerTag,
  3852. nil]]];
  3853. /* if we have a previously selected vid encoder tag, then try to select it */
  3854. if (selectedVidEncoderTag)
  3855. {
  3856. [fVidEncoderPopUp selectItemWithTag: selectedVidEncoderTag];
  3857. }
  3858. else
  3859. {
  3860. [fVidEncoderPopUp selectItemAtIndex: 0];
  3861. }
  3862. if( format == 0 )
  3863. [self autoSetM4vExtension: sender];
  3864. else
  3865. [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%s", [string stringByDeletingPathExtension], ext]];
  3866. if( SuccessfulScan )
  3867. {
  3868. /* Add/replace to the correct extension */
  3869. if( [fVidEncoderPopUp selectedItem] == nil )
  3870. {
  3871. [fVidEncoderPopUp selectItemAtIndex:0];
  3872. [self videoEncoderPopUpChanged:nil];
  3873. /* changing the format may mean that we can / can't offer mono or 6ch, */
  3874. /* so call audioTrackPopUpChanged for both audio tracks to update the mixdown popups */
  3875. /* We call the method to properly enable/disable turbo 2 pass */
  3876. [self twoPassCheckboxChanged: sender];
  3877. /* We call method method to change UI to reflect whether a preset is used or not*/
  3878. }
  3879. }
  3880. [self customSettingUsed: sender];
  3881. }
  3882. - (IBAction) autoSetM4vExtension: (id) sender
  3883. {
  3884. if ( [fDstFormatPopUp indexOfSelectedItem] )
  3885. return;
  3886. NSString * extension = @"mp4";
  3887. BOOL anyCodecAC3 = [fAudioDelegate anyCodecMatches: HB_ACODEC_AC3] || [fAudioDelegate anyCodecMatches: HB_ACODEC_AC3_PASS];
  3888. if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"DefaultMpegExtension"] isEqualToString: @".m4v"] ||
  3889. ((YES == anyCodecAC3 || [fCreateChapterMarkers state] == NSOnState) &&
  3890. [[[NSUserDefaults standardUserDefaults] objectForKey:@"DefaultMpegExtension"] isEqualToString: @"Auto"] ))
  3891. {
  3892. extension = @"m4v";
  3893. }
  3894. if( [extension isEqualTo: [[fDstFile2Field stringValue] pathExtension]] )
  3895. return;
  3896. else
  3897. [fDstFile2Field setStringValue: [NSString stringWithFormat:@"%@.%@",
  3898. [[fDstFile2Field stringValue] stringByDeletingPathExtension], extension]];
  3899. }
  3900. /* Method to determine if we should change the UI
  3901. To reflect whether or not a Preset is being used or if
  3902. the user is using "Custom" settings by determining the sender*/
  3903. - (IBAction) customSettingUsed: (id) sender
  3904. {
  3905. if ([sender stringValue])
  3906. {
  3907. /* Deselect the currently selected Preset if there is one*/
  3908. [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
  3909. /* Change UI to show "Custom" settings are being used */
  3910. [fPresetSelectedDisplay setStringValue: @"Custom"];
  3911. curUserPresetChosenNum = nil;
  3912. }
  3913. [self calculateBitrate:nil];
  3914. }
  3915. #pragma mark -
  3916. #pragma mark - Video
  3917. - (IBAction) videoEncoderPopUpChanged: (id) sender
  3918. {
  3919. hb_job_t * job = fTitle->job;
  3920. int videoEncoder = [[fVidEncoderPopUp selectedItem] tag];
  3921. [fAdvancedOptions setHidden:YES];
  3922. /* If we are using x264 then show the x264 advanced panel*/
  3923. if (videoEncoder == HB_VCODEC_X264)
  3924. {
  3925. [fAdvancedOptions setHidden:NO];
  3926. [self autoSetM4vExtension: sender];
  3927. }
  3928. if (videoEncoder == HB_VCODEC_FFMPEG)
  3929. {
  3930. /* We set the iPod atom checkbox to disabled and uncheck it as its only for x264 in the mp4
  3931. container. Format is taken care of in formatPopUpChanged method by hiding and unchecking
  3932. anything other than MP4.
  3933. */
  3934. [fDstMp4iPodFileCheck setEnabled: NO];
  3935. [fDstMp4iPodFileCheck setState: NSOffState];
  3936. }
  3937. else
  3938. {
  3939. [fDstMp4iPodFileCheck setEnabled: YES];
  3940. }
  3941. [self setupQualitySlider];
  3942. [self calculatePictureSizing: sender];
  3943. [self twoPassCheckboxChanged: sender];
  3944. }
  3945. - (IBAction) twoPassCheckboxChanged: (id) sender
  3946. {
  3947. /* check to see if x264 is chosen */
  3948. if([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
  3949. {
  3950. if( [fVidTwoPassCheck state] == NSOnState)
  3951. {
  3952. [fVidTurboPassCheck setHidden: NO];
  3953. }
  3954. else
  3955. {
  3956. [fVidTurboPassCheck setHidden: YES];
  3957. [fVidTurboPassCheck setState: NSOffState];
  3958. }
  3959. /* Make sure Two Pass is checked if Turbo is checked */
  3960. if( [fVidTurboPassCheck state] == NSOnState)
  3961. {
  3962. [fVidTwoPassCheck setState: NSOnState];
  3963. }
  3964. }
  3965. else
  3966. {
  3967. [fVidTurboPassCheck setHidden: YES];
  3968. [fVidTurboPassCheck setState: NSOffState];
  3969. }
  3970. /* We call method method to change UI to reflect whether a preset is used or not*/
  3971. [self customSettingUsed: sender];
  3972. }
  3973. - (IBAction ) videoFrameRateChanged: (id) sender
  3974. {
  3975. /* Hide and set the PFR Checkbox to OFF if we are set to Same as Source */
  3976. if ([fVidRatePopUp indexOfSelectedItem] == 0)
  3977. {
  3978. [fFrameratePfrCheck setHidden:YES];
  3979. [fFrameratePfrCheck setState:0];
  3980. }
  3981. else
  3982. {
  3983. [fFrameratePfrCheck setHidden:NO];
  3984. }
  3985. /* We call method method to calculatePictureSizing to error check detelecine*/
  3986. [self calculatePictureSizing: sender];
  3987. /* We call method method to change UI to reflect whether a preset is used or not*/
  3988. [self customSettingUsed: sender];
  3989. }
  3990. - (IBAction) videoMatrixChanged: (id) sender;
  3991. {
  3992. bool target, bitrate, quality;
  3993. target = bitrate = quality = false;
  3994. if( [fVidQualityMatrix isEnabled] )
  3995. {
  3996. switch( [fVidQualityMatrix selectedRow] )
  3997. {
  3998. case 0:
  3999. target = true;
  4000. break;
  4001. case 1:
  4002. bitrate = true;
  4003. break;
  4004. case 2:
  4005. quality = true;
  4006. break;
  4007. }
  4008. }
  4009. [fVidTargetSizeField setEnabled: target];
  4010. [fVidBitrateField setEnabled: bitrate];
  4011. [fVidQualitySlider setEnabled: quality];
  4012. [fVidQualityRFField setEnabled: quality];
  4013. [fVidQualityRFLabel setEnabled: quality];
  4014. [fVidTwoPassCheck setEnabled: !quality &&
  4015. [fVidQualityMatrix isEnabled]];
  4016. if( quality )
  4017. {
  4018. [fVidTwoPassCheck setState: NSOffState];
  4019. [fVidTurboPassCheck setHidden: YES];
  4020. [fVidTurboPassCheck setState: NSOffState];
  4021. }
  4022. [self qualitySliderChanged: sender];
  4023. [self calculateBitrate: sender];
  4024. [self customSettingUsed: sender];
  4025. }
  4026. /* Use this method to setup the quality slider for cq/rf values depending on
  4027. * the video encoder selected.
  4028. */
  4029. - (void) setupQualitySlider
  4030. {
  4031. /* Get the current slider maxValue to check for a change in slider scale later
  4032. * so that we can choose a new similar value on the new slider scale */
  4033. float previousMaxValue = [fVidQualitySlider maxValue];
  4034. float previousPercentOfSliderScale = [fVidQualitySlider floatValue] / ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1);
  4035. NSString * qpRFLabelString = @"QP:";
  4036. /* x264 0-51 */
  4037. if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264)
  4038. {
  4039. [fVidQualitySlider setMinValue:0.0];
  4040. [fVidQualitySlider setMaxValue:51.0];
  4041. /* As x264 allows for qp/rf values that are fractional, we get the value from the preferences */
  4042. int fractionalGranularity = 1 / [[NSUserDefaults standardUserDefaults] floatForKey:@"x264CqSliderFractional"];
  4043. [fVidQualitySlider setNumberOfTickMarks:(([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * fractionalGranularity) + 1];
  4044. qpRFLabelString = @"RF:";
  4045. }
  4046. /* ffmpeg 1-31 */
  4047. if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_FFMPEG )
  4048. {
  4049. [fVidQualitySlider setMinValue:1.0];
  4050. [fVidQualitySlider setMaxValue:31.0];
  4051. [fVidQualitySlider setNumberOfTickMarks:31];
  4052. }
  4053. /* Theora 0-63 */
  4054. if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
  4055. {
  4056. [fVidQualitySlider setMinValue:0.0];
  4057. [fVidQualitySlider setMaxValue:63.0];
  4058. [fVidQualitySlider setNumberOfTickMarks:64];
  4059. }
  4060. [fVidQualityRFLabel setStringValue:qpRFLabelString];
  4061. /* check to see if we have changed slider scales */
  4062. if (previousMaxValue != [fVidQualitySlider maxValue])
  4063. {
  4064. /* if so, convert the old setting to the new scale as close as possible based on percentages */
  4065. float rf = ([fVidQualitySlider maxValue] - [fVidQualitySlider minValue] + 1) * previousPercentOfSliderScale;
  4066. [fVidQualitySlider setFloatValue:rf];
  4067. }
  4068. [self qualitySliderChanged:nil];
  4069. }
  4070. - (IBAction) qualitySliderChanged: (id) sender
  4071. {
  4072. /* Our constant quality slider is in a range based
  4073. * on each encoders qp/rf values. The range depends
  4074. * on the encoder. Also, the range is inverse of quality
  4075. * for all of the encoders *except* for theora
  4076. * (ie. as the "quality" goes up, the cq or rf value
  4077. * actually goes down). Since the IB sliders always set
  4078. * their max value at the right end of the slider, we
  4079. * will calculate the inverse, so as the slider floatValue
  4080. * goes up, we will show the inverse in the rf field
  4081. * so, the floatValue at the right for x264 would be 51
  4082. * and our rf field needs to show 0 and vice versa.
  4083. */
  4084. float sliderRfInverse = ([fVidQualitySlider maxValue] - [fVidQualitySlider floatValue]) + [fVidQualitySlider minValue];
  4085. /* If the encoder is theora, use the float, otherwise use the inverse float*/
  4086. //float sliderRfToPercent;
  4087. if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
  4088. {
  4089. [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", [fVidQualitySlider floatValue]]];
  4090. }
  4091. else
  4092. {
  4093. [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f", sliderRfInverse]];
  4094. }
  4095. /* Show a warning if x264 and rf 0 which is lossless */
  4096. if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_X264 && sliderRfInverse == 0.0)
  4097. {
  4098. [fVidQualityRFField setStringValue: [NSString stringWithFormat: @"%.2f (Warning: Lossless)", sliderRfInverse]];
  4099. }
  4100. [self customSettingUsed: sender];
  4101. }
  4102. - (void) controlTextDidChange: (NSNotification *) notification
  4103. {
  4104. [self calculateBitrate:nil];
  4105. }
  4106. - (IBAction) calculateBitrate: (id) sender
  4107. {
  4108. if( !fHandle || [fVidQualityMatrix selectedRow] != 0 || !SuccessfulScan )
  4109. {
  4110. return;
  4111. }
  4112. hb_list_t * list = hb_get_titles( fHandle );
  4113. hb_title_t * title = (hb_title_t *) hb_list_item( list,
  4114. [fSrcTitlePopUp indexOfSelectedItem] );
  4115. hb_job_t * job = title->job;
  4116. hb_audio_config_t * audio;
  4117. /* For hb_calc_bitrate in addition to the Target Size in MB out of the
  4118. * Target Size Field, we also need the job info for the Muxer, the Chapters
  4119. * as well as all of the audio track info.
  4120. * This used to be accomplished by simply calling prepareJob here, however
  4121. * since the resilient queue sets the queue array values instead of the job
  4122. * values directly, we duplicate the old prepareJob code here for the variables
  4123. * needed
  4124. */
  4125. job->chapter_start = [fSrcChapterStartPopUp indexOfSelectedItem] + 1;
  4126. job->chapter_end = [fSrcChapterEndPopUp indexOfSelectedItem] + 1;
  4127. job->mux = [[fDstFormatPopUp selectedItem] tag];
  4128. /* Audio goes here */
  4129. [fAudioDelegate prepareAudioForJob: job];
  4130. [fVidBitrateField setIntValue: hb_calc_bitrate( job, [fVidTargetSizeField intValue] )];
  4131. }
  4132. #pragma mark -
  4133. #pragma mark - Picture
  4134. /* lets set the picture size back to the max from right after title scan
  4135. Lets use an IBAction here as down the road we could always use a checkbox
  4136. in the gui to easily take the user back to max. Remember, the compiler
  4137. resolves IBActions down to -(void) during compile anyway */
  4138. - (IBAction) revertPictureSizeToMax: (id) sender
  4139. {
  4140. hb_job_t * job = fTitle->job;
  4141. /* Here we apply the title source and height */
  4142. job->width = fTitle->width;
  4143. job->height = fTitle->height;
  4144. [self calculatePictureSizing: sender];
  4145. /* We call method to change UI to reflect whether a preset is used or not*/
  4146. [self customSettingUsed: sender];
  4147. }
  4148. /**
  4149. * Registers changes made in the Picture Settings Window.
  4150. */
  4151. - (void)pictureSettingsDidChange
  4152. {
  4153. [self calculatePictureSizing:nil];
  4154. }
  4155. /* Get and Display Current Pic Settings in main window */
  4156. - (IBAction) calculatePictureSizing: (id) sender
  4157. {
  4158. if (fTitle->job->anamorphic.mode > 0)
  4159. {
  4160. fTitle->job->keep_ratio = 0;
  4161. }
  4162. if (fTitle->job->anamorphic.mode != 1) // we are not strict so show the modulus
  4163. {
  4164. [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@, Modulus: %d", [fPictureController getPictureSizeInfoString], fTitle->job->modulus]];
  4165. }
  4166. else
  4167. {
  4168. [fPictureSizeField setStringValue: [NSString stringWithFormat:@"Picture Size: %@", [fPictureController getPictureSizeInfoString]]];
  4169. }
  4170. NSString *picCropping;
  4171. /* Set the display field for crop as per boolean */
  4172. if (![fPictureController autoCrop])
  4173. {
  4174. picCropping = @"Custom";
  4175. }
  4176. else
  4177. {
  4178. picCropping = @"Auto";
  4179. }
  4180. picCropping = [picCropping stringByAppendingString:[NSString stringWithFormat:@" %d/%d/%d/%d",fTitle->job->crop[0],fTitle->job->crop[1],fTitle->job->crop[2],fTitle->job->crop[3]]];
  4181. [fPictureCroppingField setStringValue: [NSString stringWithFormat:@"Picture Cropping: %@",picCropping]];
  4182. NSString *videoFilters;
  4183. videoFilters = @"";
  4184. /* Detelecine */
  4185. if ([fPictureController detelecine] == 2)
  4186. {
  4187. videoFilters = [videoFilters stringByAppendingString:@" - Detelecine (Default)"];
  4188. }
  4189. else if ([fPictureController detelecine] == 1)
  4190. {
  4191. videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Detelecine (%@)",[fPictureController detelecineCustomString]]];
  4192. }
  4193. if ([fPictureController useDecomb] == 1)
  4194. {
  4195. /* Decomb */
  4196. if ([fPictureController decomb] == 2)
  4197. {
  4198. videoFilters = [videoFilters stringByAppendingString:@" - Decomb (Default)"];
  4199. }
  4200. else if ([fPictureController decomb] == 1)
  4201. {
  4202. videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Decomb (%@)",[fPictureController decombCustomString]]];
  4203. }
  4204. }
  4205. else
  4206. {
  4207. /* Deinterlace */
  4208. if ([fPictureController deinterlace] > 0)
  4209. {
  4210. fTitle->job->deinterlace = 1;
  4211. }
  4212. else
  4213. {
  4214. fTitle->job->deinterlace = 0;
  4215. }
  4216. if ([fPictureController deinterlace] == 2)
  4217. {
  4218. videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Fast)"];
  4219. }
  4220. else if ([fPictureController deinterlace] == 3)
  4221. {
  4222. videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slow)"];
  4223. }
  4224. else if ([fPictureController deinterlace] == 4)
  4225. {
  4226. videoFilters = [videoFilters stringByAppendingString:@" - Deinterlace (Slower)"];
  4227. }
  4228. else if ([fPictureController deinterlace] == 1)
  4229. {
  4230. videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deinterlace (%@)",[fPictureController deinterlaceCustomString]]];
  4231. }
  4232. }
  4233. /* Denoise */
  4234. if ([fPictureController denoise] == 2)
  4235. {
  4236. videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Weak)"];
  4237. }
  4238. else if ([fPictureController denoise] == 3)
  4239. {
  4240. videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Medium)"];
  4241. }
  4242. else if ([fPictureController denoise] == 4)
  4243. {
  4244. videoFilters = [videoFilters stringByAppendingString:@" - Denoise (Strong)"];
  4245. }
  4246. else if ([fPictureController denoise] == 1)
  4247. {
  4248. videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Denoise (%@)",[fPictureController denoiseCustomString]]];
  4249. }
  4250. /* Deblock */
  4251. if ([fPictureController deblock] > 0)
  4252. {
  4253. videoFilters = [videoFilters stringByAppendingString:[NSString stringWithFormat:@" - Deblock (%d)",[fPictureController deblock]]];
  4254. }
  4255. /* Grayscale */
  4256. if ([fPictureController grayscale])
  4257. {
  4258. videoFilters = [videoFilters stringByAppendingString:@" - Grayscale"];
  4259. }
  4260. [fVideoFiltersField setStringValue: [NSString stringWithFormat:@"Video Filters: %@", videoFilters]];
  4261. //[fPictureController reloadStillPreview];
  4262. }
  4263. #pragma mark -
  4264. #pragma mark - Audio and Subtitles
  4265. #pragma mark -
  4266. - (BOOL) hasValidPresetSelected
  4267. {
  4268. return ([fPresetsOutlineView selectedRow] >= 0 && [[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] != 1);
  4269. }
  4270. // This causes all audio tracks from the title to be used based on the current preset
  4271. - (IBAction) addAllAudioTracks: (id) sender
  4272. {
  4273. [fAudioDelegate addAllTracksFromPreset: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
  4274. return;
  4275. }
  4276. - (IBAction) browseImportSrtFile: (id) sender
  4277. {
  4278. NSOpenPanel * panel;
  4279. panel = [NSOpenPanel openPanel];
  4280. [panel setAllowsMultipleSelection: NO];
  4281. [panel setCanChooseFiles: YES];
  4282. [panel setCanChooseDirectories: NO ];
  4283. NSString * sourceDirectory;
  4284. if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"])
  4285. {
  4286. sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastSrtImportDirectory"];
  4287. }
  4288. else
  4289. {
  4290. sourceDirectory = @"~/Desktop";
  4291. sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
  4292. }
  4293. /* we open up the browse srt sheet here and call for browseImportSrtFileDone after the sheet is closed */
  4294. NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"srt", nil];
  4295. [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
  4296. modalForWindow: fWindow modalDelegate: self
  4297. didEndSelector: @selector( browseImportSrtFileDone:returnCode:contextInfo: )
  4298. contextInfo: sender];
  4299. }
  4300. - (void) browseImportSrtFileDone: (NSSavePanel *) sheet
  4301. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  4302. {
  4303. if( returnCode == NSOKButton )
  4304. {
  4305. NSString *importSrtDirectory = [[sheet filename] stringByDeletingLastPathComponent];
  4306. NSString *importSrtFilePath = [sheet filename];
  4307. [[NSUserDefaults standardUserDefaults] setObject:importSrtDirectory forKey:@"LastSrtImportDirectory"];
  4308. /* now pass the string off to fSubtitlesDelegate to add the srt file to the dropdown */
  4309. [fSubtitlesDelegate createSubtitleSrtTrack:importSrtFilePath];
  4310. [fSubtitlesTable reloadData];
  4311. }
  4312. }
  4313. #pragma mark -
  4314. #pragma mark Open New Windows
  4315. - (IBAction) openHomepage: (id) sender
  4316. {
  4317. [[NSWorkspace sharedWorkspace] openURL: [NSURL
  4318. URLWithString:@"http://handbrake.fr/"]];
  4319. }
  4320. - (IBAction) openForums: (id) sender
  4321. {
  4322. [[NSWorkspace sharedWorkspace] openURL: [NSURL
  4323. URLWithString:@"http://forum.handbrake.fr/"]];
  4324. }
  4325. - (IBAction) openUserGuide: (id) sender
  4326. {
  4327. [[NSWorkspace sharedWorkspace] openURL: [NSURL
  4328. URLWithString:@"http://trac.handbrake.fr/wiki/HandBrakeGuide"]];
  4329. }
  4330. /**
  4331. * Shows debug output window.
  4332. */
  4333. - (IBAction)showDebugOutputPanel:(id)sender
  4334. {
  4335. [outputPanel showOutputPanel:sender];
  4336. }
  4337. /**
  4338. * Shows preferences window.
  4339. */
  4340. - (IBAction) showPreferencesWindow: (id) sender
  4341. {
  4342. NSWindow * window = [fPreferencesController window];
  4343. if (![window isVisible])
  4344. [window center];
  4345. [window makeKeyAndOrderFront: nil];
  4346. }
  4347. /**
  4348. * Shows queue window.
  4349. */
  4350. - (IBAction) showQueueWindow:(id)sender
  4351. {
  4352. [fQueueController showQueueWindow:sender];
  4353. }
  4354. - (IBAction) toggleDrawer:(id)sender {
  4355. [fPresetDrawer toggle:self];
  4356. }
  4357. /**
  4358. * Shows Picture Settings Window.
  4359. */
  4360. - (IBAction) showPicturePanel: (id) sender
  4361. {
  4362. [fPictureController showPictureWindow:sender];
  4363. }
  4364. - (void) picturePanelFullScreen
  4365. {
  4366. [fPictureController setToFullScreenMode];
  4367. }
  4368. - (void) picturePanelWindowed
  4369. {
  4370. [fPictureController setToWindowedMode];
  4371. }
  4372. - (IBAction) showPreviewWindow: (id) sender
  4373. {
  4374. [fPictureController showPreviewWindow:sender];
  4375. }
  4376. #pragma mark -
  4377. #pragma mark Preset Outline View Methods
  4378. #pragma mark - Required
  4379. /* These are required by the NSOutlineView Datasource Delegate */
  4380. /* used to specify the number of levels to show for each item */
  4381. - (int)outlineView:(NSOutlineView *)fPresetsOutlineView numberOfChildrenOfItem:(id)item
  4382. {
  4383. /* currently use no levels to test outline view viability */
  4384. if (item == nil) // for an outline view the root level of the hierarchy is always nil
  4385. {
  4386. return [UserPresets count];
  4387. }
  4388. else
  4389. {
  4390. /* we need to return the count of the array in ChildrenArray for this folder */
  4391. NSArray *children = nil;
  4392. children = [item objectForKey:@"ChildrenArray"];
  4393. if ([children count] > 0)
  4394. {
  4395. return [children count];
  4396. }
  4397. else
  4398. {
  4399. return 0;
  4400. }
  4401. }
  4402. }
  4403. /* We use this to deterimine children of an item */
  4404. - (id)outlineView:(NSOutlineView *)fPresetsOutlineView child:(NSInteger)index ofItem:(id)item
  4405. {
  4406. /* we need to return the count of the array in ChildrenArray for this folder */
  4407. NSArray *children = nil;
  4408. if (item == nil)
  4409. {
  4410. children = UserPresets;
  4411. }
  4412. else
  4413. {
  4414. if ([item objectForKey:@"ChildrenArray"])
  4415. {
  4416. children = [item objectForKey:@"ChildrenArray"];
  4417. }
  4418. }
  4419. if ((children == nil) || ( [children count] <= (NSUInteger) index))
  4420. {
  4421. return nil;
  4422. }
  4423. else
  4424. {
  4425. return [children objectAtIndex:index];
  4426. }
  4427. // We are only one level deep, so we can't be asked about children
  4428. //NSAssert (NO, @"Presets View outlineView:child:ofItem: currently can't handle nested items.");
  4429. //return nil;
  4430. }
  4431. /* We use this to determine if an item should be expandable */
  4432. - (BOOL)outlineView:(NSOutlineView *)fPresetsOutlineView isItemExpandable:(id)item
  4433. {
  4434. /* we need to return the count of the array in ChildrenArray for this folder */
  4435. NSArray *children= nil;
  4436. if (item == nil)
  4437. {
  4438. children = UserPresets;
  4439. }
  4440. else
  4441. {
  4442. if ([item objectForKey:@"ChildrenArray"])
  4443. {
  4444. children = [item objectForKey:@"ChildrenArray"];
  4445. }
  4446. }
  4447. /* To deterimine if an item should show a disclosure triangle
  4448. * we could do it by the children count as so:
  4449. * if ([children count] < 1)
  4450. * However, lets leave the triangle show even if there are no
  4451. * children to help indicate a folder, just like folder in the
  4452. * finder can show a disclosure triangle even when empty
  4453. */
  4454. /* We need to determine if the item is a folder */
  4455. if ([[item objectForKey:@"Folder"] intValue] == 1)
  4456. {
  4457. return YES;
  4458. }
  4459. else
  4460. {
  4461. return NO;
  4462. }
  4463. }
  4464. - (BOOL)outlineView:(NSOutlineView *)outlineView shouldExpandItem:(id)item
  4465. {
  4466. // Our outline view has no levels, but we can still expand every item. Doing so
  4467. // just makes the row taller. See heightOfRowByItem below.
  4468. //return ![(HBQueueOutlineView*)outlineView isDragging];
  4469. return YES;
  4470. }
  4471. /* Used to tell the outline view which information is to be displayed per item */
  4472. - (id)outlineView:(NSOutlineView *)fPresetsOutlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
  4473. {
  4474. /* We have two columns right now, icon and PresetName */
  4475. if ([[tableColumn identifier] isEqualToString:@"PresetName"])
  4476. {
  4477. return [item objectForKey:@"PresetName"];
  4478. }
  4479. else
  4480. {
  4481. //return @"";
  4482. return nil;
  4483. }
  4484. }
  4485. - (id)outlineView:(NSOutlineView *)outlineView itemForPersistentObject:(id)object
  4486. {
  4487. return [NSKeyedUnarchiver unarchiveObjectWithData:object];
  4488. }
  4489. - (id)outlineView:(NSOutlineView *)outlineView persistentObjectForItem:(id)item
  4490. {
  4491. return [NSKeyedArchiver archivedDataWithRootObject:item];
  4492. }
  4493. #pragma mark - Added Functionality (optional)
  4494. /* Use to customize the font and display characteristics of the title cell */
  4495. - (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
  4496. {
  4497. if ([[tableColumn identifier] isEqualToString:@"PresetName"])
  4498. {
  4499. NSFont *txtFont;
  4500. NSColor *fontColor;
  4501. NSColor *shadowColor;
  4502. txtFont = [NSFont systemFontOfSize: [NSFont smallSystemFontSize]];
  4503. /*check to see if its a selected row */
  4504. if ([fPresetsOutlineView selectedRow] == [fPresetsOutlineView rowForItem:item])
  4505. {
  4506. fontColor = [NSColor blackColor];
  4507. shadowColor = [NSColor colorWithDeviceRed:(127.0/255.0) green:(140.0/255.0) blue:(160.0/255.0) alpha:1.0];
  4508. }
  4509. else
  4510. {
  4511. if ([[item objectForKey:@"Type"] intValue] == 0)
  4512. {
  4513. fontColor = [NSColor blueColor];
  4514. }
  4515. else // User created preset, use a black font
  4516. {
  4517. fontColor = [NSColor blackColor];
  4518. }
  4519. /* check to see if its a folder */
  4520. //if ([[item objectForKey:@"Folder"] intValue] == 1)
  4521. //{
  4522. //fontColor = [NSColor greenColor];
  4523. //}
  4524. }
  4525. /* We use Bold Text for the HB Default */
  4526. if ([[item objectForKey:@"Default"] intValue] == 1)// 1 is HB default
  4527. {
  4528. txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
  4529. }
  4530. /* We use Bold Text for the User Specified Default */
  4531. if ([[item objectForKey:@"Default"] intValue] == 2)// 2 is User default
  4532. {
  4533. txtFont = [NSFont boldSystemFontOfSize: [NSFont smallSystemFontSize]];
  4534. }
  4535. [cell setTextColor:fontColor];
  4536. [cell setFont:txtFont];
  4537. }
  4538. }
  4539. /* We use this to edit the name field in the outline view */
  4540. - (void)outlineView:(NSOutlineView *)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
  4541. {
  4542. if ([[tableColumn identifier] isEqualToString:@"PresetName"])
  4543. {
  4544. id theRecord;
  4545. theRecord = item;
  4546. [theRecord setObject:object forKey:@"PresetName"];
  4547. [self sortPresets];
  4548. [fPresetsOutlineView reloadData];
  4549. /* We save all of the preset data here */
  4550. [self savePreset];
  4551. }
  4552. }
  4553. /* We use this to provide tooltips for the items in the presets outline view */
  4554. - (NSString *)outlineView:(NSOutlineView *)fPresetsOutlineView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tc item:(id)item mouseLocation:(NSPoint)mouseLocation
  4555. {
  4556. //if ([[tc identifier] isEqualToString:@"PresetName"])
  4557. //{
  4558. /* initialize the tooltip contents variable */
  4559. NSString *loc_tip;
  4560. /* if there is a description for the preset, we show it in the tooltip */
  4561. if ([item objectForKey:@"PresetDescription"])
  4562. {
  4563. loc_tip = [item objectForKey:@"PresetDescription"];
  4564. return (loc_tip);
  4565. }
  4566. else
  4567. {
  4568. loc_tip = @"No description available";
  4569. }
  4570. return (loc_tip);
  4571. //}
  4572. }
  4573. - (void) outlineViewSelectionDidChange: (NSNotification *) ignored
  4574. {
  4575. [self willChangeValueForKey: @"hasValidPresetSelected"];
  4576. [self didChangeValueForKey: @"hasValidPresetSelected"];
  4577. return;
  4578. }
  4579. #pragma mark -
  4580. #pragma mark Preset Outline View Methods (dragging related)
  4581. - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
  4582. {
  4583. // Dragging is only allowed for custom presets.
  4584. //[[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Default"] intValue] != 1
  4585. if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Type"] intValue] == 0) // 0 is built in preset
  4586. {
  4587. return NO;
  4588. }
  4589. // Don't retain since this is just holding temporaral drag information, and it is
  4590. //only used during a drag! We could put this in the pboard actually.
  4591. fDraggedNodes = items;
  4592. // Provide data for our custom type, and simple NSStrings.
  4593. [pboard declareTypes:[NSArray arrayWithObjects: DragDropSimplePboardType, nil] owner:self];
  4594. // the actual data doesn't matter since DragDropSimplePboardType drags aren't recognized by anyone but us!.
  4595. [pboard setData:[NSData data] forType:DragDropSimplePboardType];
  4596. return YES;
  4597. }
  4598. - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
  4599. {
  4600. // Don't allow dropping ONTO an item since they can't really contain any children.
  4601. BOOL isOnDropTypeProposal = index == NSOutlineViewDropOnItemIndex;
  4602. if (isOnDropTypeProposal)
  4603. return NSDragOperationNone;
  4604. // Don't allow dropping INTO an item since they can't really contain any children as of yet.
  4605. if (item != nil)
  4606. {
  4607. index = [fPresetsOutlineView rowForItem: item] + 1;
  4608. item = nil;
  4609. }
  4610. // Don't allow dropping into the Built In Presets.
  4611. if (index < presetCurrentBuiltInCount)
  4612. {
  4613. return NSDragOperationNone;
  4614. index = MAX (index, presetCurrentBuiltInCount);
  4615. }
  4616. [outlineView setDropItem:item dropChildIndex:index];
  4617. return NSDragOperationGeneric;
  4618. }
  4619. - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
  4620. {
  4621. /* first, lets see if we are dropping into a folder */
  4622. if ([[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] && [[[fPresetsOutlineView itemAtRow:index] objectForKey:@"Folder"] intValue] == 1) // if its a folder
  4623. {
  4624. NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
  4625. childrenArray = [[fPresetsOutlineView itemAtRow:index] objectForKey:@"ChildrenArray"];
  4626. [childrenArray addObject:item];
  4627. [[fPresetsOutlineView itemAtRow:index] setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
  4628. [childrenArray autorelease];
  4629. }
  4630. else // We are not, so we just move the preset into the existing array
  4631. {
  4632. NSMutableIndexSet *moveItems = [NSMutableIndexSet indexSet];
  4633. id obj;
  4634. NSEnumerator *enumerator = [fDraggedNodes objectEnumerator];
  4635. while (obj = [enumerator nextObject])
  4636. {
  4637. [moveItems addIndex:[UserPresets indexOfObject:obj]];
  4638. }
  4639. // Successful drop, lets rearrange the view and save it all
  4640. [self moveObjectsInPresetsArray:UserPresets fromIndexes:moveItems toIndex: index];
  4641. }
  4642. [fPresetsOutlineView reloadData];
  4643. [self savePreset];
  4644. return YES;
  4645. }
  4646. - (void)moveObjectsInPresetsArray:(NSMutableArray *)array fromIndexes:(NSIndexSet *)indexSet toIndex:(NSUInteger)insertIndex
  4647. {
  4648. NSUInteger index = [indexSet lastIndex];
  4649. NSUInteger aboveInsertIndexCount = 0;
  4650. NSUInteger removeIndex;
  4651. if (index >= insertIndex)
  4652. {
  4653. removeIndex = index + aboveInsertIndexCount;
  4654. aboveInsertIndexCount++;
  4655. }
  4656. else
  4657. {
  4658. removeIndex = index;
  4659. insertIndex--;
  4660. }
  4661. id object = [[array objectAtIndex:removeIndex] retain];
  4662. [array removeObjectAtIndex:removeIndex];
  4663. [array insertObject:object atIndex:insertIndex];
  4664. [object release];
  4665. index = [indexSet indexLessThanIndex:index];
  4666. }
  4667. #pragma mark - Functional Preset NSOutlineView Methods
  4668. - (IBAction)selectPreset:(id)sender
  4669. {
  4670. if (YES == [self hasValidPresetSelected])
  4671. {
  4672. chosenPreset = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
  4673. [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
  4674. if ([[chosenPreset objectForKey:@"Default"] intValue] == 1)
  4675. {
  4676. [fPresetSelectedDisplay setStringValue:[NSString stringWithFormat:@"%@ (Default)", [chosenPreset objectForKey:@"PresetName"]]];
  4677. }
  4678. else
  4679. {
  4680. [fPresetSelectedDisplay setStringValue:[chosenPreset objectForKey:@"PresetName"]];
  4681. }
  4682. /* File Format */
  4683. [fDstFormatPopUp selectItemWithTitle:[chosenPreset objectForKey:@"FileFormat"]];
  4684. [self formatPopUpChanged:nil];
  4685. /* Chapter Markers*/
  4686. [fCreateChapterMarkers setState:[[chosenPreset objectForKey:@"ChapterMarkers"] intValue]];
  4687. /* check to see if we have only one chapter */
  4688. [self chapterPopUpChanged:nil];
  4689. /* Allow Mpeg4 64 bit formatting +4GB file sizes */
  4690. [fDstMp4LargeFileCheck setState:[[chosenPreset objectForKey:@"Mp4LargeFile"] intValue]];
  4691. /* Mux mp4 with http optimization */
  4692. [fDstMp4HttpOptFileCheck setState:[[chosenPreset objectForKey:@"Mp4HttpOptimize"] intValue]];
  4693. /* Video encoder */
  4694. [fVidEncoderPopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoEncoder"]];
  4695. /* We set the advanced opt string here if applicable*/
  4696. [fAdvancedOptions setOptions:[chosenPreset objectForKey:@"x264Option"]];
  4697. /* Lets run through the following functions to get variables set there */
  4698. [self videoEncoderPopUpChanged:nil];
  4699. /* Set the state of ipod compatible with Mp4iPodCompatible. Only for x264*/
  4700. [fDstMp4iPodFileCheck setState:[[chosenPreset objectForKey:@"Mp4iPodCompatible"] intValue]];
  4701. [self calculateBitrate:nil];
  4702. /* Video quality */
  4703. [fVidQualityMatrix selectCellAtRow:[[chosenPreset objectForKey:@"VideoQualityType"] intValue] column:0];
  4704. [fVidTargetSizeField setStringValue:[chosenPreset objectForKey:@"VideoTargetSize"]];
  4705. [fVidBitrateField setStringValue:[chosenPreset objectForKey:@"VideoAvgBitrate"]];
  4706. /* Since we are now using RF Values for the slider, we detect if the preset uses an old quality float.
  4707. * So, check to see if the quality value is less than 1.0 which should indicate the old ".062" type
  4708. * quality preset. Caveat: in the case of x264, where the RF scale starts at 0, it would misinterpret
  4709. * a preset that uses 0.0 - 0.99 for RF as an old style preset. Not sure how to get around that one yet,
  4710. * though it should be a corner case since it would pretty much be a preset for lossless encoding. */
  4711. if ([[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue] < 1.0)
  4712. {
  4713. /* For the quality slider we need to convert the old percent's to the new rf scales */
  4714. float rf = (([fVidQualitySlider maxValue] - [fVidQualitySlider minValue]) * [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]);
  4715. [fVidQualitySlider setFloatValue:rf];
  4716. }
  4717. else
  4718. {
  4719. /* Since theora's qp value goes up from left to right, we can just set the slider float value */
  4720. if ([[fVidEncoderPopUp selectedItem] tag] == HB_VCODEC_THEORA)
  4721. {
  4722. [fVidQualitySlider setFloatValue:[[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
  4723. }
  4724. else
  4725. {
  4726. /* since ffmpeg and x264 use an "inverted" slider (lower qp/rf values indicate a higher quality) we invert the value on the slider */
  4727. [fVidQualitySlider setFloatValue:([fVidQualitySlider maxValue] + [fVidQualitySlider minValue]) - [[chosenPreset objectForKey:@"VideoQualitySlider"] floatValue]];
  4728. }
  4729. }
  4730. [self videoMatrixChanged:nil];
  4731. /* Video framerate */
  4732. /* For video preset video framerate, we want to make sure that Same as source does not conflict with the
  4733. detected framerate in the fVidRatePopUp so we use index 0*/
  4734. if ([[chosenPreset objectForKey:@"VideoFramerate"] isEqualToString:@"Same as source"])
  4735. {
  4736. [fVidRatePopUp selectItemAtIndex: 0];
  4737. }
  4738. else
  4739. {
  4740. [fVidRatePopUp selectItemWithTitle:[chosenPreset objectForKey:@"VideoFramerate"]];
  4741. }
  4742. /* Set PFR */
  4743. [fFrameratePfrCheck setState:[[chosenPreset objectForKey:@"VideoFrameratePFR"] intValue]];
  4744. [self videoFrameRateChanged:nil];
  4745. /* 2 Pass Encoding */
  4746. [fVidTwoPassCheck setState:[[chosenPreset objectForKey:@"VideoTwoPass"] intValue]];
  4747. [self twoPassCheckboxChanged:nil];
  4748. /* Turbo 1st pass for 2 Pass Encoding */
  4749. [fVidTurboPassCheck setState:[[chosenPreset objectForKey:@"VideoTurboTwoPass"] intValue]];
  4750. /*Audio*/
  4751. [fAudioDelegate addTracksFromPreset: chosenPreset];
  4752. /*Subtitles*/
  4753. [fSubPopUp selectItemWithTitle:[chosenPreset objectForKey:@"Subtitles"]];
  4754. /* Forced Subtitles */
  4755. [fSubForcedCheck setState:[[chosenPreset objectForKey:@"SubtitlesForced"] intValue]];
  4756. /* Picture Settings */
  4757. /* Note: objectForKey:@"UsesPictureSettings" refers to picture size, which encompasses:
  4758. * height, width, keep ar, anamorphic and crop settings.
  4759. * picture filters are handled separately below.
  4760. */
  4761. /* Check to see if the objectForKey:@"UsesPictureSettings is greater than 0, as 0 means use picture sizing "None"
  4762. * ( 2 is use max for source and 1 is use exact size when the preset was created ) and the
  4763. * preset completely ignores any picture sizing values in the preset.
  4764. */
  4765. if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] > 0)
  4766. {
  4767. hb_job_t * job = fTitle->job;
  4768. /* If Cropping is set to custom, then recall all four crop values from
  4769. when the preset was created and apply them */
  4770. if ([[chosenPreset objectForKey:@"PictureAutoCrop"] intValue] == 0)
  4771. {
  4772. [fPictureController setAutoCrop:NO];
  4773. /* Here we use the custom crop values saved at the time the preset was saved */
  4774. job->crop[0] = [[chosenPreset objectForKey:@"PictureTopCrop"] intValue];
  4775. job->crop[1] = [[chosenPreset objectForKey:@"PictureBottomCrop"] intValue];
  4776. job->crop[2] = [[chosenPreset objectForKey:@"PictureLeftCrop"] intValue];
  4777. job->crop[3] = [[chosenPreset objectForKey:@"PictureRightCrop"] intValue];
  4778. }
  4779. else /* if auto crop has been saved in preset, set to auto and use post scan auto crop */
  4780. {
  4781. [fPictureController setAutoCrop:YES];
  4782. /* Here we use the auto crop values determined right after scan */
  4783. job->crop[0] = AutoCropTop;
  4784. job->crop[1] = AutoCropBottom;
  4785. job->crop[2] = AutoCropLeft;
  4786. job->crop[3] = AutoCropRight;
  4787. }
  4788. /* Set modulus */
  4789. if ([chosenPreset objectForKey:@"PictureModulus"])
  4790. {
  4791. job->modulus = [[chosenPreset objectForKey:@"PictureModulus"] intValue];
  4792. }
  4793. else
  4794. {
  4795. job->modulus = 16;
  4796. }
  4797. /* Check to see if the objectForKey:@"UsesPictureSettings is 2 which is "Use Max for the source */
  4798. if ([[chosenPreset objectForKey:@"UsesPictureSettings"] intValue] == 2 || [[chosenPreset objectForKey:@"UsesMaxPictureSettings"] intValue] == 1)
  4799. {
  4800. /* Use Max Picture settings for whatever the dvd is.*/
  4801. [self revertPictureSizeToMax:nil];
  4802. job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
  4803. if (job->keep_ratio == 1)
  4804. {
  4805. hb_fix_aspect( job, HB_KEEP_WIDTH );
  4806. if( job->height > fTitle->height )
  4807. {
  4808. job->height = fTitle->height;
  4809. hb_fix_aspect( job, HB_KEEP_HEIGHT );
  4810. }
  4811. }
  4812. job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
  4813. }
  4814. else // /* If not 0 or 2 we assume objectForKey:@"UsesPictureSettings is 1 which is "Use picture sizing from when the preset was set" */
  4815. {
  4816. /* we check to make sure the presets width/height does not exceed the sources width/height */
  4817. if (fTitle->width < [[chosenPreset objectForKey:@"PictureWidth"] intValue] || fTitle->height < [[chosenPreset objectForKey:@"PictureHeight"] intValue])
  4818. {
  4819. /* if so, then we use the sources height and width to avoid scaling up */
  4820. //job->width = fTitle->width;
  4821. //job->height = fTitle->height;
  4822. [self revertPictureSizeToMax:nil];
  4823. }
  4824. else // source width/height is >= the preset height/width
  4825. {
  4826. /* we can go ahead and use the presets values for height and width */
  4827. job->width = [[chosenPreset objectForKey:@"PictureWidth"] intValue];
  4828. job->height = [[chosenPreset objectForKey:@"PictureHeight"] intValue];
  4829. }
  4830. job->keep_ratio = [[chosenPreset objectForKey:@"PictureKeepRatio"] intValue];
  4831. if (job->keep_ratio == 1)
  4832. {
  4833. int height = fTitle->height;
  4834. if ( job->height && job->height < fTitle->height )
  4835. height = job->height;
  4836. hb_fix_aspect( job, HB_KEEP_WIDTH );
  4837. // Make sure the resulting height is less than
  4838. // the title height and less than the height
  4839. // requested in the preset.
  4840. if( job->height > height )
  4841. {
  4842. job->height = height;
  4843. hb_fix_aspect( job, HB_KEEP_HEIGHT );
  4844. }
  4845. }
  4846. job->anamorphic.mode = [[chosenPreset objectForKey:@"PicturePAR"] intValue];
  4847. if ( job->anamorphic.mode > 0 )
  4848. {
  4849. int w, h, par_w, par_h;
  4850. job->anamorphic.par_width = fTitle->pixel_aspect_width;
  4851. job->anamorphic.par_height = fTitle->pixel_aspect_height;
  4852. job->maxWidth = job->width;
  4853. job->maxHeight = job->height;
  4854. hb_set_anamorphic_size( job, &w, &h, &par_w, &par_h );
  4855. job->maxWidth = 0;
  4856. job->maxHeight = 0;
  4857. job->width = w;
  4858. job->height = h;
  4859. }
  4860. }
  4861. }
  4862. /* If the preset has an objectForKey:@"UsesPictureFilters", and handle the filters here */
  4863. if ([chosenPreset objectForKey:@"UsesPictureFilters"] && [[chosenPreset objectForKey:@"UsesPictureFilters"] intValue] > 0)
  4864. {
  4865. /* Filters */
  4866. /* We only allow *either* Decomb or Deinterlace. So check for the PictureDecombDeinterlace key.
  4867. * also, older presets may not have this key, in which case we also check to see if that preset had PictureDecomb
  4868. * specified, in which case we use decomb and ignore any possible Deinterlace settings as using both was less than
  4869. * sane.
  4870. */
  4871. [fPictureController setUseDecomb:1];
  4872. [fPictureController setDecomb:0];
  4873. [fPictureController setDeinterlace:0];
  4874. if ([[chosenPreset objectForKey:@"PictureDecombDeinterlace"] intValue] == 1 || [[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
  4875. {
  4876. /* we are using decomb */
  4877. /* Decomb */
  4878. if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] > 0)
  4879. {
  4880. [fPictureController setDecomb:[[chosenPreset objectForKey:@"PictureDecomb"] intValue]];
  4881. /* if we are using "Custom" in the decomb setting, also set the custom string*/
  4882. if ([[chosenPreset objectForKey:@"PictureDecomb"] intValue] == 1)
  4883. {
  4884. [fPictureController setDecombCustomString:[chosenPreset objectForKey:@"PictureDecombCustom"]];
  4885. }
  4886. }
  4887. }
  4888. else
  4889. {
  4890. /* We are using Deinterlace */
  4891. /* Deinterlace */
  4892. if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] > 0)
  4893. {
  4894. [fPictureController setUseDecomb:0];
  4895. [fPictureController setDeinterlace:[[chosenPreset objectForKey:@"PictureDeinterlace"] intValue]];
  4896. /* if we are using "Custom" in the deinterlace setting, also set the custom string*/
  4897. if ([[chosenPreset objectForKey:@"PictureDeinterlace"] intValue] == 1)
  4898. {
  4899. [fPictureController setDeinterlaceCustomString:[chosenPreset objectForKey:@"PictureDeinterlaceCustom"]];
  4900. }
  4901. }
  4902. }
  4903. /* Detelecine */
  4904. if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] > 0)
  4905. {
  4906. [fPictureController setDetelecine:[[chosenPreset objectForKey:@"PictureDetelecine"] intValue]];
  4907. /* if we are using "Custom" in the detelecine setting, also set the custom string*/
  4908. if ([[chosenPreset objectForKey:@"PictureDetelecine"] intValue] == 1)
  4909. {
  4910. [fPictureController setDetelecineCustomString:[chosenPreset objectForKey:@"PictureDetelecineCustom"]];
  4911. }
  4912. }
  4913. else
  4914. {
  4915. [fPictureController setDetelecine:0];
  4916. }
  4917. /* Denoise */
  4918. if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] > 0)
  4919. {
  4920. [fPictureController setDenoise:[[chosenPreset objectForKey:@"PictureDenoise"] intValue]];
  4921. /* if we are using "Custom" in the denoise setting, also set the custom string*/
  4922. if ([[chosenPreset objectForKey:@"PictureDenoise"] intValue] == 1)
  4923. {
  4924. [fPictureController setDenoiseCustomString:[chosenPreset objectForKey:@"PictureDenoiseCustom"]];
  4925. }
  4926. }
  4927. else
  4928. {
  4929. [fPictureController setDenoise:0];
  4930. }
  4931. /* Deblock */
  4932. if ([[chosenPreset objectForKey:@"PictureDeblock"] intValue] == 1)
  4933. {
  4934. /* if its a one, then its the old on/off deblock, set on to 5*/
  4935. [fPictureController setDeblock:5];
  4936. }
  4937. else
  4938. {
  4939. /* use the settings intValue */
  4940. [fPictureController setDeblock:[[chosenPreset objectForKey:@"PictureDeblock"] intValue]];
  4941. }
  4942. if ([[chosenPreset objectForKey:@"VideoGrayScale"] intValue] == 1)
  4943. {
  4944. [fPictureController setGrayscale:1];
  4945. }
  4946. else
  4947. {
  4948. [fPictureController setGrayscale:0];
  4949. }
  4950. }
  4951. /* we call SetTitle: in fPictureController so we get an instant update in the Picture Settings window */
  4952. [fPictureController SetTitle:fTitle];
  4953. [fPictureController SetTitle:fTitle];
  4954. [self calculatePictureSizing:nil];
  4955. }
  4956. }
  4957. #pragma mark -
  4958. #pragma mark Manage Presets
  4959. - (void) loadPresets {
  4960. /* We declare the default NSFileManager into fileManager */
  4961. NSFileManager * fileManager = [NSFileManager defaultManager];
  4962. /*We define the location of the user presets file */
  4963. UserPresetsFile = @"~/Library/Application Support/HandBrake/UserPresets.plist";
  4964. UserPresetsFile = [[UserPresetsFile stringByExpandingTildeInPath]retain];
  4965. /* We check for the presets.plist */
  4966. if ([fileManager fileExistsAtPath:UserPresetsFile] == 0)
  4967. {
  4968. [fileManager createFileAtPath:UserPresetsFile contents:nil attributes:nil];
  4969. }
  4970. UserPresets = [[NSMutableArray alloc] initWithContentsOfFile:UserPresetsFile];
  4971. if (nil == UserPresets)
  4972. {
  4973. UserPresets = [[NSMutableArray alloc] init];
  4974. [self addFactoryPresets:nil];
  4975. }
  4976. [fPresetsOutlineView reloadData];
  4977. [self checkBuiltInsForUpdates];
  4978. }
  4979. - (void) checkBuiltInsForUpdates {
  4980. BOOL updateBuiltInPresets = NO;
  4981. int i = 0;
  4982. NSEnumerator *enumerator = [UserPresets objectEnumerator];
  4983. id tempObject;
  4984. while (tempObject = [enumerator nextObject])
  4985. {
  4986. /* iterate through the built in presets to see if any have an old build number */
  4987. NSMutableDictionary *thisPresetDict = tempObject;
  4988. /*Key Type == 0 is built in, and key PresetBuildNumber is the build number it was created with */
  4989. if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0)
  4990. {
  4991. if (![thisPresetDict objectForKey:@"PresetBuildNumber"] || [[thisPresetDict objectForKey:@"PresetBuildNumber"] intValue] < [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue])
  4992. {
  4993. updateBuiltInPresets = YES;
  4994. }
  4995. }
  4996. i++;
  4997. }
  4998. /* if we have built in presets to update, then do so AlertBuiltInPresetUpdate*/
  4999. if ( updateBuiltInPresets == YES)
  5000. {
  5001. if( [[NSUserDefaults standardUserDefaults] boolForKey:@"AlertBuiltInPresetUpdate"] == YES)
  5002. {
  5003. /* Show an alert window that built in presets will be updated */
  5004. /*On Screen Notification*/
  5005. int status;
  5006. NSBeep();
  5007. status = NSRunAlertPanel(@"HandBrake has determined your built in presets are out of date...",@"HandBrake will now update your built-in presets.", @"OK", nil, nil);
  5008. [NSApp requestUserAttention:NSCriticalRequest];
  5009. }
  5010. /* when alert is dismissed, go ahead and update the built in presets */
  5011. [self addFactoryPresets:nil];
  5012. }
  5013. }
  5014. - (IBAction) addPresetPicDropdownChanged: (id) sender
  5015. {
  5016. if ([fPresetNewPicSettingsPopUp indexOfSelectedItem] == 1)
  5017. {
  5018. [fPresetNewPicWidthHeightBox setHidden:NO];
  5019. }
  5020. else
  5021. {
  5022. [fPresetNewPicWidthHeightBox setHidden:YES];
  5023. }
  5024. }
  5025. - (IBAction) showAddPresetPanel: (id) sender
  5026. {
  5027. /* Deselect the currently selected Preset if there is one*/
  5028. [fPresetsOutlineView deselectRow:[fPresetsOutlineView selectedRow]];
  5029. /* Populate the preset picture settings popup here */
  5030. [fPresetNewPicSettingsPopUp removeAllItems];
  5031. [fPresetNewPicSettingsPopUp addItemWithTitle:@"None"];
  5032. [fPresetNewPicSettingsPopUp addItemWithTitle:@"Custom"];
  5033. [fPresetNewPicSettingsPopUp addItemWithTitle:@"Source Maximum (post source scan)"];
  5034. [fPresetNewPicSettingsPopUp selectItemAtIndex: 0];
  5035. /* Uncheck the preset use filters checkbox */
  5036. [fPresetNewPicFiltersCheck setState:NSOffState];
  5037. // fPresetNewFolderCheck
  5038. [fPresetNewFolderCheck setState:NSOffState];
  5039. /* Erase info from the input fields*/
  5040. [fPresetNewName setStringValue: @""];
  5041. [fPresetNewDesc setStringValue: @""];
  5042. /* Initialize custom height and width settings to current values */
  5043. [fPresetNewPicWidth setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->width]];
  5044. [fPresetNewPicHeight setStringValue: [NSString stringWithFormat:@"%d",fTitle->job->height]];
  5045. [self addPresetPicDropdownChanged:nil];
  5046. /* Show the panel */
  5047. [NSApp beginSheet:fAddPresetPanel modalForWindow:fWindow modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
  5048. }
  5049. - (IBAction) closeAddPresetPanel: (id) sender
  5050. {
  5051. [NSApp endSheet: fAddPresetPanel];
  5052. [fAddPresetPanel orderOut: self];
  5053. }
  5054. - (IBAction)addUserPreset:(id)sender
  5055. {
  5056. if (![[fPresetNewName stringValue] length])
  5057. NSRunAlertPanel(@"Warning!", @"You need to insert a name for the preset.", @"OK", nil , nil);
  5058. else
  5059. {
  5060. /* Here we create a custom user preset */
  5061. [UserPresets addObject:[self createPreset]];
  5062. [self addPreset];
  5063. [self closeAddPresetPanel:nil];
  5064. }
  5065. }
  5066. - (void)addPreset
  5067. {
  5068. /* We Reload the New Table data for presets */
  5069. [fPresetsOutlineView reloadData];
  5070. /* We save all of the preset data here */
  5071. [self savePreset];
  5072. }
  5073. - (void)sortPresets
  5074. {
  5075. /* We Sort the Presets By Factory or Custom */
  5076. NSSortDescriptor * presetTypeDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"Type"
  5077. ascending:YES] autorelease];
  5078. /* We Sort the Presets Alphabetically by name We do not use this now as we have drag and drop*/
  5079. /*
  5080. NSSortDescriptor * presetNameDescriptor=[[[NSSortDescriptor alloc] initWithKey:@"PresetName"
  5081. ascending:YES selector:@selector(caseInsensitiveCompare:)] autorelease];
  5082. //NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,presetNameDescriptor,nil];
  5083. */
  5084. /* Since we can drag and drop our custom presets, lets just sort by type and not name */
  5085. NSArray *sortDescriptors=[NSArray arrayWithObjects:presetTypeDescriptor,nil];
  5086. NSArray *sortedArray=[UserPresets sortedArrayUsingDescriptors:sortDescriptors];
  5087. [UserPresets setArray:sortedArray];
  5088. }
  5089. - (IBAction)insertPreset:(id)sender
  5090. {
  5091. int index = [fPresetsOutlineView selectedRow];
  5092. [UserPresets insertObject:[self createPreset] atIndex:index];
  5093. [fPresetsOutlineView reloadData];
  5094. [self savePreset];
  5095. }
  5096. - (NSDictionary *)createPreset
  5097. {
  5098. NSMutableDictionary *preset = [[NSMutableDictionary alloc] init];
  5099. /* Preset build number */
  5100. [preset setObject:[NSString stringWithFormat: @"%d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
  5101. [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
  5102. /* Get the New Preset Name from the field in the AddPresetPanel */
  5103. [preset setObject:[fPresetNewName stringValue] forKey:@"PresetName"];
  5104. /* Set whether or not this is to be a folder fPresetNewFolderCheck*/
  5105. [preset setObject:[NSNumber numberWithBool:[fPresetNewFolderCheck state]] forKey:@"Folder"];
  5106. /*Set whether or not this is a user preset or factory 0 is factory, 1 is user*/
  5107. [preset setObject:[NSNumber numberWithInt:1] forKey:@"Type"];
  5108. /*Set whether or not this is default, at creation set to 0*/
  5109. [preset setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
  5110. if ([fPresetNewFolderCheck state] == YES)
  5111. {
  5112. /* initialize and set an empty array for children here since we are a new folder */
  5113. NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
  5114. [preset setObject:[NSMutableArray arrayWithArray: childrenArray] forKey:@"ChildrenArray"];
  5115. [childrenArray autorelease];
  5116. }
  5117. else // we are not creating a preset folder, so we go ahead with the rest of the preset info
  5118. {
  5119. /*Get the whether or not to apply pic Size and Cropping (includes Anamorphic)*/
  5120. [preset setObject:[NSNumber numberWithInt:[fPresetNewPicSettingsPopUp indexOfSelectedItem]] forKey:@"UsesPictureSettings"];
  5121. /* Get whether or not to use the current Picture Filter settings for the preset */
  5122. [preset setObject:[NSNumber numberWithInt:[fPresetNewPicFiltersCheck state]] forKey:@"UsesPictureFilters"];
  5123. /* Get New Preset Description from the field in the AddPresetPanel*/
  5124. [preset setObject:[fPresetNewDesc stringValue] forKey:@"PresetDescription"];
  5125. /* File Format */
  5126. [preset setObject:[fDstFormatPopUp titleOfSelectedItem] forKey:@"FileFormat"];
  5127. /* Chapter Markers fCreateChapterMarkers*/
  5128. [preset setObject:[NSNumber numberWithInt:[fCreateChapterMarkers state]] forKey:@"ChapterMarkers"];
  5129. /* Allow Mpeg4 64 bit formatting +4GB file sizes */
  5130. [preset setObject:[NSNumber numberWithInt:[fDstMp4LargeFileCheck state]] forKey:@"Mp4LargeFile"];
  5131. /* Mux mp4 with http optimization */
  5132. [preset setObject:[NSNumber numberWithInt:[fDstMp4HttpOptFileCheck state]] forKey:@"Mp4HttpOptimize"];
  5133. /* Add iPod uuid atom */
  5134. [preset setObject:[NSNumber numberWithInt:[fDstMp4iPodFileCheck state]] forKey:@"Mp4iPodCompatible"];
  5135. /* Codecs */
  5136. /* Video encoder */
  5137. [preset setObject:[fVidEncoderPopUp titleOfSelectedItem] forKey:@"VideoEncoder"];
  5138. /* x264 Option String */
  5139. [preset setObject:[fAdvancedOptions optionsString] forKey:@"x264Option"];
  5140. [preset setObject:[NSNumber numberWithInt:[fVidQualityMatrix selectedRow]] forKey:@"VideoQualityType"];
  5141. [preset setObject:[fVidTargetSizeField stringValue] forKey:@"VideoTargetSize"];
  5142. [preset setObject:[fVidBitrateField stringValue] forKey:@"VideoAvgBitrate"];
  5143. [preset setObject:[NSNumber numberWithFloat:[fVidQualityRFField floatValue]] forKey:@"VideoQualitySlider"];
  5144. /* Video framerate */
  5145. if ([fVidRatePopUp indexOfSelectedItem] == 0) // Same as source is selected
  5146. {
  5147. [preset setObject:@"Same as source" forKey:@"VideoFramerate"];
  5148. }
  5149. else // we can record the actual titleOfSelectedItem
  5150. {
  5151. [preset setObject:[fVidRatePopUp titleOfSelectedItem] forKey:@"VideoFramerate"];
  5152. }
  5153. [preset setObject:[NSNumber numberWithInt:[fFrameratePfrCheck state]] forKey:@"VideoFrameratePFR"];
  5154. /* 2 Pass Encoding */
  5155. [preset setObject:[NSNumber numberWithInt:[fVidTwoPassCheck state]] forKey:@"VideoTwoPass"];
  5156. /* Turbo 2 pass Encoding fVidTurboPassCheck*/
  5157. [preset setObject:[NSNumber numberWithInt:[fVidTurboPassCheck state]] forKey:@"VideoTurboTwoPass"];
  5158. /*Picture Settings*/
  5159. hb_job_t * job = fTitle->job;
  5160. /* Picture Sizing */
  5161. [preset setObject:[NSNumber numberWithInt:0] forKey:@"UsesMaxPictureSettings"];
  5162. [preset setObject:[NSNumber numberWithInt:[fPresetNewPicWidth intValue]] forKey:@"PictureWidth"];
  5163. [preset setObject:[NSNumber numberWithInt:[fPresetNewPicHeight intValue]] forKey:@"PictureHeight"];
  5164. [preset setObject:[NSNumber numberWithInt:fTitle->job->keep_ratio] forKey:@"PictureKeepRatio"];
  5165. [preset setObject:[NSNumber numberWithInt:fTitle->job->anamorphic.mode] forKey:@"PicturePAR"];
  5166. [preset setObject:[NSNumber numberWithInt:fTitle->job->modulus] forKey:@"PictureModulus"];
  5167. /* Set crop settings here */
  5168. [preset setObject:[NSNumber numberWithInt:[fPictureController autoCrop]] forKey:@"PictureAutoCrop"];
  5169. [preset setObject:[NSNumber numberWithInt:job->crop[0]] forKey:@"PictureTopCrop"];
  5170. [preset setObject:[NSNumber numberWithInt:job->crop[1]] forKey:@"PictureBottomCrop"];
  5171. [preset setObject:[NSNumber numberWithInt:job->crop[2]] forKey:@"PictureLeftCrop"];
  5172. [preset setObject:[NSNumber numberWithInt:job->crop[3]] forKey:@"PictureRightCrop"];
  5173. /* Picture Filters */
  5174. [preset setObject:[NSNumber numberWithInt:[fPictureController useDecomb]] forKey:@"PictureDecombDeinterlace"];
  5175. [preset setObject:[NSNumber numberWithInt:[fPictureController deinterlace]] forKey:@"PictureDeinterlace"];
  5176. [preset setObject:[fPictureController deinterlaceCustomString] forKey:@"PictureDeinterlaceCustom"];
  5177. [preset setObject:[NSNumber numberWithInt:[fPictureController detelecine]] forKey:@"PictureDetelecine"];
  5178. [preset setObject:[fPictureController detelecineCustomString] forKey:@"PictureDetelecineCustom"];
  5179. [preset setObject:[NSNumber numberWithInt:[fPictureController denoise]] forKey:@"PictureDenoise"];
  5180. [preset setObject:[fPictureController denoiseCustomString] forKey:@"PictureDenoiseCustom"];
  5181. [preset setObject:[NSNumber numberWithInt:[fPictureController deblock]] forKey:@"PictureDeblock"];
  5182. [preset setObject:[NSNumber numberWithInt:[fPictureController decomb]] forKey:@"PictureDecomb"];
  5183. [preset setObject:[fPictureController decombCustomString] forKey:@"PictureDecombCustom"];
  5184. [preset setObject:[NSNumber numberWithInt:[fPictureController grayscale]] forKey:@"VideoGrayScale"];
  5185. /*Audio*/
  5186. NSMutableArray *audioListArray = [[NSMutableArray alloc] init];
  5187. [fAudioDelegate prepareAudioForPreset: audioListArray];
  5188. [preset setObject:[NSMutableArray arrayWithArray: audioListArray] forKey:@"AudioList"];
  5189. /* Temporarily remove subtitles from creating a new preset as it has to be converted over to use the new
  5190. * subititle array code. */
  5191. /* Subtitles*/
  5192. //[preset setObject:[fSubPopUp titleOfSelectedItem] forKey:@"Subtitles"];
  5193. /* Forced Subtitles */
  5194. //[preset setObject:[NSNumber numberWithInt:[fSubForcedCheck state]] forKey:@"SubtitlesForced"];
  5195. }
  5196. [preset autorelease];
  5197. return preset;
  5198. }
  5199. - (void)savePreset
  5200. {
  5201. [UserPresets writeToFile:UserPresetsFile atomically:YES];
  5202. /* We get the default preset in case it changed */
  5203. [self getDefaultPresets:nil];
  5204. }
  5205. - (IBAction)deletePreset:(id)sender
  5206. {
  5207. if ( [fPresetsOutlineView numberOfSelectedRows] == 0 )
  5208. {
  5209. return;
  5210. }
  5211. /* Alert user before deleting preset */
  5212. int status;
  5213. status = NSRunAlertPanel(@"Warning!", @"Are you sure that you want to delete the selected preset?", @"OK", @"Cancel", nil);
  5214. if ( status == NSAlertDefaultReturn )
  5215. {
  5216. int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
  5217. NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
  5218. NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
  5219. NSEnumerator *enumerator;
  5220. NSMutableArray *presetsArrayToMod;
  5221. NSMutableArray *tempArray;
  5222. id tempObject;
  5223. /* If we are a root level preset, we are modding the UserPresets array */
  5224. if (presetToModLevel == 0)
  5225. {
  5226. presetsArrayToMod = UserPresets;
  5227. }
  5228. else // We have a parent preset, so we modify the chidren array object for key
  5229. {
  5230. presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
  5231. }
  5232. enumerator = [presetsArrayToMod objectEnumerator];
  5233. tempArray = [NSMutableArray array];
  5234. while (tempObject = [enumerator nextObject])
  5235. {
  5236. NSDictionary *thisPresetDict = tempObject;
  5237. if (thisPresetDict == presetToMod)
  5238. {
  5239. [tempArray addObject:tempObject];
  5240. }
  5241. }
  5242. [presetsArrayToMod removeObjectsInArray:tempArray];
  5243. [fPresetsOutlineView reloadData];
  5244. [self savePreset];
  5245. }
  5246. }
  5247. #pragma mark -
  5248. #pragma mark Import Export Preset(s)
  5249. - (IBAction) browseExportPresetFile: (id) sender
  5250. {
  5251. /* Open a panel to let the user choose where and how to save the export file */
  5252. NSSavePanel * panel = [NSSavePanel savePanel];
  5253. /* We get the current file name and path from the destination field here */
  5254. NSString *defaultExportDirectory = [NSString stringWithFormat: @"%@/Desktop/", NSHomeDirectory()];
  5255. [panel beginSheetForDirectory: defaultExportDirectory file: @"HB_Export.plist"
  5256. modalForWindow: fWindow modalDelegate: self
  5257. didEndSelector: @selector( browseExportPresetFileDone:returnCode:contextInfo: )
  5258. contextInfo: NULL];
  5259. }
  5260. - (void) browseExportPresetFileDone: (NSSavePanel *) sheet
  5261. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  5262. {
  5263. if( returnCode == NSOKButton )
  5264. {
  5265. NSString *presetExportDirectory = [[sheet filename] stringByDeletingLastPathComponent];
  5266. NSString *exportPresetsFile = [sheet filename];
  5267. [[NSUserDefaults standardUserDefaults] setObject:presetExportDirectory forKey:@"LastPresetExportDirectory"];
  5268. /* We check for the presets.plist */
  5269. if ([[NSFileManager defaultManager] fileExistsAtPath:exportPresetsFile] == 0)
  5270. {
  5271. [[NSFileManager defaultManager] createFileAtPath:exportPresetsFile contents:nil attributes:nil];
  5272. }
  5273. NSMutableArray * presetsToExport = [[NSMutableArray alloc] initWithContentsOfFile:exportPresetsFile];
  5274. if (nil == presetsToExport)
  5275. {
  5276. presetsToExport = [[NSMutableArray alloc] init];
  5277. /* now get and add selected presets to export */
  5278. }
  5279. if (YES == [self hasValidPresetSelected])
  5280. {
  5281. [presetsToExport addObject:[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
  5282. [presetsToExport writeToFile:exportPresetsFile atomically:YES];
  5283. }
  5284. }
  5285. }
  5286. - (IBAction) browseImportPresetFile: (id) sender
  5287. {
  5288. NSOpenPanel * panel;
  5289. panel = [NSOpenPanel openPanel];
  5290. [panel setAllowsMultipleSelection: NO];
  5291. [panel setCanChooseFiles: YES];
  5292. [panel setCanChooseDirectories: NO ];
  5293. NSString * sourceDirectory;
  5294. if ([[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"])
  5295. {
  5296. sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastPresetImportDirectory"];
  5297. }
  5298. else
  5299. {
  5300. sourceDirectory = @"~/Desktop";
  5301. sourceDirectory = [sourceDirectory stringByExpandingTildeInPath];
  5302. }
  5303. /* we open up the browse sources sheet here and call for browseSourcesDone after the sheet is closed
  5304. * to evaluate whether we want to specify a title, we pass the sender in the contextInfo variable
  5305. */
  5306. /* set this for allowed file types, not sure if we should allow xml or not */
  5307. NSArray *fileTypes = [NSArray arrayWithObjects:@"plist", @"xml", nil];
  5308. [panel beginSheetForDirectory: sourceDirectory file: nil types: fileTypes
  5309. modalForWindow: fWindow modalDelegate: self
  5310. didEndSelector: @selector( browseImportPresetDone:returnCode:contextInfo: )
  5311. contextInfo: sender];
  5312. }
  5313. - (void) browseImportPresetDone: (NSSavePanel *) sheet
  5314. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  5315. {
  5316. if( returnCode == NSOKButton )
  5317. {
  5318. NSString *importPresetsDirectory = [[sheet filename] stringByDeletingLastPathComponent];
  5319. NSString *importPresetsFile = [sheet filename];
  5320. [[NSUserDefaults standardUserDefaults] setObject:importPresetsDirectory forKey:@"LastPresetImportDirectory"];
  5321. /* NOTE: here we need to do some sanity checking to verify we do not hose up our presets file */
  5322. NSMutableArray * presetsToImport = [[NSMutableArray alloc] initWithContentsOfFile:importPresetsFile];
  5323. /* iterate though the new array of presets to import and add them to our presets array */
  5324. int i = 0;
  5325. NSEnumerator *enumerator = [presetsToImport objectEnumerator];
  5326. id tempObject;
  5327. while (tempObject = [enumerator nextObject])
  5328. {
  5329. /* make any changes to the incoming preset we see fit */
  5330. /* make sure the incoming preset is not tagged as default */
  5331. [tempObject setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
  5332. /* prepend "(imported) to the name of the incoming preset for clarification since it can be changed */
  5333. NSString * prependedName = [@"(import) " stringByAppendingString:[tempObject objectForKey:@"PresetName"]] ;
  5334. [tempObject setObject:prependedName forKey:@"PresetName"];
  5335. /* actually add the new preset to our presets array */
  5336. [UserPresets addObject:tempObject];
  5337. i++;
  5338. }
  5339. [presetsToImport autorelease];
  5340. [self sortPresets];
  5341. [self addPreset];
  5342. }
  5343. }
  5344. #pragma mark -
  5345. #pragma mark Manage Default Preset
  5346. - (IBAction)getDefaultPresets:(id)sender
  5347. {
  5348. presetHbDefault = nil;
  5349. presetUserDefault = nil;
  5350. presetUserDefaultParent = nil;
  5351. presetUserDefaultParentParent = nil;
  5352. NSMutableDictionary *presetHbDefaultParent = nil;
  5353. NSMutableDictionary *presetHbDefaultParentParent = nil;
  5354. int i = 0;
  5355. BOOL userDefaultFound = NO;
  5356. presetCurrentBuiltInCount = 0;
  5357. /* First we iterate through the root UserPresets array to check for defaults */
  5358. NSEnumerator *enumerator = [UserPresets objectEnumerator];
  5359. id tempObject;
  5360. while (tempObject = [enumerator nextObject])
  5361. {
  5362. NSMutableDictionary *thisPresetDict = tempObject;
  5363. if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
  5364. {
  5365. presetHbDefault = thisPresetDict;
  5366. }
  5367. if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
  5368. {
  5369. presetUserDefault = thisPresetDict;
  5370. userDefaultFound = YES;
  5371. }
  5372. if ([[thisPresetDict objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
  5373. {
  5374. presetCurrentBuiltInCount++; // <--increment the current number of built in presets
  5375. }
  5376. i++;
  5377. /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
  5378. if ([thisPresetDict objectForKey:@"ChildrenArray"])
  5379. {
  5380. NSMutableDictionary *thisPresetDictParent = thisPresetDict;
  5381. NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
  5382. id tempObject;
  5383. while (tempObject = [enumerator nextObject])
  5384. {
  5385. NSMutableDictionary *thisPresetDict = tempObject;
  5386. if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
  5387. {
  5388. presetHbDefault = thisPresetDict;
  5389. presetHbDefaultParent = thisPresetDictParent;
  5390. }
  5391. if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
  5392. {
  5393. presetUserDefault = thisPresetDict;
  5394. presetUserDefaultParent = thisPresetDictParent;
  5395. userDefaultFound = YES;
  5396. }
  5397. /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
  5398. if ([thisPresetDict objectForKey:@"ChildrenArray"])
  5399. {
  5400. NSMutableDictionary *thisPresetDictParentParent = thisPresetDict;
  5401. NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
  5402. id tempObject;
  5403. while (tempObject = [enumerator nextObject])
  5404. {
  5405. NSMutableDictionary *thisPresetDict = tempObject;
  5406. if ([[thisPresetDict objectForKey:@"Default"] intValue] == 1) // 1 is HB default
  5407. {
  5408. presetHbDefault = thisPresetDict;
  5409. presetHbDefaultParent = thisPresetDictParent;
  5410. presetHbDefaultParentParent = thisPresetDictParentParent;
  5411. }
  5412. if ([[thisPresetDict objectForKey:@"Default"] intValue] == 2) // 2 is User specified default
  5413. {
  5414. presetUserDefault = thisPresetDict;
  5415. presetUserDefaultParent = thisPresetDictParent;
  5416. presetUserDefaultParentParent = thisPresetDictParentParent;
  5417. userDefaultFound = YES;
  5418. }
  5419. }
  5420. }
  5421. }
  5422. }
  5423. }
  5424. /* check to see if a user specified preset was found, if not then assign the parents for
  5425. * the presetHbDefault so that we can open the parents for the nested presets
  5426. */
  5427. if (userDefaultFound == NO)
  5428. {
  5429. presetUserDefaultParent = presetHbDefaultParent;
  5430. presetUserDefaultParentParent = presetHbDefaultParentParent;
  5431. }
  5432. }
  5433. - (IBAction)setDefaultPreset:(id)sender
  5434. {
  5435. /* We need to determine if the item is a folder */
  5436. if ([[[fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]] objectForKey:@"Folder"] intValue] == 1)
  5437. {
  5438. return;
  5439. }
  5440. int i = 0;
  5441. NSEnumerator *enumerator = [UserPresets objectEnumerator];
  5442. id tempObject;
  5443. /* First make sure the old user specified default preset is removed */
  5444. while (tempObject = [enumerator nextObject])
  5445. {
  5446. NSMutableDictionary *thisPresetDict = tempObject;
  5447. if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
  5448. {
  5449. [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
  5450. }
  5451. /* if we run into a folder, go to level 1 and iterate through the children arrays for the default */
  5452. if ([thisPresetDict objectForKey:@"ChildrenArray"])
  5453. {
  5454. NSEnumerator *enumerator = [[thisPresetDict objectForKey:@"ChildrenArray"] objectEnumerator];
  5455. id tempObject;
  5456. int ii = 0;
  5457. while (tempObject = [enumerator nextObject])
  5458. {
  5459. NSMutableDictionary *thisPresetDict1 = tempObject;
  5460. if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
  5461. {
  5462. [[[thisPresetDict objectForKey:@"ChildrenArray"] objectAtIndex:ii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
  5463. }
  5464. /* if we run into a folder, go to level 2 and iterate through the children arrays for the default */
  5465. if ([thisPresetDict1 objectForKey:@"ChildrenArray"])
  5466. {
  5467. NSEnumerator *enumerator = [[thisPresetDict1 objectForKey:@"ChildrenArray"] objectEnumerator];
  5468. id tempObject;
  5469. int iii = 0;
  5470. while (tempObject = [enumerator nextObject])
  5471. {
  5472. if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 0
  5473. {
  5474. [[[thisPresetDict1 objectForKey:@"ChildrenArray"] objectAtIndex:iii] setObject:[NSNumber numberWithInt:0] forKey:@"Default"];
  5475. }
  5476. iii++;
  5477. }
  5478. }
  5479. ii++;
  5480. }
  5481. }
  5482. i++;
  5483. }
  5484. int presetToModLevel = [fPresetsOutlineView levelForItem: [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]]];
  5485. NSDictionary *presetToMod = [fPresetsOutlineView itemAtRow:[fPresetsOutlineView selectedRow]];
  5486. NSDictionary *presetToModParent = [fPresetsOutlineView parentForItem: presetToMod];
  5487. NSMutableArray *presetsArrayToMod;
  5488. NSMutableArray *tempArray;
  5489. /* If we are a root level preset, we are modding the UserPresets array */
  5490. if (presetToModLevel == 0)
  5491. {
  5492. presetsArrayToMod = UserPresets;
  5493. }
  5494. else // We have a parent preset, so we modify the chidren array object for key
  5495. {
  5496. presetsArrayToMod = [presetToModParent objectForKey:@"ChildrenArray"];
  5497. }
  5498. enumerator = [presetsArrayToMod objectEnumerator];
  5499. tempArray = [NSMutableArray array];
  5500. int iiii = 0;
  5501. while (tempObject = [enumerator nextObject])
  5502. {
  5503. NSDictionary *thisPresetDict = tempObject;
  5504. if (thisPresetDict == presetToMod)
  5505. {
  5506. if ([[tempObject objectForKey:@"Default"] intValue] != 1) // if not the default HB Preset, set to 2
  5507. {
  5508. [[presetsArrayToMod objectAtIndex:iiii] setObject:[NSNumber numberWithInt:2] forKey:@"Default"];
  5509. }
  5510. }
  5511. iiii++;
  5512. }
  5513. /* We save all of the preset data here */
  5514. [self savePreset];
  5515. /* We Reload the New Table data for presets */
  5516. [fPresetsOutlineView reloadData];
  5517. }
  5518. - (IBAction)selectDefaultPreset:(id)sender
  5519. {
  5520. NSMutableDictionary *presetToMod;
  5521. /* if there is a user specified default, we use it */
  5522. if (presetUserDefault)
  5523. {
  5524. presetToMod = presetUserDefault;
  5525. }
  5526. else if (presetHbDefault) //else we use the built in default presetHbDefault
  5527. {
  5528. presetToMod = presetHbDefault;
  5529. }
  5530. else
  5531. {
  5532. return;
  5533. }
  5534. if (presetUserDefaultParent != nil)
  5535. {
  5536. [fPresetsOutlineView expandItem:presetUserDefaultParent];
  5537. }
  5538. if (presetUserDefaultParentParent != nil)
  5539. {
  5540. [fPresetsOutlineView expandItem:presetUserDefaultParentParent];
  5541. }
  5542. [fPresetsOutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[fPresetsOutlineView rowForItem: presetToMod]] byExtendingSelection:NO];
  5543. [self selectPreset:nil];
  5544. }
  5545. #pragma mark -
  5546. #pragma mark Manage Built In Presets
  5547. - (IBAction)deleteFactoryPresets:(id)sender
  5548. {
  5549. //int status;
  5550. NSEnumerator *enumerator = [UserPresets objectEnumerator];
  5551. id tempObject;
  5552. //NSNumber *index;
  5553. NSMutableArray *tempArray;
  5554. tempArray = [NSMutableArray array];
  5555. /* we look here to see if the preset is we move on to the next one */
  5556. while ( tempObject = [enumerator nextObject] )
  5557. {
  5558. /* if the preset is "Factory" then we put it in the array of
  5559. presets to delete */
  5560. if ([[tempObject objectForKey:@"Type"] intValue] == 0)
  5561. {
  5562. [tempArray addObject:tempObject];
  5563. }
  5564. }
  5565. [UserPresets removeObjectsInArray:tempArray];
  5566. [fPresetsOutlineView reloadData];
  5567. [self savePreset];
  5568. }
  5569. /* We use this method to recreate new, updated factory presets */
  5570. - (IBAction)addFactoryPresets:(id)sender
  5571. {
  5572. /* First, we delete any existing built in presets */
  5573. [self deleteFactoryPresets: sender];
  5574. /* Then we generate new built in presets programmatically with fPresetsBuiltin
  5575. * which is all setup in HBPresets.h and HBPresets.m*/
  5576. [fPresetsBuiltin generateBuiltinPresets:UserPresets];
  5577. /* update build number for built in presets */
  5578. /* iterate though the new array of presets to import and add them to our presets array */
  5579. int i = 0;
  5580. NSEnumerator *enumerator = [UserPresets objectEnumerator];
  5581. id tempObject;
  5582. while (tempObject = [enumerator nextObject])
  5583. {
  5584. /* Record the apps current build number in the PresetBuildNumber key */
  5585. if ([[tempObject objectForKey:@"Type"] intValue] == 0) // Type 0 is a built in preset
  5586. {
  5587. /* Preset build number */
  5588. [[UserPresets objectAtIndex:i] setObject:[NSNumber numberWithInt:[[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]] forKey:@"PresetBuildNumber"];
  5589. }
  5590. i++;
  5591. }
  5592. /* report the built in preset updating to the activity log */
  5593. [self writeToActivityLog: "built in presets updated to build number: %d", [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] intValue]];
  5594. [self sortPresets];
  5595. [self addPreset];
  5596. }
  5597. #pragma mark -
  5598. #pragma mark Chapter Files Import / Export
  5599. - (IBAction) browseForChapterFile: (id) sender
  5600. {
  5601. /* Open a panel to let the user choose the file */
  5602. NSOpenPanel * panel = [NSOpenPanel openPanel];
  5603. /* We get the current file name and path from the destination field here */
  5604. [panel beginSheetForDirectory: [NSString stringWithFormat:@"%@/",
  5605. [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"]]
  5606. file: NULL
  5607. types: [NSArray arrayWithObjects:@"csv",nil]
  5608. modalForWindow: fWindow modalDelegate: self
  5609. didEndSelector: @selector( browseForChapterFileDone:returnCode:contextInfo: )
  5610. contextInfo: NULL];
  5611. }
  5612. - (void) browseForChapterFileDone: (NSOpenPanel *) sheet
  5613. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  5614. {
  5615. NSArray *chaptersArray; /* temp array for chapters */
  5616. NSMutableArray *chaptersMutableArray; /* temp array for chapters */
  5617. NSString *chapterName; /* temp string from file */
  5618. int chapters, i;
  5619. if( returnCode == NSOKButton ) /* if they click OK */
  5620. {
  5621. chapterName = [[NSString alloc] initWithContentsOfFile:[sheet filename] encoding:NSUTF8StringEncoding error:NULL];
  5622. chaptersArray = [chapterName componentsSeparatedByString:@"\n"];
  5623. chaptersMutableArray= [chaptersArray mutableCopy];
  5624. chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
  5625. if ([chaptersMutableArray count] > 0)
  5626. {
  5627. /* if last item is empty remove it */
  5628. if ([[chaptersMutableArray objectAtIndex:[chaptersArray count]-1] length] == 0)
  5629. {
  5630. [chaptersMutableArray removeLastObject];
  5631. }
  5632. }
  5633. /* if chapters in table is not equal to array count */
  5634. if ((unsigned int) chapters != [chaptersMutableArray count])
  5635. {
  5636. [sheet close];
  5637. [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
  5638. defaultButton:NSLocalizedString(@"OK", @"OK")
  5639. alternateButton:NULL
  5640. otherButton:NULL
  5641. informativeTextWithFormat:NSLocalizedString(@"%d chapters expected, %d chapters found in %@", @"%d chapters expected, %d chapters found in %@"),
  5642. chapters, [chaptersMutableArray count], [[sheet filename] lastPathComponent]] runModal];
  5643. return;
  5644. }
  5645. /* otherwise, go ahead and populate table with array */
  5646. for (i=0; i<chapters; i++)
  5647. {
  5648. if([[chaptersMutableArray objectAtIndex:i] length] > 5)
  5649. {
  5650. /* avoid a segfault */
  5651. /* Get the Range.location of the first comma in the line and then put everything after that into chapterTitle */
  5652. NSRange firstCommaRange = [[chaptersMutableArray objectAtIndex:i] rangeOfString:@","];
  5653. NSString *chapterTitle = [[chaptersMutableArray objectAtIndex:i] substringFromIndex:firstCommaRange.location + 1];
  5654. /* Since we store our chapterTitle commas as "\," for the cli, we now need to remove the escaping "\" from the title */
  5655. chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"\\," withString:@","];
  5656. [fChapterTitlesDelegate tableView:fChapterTable
  5657. setObjectValue:chapterTitle
  5658. forTableColumn:fChapterTableNameColumn
  5659. row:i];
  5660. }
  5661. else
  5662. {
  5663. [sheet close];
  5664. [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
  5665. defaultButton:NSLocalizedString(@"OK", @"OK")
  5666. alternateButton:NULL
  5667. otherButton:NULL
  5668. informativeTextWithFormat:NSLocalizedString(@"%@ was not formatted as expected.", @"%@ was not formatted as expected."), [[sheet filename] lastPathComponent]] runModal];
  5669. [fChapterTable reloadData];
  5670. return;
  5671. }
  5672. }
  5673. [fChapterTable reloadData];
  5674. }
  5675. }
  5676. - (IBAction) browseForChapterFileSave: (id) sender
  5677. {
  5678. NSSavePanel *panel = [NSSavePanel savePanel];
  5679. /* Open a panel to let the user save to a file */
  5680. [panel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv",nil]];
  5681. [panel beginSheetForDirectory: [[fDstFile2Field stringValue] stringByDeletingLastPathComponent]
  5682. file: [[[[fDstFile2Field stringValue] lastPathComponent] stringByDeletingPathExtension]
  5683. stringByAppendingString:@"-chapters.csv"]
  5684. modalForWindow: fWindow
  5685. modalDelegate: self
  5686. didEndSelector: @selector( browseForChapterFileSaveDone:returnCode:contextInfo: )
  5687. contextInfo: NULL];
  5688. }
  5689. - (void) browseForChapterFileSaveDone: (NSSavePanel *) sheet
  5690. returnCode: (int) returnCode contextInfo: (void *) contextInfo
  5691. {
  5692. NSString *chapterName; /* pointer for string for later file-writing */
  5693. NSString *chapterTitle;
  5694. NSError *saveError = [[NSError alloc] init];
  5695. int chapters, i; /* ints for the number of chapters in the table and the loop */
  5696. if( returnCode == NSOKButton ) /* if they clicked OK */
  5697. {
  5698. chapters = [fChapterTitlesDelegate numberOfRowsInTableView:fChapterTable];
  5699. chapterName = [NSString string];
  5700. for (i=0; i<chapters; i++)
  5701. {
  5702. /* put each chapter title from the table into the array */
  5703. if (i<9)
  5704. { /* if i is from 0 to 8 (chapters 1 to 9) add two leading zeros */
  5705. chapterName = [chapterName stringByAppendingFormat:@"00%d,",i+1];
  5706. }
  5707. else if (i<99)
  5708. { /* if i is from 9 to 98 (chapters 10 to 99) add one leading zero */
  5709. chapterName = [chapterName stringByAppendingFormat:@"0%d,",i+1];
  5710. }
  5711. else if (i<999)
  5712. { /* in case i is from 99 to 998 (chapters 100 to 999) no leading zeros */
  5713. chapterName = [chapterName stringByAppendingFormat:@"%d,",i+1];
  5714. }
  5715. chapterTitle = [fChapterTitlesDelegate tableView:fChapterTable objectValueForTableColumn:fChapterTableNameColumn row:i];
  5716. /* escape any commas in the chapter name with "\," */
  5717. chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"," withString:@"\\,"];
  5718. chapterName = [chapterName stringByAppendingString:chapterTitle];
  5719. if (i+1 != chapters)
  5720. { /* if not the last chapter */
  5721. chapterName = [chapterName stringByAppendingString:@ "\n"];
  5722. }
  5723. }
  5724. /* try to write it to where the user wanted */
  5725. if (![chapterName writeToFile:[sheet filename]
  5726. atomically:NO
  5727. encoding:NSUTF8StringEncoding
  5728. error:&saveError])
  5729. {
  5730. [sheet close];
  5731. [[NSAlert alertWithError:saveError] runModal];
  5732. }
  5733. }
  5734. }
  5735. @end
  5736. /*******************************
  5737. * Subclass of the HBPresetsOutlineView *
  5738. *******************************/
  5739. @implementation HBPresetsOutlineView
  5740. - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent*)dragEvent offset:(NSPointPointer)dragImageOffset
  5741. {
  5742. fIsDragging = YES;
  5743. // By default, NSTableView only drags an image of the first column. Change this to
  5744. // drag an image of the queue's icon and PresetName columns.
  5745. NSArray * cols = [NSArray arrayWithObjects: [self tableColumnWithIdentifier:@"PresetName"], nil];
  5746. return [super dragImageForRowsWithIndexes:dragRows tableColumns:cols event:dragEvent offset:dragImageOffset];
  5747. }
  5748. - (void) mouseDown:(NSEvent *)theEvent
  5749. {
  5750. [super mouseDown:theEvent];
  5751. fIsDragging = NO;
  5752. }
  5753. - (BOOL) isDragging;
  5754. {
  5755. return fIsDragging;
  5756. }
  5757. @end