VirtualBox

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

Last change on this file since 63169 was 63169, checked in by vboxsync, 8 years ago

colorConvWriteYUV420p: Hope asserting on getRGB failure is ok, make MSC happier wrt variable initialization state. (Also avoid two unnecessary test/jcc instructions in debug builds.)

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