VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/WebMWriter.cpp@ 74903

Last change on this file since 74903 was 74903, checked in by vboxsync, 6 years ago

Main/WebMWriter: Added some more checks for WebMWriter::AddAudioTrack().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 26.5 KB
Line 
1/* $Id: WebMWriter.cpp 74903 2018-10-18 07:59:50Z vboxsync $ */
2/** @file
3 * WebMWriter.cpp - WebM container handling.
4 */
5
6/*
7 * Copyright (C) 2013-2018 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/**
19 * For more information, see:
20 * - https://w3c.github.io/media-source/webm-byte-stream-format.html
21 * - https://www.webmproject.org/docs/container/#muxer-guidelines
22 */
23
24#define LOG_GROUP LOG_GROUP_MAIN_DISPLAY
25#include "LoggingNew.h"
26
27#include <list>
28#include <map>
29#include <queue>
30#include <stack>
31
32#include <math.h> /* For lround.h. */
33
34#include <iprt/asm.h>
35#include <iprt/buildconfig.h>
36#include <iprt/cdefs.h>
37#include <iprt/critsect.h>
38#include <iprt/err.h>
39#include <iprt/file.h>
40#include <iprt/rand.h>
41#include <iprt/string.h>
42
43#include <VBox/log.h>
44#include <VBox/version.h>
45
46#include "WebMWriter.h"
47#include "EBML_MKV.h"
48
49
50WebMWriter::WebMWriter(void)
51{
52 /* Size (in bytes) of time code to write. We use 2 bytes (16 bit) by default. */
53 m_cbTimecode = 2;
54 m_uTimecodeMax = UINT16_MAX;
55
56 m_fInTracksSection = false;
57}
58
59WebMWriter::~WebMWriter(void)
60{
61 Close();
62}
63
64/**
65 * Opens (creates) an output file using an already open file handle.
66 *
67 * @returns VBox status code.
68 * @param a_pszFilename Name of the file the file handle points at.
69 * @param a_phFile Pointer to open file handle to use.
70 * @param a_enmAudioCodec Audio codec to use.
71 * @param a_enmVideoCodec Video codec to use.
72 */
73int WebMWriter::OpenEx(const char *a_pszFilename, PRTFILE a_phFile,
74 WebMWriter::AudioCodec a_enmAudioCodec, WebMWriter::VideoCodec a_enmVideoCodec)
75{
76 try
77 {
78 m_enmAudioCodec = a_enmAudioCodec;
79 m_enmVideoCodec = a_enmVideoCodec;
80
81 LogFunc(("Creating '%s'\n", a_pszFilename));
82
83 int rc = createEx(a_pszFilename, a_phFile);
84 if (RT_SUCCESS(rc))
85 {
86 rc = init();
87 if (RT_SUCCESS(rc))
88 rc = writeHeader();
89 }
90 }
91 catch(int rc)
92 {
93 return rc;
94 }
95 return VINF_SUCCESS;
96}
97
98/**
99 * Opens an output file.
100 *
101 * @returns VBox status code.
102 * @param a_pszFilename Name of the file to create.
103 * @param a_fOpen File open mode of type RTFILE_O_.
104 * @param a_enmAudioCodec Audio codec to use.
105 * @param a_enmVideoCodec Video codec to use.
106 */
107int WebMWriter::Open(const char *a_pszFilename, uint64_t a_fOpen,
108 WebMWriter::AudioCodec a_enmAudioCodec, WebMWriter::VideoCodec a_enmVideoCodec)
109{
110 try
111 {
112 m_enmAudioCodec = a_enmAudioCodec;
113 m_enmVideoCodec = a_enmVideoCodec;
114
115 LogFunc(("Creating '%s'\n", a_pszFilename));
116
117 int rc = create(a_pszFilename, a_fOpen);
118 if (RT_SUCCESS(rc))
119 {
120 rc = init();
121 if (RT_SUCCESS(rc))
122 rc = writeHeader();
123 }
124 }
125 catch(int rc)
126 {
127 return rc;
128 }
129 return VINF_SUCCESS;
130}
131
132/**
133 * Closes the WebM file and drains all queues.
134 *
135 * @returns IPRT status code.
136 */
137int WebMWriter::Close(void)
138{
139 LogFlowFuncEnter();
140
141 if (!isOpen())
142 return VINF_SUCCESS;
143
144 /* Make sure to drain all queues. */
145 processQueues(&CurSeg.queueBlocks, true /* fForce */);
146
147 writeFooter();
148
149 WebMTracks::iterator itTrack = CurSeg.mapTracks.begin();
150 while (itTrack != CurSeg.mapTracks.end())
151 {
152 WebMTrack *pTrack = itTrack->second;
153 if (pTrack) /* Paranoia. */
154 delete pTrack;
155
156 CurSeg.mapTracks.erase(itTrack);
157
158 itTrack = CurSeg.mapTracks.begin();
159 }
160
161 Assert(CurSeg.queueBlocks.Map.size() == 0);
162 Assert(CurSeg.mapTracks.size() == 0);
163
164 close();
165
166 return VINF_SUCCESS;
167}
168
169/**
170 * Adds an audio track.
171 *
172 * @returns IPRT status code.
173 * @param uHz Input sampling rate.
174 * Must be supported by the selected audio codec.
175 * @param cChannels Number of input audio channels.
176 * @param cBits Number of input bits per channel.
177 * @param puTrack Track number on successful creation. Optional.
178 */
179int WebMWriter::AddAudioTrack(uint16_t uHz, uint8_t cChannels, uint8_t cBits, uint8_t *puTrack)
180{
181#ifdef VBOX_WITH_LIBOPUS
182 AssertReturn(uHz, VERR_INVALID_PARAMETER);
183 AssertReturn(cBits, VERR_INVALID_PARAMETER);
184 AssertReturn(cChannels, VERR_INVALID_PARAMETER);
185
186 /*
187 * Adjust the handed-in Hz rate to values which are supported by the Opus codec.
188 *
189 * Only the following values are supported by an Opus standard build
190 * -- every other rate only is supported by a custom build.
191 *
192 * See opus_encoder_create() for more information.
193 */
194 if (uHz > 24000) uHz = 48000;
195 else if (uHz > 16000) uHz = 24000;
196 else if (uHz > 12000) uHz = 16000;
197 else if (uHz > 8000 ) uHz = 12000;
198 else uHz = 8000;
199
200 /* Some players (e.g. Firefox with Nestegg) rely on track numbers starting at 1.
201 * Using a track number 0 will show those files as being corrupted. */
202 const uint8_t uTrack = (uint8_t)CurSeg.mapTracks.size() + 1;
203
204 subStart(MkvElem_TrackEntry);
205
206 serializeUnsignedInteger(MkvElem_TrackNumber, (uint8_t)uTrack);
207 serializeString (MkvElem_Language, "und" /* "Undefined"; see ISO-639-2. */);
208 serializeUnsignedInteger(MkvElem_FlagLacing, (uint8_t)0);
209
210 WebMTrack *pTrack = new WebMTrack(WebMTrackType_Audio, uTrack, RTFileTell(getFile()));
211
212 pTrack->Audio.uHz = uHz;
213 pTrack->Audio.msPerBlock = 20; /** Opus uses 20ms by default. Make this configurable? */
214 pTrack->Audio.framesPerBlock = uHz / (1000 /* s in ms */ / pTrack->Audio.msPerBlock);
215
216 WEBMOPUSPRIVDATA opusPrivData(uHz, cChannels);
217
218 LogFunc(("Opus @ %RU16Hz (%RU16ms + %RU16 frames per block)\n",
219 pTrack->Audio.uHz, pTrack->Audio.msPerBlock, pTrack->Audio.framesPerBlock));
220
221 serializeUnsignedInteger(MkvElem_TrackUID, pTrack->uUUID, 4)
222 .serializeUnsignedInteger(MkvElem_TrackType, 2 /* Audio */)
223 .serializeString(MkvElem_CodecID, "A_OPUS")
224 .serializeData(MkvElem_CodecPrivate, &opusPrivData, sizeof(opusPrivData))
225 .serializeUnsignedInteger(MkvElem_CodecDelay, 0)
226 .serializeUnsignedInteger(MkvElem_SeekPreRoll, 80 * 1000000) /* 80ms in ns. */
227 .subStart(MkvElem_Audio)
228 .serializeFloat(MkvElem_SamplingFrequency, (float)uHz)
229 .serializeUnsignedInteger(MkvElem_Channels, cChannels)
230 .serializeUnsignedInteger(MkvElem_BitDepth, cBits)
231 .subEnd(MkvElem_Audio)
232 .subEnd(MkvElem_TrackEntry);
233
234 CurSeg.mapTracks[uTrack] = pTrack;
235
236 if (puTrack)
237 *puTrack = uTrack;
238
239 return VINF_SUCCESS;
240#else
241 RT_NOREF(uHz, cChannels, cBits, puTrack);
242 return VERR_NOT_SUPPORTED;
243#endif
244}
245
246/**
247 * Adds a video track.
248 *
249 * @returns IPRT status code.
250 * @param uWidth Width (in pixels) of the video track.
251 * @param uHeight Height (in pixels) of the video track.
252 * @param uFPS FPS (Frames Per Second) of the video track.
253 * @param puTrack Track number of the added video track on success. Optional.
254 */
255int WebMWriter::AddVideoTrack(uint16_t uWidth, uint16_t uHeight, uint32_t uFPS, uint8_t *puTrack)
256{
257#ifdef VBOX_WITH_LIBVPX
258 /* Some players (e.g. Firefox with Nestegg) rely on track numbers starting at 1.
259 * Using a track number 0 will show those files as being corrupted. */
260 const uint8_t uTrack = (uint8_t)CurSeg.mapTracks.size() + 1;
261
262 subStart(MkvElem_TrackEntry);
263
264 serializeUnsignedInteger(MkvElem_TrackNumber, (uint8_t)uTrack);
265 serializeString (MkvElem_Language, "und" /* "Undefined"; see ISO-639-2. */);
266 serializeUnsignedInteger(MkvElem_FlagLacing, (uint8_t)0);
267
268 WebMTrack *pTrack = new WebMTrack(WebMTrackType_Video, uTrack, RTFileTell(getFile()));
269
270 /** @todo Resolve codec type. */
271 serializeUnsignedInteger(MkvElem_TrackUID, pTrack->uUUID /* UID */, 4)
272 .serializeUnsignedInteger(MkvElem_TrackType, 1 /* Video */)
273 .serializeString(MkvElem_CodecID, "V_VP8")
274 .subStart(MkvElem_Video)
275 .serializeUnsignedInteger(MkvElem_PixelWidth, uWidth)
276 .serializeUnsignedInteger(MkvElem_PixelHeight, uHeight)
277 /* Some players rely on the FPS rate for timing calculations.
278 * So make sure to *always* include that. */
279 .serializeFloat (MkvElem_FrameRate, (float)uFPS)
280 .subEnd(MkvElem_Video);
281
282 subEnd(MkvElem_TrackEntry);
283
284 CurSeg.mapTracks[uTrack] = pTrack;
285
286 if (puTrack)
287 *puTrack = uTrack;
288
289 return VINF_SUCCESS;
290#else
291 RT_NOREF(uWidth, uHeight, dbFPS, puTrack);
292 return VERR_NOT_SUPPORTED;
293#endif
294}
295
296/**
297 * Gets file name.
298 *
299 * @returns File name as UTF-8 string.
300 */
301const Utf8Str& WebMWriter::GetFileName(void)
302{
303 return getFileName();
304}
305
306/**
307 * Gets current output file size.
308 *
309 * @returns File size in bytes.
310 */
311uint64_t WebMWriter::GetFileSize(void)
312{
313 return getFileSize();
314}
315
316/**
317 * Gets current free storage space available for the file.
318 *
319 * @returns Available storage free space.
320 */
321uint64_t WebMWriter::GetAvailableSpace(void)
322{
323 return getAvailableSpace();
324}
325
326/**
327 * Takes care of the initialization of the instance.
328 *
329 * @returns IPRT status code.
330 */
331int WebMWriter::init(void)
332{
333 return CurSeg.init();
334}
335
336/**
337 * Takes care of the destruction of the instance.
338 */
339void WebMWriter::destroy(void)
340{
341 CurSeg.destroy();
342}
343
344/**
345 * Writes the WebM file header.
346 *
347 * @returns IPRT status code.
348 */
349int WebMWriter::writeHeader(void)
350{
351 LogFunc(("Header @ %RU64\n", RTFileTell(getFile())));
352
353 subStart(MkvElem_EBML)
354 .serializeUnsignedInteger(MkvElem_EBMLVersion, 1)
355 .serializeUnsignedInteger(MkvElem_EBMLReadVersion, 1)
356 .serializeUnsignedInteger(MkvElem_EBMLMaxIDLength, 4)
357 .serializeUnsignedInteger(MkvElem_EBMLMaxSizeLength, 8)
358 .serializeString(MkvElem_DocType, "webm")
359 .serializeUnsignedInteger(MkvElem_DocTypeVersion, 2)
360 .serializeUnsignedInteger(MkvElem_DocTypeReadVersion, 2)
361 .subEnd(MkvElem_EBML);
362
363 subStart(MkvElem_Segment);
364
365 /* Save offset of current segment. */
366 CurSeg.offStart = RTFileTell(getFile());
367
368 writeSeekHeader();
369
370 /* Save offset of upcoming tracks segment. */
371 CurSeg.offTracks = RTFileTell(getFile());
372
373 /* The tracks segment starts right after this header. */
374 subStart(MkvElem_Tracks);
375 m_fInTracksSection = true;
376
377 return VINF_SUCCESS;
378}
379
380/**
381 * Writes a simple block into the EBML structure.
382 *
383 * @returns IPRT status code.
384 * @param a_pTrack Track the simple block is assigned to.
385 * @param a_pBlock Simple block to write.
386 */
387int WebMWriter::writeSimpleBlockEBML(WebMTrack *a_pTrack, WebMSimpleBlock *a_pBlock)
388{
389#ifdef LOG_ENABLED
390 WebMCluster &Cluster = CurSeg.CurCluster;
391
392 Log3Func(("[T%RU8C%RU64] Off=%RU64, AbsPTSMs=%RU64, RelToClusterMs=%RU16, %zu bytes\n",
393 a_pTrack->uTrack, Cluster.uID, RTFileTell(getFile()),
394 a_pBlock->Data.tcAbsPTSMs, a_pBlock->Data.tcRelToClusterMs, a_pBlock->Data.cb));
395#endif
396 /*
397 * Write a "Simple Block".
398 */
399 writeClassId(MkvElem_SimpleBlock);
400 /* Block size. */
401 writeUnsignedInteger(0x10000000u | ( 1 /* Track number size. */
402 + m_cbTimecode /* Timecode size .*/
403 + 1 /* Flags size. */
404 + a_pBlock->Data.cb /* Actual frame data size. */), 4);
405 /* Track number. */
406 writeSize(a_pTrack->uTrack);
407 /* Timecode (relative to cluster opening timecode). */
408 writeUnsignedInteger(a_pBlock->Data.tcRelToClusterMs, m_cbTimecode);
409 /* Flags. */
410 writeUnsignedInteger(a_pBlock->Data.fFlags, 1);
411 /* Frame data. */
412 write(a_pBlock->Data.pv, a_pBlock->Data.cb);
413
414 return VINF_SUCCESS;
415}
416
417/**
418 * Writes a simple block and enqueues it into the segment's render queue.
419 *
420 * @returns IPRT status code.
421 * @param a_pTrack Track the simple block is assigned to.
422 * @param a_pBlock Simple block to write and enqueue.
423 */
424int WebMWriter::writeSimpleBlockQueued(WebMTrack *a_pTrack, WebMSimpleBlock *a_pBlock)
425{
426 RT_NOREF(a_pTrack);
427
428 int rc = VINF_SUCCESS;
429
430 try
431 {
432 const WebMTimecodeAbs tcAbsPTS = a_pBlock->Data.tcAbsPTSMs;
433
434 /* See if we already have an entry for the specified timecode in our queue. */
435 WebMBlockMap::iterator itQueue = CurSeg.queueBlocks.Map.find(tcAbsPTS);
436 if (itQueue != CurSeg.queueBlocks.Map.end()) /* Use existing queue. */
437 {
438 WebMTimecodeBlocks &Blocks = itQueue->second;
439 Blocks.Enqueue(a_pBlock);
440 }
441 else /* Create a new timecode entry. */
442 {
443 WebMTimecodeBlocks Blocks;
444 Blocks.Enqueue(a_pBlock);
445
446 CurSeg.queueBlocks.Map[tcAbsPTS] = Blocks;
447 }
448
449 processQueues(&CurSeg.queueBlocks, false /* fForce */);
450 }
451 catch(...)
452 {
453 delete a_pBlock;
454 a_pBlock = NULL;
455
456 rc = VERR_NO_MEMORY;
457 }
458
459 return rc;
460}
461
462#ifdef VBOX_WITH_LIBVPX
463/**
464 * Writes VPX (VP8 video) simple data block.
465 *
466 * @returns IPRT status code.
467 * @param a_pTrack Track ID to write data to.
468 * @param a_pCfg VPX encoder configuration to use.
469 * @param a_pPkt VPX packet video data packet to write.
470 */
471int WebMWriter::writeSimpleBlockVP8(WebMTrack *a_pTrack, const vpx_codec_enc_cfg_t *a_pCfg, const vpx_codec_cx_pkt_t *a_pPkt)
472{
473 RT_NOREF(a_pTrack);
474
475 /* Calculate the absolute PTS of this frame (in ms). */
476 WebMTimecodeAbs tcAbsPTSMs = a_pPkt->data.frame.pts * 1000
477 * (uint64_t) a_pCfg->g_timebase.num / a_pCfg->g_timebase.den;
478 if ( tcAbsPTSMs
479 && tcAbsPTSMs <= a_pTrack->tcAbsLastWrittenMs)
480 {
481 tcAbsPTSMs = a_pTrack->tcAbsLastWrittenMs + 1;
482 }
483
484 const bool fKeyframe = RT_BOOL(a_pPkt->data.frame.flags & VPX_FRAME_IS_KEY);
485
486 uint8_t fFlags = VBOX_WEBM_BLOCK_FLAG_NONE;
487 if (fKeyframe)
488 fFlags |= VBOX_WEBM_BLOCK_FLAG_KEY_FRAME;
489 if (a_pPkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
490 fFlags |= VBOX_WEBM_BLOCK_FLAG_INVISIBLE;
491
492 return writeSimpleBlockQueued(a_pTrack,
493 new WebMSimpleBlock(a_pTrack,
494 tcAbsPTSMs, a_pPkt->data.frame.buf, a_pPkt->data.frame.sz, fFlags));
495}
496#endif /* VBOX_WITH_LIBVPX */
497
498#ifdef VBOX_WITH_LIBOPUS
499/**
500 * Writes an Opus (audio) simple data block.
501 *
502 * @returns IPRT status code.
503 * @param a_pTrack Track ID to write data to.
504 * @param pvData Pointer to simple data block to write.
505 * @param cbData Size (in bytes) of simple data block to write.
506 * @param tcAbsPTSMs Absolute PTS of simple data block.
507 *
508 * @remarks Audio blocks that have same absolute timecode as video blocks SHOULD be written before the video blocks.
509 */
510int WebMWriter::writeSimpleBlockOpus(WebMTrack *a_pTrack, const void *pvData, size_t cbData, WebMTimecodeAbs tcAbsPTSMs)
511{
512 AssertPtrReturn(a_pTrack, VERR_INVALID_POINTER);
513 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
514 AssertReturn(cbData, VERR_INVALID_PARAMETER);
515
516 /* Every Opus frame is a key frame. */
517 const uint8_t fFlags = VBOX_WEBM_BLOCK_FLAG_KEY_FRAME;
518
519 return writeSimpleBlockQueued(a_pTrack,
520 new WebMSimpleBlock(a_pTrack, tcAbsPTSMs, pvData, cbData, fFlags));
521}
522#endif /* VBOX_WITH_LIBOPUS */
523
524/**
525 * Writes a data block to the specified track.
526 *
527 * @returns IPRT status code.
528 * @param uTrack Track ID to write data to.
529 * @param pvData Pointer to data block to write.
530 * @param cbData Size (in bytes) of data block to write.
531 */
532int WebMWriter::WriteBlock(uint8_t uTrack, const void *pvData, size_t cbData)
533{
534 RT_NOREF(cbData); /* Only needed for assertions for now. */
535
536 int rc = RTCritSectEnter(&CurSeg.CritSect);
537 AssertRC(rc);
538
539 WebMTracks::iterator itTrack = CurSeg.mapTracks.find(uTrack);
540 if (itTrack == CurSeg.mapTracks.end())
541 {
542 RTCritSectLeave(&CurSeg.CritSect);
543 return VERR_NOT_FOUND;
544 }
545
546 WebMTrack *pTrack = itTrack->second;
547 AssertPtr(pTrack);
548
549 if (m_fInTracksSection)
550 {
551 subEnd(MkvElem_Tracks);
552 m_fInTracksSection = false;
553 }
554
555 switch (pTrack->enmType)
556 {
557
558 case WebMTrackType_Audio:
559 {
560#ifdef VBOX_WITH_LIBOPUS
561 if (m_enmAudioCodec == WebMWriter::AudioCodec_Opus)
562 {
563 Assert(cbData == sizeof(WebMWriter::BlockData_Opus));
564 WebMWriter::BlockData_Opus *pData = (WebMWriter::BlockData_Opus *)pvData;
565 rc = writeSimpleBlockOpus(pTrack, pData->pvData, pData->cbData, pData->uPTSMs);
566 }
567 else
568#endif /* VBOX_WITH_LIBOPUS */
569 rc = VERR_NOT_SUPPORTED;
570 break;
571 }
572
573 case WebMTrackType_Video:
574 {
575#ifdef VBOX_WITH_LIBVPX
576 if (m_enmVideoCodec == WebMWriter::VideoCodec_VP8)
577 {
578 Assert(cbData == sizeof(WebMWriter::BlockData_VP8));
579 WebMWriter::BlockData_VP8 *pData = (WebMWriter::BlockData_VP8 *)pvData;
580 rc = writeSimpleBlockVP8(pTrack, pData->pCfg, pData->pPkt);
581 }
582 else
583#endif /* VBOX_WITH_LIBVPX */
584 rc = VERR_NOT_SUPPORTED;
585 break;
586 }
587
588 default:
589 rc = VERR_NOT_SUPPORTED;
590 break;
591 }
592
593 int rc2 = RTCritSectLeave(&CurSeg.CritSect);
594 AssertRC(rc2);
595
596 return rc;
597}
598
599/**
600 * Processes a render queue.
601 *
602 * @returns IPRT status code.
603 * @param pQueue Queue to process.
604 * @param fForce Whether forcing to process the render queue or not.
605 * Needed to drain the queues when terminating.
606 */
607int WebMWriter::processQueues(WebMQueue *pQueue, bool fForce)
608{
609 if (pQueue->tsLastProcessedMs == 0)
610 pQueue->tsLastProcessedMs = RTTimeMilliTS();
611
612 if (!fForce)
613 {
614 /* Only process when we reached a certain threshold. */
615 if (RTTimeMilliTS() - pQueue->tsLastProcessedMs < 5000 /* ms */ /** @todo Make this configurable */)
616 return VINF_SUCCESS;
617 }
618
619 WebMCluster &Cluster = CurSeg.CurCluster;
620
621 /* Iterate through the block map. */
622 WebMBlockMap::iterator it = pQueue->Map.begin();
623 while (it != CurSeg.queueBlocks.Map.end())
624 {
625 WebMTimecodeAbs mapAbsPTSMs = it->first;
626 WebMTimecodeBlocks mapBlocks = it->second;
627
628 /* Whether to start a new cluster or not. */
629 bool fClusterStart = false;
630
631 /* No blocks written yet? Start a new cluster. */
632 if (Cluster.cBlocks == 0)
633 fClusterStart = true;
634
635 /* Did we reach the maximum a cluster can hold? Use a new cluster then. */
636 if (mapAbsPTSMs - Cluster.tcAbsStartMs > VBOX_WEBM_CLUSTER_MAX_LEN_MS)
637 fClusterStart = true;
638
639 /* If the block map indicates that a cluster is needed for this timecode, create one. */
640 if (mapBlocks.fClusterNeeded)
641 fClusterStart = true;
642
643 if ( fClusterStart
644 && !mapBlocks.fClusterStarted)
645 {
646 if (Cluster.fOpen) /* Close current cluster first. */
647 {
648 /* Make sure that the current cluster contained some data. */
649 Assert(Cluster.offStart);
650 Assert(Cluster.cBlocks);
651
652 subEnd(MkvElem_Cluster);
653 Cluster.fOpen = false;
654 }
655
656 Cluster.fOpen = true;
657 Cluster.uID = CurSeg.cClusters;
658 Cluster.tcAbsStartMs = mapAbsPTSMs;
659 Cluster.offStart = RTFileTell(getFile());
660 Cluster.cBlocks = 0;
661
662 Log2Func(("[C%RU64] Start @ %RU64ms (map TC is %RU64) / %RU64 bytes\n",
663 Cluster.uID, Cluster.tcAbsStartMs, mapAbsPTSMs, Cluster.offStart));
664
665 if (CurSeg.cClusters)
666 AssertMsg(Cluster.tcAbsStartMs, ("[C%RU64] @ %RU64 starting timecode is 0 which is invalid\n",
667 Cluster.uID, Cluster.offStart));
668
669 WebMTracks::iterator itTrack = CurSeg.mapTracks.begin();
670 while (itTrack != CurSeg.mapTracks.end())
671 {
672 /* Insert cue points for all tracks if a new cluster has been started. */
673 WebMCuePoint cue(itTrack->second /* pTrack */, Cluster.offStart, Cluster.tcAbsStartMs);
674 CurSeg.lstCues.push_back(cue);
675
676 ++itTrack;
677 }
678
679 subStart(MkvElem_Cluster)
680 .serializeUnsignedInteger(MkvElem_Timecode, Cluster.tcAbsStartMs);
681
682 CurSeg.cClusters++;
683
684 mapBlocks.fClusterStarted = true;
685 }
686
687 /* Iterate through all blocks related to the current timecode. */
688 while (!mapBlocks.Queue.empty())
689 {
690 WebMSimpleBlock *pBlock = mapBlocks.Queue.front();
691 AssertPtr(pBlock);
692
693 WebMTrack *pTrack = pBlock->pTrack;
694 AssertPtr(pTrack);
695
696 /* Calculate the block's relative time code to the current cluster's starting time code. */
697 Assert(pBlock->Data.tcAbsPTSMs >= Cluster.tcAbsStartMs);
698 pBlock->Data.tcRelToClusterMs = pBlock->Data.tcAbsPTSMs - Cluster.tcAbsStartMs;
699
700 int rc2 = writeSimpleBlockEBML(pTrack, pBlock);
701 AssertRC(rc2);
702
703 Cluster.cBlocks++;
704
705 pTrack->cTotalBlocks++;
706 pTrack->tcAbsLastWrittenMs = pBlock->Data.tcAbsPTSMs;
707
708 if (CurSeg.tcAbsLastWrittenMs < pTrack->tcAbsLastWrittenMs)
709 CurSeg.tcAbsLastWrittenMs = pTrack->tcAbsLastWrittenMs;
710
711 /* Save a cue point if this is a keyframe (if no new cluster has been started,
712 * as this implies that a cue point already is present. */
713 if ( !fClusterStart
714 && (pBlock->Data.fFlags & VBOX_WEBM_BLOCK_FLAG_KEY_FRAME))
715 {
716 WebMCuePoint cue(pBlock->pTrack, Cluster.offStart, Cluster.tcAbsStartMs);
717 CurSeg.lstCues.push_back(cue);
718 }
719
720 delete pBlock;
721 pBlock = NULL;
722
723 mapBlocks.Queue.pop();
724 }
725
726 Assert(mapBlocks.Queue.empty());
727
728 CurSeg.queueBlocks.Map.erase(it);
729
730 it = CurSeg.queueBlocks.Map.begin();
731 }
732
733 Assert(CurSeg.queueBlocks.Map.empty());
734
735 pQueue->tsLastProcessedMs = RTTimeMilliTS();
736
737 return VINF_SUCCESS;
738}
739
740/**
741 * Writes the WebM footer.
742 *
743 * @returns IPRT status code.
744 */
745int WebMWriter::writeFooter(void)
746{
747 AssertReturn(isOpen(), VERR_WRONG_ORDER);
748
749 if (m_fInTracksSection)
750 {
751 subEnd(MkvElem_Tracks);
752 m_fInTracksSection = false;
753 }
754
755 if (CurSeg.CurCluster.fOpen)
756 {
757 subEnd(MkvElem_Cluster);
758 CurSeg.CurCluster.fOpen = false;
759 }
760
761 /*
762 * Write Cues element.
763 */
764 CurSeg.offCues = RTFileTell(getFile());
765 LogFunc(("Cues @ %RU64\n", CurSeg.offCues));
766
767 subStart(MkvElem_Cues);
768
769 std::list<WebMCuePoint>::iterator itCuePoint = CurSeg.lstCues.begin();
770 while (itCuePoint != CurSeg.lstCues.end())
771 {
772 /* Sanity. */
773 AssertPtr(itCuePoint->pTrack);
774
775 LogFunc(("CuePoint @ %RU64: Track #%RU8 (Cluster @ %RU64, tcAbs=%RU64)\n",
776 RTFileTell(getFile()), itCuePoint->pTrack->uTrack,
777 itCuePoint->offCluster, itCuePoint->tcAbs));
778
779 subStart(MkvElem_CuePoint)
780 .serializeUnsignedInteger(MkvElem_CueTime, itCuePoint->tcAbs)
781 .subStart(MkvElem_CueTrackPositions)
782 .serializeUnsignedInteger(MkvElem_CueTrack, itCuePoint->pTrack->uTrack)
783 .serializeUnsignedInteger(MkvElem_CueClusterPosition, itCuePoint->offCluster - CurSeg.offStart, 8)
784 .subEnd(MkvElem_CueTrackPositions)
785 .subEnd(MkvElem_CuePoint);
786
787 itCuePoint++;
788 }
789
790 subEnd(MkvElem_Cues);
791 subEnd(MkvElem_Segment);
792
793 /*
794 * Re-Update seek header with final information.
795 */
796
797 writeSeekHeader();
798
799 return RTFileSeek(getFile(), 0, RTFILE_SEEK_END, NULL);
800}
801
802/**
803 * Writes the segment's seek header.
804 */
805void WebMWriter::writeSeekHeader(void)
806{
807 if (CurSeg.offSeekInfo)
808 RTFileSeek(getFile(), CurSeg.offSeekInfo, RTFILE_SEEK_BEGIN, NULL);
809 else
810 CurSeg.offSeekInfo = RTFileTell(getFile());
811
812 LogFunc(("Seek Headeder @ %RU64\n", CurSeg.offSeekInfo));
813
814 subStart(MkvElem_SeekHead);
815
816 subStart(MkvElem_Seek)
817 .serializeUnsignedInteger(MkvElem_SeekID, MkvElem_Tracks)
818 .serializeUnsignedInteger(MkvElem_SeekPosition, CurSeg.offTracks - CurSeg.offStart, 8)
819 .subEnd(MkvElem_Seek);
820
821 if (CurSeg.offCues)
822 LogFunc(("Updating Cues @ %RU64\n", CurSeg.offCues));
823
824 subStart(MkvElem_Seek)
825 .serializeUnsignedInteger(MkvElem_SeekID, MkvElem_Cues)
826 .serializeUnsignedInteger(MkvElem_SeekPosition, CurSeg.offCues - CurSeg.offStart, 8)
827 .subEnd(MkvElem_Seek);
828
829 subStart(MkvElem_Seek)
830 .serializeUnsignedInteger(MkvElem_SeekID, MkvElem_Info)
831 .serializeUnsignedInteger(MkvElem_SeekPosition, CurSeg.offInfo - CurSeg.offStart, 8)
832 .subEnd(MkvElem_Seek);
833
834 subEnd(MkvElem_SeekHead);
835
836 /*
837 * Write the segment's info element.
838 */
839
840 /* Save offset of the segment's info element. */
841 CurSeg.offInfo = RTFileTell(getFile());
842
843 LogFunc(("Info @ %RU64\n", CurSeg.offInfo));
844
845 char szMux[64];
846 RTStrPrintf(szMux, sizeof(szMux),
847#ifdef VBOX_WITH_LIBVPX
848 "vpxenc%s", vpx_codec_version_str());
849#else
850 "unknown");
851#endif
852 char szApp[64];
853 RTStrPrintf(szApp, sizeof(szApp), VBOX_PRODUCT " %sr%u", VBOX_VERSION_STRING, RTBldCfgRevision());
854
855 const WebMTimecodeAbs tcAbsDurationMs = CurSeg.tcAbsLastWrittenMs - CurSeg.tcAbsStartMs;
856
857 if (!CurSeg.lstCues.empty())
858 {
859 LogFunc(("tcAbsDurationMs=%RU64\n", tcAbsDurationMs));
860 AssertMsg(tcAbsDurationMs, ("Segment seems to be empty (duration is 0)\n"));
861 }
862
863 subStart(MkvElem_Info)
864 .serializeUnsignedInteger(MkvElem_TimecodeScale, CurSeg.uTimecodeScaleFactor)
865 .serializeFloat(MkvElem_Segment_Duration, tcAbsDurationMs)
866 .serializeString(MkvElem_MuxingApp, szMux)
867 .serializeString(MkvElem_WritingApp, szApp)
868 .subEnd(MkvElem_Info);
869}
870
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