1 /* $Id: HBPreviewController.mm,v 1.11 2005/08/01 15:10:44 titer Exp $
3 This file is part of the HandBrake source code.
4 Homepage: <http://handbrake.fr/>.
5 It may be used under the terms of the GNU General Public License. */
7 #import "HBPreviewController.h"
10 @implementation QTMovieView ( HBQTkitExt )
11 - (void) mouseMoved:(NSEvent *)theEvent
13 [super mouseMoved:theEvent];
17 @interface PreviewController (Private)
19 - (NSSize)optimalViewSizeForImageSize: (NSSize)imageSize;
20 - (void)resizeSheetForViewSize: (NSSize)viewSize;
21 - (void)setViewSize: (NSSize)viewSize;
22 - (BOOL)viewNeedsToResizeToSize: (NSSize)newSize;
26 @implementation PreviewController
30 if (self = [super initWithWindowNibName:@"PicturePreview"])
32 // NSWindowController likes to lazily load its window. However since
33 // this controller tries to set all sorts of outlets before the window
34 // is displayed, we need it to load immediately. The correct way to do
35 // this, according to the documentation, is simply to invoke the window
38 // If/when we switch a lot of this stuff to bindings, this can probably
42 fPicturePreviews = [[NSMutableDictionary dictionaryWithCapacity: HB_NUM_HBLIB_PICTURES] retain];
43 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
44 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
45 fPreviewLibhb = hb_init(loggingLevel, 0);
53 //------------------------------------------------------------------------------------
54 // Displays and brings the picture window to the front
55 //------------------------------------------------------------------------------------
56 - (IBAction) showPreviewWindow: (id)sender
58 [self showWindow:sender];
59 [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"PreviewWindowIsOpen"];
61 /* lets set the preview window to accept mouse moved events */
62 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
64 [self pictureSliderChanged:nil];
65 [self startReceivingLibhbNotifications];
68 - (void)setHBController: (HBController *)controller
70 fHBController = controller;
75 [fPreviewWindow setDelegate:self];
76 if( ![[self window] setFrameUsingName:@"Preview"] )
77 [[self window] center];
78 [self setWindowFrameAutosaveName:@"Preview"];
79 [[self window] setExcludedFromWindowsMenu:YES];
81 /* lets set the preview window to accept mouse moved events */
82 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
83 //[self pictureSliderChanged:nil];
84 [self startReceivingLibhbNotifications];
87 /* we set the progress indicator to not use threaded animation
88 * as it causes a conflict with the qtmovieview's controllerbar
90 [fMovieCreationProgressIndicator setUsesThreadedAnimation:NO];
92 /* Setup our layers for core animation */
93 [fPictureViewArea setWantsLayer:YES];
94 [fPictureView setWantsLayer:YES];
96 [fCancelPreviewMovieButton setWantsLayer:YES];
97 [fMovieCreationProgressIndicator setWantsLayer:YES];
99 [fPictureControlBox setWantsLayer:YES];
100 [fEncodingControlBox setWantsLayer:YES];
101 [fMovieView setWantsLayer:YES];
102 [fMovieView setHidden:YES];
103 [fMovieView setDelegate:self];
105 /* Since the xib has everything off center for easy acess
106 * we align our views and windows here we an align to anything
107 * since it will actually change later upon source load, but
108 * for convenience we will use the fPictureViewArea
111 /* Align the still preview image view to the picture box */
112 [fPictureView setFrameSize:[fPictureViewArea frame].size];
113 [fMovieView setFrameSize:[fPictureViewArea frame].size];
114 //[fPreviewWindow setFrameSize:[fPictureViewArea frame].size];
118 - (BOOL)acceptsMouseMovedEvents
123 - (void)windowWillClose:(NSNotification *)aNotification
125 /* Upon Closing the picture window, we make sure we clean up any
126 * preview movie that might be playing
128 hb_stop( fPreviewLibhb );
130 // Show the picture view
131 [fPictureView setHidden:NO];
132 [fMovieView pause:nil];
133 [fMovieView setHidden:YES];
134 [fMovieView setMovie:nil];
137 [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"PreviewWindowIsOpen"];
140 - (BOOL)windowShouldClose:(id)fPictureWindow
147 hb_stop(fPreviewLibhb);
148 if (fPreviewMoviePath)
150 [[NSFileManager defaultManager] removeFileAtPath:fPreviewMoviePath handler:nil];
151 [fPreviewMoviePath release];
154 [fLibhbTimer invalidate];
155 [fLibhbTimer release];
157 [fHudTimer invalidate];
160 [fPicturePreviews release];
161 [fFullScreenWindow release];
166 - (void) SetHandle: (hb_handle_t *) handle
172 /* we set the preview length popup in seconds */
173 [fPreviewMovieLengthPopUp removeAllItems];
174 [fPreviewMovieLengthPopUp addItemWithTitle: @"5"];
175 [fPreviewMovieLengthPopUp addItemWithTitle: @"10"];
176 [fPreviewMovieLengthPopUp addItemWithTitle: @"15"];
177 [fPreviewMovieLengthPopUp addItemWithTitle: @"20"];
178 [fPreviewMovieLengthPopUp addItemWithTitle: @"25"];
179 [fPreviewMovieLengthPopUp addItemWithTitle: @"30"];
180 [fPreviewMovieLengthPopUp addItemWithTitle: @"35"];
181 [fPreviewMovieLengthPopUp addItemWithTitle: @"40"];
182 [fPreviewMovieLengthPopUp addItemWithTitle: @"45"];
183 [fPreviewMovieLengthPopUp addItemWithTitle: @"50"];
184 [fPreviewMovieLengthPopUp addItemWithTitle: @"55"];
185 [fPreviewMovieLengthPopUp addItemWithTitle: @"60"];
187 /* adjust the preview slider length */
188 /* We use our advance pref to determine how many previews we scanned */
189 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
190 [fPictureSlider setMaxValue: hb_num_previews - 1.0];
191 [fPictureSlider setNumberOfTickMarks: hb_num_previews];
193 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewLength"])
195 [fPreviewMovieLengthPopUp selectItemWithTitle:[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewLength"]];
199 /* currently hard set default to 10 seconds */
200 [fPreviewMovieLengthPopUp selectItemAtIndex: 1];
204 - (void) SetTitle: (hb_title_t *) title
206 hb_job_t * job = title->job;
210 MaxOutputWidth = title->width - job->crop[2] - job->crop[3];
211 MaxOutputHeight = title->height - job->crop[0] - job->crop[1];
212 [self SettingsChanged: nil];
214 /* set the top of the hud controller boxes centered vertically with the origin of our window */
215 NSPoint hudControlBoxOrigin = [fPictureControlBox frame].origin;
216 hudControlBoxOrigin.y = ([[self window] frame].size.height / 2) - [fPictureControlBox frame].size.height;
217 [fPictureControlBox setFrameOrigin:hudControlBoxOrigin];
218 [fEncodingControlBox setFrameOrigin:hudControlBoxOrigin];
224 // Adjusts the window to draw the current picture (fPicture) adjusting its size as
225 // necessary to display as much of the picture as possible.
226 - (void) displayPreview
228 hb_job_t * job = fTitle->job;
229 /* lets make sure that the still picture view is not hidden and that
230 * the movie preview is
232 [fMovieView pause:nil];
233 [fMovieView setHidden:YES];
234 [fMovieView setMovie:nil];
235 [fMovieCreationProgressIndicator stopAnimation: nil];
236 [fMovieCreationProgressIndicator setHidden: YES];
238 [fPictureView setHidden:NO];
240 NSImage *fPreviewImage = [self imageForPicture: fPicture];
241 NSSize imageScaledSize = [fPreviewImage size];
242 [fPictureView setImage: fPreviewImage];
244 NSSize displaySize = NSMakeSize( ( CGFloat )fTitle->width, ( CGFloat )fTitle->height );
245 NSString *sizeInfoString;
246 /* Set the picture size display fields below the Preview Picture*/
247 if( fTitle->job->anamorphic.mode == 1 ) // Original PAR Implementation
249 output_width = fTitle->width-fTitle->job->crop[2]-fTitle->job->crop[3];
250 output_height = fTitle->height-fTitle->job->crop[0]-fTitle->job->crop[1];
251 display_width = output_width * fTitle->job->anamorphic.par_width / fTitle->job->anamorphic.par_height;
252 sizeInfoString = [NSString stringWithFormat:
253 @"Source: %dx%d, Output: %dx%d, Anamorphic: %dx%d Strict",
254 fTitle->width, fTitle->height, output_width, output_height, display_width, output_height];
256 displaySize.width = display_width;
257 displaySize.height = fTitle->height;
258 imageScaledSize.width = display_width;
259 imageScaledSize.height = output_height;
261 else if (fTitle->job->anamorphic.mode == 2) // Loose Anamorphic
263 hb_set_anamorphic_size(job, &output_width, &output_height, &output_par_width, &output_par_height);
264 display_width = output_width * output_par_width / output_par_height;
265 sizeInfoString = [NSString stringWithFormat:
266 @"Source: %dx%d, Output: %dx%d, Anamorphic: %dx%d Loose",
267 fTitle->width, fTitle->height, output_width, output_height, display_width, output_height];
269 displaySize.width = display_width;
270 displaySize.height = fTitle->height;
271 imageScaledSize.width = display_width;
272 imageScaledSize.height = output_height;
274 else if (fTitle->job->anamorphic.mode == 3) // Custom Anamorphic
276 hb_set_anamorphic_size(job, &output_width, &output_height, &output_par_width, &output_par_height);
277 display_width = output_width * output_par_width / output_par_height;
278 sizeInfoString = [NSString stringWithFormat:
279 @"Source: %dx%d, Output: %dx%d, Anamorphic: %dx%d Custom",
280 fTitle->width, fTitle->height, output_width, output_height, fTitle->job->anamorphic.dar_width, fTitle->job->anamorphic.dar_height];
282 displaySize.width = fTitle->job->anamorphic.dar_width + fTitle->job->crop[2] + fTitle->job->crop[3];
283 displaySize.height = fTitle->job->anamorphic.dar_height + fTitle->job->crop[0] + fTitle->job->crop[1];
284 imageScaledSize.width = (int)fTitle->job->anamorphic.dar_width;
285 imageScaledSize.height = (int)fTitle->job->height;
287 else // No Anamorphic
289 sizeInfoString = [NSString stringWithFormat:
290 @"Source: %dx%d, Output: %dx%d", fTitle->width, fTitle->height,
291 fTitle->job->width, fTitle->job->height];
293 displaySize.width = fTitle->width;
294 displaySize.height = fTitle->height;
295 imageScaledSize.width = fTitle->job->width;
296 imageScaledSize.height = fTitle->job->height;
299 displaySize.width = fTitle->width;
300 displaySize.height = fTitle->height;
301 imageScaledSize.width = fTitle->job->width + fTitle->job->crop[2] + fTitle->job->crop[3];
302 imageScaledSize.height = fTitle->job->height + fTitle->job->crop[0] - fTitle->job->crop[1];
305 NSSize viewSize = [self optimalViewSizeForImageSize:displaySize];
307 /* we also need to take into account scaling to full screen to activate switching the view size */
308 if( [self viewNeedsToResizeToSize:viewSize])
310 if (fTitle->job->anamorphic.mode != 2 || (fTitle->job->anamorphic.mode == 2 && fTitle->width == fTitle->job->width))
312 [self resizeSheetForViewSize:viewSize];
313 [self setViewSize:viewSize];
318 viewSize.width = viewSize.width - (viewSize.width - imageScaledSize.width);
319 viewSize.height = viewSize.height - (viewSize.height - imageScaledSize.height);
320 [self setViewSize:viewSize];
322 /* special case for scaleToScreen */
323 if (scaleToScreen == YES)
325 [fPreviewImage setSize: viewSize];
326 [fPictureView setImage: fPreviewImage];
329 NSString *scaleString;
330 CGFloat scale = ( ( CGFloat )[fPictureView frame].size.width) / ( ( CGFloat )imageScaledSize.width);
331 if (scale * 100.0 != 100)
333 //CGFloat scale = ( ( CGFloat )[fPictureView frame].size.width) / ( ( CGFloat )imageScaledSize.width);
334 scaleString = [NSString stringWithFormat:
335 NSLocalizedString( @" (%.0f%% actual size)",
336 @"String shown when a preview is scaled" ), scale * 100.0];
340 scaleString = @"(Actual size)";
342 /* Set the info fields in the hud controller */
343 [fInfoField setStringValue: [NSString stringWithFormat:
344 @"%@", sizeInfoString]];
346 [fscaleInfoField setStringValue: [NSString stringWithFormat:
347 @"%@", scaleString]];
348 /* Set the info field in the window title bar */
349 [[self window] setTitle:[NSString stringWithFormat: @"Preview - %@ %@",sizeInfoString, scaleString]];
352 - (IBAction) previewDurationPopUpChanged: (id) sender
355 [[NSUserDefaults standardUserDefaults] setObject:[fPreviewMovieLengthPopUp titleOfSelectedItem] forKey:@"PreviewLength"];
359 - (IBAction) SettingsChanged: (id) sender
361 // Purge the existing picture previews so they get recreated the next time
363 [self purgeImageCache];
364 [self pictureSliderChanged:nil];
367 - (IBAction) pictureSliderChanged: (id) sender
369 // Show the picture view
370 [fPictureView setHidden:NO];
371 [fMovieView pause:nil];
372 [fMovieView setHidden:YES];
373 [fMovieView setMovie:nil];
374 [fEncodingControlBox setHidden: YES];
376 int newPicture = [fPictureSlider intValue];
377 if (newPicture != fPicture)
379 fPicture = newPicture;
381 [self displayPreview];
385 - (IBAction)showPreviewPanel: (id)sender forTitle: (hb_title_t *)title
387 if ([fPreviewWindow isVisible])
389 [fPreviewWindow close];
393 [self showWindow:sender];
394 [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"PreviewWindowIsOpen"];
395 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
397 [self pictureSliderChanged:nil];
402 - (NSString*) pictureSizeInfoString
404 return [fInfoField stringValue];
407 - (IBAction)showPictureSettings:(id)sender
409 [fHBController showPicturePanel:self];
412 #pragma mark Hud Control Overlay
413 - (void) mouseMoved:(NSEvent *)theEvent
415 [super mouseMoved:theEvent];
416 NSPoint mouseLoc = [theEvent locationInWindow];
418 /* Test for mouse location to show/hide hud controls */
419 if( isEncoding == NO ) {
420 if( NSPointInRect( mouseLoc, [fPictureControlBox frame] ) )
422 [[fPictureControlBox animator] setHidden: NO];
425 else if( NSPointInRect( mouseLoc, [fPictureViewArea frame] ) )
427 [[fPictureControlBox animator] setHidden: NO];
428 [self startHudTimer];
431 [[fPictureControlBox animator] setHidden: YES];
435 - (void) startHudTimer
438 [fHudTimer invalidate];
441 fHudTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hudTimerFired:) userInfo:nil repeats:YES];
445 - (void) stopHudTimer
449 [fHudTimer invalidate];
456 - (void) hudTimerFired: (NSTimer*)theTimer
459 if( hudTimerSeconds >= 10 ) {
460 [[fPictureControlBox animator] setHidden: YES];
467 - (IBAction)toggleScaleToScreen:(id)sender
469 if (scaleToScreen == YES)
472 /* make sure we are set to a still preview */
473 [self pictureSliderChanged:nil];
474 [fScaleToScreenToggleButton setTitle:@"Scale To Screen"];
479 /* make sure we are set to a still preview */
480 [self pictureSliderChanged:nil];
481 [fScaleToScreenToggleButton setTitle:@"Actual Scale"];
488 // Title-less windows normally don't receive key presses, override this
489 - (BOOL)canBecomeKeyWindow
494 // Title-less windows normally can't become main which means that another
495 // non-fullscreen window will have the "active" titlebar in expose. Bad, fix it.
496 - (BOOL)canBecomeMainWindow
502 - (IBAction)goWindowedScreen:(id)sender
505 /* Get the screen info to release the display but don't actually do
506 * it until the windowed screen is setup.
509 [self pictureSliderChanged:nil];
510 [fScaleToScreenToggleButton setTitle:@"<->"];
512 NSScreen* mainScreen = [NSScreen mainScreen];
513 NSDictionary* screenInfo = [mainScreen deviceDescription];
514 NSNumber* screenID = [screenInfo objectForKey:@"NSScreenNumber"];
515 CGDirectDisplayID displayID = (CGDirectDisplayID)[screenID longValue];
517 [fFullScreenWindow dealloc];
518 [fFullScreenWindow release];
521 [fPreviewWindow setContentView:fPictureViewArea];
522 [fPictureViewArea setNeedsDisplay:YES];
523 [self setWindow:fPreviewWindow];
526 [fPreviewWindow makeKeyAndOrderFront:self];
528 /* Set the window back to regular level */
529 [fPreviewWindow setLevel:NSNormalWindowLevel];
531 /* Set the isFullScreen flag back to NO */
534 /* make sure we are set to a still preview */
535 [self pictureSliderChanged:nil];
536 [self showPreviewWindow:nil];
538 /* Change the name of fFullScreenToggleButton appropriately */
539 //[fFullScreenToggleButton setTitle: @"Full Screen"];
540 // [fScaleToScreenToggleButton setHidden:YES];
541 /* set the picture settings pallete back to normal level */
542 [fHBController picturePanelWindowed];
544 /* Release the display now that the we are back in windowed mode */
545 CGDisplayRelease(displayID);
547 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
548 //[fFullScreenWindow setAcceptsMouseMovedEvents:NO];
551 [self startHudTimer];
556 #pragma mark Still Preview Image Processing
559 // This function converts an image created by libhb (specified via pictureIndex) into
560 // an NSImage suitable for the GUI code to use. If removeBorders is YES,
561 // makeImageForPicture crops the image generated by libhb stripping off the gray
562 // border around the content. This is the low-level method that generates the image.
563 // -imageForPicture calls this function whenever it can't find an image in its cache.
564 + (NSImage *) makeImageForPicture: (int)pictureIndex
565 libhb:(hb_handle_t*)handle
566 title:(hb_title_t*)title
568 static uint8_t * buffer;
569 static int bufferSize;
571 // Make sure we have a big enough buffer to receive the image from libhb. libhb
572 int dstWidth = title->job->width;
573 int dstHeight = title->job->height;
576 newSize = dstWidth * dstHeight * 4;
577 if( bufferSize < newSize )
579 bufferSize = newSize;
580 buffer = (uint8_t *) realloc( buffer, bufferSize );
583 hb_get_preview( handle, title, pictureIndex, buffer );
585 // Create an NSBitmapImageRep and copy the libhb image into it, converting it from
586 // libhb's format to one suitable for NSImage. Along the way, we'll strip off the
587 // border around libhb's image.
589 // The image data returned by hb_get_preview is 4 bytes per pixel, BGRA format.
592 NSBitmapFormat bitmapFormat = (NSBitmapFormat)NSAlphaFirstBitmapFormat;
593 NSBitmapImageRep * imgrep = [[[NSBitmapImageRep alloc]
594 initWithBitmapDataPlanes:nil
598 samplesPerPixel:3 // ignore alpha
601 colorSpaceName:NSCalibratedRGBColorSpace
602 bitmapFormat:bitmapFormat
603 bytesPerRow:dstWidth * 4
604 bitsPerPixel:32] autorelease];
606 UInt32 * src = (UInt32 *)buffer;
607 UInt32 * dst = (UInt32 *)[imgrep bitmapData];
609 for (r = 0; r < dstHeight; r++)
611 for (c = 0; c < dstWidth; c++)
612 #if TARGET_RT_LITTLE_ENDIAN
613 *dst++ = Endian32_Swap(*src++);
619 NSImage * img = [[[NSImage alloc] initWithSize: NSMakeSize(dstWidth, dstHeight)] autorelease];
620 [img addRepresentation:imgrep];
625 // Returns the preview image for the specified index, retrieving it from its internal
626 // cache or by calling makeImageForPicture if it is not cached. Generally, you should
627 // use imageForPicture so that images are cached. Calling makeImageForPicture will
628 // always generate a new copy of the image.
629 - (NSImage *) imageForPicture: (int) pictureIndex
631 // The preview for the specified index may not currently exist, so this method
632 // generates it if necessary.
633 NSString * key = [NSString stringWithFormat:@"%d", pictureIndex];
634 NSImage * theImage = [fPicturePreviews objectForKey:key];
637 theImage = [PreviewController makeImageForPicture:pictureIndex libhb:fHandle title:fTitle];
638 [fPicturePreviews setObject:theImage forKey:key];
643 // Purges all images from the cache. The next call to imageForPicture will cause a new
644 // image to be generated.
645 - (void) purgeImageCache
647 [fPicturePreviews removeAllObjects];
652 #pragma mark Movie Preview
653 - (IBAction) createMoviePreview: (id) sender
657 /* Lets make sure the still picture previews are showing in case
658 * there is currently a movie showing */
659 [self pictureSliderChanged:nil];
661 /* Rip or Cancel ? */
663 hb_get_state2( fPreviewLibhb, &s );
665 if(sender == fCancelPreviewMovieButton && (s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED))
667 hb_stop( fPreviewLibhb );
668 [fPictureView setHidden:NO];
669 [fMovieView pause:nil];
670 [fMovieView setHidden:YES];
671 [fMovieView setMovie:nil];
672 [fPictureSlider setHidden:NO];
679 /* we use controller.mm's prepareJobForPreview to go ahead and set all of our settings
680 * however, we want to use a temporary destination field of course
681 * so that we do not put our temp preview in the users chosen
684 hb_job_t * job = fTitle->job;
686 /* We run our current setting through prepeareJob in Controller.mm
687 * just as if it were a regular encode */
689 [fHBController prepareJobForPreview];
691 /* Destination file. We set this to our preview directory
692 * changing the extension appropriately.*/
693 if (fTitle->job->mux == HB_MUX_MP4) // MP4 file
695 /* we use .m4v for our mp4 files so that ac3 and chapters in mp4 will play properly */
696 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.m4v";
698 else if (fTitle->job->mux == HB_MUX_MKV) // MKV file
700 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.mkv";
702 else if (fTitle->job->mux == HB_MUX_AVI) // AVI file
704 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.avi";
706 else if (fTitle->job->mux == HB_MUX_OGM) // OGM file
708 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.ogm";
711 fPreviewMoviePath = [[fPreviewMoviePath stringByExpandingTildeInPath]retain];
713 /* See if there is an existing preview file, if so, delete it */
714 if( ![[NSFileManager defaultManager] fileExistsAtPath:fPreviewMoviePath] )
716 [[NSFileManager defaultManager] removeFileAtPath:fPreviewMoviePath
720 /* We now direct our preview encode to fPreviewMoviePath */
721 fTitle->job->file = [fPreviewMoviePath UTF8String];
723 /* We use our advance pref to determine how many previews to scan */
724 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
725 job->start_at_preview = fPicture + 1;
726 job->seek_points = hb_num_previews;
728 /* we use the preview duration popup to get the specified
729 * number of seconds for the preview encode.
732 job->pts_to_stop = [[fPreviewMovieLengthPopUp titleOfSelectedItem] intValue] * 90000LL;
734 /* lets go ahead and send it off to libhb
735 * Note: unlike a full encode, we only send 1 pass regardless if the final encode calls for 2 passes.
736 * this should suffice for a fairly accurate short preview and cuts our preview generation time in half.
737 * However we also need to take into account the indepth scan for subtitles.
740 * If scanning we need to do some extra setup of the job.
742 if( job->indepth_scan == 1 )
747 * When subtitle scan is enabled do a fast pre-scan job
748 * which will determine which subtitles to enable, if any.
751 x264opts_tmp = job->x264opts;
753 job->x264opts = NULL;
754 job->indepth_scan = 1;
756 * Add the pre-scan job
758 hb_add( fPreviewLibhb, job );
759 job->x264opts = x264opts_tmp;
761 /* Go ahead and perform the actual encoding preview scan */
762 job->indepth_scan = 0;
764 hb_add( fPreviewLibhb, job );
766 [fEncodingControlBox setHidden: NO];
767 [fPictureControlBox setHidden: YES];
769 [fMovieCreationProgressIndicator setHidden: NO];
770 [fPreviewMovieStatusField setHidden: NO];
774 /* Let fPreviewLibhb do the job */
775 hb_start( fPreviewLibhb );
779 - (void) startReceivingLibhbNotifications
783 fLibhbTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(libhbTimerFired:) userInfo:nil repeats:YES];
784 [fLibhbTimer retain];
788 - (void) stopReceivingLibhbNotifications
792 [fLibhbTimer invalidate];
793 [fLibhbTimer release];
797 - (void) libhbTimerFired: (NSTimer*)theTimer
800 hb_get_state( fPreviewLibhb, &s );
801 [self libhbStateChanged: s];
805 - (void) libhbStateChanged: (hb_state_t)state
807 switch( state.state )
810 case HB_STATE_SCANNING:
811 case HB_STATE_SCANDONE:
814 case HB_STATE_WORKING:
816 #define p state.param.working
818 NSMutableString * string;
819 /* Update text field */
820 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding preview: %.2f %%", @"" ), 100.0 * p.progress];
824 [string appendFormat:
825 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
826 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
828 [fPreviewMovieStatusField setStringValue: string];
830 [fMovieCreationProgressIndicator setIndeterminate: NO];
832 [fMovieCreationProgressIndicator setDoubleValue: 100.0 * p.progress];
834 [fCreatePreviewMovieButton setTitle: @"Cancel Preview"];
841 #define p state.param.muxing
842 case HB_STATE_MUXING:
844 // Update fMovieCreationProgressIndicator
845 [fMovieCreationProgressIndicator setIndeterminate: YES];
846 [fMovieCreationProgressIndicator startAnimation: nil];
847 [fPreviewMovieStatusField setStringValue: [NSString stringWithFormat:
848 NSLocalizedString( @"Muxing Preview ...", @"" )]];
852 case HB_STATE_PAUSED:
853 [fMovieCreationProgressIndicator stopAnimation: nil];
856 case HB_STATE_WORKDONE:
858 // Delete all remaining jobs since libhb doesn't do this on its own.
860 while( ( job = hb_job(fPreviewLibhb, 0) ) )
861 hb_rem( fHandle, job );
863 [fPreviewMovieStatusField setStringValue: @""];
864 [fPreviewMovieStatusField setHidden: YES];
866 [fMovieCreationProgressIndicator stopAnimation: nil];
867 [fMovieCreationProgressIndicator setHidden: YES];
868 [fEncodingControlBox setHidden: YES];
870 /* we make sure the picture slider and preview match */
871 [self pictureSliderChanged:nil];
873 // Show the movie view
874 [self showMoviePreview:fPreviewMoviePath];
875 [fCreatePreviewMovieButton setTitle: @"Live Preview"];
882 - (IBAction) showMoviePreview: (NSString *) path
884 /* Since the gray background for the still images is part of
885 * fPictureView, lets leave the picture view visible and postion
886 * the fMovieView over the image portion of fPictureView so
887 * we retain the gray cropping border we have already established
888 * with the still previews
891 /* Load the new movie into fMovieView */
896 NSURL *movieUrl = [NSURL fileURLWithPath:path];
897 NSDictionary *movieAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
898 movieUrl, QTMovieURLAttribute,
899 [NSNumber numberWithBool:NO], QTMovieAskUnresolvedDataRefsAttribute,
900 [NSNumber numberWithBool:YES], @"QTMovieOpenForPlaybackAttribute",
901 [NSNumber numberWithBool:NO], @"QTMovieOpenAsyncRequiredAttribute",
902 [NSNumber numberWithBool:NO], @"QTMovieOpenAsyncOKAttribute",
903 QTMovieApertureModeClean, QTMovieApertureModeAttribute,
906 aMovie = [[[QTMovie alloc] initWithAttributes:movieAttributes error:&outError] autorelease];
910 NSLog(@"Unable to open movie");
915 /* we get some size information from the preview movie */
916 NSSize movieSize= [[aMovie attributeForKey:QTMovieNaturalSizeAttribute] sizeValue];
917 movieBounds = [fMovieView movieBounds];
918 movieBounds.size.height = movieSize.height;
920 if ([fMovieView isControllerVisible])
922 CGFloat controllerBarHeight = [fMovieView controllerBarHeight];
923 if ( controllerBarHeight != 0 ) //Check if QTKit return a real value or not.
924 movieBounds.size.height += controllerBarHeight;
926 movieBounds.size.height += 15;
929 movieBounds.size.width = movieSize.width;
931 /* We need to find out if the preview movie needs to be scaled down so
932 * that it doesn't overflow our available viewing container (just like for image
933 * in -displayPreview) for HD sources, etc. [fPictureViewArea frame].size.height*/
934 if( (movieBounds.size.height) > [fPictureViewArea frame].size.height || scaleToScreen == YES )
936 /* The preview movie would be larger than the available viewing area
937 * in the preview movie, so we go ahead and scale it down to the same size
938 * as the still preview or we readjust our window to allow for the added height if need be
940 NSSize displaySize = NSMakeSize( ( CGFloat ) movieBounds.size.width, ( CGFloat ) movieBounds.size.height );
941 NSSize viewSize = [self optimalViewSizeForImageSize:displaySize];
942 if( [self viewNeedsToResizeToSize:viewSize] )
944 [self resizeSheetForViewSize:viewSize];
945 [self setViewSize:viewSize];
947 [fMovieView setFrameSize:viewSize];
951 /* Since the preview movie is smaller than the available viewing area
952 * we can go ahead and use the preview movies native size */
953 [fMovieView setFrameSize:movieBounds.size];
956 //lets reposition the movie if need be
958 NSPoint origin = [fPictureViewArea frame].origin;
959 origin.x += trunc( ( [fPictureViewArea frame].size.width -
960 [fMovieView frame].size.width ) / 2.0 );
961 /* We need to detect whether or not we are currently less than the available height.*/
962 if( movieBounds.size.height < [fPictureView frame].size.height )
964 /* If we are, we are adding 15 to the height to allow for the controller bar so
965 * we need to subtract half of that for the origin.y to get the controller bar
966 * below the movie to it lines up vertically with where our still preview was
968 origin.y += trunc( ( ( [fPictureViewArea frame].size.height -
969 [fMovieView frame].size.height ) / 2.0 ) - 7.5 );
973 /* if we are >= to the height of the picture view area, the controller bar
974 * gets taken care of with picture resizing, so we do not want to offset the height
976 origin.y += trunc( ( [fPictureViewArea frame].size.height -
977 [fMovieView frame].size.height ) / 2.0 );
979 [fMovieView setFrameOrigin:origin];
980 [fMovieView setMovie:aMovie];
981 [fMovieView setHidden:NO];
982 // to actually play the movie
983 [fMovieView play:aMovie];
991 @implementation PreviewController (Private)
994 // -[PictureController(Private) optimalViewSizeForImageSize:]
996 // Given the size of the preview image to be shown, returns the best possible
997 // size for the view.
999 - (NSSize)optimalViewSizeForImageSize: (NSSize)imageSize
1001 // The min size is 320x240
1002 CGFloat minWidth = 480.0;
1003 CGFloat minHeight = 360.0;
1005 NSSize screenSize = [[NSScreen mainScreen] visibleFrame].size;
1006 NSSize sheetSize = [[self window] frame].size;
1007 NSSize viewAreaSize = [fPictureViewArea frame].size;
1008 CGFloat paddingX = sheetSize.width - viewAreaSize.width;
1009 CGFloat paddingY = sheetSize.height - viewAreaSize.height;
1013 maxWidth = screenSize.width - paddingX;
1014 maxHeight = screenSize.height - paddingY;
1016 NSSize resultSize = imageSize;
1017 CGFloat resultPar = resultSize.width / resultSize.height;
1019 //note, a mbp 15" at 1440 x 900 is a 1.6 ar
1020 CGFloat screenAspect = screenSize.width / screenSize.height;
1021 // Note, a standard dvd will use 720 x 480 which is a 1.5
1022 CGFloat viewAreaAspect = viewAreaSize.width / viewAreaSize.height;
1024 if (scaleToScreen == YES)
1027 if (screenAspect < viewAreaAspect)
1029 resultSize.width = screenSize.width;
1030 resultSize.height = (screenSize.width / viewAreaAspect);
1034 resultSize.height = screenSize.height;
1035 resultSize.width = resultSize.height * viewAreaAspect;
1039 else if ( resultSize.width > maxWidth || resultSize.height > maxHeight )
1041 // Source is larger than screen in one or more dimensions
1042 if ( resultPar > screenAspect )
1044 // Source aspect wider than screen aspect, snap to max width and vary height
1045 resultSize.width = maxWidth;
1046 resultSize.height = (maxWidth / resultPar);
1050 // Source aspect narrower than screen aspect, snap to max height vary width
1051 resultSize.height = maxHeight;
1052 resultSize.width = (maxHeight * resultPar);
1056 // If necessary, grow to minimum dimensions to ensure controls overlay is not obstructed
1057 if ( resultSize.width < minWidth )
1059 resultSize.width = minWidth;
1061 if ( resultSize.height < minHeight )
1063 resultSize.height = minHeight;
1072 // -[PictureController(Private) resizePanelForViewSize:animate:]
1074 // Resizes the entire window to accomodate a view of a particular size.
1076 - (void)resizeSheetForViewSize: (NSSize)viewSize
1078 // Figure out the deltas for the new frame area
1079 NSSize currentSize = [fPictureViewArea frame].size;
1080 CGFloat deltaX = viewSize.width - currentSize.width;
1081 CGFloat deltaY = viewSize.height - currentSize.height;
1083 // Now resize the whole panel by those same deltas, but don't exceed the min
1084 NSRect frame = [[self window] frame];
1085 NSSize maxSize = [[[self window] screen] visibleFrame].size;
1086 NSSize minSize = [[self window] minSize];
1088 frame.size.width += deltaX;
1089 frame.size.height += deltaY;
1090 if( frame.size.width < minSize.width )
1092 frame.size.width = minSize.width;
1095 if( frame.size.height < minSize.height )
1097 frame.size.height = minSize.height;
1099 /* compare frame to max size of screen */
1100 if( frame.size.width > maxSize.width )
1102 frame.size.width = maxSize.width;
1105 if( frame.size.height > maxSize.height )
1107 frame.size.height = maxSize.height;
1113 // But now the sheet is off-center, so also shift the origin to center it and
1114 // keep the top aligned.
1115 if( frame.size.width != [[self window] frame].size.width )
1116 frame.origin.x -= (deltaX / 2.0);
1119 /* Since upon launch we can open up the preview window if it was open
1120 * the last time we quit (and at the size it was) we want to make
1121 * sure that upon resize we do not have the window off the screen
1122 * So check the origin against the screen origin and adjust if
1125 NSSize screenSize = [[[self window] screen] visibleFrame].size;
1126 NSPoint screenOrigin = [[[self window] screen] frame].origin;
1127 if (screenSize.height < frame.size.height)
1129 frame.size.height = screenSize.height;
1131 if (screenSize.width < frame.size.width)
1133 frame.size.width = screenSize.width;
1137 /* our origin is off the screen to the left*/
1138 if (frame.origin.x < screenOrigin.x)
1140 /* so shift our origin to the right */
1141 frame.origin.x = screenOrigin.x;
1143 else if ((frame.origin.x + frame.size.width) > (screenOrigin.x + screenSize.width))
1145 /* the right side of the preview is off the screen, so shift to the left */
1146 frame.origin.x = (screenOrigin.x + screenSize.width) - frame.size.width;
1149 [[self window] setFrame:frame display:YES animate:YES];
1155 // -[PictureController(Private) setViewSize:]
1157 // Changes the view's size and centers it vertically inside of its area.
1158 // Assumes resizeSheetForViewSize: has already been called.
1160 - (void)setViewSize: (NSSize)viewSize
1162 /* special case for scaleToScreen */
1163 NSSize screenSize = [[[self window] screen] visibleFrame].size;
1164 NSSize areaSize = [fPictureViewArea frame].size;
1165 if (scaleToScreen == YES || viewSize.width > areaSize.width || viewSize.height > areaSize.height)
1167 /* for scaleToScreen, we expand the fPictureView to fit the entire screen */
1168 CGFloat viewSizeAspect = viewSize.width / viewSize.height;
1169 if (viewSizeAspect > 1.0) // we are wider than taller, so expand the width to fill the area and scale the height
1171 viewSize.width = areaSize.width;
1172 viewSize.height = viewSize.width / viewSizeAspect;
1176 viewSize.height = areaSize.height;
1177 viewSize.width = viewSize.height * viewSizeAspect;
1183 [fPictureView setFrameSize:viewSize];
1185 // center it vertically and horizontally
1186 NSPoint origin = [fPictureViewArea frame].origin;
1187 origin.y += ([fPictureViewArea frame].size.height -
1188 [fPictureView frame].size.height) / 2.0;
1190 origin.x += ([fPictureViewArea frame].size.width -
1191 [fPictureView frame].size.width) / 2.0;
1193 origin.x = floor( origin.x );
1194 origin.y = floor( origin.y );
1196 [fPictureView setFrameOrigin:origin];
1201 - (BOOL)viewNeedsToResizeToSize: (NSSize)newSize
1203 NSSize viewSize = [fPictureViewArea frame].size;
1204 return (newSize.width != viewSize.width || newSize.height != viewSize.height);