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];
19 @interface PreviewController (Private)
21 - (NSSize)optimalViewSizeForImageSize: (NSSize)imageSize;
22 - (void)resizeSheetForViewSize: (NSSize)viewSize;
23 - (void)setViewSize: (NSSize)viewSize;
24 - (BOOL)viewNeedsToResizeToSize: (NSSize)newSize;
28 @implementation PreviewController
32 if (self = [super initWithWindowNibName:@"PicturePreview"])
34 // NSWindowController likes to lazily load its window. However since
35 // this controller tries to set all sorts of outlets before the window
36 // is displayed, we need it to load immediately. The correct way to do
37 // this, according to the documentation, is simply to invoke the window
40 // If/when we switch a lot of this stuff to bindings, this can probably
44 fPicturePreviews = [[NSMutableDictionary dictionaryWithCapacity: HB_NUM_HBLIB_PICTURES] retain];
45 /* Init libhb with check for updates libhb style set to "0" so its ignored and lets sparkle take care of it */
46 int loggingLevel = [[[NSUserDefaults standardUserDefaults] objectForKey:@"LoggingLevel"] intValue];
47 fPreviewLibhb = hb_init(loggingLevel, 0);
56 //------------------------------------------------------------------------------------
57 // Displays and brings the picture window to the front
58 //------------------------------------------------------------------------------------
59 - (IBAction) showPreviewWindow: (id)sender
61 [self showWindow:sender];
62 [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"PreviewWindowIsOpen"];
64 /* lets set the preview window to accept mouse moved events */
65 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
67 [self pictureSliderChanged:nil];
68 [self startReceivingLibhbNotifications];
71 - (void)setHBController: (HBController *)controller
73 fHBController = controller;
78 [fPreviewWindow setDelegate:self];
79 if( ![[self window] setFrameUsingName:@"Preview"] )
80 [[self window] center];
81 [self setWindowFrameAutosaveName:@"Preview"];
82 [[self window] setExcludedFromWindowsMenu:YES];
84 /* lets set the preview window to accept mouse moved events */
85 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
86 //[self pictureSliderChanged:nil];
87 [self startReceivingLibhbNotifications];
90 /* we set the progress indicator to not use threaded animation
91 * as it causes a conflict with the qtmovieview's controllerbar
93 [fMovieCreationProgressIndicator setUsesThreadedAnimation:NO];
95 /* Setup our layers for core animation */
96 [fPictureViewArea setWantsLayer:YES];
97 [fPictureView setWantsLayer:YES];
99 [fCancelPreviewMovieButton setWantsLayer:YES];
100 [fMovieCreationProgressIndicator setWantsLayer:YES];
102 [fPictureControlBox setWantsLayer:YES];
103 [fEncodingControlBox setWantsLayer:YES];
104 [fMovieView setWantsLayer:YES];
105 [fMovieView setHidden:YES];
106 [fMovieView setDelegate:self];
108 /* Since the xib has everything off center for easy acess
109 * we align our views and windows here we an align to anything
110 * since it will actually change later upon source load, but
111 * for convenience we will use the fPictureViewArea
114 /* Align the still preview image view to the picture box */
115 [fPictureView setFrameSize:[fPictureViewArea frame].size];
116 [fMovieView setFrameSize:[fPictureViewArea frame].size];
117 //[fPreviewWindow setFrameSize:[fPictureViewArea frame].size];
121 - (BOOL)acceptsMouseMovedEvents
126 - (void)windowWillClose:(NSNotification *)aNotification
128 /* Upon Closing the picture window, we make sure we clean up any
129 * preview movie that might be playing
131 hb_stop( fPreviewLibhb );
133 // Show the picture view
134 [fPictureView setHidden:NO];
135 [fMovieView pause:nil];
136 [fMovieTimer invalidate];
137 [fMovieTimer release];
138 [fMovieView setHidden:YES];
139 [fMovieView setMovie:nil];
142 [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"PreviewWindowIsOpen"];
145 - (BOOL)windowShouldClose:(id)fPictureWindow
152 hb_stop(fPreviewLibhb);
153 if (fPreviewMoviePath)
155 [[NSFileManager defaultManager] removeFileAtPath:fPreviewMoviePath handler:nil];
156 [fPreviewMoviePath release];
159 [fLibhbTimer invalidate];
160 [fLibhbTimer release];
162 [fHudTimer invalidate];
165 [fMovieTimer invalidate];
166 [fMovieTimer release];
168 [fPicturePreviews release];
169 [fFullScreenWindow release];
171 hb_close(&fPreviewLibhb);
173 [self removeMovieCallbacks];
178 - (void) SetHandle: (hb_handle_t *) handle
184 /* we set the preview length popup in seconds */
185 [fPreviewMovieLengthPopUp removeAllItems];
186 [fPreviewMovieLengthPopUp addItemWithTitle: @"5"];
187 [fPreviewMovieLengthPopUp addItemWithTitle: @"10"];
188 [fPreviewMovieLengthPopUp addItemWithTitle: @"15"];
189 [fPreviewMovieLengthPopUp addItemWithTitle: @"20"];
190 [fPreviewMovieLengthPopUp addItemWithTitle: @"25"];
191 [fPreviewMovieLengthPopUp addItemWithTitle: @"30"];
192 [fPreviewMovieLengthPopUp addItemWithTitle: @"35"];
193 [fPreviewMovieLengthPopUp addItemWithTitle: @"40"];
194 [fPreviewMovieLengthPopUp addItemWithTitle: @"45"];
195 [fPreviewMovieLengthPopUp addItemWithTitle: @"50"];
196 [fPreviewMovieLengthPopUp addItemWithTitle: @"55"];
197 [fPreviewMovieLengthPopUp addItemWithTitle: @"60"];
199 /* adjust the preview slider length */
200 /* We use our advance pref to determine how many previews we scanned */
201 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
202 [fPictureSlider setMaxValue: hb_num_previews - 1.0];
203 [fPictureSlider setNumberOfTickMarks: hb_num_previews];
205 if ([[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewLength"])
207 [fPreviewMovieLengthPopUp selectItemWithTitle:[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewLength"]];
211 /* currently hard set default to 10 seconds */
212 [fPreviewMovieLengthPopUp selectItemAtIndex: 1];
216 - (void) SetTitle: (hb_title_t *) title
218 hb_job_t * job = title->job;
222 MaxOutputWidth = title->width - job->crop[2] - job->crop[3];
223 MaxOutputHeight = title->height - job->crop[0] - job->crop[1];
225 [self SettingsChanged: nil];
231 // Adjusts the window to draw the current picture (fPicture) adjusting its size as
232 // necessary to display as much of the picture as possible.
233 - (void) displayPreview
235 hb_job_t * job = fTitle->job;
236 /* lets make sure that the still picture view is not hidden and that
237 * the movie preview is
240 [fMovieView pause:nil];
241 [fMovieView setHidden:YES];
242 [fMovieView setMovie:nil];
243 [fMovieCreationProgressIndicator stopAnimation: nil];
244 [fMovieCreationProgressIndicator setHidden: YES];
245 [fMoviePlaybackControlBox setHidden: YES];
246 [self stopMovieTimer];
247 [fPictureControlBox setHidden: NO];
249 [fPictureView setHidden:NO];
251 NSImage *fPreviewImage = [self imageForPicture: fPicture];
252 NSSize imageScaledSize = [fPreviewImage size];
253 [fPictureView setImage: fPreviewImage];
255 NSSize displaySize = NSMakeSize( ( CGFloat )fTitle->width, ( CGFloat )fTitle->height );
256 NSString *sizeInfoString;
257 /* Set the picture size display fields below the Preview Picture*/
258 if( fTitle->job->anamorphic.mode == 1 ) // Original PAR Implementation
260 output_width = fTitle->width-fTitle->job->crop[2]-fTitle->job->crop[3];
261 output_height = fTitle->height-fTitle->job->crop[0]-fTitle->job->crop[1];
262 display_width = output_width * fTitle->job->anamorphic.par_width / fTitle->job->anamorphic.par_height;
263 sizeInfoString = [NSString stringWithFormat:
264 @"Source: %dx%d, Output: %dx%d, Anamorphic: %dx%d Strict",
265 fTitle->width, fTitle->height, output_width, output_height, display_width, output_height];
267 displaySize.width = display_width;
268 displaySize.height = fTitle->height;
269 imageScaledSize.width = display_width;
270 imageScaledSize.height = output_height;
272 else if (fTitle->job->anamorphic.mode == 2) // Loose Anamorphic
274 hb_set_anamorphic_size(job, &output_width, &output_height, &output_par_width, &output_par_height);
275 display_width = output_width * output_par_width / output_par_height;
276 sizeInfoString = [NSString stringWithFormat:
277 @"Source: %dx%d, Output: %dx%d, Anamorphic: %dx%d Loose",
278 fTitle->width, fTitle->height, output_width, output_height, display_width, output_height];
280 displaySize.width = display_width;
281 displaySize.height = fTitle->height;
282 imageScaledSize.width = display_width;
283 imageScaledSize.height = output_height;
285 else if (fTitle->job->anamorphic.mode == 3) // Custom Anamorphic
287 hb_set_anamorphic_size(job, &output_width, &output_height, &output_par_width, &output_par_height);
288 display_width = output_width * output_par_width / output_par_height;
289 sizeInfoString = [NSString stringWithFormat:
290 @"Source: %dx%d, Output: %dx%d, Anamorphic: %dx%d Custom",
291 fTitle->width, fTitle->height, output_width, output_height, fTitle->job->anamorphic.dar_width, fTitle->job->anamorphic.dar_height];
293 displaySize.width = fTitle->job->anamorphic.dar_width + fTitle->job->crop[2] + fTitle->job->crop[3] ;
294 displaySize.height = fTitle->job->anamorphic.dar_height + fTitle->job->crop[0] + fTitle->job->crop[1];
295 imageScaledSize.width = (int)fTitle->job->anamorphic.dar_width;
296 imageScaledSize.height = (int)fTitle->job->height;
298 else // No Anamorphic
300 sizeInfoString = [NSString stringWithFormat:
301 @"Source: %dx%d, Output: %dx%d", fTitle->width, fTitle->height,
302 fTitle->job->width, fTitle->job->height];
304 displaySize.width = fTitle->width;
305 displaySize.height = fTitle->height;
306 imageScaledSize.width = fTitle->job->width;
307 imageScaledSize.height = fTitle->job->height;
312 NSSize viewSize = [self optimalViewSizeForImageSize:displaySize];
313 [self resizeSheetForViewSize:viewSize];
315 NSSize windowSize = [[self window] frame].size;
317 if (scaleToScreen == YES)
319 /* Note: this should probably become a utility function */
320 /* We are in Scale To Screen mode so, we have to get the ratio for height and width against the window
321 *size so we can scale from there.
323 CGFloat deltaWidth = imageScaledSize.width / displaySize.width;
324 CGFloat deltaHeight = imageScaledSize.height /displaySize.height;
325 NSSize windowSize = [[self window] frame].size;
326 CGFloat pictureAspectRatio = imageScaledSize.width / imageScaledSize.height;
328 /* Set our min size to the storage size */
330 minSize.width = fTitle->width;
331 minSize.height = fTitle->height;
333 /* Set delta's based on minimum size */
334 if (imageScaledSize.width < minSize.width)
336 deltaWidth = imageScaledSize.width / minSize.width;
343 if (imageScaledSize.height < minSize.height)
345 deltaHeight = imageScaledSize.height / minSize.height;
352 /* Now apply our deltas to the full screen view */
353 if (pictureAspectRatio > 1.0) // we are wider than taller, so expand the width to fill the area and scale the height
355 viewSize.width = windowSize.width * deltaWidth;
356 viewSize.height = viewSize.width / pictureAspectRatio;
361 viewSize.height = windowSize.height * deltaHeight;
362 viewSize.width = viewSize.height * pictureAspectRatio;
368 viewSize.width = viewSize.width - (viewSize.width - imageScaledSize.width);
369 viewSize.height = viewSize.height - (viewSize.height - imageScaledSize.height);
371 if (fTitle->width > windowSize.width || fTitle->height > windowSize.height)
373 CGFloat viewSizeAspect = viewSize.width / viewSize.height;
374 if (viewSizeAspect > 1.0) // we are wider than taller, so expand the width to fill the area and scale the height
376 viewSize.width = viewSize.width * (windowSize.width / fTitle->width) ;
377 viewSize.height = viewSize.width / viewSizeAspect;
381 viewSize.height = viewSize.height * (windowSize.height / fTitle->height);
382 viewSize.width = viewSize.height * viewSizeAspect;
388 [self setViewSize:viewSize];
390 /* relocate our hud origins as per setViewSize */
391 NSPoint hudControlBoxOrigin = [fPictureControlBox frame].origin;
392 hudControlBoxOrigin.y = ([[self window] frame].size.height / 2) - (viewSize.height / 2);
393 hudControlBoxOrigin.x = ([[self window] frame].size.width / 2) - ([fPictureControlBox frame].size.width / 2);
394 [fPictureControlBox setFrameOrigin:hudControlBoxOrigin];
395 [fEncodingControlBox setFrameOrigin:hudControlBoxOrigin];
396 [fMoviePlaybackControlBox setFrameOrigin:hudControlBoxOrigin];
399 NSString *scaleString;
400 CGFloat scale = ( ( CGFloat )[fPictureView frame].size.width) / ( ( CGFloat )imageScaledSize.width);
401 if (scale * 100.0 != 100)
403 scaleString = [NSString stringWithFormat:
404 NSLocalizedString( @" (%.0f%% actual size)",
405 @"String shown when a preview is scaled" ), scale * 100.0];
409 scaleString = @"(Actual size)";
412 if (scaleToScreen == YES)
414 scaleString = [scaleString stringByAppendingString:@" Scaled To Screen"];
416 /* Set the info fields in the hud controller */
417 [fInfoField setStringValue: [NSString stringWithFormat:
418 @"%@", sizeInfoString]];
420 [fscaleInfoField setStringValue: [NSString stringWithFormat:
421 @"%@", scaleString]];
422 /* Set the info field in the window title bar */
423 [[self window] setTitle:[NSString stringWithFormat: @"Preview - %@ %@",sizeInfoString, scaleString]];
426 - (IBAction) previewDurationPopUpChanged: (id) sender
429 [[NSUserDefaults standardUserDefaults] setObject:[fPreviewMovieLengthPopUp titleOfSelectedItem] forKey:@"PreviewLength"];
433 - (IBAction) SettingsChanged: (id) sender
435 // Purge the existing picture previews so they get recreated the next time
437 [self purgeImageCache];
438 [self pictureSliderChanged:nil];
441 - (IBAction) pictureSliderChanged: (id) sender
443 // Show the picture view
444 [fPictureView setHidden:NO];
445 [fMovieView pause:nil];
446 [fMovieView setHidden:YES];
447 [fMovieView setMovie:nil];
448 [fEncodingControlBox setHidden: YES];
450 int newPicture = [fPictureSlider intValue];
451 if (newPicture != fPicture)
453 fPicture = newPicture;
455 [self displayPreview];
459 - (IBAction)showPreviewPanel: (id)sender forTitle: (hb_title_t *)title
461 if ([fPreviewWindow isVisible])
463 [fPreviewWindow close];
467 [self showWindow:sender];
468 [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"PreviewWindowIsOpen"];
469 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
471 [self pictureSliderChanged:nil];
476 - (NSString*) pictureSizeInfoString
478 return [fInfoField stringValue];
481 - (IBAction)showPictureSettings:(id)sender
483 [fHBController showPicturePanel:self];
486 #pragma mark Hud Control Overlay
487 - (void) mouseMoved:(NSEvent *)theEvent
489 [super mouseMoved:theEvent];
490 NSPoint mouseLoc = [theEvent locationInWindow];
492 /* Test for mouse location to show/hide hud controls */
493 if( isEncoding == NO )
495 /* Since we are not encoding, verify which control hud to show
496 * or hide based on aMovie ( aMovie indicates we need movie controls )
498 NSBox * hudBoxToShow;
499 if ( aMovie == nil ) // No movie loaded up
501 hudBoxToShow = fPictureControlBox;
503 else // We have a movie
505 hudBoxToShow = fMoviePlaybackControlBox;
508 if( NSPointInRect( mouseLoc, [fPictureControlBox frame] ) )
510 [[hudBoxToShow animator] setHidden: NO];
513 else if( NSPointInRect( mouseLoc, [fPictureViewArea frame] ) )
515 [[hudBoxToShow animator] setHidden: NO];
516 [self startHudTimer];
520 [[hudBoxToShow animator] setHidden: YES];
525 - (void) startHudTimer
528 [fHudTimer invalidate];
531 fHudTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hudTimerFired:) userInfo:nil repeats:YES];
535 - (void) stopHudTimer
539 [fHudTimer invalidate];
546 - (void) hudTimerFired: (NSTimer*)theTimer
549 if( hudTimerSeconds >= 10 )
551 /* Regardless which control box is active, after the timer
552 * period we want either one to fade to hidden.
554 [[fPictureControlBox animator] setHidden: YES];
555 [[fMoviePlaybackControlBox animator] setHidden: YES];
562 - (IBAction)toggleScaleToScreen:(id)sender
564 if (scaleToScreen == YES)
567 /* make sure we are set to a still preview */
568 [self pictureSliderChanged:nil];
569 [fScaleToScreenToggleButton setTitle:@"Scale To Screen"];
574 /* make sure we are set to a still preview */
575 [self pictureSliderChanged:nil];
576 [fScaleToScreenToggleButton setTitle:@"Actual Scale"];
583 // Title-less windows normally don't receive key presses, override this
584 - (BOOL)canBecomeKeyWindow
589 // Title-less windows normally can't become main which means that another
590 // non-fullscreen window will have the "active" titlebar in expose. Bad, fix it.
591 - (BOOL)canBecomeMainWindow
597 - (IBAction)goWindowedScreen:(id)sender
600 /* Get the screen info to release the display but don't actually do
601 * it until the windowed screen is setup.
604 [self pictureSliderChanged:nil];
605 [fScaleToScreenToggleButton setTitle:@"<->"];
607 NSScreen* mainScreen = [NSScreen mainScreen];
608 NSDictionary* screenInfo = [mainScreen deviceDescription];
609 NSNumber* screenID = [screenInfo objectForKey:@"NSScreenNumber"];
610 CGDirectDisplayID displayID = (CGDirectDisplayID)[screenID longValue];
612 [fFullScreenWindow dealloc];
613 [fFullScreenWindow release];
616 [fPreviewWindow setContentView:fPictureViewArea];
617 [fPictureViewArea setNeedsDisplay:YES];
618 [self setWindow:fPreviewWindow];
621 [fPreviewWindow makeKeyAndOrderFront:self];
623 /* Set the window back to regular level */
624 [fPreviewWindow setLevel:NSNormalWindowLevel];
626 /* Set the isFullScreen flag back to NO */
629 /* make sure we are set to a still preview */
630 [self pictureSliderChanged:nil];
631 [self showPreviewWindow:nil];
633 /* Change the name of fFullScreenToggleButton appropriately */
634 //[fFullScreenToggleButton setTitle: @"Full Screen"];
635 // [fScaleToScreenToggleButton setHidden:YES];
636 /* set the picture settings pallete back to normal level */
637 [fHBController picturePanelWindowed];
639 /* Release the display now that the we are back in windowed mode */
640 CGDisplayRelease(displayID);
642 [fPreviewWindow setAcceptsMouseMovedEvents:YES];
643 //[fFullScreenWindow setAcceptsMouseMovedEvents:NO];
646 [self startHudTimer];
651 #pragma mark Still Preview Image Processing
654 // This function converts an image created by libhb (specified via pictureIndex) into
655 // an NSImage suitable for the GUI code to use. If removeBorders is YES,
656 // makeImageForPicture crops the image generated by libhb stripping off the gray
657 // border around the content. This is the low-level method that generates the image.
658 // -imageForPicture calls this function whenever it can't find an image in its cache.
659 + (NSImage *) makeImageForPicture: (int)pictureIndex
660 libhb:(hb_handle_t*)handle
661 title:(hb_title_t*)title
663 static uint8_t * buffer;
664 static int bufferSize;
666 // Make sure we have a big enough buffer to receive the image from libhb. libhb
667 int dstWidth = title->job->width;
668 int dstHeight = title->job->height;
671 newSize = dstWidth * dstHeight * 4;
672 if( bufferSize < newSize )
674 bufferSize = newSize;
675 buffer = (uint8_t *) realloc( buffer, bufferSize );
678 hb_get_preview( handle, title, pictureIndex, buffer );
680 // Create an NSBitmapImageRep and copy the libhb image into it, converting it from
681 // libhb's format to one suitable for NSImage. Along the way, we'll strip off the
682 // border around libhb's image.
684 // The image data returned by hb_get_preview is 4 bytes per pixel, BGRA format.
687 NSBitmapFormat bitmapFormat = (NSBitmapFormat)NSAlphaFirstBitmapFormat;
688 NSBitmapImageRep * imgrep = [[[NSBitmapImageRep alloc]
689 initWithBitmapDataPlanes:nil
693 samplesPerPixel:3 // ignore alpha
696 colorSpaceName:NSCalibratedRGBColorSpace
697 bitmapFormat:bitmapFormat
698 bytesPerRow:dstWidth * 4
699 bitsPerPixel:32] autorelease];
701 UInt32 * src = (UInt32 *)buffer;
702 UInt32 * dst = (UInt32 *)[imgrep bitmapData];
704 for (r = 0; r < dstHeight; r++)
706 for (c = 0; c < dstWidth; c++)
707 #if TARGET_RT_LITTLE_ENDIAN
708 *dst++ = Endian32_Swap(*src++);
714 NSImage * img = [[[NSImage alloc] initWithSize: NSMakeSize(dstWidth, dstHeight)] autorelease];
715 [img addRepresentation:imgrep];
720 // Returns the preview image for the specified index, retrieving it from its internal
721 // cache or by calling makeImageForPicture if it is not cached. Generally, you should
722 // use imageForPicture so that images are cached. Calling makeImageForPicture will
723 // always generate a new copy of the image.
724 - (NSImage *) imageForPicture: (int) pictureIndex
726 // The preview for the specified index may not currently exist, so this method
727 // generates it if necessary.
728 NSString * key = [NSString stringWithFormat:@"%d", pictureIndex];
729 NSImage * theImage = [fPicturePreviews objectForKey:key];
732 theImage = [PreviewController makeImageForPicture:pictureIndex libhb:fHandle title:fTitle];
733 [fPicturePreviews setObject:theImage forKey:key];
738 // Purges all images from the cache. The next call to imageForPicture will cause a new
739 // image to be generated.
740 - (void) purgeImageCache
742 [fPicturePreviews removeAllObjects];
747 #pragma mark Movie Preview
748 - (IBAction) createMoviePreview: (id) sender
752 /* Lets make sure the still picture previews are showing in case
753 * there is currently a movie showing */
754 [self pictureSliderChanged:nil];
756 /* Rip or Cancel ? */
758 hb_get_state2( fPreviewLibhb, &s );
760 if(sender == fCancelPreviewMovieButton && (s.state == HB_STATE_WORKING || s.state == HB_STATE_PAUSED))
762 hb_stop( fPreviewLibhb );
763 [fPictureView setHidden:NO];
764 [fMovieView pause:nil];
765 [fMovieView setHidden:YES];
766 [fMovieView setMovie:nil];
767 [fPictureSlider setHidden:NO];
774 /* we use controller.mm's prepareJobForPreview to go ahead and set all of our settings
775 * however, we want to use a temporary destination field of course
776 * so that we do not put our temp preview in the users chosen
779 hb_job_t * job = fTitle->job;
781 /* We run our current setting through prepeareJob in Controller.mm
782 * just as if it were a regular encode */
784 [fHBController prepareJobForPreview];
786 /* Destination file. We set this to our preview directory
787 * changing the extension appropriately.*/
788 if (fTitle->job->mux == HB_MUX_MP4) // MP4 file
790 /* we use .m4v for our mp4 files so that ac3 and chapters in mp4 will play properly */
791 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.m4v";
793 else if (fTitle->job->mux == HB_MUX_MKV) // MKV file
795 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.mkv";
797 else if (fTitle->job->mux == HB_MUX_AVI) // AVI file
799 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.avi";
801 else if (fTitle->job->mux == HB_MUX_OGM) // OGM file
803 fPreviewMoviePath = @"~/Library/Application Support/HandBrake/Previews/preview_temp.ogm";
806 fPreviewMoviePath = [[fPreviewMoviePath stringByExpandingTildeInPath]retain];
808 /* See if there is an existing preview file, if so, delete it */
809 if( ![[NSFileManager defaultManager] fileExistsAtPath:fPreviewMoviePath] )
811 [[NSFileManager defaultManager] removeFileAtPath:fPreviewMoviePath
815 /* We now direct our preview encode to fPreviewMoviePath */
816 fTitle->job->file = [fPreviewMoviePath UTF8String];
818 /* We use our advance pref to determine how many previews to scan */
819 int hb_num_previews = [[[NSUserDefaults standardUserDefaults] objectForKey:@"PreviewsNumber"] intValue];
820 job->start_at_preview = fPicture + 1;
821 job->seek_points = hb_num_previews;
823 /* we use the preview duration popup to get the specified
824 * number of seconds for the preview encode.
827 job->pts_to_stop = [[fPreviewMovieLengthPopUp titleOfSelectedItem] intValue] * 90000LL;
829 /* lets go ahead and send it off to libhb
830 * Note: unlike a full encode, we only send 1 pass regardless if the final encode calls for 2 passes.
831 * this should suffice for a fairly accurate short preview and cuts our preview generation time in half.
832 * However we also need to take into account the indepth scan for subtitles.
835 * If scanning we need to do some extra setup of the job.
837 if( job->indepth_scan == 1 )
842 * When subtitle scan is enabled do a fast pre-scan job
843 * which will determine which subtitles to enable, if any.
846 x264opts_tmp = job->x264opts;
848 job->x264opts = NULL;
849 job->indepth_scan = 1;
851 * Add the pre-scan job
853 hb_add( fPreviewLibhb, job );
854 job->x264opts = x264opts_tmp;
856 /* Go ahead and perform the actual encoding preview scan */
857 job->indepth_scan = 0;
859 hb_add( fPreviewLibhb, job );
861 [fEncodingControlBox setHidden: NO];
862 [fPictureControlBox setHidden: YES];
864 [fMovieCreationProgressIndicator setHidden: NO];
865 [fPreviewMovieStatusField setHidden: NO];
869 /* Let fPreviewLibhb do the job */
870 hb_start( fPreviewLibhb );
874 - (void) startReceivingLibhbNotifications
878 fLibhbTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(libhbTimerFired:) userInfo:nil repeats:YES];
879 [fLibhbTimer retain];
883 - (void) stopReceivingLibhbNotifications
887 [fLibhbTimer invalidate];
888 [fLibhbTimer release];
892 - (void) libhbTimerFired: (NSTimer*)theTimer
895 hb_get_state( fPreviewLibhb, &s );
896 [self libhbStateChanged: s];
900 - (void) libhbStateChanged: (hb_state_t)state
902 switch( state.state )
905 case HB_STATE_SCANNING:
906 case HB_STATE_SCANDONE:
909 case HB_STATE_WORKING:
911 #define p state.param.working
913 NSMutableString * string;
914 /* Update text field */
915 string = [NSMutableString stringWithFormat: NSLocalizedString( @"Encoding preview: %.2f %%", @"" ), 100.0 * p.progress];
919 [string appendFormat:
920 NSLocalizedString( @" (%.2f fps, avg %.2f fps, ETA %02dh%02dm%02ds)", @"" ),
921 p.rate_cur, p.rate_avg, p.hours, p.minutes, p.seconds];
923 [fPreviewMovieStatusField setStringValue: string];
925 [fMovieCreationProgressIndicator setIndeterminate: NO];
927 [fMovieCreationProgressIndicator setDoubleValue: 100.0 * p.progress];
929 [fCreatePreviewMovieButton setTitle: @"Cancel Preview"];
936 #define p state.param.muxing
937 case HB_STATE_MUXING:
939 // Update fMovieCreationProgressIndicator
940 [fMovieCreationProgressIndicator setIndeterminate: YES];
941 [fMovieCreationProgressIndicator startAnimation: nil];
942 [fPreviewMovieStatusField setStringValue: [NSString stringWithFormat:
943 NSLocalizedString( @"Muxing Preview ...", @"" )]];
947 case HB_STATE_PAUSED:
948 [fMovieCreationProgressIndicator stopAnimation: nil];
951 case HB_STATE_WORKDONE:
953 // Delete all remaining jobs since libhb doesn't do this on its own.
955 while( ( job = hb_job(fPreviewLibhb, 0) ) )
956 hb_rem( fHandle, job );
958 [fPreviewMovieStatusField setStringValue: @""];
959 [fPreviewMovieStatusField setHidden: YES];
961 [fMovieCreationProgressIndicator stopAnimation: nil];
962 [fMovieCreationProgressIndicator setHidden: YES];
963 [fEncodingControlBox setHidden: YES];
964 [fPictureControlBox setHidden: YES];
967 // Show the movie view
968 [self showMoviePreview:fPreviewMoviePath];
969 [fCreatePreviewMovieButton setTitle: @"Live Preview"];
976 - (IBAction) toggleMoviePreviewPlayPause: (id) sender
978 /* make sure a movie is even loaded up */
981 /* For some stupid reason there is no "isPlaying" method for a QTMovie
982 * object, given that, we detect the rate to determine whether the movie
985 if ([aMovie rate] != 0) // we are playing
987 [fMovieView pause:aMovie];
988 [fPlayPauseButton setTitle: @">"];
990 else // we are paused or stopped
992 [fMovieView play:aMovie];
993 [fPlayPauseButton setTitle: @"||"];
999 - (IBAction) moviePlaybackGoToBeginning: (id) sender
1001 /* make sure a movie is even loaded up */
1004 [fMovieView gotoBeginning:aMovie];
1009 - (IBAction) moviePlaybackGoToEnd: (id) sender
1011 /* make sure a movie is even loaded up */
1014 [fMovieView gotoEnd:aMovie];
1019 - (IBAction) moviePlaybackGoBackwardOneFrame: (id) sender
1021 /* make sure a movie is even loaded up */
1024 [fMovieView pause:aMovie]; // Pause the movie
1025 [fMovieView stepBackward:aMovie];
1030 - (IBAction) moviePlaybackGoForwardOneFrame: (id) sender
1032 /* make sure a movie is even loaded up */
1035 [fMovieView pause:aMovie]; // Pause the movie
1036 [fMovieView stepForward:aMovie];
1042 - (void) startMovieTimer
1045 [fMovieTimer invalidate];
1046 [fMovieTimer release];
1048 fMovieTimer = [NSTimer scheduledTimerWithTimeInterval:0.10 target:self selector:@selector(movieTimerFired:) userInfo:nil repeats:YES];
1049 [fMovieTimer retain];
1052 - (void) stopMovieTimer
1056 [fMovieTimer invalidate];
1057 [fMovieTimer release];
1062 - (void) movieTimerFired: (NSTimer*)theTimer
1066 [self adjustPreviewScrubberForCurrentMovieTime];
1067 [fMovieInfoField setStringValue: [NSString stringWithFormat:NSLocalizedString( @"%@", @"" ),[self calculatePlaybackSMTPETimecodeForDisplay]]];
1073 - (IBAction) showMoviePreview: (NSString *) path
1075 /* Since the gray background for the still images is part of
1076 * fPictureView, lets leave the picture view visible and postion
1077 * the fMovieView over the image portion of fPictureView so
1078 * we retain the gray cropping border we have already established
1079 * with the still previews
1082 /* Load the new movie into fMovieView */
1087 NSURL *movieUrl = [NSURL fileURLWithPath:path];
1088 NSDictionary *movieAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
1089 movieUrl, QTMovieURLAttribute,
1090 [NSNumber numberWithBool:NO], QTMovieAskUnresolvedDataRefsAttribute,
1091 [NSNumber numberWithBool:YES], @"QTMovieOpenForPlaybackAttribute",
1092 [NSNumber numberWithBool:NO], @"QTMovieOpenAsyncRequiredAttribute",
1093 [NSNumber numberWithBool:NO], @"QTMovieOpenAsyncOKAttribute",
1094 [NSNumber numberWithBool:YES], @"QTMovieIsSteppableAttribute",
1095 QTMovieApertureModeClean, QTMovieApertureModeAttribute,
1098 aMovie = [[[QTMovie alloc] initWithAttributes:movieAttributes error:&outError] autorelease];
1103 NSLog(@"Unable to open movie");
1108 /* we get some size information from the preview movie */
1109 NSSize movieSize= [[aMovie attributeForKey:QTMovieNaturalSizeAttribute] sizeValue];
1110 movieBounds = [fMovieView movieBounds];
1111 movieBounds.size.height = movieSize.height;
1112 /* We also get our view size to use for scaling fMovieView's size */
1113 NSSize scaledMovieViewSize = [fPictureView frame].size;
1114 [fMovieView setControllerVisible:FALSE];
1115 if ([fMovieView isControllerVisible])
1117 CGFloat controllerBarHeight = [fMovieView controllerBarHeight];
1118 if ( controllerBarHeight != 0 ) //Check if QTKit return a real value or not.
1120 movieBounds.size.height += controllerBarHeight;
1121 scaledMovieViewSize.height += controllerBarHeight;
1125 movieBounds.size.height += 15;
1126 scaledMovieViewSize.height += 15;
1130 movieBounds.size.width = movieSize.width;
1132 /* we need to account for an issue where the scaledMovieViewSize > the window size */
1133 if (scaledMovieViewSize.height > [[self window] frame].size.height)
1135 [fHBController writeToActivityLog: "showMoviePreview: Our window is not tall enough to show the controller bar ..."];
1140 /* Scale the fMovieView to scaledMovieViewSize */
1141 [fMovieView setFrameSize:scaledMovieViewSize];
1143 /*set our origin try using fPictureViewArea or fPictureView */
1144 NSPoint origin = [fPictureView frame].origin;
1145 origin.x += trunc( ( [fPictureView frame].size.width -
1146 [fMovieView frame].size.width ) / 2.0 );
1147 origin.y += trunc( ( ( [fPictureView frame].size.height -
1148 [fMovieView frame].size.height ) / 2.0 ) - 7.5 );
1150 [fMovieView setFrameOrigin:origin];
1151 [fMovieView setMovie:aMovie];
1152 [fMovieView setHidden:NO];
1153 [fMoviePlaybackControlBox setHidden: NO];
1154 [fPictureControlBox setHidden: YES];
1156 // to actually play the movie
1158 [self initPreviewScrubberForMovie];
1159 [self startMovieTimer];
1160 /* Install amovie notifications */
1161 [aMovie setDelegate:self];
1162 [self installMovieCallbacks];
1163 [fMovieView play:aMovie];
1169 #pragma mark *** Movie Playback Scrubber and time code methods ***
1171 /* Since MacOSX Leopard QTKit has taken over some responsibility for assessing movie playback
1172 * information from the old QuickTime carbon api ( time code information as well as fps, etc.).
1173 * However, the QTKit devs at apple were not really big on documentation and further ...
1174 * QuickTimes ability to playback HB's largely variable framerate output makes perfectly frame
1175 * accurate information at best convoluted. Still, for the purpose of a custom hud based custom
1176 * playback scrubber slider this has so far proven to be as accurate as I have found. To say it
1177 * could use some better accuracy is not understating it enough probably.
1178 * Most of this was gleaned from this obscure Apple Mail list thread:
1179 * http://www.mailinglistarchive.com/quicktime-api@lists.apple.com/msg05642.html
1180 * Now as we currently do not show a QTKit control bar with scrubber for display sizes > container
1181 * size, this seems to facilitate playback control from the HB custom HUD controller fairly close
1182 * to the built in controller bar.
1183 * Further work needs to be done to try to get accurate frame by frame playback display if we want it.
1184 * Note that the keyboard commands for frame by frame step through etc. work as always.
1187 // Returns a human readable string from the currentTime of movie playback
1188 - (NSString*) calculatePlaybackSMTPETimecodeForDisplay
1190 QTTime time = [aMovie currentTime];
1192 NSString *smtpeTimeCodeString;
1193 int days, hour, minute, second, frame;
1196 result = time.timeValue / time.timeScale; // second
1197 frame = (time.timeValue % time.timeScale) / 100;
1199 second = result % 60;
1201 result = result / 60; // minute
1202 minute = result % 60;
1204 result = result / 60; // hour
1208 smtpeTimeCodeString = [NSString stringWithFormat:@"Time: %02d:%02d:%02d", hour, minute, second]; // hh:mm:ss
1209 return smtpeTimeCodeString;
1214 // Initialize the preview scrubber min/max to appropriate values for the current movie
1215 -(void) initPreviewScrubberForMovie
1220 QTTime duration = [aMovie duration];
1221 float result = duration.timeValue / duration.timeScale;
1223 [fMovieScrubberSlider setMinValue:0.0];
1224 [fMovieScrubberSlider setMaxValue: (float)result];
1225 [fMovieScrubberSlider setFloatValue: 0.0];
1230 -(void) adjustPreviewScrubberForCurrentMovieTime
1234 QTTime time = [aMovie currentTime];
1236 float result = (float)time.timeValue / (float)time.timeScale;;
1237 [fMovieScrubberSlider setFloatValue:result];
1241 - (IBAction) previewScrubberChanged: (id) sender
1245 [fMovieView pause:aMovie]; // Pause the movie
1246 QTTime time = [aMovie currentTime];
1247 [self setTime: time.timeScale * [fMovieScrubberSlider floatValue]];
1248 [self calculatePlaybackSMTPETimecodeForDisplay];
1251 #pragma mark *** Movie Notifications ***
1253 - (void) installMovieCallbacks
1257 /*Notification for any time the movie rate changes */
1258 [[NSNotificationCenter defaultCenter] addObserver:self
1259 selector:@selector(movieRateDidChange:)
1260 name:@"QTMovieRateDidChangeNotification"
1262 /*Notification for when the movie ends */
1263 [[NSNotificationCenter defaultCenter] addObserver:self
1264 selector:@selector(movieDidEnd:)
1265 name:@"QTMovieDidEndNotification"
1269 - (void)removeMovieCallbacks
1273 /*Notification for any time the movie rate changes */
1274 [[NSNotificationCenter defaultCenter] removeObserver:self
1275 name:@"QTMovieRateDidChangeNotification"
1277 /*Notification for when the movie ends */
1278 [[NSNotificationCenter defaultCenter] removeObserver:self
1279 name:@"QTMovieDidEndNotification"
1284 - (void)movieRateDidChange:(NSNotification *)notification
1288 /* For some stupid reason there is no "isPlaying" method for a QTMovie
1289 * object, given that, we detect the rate to determine whether the movie
1290 * is playing or not.
1292 //[self adjustPreviewScrubberForCurrentMovieTime];
1293 if ([aMovie rate] != 0) // we are playing
1295 [fPlayPauseButton setTitle: @"||"];
1297 else // we are paused or stopped
1299 [fPlayPauseButton setTitle: @">"];
1303 /* This notification is not currently used. However we should keep it "just in case" as
1304 * live preview playback is enhanced.
1306 - (void)movieDidEnd:(NSNotification *)notification
1309 //[fHBController writeToActivityLog: "Movie DidEnd Notification Received"];
1313 #pragma mark *** QTTime Utilities ***
1315 // convert a time value (long) to a QTTime structure
1316 -(void)timeToQTTime:(long)timeValue resultTime:(QTTime *)aQTTime
1318 NSNumber *timeScaleObj;
1319 long timeScaleValue;
1321 timeScaleObj = [aMovie attributeForKey:QTMovieTimeScaleAttribute];
1322 timeScaleValue = [timeScaleObj longValue];
1324 *aQTTime = QTMakeTime(timeValue, timeScaleValue);
1327 // set the movie's current time
1328 -(void)setTime:(int)timeValue
1331 NSValue *valueForQTTime;
1333 [self timeToQTTime:timeValue resultTime:&movieQTTime];
1335 valueForQTTime = [NSValue valueWithQTTime:movieQTTime];
1337 [aMovie setAttribute:valueForQTTime forKey:QTMovieCurrentTimeAttribute];
1343 @implementation PreviewController (Private)
1346 // -[PictureController(Private) optimalViewSizeForImageSize:]
1348 // Given the size of the preview image to be shown, returns the best possible
1349 // size for the view.
1351 - (NSSize)optimalViewSizeForImageSize: (NSSize)imageSize
1353 // The min size is 480x360
1354 CGFloat minWidth = 480.0;
1355 CGFloat minHeight = 360.0;
1357 NSSize screenSize = [[[self window] screen] visibleFrame].size;
1358 NSSize sheetSize = [[self window] frame].size;
1359 NSSize viewAreaSize = [fPictureViewArea frame].size;
1360 CGFloat paddingX = 0.00;
1361 CGFloat paddingY = 0.00;
1363 if (fTitle->width > screenSize.width || fTitle->height > screenSize.height)
1365 if (scaleToScreen == YES)
1367 paddingX = screenSize.width - imageSize.width;
1368 paddingY = screenSize.height - imageSize.height;
1373 paddingX = sheetSize.width - viewAreaSize.width;
1374 paddingY = sheetSize.height - viewAreaSize.height;
1381 maxWidth = screenSize.width - paddingX;
1382 maxHeight = screenSize.height - paddingY;
1384 NSSize resultSize = imageSize;
1385 CGFloat resultPar = resultSize.width / resultSize.height;
1387 //note, a mbp 15" at 1440 x 900 is a 1.6 ar
1388 CGFloat screenAspect = screenSize.width / screenSize.height;
1389 // Note, a standard dvd will use 720 x 480 which is a 1.5
1390 CGFloat viewAreaAspect = viewAreaSize.width / viewAreaSize.height;
1392 if (scaleToScreen == YES)
1395 if (screenAspect < viewAreaAspect)
1397 resultSize.width = screenSize.width;
1398 resultSize.height = (screenSize.width / viewAreaAspect);
1402 resultSize.height = screenSize.height;
1403 resultSize.width = resultSize.height * viewAreaAspect;
1407 else if ( resultSize.width > maxWidth || resultSize.height > maxHeight )
1409 // Source is larger than screen in one or more dimensions
1410 if ( resultPar > screenAspect )
1412 // Source aspect wider than screen aspect, snap to max width and vary height
1413 resultSize.width = maxWidth;
1414 resultSize.height = (maxWidth / resultPar);
1418 // Source aspect narrower than screen aspect, snap to max height vary width
1419 resultSize.height = maxHeight;
1420 resultSize.width = (maxHeight * resultPar);
1424 // If necessary, grow to minimum dimensions to ensure controls overlay is not obstructed
1425 if ( resultSize.width < minWidth )
1427 resultSize.width = minWidth;
1429 if ( resultSize.height < minHeight )
1431 resultSize.height = minHeight;
1440 // -[PictureController(Private) resizePanelForViewSize:animate:]
1442 // Resizes the entire window to accomodate a view of a particular size.
1444 - (void)resizeSheetForViewSize: (NSSize)viewSize
1446 // Figure out the deltas for the new frame area
1447 NSSize currentSize = [fPictureViewArea frame].size;
1448 CGFloat deltaX = viewSize.width - currentSize.width;
1449 CGFloat deltaY = viewSize.height - currentSize.height;
1451 // Now resize the whole panel by those same deltas, but don't exceed the min
1452 NSRect frame = [[self window] frame];
1453 NSSize maxSize = [[[self window] screen] visibleFrame].size;
1454 /* if we are not Scale To Screen, put an 85% of visible screen on the window */
1455 if (scaleToScreen == NO )
1457 maxSize.width = maxSize.width * 0.85;
1458 maxSize.height = maxSize.height * 0.85;
1461 /* Set our min size to the storage size */
1463 minSize.width = fTitle->width;
1464 minSize.height = fTitle->height;
1466 frame.size.width += deltaX;
1467 frame.size.height += deltaY;
1468 if( frame.size.width < minSize.width )
1470 frame.size.width = minSize.width;
1473 if( frame.size.height < minSize.height )
1475 frame.size.height = minSize.height;
1477 /* compare frame to max size of screen */
1479 if( frame.size.width > maxSize.width )
1481 frame.size.width = maxSize.width;
1484 if( frame.size.height > maxSize.height )
1486 frame.size.height = maxSize.height;
1493 // But now the sheet is off-center, so also shift the origin to center it and
1494 // keep the top aligned.
1495 if( frame.size.width != [[self window] frame].size.width )
1496 frame.origin.x -= (deltaX / 2.0);
1499 /* Since upon launch we can open up the preview window if it was open
1500 * the last time we quit (and at the size it was) we want to make
1501 * sure that upon resize we do not have the window off the screen
1502 * So check the origin against the screen origin and adjust if
1505 NSSize screenSize = [[[self window] screen] visibleFrame].size;
1506 NSPoint screenOrigin = [[[self window] screen] frame].origin;
1507 if (screenSize.height < frame.size.height)
1509 frame.size.height = screenSize.height;
1511 if (screenSize.width < frame.size.width)
1513 frame.size.width = screenSize.width;
1517 /* our origin is off the screen to the left*/
1518 if (frame.origin.x < screenOrigin.x)
1520 /* so shift our origin to the right */
1521 frame.origin.x = screenOrigin.x;
1523 else if ((frame.origin.x + frame.size.width) > (screenOrigin.x + screenSize.width))
1525 /* the right side of the preview is off the screen, so shift to the left */
1526 frame.origin.x = (screenOrigin.x + screenSize.width) - frame.size.width;
1529 [[self window] setFrame:frame display:YES animate:YES];
1535 // -[PictureController(Private) setViewSize:]
1537 // Changes the view's size and centers it vertically inside of its area.
1538 // Assumes resizeSheetForViewSize: has already been called.
1540 - (void)setViewSize: (NSSize)viewSize
1543 /* special case for scaleToScreen */
1544 NSSize screenSize = [[[self window] screen] visibleFrame].size;
1545 NSSize areaSize = [fPictureViewArea frame].size;
1546 NSSize pictureSize = [fPictureView frame].size;
1547 CGFloat viewSizeAspect = viewSize.width / viewSize.height;
1549 if (viewSize.width > areaSize.width || viewSize.height > areaSize.height)
1552 if (viewSizeAspect > 1.0) // we are wider than taller, so expand the width to fill the area and scale the height
1554 viewSize.width = areaSize.width;
1555 viewSize.height = viewSize.width / viewSizeAspect;
1559 viewSize.height = areaSize.height;
1560 viewSize.width = viewSize.height * viewSizeAspect;
1565 [fPictureView setFrameSize:viewSize];
1566 NSSize newAreaSize = [fPictureViewArea frame].size;
1569 // center it vertically and horizontally
1570 NSPoint origin = [fPictureViewArea frame].origin;
1571 origin.y += ([fPictureViewArea frame].size.height -
1572 [fPictureView frame].size.height) / 2.0;
1574 origin.x += ([fPictureViewArea frame].size.width -
1575 [fPictureView frame].size.width) / 2.0;
1577 origin.x = floor( origin.x );
1578 origin.y = floor( origin.y );
1580 [fPictureView setFrameOrigin:origin];
1585 - (BOOL)viewNeedsToResizeToSize: (NSSize)newSize
1587 NSSize viewSize = [fPictureViewArea frame].size;
1588 return (newSize.width != viewSize.width || newSize.height != viewSize.height);