VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/VideoRec.cpp@ 52316

最後變更 在這個檔案從52316是 52312,由 vboxsync 提交於 11 年 前

6219: New parameters related to file size / recording time limitation for VM Video Capture have been added (vcpmaxtime, vcpmaxsize and vcpoptions - special codec options in key=value format). EbmlWriter has been refactored. Removed some redundant code.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
  • 屬性 svn:mergeinfo 設為 (切換已刪除的分支)
    /branches/VBox-3.0/src/VBox/Frontends/VBoxHeadless/VideoCapture/EncodeAndWrite.cpp58652,​70973
    /branches/VBox-3.2/src/VBox/Frontends/VBoxHeadless/VideoCapture/EncodeAndWrite.cpp66309,​66318
    /branches/VBox-4.0/src/VBox/Frontends/VBoxHeadless/VideoCapture/EncodeAndWrite.cpp70873
    /branches/VBox-4.1/src/VBox/Frontends/VBoxHeadless/VideoCapture/EncodeAndWrite.cpp74233
    /branches/VBox-4.2/src/VBox/Main/src-client/VideoRec.cpp91503-91504,​91506-91508,​91510,​91514-91515,​91521
    /branches/VBox-4.3/src/VBox/Main/src-client/VideoRec.cpp91223
    /branches/VBox-4.3/trunk/src/VBox/Main/src-client/VideoRec.cpp91223
    /branches/dsen/gui/src/VBox/Frontends/VBoxHeadless/VideoCapture/EncodeAndWrite.cpp79076-79078,​79089,​79109-79110,​79112-79113,​79127-79130,​79134,​79141,​79151,​79155,​79157-79159,​79193,​79197
    /branches/dsen/gui2/src/VBox/Frontends/VBoxHeadless/VideoCapture/EncodeAndWrite.cpp79224,​79228,​79233,​79235,​79258,​79262-79263,​79273,​79341,​79345,​79354,​79357,​79387-79388,​79559-79569,​79572-79573,​79578,​79581-79582,​79590-79591,​79598-79599,​79602-79603,​79605-79606,​79632,​79635,​79637,​79644
    /branches/dsen/gui3/src/VBox/Frontends/VBoxHeadless/VideoCapture/EncodeAndWrite.cpp79645-79692
檔案大小: 30.5 KB
 
1/* $Id: VideoRec.cpp 52312 2014-08-07 12:54:38Z vboxsync $ */
2/** @file
3 * Encodes the screen content in VPX format.
4 */
5
6/*
7 * Copyright (C) 2012-2013 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define LOG_GROUP LOG_GROUP_MAIN
19#include <VBox/log.h>
20#include <iprt/asm.h>
21#include <iprt/assert.h>
22#include <iprt/semaphore.h>
23#include <iprt/thread.h>
24
25#include <VBox/com/VirtualBox.h>
26#include <VBox/com/com.h>
27#include <VBox/com/string.h>
28
29#include "EbmlWriter.h"
30#include "VideoRec.h"
31
32#define VPX_CODEC_DISABLE_COMPAT 1
33#include <vpx/vp8cx.h>
34#include <vpx/vpx_image.h>
35
36/** Default VPX codec to use */
37#define DEFAULTCODEC (vpx_codec_vp8_cx())
38
39static int videoRecEncodeAndWrite(PVIDEORECSTREAM pStrm);
40static int videoRecRGBToYUV(PVIDEORECSTREAM pStrm);
41
42/* state to synchronized between threads */
43enum
44{
45 VIDREC_UNINITIALIZED = 0,
46 /* initialized, idle */
47 VIDREC_IDLE = 1,
48 /* currently in VideoRecCopyToIntBuf(), delay termination */
49 VIDREC_COPYING = 2,
50 /* signal that we are terminating */
51 VIDREC_TERMINATING = 3
52};
53
54/* Must be always accessible and therefore cannot be part of VIDEORECCONTEXT */
55static uint32_t g_enmState = VIDREC_UNINITIALIZED;
56
57
58typedef struct VIDEORECSTREAM
59{
60 /* container context */
61 WebMWriter Ebml;
62 /* VPX codec context */
63 vpx_codec_ctx_t VpxCodec;
64 /* VPX configuration */
65 vpx_codec_enc_cfg_t VpxConfig;
66 /* X resolution */
67 uint32_t uTargetWidth;
68 /* Y resolution */
69 uint32_t uTargetHeight;
70 /* X resolution of the last encoded picture */
71 uint32_t uLastSourceWidth;
72 /* Y resolution of the last encoded picture */
73 uint32_t uLastSourceHeight;
74 /* current frame number */
75 uint32_t cFrame;
76 /* RGB buffer containing the most recent frame of the framebuffer */
77 uint8_t *pu8RgbBuf;
78 /* YUV buffer the encode function fetches the frame from */
79 uint8_t *pu8YuvBuf;
80 /* VPX image context */
81 vpx_image_t VpxRawImage;
82 /* true if video recording is enabled */
83 bool fEnabled;
84 /* true if the RGB buffer is filled */
85 bool fRgbFilled;
86 /* pixel format of the current frame */
87 uint32_t u32PixelFormat;
88 /* minimal delay between two frames */
89 uint32_t uDelay;
90 /* time stamp of the last frame we encoded */
91 uint64_t u64LastTimeStamp;
92 /* time stamp of the current frame */
93 uint64_t u64TimeStamp;
94} VIDEORECSTREAM;
95
96typedef struct VIDEORECCONTEXT
97{
98 /* semaphore to signal the encoding worker thread */
99 RTSEMEVENT WaitEvent;
100 /* semaphore required during termination */
101 RTSEMEVENT TermEvent;
102 /* true if video recording is enabled */
103 bool fEnabled;
104 /* worker thread */
105 RTTHREAD Thread;
106 /* number of stream contexts */
107 uint32_t cScreens;
108 /* maximal time stamp */
109 uint64_t u64MaxTimeStamp;
110 /* maximal file size in MB */
111 uint32_t uMaxFileSize;
112 /* video recording stream contexts */
113 VIDEORECSTREAM Strm[1];
114} VIDEORECCONTEXT;
115
116
117/**
118 * Iterator class for running through a BGRA32 image buffer and converting
119 * it to RGB.
120 */
121class ColorConvBGRA32Iter
122{
123private:
124 enum { PIX_SIZE = 4 };
125public:
126 ColorConvBGRA32Iter(unsigned aWidth, unsigned aHeight, uint8_t *aBuf)
127 {
128 LogFlow(("width = %d height=%d aBuf=%lx\n", aWidth, aHeight, aBuf));
129 mPos = 0;
130 mSize = aWidth * aHeight * PIX_SIZE;
131 mBuf = aBuf;
132 }
133 /**
134 * Convert the next pixel to RGB.
135 * @returns true on success, false if we have reached the end of the buffer
136 * @param aRed where to store the red value
137 * @param aGreen where to store the green value
138 * @param aBlue where to store the blue value
139 */
140 bool getRGB(unsigned *aRed, unsigned *aGreen, unsigned *aBlue)
141 {
142 bool rc = false;
143 if (mPos + PIX_SIZE <= mSize)
144 {
145 *aRed = mBuf[mPos + 2];
146 *aGreen = mBuf[mPos + 1];
147 *aBlue = mBuf[mPos ];
148 mPos += PIX_SIZE;
149 rc = true;
150 }
151 return rc;
152 }
153
154 /**
155 * Skip forward by a certain number of pixels
156 * @param aPixels how many pixels to skip
157 */
158 void skip(unsigned aPixels)
159 {
160 mPos += PIX_SIZE * aPixels;
161 }
162private:
163 /** Size of the picture buffer */
164 unsigned mSize;
165 /** Current position in the picture buffer */
166 unsigned mPos;
167 /** Address of the picture buffer */
168 uint8_t *mBuf;
169};
170
171/**
172 * Iterator class for running through an BGR24 image buffer and converting
173 * it to RGB.
174 */
175class ColorConvBGR24Iter
176{
177private:
178 enum { PIX_SIZE = 3 };
179public:
180 ColorConvBGR24Iter(unsigned aWidth, unsigned aHeight, uint8_t *aBuf)
181 {
182 mPos = 0;
183 mSize = aWidth * aHeight * PIX_SIZE;
184 mBuf = aBuf;
185 }
186 /**
187 * Convert the next pixel to RGB.
188 * @returns true on success, false if we have reached the end of the buffer
189 * @param aRed where to store the red value
190 * @param aGreen where to store the green value
191 * @param aBlue where to store the blue value
192 */
193 bool getRGB(unsigned *aRed, unsigned *aGreen, unsigned *aBlue)
194 {
195 bool rc = false;
196 if (mPos + PIX_SIZE <= mSize)
197 {
198 *aRed = mBuf[mPos + 2];
199 *aGreen = mBuf[mPos + 1];
200 *aBlue = mBuf[mPos ];
201 mPos += PIX_SIZE;
202 rc = true;
203 }
204 return rc;
205 }
206
207 /**
208 * Skip forward by a certain number of pixels
209 * @param aPixels how many pixels to skip
210 */
211 void skip(unsigned aPixels)
212 {
213 mPos += PIX_SIZE * aPixels;
214 }
215private:
216 /** Size of the picture buffer */
217 unsigned mSize;
218 /** Current position in the picture buffer */
219 unsigned mPos;
220 /** Address of the picture buffer */
221 uint8_t *mBuf;
222};
223
224/**
225 * Iterator class for running through an BGR565 image buffer and converting
226 * it to RGB.
227 */
228class ColorConvBGR565Iter
229{
230private:
231 enum { PIX_SIZE = 2 };
232public:
233 ColorConvBGR565Iter(unsigned aWidth, unsigned aHeight, uint8_t *aBuf)
234 {
235 mPos = 0;
236 mSize = aWidth * aHeight * PIX_SIZE;
237 mBuf = aBuf;
238 }
239 /**
240 * Convert the next pixel to RGB.
241 * @returns true on success, false if we have reached the end of the buffer
242 * @param aRed where to store the red value
243 * @param aGreen where to store the green value
244 * @param aBlue where to store the blue value
245 */
246 bool getRGB(unsigned *aRed, unsigned *aGreen, unsigned *aBlue)
247 {
248 bool rc = false;
249 if (mPos + PIX_SIZE <= mSize)
250 {
251 unsigned uFull = (((unsigned) mBuf[mPos + 1]) << 8)
252 | ((unsigned) mBuf[mPos]);
253 *aRed = (uFull >> 8) & ~7;
254 *aGreen = (uFull >> 3) & ~3 & 0xff;
255 *aBlue = (uFull << 3) & ~7 & 0xff;
256 mPos += PIX_SIZE;
257 rc = true;
258 }
259 return rc;
260 }
261
262 /**
263 * Skip forward by a certain number of pixels
264 * @param aPixels how many pixels to skip
265 */
266 void skip(unsigned aPixels)
267 {
268 mPos += PIX_SIZE * aPixels;
269 }
270private:
271 /** Size of the picture buffer */
272 unsigned mSize;
273 /** Current position in the picture buffer */
274 unsigned mPos;
275 /** Address of the picture buffer */
276 uint8_t *mBuf;
277};
278
279/**
280 * Convert an image to YUV420p format
281 * @returns true on success, false on failure
282 * @param aWidth width of image
283 * @param aHeight height of image
284 * @param aDestBuf an allocated memory buffer large enough to hold the
285 * destination image (i.e. width * height * 12bits)
286 * @param aSrcBuf the source image as an array of bytes
287 */
288template <class T>
289inline bool colorConvWriteYUV420p(unsigned aWidth, unsigned aHeight,
290 uint8_t *aDestBuf, uint8_t *aSrcBuf)
291{
292 AssertReturn(0 == (aWidth & 1), false);
293 AssertReturn(0 == (aHeight & 1), false);
294 bool rc = true;
295 T iter1(aWidth, aHeight, aSrcBuf);
296 T iter2 = iter1;
297 iter2.skip(aWidth);
298 unsigned cPixels = aWidth * aHeight;
299 unsigned offY = 0;
300 unsigned offU = cPixels;
301 unsigned offV = cPixels + cPixels / 4;
302 for (unsigned i = 0; (i < aHeight / 2) && rc; ++i)
303 {
304 for (unsigned j = 0; (j < aWidth / 2) && rc; ++j)
305 {
306 unsigned red, green, blue, u, v;
307 rc = iter1.getRGB(&red, &green, &blue);
308 if (rc)
309 {
310 aDestBuf[offY] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16;
311 u = (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4;
312 v = (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4;
313 rc = iter1.getRGB(&red, &green, &blue);
314 }
315 if (rc)
316 {
317 aDestBuf[offY + 1] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16;
318 u += (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4;
319 v += (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4;
320 rc = iter2.getRGB(&red, &green, &blue);
321 }
322 if (rc)
323 {
324 aDestBuf[offY + aWidth] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16;
325 u += (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4;
326 v += (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4;
327 rc = iter2.getRGB(&red, &green, &blue);
328 }
329 if (rc)
330 {
331 aDestBuf[offY + aWidth + 1] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16;
332 u += (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4;
333 v += (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4;
334 aDestBuf[offU] = u;
335 aDestBuf[offV] = v;
336 offY += 2;
337 ++offU;
338 ++offV;
339 }
340 }
341 if (rc)
342 {
343 iter1.skip(aWidth);
344 iter2.skip(aWidth);
345 offY += aWidth;
346 }
347 }
348 return rc;
349}
350
351/**
352 * Convert an image to RGB24 format
353 * @returns true on success, false on failure
354 * @param aWidth width of image
355 * @param aHeight height of image
356 * @param aDestBuf an allocated memory buffer large enough to hold the
357 * destination image (i.e. width * height * 12bits)
358 * @param aSrcBuf the source image as an array of bytes
359 */
360template <class T>
361inline bool colorConvWriteRGB24(unsigned aWidth, unsigned aHeight,
362 uint8_t *aDestBuf, uint8_t *aSrcBuf)
363{
364 enum { PIX_SIZE = 3 };
365 bool rc = true;
366 AssertReturn(0 == (aWidth & 1), false);
367 AssertReturn(0 == (aHeight & 1), false);
368 T iter(aWidth, aHeight, aSrcBuf);
369 unsigned cPixels = aWidth * aHeight;
370 for (unsigned i = 0; i < cPixels && rc; ++i)
371 {
372 unsigned red, green, blue;
373 rc = iter.getRGB(&red, &green, &blue);
374 if (rc)
375 {
376 aDestBuf[i * PIX_SIZE ] = red;
377 aDestBuf[i * PIX_SIZE + 1] = green;
378 aDestBuf[i * PIX_SIZE + 2] = blue;
379 }
380 }
381 return rc;
382}
383
384/**
385 * Worker thread for all streams.
386 *
387 * RGB/YUV conversion and encoding.
388 */
389static DECLCALLBACK(int) videoRecThread(RTTHREAD Thread, void *pvUser)
390{
391 PVIDEORECCONTEXT pCtx = (PVIDEORECCONTEXT)pvUser;
392 for (;;)
393 {
394 int rc = RTSemEventWait(pCtx->WaitEvent, RT_INDEFINITE_WAIT);
395 AssertRCBreak(rc);
396
397 if (ASMAtomicReadU32(&g_enmState) == VIDREC_TERMINATING)
398 break;
399 for (unsigned uScreen = 0; uScreen < pCtx->cScreens; uScreen++)
400 {
401 PVIDEORECSTREAM pStrm = &pCtx->Strm[uScreen];
402 if ( pStrm->fEnabled
403 && ASMAtomicReadBool(&pStrm->fRgbFilled))
404 {
405 rc = videoRecRGBToYUV(pStrm);
406 ASMAtomicWriteBool(&pStrm->fRgbFilled, false);
407 if (RT_SUCCESS(rc))
408 rc = videoRecEncodeAndWrite(pStrm);
409 if (RT_FAILURE(rc))
410 {
411 static unsigned cErrors = 100;
412 if (cErrors > 0)
413 {
414 LogRel(("Error %Rrc encoding / writing video frame\n", rc));
415 cErrors--;
416 }
417 }
418 }
419 }
420 }
421
422 return VINF_SUCCESS;
423}
424
425/**
426 * VideoRec utility function to create video recording context.
427 *
428 * @returns IPRT status code.
429 * @param ppCtx Video recording context
430 * @param cScreens Number of screens.
431 */
432int VideoRecContextCreate(PVIDEORECCONTEXT *ppCtx, uint32_t cScreens)
433{
434 Assert(ASMAtomicReadU32(&g_enmState) == VIDREC_UNINITIALIZED);
435
436 PVIDEORECCONTEXT pCtx = (PVIDEORECCONTEXT)RTMemAllocZ(RT_OFFSETOF(VIDEORECCONTEXT, Strm[cScreens]));
437 *ppCtx = pCtx;
438 AssertPtrReturn(pCtx, VERR_NO_MEMORY);
439
440 pCtx->cScreens = cScreens;
441 for (unsigned uScreen = 0; uScreen < cScreens; uScreen++)
442 {
443 /* Since we allocate without using standard c++ new mechanism
444 * it is required to call placement new for correct initialization
445 * of some members */
446 new (&pCtx->Strm[uScreen] + RT_OFFSETOF(VIDEORECSTREAM, Ebml)) WebMWriter();
447 }
448
449 int rc = RTSemEventCreate(&pCtx->WaitEvent);
450 AssertRCReturn(rc, rc);
451
452 rc = RTSemEventCreate(&pCtx->TermEvent);
453 AssertRCReturn(rc, rc);
454
455 rc = RTThreadCreate(&pCtx->Thread, videoRecThread, (void*)pCtx, 0,
456 RTTHREADTYPE_MAIN_WORKER, RTTHREADFLAGS_WAITABLE, "VideoRec");
457 AssertRCReturn(rc, rc);
458
459 ASMAtomicWriteU32(&g_enmState, VIDREC_IDLE);
460 return VINF_SUCCESS;
461}
462
463/**
464 * VideoRec utility function to initialize video recording context.
465 *
466 * @returns IPRT status code.
467 * @param pCtx Pointer to video recording context to initialize Framebuffer width.
468 * @param uScreeen Screen number.
469 * @param strFile File to save the recorded data
470 * @param uTargetWidth Width of the target image in the video recoriding file (movie)
471 * @param uTargetHeight Height of the target image in video recording file.
472 */
473int VideoRecStrmInit(PVIDEORECCONTEXT pCtx, uint32_t uScreen, const char *pszFile,
474 uint32_t uWidth, uint32_t uHeight, uint32_t uRate, uint32_t uFps,
475 uint32_t uMaxTime, uint32_t uMaxFileSize, const char *pszOptions)
476{
477 AssertPtrReturn(pCtx, VERR_INVALID_PARAMETER);
478 AssertReturn(uScreen < pCtx->cScreens, VERR_INVALID_PARAMETER);
479
480 pCtx->u64MaxTimeStamp = (uMaxTime > 0 ? RTTimeProgramMilliTS() + uMaxTime * 1000 : 0);
481 pCtx->uMaxFileSize = uMaxFileSize;
482
483 PVIDEORECSTREAM pStrm = &pCtx->Strm[uScreen];
484 pStrm->uTargetWidth = uWidth;
485 pStrm->uTargetHeight = uHeight;
486 pStrm->pu8RgbBuf = (uint8_t *)RTMemAllocZ(uWidth * uHeight * 4);
487 AssertReturn(pStrm->pu8RgbBuf, VERR_NO_MEMORY);
488
489 /* Play safe: the file must not exist, overwriting is potentially
490 * hazardous as nothing prevents the user from picking a file name of some
491 * other important file, causing unintentional data loss. */
492
493 int rc = pStrm->Ebml.create(pszFile);
494 if (RT_FAILURE(rc))
495 {
496 LogRel(("Failed to create the video capture output file \"%s\" (%Rrc)\n", pszFile, rc));
497 return rc;
498 }
499
500 vpx_codec_err_t rcv = vpx_codec_enc_config_default(DEFAULTCODEC, &pStrm->VpxConfig, 0);
501 if (rcv != VPX_CODEC_OK)
502 {
503 LogFlow(("Failed to configure codec\n", vpx_codec_err_to_string(rcv)));
504 return VERR_INVALID_PARAMETER;
505 }
506
507 com::Utf8Str options(pszOptions);
508 size_t pos = 0;
509
510 do {
511
512 com::Utf8Str key, value;
513 pos = options.parseKeyValue(key, value, pos);
514
515 if(key == "kf_mode")
516 {
517 if(value == "auto")
518 pStrm->VpxConfig.kf_mode = VPX_KF_AUTO;
519 else if (value == "fixed")
520 pStrm->VpxConfig.kf_mode = VPX_KF_FIXED;
521 else if (value == "disabled")
522 pStrm->VpxConfig.kf_mode = VPX_KF_DISABLED;
523 else LogRel(("Unknown value %s for parameter keyframe", value.c_str()));
524 continue;
525 }
526 else if(key == "kf_min_dist")
527 {
528 pStrm->VpxConfig.kf_min_dist = value.toUInt32();
529 }
530 else if(key == "kf_max_dist")
531 {
532 pStrm->VpxConfig.kf_max_dist = value.toUInt32();
533 }
534 else if(key == "rc_buf_optimal_sz")
535 {
536 pStrm->VpxConfig.rc_buf_optimal_sz = value.toUInt32();
537 }
538 else if(key == "rc_dropframe_thresh")
539 {
540 pStrm->VpxConfig.rc_dropframe_thresh = value.toUInt32();
541 }
542 else LogRel(("Getting unknown option: %s=%s\n", key.c_str(), value.c_str()));
543
544 } while(pos != com::Utf8Str::npos);
545
546 /* target bitrate in kilobits per second */
547 pStrm->VpxConfig.rc_target_bitrate = uRate;
548 /* frame width */
549 pStrm->VpxConfig.g_w = uWidth;
550 /* frame height */
551 pStrm->VpxConfig.g_h = uHeight;
552 /* 1ms per frame */
553 pStrm->VpxConfig.g_timebase.num = 1;
554 pStrm->VpxConfig.g_timebase.den = 1000;
555 /* disable multithreading */
556 pStrm->VpxConfig.g_threads = 0;
557
558 pStrm->uDelay = 1000 / uFps;
559
560 struct vpx_rational arg_framerate = { 30, 1 };
561 rc = pStrm->Ebml.writeHeader(&pStrm->VpxConfig, &arg_framerate);
562 AssertRCReturn(rc, rc);
563
564 /* Initialize codec */
565 rcv = vpx_codec_enc_init(&pStrm->VpxCodec, DEFAULTCODEC, &pStrm->VpxConfig, 0);
566 if (rcv != VPX_CODEC_OK)
567 {
568 LogFlow(("Failed to initialize VP8 encoder %s", vpx_codec_err_to_string(rcv)));
569 return VERR_INVALID_PARAMETER;
570 }
571
572 if (!vpx_img_alloc(&pStrm->VpxRawImage, VPX_IMG_FMT_I420, uWidth, uHeight, 1))
573 {
574 LogFlow(("Failed to allocate image %dx%d", uWidth, uHeight));
575 return VERR_NO_MEMORY;
576 }
577 pStrm->pu8YuvBuf = pStrm->VpxRawImage.planes[0];
578
579 pCtx->fEnabled = true;
580 pStrm->fEnabled = true;
581 return VINF_SUCCESS;
582}
583
584/**
585 * VideoRec utility function to close the video recording context.
586 *
587 * @param pCtx Pointer to video recording context.
588 */
589void VideoRecContextClose(PVIDEORECCONTEXT pCtx)
590{
591 if (!pCtx)
592 return;
593
594 uint32_t enmState = VIDREC_IDLE;
595 for (;;)
596 {
597 if (ASMAtomicCmpXchgExU32(&g_enmState, VIDREC_TERMINATING, enmState, &enmState))
598 break;
599 if (enmState == VIDREC_UNINITIALIZED)
600 return;
601 }
602 if (enmState == VIDREC_COPYING)
603 {
604 int rc = RTSemEventWait(pCtx->TermEvent, RT_INDEFINITE_WAIT);
605 AssertRC(rc);
606 }
607
608 RTSemEventSignal(pCtx->WaitEvent);
609 RTThreadWait(pCtx->Thread, 10000, NULL);
610 RTSemEventDestroy(pCtx->WaitEvent);
611 RTSemEventDestroy(pCtx->TermEvent);
612
613 for (unsigned uScreen = 0; uScreen < pCtx->cScreens; uScreen++)
614 {
615 PVIDEORECSTREAM pStrm = &pCtx->Strm[uScreen];
616 if (pStrm->fEnabled)
617 {
618 int rc = pStrm->Ebml.writeFooter(0);
619 AssertRC(rc);
620 pStrm->Ebml.close();
621 vpx_img_free(&pStrm->VpxRawImage);
622 vpx_codec_err_t rcv = vpx_codec_destroy(&pStrm->VpxCodec);
623 Assert(rcv == VPX_CODEC_OK);
624 RTMemFree(pStrm->pu8RgbBuf);
625 pStrm->pu8RgbBuf = NULL;
626 }
627 /* explicit deinitilization of Ebml object since it was create using placement new */
628 pStrm->Ebml.~WebMWriter();
629 }
630
631 RTMemFree(pCtx);
632
633 ASMAtomicWriteU32(&g_enmState, VIDREC_UNINITIALIZED);
634}
635
636/**
637 * VideoRec utility function to check if recording is enabled.
638 *
639 * @returns true if recording is enabled
640 * @param pCtx Pointer to video recording context.
641 */
642bool VideoRecIsEnabled(PVIDEORECCONTEXT pCtx)
643{
644 uint32_t enmState = ASMAtomicReadU32(&g_enmState);
645 return ( enmState == VIDREC_IDLE
646 || enmState == VIDREC_COPYING);
647}
648
649/**
650 * VideoRec utility function to check if recording engine is ready to accept a new frame
651 * for the given screen.
652 *
653 * @returns true if recording engine is ready
654 * @param pCtx Pointer to video recording context.
655 * @param uScreen screen id.
656 * @param u64TimeStamp current time stamp
657 */
658bool VideoRecIsReady(PVIDEORECCONTEXT pCtx, uint32_t uScreen, uint64_t u64TimeStamp)
659{
660 uint32_t enmState = ASMAtomicReadU32(&g_enmState);
661 if (enmState != VIDREC_IDLE)
662 return false;
663
664 PVIDEORECSTREAM pStrm = &pCtx->Strm[uScreen];
665 if (!pStrm->fEnabled)
666 return false;
667
668 if (u64TimeStamp < pStrm->u64LastTimeStamp + pStrm->uDelay)
669 return false;
670
671 if (ASMAtomicReadBool(&pStrm->fRgbFilled))
672 return false;
673
674 return true;
675}
676
677/**
678 * VideoRec utility function to check if the file size has reached
679 * specified limits (if any).
680 *
681 * @returns true if any limit has been reached
682 * @param pCtx Pointer to video recording context
683 * @param uScreen screen id
684 * @param u64TimeStamp current time stamp
685 */
686
687bool VideoRecIsFull(PVIDEORECCONTEXT pCtx, uint32_t uScreen, uint64_t u64TimeStamp)
688{
689 PVIDEORECSTREAM pStrm = &pCtx->Strm[uScreen];
690 if(!pStrm->fEnabled)
691 return false;
692
693 if(pCtx->u64MaxTimeStamp > 0 && u64TimeStamp >= pCtx->u64MaxTimeStamp)
694 return true;
695
696 if (pCtx->uMaxFileSize > 0)
697 {
698 uint64_t sizeInMB = pStrm->Ebml.getFileSize() / (1024 * 1024);
699 if(sizeInMB >= pCtx->uMaxFileSize)
700 return true;
701 }
702
703 return false;
704}
705
706/**
707 * VideoRec utility function to encode the source image and write the encoded
708 * image to target file.
709 *
710 * @returns IPRT status code.
711 * @param pCtx Pointer to video recording context.
712 * @param uSourceWidth Width of the source image.
713 * @param uSourceHeight Height of the source image.
714 */
715static int videoRecEncodeAndWrite(PVIDEORECSTREAM pStrm)
716{
717 /* presentation time stamp */
718 vpx_codec_pts_t pts = pStrm->u64TimeStamp;
719 vpx_codec_err_t rcv = vpx_codec_encode(&pStrm->VpxCodec,
720 &pStrm->VpxRawImage,
721 pts /* time stamp */,
722 10 /* how long to show this frame */,
723 0 /* flags */,
724 VPX_DL_REALTIME /* deadline */);
725 if (rcv != VPX_CODEC_OK)
726 {
727 LogFlow(("Failed to encode:%s\n", vpx_codec_err_to_string(rcv)));
728 return VERR_GENERAL_FAILURE;
729 }
730
731 vpx_codec_iter_t iter = NULL;
732 int rc = VERR_NO_DATA;
733 for (;;)
734 {
735 const vpx_codec_cx_pkt_t *pkt = vpx_codec_get_cx_data(&pStrm->VpxCodec, &iter);
736 if (!pkt)
737 break;
738 switch (pkt->kind)
739 {
740 case VPX_CODEC_CX_FRAME_PKT:
741 rc = pStrm->Ebml.writeBlock(&pStrm->VpxConfig, pkt);
742 break;
743 default:
744 LogFlow(("Unexpected CODEC Packet.\n"));
745 break;
746 }
747 }
748
749 pStrm->cFrame++;
750 return rc;
751}
752
753/**
754 * VideoRec utility function to convert RGB to YUV.
755 *
756 * @returns IPRT status code.
757 * @param pCtx Pointer to video recording context.
758 */
759static int videoRecRGBToYUV(PVIDEORECSTREAM pStrm)
760{
761 switch (pStrm->u32PixelFormat)
762 {
763 case VPX_IMG_FMT_RGB32:
764 LogFlow(("32 bit\n"));
765 if (!colorConvWriteYUV420p<ColorConvBGRA32Iter>(pStrm->uTargetWidth,
766 pStrm->uTargetHeight,
767 pStrm->pu8YuvBuf,
768 pStrm->pu8RgbBuf))
769 return VERR_GENERAL_FAILURE;
770 break;
771 case VPX_IMG_FMT_RGB24:
772 LogFlow(("24 bit\n"));
773 if (!colorConvWriteYUV420p<ColorConvBGR24Iter>(pStrm->uTargetWidth,
774 pStrm->uTargetHeight,
775 pStrm->pu8YuvBuf,
776 pStrm->pu8RgbBuf))
777 return VERR_GENERAL_FAILURE;
778 break;
779 case VPX_IMG_FMT_RGB565:
780 LogFlow(("565 bit\n"));
781 if (!colorConvWriteYUV420p<ColorConvBGR565Iter>(pStrm->uTargetWidth,
782 pStrm->uTargetHeight,
783 pStrm->pu8YuvBuf,
784 pStrm->pu8RgbBuf))
785 return VERR_GENERAL_FAILURE;
786 break;
787 default:
788 return VERR_GENERAL_FAILURE;
789 }
790 return VINF_SUCCESS;
791}
792
793/**
794 * VideoRec utility function to copy a source image (FrameBuf) to the intermediate
795 * RGB buffer. This function is executed only once per time.
796 *
797 * @thread EMT
798 *
799 * @returns IPRT status code.
800 * @param pCtx Pointer to the video recording context.
801 * @param uScreen Screen number.
802 * @param x Starting x coordinate of the source buffer (Framebuffer).
803 * @param y Starting y coordinate of the source buffer (Framebuffer).
804 * @param uPixelFormat Pixel Format.
805 * @param uBitsPerPixel Bits Per Pixel
806 * @param uBytesPerLine Bytes per source scanlineName.
807 * @param uSourceWidth Width of the source image (framebuffer).
808 * @param uSourceHeight Height of the source image (framebuffer).
809 * @param pu8BufAddr Pointer to source image(framebuffer).
810 * @param u64TimeStamp Time stamp (milliseconds).
811 */
812int VideoRecCopyToIntBuf(PVIDEORECCONTEXT pCtx, uint32_t uScreen, uint32_t x, uint32_t y,
813 uint32_t uPixelFormat, uint32_t uBitsPerPixel, uint32_t uBytesPerLine,
814 uint32_t uSourceWidth, uint32_t uSourceHeight, uint8_t *pu8BufAddr,
815 uint64_t u64TimeStamp)
816{
817 /* Do not execute during termination and guard against termination */
818 if (!ASMAtomicCmpXchgU32(&g_enmState, VIDREC_COPYING, VIDREC_IDLE))
819 return VINF_TRY_AGAIN;
820
821 int rc = VINF_SUCCESS;
822 do
823 {
824 AssertPtrBreakStmt(pu8BufAddr, rc = VERR_INVALID_PARAMETER);
825 AssertBreakStmt(uSourceWidth, rc = VERR_INVALID_PARAMETER);
826 AssertBreakStmt(uSourceHeight, rc = VERR_INVALID_PARAMETER);
827 AssertBreakStmt(uScreen < pCtx->cScreens, rc = VERR_INVALID_PARAMETER);
828
829 PVIDEORECSTREAM pStrm = &pCtx->Strm[uScreen];
830 if (!pStrm->fEnabled)
831 {
832 rc = VINF_TRY_AGAIN; /* not (yet) enabled */
833 break;
834 }
835 if (u64TimeStamp < pStrm->u64LastTimeStamp + pStrm->uDelay)
836 {
837 rc = VINF_TRY_AGAIN; /* respect maximum frames per second */
838 break;
839 }
840 if (ASMAtomicReadBool(&pStrm->fRgbFilled))
841 {
842 rc = VERR_TRY_AGAIN; /* previous frame not yet encoded */
843 break;
844 }
845
846 pStrm->u64LastTimeStamp = u64TimeStamp;
847
848 int xDiff = ((int)pStrm->uTargetWidth - (int)uSourceWidth) / 2;
849 uint32_t w = uSourceWidth;
850 if ((int)w + xDiff + (int)x <= 0) /* nothing visible */
851 {
852 rc = VERR_INVALID_PARAMETER;
853 break;
854 }
855
856 uint32_t destX;
857 if ((int)x < -xDiff)
858 {
859 w += xDiff + x;
860 x = -xDiff;
861 destX = 0;
862 }
863 else
864 destX = x + xDiff;
865
866 uint32_t h = uSourceHeight;
867 int yDiff = ((int)pStrm->uTargetHeight - (int)uSourceHeight) / 2;
868 if ((int)h + yDiff + (int)y <= 0) /* nothing visible */
869 {
870 rc = VERR_INVALID_PARAMETER;
871 break;
872 }
873
874 uint32_t destY;
875 if ((int)y < -yDiff)
876 {
877 h += yDiff + (int)y;
878 y = -yDiff;
879 destY = 0;
880 }
881 else
882 destY = y + yDiff;
883
884 if ( destX > pStrm->uTargetWidth
885 || destY > pStrm->uTargetHeight)
886 {
887 rc = VERR_INVALID_PARAMETER; /* nothing visible */
888 break;
889 }
890
891 if (destX + w > pStrm->uTargetWidth)
892 w = pStrm->uTargetWidth - destX;
893
894 if (destY + h > pStrm->uTargetHeight)
895 h = pStrm->uTargetHeight - destY;
896
897 /* Calculate bytes per pixel */
898 uint32_t bpp = 1;
899 if (uPixelFormat == BitmapFormat_BGR)
900 {
901 switch (uBitsPerPixel)
902 {
903 case 32:
904 pStrm->u32PixelFormat = VPX_IMG_FMT_RGB32;
905 bpp = 4;
906 break;
907 case 24:
908 pStrm->u32PixelFormat = VPX_IMG_FMT_RGB24;
909 bpp = 3;
910 break;
911 case 16:
912 pStrm->u32PixelFormat = VPX_IMG_FMT_RGB565;
913 bpp = 2;
914 break;
915 default:
916 AssertMsgFailed(("Unknown color depth! mBitsPerPixel=%d\n", uBitsPerPixel));
917 break;
918 }
919 }
920 else
921 AssertMsgFailed(("Unknown pixel format! mPixelFormat=%d\n", uPixelFormat));
922
923 /* One of the dimensions of the current frame is smaller than before so
924 * clear the entire buffer to prevent artifacts from the previous frame */
925 if ( uSourceWidth < pStrm->uLastSourceWidth
926 || uSourceHeight < pStrm->uLastSourceHeight)
927 memset(pStrm->pu8RgbBuf, 0, pStrm->uTargetWidth * pStrm->uTargetHeight * 4);
928
929 pStrm->uLastSourceWidth = uSourceWidth;
930 pStrm->uLastSourceHeight = uSourceHeight;
931
932 /* Calculate start offset in source and destination buffers */
933 uint32_t offSrc = y * uBytesPerLine + x * bpp;
934 uint32_t offDst = (destY * pStrm->uTargetWidth + destX) * bpp;
935 /* do the copy */
936 for (unsigned int i = 0; i < h; i++)
937 {
938 /* Overflow check */
939 Assert(offSrc + w * bpp <= uSourceHeight * uBytesPerLine);
940 Assert(offDst + w * bpp <= pStrm->uTargetHeight * pStrm->uTargetWidth * bpp);
941 memcpy(pStrm->pu8RgbBuf + offDst, pu8BufAddr + offSrc, w * bpp);
942 offSrc += uBytesPerLine;
943 offDst += pStrm->uTargetWidth * bpp;
944 }
945
946 pStrm->u64TimeStamp = u64TimeStamp;
947
948 ASMAtomicWriteBool(&pStrm->fRgbFilled, true);
949 RTSemEventSignal(pCtx->WaitEvent);
950 } while (0);
951
952 if (!ASMAtomicCmpXchgU32(&g_enmState, VIDREC_IDLE, VIDREC_COPYING))
953 {
954 rc = RTSemEventSignal(pCtx->TermEvent);
955 AssertRC(rc);
956 }
957
958 return rc;
959}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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