VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxHeadless/VideoCapture/FFmpegFB.cpp@ 11836

Last change on this file since 11836 was 11654, checked in by vboxsync, 16 years ago

FE/VBoxHeadless: fix libavcodec version issues.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 36.6 KB
Line 
1/** @file
2 *
3 * Framebuffer implementation that interfaces with FFmpeg
4 * to create a video of the guest.
5 */
6
7/*
8 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#define LOG_GROUP LOG_GROUP_GUI
24
25#include "FFmpegFB.h"
26
27#include <iprt/file.h>
28#include <iprt/param.h>
29#include <iprt/assert.h>
30#include <VBox/log.h>
31#include <png.h>
32#include <iprt/stream.h>
33
34#define VBOX_SHOW_AVAILABLE_FORMATS
35
36// external constructor for dynamic loading
37/////////////////////////////////////////////////////////////////////////////
38
39/**
40 * Callback function to register an ffmpeg framebuffer.
41 *
42 * @returns COM status code.
43 * @param width Framebuffer width.
44 * @param height Framebuffer height.
45 * @param bitrate Bitrate of mpeg file to be created.
46 * @param filename Name of mpeg file to be created
47 * @retval retVal The new framebuffer
48 */
49extern "C" DECLEXPORT(HRESULT) VBoxRegisterFFmpegFB(ULONG width,
50 ULONG height, ULONG bitrate,
51 com::Bstr filename,
52 IFramebuffer **retVal)
53{
54 Log2(("VBoxRegisterFFmpegFB: called\n"));
55 FFmpegFB *pFramebuffer = new FFmpegFB(width, height, bitrate, filename);
56 int rc = pFramebuffer->init();
57 AssertMsg(rc == S_OK,
58 ("failed to initialise the FFmpeg framebuffer, rc = %d\n",
59 rc));
60 if (rc == S_OK)
61 {
62 *retVal = pFramebuffer;
63 return S_OK;
64 }
65 delete pFramebuffer;
66 return rc;
67}
68
69
70
71
72
73// constructor / destructor
74/////////////////////////////////////////////////////////////////////////////
75
76/**
77 * Perform parts of initialisation which are guaranteed not to fail
78 * unless we run out of memory. In this case, we just set the guest
79 * buffer to 0 so that RequestResize() does not free it the first time
80 * it is called.
81 */
82FFmpegFB::FFmpegFB(ULONG width, ULONG height, ULONG bitrate,
83 com::Bstr filename) :
84 mfUrlOpen(false),
85 mBitRate(bitrate),
86 mPixelFormat(FramebufferPixelFormat_Opaque),
87 mBitsPerPixel(0),
88 mFileName(filename),
89 mBytesPerLine(0),
90 mFrameWidth(width), mFrameHeight(height),
91 mYUVFrameSize(width * height * 3 / 2),
92 mRGBBuffer(0), mpFormatContext(0), mpStream(0),
93 mOutOfMemory(false), mToggle(false)
94{
95 ULONG cPixels = width * height;
96
97 LogFlow(("Creating FFmpegFB object %p, width=%lu, height=%lu\n",
98 this, (unsigned long) width, (unsigned long) height));
99 Assert(width % 2 == 0 && height % 2 == 0);
100 /* For temporary RGB frame we allocate enough memory to deal with
101 RGB16 to RGB32 */
102 mTempRGBBuffer = reinterpret_cast<uint8_t *>(av_malloc(cPixels * 4));
103 if (mTempRGBBuffer == 0)
104 goto nomem_temp_rgb_buffer;
105 mYUVBuffer = reinterpret_cast<uint8_t *>(av_malloc(mYUVFrameSize));
106 if (mYUVBuffer == 0)
107 goto nomem_yuv_buffer;
108 mFrame = avcodec_alloc_frame();
109 if (mFrame == 0)
110 goto nomem_mframe;
111 mOutBuf = reinterpret_cast<uint8_t *>(av_malloc(mYUVFrameSize * 2));
112 if (mOutBuf == 0)
113 goto nomem_moutbuf;
114
115 return;
116
117 /* C-based memory allocation and how to deal with it in C++ :) */
118nomem_moutbuf:
119 Log(("Failed to allocate memory for mOutBuf\n"));
120 av_free(mFrame);
121nomem_mframe:
122 Log(("Failed to allocate memory for mFrame\n"));
123 av_free(mYUVBuffer);
124nomem_yuv_buffer:
125 Log(("Failed to allocate memory for mYUVBuffer\n"));
126 av_free(mTempRGBBuffer);
127nomem_temp_rgb_buffer:
128 Log(("Failed to allocate memory for mTempRGBBuffer\n"));
129 mOutOfMemory = true;
130}
131
132
133/**
134 * Write the last frame to disk and free allocated memory
135 */
136FFmpegFB::~FFmpegFB()
137{
138 LogFlow(("Destroying FFmpegFB object %p\n", this));
139 if (mpFormatContext != 0)
140 {
141 if (mfUrlOpen)
142 {
143 /* Dummy update to make sure we get all the frame (timing). */
144 BOOL dummy;
145 NotifyUpdate(0, 0, 0, 0, &dummy);
146 /* Write the last pending frame before exiting */
147 int rc = do_rgb_to_yuv_conversion();
148 if (rc == S_OK)
149 do_encoding_and_write();
150#if 1
151 /* Add another 10 seconds. */
152 for (int i = 10*25; i > 0; i--)
153 do_encoding_and_write();
154#endif
155 /* write a png file of the last frame */
156 write_png();
157 avcodec_close(mpStream->codec);
158 av_write_trailer(mpFormatContext);
159 /* free the streams */
160 for(unsigned i = 0; i < mpFormatContext->nb_streams; i++) {
161 av_freep(&mpFormatContext->streams[i]->codec);
162 av_freep(&mpFormatContext->streams[i]);
163 }
164/* Changed sometime between 50.5.0 and 52.7.0 */
165#if LIBAVFORMAT_VERSION_INT >= (52 << 16)
166 url_fclose(mpFormatContext->pb);
167#else /* older version */
168 url_fclose(&mpFormatContext->pb);
169#endif /* older version */
170 }
171 av_free(mpFormatContext);
172 }
173 RTCritSectDelete(&mCritSect);
174 /* We have already freed the stream above */
175 mpStream = 0;
176 if (mTempRGBBuffer != 0)
177 av_free(mTempRGBBuffer);
178 if (mYUVBuffer != 0)
179 av_free(mYUVBuffer);
180 if (mFrame != 0)
181 av_free(mFrame);
182 if (mOutBuf != 0)
183 av_free(mOutBuf);
184 if (mRGBBuffer != 0)
185 RTMemFree(mRGBBuffer);
186}
187
188// public methods only for internal purposes
189/////////////////////////////////////////////////////////////////////////////
190
191/**
192 * Perform any parts of the initialisation which could potentially fail
193 * for reasons other than "out of memory".
194 *
195 * @returns COM status code
196 * @param width width to be used for MPEG frame framebuffer and initially
197 * for the guest frame buffer - must be a multiple of two
198 * @param height height to be used for MPEG frame framebuffer and
199 * initially for the guest framebuffer - must be a multiple
200 * of two
201 * @param depth depth to be used initially for the guest framebuffer
202 */
203HRESULT FFmpegFB::init()
204{
205 LogFlow(("Initialising FFmpegFB object %p\n", this));
206 if (mOutOfMemory == true)
207 return E_OUTOFMEMORY;
208 int rc = RTCritSectInit(&mCritSect);
209 AssertReturn(rc == VINF_SUCCESS, E_UNEXPECTED);
210 int rcSetupLibrary = setup_library();
211 AssertReturn(rcSetupLibrary == S_OK, rcSetupLibrary);
212 int rcSetupFormat = setup_output_format();
213 AssertReturn(rcSetupFormat == S_OK, rcSetupFormat);
214 int rcOpenCodec = open_codec();
215 AssertReturn(rcOpenCodec == S_OK, rcOpenCodec);
216 int rcOpenFile = open_output_file();
217 AssertReturn(rcOpenFile == S_OK, rcOpenFile);
218 /* Fill in the picture data for the AVFrame - not particularly
219 elegant, but that is the API. */
220 avpicture_fill((AVPicture *) mFrame, mYUVBuffer, PIX_FMT_YUV420P,
221 mFrameWidth, mFrameHeight);
222 /* Set the initial framebuffer size to the mpeg frame dimensions */
223 BOOL finished;
224 RequestResize(0, FramebufferPixelFormat_Opaque, NULL, 0, 0,
225 mFrameWidth, mFrameHeight, &finished);
226 /* Start counting time */
227 mLastTime = RTTimeMilliTS();
228 mLastTime = mLastTime - mLastTime % 40;
229 return rc;
230}
231
232// IFramebuffer properties
233/////////////////////////////////////////////////////////////////////////////
234
235/**
236 * Return the address of the frame buffer for the virtual VGA device to
237 * write to. If COMGETTER(UsesGuestVRAM) returns FLASE (or if this address
238 * is not the same as the guests VRAM buffer), the device will perform
239 * translation.
240 *
241 * @returns COM status code
242 * @retval address The address of the buffer
243 */
244STDMETHODIMP FFmpegFB::COMGETTER(Address) (BYTE **address)
245{
246 if (!address)
247 return E_POINTER;
248 LogFlow(("FFmpeg::COMGETTER(Address): returning address %p\n", mBufferAddress));
249 *address = mBufferAddress;
250 return S_OK;
251}
252
253/**
254 * Return the width of our frame buffer.
255 *
256 * @returns COM status code
257 * @retval width The width of the frame buffer
258 */
259STDMETHODIMP FFmpegFB::COMGETTER(Width) (ULONG *width)
260{
261 if (!width)
262 return E_POINTER;
263 LogFlow(("FFmpeg::COMGETTER(Width): returning width %lu\n",
264 (unsigned long) mGuestWidth));
265 *width = mGuestWidth;
266 return S_OK;
267}
268
269/**
270 * Return the height of our frame buffer.
271 *
272 * @returns COM status code
273 * @retval height The height of the frame buffer
274 */
275STDMETHODIMP FFmpegFB::COMGETTER(Height) (ULONG *height)
276{
277 if (!height)
278 return E_POINTER;
279 LogFlow(("FFmpeg::COMGETTER(Height): returning height %lu\n",
280 (unsigned long) mGuestHeight));
281 *height = mGuestHeight;
282 return S_OK;
283}
284
285/**
286 * Return the colour depth of our frame buffer. Note that we actually
287 * store the pixel format, not the colour depth internally, since
288 * when display sets FramebufferPixelFormat_Opaque, it
289 * wants to retreive FramebufferPixelFormat_Opaque and
290 * nothing else.
291 *
292 * @returns COM status code
293 * @retval bitsPerPixel The colour depth of the frame buffer
294 */
295STDMETHODIMP FFmpegFB::COMGETTER(BitsPerPixel) (ULONG *bitsPerPixel)
296{
297 if (!bitsPerPixel)
298 return E_POINTER;
299 *bitsPerPixel = mBitsPerPixel;
300 LogFlow(("FFmpeg::COMGETTER(BitsPerPixel): returning depth %lu\n",
301 (unsigned long) *bitsPerPixel));
302 return S_OK;
303}
304
305/**
306 * Return the number of bytes per line in our frame buffer.
307 *
308 * @returns COM status code
309 * @retval bytesPerLine The number of bytes per line
310 */
311STDMETHODIMP FFmpegFB::COMGETTER(BytesPerLine) (ULONG *bytesPerLine)
312{
313 if (!bytesPerLine)
314 return E_POINTER;
315 LogFlow(("FFmpeg::COMGETTER(BytesPerLine): returning line size %lu\n",
316 (unsigned long) mBytesPerLine));
317 *bytesPerLine = mBytesPerLine;
318 return S_OK;
319}
320
321/**
322 * Return the pixel layout of our frame buffer.
323 *
324 * @returns COM status code
325 * @retval pixelFormat The pixel layout
326 */
327STDMETHODIMP FFmpegFB::COMGETTER(PixelFormat) (ULONG *pixelFormat)
328{
329 if (!pixelFormat)
330 return E_POINTER;
331 LogFlow(("FFmpeg::COMGETTER(PixelFormat): returning pixel format: %lu\n",
332 (unsigned long) mPixelFormat));
333 *pixelFormat = mPixelFormat;
334 return S_OK;
335}
336
337/**
338 * Return whether we use the guest VRAM directly.
339 *
340 * @returns COM status code
341 * @retval pixelFormat The pixel layout
342 */
343STDMETHODIMP FFmpegFB::COMGETTER(UsesGuestVRAM) (BOOL *usesGuestVRAM)
344{
345 if (!usesGuestVRAM)
346 return E_POINTER;
347 LogFlow(("FFmpeg::COMGETTER(UsesGuestVRAM): uses guest VRAM? %d\n",
348 mRGBBuffer == NULL));
349 *usesGuestVRAM = (mRGBBuffer == NULL);
350 return S_OK;
351}
352
353/**
354 * Return the number of lines of our frame buffer which can not be used
355 * (e.g. for status lines etc?).
356 *
357 * @returns COM status code
358 * @retval heightReduction The number of unused lines
359 */
360STDMETHODIMP FFmpegFB::COMGETTER(HeightReduction) (ULONG *heightReduction)
361{
362 if (!heightReduction)
363 return E_POINTER;
364 /* no reduction */
365 *heightReduction = 0;
366 LogFlow(("FFmpeg::COMGETTER(HeightReduction): returning 0\n"));
367 return S_OK;
368}
369
370/**
371 * Return a pointer to the alpha-blended overlay used to render status icons
372 * etc above the framebuffer.
373 *
374 * @returns COM status code
375 * @retval aOverlay The overlay framebuffer
376 */
377STDMETHODIMP FFmpegFB::COMGETTER(Overlay) (IFramebufferOverlay **aOverlay)
378{
379 if (!aOverlay)
380 return E_POINTER;
381 /* not yet implemented */
382 *aOverlay = 0;
383 LogFlow(("FFmpeg::COMGETTER(Overlay): returning 0\n"));
384 return S_OK;
385}
386
387// IFramebuffer methods
388/////////////////////////////////////////////////////////////////////////////
389
390STDMETHODIMP FFmpegFB::Lock()
391{
392 LogFlow(("FFmpeg::Lock: called\n"));
393 int rc = RTCritSectEnter(&mCritSect);
394 AssertRC(rc);
395 if (rc == VINF_SUCCESS)
396 return S_OK;
397 return E_UNEXPECTED;
398}
399
400STDMETHODIMP FFmpegFB::Unlock()
401{
402 LogFlow(("FFmpeg::Unlock: called\n"));
403 RTCritSectLeave(&mCritSect);
404 return S_OK;
405}
406
407
408/**
409 * This method is used to notify us that an area of the guest framebuffer
410 * has been updated.
411 *
412 * @returns COM status code
413 * @param x X co-ordinate of the upper left-hand corner of the
414 * area which has been updated
415 * @param y Y co-ordinate of the upper left-hand corner of the
416 * area which has been updated
417 * @param w width of the area which has been updated
418 * @param h height of the area which has been updated
419 * @param finished
420 */
421STDMETHODIMP FFmpegFB::NotifyUpdate(ULONG x, ULONG y, ULONG w, ULONG h,
422 BOOL *finished)
423{
424 int rc;
425 int64_t iCurrentTime = RTTimeMilliTS();
426
427 LogFlow(("FFmpeg::NotifyUpdate called: x=%lu, y=%lu, w=%lu, h=%lu\n",
428 (unsigned long) x, (unsigned long) y, (unsigned long) w,
429 (unsigned long) h));
430 if (!finished)
431 return E_POINTER;
432 /* For now we will do things synchronously */
433 *finished = true;
434 /* We always leave at least one frame update pending, which we
435 process when the time until the next frame has elapsed. */
436 if (iCurrentTime - mLastTime >= 40)
437 {
438 rc = do_rgb_to_yuv_conversion();
439 if (rc != S_OK)
440 {
441 copy_to_intermediate_buffer(x, y, w, h);
442 return rc;
443 }
444 rc = do_encoding_and_write();
445 if (rc != S_OK)
446 {
447 copy_to_intermediate_buffer(x, y, w, h);
448 return rc;
449 }
450 mLastTime = mLastTime + 40;
451 /* Write frames for the time in-between. Not a good way
452 to handle this. */
453 while (iCurrentTime - mLastTime >= 40)
454 {
455/* rc = do_rgb_to_yuv_conversion();
456 if (rc != S_OK)
457 {
458 copy_to_intermediate_buffer(x, y, w, h);
459 return rc;
460 }
461*/ rc = do_encoding_and_write();
462 if (rc != S_OK)
463 {
464 copy_to_intermediate_buffer(x, y, w, h);
465 return rc;
466 }
467 mLastTime = mLastTime + 40;
468 }
469 }
470 /* Finally we copy the updated data to the intermediate buffer,
471 ready for the next update. */
472 copy_to_intermediate_buffer(x, y, w, h);
473 return S_OK;
474}
475
476
477/**
478 * Requests a resize of our "screen".
479 *
480 * @returns COM status code
481 * @param pixelFormat Layout of the guest video RAM (i.e. 16, 24,
482 * 32 bpp)
483 * @param vram host context pointer to the guest video RAM,
484 * in case we can cope with the format
485 * @param bitsPerPixel color depth of the guest video RAM
486 * @param bytesPerLine length of a screen line in the guest video RAM
487 * @param w video mode width in pixels
488 * @param h video mode height in pixels
489 * @retval finished set to true if the method is synchronous and
490 * to false otherwise
491 *
492 * This method is called when the guest attempts to resize the virtual
493 * screen. The pointer to the guest's video RAM is supplied in case
494 * the framebuffer can handle the pixel format. If it can't, it should
495 * allocate a memory buffer itself, and the virtual VGA device will copy
496 * the guest VRAM to that in a format we can handle. The
497 * COMGETTER(UsesGuestVRAM) method is used to tell the VGA device which method
498 * we have chosen, and the other COMGETTER methods tell the device about
499 * the layout of our buffer. We currently handle all VRAM layouts except
500 * FramebufferPixelFormat_Opaque (which cannot be handled by
501 * definition).
502 */
503STDMETHODIMP FFmpegFB::RequestResize(ULONG aScreenId, ULONG pixelFormat,
504 BYTE *vram, ULONG bitsPerPixel,
505 ULONG bytesPerLine,
506 ULONG w, ULONG h, BOOL *finished)
507{
508 NOREF(aScreenId);
509 if (!finished)
510 return E_POINTER;
511 LogFlow(("FFmpeg::RequestResize called: pixelFormat=%lu, vram=%lu, "
512 "bpp=%lu bpl=%lu, w=%lu, h=%lu\n",
513 (unsigned long) pixelFormat, (unsigned long) vram,
514 (unsigned long) bitsPerPixel, (unsigned long) bytesPerLine,
515 (unsigned long) w, (unsigned long) h));
516 /* For now, we are doing things synchronously */
517 *finished = true;
518
519 /* We always reallocate our buffer */
520 if (mRGBBuffer)
521 RTMemFree(mRGBBuffer);
522 mGuestWidth = w;
523 mGuestHeight = h;
524
525 bool fallback = false;
526
527 /* See if there are conditions under which we can use the guest's VRAM,
528 * fallback to our own memory buffer otherwise */
529
530 if (pixelFormat == FramebufferPixelFormat_FOURCC_RGB)
531 {
532 switch (bitsPerPixel)
533 {
534 case 32:
535 mFFMPEGPixelFormat = PIX_FMT_RGBA32;
536 Log2(("FFmpeg::RequestResize: setting ffmpeg pixel format to PIX_FMT_RGBA32\n"));
537 break;
538 case 24:
539 mFFMPEGPixelFormat = PIX_FMT_RGB24;
540 Log2(("FFmpeg::RequestResize: setting ffmpeg pixel format to PIX_FMT_RGB24\n"));
541 break;
542 case 16:
543 mFFMPEGPixelFormat = PIX_FMT_RGB565;
544 Log2(("FFmpeg::RequestResize: setting ffmpeg pixel format to PIX_FMT_RGB565\n"));
545 break;
546 default:
547 fallback = true;
548 break;
549 }
550 }
551 else
552 {
553 fallback = true;
554 }
555
556 if (!fallback)
557 {
558 mPixelFormat = FramebufferPixelFormat_FOURCC_RGB;
559 mBufferAddress = reinterpret_cast<uint8_t *>(vram);
560 mBytesPerLine = bytesPerLine;
561 mBitsPerPixel = bitsPerPixel;
562 mRGBBuffer = 0;
563 Log2(("FFmpeg::RequestResize: setting mBufferAddress to vram and mLineSize to %lu\n",
564 (unsigned long) mBytesPerLine));
565 }
566 else
567 {
568 /* we always fallback to 32bpp RGB */
569 mPixelFormat = FramebufferPixelFormat_FOURCC_RGB;
570 mFFMPEGPixelFormat = PIX_FMT_RGBA32;
571 Log2(("FFmpeg::RequestResize: setting ffmpeg pixel format to PIX_FMT_RGBA32\n"));
572
573 mBytesPerLine = w * 4;
574 mBitsPerPixel = 32;
575 mRGBBuffer = reinterpret_cast<uint8_t *>(RTMemAlloc(mBytesPerLine * h));
576 AssertReturn(mRGBBuffer != 0, E_OUTOFMEMORY);
577 Log2(("FFmpeg::RequestResize: alloc'ing mBufferAddress and mRGBBuffer to %p and mBytesPerLine to %lu\n",
578 mBufferAddress, (unsigned long) mBytesPerLine));
579 mBufferAddress = mRGBBuffer;
580 }
581
582 /* Blank out the intermediate frame framebuffer */
583 memset(mTempRGBBuffer, 0, mFrameWidth * mFrameHeight * 4);
584 return S_OK;
585}
586
587
588/**
589 * Queries whether we support a given accelerated opperation. Since we
590 * do not have any way of performing accelerated operations, we always
591 * return false in supported.
592 *
593 * @returns COM status code
594 * @param operation The operation being queried
595 * @retval supported Whether or not we support that operation
596 */
597STDMETHODIMP FFmpegFB::OperationSupported(FramebufferAccelerationOperation_T operation,
598 BOOL *supported)
599{
600 if (!supported)
601 return E_POINTER;
602 *supported = false;
603 return S_OK;
604}
605
606/**
607 * Returns whether we like the given video mode.
608 *
609 * @returns COM status code
610 * @param width video mode width in pixels
611 * @param height video mode height in pixels
612 * @param bpp video mode bit depth in bits per pixel
613 * @param supported pointer to result variable
614 *
615 * As far as I know, the only restruction we have on video modes is that
616 * we have to have an even number of horizontal and vertical pixels.
617 * I sincerely doubt that anything else will be requested, and if it
618 * is anyway, we will just silently amputate one line when we write to
619 * the mpeg file.
620 */
621STDMETHODIMP FFmpegFB::VideoModeSupported(ULONG width, ULONG height,
622 ULONG bpp, BOOL *supported)
623{
624 if (!supported)
625 return E_POINTER;
626 *supported = true;
627 return S_OK;
628}
629
630/**
631 * Since we currently do not have any way of doing this faster than
632 * the VGA device, we simply false in handled. Behaviour taken from
633 * src/VBox/RDP/server/framebuffer.cpp.
634 */
635STDMETHODIMP FFmpegFB::SolidFill(ULONG x, ULONG y, ULONG width,
636 ULONG height, ULONG color, BOOL *handled)
637{
638 LogFlow(("FFmpeg::SolidFill called.\n"));
639 if (!handled)
640 return E_POINTER;
641 *handled = false;
642 return S_OK;
643}
644
645/**
646 * Since we currently do not have any way of doing this faster than
647 * the VGA device, we simply false in handled. Behaviour taken from
648 * src/VBox/RDP/server/framebuffer.cpp.
649 */
650STDMETHODIMP FFmpegFB::CopyScreenBits(ULONG xDst, ULONG yDst, ULONG xSrc,
651 ULONG ySrc, ULONG width,
652 ULONG height, BOOL *handled)
653{
654 LogFlow(("FFmpeg::CopyScreenBits called.\n"));
655 if (!handled)
656 return E_POINTER;
657 *handled = false;
658 return S_OK;
659}
660
661/** Stubbed */
662STDMETHODIMP FFmpegFB::GetVisibleRegion(BYTE *rectangles, ULONG /* count */, ULONG * /* countCopied */)
663{
664 if (!rectangles)
665 return E_POINTER;
666 *rectangles = 0;
667 return S_OK;
668}
669
670/** Stubbed */
671STDMETHODIMP FFmpegFB::SetVisibleRegion(BYTE *rectangles, ULONG /* count */)
672{
673 if (!rectangles)
674 return E_POINTER;
675 return S_OK;
676}
677
678
679// Private Methods
680//////////////////////////////////////////////////////////////////////////
681//
682
683HRESULT FFmpegFB::setup_library()
684{
685 /* Set up the avcodec library */
686 avcodec_init();
687 /* Register all codecs in the library. */
688 avcodec_register_all();
689 /* Register all formats in the format library */
690 av_register_all();
691 mpFormatContext = av_alloc_format_context();
692 AssertReturn(mpFormatContext != 0, E_OUTOFMEMORY);
693 mpStream = av_new_stream(mpFormatContext, 0);
694 AssertReturn(mpStream != 0, E_UNEXPECTED);
695 strncpy(mpFormatContext->filename, com::Utf8Str(mFileName),
696 sizeof(mpFormatContext->filename));
697 return S_OK;
698}
699
700
701/**
702 * Determine the correct output format and codec for our MPEG file.
703 *
704 * @returns COM status code
705 *
706 * @pre The format context (mpFormatContext) should have already been
707 * allocated.
708 */
709HRESULT FFmpegFB::setup_output_format()
710{
711 Assert(mpFormatContext != 0);
712 AVOutputFormat *pOutFormat = guess_format(0, com::Utf8Str(mFileName),
713 0);
714#ifdef VBOX_SHOW_AVAILABLE_FORMATS
715 if (!pOutFormat)
716 {
717 RTPrintf("Could not guess an output format for that extension.\n"
718 "Available formats:\n");
719 list_formats();
720 }
721#endif
722 AssertMsgReturn(pOutFormat != 0,
723 ("Could not deduce output format from file name\n"),
724 E_INVALIDARG);
725 AssertMsgReturn((pOutFormat->flags & AVFMT_RAWPICTURE) == 0,
726 ("Can't handle output format for file\n"),
727 E_INVALIDARG);
728 AssertMsgReturn((pOutFormat->flags & AVFMT_NOFILE) == 0,
729 ("pOutFormat->flags=%x, pOutFormat->name=%s\n",
730 pOutFormat->flags, pOutFormat->name), E_UNEXPECTED);
731 AssertMsgReturn(pOutFormat->video_codec != CODEC_ID_NONE,
732 ("No video codec available - you have probably selected a non-video file format\n"), E_UNEXPECTED);
733 mpFormatContext->oformat = pOutFormat;
734 /* Set format specific parameters - requires the format to be set. */
735 int rcSetParam = av_set_parameters(mpFormatContext, 0);
736 AssertReturn(rcSetParam >= 0, E_UNEXPECTED);
737#if 1 /* bird: This works for me on the mac, please review & test elsewhere. */
738 /* Fill in any uninitialized parameters like opt_output_file in ffpmeg.c does.
739 This fixes most of the buffer underflow warnings:
740 http://lists.mplayerhq.hu/pipermail/ffmpeg-devel/2005-June/001699.html */
741 if (!mpFormatContext->preload)
742 mpFormatContext->preload = (int)(0.5 * AV_TIME_BASE);
743 if (!mpFormatContext->max_delay)
744 mpFormatContext->max_delay = (int)(0.7 * AV_TIME_BASE);
745#endif
746 return S_OK;
747}
748
749
750HRESULT FFmpegFB::list_formats()
751{
752 AVCodec *codec;
753 for (codec = first_avcodec; codec != NULL; codec = codec->next)
754 {
755 if (codec->type == CODEC_TYPE_VIDEO && codec->encode)
756 {
757 AVOutputFormat *ofmt;
758 for (ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next)
759 {
760 if (ofmt->video_codec == codec->id)
761 RTPrintf(" %20s: %20s => '%s'\n", codec->name, ofmt->extensions, ofmt->long_name);
762 }
763 }
764 }
765 return S_OK;
766}
767
768
769/**
770 * Open the FFmpeg codec and set it up (width, etc) for our MPEG file.
771 *
772 * @returns COM status code
773 *
774 * @pre The format context (mpFormatContext) and the stream (mpStream)
775 * should have already been allocated.
776 */
777HRESULT FFmpegFB::open_codec()
778{
779 Assert(mpFormatContext != 0);
780 Assert(mpStream != 0);
781 AVOutputFormat *pOutFormat = mpFormatContext->oformat;
782 AVCodecContext *pCodecContext = mpStream->codec;
783 AssertReturn(pCodecContext != 0, E_UNEXPECTED);
784 AVCodec *pCodec = avcodec_find_encoder(pOutFormat->video_codec);
785#ifdef VBOX_SHOW_AVAILABLE_FORMATS
786 if (!pCodec)
787 {
788 RTPrintf("Could not find a suitable codec for the output format on your system\n"
789 "Available formats:\n");
790 list_formats();
791 }
792#endif
793 AssertReturn(pCodec != 0, E_UNEXPECTED);
794 pCodecContext->codec_id = pOutFormat->video_codec;
795 pCodecContext->codec_type = CODEC_TYPE_VIDEO;
796 pCodecContext->bit_rate = mBitRate;
797 pCodecContext->width = mFrameWidth;
798 pCodecContext->height = mFrameHeight;
799 pCodecContext->time_base.den = 25;
800 pCodecContext->time_base.num = 1;
801 pCodecContext->gop_size = 12; /* at most one intra frame in 12 */
802 pCodecContext->max_b_frames = 1;
803 pCodecContext->pix_fmt = PIX_FMT_YUV420P;
804 /* taken from the ffmpeg output example */
805 // some formats want stream headers to be seperate
806 if (!strcmp(pOutFormat->name, "mp4")
807 || !strcmp(pOutFormat->name, "mov")
808 || !strcmp(pOutFormat->name, "3gp"))
809 pCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
810 /* end output example section */
811 int rcOpenCodec = avcodec_open(pCodecContext, pCodec);
812 AssertReturn(rcOpenCodec >= 0, E_UNEXPECTED);
813 return S_OK;
814}
815
816
817/**
818 * Open our MPEG file and write the header.
819 *
820 * @returns COM status code
821 *
822 * @pre The format context (mpFormatContext) and the stream (mpStream)
823 * should have already been allocated and set up.
824 */
825HRESULT FFmpegFB::open_output_file()
826{
827 char szFileName[RTPATH_MAX];
828 Assert(mpFormatContext);
829 Assert(mpFormatContext->oformat);
830 strcpy(szFileName, com::Utf8Str(mFileName));
831 int rcUrlFopen = url_fopen(&mpFormatContext->pb,
832 szFileName, URL_WRONLY);
833 AssertReturn(rcUrlFopen >= 0, E_UNEXPECTED);
834 mfUrlOpen = true;
835 av_write_header(mpFormatContext);
836 return S_OK;
837}
838
839
840/**
841 * Copy an area from the output buffer used by the virtual VGA (may
842 * just be the guest's VRAM) to our fixed size intermediate buffer.
843 * The picture in the intermediate buffer is centred if the guest
844 * screen dimensions are smaller and amputated if they are larger than
845 * our frame dimensions.
846 *
847 * @param x X co-ordinate of the upper left-hand corner of the
848 * area which has been updated
849 * @param y Y co-ordinate of the upper left-hand corner of the
850 * area which has been updated
851 * @param w width of the area which has been updated
852 * @param h height of the area which has been updated
853 */
854void FFmpegFB::copy_to_intermediate_buffer(ULONG x, ULONG y, ULONG w, ULONG h)
855{
856 Log2(("FFmpegFB::copy_to_intermediate_buffer: x=%lu, y=%lu, w=%lu, h=%lu\n",
857 (unsigned long) x, (unsigned long) y, (unsigned long) w, (unsigned long) h));
858 /* Perform clipping and calculate the destination co-ordinates */
859 ULONG destX, destY, bpp;
860 LONG xDiff = (LONG(mFrameWidth) - LONG(mGuestWidth)) / 2;
861 LONG yDiff = (LONG(mFrameHeight) - LONG(mGuestHeight)) / 2;
862 if (LONG(w) + xDiff + LONG(x) <= 0) /* nothing visible */
863 return;
864 if (LONG(x) < -xDiff)
865 {
866 w = LONG(w) + xDiff + x;
867 x = -xDiff;
868 destX = 0;
869 }
870 else
871 destX = x + xDiff;
872 if (LONG(h) + yDiff + LONG(y) <= 0) /* nothing visible */
873 return;
874 if (LONG(y) < -yDiff)
875 {
876 h = LONG(h) + yDiff + LONG(y);
877 y = -yDiff;
878 destY = 0;
879 }
880 else
881 destY = y + yDiff;
882 if (destX > mFrameWidth || destY > mFrameHeight)
883 return; /* nothing visible */
884 if (destX + w > mFrameWidth)
885 w = mFrameWidth - destX;
886 if (destY + h > mFrameHeight)
887 h = mFrameHeight - destY;
888 /* Calculate bytes per pixel */
889 if (mPixelFormat == FramebufferPixelFormat_FOURCC_RGB)
890 {
891 switch (mBitsPerPixel)
892 {
893 case 32:
894 case 24:
895 case 16:
896 bpp = mBitsPerPixel / 8;
897 break;
898 default:
899 AssertMsgFailed(("Unknown color depth! mBitsPerPixel=%d\n", mBitsPerPixel));
900 bpp = 1;
901 break;
902 }
903 }
904 else
905 {
906 AssertMsgFailed(("Unknown pixel format! mPixelFormat=%d\n", mPixelFormat));
907 bpp = 1;
908 }
909 /* Calculate start offset in source and destination buffers */
910 ULONG srcOffs = y * mBytesPerLine + x * bpp;
911 ULONG destOffs = (destY * mFrameWidth + destX) * bpp;
912 /* do the copy */
913 for (unsigned int i = 0; i < h; i++)
914 {
915 /* Overflow check */
916 Assert(srcOffs + w * bpp <= mGuestHeight * mBytesPerLine);
917 Assert(destOffs + w * bpp <= mFrameHeight * mFrameWidth * bpp);
918 memcpy(mTempRGBBuffer + destOffs, mBufferAddress + srcOffs,
919 w * bpp);
920 srcOffs = srcOffs + mBytesPerLine;
921 destOffs = destOffs + mFrameWidth * bpp;
922 }
923}
924
925
926/**
927 * Copy the RGB data in the intermediate framebuffer to YUV data in
928 * the YUV framebuffer.
929 *
930 * @returns COM status code
931 */
932HRESULT FFmpegFB::do_rgb_to_yuv_conversion()
933{
934 switch (mFFMPEGPixelFormat)
935 {
936 case PIX_FMT_RGBA32:
937 if (!FFmpegWriteYUV420p<FFmpegBGRA32Iter>(mFrameWidth, mFrameHeight,
938 mYUVBuffer, mTempRGBBuffer))
939 return E_UNEXPECTED;
940 break;
941 case PIX_FMT_RGB24:
942 if (!FFmpegWriteYUV420p<FFmpegBGR24Iter>(mFrameWidth, mFrameHeight,
943 mYUVBuffer, mTempRGBBuffer))
944 return E_UNEXPECTED;
945 break;
946 case PIX_FMT_RGB565:
947 if (!FFmpegWriteYUV420p<FFmpegBGR565Iter>(mFrameWidth, mFrameHeight,
948 mYUVBuffer, mTempRGBBuffer))
949 return E_UNEXPECTED;
950 break;
951 default:
952 return E_UNEXPECTED;
953 }
954 return S_OK;
955}
956
957
958/**
959 * Encode the YUV framebuffer as an MPEG frame and write it to the file.
960 *
961 * @returns COM status code
962 */
963HRESULT FFmpegFB::do_encoding_and_write()
964{
965 AVCodecContext *pContext = mpStream->codec;
966
967 /* A hack: ffmpeg mpeg2 only writes a frame if something has
968 changed. So we flip the low luminance bit of the first
969 pixel every frame. */
970 if (mToggle)
971 mYUVBuffer[0] |= 1;
972 else
973 mYUVBuffer[0] &= 0xfe;
974 mToggle = !mToggle;
975 int cSize = avcodec_encode_video(pContext, mOutBuf, mYUVFrameSize * 2,
976 mFrame);
977 AssertMsgReturn(cSize >= 0,
978 ("avcodec_encode_video() failed with rc=%d.\n"
979 "mFrameWidth=%u, mFrameHeight=%u\n", cSize,
980 mFrameWidth, mFrameHeight), E_UNEXPECTED);
981 if (cSize > 0)
982 {
983 AVPacket Packet;
984 av_init_packet(&Packet);
985 Packet.pts = av_rescale_q(pContext->coded_frame->pts,
986 pContext->time_base,
987 mpStream->time_base);
988 if(pContext->coded_frame->key_frame)
989 Packet.flags |= PKT_FLAG_KEY;
990 Packet.stream_index = mpStream->index;
991 Packet.data = mOutBuf;
992 Packet.size = cSize;
993
994 /* write the compressed frame in the media file */
995 int rcWriteFrame = av_write_frame(mpFormatContext, &Packet);
996 AssertReturn(rcWriteFrame == 0, E_UNEXPECTED);
997 }
998 return S_OK;
999}
1000
1001
1002/**
1003 * Capture the current (i.e. the last) frame as a PNG file with the
1004 * same basename as the captured video file.
1005 */
1006HRESULT FFmpegFB::write_png()
1007{
1008 HRESULT errorCode = E_OUTOFMEMORY;
1009 png_bytep *row_pointers;
1010 char PNGFileName[RTPATH_MAX], oldName[RTPATH_MAX];
1011 png_structp png_ptr;
1012 png_infop info_ptr;
1013 uint8_t *PNGBuffer;
1014 /* Work out the new file name - for some reason, we can't use
1015 the com::Utf8Str() directly, but have to copy it */
1016 strcpy(oldName, com::Utf8Str(mFileName));
1017 int baseLen = strrchr(oldName, '.') - oldName;
1018 if (baseLen == 0)
1019 baseLen = strlen(oldName);
1020 if (baseLen >= RTPATH_MAX - 5) /* for whatever reason */
1021 baseLen = RTPATH_MAX - 5;
1022 memcpy(&PNGFileName[0], oldName, baseLen);
1023 PNGFileName[baseLen] = '.';
1024 PNGFileName[baseLen + 1] = 'p';
1025 PNGFileName[baseLen + 2] = 'n';
1026 PNGFileName[baseLen + 3] = 'g';
1027 PNGFileName[baseLen + 4] = 0;
1028 /* Open output file */
1029 FILE *fp = fopen(PNGFileName, "wb");
1030 if (fp == 0)
1031 {
1032 errorCode = E_UNEXPECTED;
1033 goto fopen_failed;
1034 }
1035 /* Create libpng basic structures */
1036 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL,
1037 0 /* error function */, 0 /* warning function */);
1038 if (png_ptr == 0)
1039 goto png_create_write_struct_failed;
1040 info_ptr = png_create_info_struct(png_ptr);
1041 if (info_ptr == 0)
1042 {
1043 png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
1044 goto png_create_info_struct_failed;
1045 }
1046 /* Convert image to standard RGB24 to simplify life */
1047 PNGBuffer = reinterpret_cast<uint8_t *>(av_malloc(mFrameWidth
1048 * mFrameHeight * 4));
1049 if (PNGBuffer == 0)
1050 goto av_malloc_buffer_failed;
1051 row_pointers =
1052 reinterpret_cast<png_bytep *>(av_malloc(mFrameHeight
1053 * sizeof(png_bytep)));
1054 if (row_pointers == 0)
1055 goto av_malloc_pointers_failed;
1056 switch (mFFMPEGPixelFormat)
1057 {
1058 case PIX_FMT_RGBA32:
1059 if (!FFmpegWriteRGB24<FFmpegBGRA32Iter>(mFrameWidth, mFrameHeight,
1060 PNGBuffer, mTempRGBBuffer))
1061 goto setjmp_exception;
1062 break;
1063 case PIX_FMT_RGB24:
1064 if (!FFmpegWriteRGB24<FFmpegBGR24Iter>(mFrameWidth, mFrameHeight,
1065 PNGBuffer, mTempRGBBuffer))
1066 goto setjmp_exception;
1067 break;
1068 case PIX_FMT_RGB565:
1069 if (!FFmpegWriteRGB24<FFmpegBGR565Iter>(mFrameWidth, mFrameHeight,
1070 PNGBuffer, mTempRGBBuffer))
1071 goto setjmp_exception;
1072 break;
1073 default:
1074 goto setjmp_exception;
1075 }
1076 /* libpng exception handling */
1077 if (setjmp(png_jmpbuf(png_ptr)))
1078 goto setjmp_exception;
1079 /* pass libpng the file pointer */
1080 png_init_io(png_ptr, fp);
1081 /* set the image properties */
1082 png_set_IHDR(png_ptr, info_ptr, mFrameWidth, mFrameHeight,
1083 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1084 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1085 /* set up the information about the bitmap for libpng */
1086 row_pointers[0] = png_bytep(PNGBuffer);
1087 for (unsigned i = 1; i < mFrameHeight; i++)
1088 row_pointers[i] = row_pointers[i - 1] + mFrameWidth * 3;
1089 png_set_rows(png_ptr, info_ptr, &row_pointers[0]);
1090 /* and write the thing! */
1091 png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, 0);
1092 /* drop through to cleanup */
1093 errorCode = S_OK;
1094setjmp_exception:
1095 av_free(row_pointers);
1096av_malloc_pointers_failed:
1097 av_free(PNGBuffer);
1098av_malloc_buffer_failed:
1099 png_destroy_write_struct(&png_ptr, &info_ptr);
1100png_create_info_struct_failed:
1101png_create_write_struct_failed:
1102 fclose(fp);
1103fopen_failed:
1104 if (errorCode != S_OK)
1105 Log(("FFmpegFB::write_png: Failed to write .png image of final frame\n"));
1106 return errorCode;
1107}
1108
1109
1110#ifdef VBOX_WITH_XPCOM
1111NS_DECL_CLASSINFO(FFmpegFB)
1112NS_IMPL_THREADSAFE_ISUPPORTS1_CI(FFmpegFB, IFramebuffer)
1113#endif
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette